diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9a1941d..2022abe 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -51,6 +51,9 @@ jobs: - name: Run regression test suite run: npm test + - name: Admin StrictMode tests (React 18) + run: npm run test:admin + - name: Type checks run: | npm run test:ts:front @@ -81,6 +84,38 @@ jobs: test -f README.md test -f LICENSE + react-19: + # Informational: the peer range is React ^18, like the Strapi 5 admin, and stays so. This job + # runs the admin StrictMode tests against React 19 (RFC strapi/strapi#25739) to see problems + # before Strapi moves; a failure here does not block a pull request. + name: Admin StrictMode tests on React 19 (informational) + runs-on: ubuntu-latest + timeout-minutes: 20 + continue-on-error: true + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + cache: npm + + - name: Install dependencies + run: npm ci --legacy-peer-deps + + - name: Install React 19 (not saved) + run: npm install --no-save --legacy-peer-deps --ignore-scripts react@19 react-dom@19 + + - name: Show installed React version + run: node -p "'react ' + require('react/package.json').version + ', react-dom ' + require('react-dom/package.json').version" + + - name: Admin StrictMode tests (React 19) + run: npm run test:admin + multi-process: name: Multi-process coordination (SQLite + PostgreSQL) runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index eb554dd..d0e4dcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +## [Unreleased] + +### Fixed + +* The Online users widget, the Analytics page and the Configuration page no longer show "could not be loaded" after the component is mounted a second time. `useFetchClient` aborts the requests of an unmounted component; the widget and the Analytics page then skipped their next load because the aborted one still counted as running, and the Configuration page set the error of the aborted load after the next load had started. React StrictMode mounts every component twice in development, and React 19 and a future StrictMode admin do the same. Each load now belongs to one mount: an aborted or outdated load sets no state. + +### Tests + +* `npm run test:admin`: StrictMode tests for every admin entry point (no duplicate requests, no leaked timers, listeners, connections or observers after unmount, no console errors or warnings), also run against React 19 in an informational CI job. + ## [4.14.1](https://github.com/Schero94/Magic-Sessionmanager/compare/v4.14.0...v4.14.1) (2026-11-18) diff --git a/README.md b/README.md index d32f4d7..ae5045f 100644 --- a/README.md +++ b/README.md @@ -960,6 +960,7 @@ Version 4.0.0 moved to Strapi 5 and its Document Service API. Upgrade Strapi its ```bash npm ci --legacy-peer-deps npm test # node --test tests/*.test.js tests/*.test.mjs +npm run test:admin # admin entry points in React.StrictMode (jsdom, fake network) npm run test:concurrency # 8 processes on one database (SQLite; PostgreSQL with MSM_TEST_PG_URL) npm run test:ts:front npm run test:ts:back @@ -968,6 +969,8 @@ npm run verify npm run verify:runtime ``` +`npm run test:admin` renders every admin entry point (the session dashboard and the admin panel sessions view with their dialogs, the Configuration and Analytics settings pages, the Online users widget and the Content Manager side panel) inside `React.StrictMode` with the providers of the Strapi admin, in jsdom with a fake network. It fails on a mutation sent twice, a read repeated without aborting the first one, an interval, listener, connection or observer left after unmount, and any console error or warning. A separate CI job runs the same tests against React 19 for information only: the plugin's peer range is React 18, like the Strapi 5 admin. + HTTP integration tests need Strapi host dependencies: set `SESSION_HTTP_STRAPI_NODE_MODULES` to the `node_modules` of a Strapi 5 host; without it they skip with a message. This repository's own `node_modules` works (its devDependencies include Strapi 5.62 and Users & Permissions), which is what CI uses: ```bash @@ -990,7 +993,7 @@ Releases use Conventional Commits and semantic-release on Node.js 22 with npm Tr Issues and pull requests are welcome. - Bugs and feature ideas: [open an issue](https://github.com/Schero94/Magic-Sessionmanager/issues/new/choose) (templates included). Questions: [Discussions](https://github.com/Schero94/Magic-Sessionmanager/discussions). -- Pull requests: branch from `main`, write a failing test first, and use Conventional Commits (`fix:`, `feat:`, `docs:`; a breaking change needs a `BREAKING CHANGE:` footer). Before you push, run `npm run lint`, `npm run format:check`, `npm test`, both type checks and `npm run build && npm run verify`. +- Pull requests: branch from `main`, write a failing test first, and use Conventional Commits (`fix:`, `feat:`, `docs:`; a breaking change needs a `BREAKING CHANGE:` footer). Before you push, run `npm run lint`, `npm run format:check`, `npm test`, `npm run test:admin`, both type checks and `npm run build && npm run verify`. - Use synthetic data only in tests, screenshots and issues: `*.example.test` addresses and IP addresses from `203.0.113.0/24`. Never paste real tokens. --- diff --git a/admin/src/components/OnlineUsersWidget.jsx b/admin/src/components/OnlineUsersWidget.jsx index fc5b48b..e895d50 100644 --- a/admin/src/components/OnlineUsersWidget.jsx +++ b/admin/src/components/OnlineUsersWidget.jsx @@ -221,7 +221,8 @@ const OnlineUsersWidget = () => { const [userCounts, setUserCounts] = useState(null); const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(false); - const requestInProgress = useRef(false); + // The running load (an object per call) or null. One load at a time. + const requestInProgress = useRef(null); /** * Loads the count-only session statistics and user totals in parallel @@ -232,19 +233,28 @@ const OnlineUsersWidget = () => { * The loading state starts as true and "Try again" sets it before calling, * so this function only clears it. * + * The effect cleanup forgets the running load (useFetchClient aborts its + * requests on unmount). A load that is no longer current sets no state, and + * the next mount starts its own load instead of waiting for the aborted one: + * React StrictMode mounts, unmounts and mounts again, and before this the + * widget stayed on "Online users could not be loaded." after that remount. + * * @param {{showLoading?: boolean}} [options] Whether this load owns the loading and error state. * @returns {Promise} */ const fetchStats = useCallback( async ({ showLoading = true } = {}) => { if (requestInProgress.current) return; - requestInProgress.current = true; + const request = {}; + requestInProgress.current = request; + const isCurrent = () => requestInProgress.current === request; try { const [sessionResult, countResult] = await Promise.allSettled([ get('/magic-sessionmanager/sessions/stats'), get('/magic-sessionmanager/users/stats'), ]); + if (!isCurrent()) return; if (sessionResult.status === 'rejected') throw sessionResult.reason; setStats(widgetStatsFromCounts(sessionResult.value?.data)); setLoadError(false); @@ -262,12 +272,14 @@ const OnlineUsersWidget = () => { } } catch (error) { // A request aborted because the widget unmounted is not a failure. - if (isCancelledRequest(error)) return; + if (!isCurrent() || isCancelledRequest(error)) return; logSafeAdminError('onlineUsers.loadSessions', error); if (showLoading) setLoadError(true); } finally { - if (showLoading) setLoading(false); - requestInProgress.current = false; + if (isCurrent()) { + if (showLoading) setLoading(false); + requestInProgress.current = null; + } } }, [get] @@ -279,7 +291,10 @@ const OnlineUsersWidget = () => { const interval = setInterval(() => { void fetchStats({ showLoading: false }); }, REFRESH_INTERVAL_MS); - return () => clearInterval(interval); + return () => { + clearInterval(interval); + requestInProgress.current = null; + }; }, [fetchStats]); if (loading) { diff --git a/admin/src/pages/Analytics.jsx b/admin/src/pages/Analytics.jsx index 0c055d5..99ecb9f 100644 --- a/admin/src/pages/Analytics.jsx +++ b/admin/src/pages/Analytics.jsx @@ -25,7 +25,7 @@ import { PageShell, SectionCard, StatGrid, StatCard, EqualGrid } from '../compon import Alert from '../components/PersistentAlert'; import ReadableText from '../components/ReadableText'; import { getTranslation } from '../utils/getTranslation'; -import { logSafeAdminError } from '../utils/safeAdminLog.mjs'; +import { isCancelledRequest, logSafeAdminError } from '../utils/safeAdminLog.mjs'; // ================ BAR LIST ================ // Label, track and count are three grid cells. The count never overlaps the @@ -159,7 +159,8 @@ const AnalyticsPage = () => { const [updatedAt, setUpdatedAt] = useState(null); const [loadError, setLoadError] = useState(false); const [forbidden, setForbidden] = useState(false); - const requestPendingRef = useRef(false); + // The running load (an object per call) or null. One load at a time. + const requestPendingRef = useRef(null); /** * Loads the aggregates over every session (computed on the server, no row @@ -169,24 +170,36 @@ const AnalyticsPage = () => { * above it. Failures are logged without response data. `get` is stable, so * the callback is created once. * + * The effect cleanup forgets the running load (useFetchClient aborts its + * requests on unmount). A load that is no longer current sets no state, and + * the next mount starts its own load: React StrictMode mounts, unmounts and + * mounts again, and before this the page showed "Analytics could not be + * loaded." for the aborted first load and skipped the second. + * * @returns {Promise} */ const fetchAnalytics = useCallback(async () => { if (requestPendingRef.current) return; - requestPendingRef.current = true; + const request = {}; + requestPendingRef.current = request; + const isCurrent = () => requestPendingRef.current === request; try { const { data } = await get(`/${pluginId}/sessions/analytics`); + if (!isCurrent()) return; setAnalytics(analyticsFromServer(data)); setUpdatedAt(Date.now()); setLoadError(false); } catch (err) { + if (!isCurrent() || isCancelledRequest(err)) return; logSafeAdminError('analytics.load', err); if (isForbidden(err)) setForbidden(true); setLoadError(true); } finally { - requestPendingRef.current = false; - setRefreshing(false); - setLoading(false); + if (isCurrent()) { + requestPendingRef.current = null; + setRefreshing(false); + setLoading(false); + } } }, [get]); @@ -204,6 +217,9 @@ const AnalyticsPage = () => { useEffect(() => { // eslint-disable-next-line react-hooks/set-state-in-effect -- state updates run after await; the compiler cannot see through the callback void fetchAnalytics(); + return () => { + requestPendingRef.current = null; + }; }, [fetchAnalytics]); if (loading) { diff --git a/admin/src/pages/Settings/hooks/useSettingsForm.js b/admin/src/pages/Settings/hooks/useSettingsForm.js index 97da184..c9588de 100644 --- a/admin/src/pages/Settings/hooks/useSettingsForm.js +++ b/admin/src/pages/Settings/hooks/useSettingsForm.js @@ -3,7 +3,7 @@ import { useFetchClient, useNotification } from '@strapi/strapi/admin'; import pluginId from '../../../pluginId'; import { areSettingsEqual } from '../../../utils/settingsEquality.mjs'; import { requireSuccessfulMutation } from '../../../utils/adminResponse.mjs'; -import { logSafeAdminError } from '../../../utils/safeAdminLog.mjs'; +import { isCancelledRequest, logSafeAdminError } from '../../../utils/safeAdminLog.mjs'; import { copyText } from '../../../utils/copyText.mjs'; import { formatSessionDate } from '../../../utils/sessionDates.mjs'; import { @@ -87,6 +87,8 @@ export function useSettingsForm() { // Server settings revision the draft is based on. Sent with every save so // the server rejects it (409) when another administrator saved in between. const revisionRef = useRef(null); + // Number of the latest settings load; older loads set no state. + const loadRequestRef = useRef(0); useLayoutEffect(() => { settingsRef.current = settings; savedSettingsRef.current = savedSettings; @@ -151,13 +153,21 @@ export function useSettingsForm() { * failed response shows the retry state instead of an editable default * draft (IA G). * + * Only the latest load sets state, and a request aborted on unmount is not + * a failure. React StrictMode mounts, unmounts and mounts again: before + * this, the aborted first load set the error after the second load had + * started, and the page stayed on "Settings could not be loaded." + * * @returns {Promise} */ const fetchSettings = useCallback(async () => { + const request = loadRequestRef.current + 1; + loadRequestRef.current = request; setLoading(true); setLoadError(false); try { const response = await get(`/${pluginId}/settings`); + if (request !== loadRequestRef.current) return; if ( !response?.data?.settings || typeof response.data.settings !== 'object' || @@ -173,10 +183,11 @@ export function useSettingsForm() { setSavedSettings(nextSettings); await fetchGeoIpStatus(); } catch (err) { + if (request !== loadRequestRef.current || isCancelledRequest(err)) return; logSafeAdminError('settings.load', err); setLoadError(true); } finally { - setLoading(false); + if (request === loadRequestRef.current) setLoading(false); } }, [get, fetchGeoIpStatus]); diff --git a/eslint.config.mjs b/eslint.config.mjs index 97d5d8b..cd0eec9 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -5,6 +5,7 @@ * - Admin panel: ESM, browser globals, JSX, React Hooks recommended rules. * - Server and Strapi entry files: CommonJS, Node globals, `strapi` as a readonly global. * - Tests and scripts: Node globals, module type per file extension. + * - Admin StrictMode harness (tests/admin): JSX, Node and browser (jsdom) globals, React Hooks. * - `eslint-config-prettier` last, so formatting stays with Prettier. * * eslint-plugin-jsx-a11y is not used: its latest release (6.10.2, 2024-10) declares @@ -89,6 +90,18 @@ export default defineConfig([ }, }, + // Admin StrictMode harness and tests: Node test runner with a jsdom window + { + files: ['tests/admin/**/*.{mjs,jsx}'], + extends: [reactHooks.configs.flat.recommended], + languageOptions: { + ecmaVersion: 'latest', + sourceType: 'module', + parserOptions: { ecmaFeatures: { jsx: true } }, + globals: { ...globals.node, ...globals.browser }, + }, + }, + // Playwright snippet: the page.evaluate callbacks run in the browser { files: ['tests/ui-field-fixture/check.js'], diff --git a/package-lock.json b/package-lock.json index 314e6c8..cd7d9b0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -35,6 +35,7 @@ "eslint-config-prettier": "^10.1.8", "eslint-plugin-react-hooks": "^7.1.1", "globals": "^17.14.0", + "jsdom": "^31.0.1", "pg": "^8.23.1", "prettier": "^3.9.10", "react": "^18.3.1", @@ -1970,6 +1971,24 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@floating-ui/core": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", @@ -14325,6 +14344,33 @@ "node": ">=6.0.0" } }, + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/bcryptjs": { "version": "2.4.3", "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", @@ -16053,6 +16099,20 @@ "dev": true, "license": "MIT" }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/date-fns": { "version": "2.30.0", "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz", @@ -16110,6 +16170,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/decode-named-character-reference": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", @@ -19030,6 +19097,19 @@ "node": "20 || >=22" } }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, "node_modules/html-entities": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz", @@ -20062,6 +20142,13 @@ "node": ">=0.10.0" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-regex": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", @@ -20421,6 +20508,90 @@ "node": "^14.17.0 || ^16.13.0 || >=18.0.0" } }, + "node_modules/jsdom": { + "version": "31.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.1.tgz", + "integrity": "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.3", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.3.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@napi-rs/canvas": "^1.0.13" + }, + "peerDependenciesMeta": { + "@napi-rs/canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jsdom/node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/jsdom/node_modules/undici": { + "version": "8.12.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz", + "integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -26072,6 +26243,45 @@ "dev": true, "license": "MIT" }, + "node_modules/parse5-parser-stream": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz", + "integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.1.1" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream/node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/parse5-parser-stream/node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -28636,6 +28846,19 @@ "node": ">=0.10.0" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/scheduler": { "version": "0.23.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz", @@ -30286,6 +30509,26 @@ "dev": true, "license": "MIT" }, + "node_modules/tldts": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.5.4.tgz", + "integrity": "sha512-Rn2ABgjHZrA+jzqom5zhxA0hLohzYrIgfCPyhpTUxqsUrcsBYuab49LseR9waB9Jr8/MxdodvMHA91oRiGLO3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.5.4" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.5.4.tgz", + "integrity": "sha512-9+4zWtKEDZ3V3FoZ1B97rv+5z5oqp7yeXGVze3CxgQ+CJro9do9DCPD00wxstYZDXDMXsurkBerFfiB6GYtPbA==", + "dev": true, + "license": "MIT" + }, "node_modules/tmp": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", @@ -30362,6 +30605,32 @@ "nodetouch": "bin/nodetouch.js" } }, + "node_modules/tough-cookie": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", + "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/traverse": { "version": "0.6.8", "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.6.8.tgz", @@ -31678,6 +31947,19 @@ "dev": true, "license": "MIT" }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, "node_modules/watchpack": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.6.1.tgz", @@ -31708,6 +31990,16 @@ "dev": true, "license": "Apache-2.0" }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, "node_modules/webpack": { "version": "5.109.2", "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.109.2.tgz", @@ -31886,6 +32178,31 @@ "node": ">=10.13.0" } }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -32216,6 +32533,23 @@ "fsevents": "*" } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", diff --git a/package.json b/package.json index 0ae8ca8..499be76 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,7 @@ "scripts": { "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"", "test": "node --test tests/*.test.js tests/*.test.mjs", + "test:admin": "node --import ./tests/admin/harness/setup.mjs --test \"tests/admin/*.test.jsx\"", "test:concurrency": "node scripts/concurrency/run.mjs", "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json", "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json", @@ -89,6 +90,7 @@ "eslint-config-prettier": "^10.1.8", "eslint-plugin-react-hooks": "^7.1.1", "globals": "^17.14.0", + "jsdom": "^31.0.1", "pg": "^8.23.1", "prettier": "^3.9.10", "react": "^18.3.1", diff --git a/tests/admin/harness/fake-socket.mjs b/tests/admin/harness/fake-socket.mjs new file mode 100644 index 0000000..038b312 --- /dev/null +++ b/tests/admin/harness/fake-socket.mjs @@ -0,0 +1,120 @@ +/** + * Counting fake of `socket.io-client` 4.8 (`io(url, options)` returns a Socket with on/off/emit, + * connect/disconnect/close and `io` the Manager). Every socket that is created and not + * disconnected stays in `__strictHarness.resources.sockets`, so a test sees a leaked connection. + * Docs: https://socket.io/docs/v4/client-api/ + */ +const resources = () => globalThis.__strictHarness.resources; + +class FakeSocket { + /** + * @param {string} url - Server URL. + * @param {object} [options] - Client options. + */ + constructor(url, options = {}) { + this.kind = 'socket.io'; + this.url = String(url ?? ''); + this.options = options; + this.connected = false; + this.disconnected = true; + this.id = undefined; + this.handlers = new Map(); + this.emitted = []; + this.io = { + on: () => this.io, + off: () => this.io, + opts: options, + engine: { on() {}, off() {} }, + }; + this.origin = (new Error().stack || '').split('\n').slice(2, 6).join(' <- '); + if (options.autoConnect !== false) this.connect(); + } + connect() { + if (this.connected) return this; + this.connected = true; + this.disconnected = false; + resources().sockets.add(this); + return this; + } + open() { + return this.connect(); + } + disconnect() { + this.connected = false; + this.disconnected = true; + resources().sockets.delete(this); + return this; + } + close() { + return this.disconnect(); + } + on(event, handler) { + if (!this.handlers.has(event)) this.handlers.set(event, new Set()); + this.handlers.get(event).add(handler); + return this; + } + once(event, handler) { + const wrapped = (...args) => { + this.off(event, wrapped); + handler(...args); + }; + return this.on(event, wrapped); + } + off(event, handler) { + if (!event) this.handlers.clear(); + else if (!handler) this.handlers.delete(event); + else this.handlers.get(event)?.delete(handler); + return this; + } + removeAllListeners(event) { + return this.off(event); + } + onAny() { + return this; + } + offAny() { + return this; + } + emit(event, ...args) { + this.emitted.push({ event, args }); + return this; + } + timeout() { + return this; + } + emitWithAck(event, ...args) { + this.emitted.push({ event, args }); + return Promise.resolve(undefined); + } + /** + * Test helper: delivers a server event to the registered handlers. + * @param {string} event - Event name. + * @param {...unknown} args - Payload. + */ + receive(event, ...args) { + for (const handler of [...(this.handlers.get(event) || [])]) handler(...args); + } +} + +/** Every socket created in this test file, open or closed. */ +export const createdSockets = []; + +/** + * `io()` of socket.io-client. + * @param {string | object} [url] - Server URL or options. + * @param {object} [options] - Options. + * @returns {FakeSocket} Socket. + */ +export function io(url, options) { + const socket = typeof url === 'object' ? new FakeSocket('', url) : new FakeSocket(url, options); + createdSockets.push(socket); + return socket; +} +export const connect = io; +export const Socket = FakeSocket; +export class Manager { + socket(namespace, options) { + return io(namespace, options); + } +} +export default io; diff --git a/tests/admin/harness/index.jsx b/tests/admin/harness/index.jsx new file mode 100644 index 0000000..e37b040 --- /dev/null +++ b/tests/admin/harness/index.jsx @@ -0,0 +1,518 @@ +/** + * React StrictMode harness for the plugin's admin entry points (RFC strapi/strapi#27897 StrictMode, + * #25739 React 19). + * + * `renderStrict(ui)` mounts `ui` inside `` and the provider tree Strapi 5.62 + * uses for its own admin tests (`@strapi/admin/dist/admin/admin/tests/utils.mjs`, `Providers`): + * data router (createMemoryRouter), StrapiAppProvider, Redux store with `adminApi`, + * LanguageProvider, Theme (Design System light/dark), NotificationsProvider, AuthProvider, + * react-query QueryClientProvider, react-dnd DndProvider, GuidedTourContext, + * ConfigurationProvider and AppInfoProvider. These providers are not in the package's `exports` + * map, so they are imported by file path; Strapi's own test utils need jest and msw, which this + * repository does not use. Every `@strapi/strapi/admin` component and hook the plugin imports is + * the real one: the package loads unchanged through loader.mjs. + * + * In StrictMode React mounts every component, runs each effect's cleanup, and mounts again + * (react.dev/reference/react/StrictMode). Assertions: + * - `expectNoDuplicateRequests`: no mutation (POST/PUT/PATCH/DELETE) twice, no GET twice unless the + * first copy was aborted by the effect cleanup or the test lists it with a reason. + * - `unmount()` + `expectNoLeaks`: no interval, animation frame, window/document/body listener, + * WebSocket/EventSource/BroadcastChannel/socket.io connection or Resize/Intersection observer + * left behind, and no pending plugin timeout. Resources Strapi's own providers leave behind + * (measured once per file with an empty tree) are not counted. + * - `expectNoConsole`: no console.error/console.warn and no uncaught error, apart from messages the + * providers alone print (measured in the same calibration run). + */ +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { configureStore } from '@reduxjs/toolkit'; +import { darkTheme, lightTheme } from '@strapi/design-system'; +import { DndProvider } from 'react-dnd'; +import { HTML5Backend } from 'react-dnd-html5-backend'; +import { QueryClient, QueryClientProvider, setLogger } from 'react-query'; +import { Provider as ReduxProvider } from 'react-redux'; +import { createMemoryRouter, RouterProvider } from 'react-router-dom'; +import { installNetwork, network } from './network.mjs'; + +export { network }; +export { createdSockets } from './fake-socket.mjs'; + +const harnessDir = path.dirname(fileURLToPath(import.meta.url)); +const repoRoot = path.resolve(harnessDir, '../../..'); +const requireFromRepo = createRequire(path.join(repoRoot, 'package.json')); +const adminDist = path.join( + path.dirname(requireFromRepo.resolve('@strapi/admin/package.json')), + 'dist/admin/admin/src' +); +/** + * Imports a module of the installed @strapi/admin by file path (same URL as the package's own + * relative imports, so the same module instance and React contexts). + * @param {string} file - Path below dist/admin/admin/src. + * @returns {Promise} Module namespace. + */ +const adminModule = (file) => import(pathToFileURL(path.join(adminDist, file)).href); + +const [ + { GuidedTourContext }, + { LanguageProvider }, + { Theme }, + { RBAC }, + { AppInfoProvider }, + { AuthProvider }, + { _internalConfigurationContextProvider: ConfigurationContextProvider }, + { NotificationsProvider }, + { StrapiAppProvider }, + { reducer }, + { adminApi }, +] = await Promise.all( + [ + adminModule('components/GuidedTour/Context.mjs'), + adminModule('components/LanguageProvider.mjs'), + adminModule('components/Theme.mjs'), + adminModule('core/apis/rbac.mjs'), + adminModule('features/AppInfo.mjs'), + adminModule('features/Auth.mjs'), + adminModule('features/Configuration.mjs'), + adminModule('features/Notifications.mjs'), + adminModule('features/StrapiApp.mjs'), + 'reducer.mjs', + 'services/api.mjs', + ].map((entry) => (typeof entry === 'string' ? adminModule(entry) : entry)) +); + +setLogger({ log: () => {}, warn: () => {}, error: () => {} }); +installNetwork(repoRoot); + +const { resources, window } = globalThis.__strictHarness; +const nativeAddListener = window.EventTarget.prototype.addEventListener; + +// Console and uncaught errors. +const consoleMessages = []; +for (const level of ['error', 'warn']) { + const original = console[level].bind(console); + console[level] = (...args) => { + const text = args + .map((arg) => + arg instanceof Error + ? arg.stack || arg.message + : typeof arg === 'string' + ? arg + : safeJson(arg) + ) + .join(' '); + consoleMessages.push({ level, text }); + if (process.env.STRICT_HARNESS_VERBOSE) original(...args); + }; +} +nativeAddListener.call(window, 'error', (event) => { + consoleMessages.push({ level: 'uncaught', text: String(event.error?.stack || event.message) }); +}); +process.on('unhandledRejection', (reason) => { + consoleMessages.push({ level: 'unhandledRejection', text: String(reason?.stack || reason) }); +}); + +/** + * JSON for console arguments, tolerant of cycles. + * @param {unknown} value - Value. + * @returns {string} Text. + */ +function safeJson(value) { + try { + return JSON.stringify(value); + } catch { + return String(value); + } +} + +const ADMIN_USER = { + id: 1, + documentId: 'admin-user-1', + firstname: 'Ada', + lastname: 'Example', + username: null, + email: 'ada@example.test', + isActive: true, + blocked: false, + preferedLanguage: 'en', + roles: [{ id: 1, name: 'Super Admin', code: 'strapi-super-admin' }], +}; + +/** + * Answers the requests Strapi's own providers make (AuthProvider: users/me and permissions). + * @param {object[]} permissions - Permissions of the signed-in admin. + */ +const installCoreRoutes = (permissions) => { + network.on('GET', '/admin/users/me', { data: ADMIN_USER }); + network.on('GET', '/admin/users/me/permissions', { data: permissions }); + network.on('POST', '/admin/permissions/check', (call) => ({ + data: (call.json()?.permissions || []).map(() => true), + })); +}; + +/** + * Builds a permission entry as the admin API returns it. + * @param {string} action - Action uid. + * @param {string | null} [subject] - Subject uid. + * @returns {object} Permission. + */ +export const permission = (action, subject = null) => ({ + id: Math.floor(Math.random() * 1e6), + action, + subject, + properties: {}, + conditions: [], + actionParameters: {}, +}); + +/** + * Lets effects, fetch promises and short timers run inside `act`. + * @param {number} [rounds] - Number of macrotask rounds. + * @param {number} [ms] - Delay per round. + */ +export const settle = async (rounds = 6, ms = 5) => { + for (let index = 0; index < rounds; index += 1) { + await React.act(async () => { + await new Promise((resolve) => setTimeout(resolve, ms)); + }); + } +}; + +/** + * Copies the live resource sets. + * @returns {object} Snapshot of resource identities. + */ +export const snapshotResources = () => ({ + intervals: new Set(resources.intervals.keys()), + timeouts: new Set(resources.timeouts.keys()), + frames: new Set(resources.frames.keys()), + listeners: new Set(resources.listeners.keys()), + sockets: new Set(resources.sockets), + observers: new Set(resources.observers), +}); + +/** + * Resources created after `before` that still exist. + * @param {object} before - Snapshot taken before mounting. + * @returns {Array<{ kind: string, label: string, origin: string }>} Leftovers. + */ +const leftoversSince = (before) => { + const out = []; + for (const [id, entry] of resources.intervals) + if (!before.intervals.has(id)) + out.push({ kind: 'interval', label: `${entry.delay}ms`, origin: entry.origin }); + for (const [id, entry] of resources.timeouts) + if (!before.timeouts.has(id)) + out.push({ kind: 'timeout', label: `${entry.delay}ms`, origin: entry.origin }); + for (const [id, entry] of resources.frames) + if (!before.frames.has(id)) + out.push({ kind: 'animationFrame', label: '', origin: entry.origin }); + for (const [id, entry] of resources.listeners) + if (!before.listeners.has(id)) + out.push({ kind: 'listener', label: `${entry.target}:${entry.type}`, origin: entry.origin }); + for (const socket of resources.sockets) + if (!before.sockets.has(socket)) + out.push({ kind: socket.kind, label: socket.url, origin: socket.origin }); + for (const observer of resources.observers) + if (!before.observers.has(observer)) + out.push({ kind: observer.kind, label: '', origin: observer.origin }); + return out; +}; + +const signature = (entry) => `${entry.kind}|${entry.label}|${entry.origin}`; + +let calibration = null; + +/** + * Mounts the providers alone once per file and records what they leave behind and print, so the + * plugin assertions only count the plugin's own resources and messages. + * @returns {Promise<{ leftovers: Set, messages: Set }>} Baseline. + */ +const calibrate = async () => { + if (calibration) return calibration; + calibration = { leftovers: new Set(), messages: new Set() }; + const startMessages = consoleMessages.length; + const before = snapshotResources(); + const handle = await mount(null, { permissions: [] }); + await handle.unmount(); + for (const entry of leftoversSince(before)) calibration.leftovers.add(signature(entry)); + for (const message of consoleMessages.slice(startMessages)) + calibration.messages.add(message.text); + return calibration; +}; + +/** + * Mounts a tree in StrictMode with Strapi's admin providers. + * @param {React.ReactNode} ui - Tree to render. + * @param {object} options - See renderStrict. + * @returns {Promise} Mounted handle. + */ +async function mount(ui, options) { + const { + path: initialPath = '/', + permissions = [], + strict = true, + plugins = {}, + getPlugin, + locale = 'en', + messages = {}, + } = options; + installCoreRoutes(permissions); + window.strapi = { + backendURL: 'http://localhost:1337', + isEE: false, + features: { isEnabled: () => false, SSO: 'sso', AUDIT: 'audit-logs' }, + featureFlags: { isEnabled: () => false }, + future: { isEnabled: () => false }, + flags: { nps: false, promoteEE: false, docLinks: false }, + projectType: 'Community', + telemetryDisabled: true, + }; + window.localStorage.setItem('jwtToken', JSON.stringify('harness-token')); + + const store = configureStore({ + preloadedState: { + admin_app: { + language: { locale, localeNames: { en: 'English' } }, + permissions: {}, + theme: { availableThemes: [], currentTheme: 'light' }, + token: 'harness-token', + }, + }, + reducer: { [adminApi.reducerPath]: adminApi.reducer, admin_app: reducer }, + middleware: (getDefaultMiddleware) => + getDefaultMiddleware({ immutableCheck: false, serializableCheck: false }).concat( + adminApi.middleware + ), + }); + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const noop = () => {}; + const element = ( + [], register: noop }} + customFields={{ customFields: {}, get: () => undefined, getAll: () => ({}), register: noop }} + fields={{}} + menu={[]} + getAdminInjectedComponents={() => []} + getPlugin={getPlugin || ((id) => plugins[id])} + plugins={plugins} + runHookParallel={noop} + runHookWaterfall={(_name, initialValue) => initialValue} + runHookSeries={noop} + settings={{}} + > + + + + + + + + + + + {ui} + + + + + + + + + + + + ); + const router = createMemoryRouter([{ path: '/*', element }], { initialEntries: [initialPath] }); + const container = document.createElement('div'); + document.body.appendChild(container); + const root = createRoot(container, { + onRecoverableError: (error) => + consoleMessages.push({ level: 'recoverable', text: String(error?.stack || error) }), + }); + const tree = ; + await React.act(async () => { + root.render(strict ? {tree} : tree); + }); + await settle(); + let mounted = true; + return { + container, + router, + store, + queryClient, + /** Unmounts the tree, tears the harness router/store down and lets cleanups run. */ + async unmount() { + if (!mounted) return; + mounted = false; + await React.act(async () => root.unmount()); + router.dispose(); + queryClient.clear(); + store.dispatch(adminApi.util.resetApiState()); + container.remove(); + window.localStorage.clear(); + await settle(4, 10); + }, + }; +} + +/** + * Renders a plugin entry point in StrictMode with Strapi's admin providers and records what it + * does while mounting. + * @param {React.ReactNode} ui - Element to render (page, widget, injected component, side panel). + * @param {object} [options] - Options. + * @param {string} [options.path] - Initial router location. + * @param {object[]} [options.permissions] - Permissions of the admin (see `permission()`). + * @param {Record} [options.plugins] - Plugins for `useStrapiApp().getPlugin`. + * @param {Record} [options.messages] - Translations. + * @returns {Promise} Handle: container, unmount, mountCalls, before (resource snapshot). + */ +export async function renderStrict(ui, options = {}) { + await calibrate(); + network.clearCalls(); + const before = snapshotResources(); + const startMessages = consoleMessages.length; + const handle = await mount(ui, options); + return { + ...handle, + /** Unmounts and forgets the test's network routes. */ + async unmount() { + await handle.unmount(); + network.reset(); + }, + before, + startMessages, + /** Requests made while mounting (StrictMode mount, cleanup, mount). */ + mountCalls: [...network.calls], + }; +} + +/** + * Fails when plugin code sent the same mutation twice, or the same GET twice without aborting the + * first copy and without an explicit allowance. + * @param {Array} calls - Recorded calls (handle.mountCalls or network.calls). + * @param {object} [options] - Options. + * @param {Array<{ path: string | RegExp, reason: string }>} [options.allowDuplicateGets] - GETs the + * plugin may repeat (idempotent reads), each with the reason. + */ +export function expectNoDuplicateRequests(calls, { allowDuplicateGets = [] } = {}) { + const groups = new Map(); + for (const call of calls.filter((entry) => entry.fromPlugin)) { + const key = `${call.method} ${call.path} ${call.method === 'GET' ? '' : (call.body ?? '')}`; + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(call); + } + const problems = []; + for (const [key, group] of groups) { + if (group.length < 2) continue; + const [first] = group; + if (first.method !== 'GET') { + problems.push(`${group.length}x ${key.trim()} (mutation sent more than once)`); + continue; + } + const live = group.filter((call) => !call.aborted); + if (live.length <= 1) continue; + const allowed = allowDuplicateGets.find((entry) => + entry.path instanceof RegExp ? entry.path.test(first.path) : entry.path === first.pathname + ); + if (allowed) { + if (!allowed.reason) problems.push(`allowance for ${first.path} has no reason`); + continue; + } + problems.push(`${live.length}x GET ${first.path} (not aborted by the effect cleanup)`); + } + if (problems.length) + throw new Error(`Duplicate requests in StrictMode:\n ${problems.join('\n ')}`); +} + +/** + * Fails when the unmounted tree left resources behind (see module docs). + * @param {object} handle - Handle from renderStrict (after `await handle.unmount()`). + * @param {object} [options] - Options. + * @param {Array<{ match: RegExp, reason: string }>} [options.allow] - Leftovers that are expected, + * matched against `kind label origin`, each with a reason. + */ +export function expectNoLeaks(handle, { allow = [] } = {}) { + const leftovers = leftoversSince(handle.before).filter((entry) => { + if (calibration.leftovers.has(signature(entry))) return false; + // A pending timeout is a leak only when plugin code set it (library caches expire on their own). + if (entry.kind === 'timeout' && entry.origin.startsWith('lib:')) return false; + // React DOM delegates events on every root and portal container (document.body for + // dialogs and popovers) and never removes those listeners, by design. + if (entry.kind === 'listener' && entry.origin.startsWith('lib:react-dom/')) return false; + const text = `${entry.kind} ${entry.label} ${entry.origin}`; + return !allow.some((rule) => rule.match.test(text)); + }); + if (leftovers.length) { + throw new Error( + `Resources left after unmount:\n ${leftovers + .map((entry) => `${entry.kind} ${entry.label} from ${entry.origin}`) + .join('\n ')}` + ); + } +} + +/** + * Fails on console errors/warnings and uncaught errors since the handle was mounted. + * @param {object} handle - Handle from renderStrict. + * @param {object} [options] - Options. + * @param {Array<{ match: RegExp, reason: string }>} [options.allow] - Third-party messages that are + * expected, each with a reason. + */ +export function expectNoConsole(handle, { allow = [] } = {}) { + const messages = consoleMessages + .slice(handle.startMessages) + .filter((message) => !calibration.messages.has(message.text)) + .filter((message) => !allow.some((rule) => rule.match.test(message.text))); + if (messages.length) { + throw new Error( + `Console output while mounted:\n ${messages + .map( + (message) => `[${message.level}] ${message.text.split('\n').slice(0, 6).join('\n ')}` + ) + .join('\n ')}` + ); + } +} + +/** + * Renders, unmounts and runs all three assertions: the standard StrictMode check of one entry + * point. + * @param {React.ReactNode} ui - Element. + * @param {object} [options] - renderStrict options plus `allowDuplicateGets`, `allowLeaks`, + * `allowConsole` and `whileMounted(handle)` (interactions before unmount). + * @returns {Promise} The unmounted handle (calls, container snapshot). + */ +export async function checkStrictEntry(ui, options = {}) { + const handle = await renderStrict(ui, options); + try { + if (options.whileMounted) await options.whileMounted(handle); + } catch (error) { + // A failed interaction must not leave the tree (and its timers) mounted for the next test. + await handle.unmount(); + throw error; + } + const html = handle.container.innerHTML; + const calls = [...network.calls]; + await handle.unmount(); + expectNoConsole(handle, { allow: options.allowConsole }); + expectNoDuplicateRequests(handle.mountCalls, { allowDuplicateGets: options.allowDuplicateGets }); + expectNoLeaks(handle, { allow: options.allowLeaks }); + return { ...handle, html, calls }; +} diff --git a/tests/admin/harness/loader.mjs b/tests/admin/harness/loader.mjs new file mode 100644 index 0000000..e82de40 --- /dev/null +++ b/tests/admin/harness/loader.mjs @@ -0,0 +1,294 @@ +/** + * Node module customization hooks for the admin StrictMode harness. + * + * Runs in the loader thread (`module.register`, Node >= 20.6). It lets `node --test` import the + * plugin's admin sources the way the Strapi admin bundler (Vite) does: + * + * - JSX/TSX/TS under the repository (outside node_modules) is transpiled with esbuild + * (`jsx: 'automatic'`) and loaded as ES modules, even in a `"type": "commonjs"` package. + * - Extensionless and directory specifiers resolve like a bundler (`./Foo` -> `./Foo.tsx`, + * `./dir` -> `./dir/index.jsx`), also inside node_modules packages that ship bundler-style ESM. + * - JSON imports without import attributes become `export default `; CSS and image imports + * become empty or string modules. + * - `aliases` (passed from setup.mjs) swap modules, for example `socket.io-client` for a counting + * fake. + * - CommonJS dependencies imported from ESM get a wrapper with every runtime export, and a bare + * package import prefers the package's `module` entry, as Vite does for the Strapi admin. + * + * Docs: https://nodejs.org/docs/latest-v22.x/api/module.html#customization-hooks and + * https://esbuild.github.io/api/#transform (esbuild 0.28). + */ +import { readFile, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { createRequire } from 'node:module'; +import { transform } from 'esbuild'; + +const CJS_INTEROP = 'strict-harness-cjs'; + +/** @type {{ root: string, aliases: Record }} */ +let config = { root: process.cwd(), aliases: {} }; + +const SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs']; +const RESOLVE_EXTENSIONS = [...SOURCE_EXTENSIONS, '.json', '.cjs']; +const ASSET_EXTENSIONS = new Set([ + '.css', + '.svg', + '.png', + '.jpg', + '.jpeg', + '.gif', + '.webp', + '.woff', + '.woff2', +]); + +/** + * Receives the harness configuration from `module.register(..., { data })`. + * @param {{ root: string, aliases: Record }} data - Repository root and aliases. + */ +export function initialize(data) { + if (data) config = { ...config, ...data }; +} + +/** + * Whether a file belongs to the repository sources the harness transpiles. + * @param {string} filePath - Absolute path. + * @returns {boolean} True for repository files outside node_modules. + */ +const isRepoSource = (filePath) => + filePath.startsWith(config.root + path.sep) && + !filePath.includes(`${path.sep}node_modules${path.sep}`); + +/** + * Checks that a path is an existing file. + * @param {string} candidate - Absolute path. + * @returns {Promise} True for a file. + */ +const isFile = async (candidate) => { + try { + return (await stat(candidate)).isFile(); + } catch { + return false; + } +}; + +/** + * Bundler-style lookup: the path itself, the path plus an extension, then `index.*`. + * @param {string} base - Absolute path without or with extension. + * @returns {Promise} Resolved file or null. + */ +const bundlerLookup = async (base) => { + if (await isFile(base)) return base; + // A directory with its own package.json (`@reduxjs/toolkit/query/react`): its ESM entry. + try { + const manifest = JSON.parse(await readFile(path.join(base, 'package.json'), 'utf8')); + const entry = manifest.module || manifest.main; + if (entry && (await isFile(path.join(base, entry)))) return path.join(base, entry); + } catch { + // no nested package.json + } + for (const extension of RESOLVE_EXTENSIONS) + if (await isFile(base + extension)) return base + extension; + for (const extension of RESOLVE_EXTENSIONS) { + const index = path.join(base, `index${extension}`); + if (await isFile(index)) return index; + } + return null; +}; + +const esmCache = new Map(); + +/** + * Whether a file is evaluated as an ES module: `.mjs`, a transpiled repository source, or `.js` + * with ESM syntax (Node 22 detects module syntax in ambiguous `.js` files, as in + * `@reduxjs/toolkit/dist/query/rtk-query.esm.js`). + * @param {string} filePath - Absolute path. + * @returns {Promise} True for ESM. + */ +const isEsmFile = async (filePath) => { + if (filePath.endsWith('.mjs') || isRepoSource(filePath)) return true; + if (!filePath.endsWith('.js')) return false; + if (!esmCache.has(filePath)) { + const code = await readFile(filePath, 'utf8').catch(() => ''); + esmCache.set(filePath, /^\s*(import\s[\s\S]*?from\s|import\s*['"{*]|export\s)/m.test(code)); + } + return esmCache.get(filePath); +}; + +/** + * Finds the directory of an installed package the way Node does (nearest node_modules upwards). + * @param {string} packageName - Package name. + * @param {string} fromPath - Importing file. + * @returns {Promise} Package directory. + */ +const findPackageRoot = async (packageName, fromPath) => { + let directory = path.dirname(fromPath); + while (directory !== path.dirname(directory)) { + const packageRoot = path.join(directory, 'node_modules', packageName); + if (await isFile(path.join(packageRoot, 'package.json'))) return packageRoot; + directory = path.dirname(directory); + } + return null; +}; + +/** + * Vite's `mainFields` (module before main): a bare package import without an `exports` map + * resolves to the package's `module` (ESM) entry, as in the Strapi admin build. + * @param {string} specifier - Bare specifier. + * @param {string} parentPath - Importing file. + * @returns {Promise} ESM entry or null. + */ +const packageModuleEntry = async (specifier, parentPath) => { + if (specifier.startsWith('.') || specifier.startsWith('node:') || path.isAbsolute(specifier)) + return null; + const parts = specifier.split('/'); + const isScoped = specifier.startsWith('@'); + if (parts.length !== (isScoped ? 2 : 1)) return null; + const packageRoot = await findPackageRoot(specifier, parentPath); + if (!packageRoot) return null; + const manifest = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8')); + if (manifest.exports || typeof manifest.module !== 'string') return null; + const entry = path.join(packageRoot, manifest.module); + if (!(await isFile(entry))) return null; + // `.js` ESM in a package without `"type": "module"` cannot load natively; leave it to Node. + return entry.endsWith('.mjs') || manifest.type === 'module' ? entry : null; +}; + +/** + * Whether a resolved module is CommonJS: `.cjs`, or `.js` whose nearest package.json is not + * `"type": "module"`. + * @param {{ url: string, format?: string | null }} resolved - Result of the next resolver. + * @returns {Promise} True for CommonJS. + */ +const isCommonJs = async (resolved) => { + if (resolved.format === 'commonjs') return true; + if (resolved.format || !resolved.url.startsWith('file:')) return false; + const filePath = fileURLToPath(resolved.url); + if (filePath.endsWith('.cjs')) return true; + if (!filePath.endsWith('.js')) return false; + let directory = path.dirname(filePath); + while (directory !== path.dirname(directory)) { + try { + const manifest = JSON.parse(await readFile(path.join(directory, 'package.json'), 'utf8')); + return manifest.type !== 'module'; + } catch { + directory = path.dirname(directory); + } + } + return true; +}; + +/** + * Resolve hook: aliases first, then Node's resolver, then bundler-style fallback. + * @param {string} specifier - Import specifier. + * @param {object} context - Resolve context. + * @param {Function} nextResolve - Next hook. + * @returns {Promise} Resolution. + */ +export async function resolve(specifier, context, nextResolve) { + const alias = config.aliases[specifier]; + if (alias && context.parentURL !== pathToFileURL(alias).href) { + return { url: pathToFileURL(alias).href, shortCircuit: true }; + } + const parentPath = context.parentURL?.startsWith('file:') + ? fileURLToPath(context.parentURL) + : null; + if (parentPath && (specifier.startsWith('./') || specifier.startsWith('../'))) { + const found = await bundlerLookup(path.resolve(path.dirname(parentPath), specifier)); + if (found) return { url: pathToFileURL(found).href, shortCircuit: true }; + } + const moduleEntry = parentPath ? await packageModuleEntry(specifier, parentPath) : null; + if (moduleEntry) + return { url: pathToFileURL(moduleEntry).href, format: 'module', shortCircuit: true }; + try { + const resolved = await nextResolve(specifier, context); + // Vite pre-bundles CommonJS dependencies so ESM code can use their named exports + // (`import { assignWith } from 'lodash'` in the Design System). Node's static CJS analysis + // misses many of them, so ESM importers get a generated wrapper with every runtime key. + const parentIsEsm = parentPath && (await isEsmFile(parentPath)); + if (parentIsEsm && (await isCommonJs(resolved))) { + return { ...resolved, url: `${resolved.url}?${CJS_INTEROP}`, format: 'module' }; + } + return resolved; + } catch (error) { + // Bundler-style deep imports inside packages (`lodash/get`, `date-fns/locale`). + if ( + !['ERR_MODULE_NOT_FOUND', 'ERR_UNSUPPORTED_DIR_IMPORT'].includes(error?.code) || + specifier.startsWith('.') || + !parentPath + ) + throw error; + const parts = specifier.split('/'); + const packageName = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]; + const rest = parts.slice(specifier.startsWith('@') ? 2 : 1).join('/'); + let directory = path.dirname(parentPath); + while (directory !== path.dirname(directory)) { + const packageRoot = path.join(directory, 'node_modules', packageName); + if (await isFile(path.join(packageRoot, 'package.json'))) { + const found = await bundlerLookup(path.join(packageRoot, rest)); + if (found) return { url: pathToFileURL(found).href, shortCircuit: true }; + break; + } + directory = path.dirname(directory); + } + throw error; + } +} + +/** + * Load hook: transpile repository sources, turn JSON and assets into ES modules. + * @param {string} url - Module URL. + * @param {object} context - Load context. + * @param {Function} nextLoad - Next hook. + * @returns {Promise} Module source. + */ +export async function load(url, context, nextLoad) { + if (!url.startsWith('file:')) return nextLoad(url, context); + if (url.endsWith(`?${CJS_INTEROP}`)) { + const filePath = fileURLToPath(url.slice(0, -CJS_INTEROP.length - 1)); + let keys = []; + try { + keys = Object.keys(createRequire(filePath)(filePath)).filter((key) => + /^[A-Za-z_$][\w$]*$/.test(key) + ); + } catch { + // A module that needs the DOM to evaluate: only the default export. + } + const named = keys.filter((key) => key !== 'default'); + const source = [ + `import { createRequire } from 'node:module';`, + `const mod = createRequire(${JSON.stringify(filePath)})(${JSON.stringify(filePath)});`, + // Transpiled ESM (`__esModule`, as in styled-components' CJS build): the default import is + // `exports.default`, like Vite's and Rollup's CommonJS interop; otherwise module.exports. + `export default mod && mod.__esModule && 'default' in mod ? mod.default : mod;`, + ...named.map((key) => `export const ${key} = mod[${JSON.stringify(key)}];`), + ].join('\n'); + return { format: 'module', source, shortCircuit: true }; + } + const filePath = fileURLToPath(url); + const extension = path.extname(filePath); + if (ASSET_EXTENSIONS.has(extension)) { + const source = + extension === '.css' ? 'export default {};' : `export default ${JSON.stringify(filePath)};`; + return { format: 'module', source, shortCircuit: true }; + } + if (extension === '.json' && !context.importAttributes?.type) { + const json = await readFile(filePath, 'utf8'); + return { format: 'module', source: `export default ${json};`, shortCircuit: true }; + } + if (isRepoSource(filePath) && SOURCE_EXTENSIONS.includes(extension)) { + const code = await readFile(filePath, 'utf8'); + const loader = extension === '.ts' ? 'ts' : extension === '.tsx' ? 'tsx' : 'jsx'; + const result = await transform(code, { + loader, + format: 'esm', + jsx: 'automatic', + target: 'node22', + sourcefile: filePath, + sourcemap: 'inline', + }); + return { format: 'module', source: result.code, shortCircuit: true }; + } + return nextLoad(url, context); +} diff --git a/tests/admin/harness/network.mjs b/tests/admin/harness/network.mjs new file mode 100644 index 0000000..8aebda0 --- /dev/null +++ b/tests/admin/harness/network.mjs @@ -0,0 +1,161 @@ +/** + * Fake network for the harness: replaces `fetch`, records every request with its initiator and + * whether it was aborted, and answers from route handlers. Strapi's `useFetchClient` + * (`getFetchClient` in @strapi/admin 5.62) and RTK Query both end in `window.fetch`, so this is + * the only network boundary of the admin. + */ + +const BACKEND = 'http://localhost:1337'; + +/** + * @typedef {object} RecordedCall + * @property {string} method - Upper-case HTTP method. + * @property {string} path - Path and query relative to the backend. + * @property {string} pathname - Path without query. + * @property {string | null} body - Request body as text. + * @property {boolean} aborted - The request's signal was aborted. + * @property {boolean} fromPlugin - Initiated by code in this repository (stack attribution). + * @property {boolean} handled - A route handler answered it. + * @property {boolean} [completed] - A response was delivered (a later abort no longer counts). + */ + +/** @type {RecordedCall[]} */ +const calls = []; +/** @type {Array<{ method: string, match: string | RegExp | ((path: string) => boolean), reply: Function }>} */ +let routes = []; +let repoRoot = ''; + +/** + * Whether the current stack contains a frame from the repository (not node_modules, not harness). + * @returns {boolean} True when plugin code initiated the call. + */ +const initiatedByPlugin = () => + (new Error().stack || '') + .split('\n') + .map((line) => decodeURIComponent(line)) + .some( + (line) => + repoRoot && + line.includes(repoRoot) && + !line.includes('node_modules') && + !line.includes('/tests/admin/') + ); + +/** + * Matches a route against method and path. + * @param {{ method: string, match: string | RegExp | Function }} route - Route. + * @param {string} method - Method. + * @param {string} path - Path with query. + * @param {string} pathname - Path without query. + * @returns {boolean} Match. + */ +const matches = (route, method, path, pathname) => { + if (route.method !== '*' && route.method !== method) return false; + if (typeof route.match === 'string') return route.match === pathname || route.match === path; + if (route.match instanceof RegExp) return route.match.test(path); + return Boolean(route.match(path, method)); +}; + +/** + * The fake `fetch`. + * @param {string | URL | Request} input - URL or request. + * @param {RequestInit} [init] - Options. + * @returns {Promise} Response. + */ +async function fakeFetch(input, init = {}) { + const url = new URL(typeof input === 'string' ? input : input.url || String(input), BACKEND); + const method = String( + init.method || (typeof input === 'object' && input.method) || 'GET' + ).toUpperCase(); + let body = init.body ?? null; + if (body && typeof body !== 'string') + body = body instanceof FormData ? '[FormData]' : String(body); + /** @type {RecordedCall} */ + const call = { + method, + path: url.pathname + url.search, + pathname: url.pathname, + body, + aborted: false, + fromPlugin: initiatedByPlugin(), + handled: false, + }; + calls.push(call); + const signal = init.signal || (typeof input === 'object' ? input.signal : undefined); + const abortError = () => new DOMException('The operation was aborted.', 'AbortError'); + if (signal?.aborted) { + call.aborted = true; + throw abortError(); + } + const route = [...routes] + .reverse() + .find((entry) => matches(entry, method, call.path, call.pathname)); + call.handled = Boolean(route); + const result = route + ? await route.reply({ + ...call, + json: () => (typeof body === 'string' ? JSON.parse(body) : body), + }) + : { + status: 404, + body: { data: null, error: { status: 404, name: 'NotFoundError', message: 'Not Found' } }, + }; + const { status = 200, body: payload = null } = + result && typeof result === 'object' && 'status' in result && 'body' in result + ? result + : { body: result }; + // Answer on a later task so abort-on-unmount can win the race, as in a browser. + await new Promise((resolve) => queueMicrotask(resolve)); + if (signal?.aborted) { + call.aborted = true; + throw abortError(); + } + call.completed = true; + return new Response(payload === null ? null : JSON.stringify(payload), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +/** + * Installs the fake fetch on window and the global object. + * @param {string} root - Repository root, for initiator attribution. + */ +export const installNetwork = (root) => { + repoRoot = root; + globalThis.fetch = fakeFetch; + globalThis.window.fetch = fakeFetch; +}; + +export const network = { + /** @returns {RecordedCall[]} Every request since the last reset. */ + get calls() { + return calls; + }, + /** + * Adds a route; later routes win. + * @param {string} method - HTTP method or '*'. + * @param {string | RegExp | Function} match - Path (without or with query), RegExp or predicate. + * @param {Function | object} reply - Body, `{ status, body }`, or a function returning either. + */ + on(method, match, reply) { + routes.push({ + method: method.toUpperCase(), + match, + reply: typeof reply === 'function' ? reply : () => reply, + }); + }, + /** Forgets recorded calls; routes stay. */ + clearCalls() { + calls.length = 0; + }, + /** Removes all routes and recorded calls. */ + reset() { + calls.length = 0; + routes = []; + }, + /** @returns {RecordedCall[]} Requests started by plugin code. */ + pluginCalls() { + return calls.filter((call) => call.fromPlugin); + }, +}; diff --git a/tests/admin/harness/setup.mjs b/tests/admin/harness/setup.mjs new file mode 100644 index 0000000..f2f1bde --- /dev/null +++ b/tests/admin/harness/setup.mjs @@ -0,0 +1,315 @@ +/** + * Preloaded with `node --import ./tests/admin/harness/setup.mjs --test ...`. + * + * 1. Creates a jsdom browser environment on the globals (window, document, navigator, DOM classes) + * before React, styled-components or the Design System are imported. + * 2. Instruments every resource a plugin component can leak and counts it: intervals, pending + * timeouts, animation frames, window/document listeners, WebSocket, EventSource, + * BroadcastChannel, ResizeObserver, IntersectionObserver, MutationObserver and fetch. + * 3. Registers the module hooks in loader.mjs (JSX/TS transpile, bundler-style resolution) with + * the module aliases below. + * + * Docs: jsdom 31 README (https://github.com/jsdom/jsdom#readme), React "act" testing + * (https://react.dev/reference/react/act: `IS_REACT_ACT_ENVIRONMENT`), Node customization hooks. + */ +import { register } from 'node:module'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { JSDOM } from 'jsdom'; + +const harnessDir = path.dirname(fileURLToPath(import.meta.url)); +const root = path.resolve(harnessDir, '../../..'); + +/** Modules the plugin imports that the harness replaces with counting fakes. */ +const ALIASES = { + 'socket.io-client': path.join(harnessDir, 'fake-socket.mjs'), +}; + +register(pathToFileURL(path.join(harnessDir, 'loader.mjs')), import.meta.url, { + data: { root, aliases: ALIASES }, +}); + +const dom = new JSDOM('', { + url: 'http://localhost:1337/admin/', + pretendToBeVisual: true, +}); +const { window } = dom; + +// Node's own globals (timers, fetch, AbortController, Event, URL, ...) stay; DOM classes come +// from jsdom. Timers are unified so `window.setTimeout` and `setTimeout` are the same instrumented +// functions. +for (const key of Object.getOwnPropertyNames(window)) { + if (key in globalThis || key.startsWith('_')) continue; + try { + globalThis[key] = window[key]; + } catch { + // read-only jsdom internals + } +} +globalThis.window = window; +globalThis.document = window.document; +Object.defineProperty(globalThis, 'navigator', { value: window.navigator, configurable: true }); +// React DOM expects the jsdom event classes on `window` and on the global object to match. +// Abort signals must be jsdom's: components pass them to DOM `addEventListener({ signal })`. +for (const key of [ + 'Event', + 'CustomEvent', + 'EventTarget', + 'KeyboardEvent', + 'MouseEvent', + 'FocusEvent', + 'AbortController', + 'AbortSignal', +]) { + globalThis[key] = window[key]; +} +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +/** Live resource counters, read by index.jsx (`snapshotResources`). */ +const resources = { + intervals: new Map(), + timeouts: new Map(), + frames: new Map(), + listeners: new Map(), + sockets: new Set(), + observers: new Set(), +}; +globalThis.__strictHarness = { resources, window }; + +/** + * Records where a resource was created, to name the owner in a failure message. + * @returns {string} Stack lines of the caller in the repository (no node_modules). + */ +const origin = () => { + const frames = (new Error().stack || '') + .split('\n') + .slice(3) + .map((line) => decodeURIComponent(line).replace('file://', '')); + const own = frames + .filter( + (line) => line.includes(root) && !line.includes('node_modules') && !line.includes(harnessDir) + ) + .slice(0, 3) + .map((line) => + line + .trim() + .replace(/\?.*?(?=:\d+:\d+)/, '') + .replace(root, '.') + .replace(/^at /, '') + ); + if (own.length) return own.join(' <- '); + const library = frames.find((line) => line.includes('node_modules')); + if (!library) return 'lib:runtime'; + // Package path without line numbers, so the same call site matches across runs. + return `lib:${library.slice(library.lastIndexOf('node_modules/') + 13).replace(/:\d+:\d+\)?$/, '')}`; +}; + +const nodeSetTimeout = globalThis.setTimeout; +const nodeClearTimeout = globalThis.clearTimeout; +const nodeSetInterval = globalThis.setInterval; +const nodeClearInterval = globalThis.clearInterval; + +/** + * setTimeout that tracks pending timeouts until they run or are cleared. + * @param {Function} callback - Callback. + * @param {number} [delay] - Delay in ms. + * @param {...unknown} args - Arguments. + * @returns {ReturnType} Handle. + */ +function trackedSetTimeout(callback, delay, ...args) { + const handle = nodeSetTimeout( + (...callArgs) => { + resources.timeouts.delete(handle); + if (typeof callback === 'function') callback(...callArgs); + }, + delay, + ...args + ); + resources.timeouts.set(handle, { delay: Number(delay) || 0, origin: origin() }); + return handle; +} +function trackedClearTimeout(handle) { + resources.timeouts.delete(handle); + nodeClearTimeout(handle); +} +function trackedSetInterval(callback, delay, ...args) { + const handle = nodeSetInterval(callback, delay, ...args); + resources.intervals.set(handle, { delay: Number(delay) || 0, origin: origin() }); + return handle; +} +function trackedClearInterval(handle) { + resources.intervals.delete(handle); + nodeClearInterval(handle); +} +for (const target of [globalThis, window]) { + target.setTimeout = trackedSetTimeout; + target.clearTimeout = trackedClearTimeout; + target.setInterval = trackedSetInterval; + target.clearInterval = trackedClearInterval; +} + +let frameId = 0; +window.requestAnimationFrame = globalThis.requestAnimationFrame = (callback) => { + frameId += 1; + const id = frameId; + const handle = nodeSetTimeout(() => { + resources.frames.delete(id); + callback(performance.now()); + }, 16); + resources.frames.set(id, { handle, origin: origin() }); + return id; +}; +window.cancelAnimationFrame = globalThis.cancelAnimationFrame = (id) => { + const frame = resources.frames.get(id); + if (frame) nodeClearTimeout(frame.handle); + resources.frames.delete(id); +}; + +/** + * Counts listeners on long-lived targets (window, document, document.body). Listeners on + * elements inside the rendered tree go away with the tree and are not counted. + * @param {EventTarget} target - Target to instrument. + * @param {string} name - Name used in reports. + */ +const trackListeners = (target, name) => { + const add = target.addEventListener.bind(target); + const remove = target.removeEventListener.bind(target); + const keyOf = (type, listener, options) => { + const capture = typeof options === 'boolean' ? options : Boolean(options && options.capture); + return { type, listener, capture }; + }; + target.addEventListener = (type, listener, options) => { + if (listener) { + const key = keyOf(type, listener, options); + const exists = [...resources.listeners.values()].some( + (entry) => + entry.target === name && + entry.type === key.type && + entry.listener === listener && + entry.capture === key.capture + ); + if (!exists) { + const id = Symbol(type); + resources.listeners.set(id, { target: name, ...key, origin: origin() }); + const signal = options && typeof options === 'object' ? options.signal : undefined; + if (signal) + signal.addEventListener('abort', () => resources.listeners.delete(id), { once: true }); + // A `once` listener is gone after its first event. + if (options && typeof options === 'object' && options.once) { + add(type, () => resources.listeners.delete(id), { once: true, capture: key.capture }); + } + } + } + add(type, listener, options); + }; + target.removeEventListener = (type, listener, options) => { + const key = keyOf(type, listener, options); + for (const [id, entry] of resources.listeners) { + if ( + entry.target === name && + entry.type === key.type && + entry.listener === listener && + entry.capture === key.capture + ) { + resources.listeners.delete(id); + break; + } + } + remove(type, listener, options); + }; +}; +trackListeners(window, 'window'); +trackListeners(window.document, 'document'); +trackListeners(window.document.body, 'body'); + +/** + * Base class for counted connection-like fakes (WebSocket, EventSource, BroadcastChannel). + */ +class CountedConnection extends window.EventTarget { + /** + * @param {string} kind - Constructor name. + * @param {string} [url] - URL or channel name. + */ + constructor(kind, url) { + super(); + this.kind = kind; + this.url = String(url ?? ''); + this.readyState = 0; + this.origin = origin(); + resources.sockets.add(this); + } + close() { + this.readyState = 3; + resources.sockets.delete(this); + } + send() {} + postMessage() {} +} +globalThis.WebSocket = window.WebSocket = class WebSocket extends CountedConnection { + constructor(url) { + super('WebSocket', url); + } +}; +globalThis.EventSource = window.EventSource = class EventSource extends CountedConnection { + constructor(url) { + super('EventSource', url); + } +}; +globalThis.BroadcastChannel = window.BroadcastChannel = class BroadcastChannel extends ( + CountedConnection +) { + constructor(name) { + super('BroadcastChannel', name); + } +}; + +/** + * Counted observer fake for ResizeObserver and IntersectionObserver (jsdom has neither). + * @param {string} kind - Constructor name. + * @returns {Function} Observer class. + */ +const countedObserver = (kind) => + class { + constructor(callback) { + this.kind = kind; + this.callback = callback; + this.targets = new Set(); + this.origin = origin(); + } + observe(target) { + this.targets.add(target); + resources.observers.add(this); + } + unobserve(target) { + this.targets.delete(target); + if (this.targets.size === 0) resources.observers.delete(this); + } + disconnect() { + this.targets.clear(); + resources.observers.delete(this); + } + takeRecords() { + return []; + } + }; +globalThis.ResizeObserver = window.ResizeObserver = countedObserver('ResizeObserver'); +globalThis.IntersectionObserver = window.IntersectionObserver = + countedObserver('IntersectionObserver'); + +window.matchMedia = globalThis.matchMedia = (query) => ({ + matches: false, + media: query, + onchange: null, + addListener() {}, + removeListener() {}, + addEventListener() {}, + removeEventListener() {}, + dispatchEvent: () => false, +}); +window.scrollTo = () => {}; +window.HTMLElement.prototype.scrollIntoView = function scrollIntoView() {}; +if (!window.HTMLElement.prototype.hasPointerCapture) { + window.HTMLElement.prototype.hasPointerCapture = () => false; + window.HTMLElement.prototype.releasePointerCapture = () => {}; + window.HTMLElement.prototype.setPointerCapture = () => {}; +} diff --git a/tests/admin/strict-mode.test.jsx b/tests/admin/strict-mode.test.jsx new file mode 100644 index 0000000..7386176 --- /dev/null +++ b/tests/admin/strict-mode.test.jsx @@ -0,0 +1,382 @@ +/** + * StrictMode checks of every Session Manager admin entry point: the plugin page (session dashboard + * and admin panel sessions), the two settings pages (Configuration, Analytics), the homepage widget, + * the Content Manager side panel for users, the initializer, and the dialogs they open. See + * harness/index.jsx for what each assertion counts. + */ +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import path from 'node:path'; +import { test } from 'node:test'; +import { pathToFileURL } from 'node:url'; +import { act } from 'react'; +import { Route, Routes } from 'react-router-dom'; +import { Form } from '@strapi/strapi/admin'; +import { checkStrictEntry, network, permission } from './harness/index.jsx'; +import App from '../../admin/src/pages/App'; +import Settings from '../../admin/src/pages/Settings'; +import Analytics from '../../admin/src/pages/Analytics'; +import OnlineUsersWidget from '../../admin/src/components/OnlineUsersWidget'; +import SessionInfoPanel from '../../admin/src/components/SessionInfoPanel'; +import Initializer from '../../admin/src/components/Initializer'; +import plugin from '../../admin/src/index'; + +// Strapi's own renderer of Content Manager side panel descriptions (not in the package exports). +const adminDist = path.join( + path.dirname(createRequire(import.meta.url).resolve('@strapi/admin/package.json')), + 'dist/admin/admin/src' +); +const { DescriptionComponentRenderer } = await import( + pathToFileURL(path.join(adminDist, 'components/DescriptionComponentRenderer.mjs')).href +); + +const PLUGIN = 'plugin::magic-sessionmanager'; +const ACCESS = permission(`${PLUGIN}.access`); +const ADMIN_READ = permission(`${PLUGIN}.admin-sessions.read`); +const ADMIN_REVOKE = permission(`${PLUGIN}.admin-sessions.revoke`); +const ALL = [ACCESS, ADMIN_READ, ADMIN_REVOKE]; +const USER_MODEL = 'plugin::users-permissions.user'; + +const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60_000).toISOString(); + +const STATS = { + total: 2, + open: 1, + active: 1, + idle: 0, + ended: 1, + loggedOut: 1, + timedOut: 0, + otherReasons: 0, + usersOnline: 1, + nativeOnly: 0, + nativeOnlyAfterTracking: 0, +}; + +const session = (overrides = {}) => ({ + id: 11, + documentId: 'session-11', + isActive: true, + isTrulyActive: true, + loginTime: minutesAgo(30), + lastActive: minutesAgo(1), + ipAddress: '203.0.113.10', + userAgent: + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36', + user: { id: 7, documentId: 'user-7', username: 'grace', email: 'grace@example.test' }, + ...overrides, +}); + +const SESSIONS = [ + session(), + session({ + id: 12, + documentId: 'session-12', + isActive: false, + isTrulyActive: false, + terminationReason: 'logout', + logoutTime: minutesAgo(5), + }), +]; + +/** Routes of the session dashboard (list, counts, untracked summary). */ +const dashboardRoutes = () => { + network.on('GET', '/magic-sessionmanager/sessions', { + data: SESSIONS, + meta: { pagination: { page: 1, pageSize: 25, pageCount: 1, total: SESSIONS.length } }, + }); + network.on('GET', '/magic-sessionmanager/sessions/stats', { data: STATS }); + network.on('GET', '/magic-sessionmanager/users/stats', { + success: true, + data: { totalUsers: 5, blockedUsers: 1 }, + }); + network.on('GET', /^\/magic-sessionmanager\/geolocation\//, { + data: { country: 'Example', city: 'Example City' }, + }); +}; + +/** + * Clicks an element inside `act` (Radix triggers also need pointerdown). + * @param {Element | null | undefined} element - Element. + */ +const click = async (element) => { + assert.ok(element, 'element to click exists'); + await act(async () => { + element.dispatchEvent(new window.PointerEvent('pointerdown', { bubbles: true, button: 0 })); + element.click(); + }); + await act(async () => new Promise((resolve) => setTimeout(resolve, 20))); +}; + +/** + * Finds a button by accessible label or exact text anywhere in the document (dialogs render in + * portals). + * @param {string | RegExp} label - Label or text. + * @returns {HTMLElement | undefined} Button. + */ +const button = (label) => + [...document.querySelectorAll('button, [role="tab"]')].find((node) => { + const name = node.getAttribute('aria-label') || node.textContent.trim(); + return label instanceof RegExp ? label.test(name) : name === label; + }); + +/** The plugin page as Strapi mounts it: at `plugins/magic-sessionmanager/*`. */ +const PluginPage = () => ( + + } /> + +); + +/** + * Plugin intervals that run right now (the harness counts every setInterval with its origin). + * @param {string} file - Source file below admin/src. + * @returns {number} Count. + */ +const runningIntervals = (file) => + [...globalThis.__strictHarness.resources.intervals.values()].filter((entry) => + entry.origin.includes(`admin/src/${file}`) + ).length; + +const live = (calls, pathname, method = 'GET') => + calls.filter((call) => call.method === method && call.pathname === pathname && !call.aborted); + +test('plugin registration: menu link, settings links, widget and side panel are registered', () => { + const app = { + menu: [], + settings: [], + addMenuLink: (link) => app.menu.push(link), + addSettingsLink: (_section, links) => app.settings.push(...links), + registerPlugin: () => {}, + widgets: { register: (widget) => app.widgetList.push(widget) }, + widgetList: [], + }; + plugin.register(app); + assert.equal(app.menu.length, 1); + assert.deepEqual( + app.settings.map((link) => link.id), + ['general', 'analytics'] + ); + assert.equal(app.widgetList.length, 1); + const panels = []; + plugin.bootstrap({ + getPlugin: () => ({ apis: { addEditViewSidePanel: (list) => panels.push(...list) } }), + }); + assert.deepEqual(panels, [SessionInfoPanel]); +}); + +test('initializer: StrictMode mount reports the plugin and leaves nothing behind', async () => { + const ready = []; + await checkStrictEntry( ready.push(id)} />); + assert.ok(ready.length >= 1); + assert.ok(ready.every((id) => id === 'magic-sessionmanager')); +}); + +test('session dashboard: StrictMode mount, one live list request, clock and auto refresh stop on unmount', async () => { + dashboardRoutes(); + const result = await checkStrictEntry(, { + path: '/plugins/magic-sessionmanager', + permissions: ALL, + whileMounted() { + // The relative-time clock and the 10-minute auto refresh; StrictMode's first mount cleared its own. + assert.equal(runningIntervals('pages/HomePage.jsx'), 2); + }, + }); + assert.match(result.html, /grace/); + assert.equal(live(result.mountCalls, '/magic-sessionmanager/sessions').length, 1); + assert.equal(live(result.mountCalls, '/magic-sessionmanager/sessions/stats').length, 1); + assert.equal(runningIntervals('pages/HomePage.jsx'), 0); +}); + +test('session dashboard: details dialog and end-session confirmation open and close cleanly', async () => { + dashboardRoutes(); + const result = await checkStrictEntry(, { + path: '/plugins/magic-sessionmanager', + permissions: ALL, + async whileMounted() { + await click(button('View details for grace')); + assert.ok(document.querySelector('[role="dialog"]'), 'details dialog is open'); + await click(button('Close')); + assert.equal(document.querySelector('[role="dialog"]'), null, 'details dialog closed'); + await click(button('End session of grace')); + assert.match(document.body.textContent, /End this session\?/); + await click(button('Cancel')); + }, + }); + assert.equal(result.calls.filter((call) => call.method !== 'GET').length, 0, 'no mutation'); +}); + +test('session dashboard: the search field debounces without leaking its timer', async () => { + dashboardRoutes(); + await checkStrictEntry(, { + path: '/plugins/magic-sessionmanager', + permissions: ALL, + async whileMounted(handle) { + const input = handle.container.querySelector('input[type="search"], input[name="search"]'); + assert.ok(input, 'search input exists'); + await act(async () => { + const setter = Object.getOwnPropertyDescriptor( + window.HTMLInputElement.prototype, + 'value' + ).set; + setter.call(input, 'grace'); + input.dispatchEvent(new window.Event('input', { bubbles: true })); + }); + }, + }); +}); + +test('admin panel sessions: StrictMode mount, one live list request, clean unmount', async () => { + network.on('GET', '/magic-sessionmanager/admin-sessions/admins', { + data: [ + { + id: 1, + name: 'Ada Example', + email: 'ada@example.test', + roles: [{ name: 'Super Admin' }], + account: 'active', + sessionCount: 1, + lastActiveAt: minutesAgo(2), + self: true, + canSignOut: false, + }, + ], + meta: { + pagination: { page: 1, pageSize: 25, pageCount: 1, total: 1 }, + stats: { signedInAdmins: 1, activeSessions: 1, activeAccounts: 1, totalAdmins: 1 }, + supported: true, + }, + }); + network.on('GET', '/magic-sessionmanager/admin-sessions/admins/1/sessions', { + data: [session({ id: 31, user: undefined })], + meta: {}, + }); + const result = await checkStrictEntry(, { + path: '/plugins/magic-sessionmanager/admin-panel', + permissions: ALL, + async whileMounted() { + await click(button('View sessions of Ada Example')); + assert.ok(document.querySelector('[role="dialog"]'), 'sessions dialog is open'); + }, + }); + assert.match(result.html, /Ada Example/); + assert.equal(live(result.mountCalls, '/magic-sessionmanager/admin-sessions/admins').length, 1); + assert.equal( + live(result.calls, '/magic-sessionmanager/admin-sessions/admins/1/sessions').length, + 1 + ); + assert.equal(result.calls.filter((call) => call.method !== 'GET').length, 0, 'no mutation'); +}); + +test('settings page: StrictMode mount shows the loaded form, tabs switch cleanly', async () => { + network.on('GET', '/magic-sessionmanager/settings', { settings: {}, revision: 1 }); + network.on('GET', '/magic-sessionmanager/geoip/status', { + status: { exists: false, hasCredentials: false }, + }); + const result = await checkStrictEntry(, { + path: '/settings/magic-sessionmanager/general', + permissions: ALL, + async whileMounted(handle) { + assert.doesNotMatch(handle.container.textContent, /could not be loaded/i); + for (const tab of [...document.querySelectorAll('[role="tab"]')].slice(1)) await click(tab); + }, + }); + assert.equal(live(result.mountCalls, '/magic-sessionmanager/settings').length, 1); + assert.equal(result.calls.filter((call) => call.method !== 'GET').length, 0, 'no mutation'); +}); + +test('analytics page: StrictMode mount shows the aggregates, not the error state', async () => { + network.on('GET', '/magic-sessionmanager/sessions/analytics', { + data: { + totalSessions: 2, + activeSessions: 1, + idleSessions: 0, + endedSessions: 1, + signInsLast24Hours: 2, + signInsLast7Days: 2, + uniqueUsers: 1, + avgSessionDuration: 1800, + devices: [{ name: 'desktop', count: 2 }], + browsers: [{ name: 'Chrome', count: 2 }], + }, + }); + const result = await checkStrictEntry(, { + path: '/settings/magic-sessionmanager/analytics', + permissions: ALL, + }); + assert.doesNotMatch(result.html, /could not be loaded/i); + assert.equal(live(result.mountCalls, '/magic-sessionmanager/sessions/analytics').length, 1); +}); + +test('homepage widget: StrictMode mount shows the counts, polls once and stops on unmount', async () => { + dashboardRoutes(); + const result = await checkStrictEntry(, { + permissions: [ACCESS], + whileMounted: () => assert.equal(runningIntervals('components/OnlineUsersWidget.jsx'), 1), + }); + // Before the fix the remount waited for the aborted first load and showed the error state. + assert.doesNotMatch(result.html, /could not be loaded/i); + assert.equal(live(result.mountCalls, '/magic-sessionmanager/sessions/stats').length, 1); + assert.equal(live(result.mountCalls, '/magic-sessionmanager/users/stats').length, 1); + assert.equal(runningIntervals('components/OnlineUsersWidget.jsx'), 0); +}); + +/** Lets throttled updates (Strapi's side panel renderer: 60 ms) and async work run. */ +const wait = (ms) => act(async () => new Promise((resolve) => setTimeout(resolve, ms))); + +/** + * Content Manager edit view side panels: Strapi's DescriptionComponentRenderer renders the panel + * description as a component and pushes its `{ title, content }` out, inside the edit view Form. + * @param {object} props - Side panel props. + * @returns {import('react').ReactElement} Panels. + */ +const SidePanelHost = (props) => ( + + {(panels) => + panels.map(({ id, title, content }) => ( +
+

{title}

+ {content} +
+ )) + } +
+); + +test('Content Manager side panel: StrictMode mount, one live request, confirmation dialog', async () => { + network.on('GET', '/magic-sessionmanager/user/user-7/sessions', { data: SESSIONS }); + const document_ = { documentId: 'user-7', username: 'grace', blocked: false }; + const result = await checkStrictEntry( +
+ + , + { + path: `/content-manager/collection-types/${USER_MODEL}/user-7`, + permissions: ALL, + async whileMounted() { + await wait(150); + await click(button('Block user')); + assert.ok(document.querySelector('[role="alertdialog"], [role="dialog"]')); + await click(button('Cancel')); + }, + } + ); + assert.match(result.html, /1 open session/); + assert.equal(live(result.mountCalls, '/magic-sessionmanager/user/user-7/sessions').length, 1); + assert.equal(result.calls.filter((call) => call.method !== 'GET').length, 0, 'no mutation'); +}); + +test('Content Manager side panel: renders nothing for other content types', async () => { + const result = await checkStrictEntry( +
+ + , + { permissions: ALL, whileMounted: () => wait(150) } + ); + assert.equal(result.mountCalls.filter((call) => call.fromPlugin).length, 0); +});