diff --git a/.changeset/ssr-single-react.md b/.changeset/ssr-single-react.md new file mode 100644 index 00000000..2218aa22 --- /dev/null +++ b/.changeset/ssr-single-react.md @@ -0,0 +1,9 @@ +--- +'@tanstack/cms-ui-react': patch +--- + +Fix the production server returning 500 on every server-rendered page with "Invalid hook call" (`Cannot read properties of null (reading 'useRef')`) in apps installed with pnpm. + +`@tanstack/react-store`, which the admin's auth hooks and `@tanstack/react-form` use, imports the CommonJS `use-sync-external-store` shim. A production SSR build resolves bare imports from the app root. Under pnpm the app can't resolve react-store, so Vite inlined it with the shim, and the shim's `require('react')` loaded a second React at runtime beside the one Nitro bundles. In SSR, `tanstackCms()` now serves the shim's entry points as ESM on React's built-in `useSyncExternalStore`, so they share the app's React. + +Apps that worked around this with `ssr: { external: ['@tanstack/react-store'] }` and a direct `@tanstack/react-store` dependency can drop both. An app needs the `tanstackCms()` plugin to get the fix. diff --git a/docs/architecture/routes-in-a-package.md b/docs/architecture/routes-in-a-package.md index 9606c1c8..752e7846 100644 --- a/docs/architecture/routes-in-a-package.md +++ b/docs/architecture/routes-in-a-package.md @@ -46,7 +46,7 @@ export default defineConfig({ }) ``` -- **`tanstackCms()`** (from `@tanstack/cms-ui-react/vite`) keeps the CMS packages (`@tanstack/cms-core`, `@tanstack/cms-api`, `@tanstack/cms-ui-react`, `@tanstack/cms-client`) and `@tanstack/ai*` out of Vite's SSR externals and dependency pre-bundling. The packages ship TanStack Start server functions and route files that your app's Start compiler must transform, so the plugin is required when you consume the published packages. Pass `tanstackCms({ packages: [...] })` to treat additional packages the same way. +- **`tanstackCms()`** (from `@tanstack/cms-ui-react/vite`) keeps the CMS packages (`@tanstack/cms-core`, `@tanstack/cms-api`, `@tanstack/cms-ui-react`, `@tanstack/cms-client`) and `@tanstack/ai*` out of Vite's SSR externals and dependency pre-bundling. The packages ship TanStack Start server functions and route files that your app's Start compiler must transform, so the plugin is required when you consume the published packages. Pass `tanstackCms({ packages: [...] })` to treat additional packages the same way. In SSR it also serves `use-sync-external-store` (which `@tanstack/react-store` and `@tanstack/react-form` import) as ESM on React's own `useSyncExternalStore`. Otherwise, under pnpm, the production server bundle loads a second copy of React, and every server-rendered page fails with "Invalid hook call". - **`cmsVirtualRoutes()`** (from `@tanstack/cms-ui-react/virtual-routes`) returns a virtual route tree built with `@tanstack/virtual-file-routes`. The router generator turns it into your app's `src/routeTree.gen.ts`, with imports pointing into the package. Your app's `src/router.tsx` imports `./cms.config` before `./routeTree.gen`, so `defineCms()` has registered the content model before any route loader or server function reads it: diff --git a/examples/astro-starlight-after/package.json b/examples/astro-starlight-after/package.json index 2441f396..9be52ebb 100644 --- a/examples/astro-starlight-after/package.json +++ b/examples/astro-starlight-after/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3013", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit", diff --git a/examples/astro-starlight-after/vite.config.ts b/examples/astro-starlight-after/vite.config.ts index c4c9acdb..3b46b285 100644 --- a/examples/astro-starlight-after/vite.config.ts +++ b/examples/astro-starlight-after/vite.config.ts @@ -4,9 +4,11 @@ import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { tanstackCms } from '@tanstack/cms-ui-react/vite' export default defineConfig({ plugins: [ + tanstackCms(), tailwindcss(), tanstackStart({ router: { @@ -26,14 +28,5 @@ export default defineConfig({ build: { target: 'es2022', }, - ssr: { - noExternal: [ - '@tanstack/cms-core', - '@tanstack/ai', - '@tanstack/ai-anthropic', - '@tanstack/ai-gemini', - '@tanstack/ai-mcp', - ], - }, nitro: {}, }) diff --git a/examples/blog-voting/package.json b/examples/blog-voting/package.json index 3997736e..b611b97d 100644 --- a/examples/blog-voting/package.json +++ b/examples/blog-voting/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3004", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit", diff --git a/examples/blog-voting/vite.config.ts b/examples/blog-voting/vite.config.ts index 48e68122..16942ef6 100644 --- a/examples/blog-voting/vite.config.ts +++ b/examples/blog-voting/vite.config.ts @@ -5,9 +5,11 @@ import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { route } from '@tanstack/virtual-file-routes' import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { tanstackCms } from '@tanstack/cms-ui-react/vite' export default defineConfig({ plugins: [ + tanstackCms(), tailwindcss(), tanstackStart({ router: { @@ -31,14 +33,5 @@ export default defineConfig({ build: { target: 'es2022', }, - ssr: { - noExternal: [ - '@tanstack/cms-core', - '@tanstack/ai', - '@tanstack/ai-anthropic', - '@tanstack/ai-gemini', - '@tanstack/ai-mcp', - ], - }, nitro: {}, }) diff --git a/examples/blog/package.json b/examples/blog/package.json index 82122a5b..5d473745 100644 --- a/examples/blog/package.json +++ b/examples/blog/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3003", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit", diff --git a/examples/db-federated/package.json b/examples/db-federated/package.json index 93925b4e..06236481 100644 --- a/examples/db-federated/package.json +++ b/examples/db-federated/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3022", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit" diff --git a/examples/db-sqlite/package.json b/examples/db-sqlite/package.json index 5a277cca..77726b3c 100644 --- a/examples/db-sqlite/package.json +++ b/examples/db-sqlite/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3021", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit" diff --git a/examples/emdash-after/package.json b/examples/emdash-after/package.json index e338ef21..ab8aa05f 100644 --- a/examples/emdash-after/package.json +++ b/examples/emdash-after/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3015", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit", diff --git a/examples/emdash-after/vite.config.ts b/examples/emdash-after/vite.config.ts index 8c1527ce..8b54c8fa 100644 --- a/examples/emdash-after/vite.config.ts +++ b/examples/emdash-after/vite.config.ts @@ -4,9 +4,11 @@ import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { tanstackCms } from '@tanstack/cms-ui-react/vite' export default defineConfig({ plugins: [ + tanstackCms(), tailwindcss(), tanstackStart({ router: { @@ -26,14 +28,5 @@ export default defineConfig({ build: { target: 'es2022', }, - ssr: { - noExternal: [ - '@tanstack/cms-core', - '@tanstack/ai', - '@tanstack/ai-anthropic', - '@tanstack/ai-gemini', - '@tanstack/ai-mcp', - ], - }, nitro: {}, }) diff --git a/examples/payload-after/package.json b/examples/payload-after/package.json index a5641aa7..1c7ab966 100644 --- a/examples/payload-after/package.json +++ b/examples/payload-after/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3011", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit", diff --git a/examples/payload-after/vite.config.ts b/examples/payload-after/vite.config.ts index 0a72a579..03887be3 100644 --- a/examples/payload-after/vite.config.ts +++ b/examples/payload-after/vite.config.ts @@ -4,9 +4,11 @@ import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { tanstackCms } from '@tanstack/cms-ui-react/vite' export default defineConfig({ plugins: [ + tanstackCms(), tailwindcss(), tanstackStart({ router: { @@ -27,14 +29,5 @@ export default defineConfig({ build: { target: 'es2022', }, - ssr: { - noExternal: [ - '@tanstack/cms-core', - '@tanstack/ai', - '@tanstack/ai-anthropic', - '@tanstack/ai-gemini', - '@tanstack/ai-mcp', - ], - }, nitro: {}, }) diff --git a/examples/picks/package.json b/examples/picks/package.json index 67d98146..aab69c8f 100644 --- a/examples/picks/package.json +++ b/examples/picks/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3023", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit", diff --git a/examples/wordpress-after/package.json b/examples/wordpress-after/package.json index 8c4d9f40..e64f5ad4 100644 --- a/examples/wordpress-after/package.json +++ b/examples/wordpress-after/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite dev --port 3016", "build": "vite build", + "test:build": "node ../../scripts/smoke-ssr.mjs", "serve": "vite preview", "start": "node .output/server/index.mjs", "test:types": "tsc --noEmit", diff --git a/examples/wordpress-after/vite.config.ts b/examples/wordpress-after/vite.config.ts index fead3aaf..f4994941 100644 --- a/examples/wordpress-after/vite.config.ts +++ b/examples/wordpress-after/vite.config.ts @@ -4,9 +4,11 @@ import { nitro } from 'nitro/vite' import viteReact from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { cmsVirtualRoutes } from '@tanstack/cms-ui-react/virtual-routes' +import { tanstackCms } from '@tanstack/cms-ui-react/vite' export default defineConfig({ plugins: [ + tanstackCms(), tailwindcss(), tanstackStart({ router: { @@ -26,14 +28,5 @@ export default defineConfig({ build: { target: 'es2022', }, - ssr: { - noExternal: [ - '@tanstack/cms-core', - '@tanstack/ai', - '@tanstack/ai-anthropic', - '@tanstack/ai-gemini', - '@tanstack/ai-mcp', - ], - }, nitro: {}, }) diff --git a/knip.json b/knip.json index 51963b7c..246c3738 100644 --- a/knip.json +++ b/knip.json @@ -12,6 +12,9 @@ ], "ignoreExportsUsedInFile": true, "workspaces": { + ".": { + "entry": ["scripts/smoke-ssr.mjs"] + }, "onboarding/packages/react": { "entry": ["src/**/*.{ts,tsx}"] }, diff --git a/nx.json b/nx.json index ce176910..4f248e15 100644 --- a/nx.json +++ b/nx.json @@ -52,13 +52,21 @@ "test:build": { "cache": true, "dependsOn": ["build"], - "inputs": ["production"] + "inputs": [ + "production", + "^production", + "{workspaceRoot}/scripts/smoke-ssr.mjs" + ] }, "build": { "cache": true, "dependsOn": ["^build"], "inputs": ["production", "^production"], - "outputs": ["{projectRoot}/build", "{projectRoot}/dist"] + "outputs": [ + "{projectRoot}/build", + "{projectRoot}/dist", + "{projectRoot}/.output" + ] }, "test:docs": { "cache": true, diff --git a/packages/ui-react/src/vite.ts b/packages/ui-react/src/vite.ts index 51011027..14149ae3 100644 --- a/packages/ui-react/src/vite.ts +++ b/packages/ui-react/src/vite.ts @@ -21,6 +21,78 @@ const CMS_PACKAGES = [ /** Bundled into SSR alongside the CMS (ESM-only, resolved via the CMS packages). */ const SSR_BUNDLED: Array = [/^@tanstack\/ai(-[a-z]+)?$/] +/* + * `@tanstack/react-store` (used here, by `@tanstack/react-form` and by + * `@tanstack/search-ui-react`) imports the CommonJS `use-sync-external-store` + * shim. A production SSR build resolves bare imports from the app root, so + * under pnpm, where the app doesn't depend on react-store, Vite inlines it + * with the shim while React stays external. The shim's `require('react')` then + * survives as a runtime `createRequire` call that Nitro can't bundle, and it + * loads a second React next to the one Nitro bundles: every server-rendered + * page fails with "Invalid hook call". In SSR the shim's entry points resolve + * to these ESM equivalents, which `import` React like any other module. + */ +const SHIM = /^use-sync-external-store(\/shim)?(\/index)?(\.js)?$/ +const WITH_SELECTOR = /^use-sync-external-store(\/shim)?\/with-selector(\.js)?$/ +const SHIM_ID = '\0tanstack-cms:use-sync-external-store' +const WITH_SELECTOR_ID = '\0tanstack-cms:use-sync-external-store/with-selector' + +const SHIM_SOURCE = `import { useSyncExternalStore } from 'react' +export { useSyncExternalStore } +export default { useSyncExternalStore } +` + +// React's use-sync-external-store/with-selector (MIT, Meta Platforms, Inc.) +// as ESM, on React's built-in useSyncExternalStore. +const WITH_SELECTOR_SOURCE = `import { useDebugValue, useEffect, useMemo, useRef, useSyncExternalStore } from 'react' +export function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { + const instRef = useRef(null) + let inst + if (instRef.current === null) { + inst = { hasValue: false, value: null } + instRef.current = inst + } else inst = instRef.current + const [getSelection, getServerSelection] = useMemo(() => { + let hasMemo = false + let memoizedSnapshot + let memoizedSelection + const memoizedSelector = (nextSnapshot) => { + if (!hasMemo) { + hasMemo = true + memoizedSnapshot = nextSnapshot + const nextSelection = selector(nextSnapshot) + if (isEqual !== undefined && inst.hasValue) { + const currentSelection = inst.value + if (isEqual(currentSelection, nextSelection)) return (memoizedSelection = currentSelection) + } + return (memoizedSelection = nextSelection) + } + const currentSelection = memoizedSelection + if (Object.is(memoizedSnapshot, nextSnapshot)) return currentSelection + const nextSelection = selector(nextSnapshot) + if (isEqual !== undefined && isEqual(currentSelection, nextSelection)) { + memoizedSnapshot = nextSnapshot + return currentSelection + } + memoizedSnapshot = nextSnapshot + return (memoizedSelection = nextSelection) + } + return [ + () => memoizedSelector(getSnapshot()), + getServerSnapshot === undefined ? undefined : () => memoizedSelector(getServerSnapshot()), + ] + }, [getSnapshot, getServerSnapshot, selector, isEqual]) + const value = useSyncExternalStore(subscribe, getSelection, getServerSelection) + useEffect(() => { + inst.hasValue = true + inst.value = value + }, [value]) + useDebugValue(value) + return value +} +export default { useSyncExternalStoreWithSelector } +` + /** Structural subset of Vite's `Plugin`, so this file needs no `vite` import. */ export interface CmsVitePlugin { name: string @@ -29,6 +101,12 @@ export interface CmsVitePlugin { ssr: { noExternal: Array } optimizeDeps: { exclude: Array } } + resolveId: ( + id: string, + importer: string | undefined, + options?: { ssr?: boolean }, + ) => string | undefined + load: (id: string) => string | undefined } export function tanstackCms( @@ -42,5 +120,16 @@ export function tanstackCms( ssr: { noExternal: [...packages, ...SSR_BUNDLED] }, optimizeDeps: { exclude: packages }, }), + resolveId: (id, _importer, resolveOptions) => { + if (!resolveOptions?.ssr) return undefined + if (WITH_SELECTOR.test(id)) return WITH_SELECTOR_ID + if (SHIM.test(id)) return SHIM_ID + return undefined + }, + load: (id) => { + if (id === SHIM_ID) return SHIM_SOURCE + if (id === WITH_SELECTOR_ID) return WITH_SELECTOR_SOURCE + return undefined + }, } } diff --git a/packages/ui-react/tests/vite-plugin.test.tsx b/packages/ui-react/tests/vite-plugin.test.tsx new file mode 100644 index 00000000..a17eda2a --- /dev/null +++ b/packages/ui-react/tests/vite-plugin.test.tsx @@ -0,0 +1,132 @@ +// @vitest-environment happy-dom +import { mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { act, cleanup, render } from '@testing-library/react' +import { renderToString } from 'react-dom/server' +import { afterAll, afterEach, describe, expect, it } from 'vitest' +import { tanstackCms } from '../src/vite' + +const plugin = tanstackCms() +const ssr = (id: string) => plugin.resolveId(id, undefined, { ssr: true }) + +const SHIM_SPECIFIERS = [ + 'use-sync-external-store', + 'use-sync-external-store/shim', + 'use-sync-external-store/shim/index.js', +] +const WITH_SELECTOR_SPECIFIERS = [ + 'use-sync-external-store/with-selector', + 'use-sync-external-store/with-selector.js', + 'use-sync-external-store/shim/with-selector', + 'use-sync-external-store/shim/with-selector.js', +] + +describe('tanstackCms() in SSR', () => { + it('serves the use-sync-external-store entry points as ESM', () => { + const shimIds = new Set(SHIM_SPECIFIERS.map(ssr)) + const selectorIds = new Set(WITH_SELECTOR_SPECIFIERS.map(ssr)) + expect(shimIds.size).toBe(1) + expect(selectorIds.size).toBe(1) + const [shimId] = [...shimIds] + const [selectorId] = [...selectorIds] + expect(shimId).not.toBe(selectorId) + expect(plugin.load(shimId!)).toContain("from 'react'") + expect(plugin.load(selectorId!)).toContain( + 'export function useSyncExternalStoreWithSelector', + ) + }) + + it('leaves client builds, other specifiers and other modules alone', () => { + for (const id of [...SHIM_SPECIFIERS, ...WITH_SELECTOR_SPECIFIERS]) { + expect(plugin.resolveId(id, undefined, { ssr: false })).toBeUndefined() + expect(plugin.resolveId(id, undefined)).toBeUndefined() + } + expect(ssr('use-sync-external-store/shim/index.native')).toBeUndefined() + expect(ssr('react')).toBeUndefined() + expect(plugin.load('/src/main.tsx')).toBeUndefined() + }) +}) + +describe('the served useSyncExternalStoreWithSelector', () => { + // Inside the package, so the module's `import … from 'react'` resolves. + const dir = join(import.meta.dirname, '../.generated/vite-plugin-test') + afterEach(cleanup) + afterAll(() => rmSync(dir, { recursive: true, force: true })) + + async function load() { + mkdirSync(dir, { recursive: true }) + const file = join(dir, 'with-selector.mjs') + writeFileSync( + file, + plugin.load(ssr('use-sync-external-store/shim/with-selector')!)!, + ) + return (await import(/* @vite-ignore */ file)) as { + useSyncExternalStoreWithSelector: ( + subscribe: (onChange: () => void) => () => void, + getSnapshot: () => T, + getServerSnapshot: (() => T) | undefined, + selector: (snapshot: T) => S, + isEqual?: (a: S, b: S) => boolean, + ) => S + } + } + + function createStore(count: number) { + let state = { count, label: 'a' } + const listeners = new Set<() => void>() + return { + get: () => state, + set: (next: typeof state) => { + state = next + for (const listener of listeners) listener() + }, + subscribe: (listener: () => void) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + } + } + + it('renders the selection on the server and follows store updates', async () => { + const { useSyncExternalStoreWithSelector } = await load() + const store = createStore(1) + function Count() { + const count = useSyncExternalStoreWithSelector( + store.subscribe, + store.get, + store.get, + (s) => s.count, + ) + return {`count ${count}`} + } + expect(renderToString()).toBe('count 1') + const view = render() + expect(view.container.textContent).toBe('count 1') + act(() => store.set({ count: 2, label: 'a' })) + expect(view.container.textContent).toBe('count 2') + }) + + it('skips the re-render while isEqual says the selection is unchanged', async () => { + const { useSyncExternalStoreWithSelector } = await load() + const store = createStore(1) + let renders = 0 + function Count() { + const selection = useSyncExternalStoreWithSelector( + store.subscribe, + store.get, + undefined, + (s) => ({ count: s.count }), + (a, b) => a.count === b.count, + ) + renders++ + return {`count ${selection.count}`} + } + const view = render() + expect(renders).toBe(1) + act(() => store.set({ count: 1, label: 'b' })) + expect(renders).toBe(1) + act(() => store.set({ count: 3, label: 'b' })) + expect(renders).toBe(2) + expect(view.container.textContent).toBe('count 3') + }) +}) diff --git a/scripts/smoke-ssr.mjs b/scripts/smoke-ssr.mjs new file mode 100644 index 00000000..b708f591 --- /dev/null +++ b/scripts/smoke-ssr.mjs @@ -0,0 +1,107 @@ +// Boots a built TanStack Start app (`.output/server/index.mjs`) and checks +// that server-rendered pages don't fail. Catches a production SSR bundle that +// loads a second copy of React ("Invalid hook call", then a 500 on every page), +// which dev and E2E (both on the Vite dev server) don't exercise. +// +// node scripts/smoke-ssr.mjs [appDir] [--path /a --path /b] +// +// Run it after `vite build`. `appDir` defaults to the current directory, the +// paths to the public root and the admin at either mount point. Every path must +// answer below 500, and at least one below 400. Content is written to a +// throwaway CMS_DATA_DIR. +import { spawn } from 'node:child_process' +import { existsSync, mkdtempSync, rmSync } from 'node:fs' +import { createServer } from 'node:net' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +const args = process.argv.slice(2) +const paths = [] +let appDir = '.' +for (let i = 0; i < args.length; i++) { + if (args[i] === '--path') paths.push(args[++i]) + else appDir = args[i] +} +if (paths.length === 0) paths.push('/', '/admin', '/content', '/admin/content') + +const root = resolve(appDir) +const entry = join(root, '.output/server/index.mjs') +if (!existsSync(entry)) { + console.error(`smoke-ssr: ${entry} not found; run \`vite build\` first.`) + process.exit(1) +} + +const port = await new Promise((done, fail) => { + const probe = createServer() + probe.once('error', fail) + probe.listen(0, '127.0.0.1', () => { + const { port } = probe.address() + probe.close(() => done(port)) + }) +}) +const dataDir = mkdtempSync(join(tmpdir(), 'smoke-ssr-')) +let log = '' +const server = spawn(process.execPath, [entry], { + cwd: root, + env: { + ...process.env, + PORT: String(port), + HOST: '127.0.0.1', + CMS_DATA_DIR: dataDir, + }, + stdio: ['ignore', 'pipe', 'pipe'], +}) +server.stdout.on('data', (chunk) => (log += chunk)) +server.stderr.on('data', (chunk) => (log += chunk)) +const exited = new Promise((done) => server.once('exit', done)) + +const origin = `http://127.0.0.1:${port}` +const failures = [] +let rendered = 0 +try { + const deadline = Date.now() + 30_000 + for (;;) { + if (server.exitCode !== null) { + throw new Error(`the server exited with code ${server.exitCode}`) + } + try { + await fetch(origin, { signal: AbortSignal.timeout(2000) }) + break + } catch { + if (Date.now() > deadline) throw new Error('the server never answered') + await new Promise((done) => setTimeout(done, 200)) + } + } + for (const path of paths) { + const response = await fetch(origin + path, { + redirect: 'manual', + signal: AbortSignal.timeout(15_000), + }) + await response.arrayBuffer() + const ok = response.status < 500 + console.log(`${ok ? 'ok ' : 'FAIL'} ${response.status} ${path}`) + if (!ok) failures.push(`${path} returned ${response.status}`) + if (response.status < 400) rendered++ + } + if (rendered === 0) failures.push('no path answered below 400') + if (/Invalid hook call/.test(log)) { + failures.push('the server logged "Invalid hook call" (two copies of React)') + } +} catch (error) { + failures.push(error instanceof Error ? error.message : String(error)) +} finally { + server.kill('SIGTERM') + await Promise.race([exited, new Promise((done) => setTimeout(done, 5000))]) + if (server.exitCode === null) server.kill('SIGKILL') + rmSync(dataDir, { recursive: true, force: true }) +} + +if (failures.length) { + console.error(`\nsmoke-ssr failed for ${root}:`) + for (const failure of failures) console.error(` - ${failure}`) + console.error( + `\nServer output:\n${log.trim().split('\n').slice(-40).join('\n')}`, + ) + process.exit(1) +} +console.log(`smoke-ssr: ${paths.length} path(s) served without a 5xx.`)