@jasonshimmy/vite-plugin-cer-app 0.21.0 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +2 -0
  3. package/commits.txt +1 -1
  4. package/dist/cli/commands/dev.d.ts.map +1 -1
  5. package/dist/cli/commands/dev.js +32 -16
  6. package/dist/cli/commands/dev.js.map +1 -1
  7. package/dist/plugin/build-ssg.d.ts.map +1 -1
  8. package/dist/plugin/build-ssg.js +28 -4
  9. package/dist/plugin/build-ssg.js.map +1 -1
  10. package/dist/plugin/dev-server.d.ts.map +1 -1
  11. package/dist/plugin/dev-server.js +32 -13
  12. package/dist/plugin/dev-server.js.map +1 -1
  13. package/dist/plugin/virtual/routes.d.ts.map +1 -1
  14. package/dist/plugin/virtual/routes.js +5 -1
  15. package/dist/plugin/virtual/routes.js.map +1 -1
  16. package/dist/runtime/app-template.d.ts +1 -1
  17. package/dist/runtime/app-template.d.ts.map +1 -1
  18. package/dist/runtime/app-template.js +16 -0
  19. package/dist/runtime/app-template.js.map +1 -1
  20. package/dist/runtime/entry-server-template.d.ts +1 -1
  21. package/dist/runtime/entry-server-template.d.ts.map +1 -1
  22. package/dist/runtime/entry-server-template.js +21 -5
  23. package/dist/runtime/entry-server-template.js.map +1 -1
  24. package/docs/configuration.md +1 -1
  25. package/docs/content.md +6 -0
  26. package/docs/rendering-modes.md +2 -0
  27. package/docs/routing.md +29 -4
  28. package/package.json +3 -3
  29. package/src/__tests__/plugin/app-template.test.ts +9 -0
  30. package/src/__tests__/plugin/build-ssg.test.ts +112 -1
  31. package/src/__tests__/plugin/dev-server.test.ts +74 -5
  32. package/src/__tests__/plugin/entry-server-template.test.ts +13 -4
  33. package/src/__tests__/plugin/virtual/routes.test.ts +5 -1
  34. package/src/cli/commands/dev.ts +27 -16
  35. package/src/plugin/build-ssg.ts +37 -5
  36. package/src/plugin/dev-server.ts +41 -15
  37. package/src/plugin/virtual/routes.ts +5 -1
  38. package/src/runtime/app-template.ts +16 -0
  39. package/src/runtime/entry-server-template.ts +21 -5
@@ -20,6 +20,7 @@ import {
20
20
  component,
21
21
  ref,
22
22
  provide,
23
+ setDevMode,
23
24
  useOnConnected,
24
25
  useOnDisconnected,
25
26
  registerBuiltinComponents,
@@ -28,7 +29,22 @@ import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
28
29
  import { enableJITCSS } from '@jasonshimmy/custom-elements-runtime/jit-css'
29
30
  import { initRuntimeConfig } from '@jasonshimmy/vite-plugin-cer-app/composables'
30
31
 
32
+ const _cerProcess = (globalThis).process
33
+ const _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE
34
+ const _cerRuntimeDev =
35
+ typeof _cerNodeEnv === 'string'
36
+ ? _cerNodeEnv !== 'production'
37
+ : typeof import.meta.env?.DEV === 'boolean'
38
+ ? import.meta.env.DEV
39
+ : typeof import.meta.env?.PROD === 'boolean'
40
+ ? !import.meta.env.PROD
41
+ : typeof import.meta.env?.MODE === 'string'
42
+ ? import.meta.env.MODE !== 'production'
43
+ : false
44
+ ;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev
45
+
31
46
  registerBuiltinComponents()
47
+ setDevMode(_cerRuntimeDev)
32
48
  enableJITCSS()
33
49
  initRuntimeConfig(runtimeConfig)
34
50
 
@@ -1 +1 @@
1
- {"version":3,"file":"app-template.js","sourceRoot":"","sources":["../../src/runtime/app-template.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuVjC,CAAA"}
1
+ {"version":3,"file":"app-template.js","sourceRoot":"","sources":["../../src/runtime/app-template.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuWjC,CAAA"}
@@ -11,5 +11,5 @@
11
11
  * - useHead() support via beginHeadCollection / endHeadCollection
12
12
  * - DSD polyfill injected at end of <body> after client-template merge
13
13
  */
14
- export declare const ENTRY_SERVER_TEMPLATE = "// Server-side entry \u2014 AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app\nimport { readFileSync, existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport routes from 'virtual:cer-routes'\nimport layouts from 'virtual:cer-layouts'\nimport plugins from 'virtual:cer-plugins'\nimport apiRoutes from 'virtual:cer-server-api'\nimport serverMiddleware from 'virtual:cer-server-middleware'\nimport { runtimeConfig, _runtimePrivateDefaults, _authSessionKey, _hooks } from 'virtual:cer-app-config'\nimport { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'\nimport { registerEntityMap, renderToStreamWithJITCSSDSD, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'\nimport entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'\nimport { initRouter } from '@jasonshimmy/custom-elements-runtime/router'\nimport { beginHeadCollection, endHeadCollection, serializeHeadTags, initRuntimeConfig, resolvePrivateConfig, useSession } from '@jasonshimmy/vite-plugin-cer-app/composables'\nimport { errorTag } from 'virtual:cer-error'\nimport { createIsrHandler } from '@jasonshimmy/vite-plugin-cer-app/isr'\n\nregisterBuiltinComponents()\n\n// Resolve private config from environment variables at server startup.\n// Each key declared in runtimeConfig.private is looked up in process.env,\n// first as-is, then as ALL_CAPS. The declared default is used as fallback.\ninitRuntimeConfig({ ...runtimeConfig, private: resolvePrivateConfig(_runtimePrivateDefaults ?? {}) })\n\n// Pre-load the full HTML entity map so named entities like &mdash; decode\n// correctly during SSR. Without this the bundled runtime falls back to a\n// minimal set (&lt;, &gt;, &amp; \u2026) and re-escapes everything else.\nregisterEntityMap(entitiesJson)\n\n// Run plugins once at server startup so their provide() values are available\n// to useInject() during every SSR/SSG render pass. Stored on globalThis so all\n// dynamically-imported page chunks share the same reference.\nconst _pluginProvides = new Map()\n;(globalThis).__cerPluginProvides = _pluginProvides\nconst _pluginsReady = (async () => {\n const _bootstrapRouter = initRouter({ routes })\n for (const plugin of plugins) {\n if (plugin && typeof plugin.setup === 'function') {\n await plugin.setup({\n router: _bootstrapRouter,\n provide: (key, value) => _pluginProvides.set(key, value),\n config: {},\n })\n }\n }\n})()\n\n// Async-local storage for request-scoped SSR loader data.\n// Using AsyncLocalStorage ensures concurrent SSR renders (e.g. SSG with\n// concurrency > 1) never see each other's data \u2014 each request's async chain\n// carries its own store value, so usePageData() is always race-condition-free.\nconst _cerDataStore = new AsyncLocalStorage()\n// Expose the store so the usePageData() composable can read it server-side.\n;(globalThis).__CER_DATA_STORE__ = _cerDataStore\n\n// Async-local storage for request-scoped req/res access.\n// Allows isomorphic composables (e.g. useCookie) to read/write HTTP headers\n// without prop-drilling the request context through the component tree.\nconst _cerReqStore = new AsyncLocalStorage()\n;(globalThis).__CER_REQ_STORE__ = _cerReqStore\n\n// Async-local storage for the authenticated user resolved before each render.\n// useAuth() reads this store server-side to return the current user synchronously.\nconst _cerAuthStore = new AsyncLocalStorage()\n;(globalThis).__CER_AUTH_STORE__ = _cerAuthStore\n\n// Async-local storage for per-request useFetch() data.\n// useFetch() writes fetched results here; the handler serialises the map into\n// window.__CER_FETCH_DATA__ for client-side hydration.\nconst _cerFetchStore = new AsyncLocalStorage()\n;(globalThis).__CER_FETCH_STORE__ = _cerFetchStore\n\n// Async-local storage for the current route info (path, params, query, meta).\n// useRoute() reads this on the server so layouts and components can access\n// route metadata without prop-drilling.\nconst _cerRouteStore = new AsyncLocalStorage()\n;(globalThis).__CER_ROUTE_STORE__ = _cerRouteStore\n\n// Async-local storage for per-request useState() reactive state.\n// Each request gets a fresh Map so concurrent SSR/SSG renders never share\n// reactive state set by different pages or loaders.\nconst _cerStateStore = new AsyncLocalStorage()\n;(globalThis).__CER_STATE_STORE__ = _cerStateStore\n\n// Runs fn inside the per-request AsyncLocalStorage context so that isomorphic\n// composables (useCookie, useSession, etc.) can access req/res without prop-drilling.\n// Call this for every API handler invocation \u2014 not just SSR renders.\nexport function runWithRequestContext(req, res, fn) {\n return _cerReqStore.run({ req, res }, fn)\n}\n\n// Runs the server/middleware/ chain for a request.\n// Returns false if a middleware short-circuited the response; true to continue.\n// Exported so Netlify / Vercel / Cloudflare bridges can also call it for API routes.\n// P1-2: Middleware may throw { status: 401 } (or any numeric .status) to produce\n// a non-500 response \u2014 the status is extracted and forwarded to res.statusCode.\nexport async function runServerMiddleware(req, res) {\n for (const { handler: mw } of (serverMiddleware ?? [])) {\n if (typeof mw !== 'function') continue\n let calledNext = false\n try {\n await new Promise((resolve, reject) => {\n Promise.resolve(mw(req, res, (err) => {\n if (err) reject(err)\n else { calledNext = true; resolve() }\n })).catch(reject)\n })\n } catch (err) {\n if (_hooks?.onError) {\n try { await _hooks.onError(err, { type: 'middleware', path: new URL(req.url ?? '/', 'http://x').pathname, req }) } catch { /* hooks must not crash the handler */ }\n }\n if (!res.writableEnded) {\n const statusCode = (typeof err === 'object' && err !== null && 'status' in err && typeof err.status === 'number')\n ? (isNaN(err.status) ? 500 : err.status)\n : 500\n res.statusCode = statusCode\n res.end('Internal Server Error')\n }\n return false\n }\n if (res.writableEnded || !calledNext) return false\n }\n return true\n}\n\n// Load the Vite-built client index.html (dist/client/index.html) so every SSR\n// response includes the client-side scripts needed for hydration and routing.\n// The server bundle lives at dist/server/server.js, so ../client resolves correctly.\n//\n// Cloudflare Workers (and other runtimes without node:fs) can inject the\n// template before this module loads by setting globalThis.__CER_CLIENT_TEMPLATE__.\n// The Cloudflare adapter inlines dist/client/index.html as a string constant in\n// _worker.js and sets the global before dynamically importing the server bundle.\nlet _clientTemplate = (globalThis).__CER_CLIENT_TEMPLATE__ ?? null\nif (!_clientTemplate) {\n try {\n const _clientTemplatePath = join(dirname(fileURLToPath(import.meta.url)), '../client/index.html')\n _clientTemplate = existsSync(_clientTemplatePath)\n ? readFileSync(_clientTemplatePath, 'utf-8')\n : null\n } catch {\n // node:fs not available in this runtime \u2014 Cloudflare adapter must set\n // globalThis.__CER_CLIENT_TEMPLATE__ before importing this bundle.\n }\n}\n\n// Merge the SSR rendered body with the Vite client shell so the final page\n// contains both pre-rendered DSD content and the client bundle scripts.\nfunction _mergeWithClientTemplate(ssrHtml, clientTemplate) {\n const headTag = '<head>', headCloseTag = '</head>'\n const bodyTag = '<body>', bodyCloseTag = '</body>'\n const headStart = ssrHtml.indexOf(headTag)\n const headEnd = ssrHtml.indexOf(headCloseTag)\n const bodyStart = ssrHtml.indexOf(bodyTag)\n const bodyEnd = ssrHtml.lastIndexOf(bodyCloseTag)\n const ssrHead = headStart >= 0 && headEnd > headStart\n ? ssrHtml.slice(headStart + headTag.length, headEnd).trim() : ''\n const ssrBody = bodyStart >= 0 && bodyEnd > bodyStart\n ? ssrHtml.slice(bodyStart + bodyTag.length, bodyEnd).trim() : ssrHtml\n // Hoist only top-level <style id=...> elements (cer-ssr-jit, cer-ssr-global)\n // from the SSR body into the document <head>. Plain <style> blocks without\n // an id attribute belong to shadow DOM templates and must stay in place \u2014\n // hoisting them to <head> breaks shadow DOM style encapsulation (document\n // styles do not pierce shadow roots), which is the root cause of FOUC.\n const headParts = ssrHead ? [ssrHead] : []\n let ssrBodyContent = ssrBody\n let pos = 0\n while (pos < ssrBodyContent.length) {\n const styleOpen = ssrBodyContent.indexOf('<style id=', pos)\n if (styleOpen < 0) break\n const styleClose = ssrBodyContent.indexOf('</style>', styleOpen)\n if (styleClose < 0) break\n headParts.push(ssrBodyContent.slice(styleOpen, styleClose + 8))\n ssrBodyContent = ssrBodyContent.slice(0, styleOpen) + ssrBodyContent.slice(styleClose + 8)\n pos = styleOpen\n }\n ssrBodyContent = ssrBodyContent.trim()\n // Inject the pre-rendered layout+page as light DOM of the app mount element\n // so it is visible before JS boots, then the client router takes over.\n let merged = clientTemplate\n if (merged.includes('<cer-layout-view></cer-layout-view>')) {\n merged = merged.replace('<cer-layout-view></cer-layout-view>',\n '<cer-layout-view>' + ssrBodyContent + '</cer-layout-view>')\n } else if (merged.includes('<div id=\"app\"></div>')) {\n merged = merged.replace('<div id=\"app\"></div>',\n '<div id=\"app\">' + ssrBodyContent + '</div>')\n }\n const headAdditions = headParts.filter(Boolean).join('\\n')\n if (headAdditions) {\n // If SSR provides a <title>, replace the client template's <title> so the\n // SSR title wins (client template title is the fallback default).\n if (headAdditions.includes('<title>')) {\n merged = merged.replace(/<title>[^<]*<\\/title>/, '')\n }\n merged = merged.replace('</head>', headAdditions + '\\n</head>')\n }\n return merged\n}\n\n// Per-request async setup: initialize a fresh router, resolve the matched\n// route and layout, pre-load the page module, and call the data loader.\n// Loader data is returned so the handler can scope it to _cerDataStore.run()\n// during rendering. (AsyncLocalStorage.enterWith() inside an awaited child\n// function does not propagate back to the parent continuation, so run() is\n// the only reliable approach.)\nconst _prepareRequest = async (req) => {\n await _pluginsReady\n const router = initRouter({ routes, initialUrl: req.url ?? '/' })\n const current = router.getCurrent()\n const { route, params } = router.matchRoute(current.path)\n\n // Store the current route info so useRoute() can read it synchronously\n // from any layout or component during this render pass.\n _cerRouteStore.enterWith({\n path: current.path,\n params,\n query: current.query ?? {},\n meta: route?.meta ?? null,\n })\n\n // Pre-load the page module so we can embed the component tag directly.\n // This avoids the async router-view (which injects content via script tags\n // and breaks Declarative Shadow DOM on initial parse).\n let pageVnode = { tag: 'div', props: {}, children: [] }\n let head\n // Loader data to pass to usePageData() during rendering. Declared here\n // (outside try/catch) so it's visible in all return paths.\n let loaderData = null\n if (route?.load) {\n try {\n const mod = await route.load()\n const pageTag = mod.default\n // P2-2: Route-level error tag (from co-located .error.ts or _error.ts).\n // Preferred over the global errorTag when rendering loader errors for this route.\n const routeErrorTag = mod.errorTag ?? null\n\n // P1-1: Synthetic 404 catch-all \u2014 no page component registered.\n if (!pageTag) {\n const notFoundErrorTag = routeErrorTag ?? errorTag\n const notFoundVnode = notFoundErrorTag\n ? { tag: notFoundErrorTag, props: { attrs: { error: 'Not Found', status: '404' } }, children: [] }\n : { tag: 'div', props: {}, children: [] }\n return { vnode: notFoundVnode, router, head: undefined, status: 404 }\n }\n\n // Run the loader before creating the page vnode so we can pass its\n // primitive return values as HTML attributes. useProps() in the page\n // component reads element attributes, so merging loader data here makes\n // both useProps() and usePageData() work in SSR / SSG.\n let loaderAttrs = {}\n if (typeof mod.loader === 'function') {\n const query = current.query ?? {}\n const data = await mod.loader({ params, query, req })\n if (data !== undefined && data !== null) {\n // Store loader data so the handler can pass it to _cerDataStore.run()\n // below. Using enterWith() here doesn't work because it only modifies\n // the async context *inside* this awaited function, not the outer\n // handler's continuation where renderToStreamWithJITCSSDSD runs.\n loaderData = data\n head = `<script>window.__CER_DATA__ = ${JSON.stringify(data)}</script>`\n // Expose primitive loader values as element attributes so useProps()\n // can read them. Complex objects are only accessible via usePageData().\n loaderAttrs = Object.fromEntries(\n Object.entries(data).filter(([, v]) => v !== null && v !== undefined && typeof v !== 'object' && typeof v !== 'function')\n )\n }\n }\n\n pageVnode = { tag: pageTag, props: { attrs: { ...params, ...loaderAttrs } }, children: [] }\n } catch (err) {\n // Loader threw \u2014 render the error page server-side if app/error.ts exists.\n const status = (err && typeof err === 'object' && 'status' in err && typeof err.status === 'number')\n ? err.status : 500\n const message = (err instanceof Error) ? err.message : String(err)\n if (_hooks?.onError) {\n try { await _hooks.onError(err, { type: 'loader', path: new URL(req.url ?? '/', 'http://x').pathname, req }) } catch { /* hooks must not crash the handler */ }\n }\n // P2-2: Prefer the route-level errorTag over the global one.\n // routeErrorTag is not in scope here; use route?.meta?.errorTag from the matched route.\n const effectiveErrorTag = route?.meta?.errorTag ?? errorTag\n if (!effectiveErrorTag) {\n console.error('[cer-app] Loader error (no app/error.ts defined):', err)\n }\n const errVnode = effectiveErrorTag\n ? { tag: effectiveErrorTag, props: { attrs: { error: message, status: String(status) } }, children: [] }\n : { tag: 'div', props: {}, children: [] }\n return { vnode: errVnode, router, head: undefined, status }\n }\n }\n\n // Resolve layout chain: nested layouts (meta.layoutChain) or single layout.\n const chain = route?.meta?.layoutChain\n ? route.meta.layoutChain\n : [route?.meta?.layout ?? 'default']\n\n // Wrap pageVnode in the layout chain from innermost to outermost.\n let vnode = pageVnode\n for (let i = chain.length - 1; i >= 0; i--) {\n const tag = layouts[chain[i]]\n if (tag) vnode = { tag, props: {}, children: [vnode] }\n }\n\n // If the request matched a catch-all route (user-defined 404.ts or [...all].ts),\n // return HTTP 404 so browsers and crawlers treat it as a not-found response.\n const isCatchAll = route?.path === '/:all*'\n return { vnode, router, head, status: isCatchAll ? 404 : null, loaderData }\n}\n\nexport const handler = async (req, res) => {\n const _requestPath = new URL(req.url ?? '/', 'http://x').pathname\n const _requestStart = Date.now()\n if (_hooks?.onRequest) {\n try { await _hooks.onRequest({ path: _requestPath, method: req.method ?? 'GET', req }) } catch { /* hooks must not crash the handler */ }\n }\n await _cerStateStore.run(new Map(), async () => {\n await _cerReqStore.run({ req, res }, async () => {\n await _cerDataStore.run(null, async () => {\n // Fresh per-request fetch map \u2014 populated by useFetch() calls inside loaders.\n const _fetchMap = new Map()\n await _cerFetchStore.run(_fetchMap, async () => {\n // Pre-resolve the authenticated user so useAuth() works synchronously during rendering.\n let _authUser = null\n if (_authSessionKey) {\n try { _authUser = await useSession({ name: _authSessionKey }).get() } catch { /* no session secret */ }\n }\n await _cerAuthStore.run(_authUser, async () => {\n const { vnode, router, head, status, loaderData } = await _prepareRequest(req)\n if (status != null) res.statusCode = status\n\n let _headCollectionOpen = false\n // Wrap the entire render pass in _cerDataStore.run(loaderData) so that\n // usePageData() inside component renderFn calls sees the correct store\n // value. AsyncLocalStorage.enterWith() inside _prepareRequest does NOT\n // propagate back to this outer async continuation \u2014 it only affects the\n // async chain inside _prepareRequest itself. Using run() here is the only\n // reliable way to scope the data store to the synchronous render pass.\n await _cerDataStore.run(loaderData ?? null, async () => {\n try {\n // Begin collecting useHead() calls made during the synchronous render pass.\n // IMPORTANT: the stream's start() function runs synchronously on construction,\n // so ALL useHead() calls happen before the stream object is returned. We must\n // call endHeadCollection() immediately \u2014 before any await \u2014 to avoid a race\n // window where a concurrent request (e.g. SSG concurrency > 1) resets the\n // shared globalThis collector while this handler is suspended at an await.\n _headCollectionOpen = true\n beginHeadCollection()\n\n // dsdPolyfill: false \u2014 we inject the polyfill manually after merging so it\n // lands at the end of <body>, not inside <cer-layout-view> light DOM where\n // scripts may not execute.\n // The first chunk from the stream is the full synchronous render. Subsequent\n // chunks are async component swap scripts streamed as they resolve.\n const stream = renderToStreamWithJITCSSDSD(vnode, { dsdPolyfill: false, router })\n\n // Collect head tags synchronously \u2014 all useHead() calls have already fired\n // inside the stream constructor's start() before it returned.\n const headTags = serializeHeadTags(endHeadCollection())\n _headCollectionOpen = false\n\n const reader = stream.getReader()\n\n // Read the first (synchronous) chunk \u2014 rejects if the sync render failed.\n const { value: firstChunk = '' } = await reader.read()\n\n // Serialise useFetch() results collected during loader execution.\n const _fetchObj = Object.fromEntries(_fetchMap)\n const _fetchScript = Object.keys(_fetchObj).length > 0\n ? `<script>window.__CER_FETCH_DATA__ = ${JSON.stringify(_fetchObj)}</script>`\n : ''\n\n // Serialise the auth user for client-side hydration via useAuth().\n const _authScript = _authUser\n ? `<script>window.__CER_AUTH_USER__ = ${JSON.stringify(_authUser)}</script>`\n : ''\n\n // Serialise useState() values for client-side hydration.\n // The state Map is populated by loader calls (in _prepareRequest) and by component\n // render functions (during renderToStreamWithJITCSSDSD above). Both run before this\n // point. Injected as window.__CER_STATE_INIT__ so the client useState() can\n // pre-populate its singleton Map on first use \u2014 no flash to default values.\n const _stateMap = _cerStateStore.getStore()\n let _stateScript = ''\n if (_stateMap && _stateMap.size > 0) {\n const _stateObj = {}\n for (const [k, v] of _stateMap) { _stateObj[k] = v.value }\n _stateScript = `<script>window.__CER_STATE_INIT__ = ${JSON.stringify(_stateObj)}</script>`\n }\n\n // Merge loader data script + useHead() tags + fetch/auth/state hydration scripts.\n const headContent = [head, headTags, _fetchScript, _authScript, _stateScript].filter(Boolean).join('\\n')\n\n // Wrap the rendered body in a full HTML document and inject the head additions\n // (loader data script, useHead() tags, JIT styles). No polyfill in body yet.\n const ssrHtml = `<!DOCTYPE html><html><head>${headContent}</head><body>${firstChunk}</body></html>`\n\n // In dev mode the module-level _clientTemplate is null (only the\n // production dist/client/index.html path is searched at init time).\n // The dev server sets (globalThis).__CER_CLIENT_TEMPLATE__ per-request\n // after running server.transformIndexHtml so the Vite client scripts\n // (/@vite/client, HMR) are included in every SSR response.\n const _resolvedClientTemplate = (globalThis).__CER_CLIENT_TEMPLATE__ ?? _clientTemplate\n const merged = _resolvedClientTemplate\n ? _mergeWithClientTemplate(ssrHtml, _resolvedClientTemplate)\n : ssrHtml\n\n // Split at </body> so async swap scripts and the DSD polyfill can be streamed\n // in before the document is closed.\n const bodyCloseIdx = merged.lastIndexOf('</body>')\n const beforeBodyClose = bodyCloseIdx >= 0 ? merged.slice(0, bodyCloseIdx) : merged\n const fromBodyClose = bodyCloseIdx >= 0 ? merged.slice(bodyCloseIdx) : ''\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.setHeader('Transfer-Encoding', 'chunked')\n res.write(beforeBodyClose)\n\n // Stream async component swap scripts through as-is.\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n res.write(value)\n }\n\n // Inject DSD polyfill immediately before </body>, then close the document.\n res.end(DSD_POLYFILL_SCRIPT + fromBodyClose)\n if (_hooks?.onResponse) {\n try { void _hooks.onResponse({ path: _requestPath, method: req.method ?? 'GET', statusCode: res.statusCode, duration: Date.now() - _requestStart, req }) } catch { /* ignore */ }\n }\n } catch (_renderErr) {\n if (_hooks?.onError) {\n try { await _hooks.onError(_renderErr, { type: 'render', path: _requestPath, req }) } catch { /* hooks must not crash the handler */ }\n }\n // Ensure the head collector is never left open on error.\n if (_headCollectionOpen) { try { endHeadCollection() } catch { /* ignore */ } }\n // If headers have not been flushed yet we can still send a proper 500 page.\n // If writing has already started we can only close the connection cleanly.\n if (!res.headersSent) {\n res.statusCode = 500\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.end('<!DOCTYPE html><html><head></head><body><h1>500 Internal Server Error</h1><p>An unexpected error occurred while rendering this page.</p></body></html>')\n } else {\n res.end()\n }\n if (_hooks?.onResponse) {\n try { void _hooks.onResponse({ path: _requestPath, method: req.method ?? 'GET', statusCode: res.statusCode, duration: Date.now() - _requestStart, req }) } catch { /* ignore */ }\n }\n }\n }) // _cerDataStore.run(loaderData)\n }) // _cerAuthStore.run\n }) // _cerFetchStore.run\n }) // _cerDataStore.run\n }) // _cerReqStore.run\n }) // _cerStateStore.run\n}\n\n// ISR-wrapped handler for production integrations (Express, Hono, Fastify).\n// Routes with meta.ssg.revalidate are served stale-while-revalidate.\nexport const isrHandler = createIsrHandler(routes, handler)\n\nexport { apiRoutes, plugins, layouts, routes, serverMiddleware }\nexport default handler\n";
14
+ export declare const ENTRY_SERVER_TEMPLATE = "// Server-side entry \u2014 AUTO-GENERATED by @jasonshimmy/vite-plugin-cer-app\nimport { readFileSync, existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport routes from 'virtual:cer-routes'\nimport layouts from 'virtual:cer-layouts'\nimport plugins from 'virtual:cer-plugins'\nimport apiRoutes from 'virtual:cer-server-api'\nimport serverMiddleware from 'virtual:cer-server-middleware'\nimport { runtimeConfig, _runtimePrivateDefaults, _authSessionKey, _hooks } from 'virtual:cer-app-config'\nimport { registerBuiltinComponents, setDevMode } from '@jasonshimmy/custom-elements-runtime'\nimport { registerEntityMap, renderToStreamWithJITCSSDSD, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'\nimport entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'\nimport { initRouter } from '@jasonshimmy/custom-elements-runtime/router'\nimport { beginHeadCollection, endHeadCollection, serializeHeadTags, initRuntimeConfig, resolvePrivateConfig, useSession } from '@jasonshimmy/vite-plugin-cer-app/composables'\nimport { errorTag } from 'virtual:cer-error'\nimport { createIsrHandler } from '@jasonshimmy/vite-plugin-cer-app/isr'\n\nconst _cerProcess = (globalThis).process\nconst _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE\nconst _cerRuntimeDev =\n typeof _cerNodeEnv === 'string'\n ? _cerNodeEnv !== 'production'\n : typeof import.meta.env?.DEV === 'boolean'\n ? import.meta.env.DEV\n : typeof import.meta.env?.PROD === 'boolean'\n ? !import.meta.env.PROD\n : typeof import.meta.env?.MODE === 'string'\n ? import.meta.env.MODE !== 'production'\n : false\n;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev\n\nregisterBuiltinComponents()\nsetDevMode(_cerRuntimeDev)\n\n// Resolve private config from environment variables at server startup.\n// Each key declared in runtimeConfig.private is looked up in process.env,\n// first as-is, then as ALL_CAPS. The declared default is used as fallback.\ninitRuntimeConfig({ ...runtimeConfig, private: resolvePrivateConfig(_runtimePrivateDefaults ?? {}) })\n\n// Pre-load the full HTML entity map so named entities like &mdash; decode\n// correctly during SSR. Without this the bundled runtime falls back to a\n// minimal set (&lt;, &gt;, &amp; \u2026) and re-escapes everything else.\nregisterEntityMap(entitiesJson)\n\n// Run plugins once at server startup so their provide() values are available\n// to useInject() during every SSR/SSG render pass. Stored on globalThis so all\n// dynamically-imported page chunks share the same reference.\nconst _pluginProvides = new Map()\n;(globalThis).__cerPluginProvides = _pluginProvides\nconst _pluginsReady = (async () => {\n const _bootstrapRouter = initRouter({ routes })\n for (const plugin of plugins) {\n if (plugin && typeof plugin.setup === 'function') {\n await plugin.setup({\n router: _bootstrapRouter,\n provide: (key, value) => _pluginProvides.set(key, value),\n config: {},\n })\n }\n }\n})()\n\n// Async-local storage for request-scoped SSR loader data.\n// Using AsyncLocalStorage ensures concurrent SSR renders (e.g. SSG with\n// concurrency > 1) never see each other's data \u2014 each request's async chain\n// carries its own store value, so usePageData() is always race-condition-free.\nconst _cerDataStore = new AsyncLocalStorage()\n// Expose the store so the usePageData() composable can read it server-side.\n;(globalThis).__CER_DATA_STORE__ = _cerDataStore\n\n// Async-local storage for request-scoped req/res access.\n// Allows isomorphic composables (e.g. useCookie) to read/write HTTP headers\n// without prop-drilling the request context through the component tree.\nconst _cerReqStore = new AsyncLocalStorage()\n;(globalThis).__CER_REQ_STORE__ = _cerReqStore\n\n// Async-local storage for the authenticated user resolved before each render.\n// useAuth() reads this store server-side to return the current user synchronously.\nconst _cerAuthStore = new AsyncLocalStorage()\n;(globalThis).__CER_AUTH_STORE__ = _cerAuthStore\n\n// Async-local storage for per-request useFetch() data.\n// useFetch() writes fetched results here; the handler serialises the map into\n// window.__CER_FETCH_DATA__ for client-side hydration.\nconst _cerFetchStore = new AsyncLocalStorage()\n;(globalThis).__CER_FETCH_STORE__ = _cerFetchStore\n\n// Async-local storage for the current route info (path, params, query, meta).\n// useRoute() reads this on the server so layouts and components can access\n// route metadata without prop-drilling.\nconst _cerRouteStore = new AsyncLocalStorage()\n;(globalThis).__CER_ROUTE_STORE__ = _cerRouteStore\n\n// Async-local storage for per-request useState() reactive state.\n// Each request gets a fresh Map so concurrent SSR/SSG renders never share\n// reactive state set by different pages or loaders.\nconst _cerStateStore = new AsyncLocalStorage()\n;(globalThis).__CER_STATE_STORE__ = _cerStateStore\n\n// Runs fn inside the per-request AsyncLocalStorage context so that isomorphic\n// composables (useCookie, useSession, etc.) can access req/res without prop-drilling.\n// Call this for every API handler invocation \u2014 not just SSR renders.\nexport function runWithRequestContext(req, res, fn) {\n return _cerReqStore.run({ req, res }, fn)\n}\n\n// Runs the server/middleware/ chain for a request.\n// Returns false if a middleware short-circuited the response; true to continue.\n// Exported so Netlify / Vercel / Cloudflare bridges can also call it for API routes.\n// P1-2: Middleware may throw { status: 401 } (or any numeric .status) to produce\n// a non-500 response \u2014 the status is extracted and forwarded to res.statusCode.\nexport async function runServerMiddleware(req, res) {\n for (const { handler: mw } of (serverMiddleware ?? [])) {\n if (typeof mw !== 'function') continue\n let calledNext = false\n try {\n await new Promise((resolve, reject) => {\n Promise.resolve(mw(req, res, (err) => {\n if (err) reject(err)\n else { calledNext = true; resolve() }\n })).catch(reject)\n })\n } catch (err) {\n if (_hooks?.onError) {\n try { await _hooks.onError(err, { type: 'middleware', path: new URL(req.url ?? '/', 'http://x').pathname, req }) } catch { /* hooks must not crash the handler */ }\n }\n if (!res.writableEnded) {\n const statusCode = (typeof err === 'object' && err !== null && 'status' in err && typeof err.status === 'number')\n ? (isNaN(err.status) ? 500 : err.status)\n : 500\n res.statusCode = statusCode\n res.end('Internal Server Error')\n }\n return false\n }\n if (res.writableEnded || !calledNext) return false\n }\n return true\n}\n\n// Load the Vite-built client index.html (dist/client/index.html) so every SSR\n// response includes the client-side scripts needed for hydration and routing.\n// The server bundle lives at dist/server/server.js, so ../client resolves correctly.\n//\n// Cloudflare Workers (and other runtimes without node:fs) can inject the\n// template before this module loads by setting globalThis.__CER_CLIENT_TEMPLATE__.\n// The Cloudflare adapter inlines dist/client/index.html as a string constant in\n// _worker.js and sets the global before dynamically importing the server bundle.\nlet _clientTemplate = (globalThis).__CER_CLIENT_TEMPLATE__ ?? null\nif (!_clientTemplate) {\n try {\n const _clientTemplatePath = join(dirname(fileURLToPath(import.meta.url)), '../client/index.html')\n _clientTemplate = existsSync(_clientTemplatePath)\n ? readFileSync(_clientTemplatePath, 'utf-8')\n : null\n } catch {\n // node:fs not available in this runtime \u2014 Cloudflare adapter must set\n // globalThis.__CER_CLIENT_TEMPLATE__ before importing this bundle.\n }\n}\n\n// Merge the SSR rendered body with the Vite client shell so the final page\n// contains both pre-rendered DSD content and the client bundle scripts.\nfunction _mergeWithClientTemplate(ssrHtml, clientTemplate) {\n const headTag = '<head>', headCloseTag = '</head>'\n const bodyTag = '<body>', bodyCloseTag = '</body>'\n const headStart = ssrHtml.indexOf(headTag)\n const headEnd = ssrHtml.indexOf(headCloseTag)\n const bodyStart = ssrHtml.indexOf(bodyTag)\n const bodyEnd = ssrHtml.lastIndexOf(bodyCloseTag)\n const ssrHead = headStart >= 0 && headEnd > headStart\n ? ssrHtml.slice(headStart + headTag.length, headEnd).trim() : ''\n const ssrBody = bodyStart >= 0 && bodyEnd > bodyStart\n ? ssrHtml.slice(bodyStart + bodyTag.length, bodyEnd).trim() : ssrHtml\n // Hoist only top-level <style id=...> elements (cer-ssr-jit, cer-ssr-global)\n // from the SSR body into the document <head>. Plain <style> blocks without\n // an id attribute belong to shadow DOM templates and must stay in place \u2014\n // hoisting them to <head> breaks shadow DOM style encapsulation (document\n // styles do not pierce shadow roots), which is the root cause of FOUC.\n const headParts = ssrHead ? [ssrHead] : []\n let ssrBodyContent = ssrBody\n let pos = 0\n while (pos < ssrBodyContent.length) {\n const styleOpen = ssrBodyContent.indexOf('<style id=', pos)\n if (styleOpen < 0) break\n const styleClose = ssrBodyContent.indexOf('</style>', styleOpen)\n if (styleClose < 0) break\n headParts.push(ssrBodyContent.slice(styleOpen, styleClose + 8))\n ssrBodyContent = ssrBodyContent.slice(0, styleOpen) + ssrBodyContent.slice(styleClose + 8)\n pos = styleOpen\n }\n ssrBodyContent = ssrBodyContent.trim()\n // Inject the pre-rendered layout+page as light DOM of the app mount element\n // so it is visible before JS boots, then the client router takes over.\n let merged = clientTemplate\n if (merged.includes('<cer-layout-view></cer-layout-view>')) {\n merged = merged.replace('<cer-layout-view></cer-layout-view>',\n '<cer-layout-view>' + ssrBodyContent + '</cer-layout-view>')\n } else if (merged.includes('<div id=\"app\"></div>')) {\n merged = merged.replace('<div id=\"app\"></div>',\n '<div id=\"app\">' + ssrBodyContent + '</div>')\n }\n const headAdditions = headParts.filter(Boolean).join('\\n')\n if (headAdditions) {\n // If SSR provides a <title>, replace the client template's <title> so the\n // SSR title wins (client template title is the fallback default).\n if (headAdditions.includes('<title>')) {\n merged = merged.replace(/<title>[^<]*<\\/title>/, '')\n }\n merged = merged.replace('</head>', headAdditions + '\\n</head>')\n }\n return merged\n}\n\n// Per-request async setup: initialize a fresh router, resolve the matched\n// route and layout, pre-load the page module, and call the data loader.\n// Loader data is returned so the handler can scope it to _cerDataStore.run()\n// during rendering. (AsyncLocalStorage.enterWith() inside an awaited child\n// function does not propagate back to the parent continuation, so run() is\n// the only reliable approach.)\nconst _prepareRequest = async (req) => {\n await _pluginsReady\n const router = initRouter({ routes, initialUrl: req.url ?? '/' })\n const current = router.getCurrent()\n const { route, params } = router.matchRoute(current.path)\n\n // Store the current route info so useRoute() can read it synchronously\n // from any layout or component during this render pass.\n _cerRouteStore.enterWith({\n path: current.path,\n params,\n query: current.query ?? {},\n meta: route?.meta ?? null,\n })\n\n // Pre-load the page module so we can embed the component tag directly.\n // This avoids the async router-view (which injects content via script tags\n // and breaks Declarative Shadow DOM on initial parse).\n let pageVnode = { tag: 'div', props: {}, children: [] }\n let head\n // Loader data to pass to usePageData() during rendering. Declared here\n // (outside try/catch) so it's visible in all return paths.\n let loaderData = null\n if (route?.load) {\n try {\n const mod = await route.load()\n const pageTag = mod.default\n // P2-2: Route-level error tag (from co-located .error.ts or _error.ts).\n // Preferred over the global errorTag when rendering loader errors for this route.\n const routeErrorTag = mod.errorTag ?? null\n\n // P1-1: Synthetic 404 catch-all \u2014 no page component registered.\n if (!pageTag) {\n const notFoundErrorTag = routeErrorTag ?? errorTag\n const notFoundVnode = notFoundErrorTag\n ? { tag: notFoundErrorTag, props: { attrs: { error: 'Not Found', status: '404' } }, children: [] }\n : { tag: 'div', props: {}, children: [] }\n return { vnode: notFoundVnode, router, head: undefined, status: 404 }\n }\n\n // Run the loader before creating the page vnode so we can pass its\n // primitive return values as HTML attributes. useProps() in the page\n // component reads element attributes, so merging loader data here makes\n // both useProps() and usePageData() work in SSR / SSG.\n let loaderAttrs = {}\n if (typeof mod.loader === 'function') {\n const query = current.query ?? {}\n const data = await mod.loader({ params, query, req })\n if (data !== undefined && data !== null) {\n // Store loader data so the handler can pass it to _cerDataStore.run()\n // below. Using enterWith() here doesn't work because it only modifies\n // the async context *inside* this awaited function, not the outer\n // handler's continuation where renderToStreamWithJITCSSDSD runs.\n loaderData = data\n head = `<script>window.__CER_DATA__ = ${JSON.stringify(data)}</script>`\n // Expose primitive loader values as element attributes so useProps()\n // can read them. Complex objects are only accessible via usePageData().\n loaderAttrs = Object.fromEntries(\n Object.entries(data).filter(([, v]) => v !== null && v !== undefined && typeof v !== 'object' && typeof v !== 'function')\n )\n }\n }\n\n pageVnode = { tag: pageTag, props: { attrs: { ...params, ...loaderAttrs } }, children: [] }\n } catch (err) {\n // Loader threw \u2014 render the error page server-side if app/error.ts exists.\n const status = (err && typeof err === 'object' && 'status' in err && typeof err.status === 'number')\n ? err.status : 500\n const message = (err instanceof Error) ? err.message : String(err)\n if (_hooks?.onError) {\n try { await _hooks.onError(err, { type: 'loader', path: new URL(req.url ?? '/', 'http://x').pathname, req }) } catch { /* hooks must not crash the handler */ }\n }\n // P2-2: Prefer the route-level errorTag over the global one.\n // routeErrorTag is not in scope here; use route?.meta?.errorTag from the matched route.\n const effectiveErrorTag = route?.meta?.errorTag ?? errorTag\n if (!effectiveErrorTag) {\n console.error('[cer-app] Loader error (no app/error.ts defined):', err)\n }\n const errVnode = effectiveErrorTag\n ? { tag: effectiveErrorTag, props: { attrs: { error: message, status: String(status) } }, children: [] }\n : { tag: 'div', props: {}, children: [] }\n return { vnode: errVnode, router, head: undefined, status }\n }\n }\n\n // Resolve layout chain: nested layouts (meta.layoutChain) or single layout.\n const chain = route?.meta?.layoutChain\n ? route.meta.layoutChain\n : [route?.meta?.layout ?? 'default']\n\n // Wrap pageVnode in the layout chain from innermost to outermost.\n let vnode = pageVnode\n for (let i = chain.length - 1; i >= 0; i--) {\n const tag = layouts[chain[i]]\n if (tag) vnode = { tag, props: {}, children: [vnode] }\n }\n\n // Only framework-owned not-found routes should force a 404 status. A user\n // catch-all page ([...all].ts) may successfully resolve real content paths\n // and should stay 200 unless its loader explicitly throws a 404.\n const isNotFoundRoute = route?.meta?._cerNotFound === true\n return { vnode, router, head, status: isNotFoundRoute ? 404 : null, loaderData }\n}\n\nexport const handler = async (req, res) => {\n const _requestPath = new URL(req.url ?? '/', 'http://x').pathname\n const _requestStart = Date.now()\n if (_hooks?.onRequest) {\n try { await _hooks.onRequest({ path: _requestPath, method: req.method ?? 'GET', req }) } catch { /* hooks must not crash the handler */ }\n }\n await _cerStateStore.run(new Map(), async () => {\n await _cerReqStore.run({ req, res }, async () => {\n await _cerDataStore.run(null, async () => {\n // Fresh per-request fetch map \u2014 populated by useFetch() calls inside loaders.\n const _fetchMap = new Map()\n await _cerFetchStore.run(_fetchMap, async () => {\n // Pre-resolve the authenticated user so useAuth() works synchronously during rendering.\n let _authUser = null\n if (_authSessionKey) {\n try { _authUser = await useSession({ name: _authSessionKey }).get() } catch { /* no session secret */ }\n }\n await _cerAuthStore.run(_authUser, async () => {\n const { vnode, router, head, status, loaderData } = await _prepareRequest(req)\n if (status != null) res.statusCode = status\n\n let _headCollectionOpen = false\n // Wrap the entire render pass in _cerDataStore.run(loaderData) so that\n // usePageData() inside component renderFn calls sees the correct store\n // value. AsyncLocalStorage.enterWith() inside _prepareRequest does NOT\n // propagate back to this outer async continuation \u2014 it only affects the\n // async chain inside _prepareRequest itself. Using run() here is the only\n // reliable way to scope the data store to the synchronous render pass.\n await _cerDataStore.run(loaderData ?? null, async () => {\n try {\n // Begin collecting useHead() calls made during the synchronous render pass.\n // IMPORTANT: the stream's start() function runs synchronously on construction,\n // so ALL useHead() calls happen before the stream object is returned. We must\n // call endHeadCollection() immediately \u2014 before any await \u2014 to avoid a race\n // window where a concurrent request (e.g. SSG concurrency > 1) resets the\n // shared globalThis collector while this handler is suspended at an await.\n _headCollectionOpen = true\n beginHeadCollection()\n\n // dsdPolyfill: false \u2014 we inject the polyfill manually after merging so it\n // lands at the end of <body>, not inside <cer-layout-view> light DOM where\n // scripts may not execute.\n // The first chunk from the stream is the full synchronous render. Subsequent\n // chunks are async component swap scripts streamed as they resolve.\n const stream = renderToStreamWithJITCSSDSD(vnode, { dsdPolyfill: false, router })\n\n // Collect head tags synchronously \u2014 all useHead() calls have already fired\n // inside the stream constructor's start() before it returned.\n const headTags = serializeHeadTags(endHeadCollection())\n _headCollectionOpen = false\n\n const reader = stream.getReader()\n\n // Read the first (synchronous) chunk \u2014 rejects if the sync render failed.\n const { value: firstChunk = '' } = await reader.read()\n\n // Serialise useFetch() results collected during loader execution.\n const _fetchObj = Object.fromEntries(_fetchMap)\n const _fetchScript = Object.keys(_fetchObj).length > 0\n ? `<script>window.__CER_FETCH_DATA__ = ${JSON.stringify(_fetchObj)}</script>`\n : ''\n\n // Serialise the auth user for client-side hydration via useAuth().\n const _authScript = _authUser\n ? `<script>window.__CER_AUTH_USER__ = ${JSON.stringify(_authUser)}</script>`\n : ''\n\n // Serialise useState() values for client-side hydration.\n // The state Map is populated by loader calls (in _prepareRequest) and by component\n // render functions (during renderToStreamWithJITCSSDSD above). Both run before this\n // point. Injected as window.__CER_STATE_INIT__ so the client useState() can\n // pre-populate its singleton Map on first use \u2014 no flash to default values.\n const _stateMap = _cerStateStore.getStore()\n let _stateScript = ''\n if (_stateMap && _stateMap.size > 0) {\n const _stateObj = {}\n for (const [k, v] of _stateMap) { _stateObj[k] = v.value }\n _stateScript = `<script>window.__CER_STATE_INIT__ = ${JSON.stringify(_stateObj)}</script>`\n }\n\n // Merge loader data script + useHead() tags + fetch/auth/state hydration scripts.\n const headContent = [head, headTags, _fetchScript, _authScript, _stateScript].filter(Boolean).join('\\n')\n\n // Wrap the rendered body in a full HTML document and inject the head additions\n // (loader data script, useHead() tags, JIT styles). No polyfill in body yet.\n const ssrHtml = `<!DOCTYPE html><html><head>${headContent}</head><body>${firstChunk}</body></html>`\n\n // In dev mode the module-level _clientTemplate is null (only the\n // production dist/client/index.html path is searched at init time).\n // The dev server sets (globalThis).__CER_CLIENT_TEMPLATE__ per-request\n // after running server.transformIndexHtml so the Vite client scripts\n // (/@vite/client, HMR) are included in every SSR response.\n const _resolvedClientTemplate = (globalThis).__CER_CLIENT_TEMPLATE__ ?? _clientTemplate\n const merged = _resolvedClientTemplate\n ? _mergeWithClientTemplate(ssrHtml, _resolvedClientTemplate)\n : ssrHtml\n\n // Split at </body> so async swap scripts and the DSD polyfill can be streamed\n // in before the document is closed.\n const bodyCloseIdx = merged.lastIndexOf('</body>')\n const beforeBodyClose = bodyCloseIdx >= 0 ? merged.slice(0, bodyCloseIdx) : merged\n const fromBodyClose = bodyCloseIdx >= 0 ? merged.slice(bodyCloseIdx) : ''\n\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.setHeader('Transfer-Encoding', 'chunked')\n res.write(beforeBodyClose)\n\n // Stream async component swap scripts through as-is.\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n res.write(value)\n }\n\n // Inject DSD polyfill immediately before </body>, then close the document.\n res.end(DSD_POLYFILL_SCRIPT + fromBodyClose)\n if (_hooks?.onResponse) {\n try { void _hooks.onResponse({ path: _requestPath, method: req.method ?? 'GET', statusCode: res.statusCode, duration: Date.now() - _requestStart, req }) } catch { /* ignore */ }\n }\n } catch (_renderErr) {\n if (_hooks?.onError) {\n try { await _hooks.onError(_renderErr, { type: 'render', path: _requestPath, req }) } catch { /* hooks must not crash the handler */ }\n }\n // Ensure the head collector is never left open on error.\n if (_headCollectionOpen) { try { endHeadCollection() } catch { /* ignore */ } }\n // If headers have not been flushed yet we can still send a proper 500 page.\n // If writing has already started we can only close the connection cleanly.\n if (!res.headersSent) {\n res.statusCode = 500\n res.setHeader('Content-Type', 'text/html; charset=utf-8')\n res.end('<!DOCTYPE html><html><head></head><body><h1>500 Internal Server Error</h1><p>An unexpected error occurred while rendering this page.</p></body></html>')\n } else {\n res.end()\n }\n if (_hooks?.onResponse) {\n try { void _hooks.onResponse({ path: _requestPath, method: req.method ?? 'GET', statusCode: res.statusCode, duration: Date.now() - _requestStart, req }) } catch { /* ignore */ }\n }\n }\n }) // _cerDataStore.run(loaderData)\n }) // _cerAuthStore.run\n }) // _cerFetchStore.run\n }) // _cerDataStore.run\n }) // _cerReqStore.run\n }) // _cerStateStore.run\n}\n\n// ISR-wrapped handler for production integrations (Express, Hono, Fastify).\n// Routes with meta.ssg.revalidate are served stale-while-revalidate.\nexport const isrHandler = createIsrHandler(routes, handler)\n\nexport { apiRoutes, plugins, layouts, routes, serverMiddleware }\nexport default handler\n";
15
15
  //# sourceMappingURL=entry-server-template.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"entry-server-template.d.ts","sourceRoot":"","sources":["../../src/runtime/entry-server-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,wzuBA8cjC,CAAA"}
1
+ {"version":3,"file":"entry-server-template.d.ts","sourceRoot":"","sources":["../../src/runtime/entry-server-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,qBAAqB,s9vBA8djC,CAAA"}
@@ -22,7 +22,7 @@ import plugins from 'virtual:cer-plugins'
22
22
  import apiRoutes from 'virtual:cer-server-api'
23
23
  import serverMiddleware from 'virtual:cer-server-middleware'
24
24
  import { runtimeConfig, _runtimePrivateDefaults, _authSessionKey, _hooks } from 'virtual:cer-app-config'
25
- import { registerBuiltinComponents } from '@jasonshimmy/custom-elements-runtime'
25
+ import { registerBuiltinComponents, setDevMode } from '@jasonshimmy/custom-elements-runtime'
26
26
  import { registerEntityMap, renderToStreamWithJITCSSDSD, DSD_POLYFILL_SCRIPT } from '@jasonshimmy/custom-elements-runtime/ssr'
27
27
  import entitiesJson from '@jasonshimmy/custom-elements-runtime/entities.json'
28
28
  import { initRouter } from '@jasonshimmy/custom-elements-runtime/router'
@@ -30,7 +30,22 @@ import { beginHeadCollection, endHeadCollection, serializeHeadTags, initRuntimeC
30
30
  import { errorTag } from 'virtual:cer-error'
31
31
  import { createIsrHandler } from '@jasonshimmy/vite-plugin-cer-app/isr'
32
32
 
33
+ const _cerProcess = (globalThis).process
34
+ const _cerNodeEnv = _cerProcess?.env?.NODE_ENV ?? _cerProcess?.env?.MODE
35
+ const _cerRuntimeDev =
36
+ typeof _cerNodeEnv === 'string'
37
+ ? _cerNodeEnv !== 'production'
38
+ : typeof import.meta.env?.DEV === 'boolean'
39
+ ? import.meta.env.DEV
40
+ : typeof import.meta.env?.PROD === 'boolean'
41
+ ? !import.meta.env.PROD
42
+ : typeof import.meta.env?.MODE === 'string'
43
+ ? import.meta.env.MODE !== 'production'
44
+ : false
45
+ ;(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev
46
+
33
47
  registerBuiltinComponents()
48
+ setDevMode(_cerRuntimeDev)
34
49
 
35
50
  // Resolve private config from environment variables at server startup.
36
51
  // Each key declared in runtimeConfig.private is looked up in process.env,
@@ -315,10 +330,11 @@ const _prepareRequest = async (req) => {
315
330
  if (tag) vnode = { tag, props: {}, children: [vnode] }
316
331
  }
317
332
 
318
- // If the request matched a catch-all route (user-defined 404.ts or [...all].ts),
319
- // return HTTP 404 so browsers and crawlers treat it as a not-found response.
320
- const isCatchAll = route?.path === '/:all*'
321
- return { vnode, router, head, status: isCatchAll ? 404 : null, loaderData }
333
+ // Only framework-owned not-found routes should force a 404 status. A user
334
+ // catch-all page ([...all].ts) may successfully resolve real content paths
335
+ // and should stay 200 unless its loader explicitly throws a 404.
336
+ const isNotFoundRoute = route?.meta?._cerNotFound === true
337
+ return { vnode, router, head, status: isNotFoundRoute ? 404 : null, loaderData }
322
338
  }
323
339
 
324
340
  export const handler = async (req, res) => {
@@ -1 +1 @@
1
- {"version":3,"file":"entry-server-template.js","sourceRoot":"","sources":["../../src/runtime/entry-server-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8cpC,CAAA"}
1
+ {"version":3,"file":"entry-server-template.js","sourceRoot":"","sources":["../../src/runtime/entry-server-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8dpC,CAAA"}
@@ -95,7 +95,7 @@ ssg: {
95
95
 
96
96
  Which paths to generate at build time.
97
97
 
98
- - `'auto'` — Scans `app/pages/` and generates all static routes. For dynamic routes, calls `meta.ssg.paths()` to enumerate paths.
98
+ - `'auto'` — Scans `app/pages/` and generates all static routes. For dynamic routes, calls `meta.ssg.paths()` to enumerate paths. Content-backed catch-all pages that use `queryContent()` can also auto-enumerate concrete paths from the content store.
99
99
  - `string[]` — Explicit list of paths, e.g. `['/about', '/blog/hello-world']`.
100
100
 
101
101
  ### `ssg.concurrency`
package/docs/content.md CHANGED
@@ -423,6 +423,12 @@ function normalizeContentPath(all: string | undefined) {
423
423
 
424
424
  This pattern works well for documentation sites, blogs, and other apps where the route structure mirrors the `content/` directory. `queryContent('/docs/getting-started').first()` returns the full `ContentItem`, including `body`, `excerpt`, and `toc`.
425
425
 
426
+ Important behavior notes:
427
+
428
+ - A content-backed `[...all].ts` route is not treated as a framework 404 by default. If `queryContent()` finds a matching document, SSR/SSG responses stay HTTP 200.
429
+ - If no document is found and you want a real HTTP 404, throw a not-found error from the loader instead of only rendering a `404` heading in the template.
430
+ - In SSG with `ssg.routes: 'auto'`, catch-all pages that use `queryContent()` can auto-generate concrete output paths from the content store. You only need `meta.ssg.paths` when the URLs come from some other source.
431
+
426
432
  ---
427
433
 
428
434
  ## `useContentSearch()`
@@ -226,6 +226,8 @@ export const meta = {
226
226
 
227
227
  Dynamic routes without `ssg.paths` are skipped during SSG. If `ssg.fallback: true`, they fall back to SSR at runtime. Otherwise they return 404.
228
228
 
229
+ Catch-all pages (`[...all].ts`) follow the same rule, with one extra convenience for the built-in content layer: if the catch-all page resolves URLs with `queryContent()` and `ssg.routes` is `'auto'`, the SSG build can auto-enumerate concrete paths from the in-memory content store. For non-content catch-all pages, continue to provide `meta.ssg.paths` explicitly.
230
+
229
231
  ### SSG manifest
230
232
 
231
233
  ```json
package/docs/routing.md CHANGED
@@ -61,9 +61,14 @@ The `:slug` param is populated by the router and passed as a prop to the compone
61
61
 
62
62
  ## Catch-all routes and 404 pages
63
63
 
64
- There are two equivalent ways to define a catch-all / 404 page:
64
+ `404.ts` and `[...all].ts` both map to the same route pattern (`/:all*`), but they are not the same thing semantically:
65
65
 
66
- **Option A — `404.ts` (recommended shorthand)**
66
+ - `404.ts` is the conventional not-found route. It should render your 404 UI, and the framework treats it as a real HTTP 404 route.
67
+ - `[...all].ts` is a general catch-all route. It can be used for not-found pages, but it is also the right choice for content-driven routing where valid URLs are resolved at runtime.
68
+
69
+ Use `404.ts` when the route is truly your global not-found page. Use `[...all].ts` when the route needs application logic to decide whether the current URL is valid.
70
+
71
+ **Option A — `404.ts` (recommended for true not-found pages)**
67
72
 
68
73
  ```ts
69
74
  // app/pages/404.ts
@@ -77,7 +82,7 @@ component('page-404', () => {
77
82
  })
78
83
  ```
79
84
 
80
- The framework special-cases `404.ts` and automatically registers it as the catch-all route (`/:all*`). This is the conventional name and is the approach used by the kitchen-sink example.
85
+ The framework special-cases `404.ts` and automatically registers it as the catch-all route (`/:all*`). In SSR/SSG, it is treated as a real not-found route and returns HTTP 404.
81
86
 
82
87
  **Option B — `[...name].ts` explicit catch-all**
83
88
 
@@ -88,7 +93,9 @@ component('page-all', () => {
88
93
  })
89
94
  ```
90
95
 
91
- Both produce the same route (`/:all*`) and either form works. Use `404.ts` for clarity.
96
+ This still produces the same route pattern (`/:all*`), but unlike `404.ts` it is not assumed to be a 404 by default. If the page successfully resolves data for the current URL, the response stays HTTP 200. If the page decides the URL is missing, throw or return a 404 from your loader explicitly.
97
+
98
+ This is the pattern to use for content-driven sites, documentation trees, storefront catalogs, and other apps where one catch-all page resolves many valid nested URLs.
92
99
 
93
100
  **Synthetic 404 fallback (automatic)**
94
101
 
@@ -101,6 +108,8 @@ The synthetic route:
101
108
 
102
109
  Add a real `404.ts` to customize the experience; the synthetic fallback is removed automatically once one exists.
103
110
 
111
+ Note that `app/error.ts` is a global error boundary, not a route page. You can also define per-route error boundaries with `foo.error.ts` or directory-level `_error.ts`. See [data-loading.md](./data-loading.md#error-boundary--apperrorts) for the global error page and the route-level error-boundary section later in this guide for per-route overrides.
112
+
104
113
  ---
105
114
 
106
115
  ## Route groups
@@ -250,6 +259,22 @@ export const meta = {
250
259
  }
251
260
  ```
252
261
 
262
+ Catch-all pages can use `meta.ssg.paths` too:
263
+
264
+ ```ts
265
+ // app/pages/[...all].ts
266
+ export const meta = {
267
+ ssg: {
268
+ paths: async () => [
269
+ { params: { all: 'docs/getting-started' } },
270
+ { params: { all: 'docs/routing' } },
271
+ ],
272
+ },
273
+ }
274
+ ```
275
+
276
+ For content-backed catch-all pages that resolve URLs with `queryContent()`, SSG can also auto-discover concrete paths from the content store when `ssg.routes` is set to `'auto'`.
277
+
253
278
  ### `meta.ssg.revalidate`
254
279
 
255
280
  **Type:** `number` (seconds)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jasonshimmy/vite-plugin-cer-app",
3
- "version": "0.21.0",
3
+ "version": "0.21.2",
4
4
  "description": "Nuxt-style meta-framework for @jasonshimmy/custom-elements-runtime",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -98,7 +98,7 @@
98
98
  "pathe": "^2.0.3"
99
99
  },
100
100
  "devDependencies": {
101
- "@jasonshimmy/custom-elements-runtime": "^3.7.4",
101
+ "@jasonshimmy/custom-elements-runtime": "^3.7.5",
102
102
  "@types/node": "^25.6.0",
103
103
  "@vitest/coverage-v8": "^4.1.2",
104
104
  "cypress": "^15.13.1",
@@ -107,7 +107,7 @@
107
107
  "jiti": "^2.6.1",
108
108
  "start-server-and-test": "^3.0.2",
109
109
  "typescript": "^5.9.3",
110
- "typescript-eslint": "^8.58.1",
110
+ "typescript-eslint": "^8.58.2",
111
111
  "vite": "^8.0.8",
112
112
  "vitest": "^4.1.0"
113
113
  },
@@ -26,9 +26,18 @@ describe('app-template (APP_ENTRY_TEMPLATE content)', () => {
26
26
 
27
27
  it('imports registerBuiltinComponents from custom-elements-runtime', () => {
28
28
  expect(src).toContain('registerBuiltinComponents')
29
+ expect(src).toContain('setDevMode')
29
30
  expect(src).toContain('@jasonshimmy/custom-elements-runtime')
30
31
  })
31
32
 
33
+ it('enables runtime dev logging from the downstream Vite env', () => {
34
+ expect(src).toContain('const _cerRuntimeDev')
35
+ expect(src).toContain('import.meta.env?.DEV')
36
+ expect(src).toContain('_cerProcess?.env')
37
+ expect(src).toContain('(globalThis).__CE_RUNTIME_DEV__ = _cerRuntimeDev')
38
+ expect(src).toContain('setDevMode(_cerRuntimeDev)')
39
+ })
40
+
32
41
  it('imports initRouter from the router subpath', () => {
33
42
  expect(src).toContain('initRouter')
34
43
  expect(src).toContain('custom-elements-runtime/router')
@@ -227,15 +227,22 @@ describe('buildSSG — path collection', () => {
227
227
  expect(manifest.paths.length + manifest.errors.length).toBe(3)
228
228
  })
229
229
 
230
- it('skips catch-all pages when auto-discovering paths', async () => {
230
+ it('skips catch-all pages without explicit paths or content queries when auto-discovering paths', async () => {
231
231
  vi.mocked(existsSync).mockReturnValue(true)
232
232
  vi.mocked(fg).mockResolvedValue(['/project/app/pages/[...all].ts'])
233
+ vi.mocked(readFile).mockResolvedValue('')
233
234
  vi.mocked(buildRouteEntry).mockReturnValueOnce({
234
235
  routePath: '/:all*',
235
236
  isDynamic: true,
236
237
  isCatchAll: true,
237
238
  } as ReturnType<typeof buildRouteEntry>)
238
239
 
240
+ const closeFn = vi.fn().mockResolvedValue(undefined)
241
+ vi.mocked(createServer).mockResolvedValue({
242
+ ssrLoadModule: vi.fn().mockResolvedValue({}),
243
+ close: closeFn,
244
+ } as unknown as Awaited<ReturnType<typeof createServer>>)
245
+
239
246
  await buildSSG(makeConfig())
240
247
 
241
248
  // Only '/' (always added) should be attempted
@@ -246,6 +253,110 @@ describe('buildSSG — path collection', () => {
246
253
  expect(manifest.paths.length + manifest.errors.length).toBe(1)
247
254
  })
248
255
 
256
+ it('auto-expands content-backed catch-all pages from the content store', async () => {
257
+ vi.mocked(existsSync).mockReturnValue(true)
258
+ vi.mocked(fg).mockResolvedValue(['/project/app/pages/[...all].ts'])
259
+ vi.mocked(readFile).mockResolvedValue('export const loader = async () => queryContent().find()')
260
+ vi.mocked(buildRouteEntry).mockReturnValueOnce({
261
+ routePath: '/:all*',
262
+ isDynamic: true,
263
+ isCatchAll: true,
264
+ } as ReturnType<typeof buildRouteEntry>)
265
+
266
+ ;(globalThis as Record<string, unknown>).__CER_CONTENT_STORE__ = [
267
+ { _path: '/music/effects/pro-co/rat' },
268
+ { _path: '/music/effects/boss/ds-1' },
269
+ ]
270
+
271
+ const closeFn = vi.fn().mockResolvedValue(undefined)
272
+ vi.mocked(createServer).mockResolvedValue({
273
+ ssrLoadModule: vi.fn().mockResolvedValue({}),
274
+ close: closeFn,
275
+ } as unknown as Awaited<ReturnType<typeof createServer>>)
276
+
277
+ await buildSSG(makeConfig({ ssg: { concurrency: 1 } } as Partial<ResolvedCerConfig>))
278
+
279
+ const manifestCall = vi.mocked(writeFile).mock.calls.find(([p]) =>
280
+ String(p).includes('ssg-manifest.json'),
281
+ )
282
+ const manifest = JSON.parse(String(manifestCall![1]))
283
+ expect(manifest.paths.length + manifest.errors.length).toBe(3)
284
+
285
+ delete (globalThis as Record<string, unknown>).__CER_CONTENT_STORE__
286
+ })
287
+
288
+ it('filters auto-expanded content paths by nested catch-all prefix', async () => {
289
+ vi.mocked(existsSync).mockReturnValue(true)
290
+ vi.mocked(fg).mockResolvedValue(['/project/app/pages/docs/[...all].ts'])
291
+ vi.mocked(readFile).mockResolvedValue('queryContent()')
292
+ vi.mocked(buildRouteEntry).mockReturnValueOnce({
293
+ routePath: '/docs/:all*',
294
+ isDynamic: true,
295
+ isCatchAll: true,
296
+ } as ReturnType<typeof buildRouteEntry>)
297
+
298
+ ;(globalThis as Record<string, unknown>).__CER_CONTENT_STORE__ = [
299
+ { _path: '/docs/getting-started' },
300
+ { _path: '/docs/api/config' },
301
+ { _path: '/blog/hello' },
302
+ ]
303
+
304
+ const closeFn = vi.fn().mockResolvedValue(undefined)
305
+ vi.mocked(createServer).mockResolvedValue({
306
+ ssrLoadModule: vi.fn().mockResolvedValue({}),
307
+ close: closeFn,
308
+ } as unknown as Awaited<ReturnType<typeof createServer>>)
309
+
310
+ await buildSSG(makeConfig({ ssg: { concurrency: 1 } } as Partial<ResolvedCerConfig>))
311
+
312
+ const manifestCall = vi.mocked(writeFile).mock.calls.find(([p]) =>
313
+ String(p).includes('ssg-manifest.json'),
314
+ )
315
+ const manifest = JSON.parse(String(manifestCall![1]))
316
+ expect(manifest.paths.length + manifest.errors.length).toBe(3)
317
+
318
+ delete (globalThis as Record<string, unknown>).__CER_CONTENT_STORE__
319
+ })
320
+
321
+ it('expands catch-all ssg.paths into concrete URL paths', async () => {
322
+ vi.mocked(existsSync).mockReturnValue(true)
323
+ vi.mocked(fg).mockResolvedValue(['/project/app/pages/[...all].ts'])
324
+ vi.mocked(readFile).mockResolvedValue('')
325
+ vi.mocked(buildRouteEntry).mockReturnValueOnce({
326
+ routePath: '/:all*',
327
+ isDynamic: true,
328
+ isCatchAll: true,
329
+ } as ReturnType<typeof buildRouteEntry>)
330
+
331
+ const closeFn = vi.fn().mockResolvedValue(undefined)
332
+ vi.mocked(createServer).mockResolvedValue({
333
+ ssrLoadModule: vi.fn().mockResolvedValue({
334
+ meta: {
335
+ ssg: {
336
+ paths: async () => [
337
+ { params: { all: 'music/effects/pro-co/rat' } },
338
+ { params: { all: 'music/effects/boss/ds-1' } },
339
+ ],
340
+ },
341
+ },
342
+ }),
343
+ close: closeFn,
344
+ } as unknown as Awaited<ReturnType<typeof createServer>>)
345
+
346
+ await buildSSG(makeConfig({ ssg: { concurrency: 1 } } as Partial<ResolvedCerConfig>))
347
+
348
+ const manifestCall = vi.mocked(writeFile).mock.calls.find(([p]) =>
349
+ String(p).includes('ssg-manifest.json'),
350
+ )
351
+ const manifest = JSON.parse(String(manifestCall![1]))
352
+ expect(manifest.paths.length + manifest.errors.length).toBe(3)
353
+ expect(manifest.errors.map((entry: { path: string }) => entry.path)).toEqual([
354
+ '/',
355
+ '/music/effects/pro-co/rat',
356
+ '/music/effects/boss/ds-1',
357
+ ])
358
+ })
359
+
249
360
  it('deduplicates collected paths', async () => {
250
361
  vi.mocked(existsSync).mockReturnValue(true)
251
362
  vi.mocked(fg).mockResolvedValue([