@demiurgejs/core 0.1.1 → 0.2.0-beta.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 (151) hide show
  1. package/README.md +5 -0
  2. package/bin/demiurge.mjs +51 -0
  3. package/dist/adapter/testing.d.ts +33 -0
  4. package/dist/adapter/testing.d.ts.map +1 -0
  5. package/dist/adapter/testing.js +251 -0
  6. package/dist/adapter/testing.js.map +1 -0
  7. package/dist/browser/file-router.d.ts.map +1 -1
  8. package/dist/chunks/document-shell-D1xo6cEA.js +35 -0
  9. package/dist/chunks/document-shell-D1xo6cEA.js.map +1 -0
  10. package/dist/chunks/image-codec-BGTx_t5K.js +141 -0
  11. package/dist/chunks/image-codec-BGTx_t5K.js.map +1 -0
  12. package/dist/chunks/images-B9MqcjSA.js +339 -0
  13. package/dist/chunks/images-B9MqcjSA.js.map +1 -0
  14. package/dist/chunks/request-metadata-D5NrT8ks.js +642 -0
  15. package/dist/chunks/request-metadata-D5NrT8ks.js.map +1 -0
  16. package/dist/chunks/streaming-BQ1bykDo.js +469 -0
  17. package/dist/chunks/streaming-BQ1bykDo.js.map +1 -0
  18. package/dist/chunks/{testing-DR3eQAvY.js → testing-B_iMFYz_.js} +2376 -1927
  19. package/dist/chunks/testing-B_iMFYz_.js.map +1 -0
  20. package/dist/cli.d.ts +42 -0
  21. package/dist/cli.d.ts.map +1 -0
  22. package/dist/cli.js +173 -0
  23. package/dist/cli.js.map +1 -0
  24. package/dist/document/deferred-scripts.d.ts +11 -0
  25. package/dist/document/deferred-scripts.d.ts.map +1 -0
  26. package/dist/document/index.d.ts +4 -2
  27. package/dist/document/index.d.ts.map +1 -1
  28. package/dist/document/render.d.ts +1 -1
  29. package/dist/document/render.d.ts.map +1 -1
  30. package/dist/document/scripts.d.ts +34 -1
  31. package/dist/document/scripts.d.ts.map +1 -1
  32. package/dist/edge/assets.d.ts +14 -0
  33. package/dist/edge/assets.d.ts.map +1 -0
  34. package/dist/edge/index.d.ts +19 -0
  35. package/dist/edge/index.d.ts.map +1 -0
  36. package/dist/edge/index.js +286 -0
  37. package/dist/edge/index.js.map +1 -0
  38. package/dist/edge/stores.d.ts +8 -0
  39. package/dist/edge/stores.d.ts.map +1 -0
  40. package/dist/edge/streaming.d.ts +7 -0
  41. package/dist/edge/streaming.d.ts.map +1 -0
  42. package/dist/index.d.ts +9 -9
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +894 -1043
  45. package/dist/index.js.map +1 -1
  46. package/dist/internal/testing.js +12 -11
  47. package/dist/internal/testing.js.map +1 -1
  48. package/dist/kv/index.d.ts +3 -0
  49. package/dist/kv/index.d.ts.map +1 -0
  50. package/dist/kv/index.js +103 -0
  51. package/dist/kv/index.js.map +1 -0
  52. package/dist/kv/store.d.ts +28 -0
  53. package/dist/kv/store.d.ts.map +1 -0
  54. package/dist/node/font.d.ts +5 -0
  55. package/dist/node/font.d.ts.map +1 -0
  56. package/dist/node/image.d.ts +15 -0
  57. package/dist/node/image.d.ts.map +1 -0
  58. package/dist/node/index.d.ts +4 -0
  59. package/dist/node/index.d.ts.map +1 -1
  60. package/dist/node/index.js +25 -23
  61. package/dist/node/index.js.map +1 -1
  62. package/dist/node/streaming.d.ts +2 -0
  63. package/dist/node/streaming.d.ts.map +1 -1
  64. package/dist/platform/analytics.d.ts +58 -5
  65. package/dist/platform/analytics.d.ts.map +1 -1
  66. package/dist/platform/font-assets.d.ts +19 -0
  67. package/dist/platform/font-assets.d.ts.map +1 -0
  68. package/dist/platform/fonts.d.ts +14 -4
  69. package/dist/platform/fonts.d.ts.map +1 -1
  70. package/dist/platform/image-codec.d.ts +15 -0
  71. package/dist/platform/image-codec.d.ts.map +1 -0
  72. package/dist/platform/image-url.d.ts +17 -0
  73. package/dist/platform/image-url.d.ts.map +1 -0
  74. package/dist/platform/image.d.ts +8 -0
  75. package/dist/platform/image.d.ts.map +1 -0
  76. package/dist/platform/images.d.ts +15 -0
  77. package/dist/platform/images.d.ts.map +1 -1
  78. package/dist/platform/index.d.ts +8 -5
  79. package/dist/platform/index.d.ts.map +1 -1
  80. package/dist/redis/index.d.ts +3 -0
  81. package/dist/redis/index.d.ts.map +1 -0
  82. package/dist/redis/index.js +171 -0
  83. package/dist/redis/index.js.map +1 -0
  84. package/dist/redis/store.d.ts +8 -0
  85. package/dist/redis/store.d.ts.map +1 -0
  86. package/dist/route/action.d.ts +11 -11
  87. package/dist/route/action.d.ts.map +1 -1
  88. package/dist/route/index.d.ts +2 -1
  89. package/dist/route/index.d.ts.map +1 -1
  90. package/dist/route/middleware.d.ts +7 -0
  91. package/dist/route/middleware.d.ts.map +1 -0
  92. package/dist/route/page.d.ts +2 -2
  93. package/dist/route/page.d.ts.map +1 -1
  94. package/dist/route/response.d.ts +19 -19
  95. package/dist/route/response.d.ts.map +1 -1
  96. package/dist/route/types.d.ts +55 -31
  97. package/dist/route/types.d.ts.map +1 -1
  98. package/dist/route/webhook.d.ts +1 -1
  99. package/dist/router/manifest.d.ts +1 -0
  100. package/dist/router/manifest.d.ts.map +1 -1
  101. package/dist/routing/generate.d.ts +2 -0
  102. package/dist/routing/generate.d.ts.map +1 -1
  103. package/dist/routing/index.d.ts +1 -1
  104. package/dist/routing/index.d.ts.map +1 -1
  105. package/dist/routing/types.d.ts +2 -0
  106. package/dist/routing/types.d.ts.map +1 -1
  107. package/dist/security/cors.d.ts.map +1 -1
  108. package/dist/security/index.d.ts +4 -2
  109. package/dist/security/index.d.ts.map +1 -1
  110. package/dist/security/policy.d.ts +5 -1
  111. package/dist/security/policy.d.ts.map +1 -1
  112. package/dist/security/types.d.ts +34 -13
  113. package/dist/security/types.d.ts.map +1 -1
  114. package/dist/security/verification.d.ts +8 -0
  115. package/dist/security/verification.d.ts.map +1 -0
  116. package/dist/server/document-shell.d.ts +12 -0
  117. package/dist/server/document-shell.d.ts.map +1 -0
  118. package/dist/server/errors.d.ts.map +1 -1
  119. package/dist/server/not-found.d.ts.map +1 -1
  120. package/dist/server/render-tree.d.ts +6 -1
  121. package/dist/server/render-tree.d.ts.map +1 -1
  122. package/dist/server/request-handler.d.ts +4 -1
  123. package/dist/server/request-handler.d.ts.map +1 -1
  124. package/dist/server/ssr.d.ts +1 -0
  125. package/dist/server/ssr.d.ts.map +1 -1
  126. package/dist/static/images.d.ts +13 -0
  127. package/dist/static/images.d.ts.map +1 -0
  128. package/dist/static/index.d.ts +18 -0
  129. package/dist/static/index.d.ts.map +1 -1
  130. package/dist/static/index.js +677 -129
  131. package/dist/static/index.js.map +1 -1
  132. package/dist/static/preview.d.ts +8 -0
  133. package/dist/static/preview.d.ts.map +1 -0
  134. package/dist/static/vercel.d.ts +34 -0
  135. package/dist/static/vercel.d.ts.map +1 -0
  136. package/dist/vite/index.d.ts +3 -2
  137. package/dist/vite/index.d.ts.map +1 -1
  138. package/dist/vite/index.js +782 -329
  139. package/dist/vite/index.js.map +1 -1
  140. package/dist/vite/plugin.d.ts +20 -0
  141. package/dist/vite/plugin.d.ts.map +1 -1
  142. package/dist/vite/policy-verification.d.ts +10 -0
  143. package/dist/vite/policy-verification.d.ts.map +1 -0
  144. package/package.json +38 -2
  145. package/dist/chunks/index-BnX9Qxbm.js +0 -44
  146. package/dist/chunks/index-BnX9Qxbm.js.map +0 -1
  147. package/dist/chunks/ssr-BJejKlkZ.js +0 -275
  148. package/dist/chunks/ssr-BJejKlkZ.js.map +0 -1
  149. package/dist/chunks/streaming-DN1DnbRE.js +0 -343
  150. package/dist/chunks/streaming-DN1DnbRE.js.map +0 -1
  151. package/dist/chunks/testing-DR3eQAvY.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/package-name.ts","../../src/routing/generate.ts","../../src/vite/plugin.ts"],"sourcesContent":["// The package name is the specifier that user code imports. Generated client\n// entries, server entries, and route type declarations use it. Page route\n// detection also compares application source with it. A mismatch then breaks\n// resolution in the consumer build.\n//\n// This is deliberately not the same thing as the many internal `demiurge`\n// strings elsewhere in the source. `__demiurge_data`, `virtual:demiurge/*`,\n// `demiurge-manifest.json`, and friends name the framework, not the package,\n// and they stay put if the registry name ever changes.\nexport const PACKAGE_NAME = \"@demiurgejs/core\";\n","import { mkdir, readdir, writeFile } from \"node:fs/promises\";\nimport { dirname, relative, resolve, sep } from \"node:path\";\nimport { PACKAGE_NAME } from \"../package-name\";\n\nexport type GenerateRoutesOptions = {\n outputFile: string;\n routesDir: string;\n};\n\ntype RouteInfo = {\n pathVars: string[];\n pattern: string;\n};\n\nexport async function generateRoutes(options: GenerateRoutesOptions) {\n const routeFiles = await findRouteFiles(options.routesDir);\n const routes = routeFiles\n .map((file) => toRouteInfo(options.routesDir, file))\n .filter((route): route is RouteInfo => Boolean(route))\n .sort((a, b) => a.pattern.localeCompare(b.pattern));\n\n const source = renderRoutesModule(routes);\n\n await mkdir(dirname(options.outputFile), { recursive: true });\n await writeFile(options.outputFile, source);\n\n return {\n routes,\n source,\n };\n}\n\nasync function findRouteFiles(directory: string) {\n const entries = await readdir(directory, {\n recursive: true,\n withFileTypes: true,\n });\n\n return entries\n .filter((entry) => entry.isFile() && /\\.tsx?$/.test(entry.name))\n .map((entry) => resolve(entry.parentPath, entry.name));\n}\n\nfunction toRouteInfo(routesDir: string, file: string) {\n const relativePath = relative(routesDir, file).split(sep).join(\"/\");\n const fileSegments = relativePath.replace(/\\.tsx?$/, \"\").split(\"/\");\n const basename = fileSegments.at(-1);\n\n if (basename?.startsWith(\"@\")) {\n return null;\n }\n\n const urlSegments = fileSegments.flatMap((segment) => {\n if (isRouteGroupSegment(segment)) {\n return [];\n }\n\n if (segment === \"index\") {\n return [];\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return [segment];\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return [segment];\n }\n\n return [segment];\n });\n\n const pathVars = fileSegments.flatMap((segment) => {\n if (isRouteGroupSegment(segment)) {\n return [];\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return [segment.slice(4, -1)];\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return [segment.slice(1, -1)];\n }\n\n return [];\n });\n\n return {\n pathVars,\n pattern: `/${urlSegments.join(\"/\")}`.replace(/\\/$/, \"\") || \"/\",\n };\n}\n\nfunction isRouteGroupSegment(segment: string) {\n return segment.startsWith(\"(\") && segment.endsWith(\")\");\n}\n\nfunction renderRoutesModule(routes: RouteInfo[]) {\n return `// Generated by Demiurge. Do not edit by hand.\nimport \"${PACKAGE_NAME}\";\nimport type { PathValue } from \"${PACKAGE_NAME}\";\n\ndeclare module \"${PACKAGE_NAME}\" {\n interface RoutePathVars {\n${routes.map(renderPathVarsEntry).join(\"\\n\")}\n }\n\n interface RouteConcretePaths {\n${routes.map(renderConcretePathEntry).join(\"\\n\")}\n }\n}\n\nexport {};\n`;\n}\n\nfunction renderPathVarsEntry(route: RouteInfo) {\n if (route.pathVars.length === 0) {\n return ` ${JSON.stringify(route.pattern)}: {};`;\n }\n\n const pathType = route.pathVars\n .map((name) => `${name}: PathValue`)\n .join(\"; \");\n\n return ` ${JSON.stringify(route.pattern)}: { ${pathType} };`;\n}\n\nfunction renderConcretePathEntry(route: RouteInfo) {\n return ` ${JSON.stringify(route.pattern)}: ${toConcretePathType(route.pattern)};`;\n}\n\nfunction toConcretePathType(pattern: string) {\n if (!pattern.includes(\"[\")) {\n return JSON.stringify(pattern);\n }\n\n const parts = pattern.split(/(\\[\\.\\.\\.[^\\]]+\\]|\\[[^\\]]+\\])/g).filter(Boolean);\n return `\\`${parts.map((part) => (part.startsWith(\"[\") ? \"${PathValue}\" : escapeTemplate(part))).join(\"\")}\\``;\n}\n\nfunction escapeTemplate(value: string) {\n return value.replace(/[`$\\\\]/g, \"\\\\$&\");\n}\n","import { existsSync } from \"node:fs\";\nimport type { IncomingMessage } from \"node:http\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { dirname, join, resolve, relative, sep } from \"node:path\";\nimport MagicString from \"magic-string\";\nimport {\n type ConfigEnv,\n parseAst,\n type Plugin,\n type UserConfig,\n type ViteDevServer,\n} from \"vite\";\nimport { renderDocument } from \"../document\";\nimport type {\n LinkTag,\n ResolvedMetadata,\n ScriptTag,\n} from \"../document\";\nimport { PACKAGE_NAME } from \"../package-name\";\nimport { generateRoutes } from \"../routing/generate\";\nimport {\n createRouteManifest,\n findRouteMatch,\n type RouteManifest,\n} from \"../router\";\nimport {\n handleRequestWithManifest,\n renderNotFoundResponse,\n renderPageDocument,\n type PageRenderer,\n} from \"../server\";\nimport {\n type RouteImporter,\n type RouteModule,\n} from \"../route\";\nimport {\n UnsupportedMethodError,\n toWebRequest,\n writeNotImplemented,\n writeWebResponse,\n} from \"../node/http\";\nimport { renderStreamingPageResponse } from \"../node/streaming\";\nimport { createCspNonce } from \"../security/policy\";\n\nexport type DemiurgeVitePluginOptions = {\n document?: {\n lang?: string;\n title?: string;\n };\n routesDir?: string;\n styles?: false | string;\n typedRoutes?: boolean | {\n outputFile?: string;\n };\n};\n\nconst CLIENT_ENTRY_ID = \"virtual:demiurge/client-entry\";\nconst DEV_CLIENT_ENTRY_PATH = `/@id/${CLIENT_ENTRY_ID}`;\nconst RESOLVED_CLIENT_ENTRY_ID = `\\0${CLIENT_ENTRY_ID}`;\nconst SERVER_ENTRY_ID = \"virtual:demiurge/server-entry\";\nconst RESOLVED_SERVER_ENTRY_ID = `\\0${SERVER_ENTRY_ID}`;\nconst DEFAULT_TYPED_ROUTES_OUTPUT = \".demiurge/route-manifest.d.ts\";\nexport function demiurge(options: DemiurgeVitePluginOptions = {}): Plugin {\n let root = process.cwd();\n let isBuild = false;\n const viteNoncePlaceholder = `demiurge-${createCspNonce()}`;\n\n return {\n enforce: \"post\",\n name: \"demiurge\",\n config(config, environment) {\n return createViteConfig(config, environment, viteNoncePlaceholder);\n },\n configResolved(config) {\n root = config.root;\n isBuild = config.command === \"build\";\n },\n resolveId(id) {\n if (id === CLIENT_ENTRY_ID) {\n return RESOLVED_CLIENT_ENTRY_ID;\n }\n\n if (id === SERVER_ENTRY_ID) {\n return RESOLVED_SERVER_ENTRY_ID;\n }\n\n return null;\n },\n load(id) {\n if (id === RESOLVED_CLIENT_ENTRY_ID) {\n return createClientEntrySource(root, options);\n }\n\n if (id === RESOLVED_SERVER_ENTRY_ID) {\n return createServerEntrySource(root, options);\n }\n\n return null;\n },\n transform: {\n order: \"post\",\n handler(code, id, transformOptions) {\n if (!isRouteSource(root, options, id)) {\n return null;\n }\n\n if (transformOptions?.ssr) {\n return isBuild ? null : protectSsrImportMeta(code, id);\n }\n\n const transformed = stripClientPageData(code);\n return transformed === code ? null : { code: transformed, map: null };\n },\n },\n generateBundle(_outputOptions, bundle) {\n const entry = Object.values(bundle).find(\n (item) =>\n item.type === \"chunk\" &&\n item.isEntry &&\n item.facadeModuleId === RESOLVED_CLIENT_ENTRY_ID,\n );\n\n if (!entry) {\n return;\n }\n\n const styles = Object.values(bundle)\n .filter(\n (asset): asset is Extract<(typeof bundle)[string], { type: \"asset\" }> =>\n asset.type === \"asset\" && asset.fileName.endsWith(\".css\"),\n )\n .map((asset) => `/${asset.fileName}`);\n const clientEntry = `/${entry.fileName}`;\n\n this.emitFile({\n fileName: \"index.html\",\n source: createDocumentHtml({\n entrySrc: clientEntry,\n lang: options.document?.lang,\n styles,\n title: options.document?.title,\n }),\n type: \"asset\",\n });\n this.emitFile({\n fileName: \"demiurge-manifest.json\",\n source: JSON.stringify({ clientEntry, styles }, null, 2),\n type: \"asset\",\n });\n },\n async buildStart() {\n if (isBuild) {\n await assertRootNotFoundRoute(root, options);\n }\n\n if (!options.typedRoutes) {\n return;\n }\n\n await generateTypedRoutes(root, options);\n },\n configureServer(server) {\n if (options.typedRoutes) {\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n\n void generateTypedRoutes(server.config.root, options);\n server.watcher.add(routesDir);\n server.watcher.on(\"add\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n }\n });\n server.watcher.on(\"change\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n }\n });\n server.watcher.on(\"unlink\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n }\n });\n }\n\n server.middlewares.use(async (request, response, next) => {\n try {\n let webRequest: Request;\n\n try {\n webRequest = toWebRequest(request, {\n // Vite performs its own configured host allowlist check before\n // Demiurge's middleware runs. Production Node listeners require\n // an explicit application allowlist instead.\n allowedHosts: [request.headers.host ?? \"localhost\"],\n });\n } catch (error) {\n if (error instanceof UnsupportedMethodError) {\n writeNotImplemented(response);\n return;\n }\n\n throw error;\n }\n\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n const manifest = await loadDevManifest(server, request, routesDir);\n const documentSecurity = createDevDocumentSecurity(\n server,\n viteNoncePlaceholder,\n );\n const result = await handleDevRequest(\n manifest,\n webRequest,\n createDevRuntimeOptions(options, documentSecurity.transform),\n );\n\n if (result === \"next\") {\n // Vite owns its own asset URLs, so an unmatched request still\n // falls through. The post middleware below is what turns whatever\n // Vite could not serve into the same negotiated not-found\n // production returns.\n next();\n return;\n }\n\n applyDevDocumentSecurity(result, documentSecurity.nonce);\n await writeWebResponse(response, result);\n } catch (error) {\n next(error);\n }\n });\n\n // The returned hook registers this after the Vite middleware. It sees\n // only requests that Vite cannot serve. `appType` is \"custom\", so no SPA\n // fallback intercepts these requests. Development and production render\n // the same negotiated not-found response for an unmatched path.\n return () => {\n server.middlewares.use(async (request, response, next) => {\n try {\n let webRequest: Request;\n\n try {\n webRequest = toWebRequest(request, {\n allowedHosts: [request.headers.host ?? \"localhost\"],\n });\n } catch (error) {\n if (error instanceof UnsupportedMethodError) {\n writeNotImplemented(response);\n return;\n }\n\n throw error;\n }\n\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n const manifest = await loadDevManifest(server, request, routesDir);\n\n warnMissingRootNotFound(manifest, routesDir);\n\n const documentSecurity = createDevDocumentSecurity(\n server,\n viteNoncePlaceholder,\n );\n const notFoundResponse = await renderNotFoundResponse(\n manifest,\n webRequest,\n createDevFallbackOptions(options, documentSecurity.transform),\n );\n applyDevDocumentSecurity(\n notFoundResponse,\n documentSecurity.nonce,\n );\n await writeWebResponse(response, notFoundResponse);\n } catch (error) {\n next(error);\n }\n });\n };\n },\n };\n}\n\ntype AstNode = {\n [key: string]: unknown;\n end: number;\n start: number;\n type: string;\n};\n\n// Vite 6 treats the `meta` token in `import.meta` as an imported reference.\n// Give an imported `meta` binding a private name before development SSR runs.\nfunction protectSsrImportMeta(code: string, id: string) {\n if (!code.includes(\"import.meta\")) {\n return null;\n }\n\n const ast = parseAst(code) as unknown as AstNode;\n const declaration = asNodeArray(ast.body).find((node) =>\n node.type === \"ImportDeclaration\" &&\n asNodeArray(node.specifiers).some((specifier) =>\n asNode(specifier.local)?.type === \"Identifier\" &&\n asNode(specifier.local)?.name === \"meta\"\n )\n );\n const specifier = declaration &&\n asNodeArray(declaration.specifiers).find((candidate) =>\n asNode(candidate.local)?.type === \"Identifier\" &&\n asNode(candidate.local)?.name === \"meta\"\n );\n const local = specifier && asNode(specifier.local);\n\n if (!declaration || !specifier || !local) {\n return null;\n }\n\n let alias = \"__demiurge_imported_meta__\";\n while (new RegExp(`\\\\b${alias}\\\\b`).test(code)) {\n alias += \"_\";\n }\n\n const editor = new MagicString(code);\n const imported = asNode(specifier.imported);\n editor.overwrite(\n local.start,\n local.end,\n imported?.start === local.start ? `meta as ${alias}` : alias,\n );\n editor.appendLeft(declaration.end, `\\nconst meta = ${alias};`);\n\n return {\n code: editor.toString(),\n map: editor.generateMap({\n hires: \"boundary\",\n includeContent: true,\n source: id,\n }),\n };\n}\n\n// Page data and document contributions are server capabilities. Vite and React\n// first parse TypeScript and JSX. The plugin then removes these capabilities\n// before Rollup follows the final client graph. This sequence excludes request\n// code and server-only imports from browser chunks. The exported document\n// bindings remain as `undefined` so the\n// route module keeps a stable shape without evaluating their initializers.\nexport function stripClientPageData(code: string) {\n const ast = parseAst(code) as unknown as AstNode;\n const dataRanges: Array<{ end: number; start: number }> = [];\n const documentRanges = findDocumentContributionRanges(ast);\n const serverImports: AstNode[] = [];\n\n walkAst(ast, (node) => {\n if (node.type === \"ImportDeclaration\" && isServerOnlyImport(node)) {\n serverImports.push(node);\n return;\n }\n\n if (node.type !== \"CallExpression\" || !isPageCallee(node.callee)) {\n return;\n }\n\n const argument = asNodeArray(node.arguments)[0];\n if (argument?.type !== \"ObjectExpression\") {\n return;\n }\n\n for (const property of asNodeArray(argument.properties)) {\n if (property.type === \"Property\" && propertyName(property.key) === \"data\") {\n dataRanges.push({ end: property.end, start: property.start });\n }\n }\n });\n\n const serverRanges = [...dataRanges, ...documentRanges];\n\n if (serverRanges.length === 0) {\n return code;\n }\n\n const removalRanges = [...serverRanges];\n for (const declaration of serverImports) {\n const localNames = asNodeArray(declaration.specifiers)\n .map((specifier) => asNode(specifier.local))\n .filter((local): local is AstNode => local?.type === \"Identifier\")\n .map((local) => String(local.name));\n const masked = maskRanges(code, [\n ...serverRanges,\n { end: declaration.end, start: declaration.start },\n ]);\n const leakedName = localNames.find((name) =>\n new RegExp(`\\\\b${escapeRegExp(name)}\\\\b`).test(masked)\n );\n\n if (leakedName) {\n throw new Error(\n `Server-only import ${JSON.stringify(leakedName)} is used by client route code. Move that use into page data, a document contribution, or a client-safe module.`,\n );\n }\n\n removalRanges.push({ end: declaration.end, start: declaration.start });\n }\n\n return replaceRanges(code, removalRanges, (range) =>\n dataRanges.includes(range) ? \"data: undefined\" :\n documentRanges.includes(range) ? \"undefined\" : \"\"\n );\n}\n\nconst documentContributionNames = new Set([\"links\", \"metadata\", \"scripts\"]);\n\nfunction findDocumentContributionRanges(ast: AstNode) {\n const exportedLocals = new Set<string>();\n\n for (const statement of asNodeArray(ast.body)) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n\n const declaration = asNode(statement.declaration);\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of asNodeArray(declaration.declarations)) {\n const id = asNode(declarator.id);\n if (\n id?.type === \"Identifier\" &&\n documentContributionNames.has(String(id.name))\n ) {\n exportedLocals.add(String(id.name));\n }\n }\n }\n\n for (const specifier of asNodeArray(statement.specifiers)) {\n const exported = propertyName(specifier.exported);\n const local = propertyName(specifier.local);\n if (exported && local && documentContributionNames.has(exported)) {\n exportedLocals.add(local);\n }\n }\n }\n\n const ranges: Array<{ end: number; start: number }> = [];\n walkAst(ast, (node) => {\n if (node.type !== \"VariableDeclarator\") return;\n const id = asNode(node.id);\n const init = asNode(node.init);\n if (\n id?.type === \"Identifier\" &&\n exportedLocals.has(String(id.name)) &&\n init\n ) {\n ranges.push({ end: init.end, start: init.start });\n }\n });\n\n return ranges;\n}\n\nfunction isRouteSource(\n root: string,\n options: DemiurgeVitePluginOptions,\n id: string,\n) {\n const file = id.split(\"?\", 1)[0] ?? id;\n const routesRoot = resolve(root, options.routesDir ?? \"src/routes\");\n const pathFromRoutes = relative(routesRoot, file);\n return pathFromRoutes !== \"\" &&\n pathFromRoutes !== \"..\" &&\n !pathFromRoutes.startsWith(`..${sep}`);\n}\n\nfunction walkAst(value: unknown, visit: (node: AstNode) => void) {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkAst(item, visit);\n return;\n }\n\n const node = value as Partial<AstNode>;\n if (typeof node.type !== \"string\") return;\n visit(node as AstNode);\n for (const [key, child] of Object.entries(node)) {\n if (!new Set([\"end\", \"loc\", \"start\", \"type\"]).has(key)) {\n walkAst(child, visit);\n }\n }\n}\n\nfunction asNode(value: unknown) {\n return value && typeof value === \"object\" && \"type\" in value\n ? value as AstNode\n : undefined;\n}\n\nfunction asNodeArray(value: unknown) {\n return Array.isArray(value)\n ? value.map(asNode).filter((node): node is AstNode => Boolean(node))\n : [];\n}\n\nfunction isPageCallee(value: unknown) {\n const callee = asNode(value);\n if (callee?.type === \"Identifier\") return callee.name === \"page\";\n return callee?.type === \"MemberExpression\" &&\n propertyName(callee.property) === \"page\";\n}\n\nfunction propertyName(value: unknown) {\n const property = asNode(value);\n return property?.type === \"Identifier\" || property?.type === \"Literal\"\n ? String(property.name ?? property.value)\n : undefined;\n}\n\nfunction isServerOnlyImport(node: AstNode) {\n const source = asNode(node.source)?.value;\n return typeof source === \"string\" &&\n /(?:^|[/.-])server(?:[/.-]|$)/.test(source);\n}\n\nfunction maskRanges(code: string, ranges: Array<{ end: number; start: number }>) {\n const characters = [...code];\n for (const { end, start } of ranges) {\n characters.fill(\" \", start, end);\n }\n return characters.join(\"\");\n}\n\nfunction replaceRanges(\n code: string,\n ranges: Array<{ end: number; start: number }>,\n replacement: (range: { end: number; start: number }) => string,\n) {\n return [...ranges]\n .sort((left, right) => right.start - left.start)\n .reduce(\n (result, range) =>\n `${result.slice(0, range.start)}${replacement(range)}${result.slice(range.end)}`,\n code,\n );\n}\n\nfunction escapeRegExp(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction createViteConfig(\n config: UserConfig,\n environment: ConfigEnv,\n viteNoncePlaceholder: string,\n): UserConfig {\n return {\n appType: \"custom\",\n build: {\n assetsInlineLimit: config.build?.assetsInlineLimit ?? 0,\n ...(environment.isSsrBuild &&\n config.build?.target === undefined &&\n config.ssr?.target !== \"webworker\"\n ? { target: \"node22.13\" }\n : {}),\n rollupOptions: {\n input: config.build?.rollupOptions?.input ?? CLIENT_ENTRY_ID,\n },\n },\n ...(environment.command === \"serve\"\n ? { html: { cspNonce: viteNoncePlaceholder } }\n : {}),\n };\n}\n\nexport function createClientEntrySource(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = options.routesDir ?? \"src/routes\";\n const stylesImport = createStylesImport(root, options);\n\n return `import { hydrateFileRouter } from \"${PACKAGE_NAME}\";\n${stylesImport}\n\n${createRouteMapSource(routesDir, {\n exportRoutes: false,\n includeServerOnly: false,\n })}\n\nvoid hydrateFileRouter({ routes });\n`;\n}\n\nexport function createServerEntrySource(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = options.routesDir ?? \"src/routes\";\n\n return `import { createRequestHandler } from \"${PACKAGE_NAME}\";\n\n${createRouteMapSource(routesDir, {\n exportRoutes: true,\n includeServerOnly: true,\n })}\n\nexport function createHandler(options = {}) {\n const { clientEntry, lang, styles, title, ...handlerOptions } = options;\n\n return createRequestHandler({\n ...handlerOptions,\n routes,\n ssr: {\n clientEntry,\n lang: lang ?? ${JSON.stringify(options.document?.lang)},\n styles,\n title: title ?? ${JSON.stringify(options.document?.title)},\n },\n });\n}\n`;\n}\n\n// Both virtual entries use this function. Therefore, their prefix removal and\n// route-key formats stay equal. The server entry requires framework-attached\n// `.ts` files such as `@policy.ts` and `@middleware.ts`. Previously, a\n// `.tsx`-only glob omitted these files from production. Development still found\n// and applied them.\nfunction createRouteMapSource(\n routesDir: string,\n {\n exportRoutes,\n includeServerOnly,\n }: { exportRoutes: boolean; includeServerOnly: boolean },\n) {\n const routesGlobs = toRootAbsoluteGlobs(routesDir, includeServerOnly);\n const routesPrefix = toRootAbsolutePrefix(routesDir);\n\n return `const routeModules = import.meta.glob(${JSON.stringify(routesGlobs)});\nconst routePrefix = ${JSON.stringify(routesPrefix)};\n${exportRoutes ? \"export \" : \"\"}const routes = Object.fromEntries(\n Object.entries(routeModules).map(([file, load]) => [\n \\`./routes/\\${file.slice(routePrefix.length)}\\`,\n load,\n ]),\n);`;\n}\n\n// These two files run only on the server. They control a request before the\n// route runs and do not render. A client glob would create public chunks in\n// `dist/client`. These chunks could expose credentials, authorization logic, or\n// internal host names from a middleware or policy closure.\nconst serverOnlyRouteFiles = [\"@middleware.ts\", \"@policy.ts\"];\n\nfunction toRootAbsoluteGlobs(routesDir: string, includeServerOnly: boolean) {\n const base = `/${routesDir.replace(/^\\/|\\/$/g, \"\")}`;\n const globs = [`${base}/**/*.{ts,tsx}`];\n\n if (!includeServerOnly) {\n globs.push(\n ...serverOnlyRouteFiles.flatMap((fileName) => [\n `!${base}/${fileName}`,\n `!${base}/**/${fileName}`,\n ]),\n );\n }\n\n return globs;\n}\n\nfunction toRootAbsolutePrefix(routesDir: string) {\n return `/${routesDir.replace(/^\\/|\\/$/g, \"\")}/`;\n}\n\nfunction createStylesImport(\n root: string,\n options: DemiurgeVitePluginOptions,\n) {\n if (options.styles === false) {\n return \"\";\n }\n\n const stylesFile = options.styles ?? \"src/styles.css\";\n const resolvedStylesFile = resolve(root, stylesFile);\n\n return existsSync(resolvedStylesFile)\n ? `import ${JSON.stringify(`/${stylesFile.replace(/^\\/+/, \"\")}`)};`\n : \"\";\n}\n\n// Development renders through the production pipeline. It adds the virtual\n// client entry, the Vite HTML transform, and a development flag for stack\n// traces. The shared handler makes all security and routing decisions.\nfunction createDevRuntimeOptions(\n options: DemiurgeVitePluginOptions,\n transformDocument: (html: string) => Promise<string>,\n) {\n return {\n dev: true,\n ssr: createDevSsrOptions(options),\n transformDocument,\n renderPage: async (\n match: Parameters<PageRenderer>[0],\n renderOptions: Parameters<PageRenderer>[1],\n ) => {\n if (match.render.mode === \"streaming\") {\n return await renderStreamingPageResponse(match, {\n ...renderOptions,\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n transformDocument,\n });\n }\n\n const html = await transformDocument(\n renderPageDocument(match, {\n ...renderOptions,\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n }),\n );\n\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n },\n };\n}\n\nfunction createDevDocumentSecurity(\n server: ViteDevServer,\n viteNoncePlaceholder: string,\n) {\n const nonce = createCspNonce();\n const shieldNonce = createCspNonce();\n\n return {\n nonce,\n transform: async (html: string) => {\n const shielded = shieldViteNonceTargets(html, shieldNonce);\n const transformed = await server.transformIndexHtml(\"/\", shielded);\n\n return replaceNonceAttribute(\n replaceNonceAttribute(transformed, shieldNonce),\n viteNoncePlaceholder,\n nonce,\n );\n },\n };\n}\n\nfunction shieldViteNonceTargets(html: string, nonce: string) {\n const lowerHtml = html.toLowerCase();\n let cursor = 0;\n let output = \"\";\n\n while (cursor < html.length) {\n const tagStart = html.indexOf(\"<\", cursor);\n\n if (tagStart === -1) {\n return output + html.slice(cursor);\n }\n\n output += html.slice(cursor, tagStart);\n\n if (lowerHtml.startsWith(\"<!--\", tagStart)) {\n const commentEnd = lowerHtml.indexOf(\"-->\", tagStart + 4);\n const end = commentEnd === -1 ? html.length : commentEnd + 3;\n output += html.slice(tagStart, end);\n cursor = end;\n continue;\n }\n\n const name = lowerHtml.slice(tagStart).match(/^<\\s*(script|style|link)\\b/)?.[1];\n\n if (!name) {\n output += \"<\";\n cursor = tagStart + 1;\n continue;\n }\n\n const tagEnd = findHtmlTagEnd(html, tagStart);\n\n if (tagEnd === -1) {\n return output + html.slice(tagStart);\n }\n\n const openingTag = html.slice(tagStart, tagEnd + 1);\n output += /(?:^|\\s)nonce(?:\\s|=|>)/i.test(openingTag)\n ? openingTag\n : addNonceAttribute(openingTag, nonce);\n cursor = tagEnd + 1;\n\n if (name === \"script\" || name === \"style\") {\n const closeStart = lowerHtml.indexOf(`</${name}`, cursor);\n\n if (closeStart === -1) {\n return output + html.slice(cursor);\n }\n\n output += html.slice(cursor, closeStart);\n cursor = closeStart;\n }\n }\n\n return output;\n}\n\nfunction findHtmlTagEnd(html: string, start: number) {\n let quote: \"\\\"\" | \"'\" | undefined;\n\n for (let index = start + 1; index < html.length; index++) {\n const character = html[index];\n\n if (quote) {\n if (character === quote) quote = undefined;\n continue;\n }\n\n if (character === \"\\\"\" || character === \"'\") {\n quote = character;\n } else if (character === \">\") {\n return index;\n }\n }\n\n return -1;\n}\n\nfunction addNonceAttribute(openingTag: string, nonce: string) {\n const insertion = /\\/\\s*>$/.test(openingTag)\n ? openingTag.lastIndexOf(\"/\")\n : openingTag.length - 1;\n\n return `${openingTag.slice(0, insertion)} nonce=\"${nonce}\"${openingTag.slice(insertion)}`;\n}\n\nfunction replaceNonceAttribute(\n html: string,\n current: string,\n replacement?: string,\n) {\n const pattern = new RegExp(\n `(\\\\snonce\\\\s*=\\\\s*)([\"'])${escapeRegExp(current)}\\\\2`,\n \"g\",\n );\n\n return html.replace(\n pattern,\n replacement ? `$1\"${replacement}\"` : \"\",\n );\n}\n\nfunction applyDevDocumentSecurity(response: Response, nonce: string) {\n const contentType = response.headers.get(\"content-type\");\n const csp = response.headers.get(\"content-security-policy\");\n\n if (!contentType?.toLowerCase().startsWith(\"text/html\") || !csp) {\n return;\n }\n\n const source = `'nonce-${nonce}'`;\n const withScriptNonce = addCspSource(\n csp,\n [\"script-src-elem\", \"script-src\"],\n \"script-src\",\n source,\n );\n const withStyleNonce = allowsUnsafeInline(\n withScriptNonce,\n [\"style-src-elem\", \"style-src\"],\n )\n ? withScriptNonce\n : addCspSource(\n withScriptNonce,\n [\"style-src-elem\", \"style-src\"],\n \"style-src\",\n source,\n );\n\n response.headers.set(\"content-security-policy\", withStyleNonce);\n response.headers.set(\"cache-control\", \"private, no-store\");\n}\n\nfunction addCspSource(\n csp: string,\n directiveNames: readonly string[],\n fallbackDirectiveName: \"script-src\" | \"style-src\",\n source: string,\n) {\n const directives = csp.split(\";\").map((directive) => directive.trim());\n const directiveIndex = findCspDirectiveIndex(directives, directiveNames);\n\n const defaultDirective = directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n );\n\n if (directiveIndex === -1 && !defaultDirective) return csp;\n\n const [currentName, ...currentSources] =\n (directiveIndex === -1 ? defaultDirective! : directives[directiveIndex]!)\n .split(/\\s+/);\n const updatedDirective = [\n directiveIndex === -1 ? fallbackDirectiveName : currentName!,\n ...new Set([\n ...currentSources.filter((current) => current !== \"'none'\"),\n source,\n ]),\n ].join(\" \");\n\n if (directiveIndex === -1) {\n directives.push(updatedDirective);\n } else {\n directives[directiveIndex] = updatedDirective;\n }\n\n return directives.join(\"; \");\n}\n\nfunction allowsUnsafeInline(\n csp: string,\n directiveNames: readonly string[],\n) {\n const directives = csp.split(\";\").map((directive) => directive.trim());\n const directiveIndex = findCspDirectiveIndex(directives, directiveNames);\n const effectiveDirective = directiveIndex === -1\n ? directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n )\n : directives[directiveIndex];\n const sources = effectiveDirective?.split(/\\s+/).slice(1) ?? [];\n\n return sources.includes(\"'unsafe-inline'\") &&\n !sources.some((source) => /^'(?:nonce-|sha(?:256|384|512)-)/i.test(source));\n}\n\nfunction findCspDirectiveIndex(\n directives: readonly string[],\n directiveNames: readonly string[],\n) {\n for (const name of directiveNames) {\n const index = directives.findIndex((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === name\n );\n\n if (index !== -1) return index;\n }\n\n return -1;\n}\n\n// Both dev middlewares need the manifest for the same request, and building\n// it walks the routes directory. The pre middleware always runs, so the post\n// middleware reuses what it already produced rather than scanning twice on\n// every unmatched request.\nconst DEV_MANIFEST = Symbol.for(\"demiurge.devManifest\");\n\ntype DevManifestCarrier = { [DEV_MANIFEST]?: RouteManifest };\n\nasync function loadDevManifest(\n server: ViteDevServer,\n request: IncomingMessage,\n routesDir: string,\n) {\n const carrier = request as IncomingMessage & DevManifestCarrier;\n const cached = carrier[DEV_MANIFEST];\n\n if (cached) {\n return cached;\n }\n\n const manifest = createRouteManifest(\n await createDevRouteImporters(server, routesDir),\n );\n\n carrier[DEV_MANIFEST] = manifest;\n\n return manifest;\n}\n\nfunction createDevSsrOptions(options: DemiurgeVitePluginOptions) {\n return {\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n lang: options.document?.lang,\n title: options.document?.title,\n };\n}\n\nfunction createDevFallbackOptions(\n options: DemiurgeVitePluginOptions,\n transformDocument: (html: string) => Promise<string>,\n) {\n return {\n ...createDevSsrOptions(options),\n dev: true,\n transformDocument,\n };\n}\n\nconst warnedRoots = new Set<string>();\n\n// The framework built-in is a temporary fallback, not a production 404. The\n// build gate enforces this rule. This warning gives the same message earlier.\nfunction warnMissingRootNotFound(manifest: RouteManifest, routesDir: string) {\n if (\n warnedRoots.has(routesDir) ||\n manifest.fallbacks.notFound.some(\n (fallback) => fallback.fileSegments.length === 0,\n )\n ) {\n return;\n }\n\n warnedRoots.add(routesDir);\n console.warn(missingRootNotFoundMessage(join(routesDir, \"@not-found.tsx\")));\n}\n\n// The framework ships a working 404 so nothing is ever blank, and refuses to\n// let an app reach production still rendering it. A generic framework page in\n// front of real users is a failure of the framework, not of the app that never\n// got around to it.\nexport async function assertRootNotFoundRoute(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDirOption = options.routesDir ?? \"src/routes\";\n const routesDir = resolve(root, routesDirOption);\n\n if (!existsSync(routesDir)) {\n return;\n }\n\n const files = await findRouteFiles(routesDir);\n const names = files.map((file) =>\n relative(routesDir, file).split(sep).join(\"/\"),\n );\n\n if (names.some((name) => /^@not-found\\.tsx?$/.test(name))) {\n return;\n }\n\n const pageRoute = await findPageRouteFile(files);\n\n // An API-only app never wants an HTML not-found document, and nagging it\n // would be user hostile. It builds clean and gets problem+json.\n if (!pageRoute) {\n return;\n }\n\n throw new Error(\n missingRootNotFoundBuildMessage(\n routesDirOption,\n relative(routesDir, pageRoute).split(sep).join(\"/\"),\n ),\n );\n}\n\n// Page detection is a source scan rather than a module evaluation: the plugin\n// cannot execute route modules at build time. A page route is a file that\n// calls `page(...)`, which is the only way to declare one.\nasync function findPageRouteFile(files: string[]) {\n for (const file of files) {\n // Framework-attached files own no address, so they are never page routes.\n if (relative(dirname(file), file).startsWith(\"@\")) {\n continue;\n }\n\n if (declaresPageRoute(await readFile(file, \"utf8\"))) {\n return file;\n }\n }\n\n return undefined;\n}\n\n// Escaped because a package name may contain `.`, which the regex would\n// otherwise read as a wildcard.\nconst PACKAGE_NAME_PATTERN = PACKAGE_NAME.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst DEMIURGE_NAMED_IMPORT = new RegExp(\n `import\\\\s*\\\\{([^}]*)\\\\}\\\\s*from\\\\s*[\"']${PACKAGE_NAME_PATTERN}[\"']`,\n \"g\",\n);\n\n// The plugin cannot evaluate route modules during the build. Therefore, page\n// detection reads the source. It checks the import, not only the word. An API\n// application can call `db.users.page(2)` without serving an HTML document.\n// Only a page route imports `page` from the framework package.\nexport function declaresPageRoute(source: string) {\n const locals = [...source.matchAll(DEMIURGE_NAMED_IMPORT)].flatMap((match) =>\n match[1].split(\",\").flatMap((binding) => {\n const [imported, local] = binding.trim().split(/\\s+as\\s+/);\n\n // `import type { page }` cannot be called, and an alias renames what the\n // call site looks like.\n return imported.replace(/^type\\s+/, \"\") === \"page\"\n ? [local ?? imported]\n : [];\n }),\n );\n\n if (locals.length === 0) {\n return false;\n }\n\n // Strip the import statements first so the binding list is not itself\n // mistaken for a call.\n const body = source.replace(DEMIURGE_NAMED_IMPORT, \"\");\n\n return locals.some((local) => new RegExp(`\\\\b${local}\\\\s*\\\\(`).test(body));\n}\n\nexport function missingRootNotFoundBuildMessage(\n routesDir: string,\n pageRoute: string,\n) {\n return `Demiurge will not build an app with page routes and no ${routesDir}/@not-found.tsx.\n\n\"${pageRoute}\" declares a page, so a browser can reach a path this app does not serve. Decide what that looks like rather than shipping the framework built-in.\n\nCreate ${routesDir}/@not-found.tsx:\n\n export default function NotFound({ pathname }: { pathname: string }) {\n return <h1>Nothing at {pathname}</h1>;\n }\n\nIt renders inside the layouts above the requested path. Opt out with \"export const layout = false\".`;\n}\n\nexport function missingRootNotFoundMessage(notFoundFile: string) {\n return `Demiurge is serving its built-in 404 because ${notFoundFile} does not exist.\n\nCreate it before building for production:\n\n export default function NotFound({ pathname }: { pathname: string }) {\n return <h1>Nothing at {pathname}</h1>;\n }\n`;\n}\n\nexport function createDocumentHtml({\n entrySrc,\n lang,\n links,\n metadata,\n nonce,\n scripts,\n styles,\n title,\n}: {\n entrySrc: string;\n lang?: string;\n links?: LinkTag[];\n metadata?: ResolvedMetadata;\n nonce?: string;\n scripts?: ScriptTag[];\n styles?: string[];\n title?: string;\n}) {\n return renderDocument({\n entrySrc,\n lang,\n links,\n metadata,\n nonce,\n scripts,\n styles,\n title,\n });\n}\n\nasync function generateTypedRoutes(\n root: string,\n options: DemiurgeVitePluginOptions,\n) {\n const routesDir = resolve(root, options.routesDir ?? \"src/routes\");\n const outputFile = resolve(\n root,\n typeof options.typedRoutes === \"object\"\n ? options.typedRoutes.outputFile ?? DEFAULT_TYPED_ROUTES_OUTPUT\n : DEFAULT_TYPED_ROUTES_OUTPUT,\n );\n\n await generateRoutes({ outputFile, routesDir });\n}\n\nfunction isRouteFile(routesDir: string, file: string) {\n return (\n file.startsWith(routesDir) &&\n /\\.tsx?$/.test(file)\n );\n}\n\nexport async function createDevRouteImporters(\n server: ViteDevServer,\n routesDir: string,\n) {\n const files = await findRouteFiles(routesDir);\n const routes: Record<string, RouteImporter> = {};\n\n for (const file of files) {\n const routeKey = toRouteKey(routesDir, file);\n routes[routeKey] = async () =>\n (await server.ssrLoadModule(file)) as RouteModule;\n }\n\n return routes;\n}\n\nexport async function handleDevRequest(\n manifest: RouteManifest,\n request: Request,\n options: Parameters<typeof handleRequestWithManifest>[2] = {},\n) {\n const url = new URL(request.url);\n const routeMatch = findRouteMatch(manifest.routes, url.pathname);\n\n if (!routeMatch) {\n return \"next\" as const;\n }\n\n return await handleRequestWithManifest(manifest, request, options);\n}\n\nasync function findRouteFiles(directory: string) {\n const entries = await readdir(directory, {\n recursive: true,\n withFileTypes: true,\n });\n\n return entries\n .filter((entry) => entry.isFile() && /\\.tsx?$/.test(entry.name))\n .map((entry) => resolve(entry.parentPath, entry.name));\n}\n\nfunction toRouteKey(routesDir: string, file: string) {\n const relativePath = relative(routesDir, file).split(sep).join(\"/\");\n return `./routes/${relativePath}`;\n}\n"],"names":["PACKAGE_NAME","generateRoutes","options","routes","findRouteFiles","file","toRouteInfo","route","a","b","source","renderRoutesModule","mkdir","dirname","writeFile","directory","readdir","entry","resolve","routesDir","fileSegments","relative","sep","urlSegments","segment","isRouteGroupSegment","renderPathVarsEntry","renderConcretePathEntry","pathType","name","toConcretePathType","pattern","part","escapeTemplate","value","CLIENT_ENTRY_ID","DEV_CLIENT_ENTRY_PATH","RESOLVED_CLIENT_ENTRY_ID","SERVER_ENTRY_ID","RESOLVED_SERVER_ENTRY_ID","DEFAULT_TYPED_ROUTES_OUTPUT","demiurge","root","isBuild","viteNoncePlaceholder","createCspNonce","config","environment","createViteConfig","id","createClientEntrySource","createServerEntrySource","code","transformOptions","isRouteSource","protectSsrImportMeta","transformed","stripClientPageData","_outputOptions","bundle","item","styles","asset","clientEntry","createDocumentHtml","assertRootNotFoundRoute","generateTypedRoutes","server","isRouteFile","request","response","next","webRequest","toWebRequest","error","UnsupportedMethodError","writeNotImplemented","manifest","loadDevManifest","documentSecurity","createDevDocumentSecurity","result","handleDevRequest","createDevRuntimeOptions","applyDevDocumentSecurity","writeWebResponse","warnMissingRootNotFound","notFoundResponse","renderNotFoundResponse","createDevFallbackOptions","ast","parseAst","declaration","asNodeArray","node","specifier","asNode","candidate","local","alias","editor","MagicString","imported","dataRanges","documentRanges","findDocumentContributionRanges","serverImports","walkAst","isServerOnlyImport","isPageCallee","argument","property","propertyName","serverRanges","removalRanges","localNames","masked","maskRanges","leakedName","escapeRegExp","replaceRanges","range","documentContributionNames","exportedLocals","statement","declarator","exported","ranges","init","routesRoot","pathFromRoutes","visit","key","child","callee","characters","end","start","replacement","left","right","stylesImport","createStylesImport","createRouteMapSource","exportRoutes","includeServerOnly","routesGlobs","toRootAbsoluteGlobs","routesPrefix","toRootAbsolutePrefix","serverOnlyRouteFiles","base","globs","fileName","stylesFile","resolvedStylesFile","existsSync","transformDocument","createDevSsrOptions","match","renderOptions","renderStreamingPageResponse","html","renderPageDocument","nonce","shieldNonce","shielded","shieldViteNonceTargets","replaceNonceAttribute","lowerHtml","cursor","output","tagStart","commentEnd","tagEnd","findHtmlTagEnd","openingTag","addNonceAttribute","closeStart","quote","index","character","insertion","current","contentType","csp","withScriptNonce","addCspSource","withStyleNonce","allowsUnsafeInline","directiveNames","fallbackDirectiveName","directives","directive","directiveIndex","findCspDirectiveIndex","defaultDirective","currentName","currentSources","updatedDirective","sources","DEV_MANIFEST","carrier","cached","createRouteManifest","createDevRouteImporters","warnedRoots","fallback","missingRootNotFoundMessage","join","routesDirOption","files","pageRoute","findPageRouteFile","missingRootNotFoundBuildMessage","declaresPageRoute","readFile","PACKAGE_NAME_PATTERN","DEMIURGE_NAMED_IMPORT","locals","binding","body","notFoundFile","entrySrc","lang","links","metadata","scripts","title","renderDocument","outputFile","routeKey","toRouteKey","url","findRouteMatch","handleRequestWithManifest"],"mappings":";;;;;;;;;;;AASO,MAAMA,IAAe;ACK5B,eAAsBC,GAAeC,GAAgC;AAEnE,QAAMC,KADa,MAAMC,GAAeF,EAAQ,SAAS,GAEtD,IAAI,CAACG,MAASC,GAAYJ,EAAQ,WAAWG,CAAI,CAAC,EAClD,OAAO,CAACE,MAA8B,EAAQA,CAAM,EACpD,KAAK,CAACC,GAAGC,MAAMD,EAAE,QAAQ,cAAcC,EAAE,OAAO,CAAC,GAE9CC,IAASC,GAAmBR,CAAM;AAExC,eAAMS,GAAMC,EAAQX,EAAQ,UAAU,GAAG,EAAE,WAAW,IAAM,GAC5D,MAAMY,GAAUZ,EAAQ,YAAYQ,CAAM,GAEnC;AAAA,IACL,QAAAP;AAAA,IACA,QAAAO;AAAA,EAAA;AAEJ;AAEA,eAAeN,GAAeW,GAAmB;AAM/C,UALgB,MAAMC,EAAQD,GAAW;AAAA,IACvC,WAAW;AAAA,IACX,eAAe;AAAA,EAAA,CAChB,GAGE,OAAO,CAACE,MAAUA,EAAM,OAAA,KAAY,UAAU,KAAKA,EAAM,IAAI,CAAC,EAC9D,IAAI,CAACA,MAAUC,EAAQD,EAAM,YAAYA,EAAM,IAAI,CAAC;AACzD;AAEA,SAASX,GAAYa,GAAmBd,GAAc;AAEpD,QAAMe,IADeC,EAASF,GAAWd,CAAI,EAAE,MAAMiB,CAAG,EAAE,KAAK,GAAG,EA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/routing/generate.ts","../../src/vite/policy-verification.ts","../../src/vite/plugin.ts"],"sourcesContent":["// The package name is the specifier that user code imports. Generated client\n// entries, server entries, and route type declarations use it. Page route\n// detection also compares application source with it. A mismatch then breaks\n// resolution in the consumer build.\n//\n// This is deliberately not the same thing as the many internal `demiurge`\n// strings elsewhere in the source. `__demiurge_data`, `virtual:demiurge/*`,\n// `demiurge-manifest.json`, and friends name the framework, not the package,\n// and they stay put if the registry name ever changes.\nexport const PACKAGE_NAME = \"@demiurgejs/core\";\n","import { mkdir, readdir, writeFile } from \"node:fs/promises\";\nimport { dirname, relative, resolve, sep } from \"node:path\";\nimport { PACKAGE_NAME } from \"../package-name\";\n\nexport type GenerateRoutesOptions = {\n outputFile: string;\n routesDir: string;\n};\n\ntype RouteInfo = {\n contextMiddleware: number[];\n fileSegments: string[];\n pathVars: string[];\n pattern: string;\n};\n\ntype MiddlewareInfo = {\n file: string;\n fileSegments: string[];\n importPath: string;\n};\n\nexport async function generateRoutes(options: GenerateRoutesOptions) {\n const routeFiles = await findRouteFiles(options.routesDir);\n const middleware = routeFiles\n .map((file) => toMiddlewareInfo(options, file))\n .filter((value): value is MiddlewareInfo => Boolean(value));\n const routes = routeFiles\n .map((file) => toRouteInfo(options.routesDir, file, middleware))\n .filter((route): route is RouteInfo => Boolean(route))\n .sort((a, b) => a.pattern.localeCompare(b.pattern));\n\n const source = renderRoutesModule(routes, middleware);\n\n await mkdir(dirname(options.outputFile), { recursive: true });\n await writeFile(options.outputFile, source);\n\n return {\n routes,\n source,\n };\n}\n\nasync function findRouteFiles(directory: string) {\n const entries = await readdir(directory, {\n recursive: true,\n withFileTypes: true,\n });\n\n return entries\n .filter((entry) => entry.isFile() && /\\.tsx?$/.test(entry.name))\n .map((entry) => resolve(entry.parentPath, entry.name));\n}\n\nfunction toRouteInfo(\n routesDir: string,\n file: string,\n middleware: MiddlewareInfo[],\n) {\n const relativePath = relative(routesDir, file).split(sep).join(\"/\");\n const fileSegments = relativePath.replace(/\\.tsx?$/, \"\").split(\"/\");\n const basename = fileSegments.at(-1);\n\n if (basename?.startsWith(\"@\")) {\n return null;\n }\n\n const urlSegments = fileSegments.flatMap((segment) => {\n if (isRouteGroupSegment(segment)) {\n return [];\n }\n\n if (segment === \"index\") {\n return [];\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return [segment];\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return [segment];\n }\n\n return [segment];\n });\n\n const pathVars = fileSegments.flatMap((segment) => {\n if (isRouteGroupSegment(segment)) {\n return [];\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return [segment.slice(4, -1)];\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return [segment.slice(1, -1)];\n }\n\n return [];\n });\n\n return {\n contextMiddleware: middleware\n .filter((entry) => isAttachedFileForRoute(entry.fileSegments, fileSegments))\n .map((entry) => middleware.indexOf(entry)),\n fileSegments,\n pathVars,\n pattern: `/${urlSegments.join(\"/\")}`.replace(/\\/$/, \"\") || \"/\",\n };\n}\n\nfunction toMiddlewareInfo(\n options: GenerateRoutesOptions,\n file: string,\n): MiddlewareInfo | null {\n const relativePath = relative(options.routesDir, file).split(sep).join(\"/\");\n const fileSegments = relativePath.replace(/\\.tsx?$/, \"\").split(\"/\");\n\n if (fileSegments.at(-1) !== \"@middleware\") {\n return null;\n }\n\n let importPath = relative(dirname(options.outputFile), file)\n .split(sep)\n .join(\"/\")\n .replace(/\\.tsx?$/, \"\");\n\n if (!importPath.startsWith(\".\")) {\n importPath = `./${importPath}`;\n }\n\n return { file, fileSegments: fileSegments.slice(0, -1), importPath };\n}\n\nfunction isAttachedFileForRoute(\n attachedFileSegments: string[],\n routeFileSegments: string[],\n) {\n return attachedFileSegments.every(\n (segment, index) => routeFileSegments[index] === segment,\n );\n}\n\nfunction isRouteGroupSegment(segment: string) {\n return segment.startsWith(\"(\") && segment.endsWith(\")\");\n}\n\nfunction renderRoutesModule(routes: RouteInfo[], middleware: MiddlewareInfo[]) {\n return `// Generated by Demiurge. Do not edit by hand.\nimport \"${PACKAGE_NAME}\";\nimport type { MiddlewareContextOf, PathValue } from \"${PACKAGE_NAME}\";\n${middleware.map(renderMiddlewareImport).join(\"\\n\")}\n\n${middleware.map((_entry, index) => renderMiddlewareContextAlias(index)).join(\"\\n\")}\n\ndeclare module \"${PACKAGE_NAME}\" {\n interface RoutePathVars {\n${routes.map(renderPathVarsEntry).join(\"\\n\")}\n }\n\n interface RouteConcretePaths {\n${routes.map(renderConcretePathEntry).join(\"\\n\")}\n }\n\n interface RouteRequestContexts {\n${routes.map(renderRequestContextEntry).join(\"\\n\")}\n }\n}\n\nexport {};\n`;\n}\n\nfunction renderMiddlewareImport(entry: MiddlewareInfo, index: number) {\n return `type __DemiurgeMiddleware${index} = typeof import(${JSON.stringify(entry.importPath)}) extends { middleware?: infer T } ? T : never;`;\n}\n\nfunction renderMiddlewareContextAlias(index: number) {\n return `type __DemiurgeMiddlewareContext${index} = MiddlewareContextOf<__DemiurgeMiddleware${index}>;`;\n}\n\nfunction renderPathVarsEntry(route: RouteInfo) {\n if (route.pathVars.length === 0) {\n return ` ${JSON.stringify(route.pattern)}: {};`;\n }\n\n const pathType = route.pathVars\n .map((name) => `${name}: PathValue`)\n .join(\"; \");\n\n return ` ${JSON.stringify(route.pattern)}: { ${pathType} };`;\n}\n\nfunction renderConcretePathEntry(route: RouteInfo) {\n return ` ${JSON.stringify(route.pattern)}: ${toConcretePathType(route.pattern)};`;\n}\n\nfunction renderRequestContextEntry(route: RouteInfo) {\n const contexts = route.contextMiddleware\n .map((index) => `__DemiurgeMiddlewareContext${index}`);\n const context = contexts.length > 0\n ? contexts.join(\" & \")\n : \"Record<never, never>\";\n\n return ` ${JSON.stringify(route.pattern)}: ${context};`;\n}\n\nfunction toConcretePathType(pattern: string) {\n if (!pattern.includes(\"[\")) {\n return JSON.stringify(pattern);\n }\n\n const parts = pattern.split(/(\\[\\.\\.\\.[^\\]]+\\]|\\[[^\\]]+\\])/g).filter(Boolean);\n return `\\`${parts.map((part) => (part.startsWith(\"[\") ? \"${PathValue}\" : escapeTemplate(part))).join(\"\")}\\``;\n}\n\nfunction escapeTemplate(value: string) {\n return value.replace(/[`$\\\\]/g, \"\\\\$&\");\n}\n","import { readFile } from \"node:fs/promises\";\nimport { parseAst, transformWithEsbuild } from \"vite\";\nimport type { HttpMethod } from \"../route\";\nimport {\n createSecurityHeaders,\n security,\n validateCorsPolicy,\n validateRateLimitPolicy,\n type ContentSecurityPolicy,\n type CorsPolicy,\n type RoutePolicy,\n type RouteSecurityPolicy,\n type SecurityPolicy,\n} from \"../security\";\n\ntype AstNode = {\n [key: string]: unknown;\n end: number;\n start: number;\n type: string;\n};\n\nexport type StaticPolicyFinding = {\n code: \"cors-invalid\" | \"cors-method-unavailable\" | \"rate-limit-invalid\" |\n \"security-header-render-failed\";\n exportName?: string;\n file: string;\n message: string;\n severity: \"error\";\n};\n\ntype ExtractedCapability = {\n cors?: CorsPolicy;\n security?: RouteSecurityPolicy;\n};\n\ntype ExtractedRouteModule = {\n capabilities: Partial<Record<HttpMethod, ExtractedCapability>>;\n declaredMethods: Set<HttpMethod>;\n policy?: RoutePolicy;\n};\n\nconst httpMethods = [\n \"GET\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"OPTIONS\",\n \"HEAD\",\n] as const satisfies readonly HttpMethod[];\nconst responseHelpers = new Set([\n \"action\",\n \"html\",\n \"json\",\n \"jsonl\",\n \"notFound\",\n \"redirect\",\n \"response\",\n \"sse\",\n \"stream\",\n \"text\",\n]);\n\nexport async function verifyRoutePolicyFile(file: string) {\n const source = await readFile(file, \"utf8\");\n return await verifyRoutePolicySource(source, file);\n}\n\nexport async function verifyRoutePolicySource(source: string, file: string) {\n const loader = file.endsWith(\".tsx\") ? \"tsx\" : \"ts\";\n const transformed = await transformWithEsbuild(source, file, {\n format: \"esm\",\n loader,\n target: \"esnext\",\n });\n const extracted = extractRouteModule(transformed.code);\n\n return validateExtractedRouteModule(extracted, file);\n}\n\nfunction extractRouteModule(code: string): ExtractedRouteModule {\n const ast = parseAst(code) as unknown as AstNode;\n const imports = collectCoreImports(ast);\n const constants = collectConstants(ast);\n const declarations = collectVariableInitializers(ast);\n const exports = collectNamedExports(ast);\n const capabilities: ExtractedRouteModule[\"capabilities\"] = {};\n const declaredMethods = new Set<HttpMethod>();\n let policy: RoutePolicy | undefined;\n\n for (const [exportName, localName] of exports) {\n const initializer = declarations.get(localName);\n\n if (exportName === \"policy\") {\n if (initializer) {\n policy = extractRoutePolicy(initializer, imports, constants);\n }\n continue;\n }\n if (!isHttpMethod(exportName)) continue;\n declaredMethods.add(exportName);\n if (!initializer) continue;\n\n const capability = extractCapability(initializer, imports, constants);\n if (capability) capabilities[exportName] = capability;\n }\n\n return { capabilities, declaredMethods, policy };\n}\n\nfunction collectVariableInitializers(ast: AstNode) {\n const declarations = new Map<string, AstNode>();\n for (const statement of asNodeArray(ast.body)) {\n const declaration = statement.type === \"ExportNamedDeclaration\"\n ? asNode(statement.declaration)\n : statement;\n if (declaration?.type !== \"VariableDeclaration\") continue;\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n const initializer = asNode(declarator.init);\n if (name && initializer) declarations.set(name, initializer);\n }\n }\n return declarations;\n}\n\nfunction collectNamedExports(ast: AstNode) {\n const exports = new Map<string, string>();\n for (const statement of asNodeArray(ast.body)) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n const declaration = asNode(statement.declaration);\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n if (name) exports.set(name, name);\n }\n }\n for (const specifier of asNodeArray(statement.specifiers)) {\n const exported = propertyName(specifier.exported);\n const local = propertyName(specifier.local);\n if (exported && local) exports.set(exported, local);\n }\n }\n return exports;\n}\n\nfunction extractCapability(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n) {\n if (node.type !== \"CallExpression\") return undefined;\n const localName = identifierName(node.callee);\n const helper = localName ? imports.get(localName) : undefined;\n\n if (!helper || !responseHelpers.has(helper)) return undefined;\n const arguments_ = asNodeArray(node.arguments);\n const optionsNode = helper === \"action\" ? arguments_[0] : arguments_[1];\n if (!optionsNode) return {};\n const cors = evaluateObjectProperty(optionsNode, \"cors\", constants);\n const securityPolicy = evaluateObjectProperty(\n optionsNode,\n \"security\",\n constants,\n );\n\n return {\n cors: isRecord(cors) ? cors as CorsPolicy : undefined,\n security: isRecord(securityPolicy)\n ? securityPolicy as RouteSecurityPolicy\n : undefined,\n } satisfies ExtractedCapability;\n}\n\nfunction evaluateObjectProperty(\n node: AstNode,\n property: string,\n constants: Map<string, unknown>,\n) {\n if (node.type === \"Identifier\") {\n const value = constants.get(String(node.name));\n return isRecord(value) ? value[property] : unresolved;\n }\n if (node.type !== \"ObjectExpression\") return unresolved;\n\n let value: unknown = undefined;\n for (const item of asNodeArray(node.properties)) {\n if (item.type !== \"Property\" || item.computed) return unresolved;\n if (propertyName(item.key) !== property) continue;\n value = evaluateLiteral(asNode(item.value), constants);\n }\n\n return value;\n}\n\nfunction extractRoutePolicy(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n): RoutePolicy | undefined {\n if (node.type === \"CallExpression\") {\n const localName = identifierName(node.callee);\n if (localName && imports.get(localName) === \"defineRoutePolicy\") {\n const argument = asNodeArray(node.arguments)[0];\n return argument\n ? extractRoutePolicy(argument, imports, constants)\n : undefined;\n }\n }\n\n if (node.type !== \"ObjectExpression\") {\n const value = evaluateLiteral(node, constants);\n return isRecord(value) ? value as RoutePolicy : undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const property of asNodeArray(node.properties)) {\n if (property.type !== \"Property\" || property.computed) return undefined;\n const name = propertyName(property.key);\n const valueNode = asNode(property.value);\n if (!name || !valueNode) return undefined;\n\n if (name === \"document\") {\n const document = extractSecurityPolicy(valueNode, imports, constants);\n if (!document) return undefined;\n result.document = document;\n continue;\n }\n\n const value = evaluateLiteral(valueNode, constants);\n if (value === unresolved) return undefined;\n result[name] = value;\n }\n\n return result as RoutePolicy;\n}\n\nfunction extractSecurityPolicy(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n): SecurityPolicy | undefined {\n if (node.type !== \"CallExpression\") {\n const value = evaluateLiteral(node, constants);\n return isRecord(value) ? value as SecurityPolicy : undefined;\n }\n\n const callee = asNode(node.callee);\n if (callee?.type !== \"MemberExpression\") return undefined;\n const objectName = identifierName(callee.object);\n const preset = propertyName(callee.property);\n if (!objectName || imports.get(objectName) !== \"security\" || !preset) {\n return undefined;\n }\n\n const options = evaluateLiteral(asNodeArray(node.arguments)[0], constants);\n if (options !== unresolved && options !== undefined && !isRecord(options)) {\n return undefined;\n }\n\n if (preset === \"api\") return security.api(options as never);\n if (preset === \"crossOriginIsolated\") {\n return security.crossOriginIsolated(options as never);\n }\n if (preset === \"static\") return security.static(options as never);\n if (preset === \"strict\") return security.strict(options as never);\n return undefined;\n}\n\nfunction validateExtractedRouteModule(\n routeModule: ExtractedRouteModule,\n file: string,\n) {\n const findings: StaticPolicyFinding[] = [];\n const availableMethods = new Set(routeModule.declaredMethods);\n if (availableMethods.has(\"GET\")) availableMethods.add(\"HEAD\");\n // Demiurge answers preflight itself, so a route never exports an OPTIONS\n // capability to serve one. Listing OPTIONS is a habit carried in from other\n // CORS configuration, and rejecting it would fail a build over nothing.\n availableMethods.add(\"OPTIONS\");\n\n for (const [exportName, capability] of Object.entries(\n routeModule.capabilities,\n ) as Array<[HttpMethod, ExtractedCapability]>) {\n if (capability.cors) {\n try {\n validateCorsPolicy(capability.cors);\n } catch (error) {\n findings.push(finding(\n \"cors-invalid\",\n file,\n errorMessage(error, \"The CORS policy is invalid.\"),\n exportName,\n ));\n }\n\n for (const method of capability.cors.methods ?? []) {\n if (!availableMethods.has(method)) {\n findings.push(finding(\n \"cors-method-unavailable\",\n file,\n `CORS method ${method} is not available from this route.`,\n exportName,\n ));\n }\n }\n }\n\n validateRateLimit(capability.security, file, exportName, findings);\n }\n\n validateRateLimit(routeModule.policy?.security, file, undefined, findings);\n if (routeModule.policy?.document) {\n try {\n createSecurityHeaders(toFragmentDocument(routeModule.policy.document), {\n nonce: \"build-verification-nonce\",\n });\n } catch (error) {\n findings.push(finding(\n \"security-header-render-failed\",\n file,\n errorMessage(error, \"The security headers are invalid.\"),\n ));\n }\n }\n\n return findings;\n}\n\n// A build reads one file at a time, but policy cascades. A file declaring no\n// reporting endpoints of its own inherits them. Its `csp.reportTo` therefore\n// names a group only the merged policy resolves, which\n// `validateRouteModules(...)` checks during startup. A file declaring its own\n// endpoint map is self-contained. A name outside that map stays a build\n// error, because that is the typo worth catching early.\nfunction toFragmentDocument(document: SecurityPolicy): SecurityPolicy {\n const endpoints = document.headers?.reportingEndpoints;\n const declaresEndpoints = Boolean(\n endpoints && Object.keys(endpoints).length,\n );\n const reportTo = document.csp === false ? undefined : document.csp?.reportTo;\n\n if (declaresEndpoints || !reportTo) {\n return document;\n }\n\n return {\n ...document,\n csp: { ...document.csp as ContentSecurityPolicy, reportTo: undefined },\n headers: endpoints\n ? { ...document.headers, reportingEndpoints: undefined }\n : document.headers,\n };\n}\n\nfunction validateRateLimit(\n securityPolicy: RouteSecurityPolicy | undefined,\n file: string,\n exportName: string | undefined,\n findings: StaticPolicyFinding[],\n) {\n if (!securityPolicy?.rateLimit) return;\n try {\n validateRateLimitPolicy(securityPolicy.rateLimit);\n } catch (error) {\n findings.push(finding(\n \"rate-limit-invalid\",\n file,\n errorMessage(error, \"The rate limit policy is invalid.\"),\n exportName,\n ));\n }\n}\n\nfunction finding(\n code: StaticPolicyFinding[\"code\"],\n file: string,\n message: string,\n exportName?: string,\n): StaticPolicyFinding {\n return { code, exportName, file, message, severity: \"error\" };\n}\n\nfunction collectCoreImports(ast: AstNode) {\n const imports = new Map<string, string>();\n for (const statement of asNodeArray(ast.body)) {\n if (\n statement.type !== \"ImportDeclaration\" ||\n asNode(statement.source)?.value !== \"@demiurgejs/core\"\n ) continue;\n for (const specifier of asNodeArray(statement.specifiers)) {\n if (specifier.type !== \"ImportSpecifier\") continue;\n const local = identifierName(specifier.local);\n const imported = propertyName(specifier.imported);\n if (local && imported) imports.set(local, imported);\n }\n }\n return imports;\n}\n\nfunction collectConstants(ast: AstNode) {\n const constants = new Map<string, unknown>();\n for (const statement of asNodeArray(ast.body)) {\n const declaration = statement.type === \"ExportNamedDeclaration\"\n ? asNode(statement.declaration)\n : statement;\n if (declaration?.type !== \"VariableDeclaration\") continue;\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n const initializer = asNode(declarator.init);\n if (!name || !initializer) continue;\n const value = evaluateLiteral(initializer, constants);\n if (value !== unresolved) constants.set(name, value);\n }\n }\n return constants;\n}\n\nconst unresolved = Symbol(\"unresolved\");\n\nfunction evaluateLiteral(\n node: AstNode | undefined,\n constants: Map<string, unknown>,\n): unknown | typeof unresolved {\n if (!node) return undefined;\n if (node.type === \"Literal\") return node.value;\n if (node.type === \"Identifier\") {\n if (node.name === \"undefined\") return undefined;\n return constants.has(String(node.name))\n ? constants.get(String(node.name))\n : unresolved;\n }\n if (node.type === \"TemplateLiteral\") {\n if (asNodeArray(node.expressions).length) return unresolved;\n return asNodeArray(node.quasis)\n .map((quasi) => asNode(quasi.value)?.cooked ?? \"\")\n .join(\"\");\n }\n if (node.type === \"UnaryExpression\") {\n const value = evaluateLiteral(asNode(node.argument), constants);\n if (typeof value !== \"number\") return unresolved;\n if (node.operator === \"-\") return -value;\n if (node.operator === \"+\") return value;\n return unresolved;\n }\n if (node.type === \"ArrayExpression\") {\n const values: unknown[] = [];\n for (const element of asNodeArray(node.elements)) {\n const value = evaluateLiteral(element, constants);\n if (value === unresolved) return unresolved;\n values.push(value);\n }\n return values;\n }\n if (node.type === \"ObjectExpression\") {\n const value: Record<string, unknown> = {};\n for (const property of asNodeArray(node.properties)) {\n if (property.type !== \"Property\" || property.computed) return unresolved;\n const name = propertyName(property.key);\n const child = evaluateLiteral(asNode(property.value), constants);\n if (!name || child === unresolved) return unresolved;\n value[name] = child;\n }\n return value;\n }\n return unresolved;\n}\n\nfunction isHttpMethod(value: string): value is HttpMethod {\n return httpMethods.includes(value as HttpMethod);\n}\n\nfunction errorMessage(error: unknown, fallback: string) {\n return error instanceof Error ? error.message : fallback;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction asNode(value: unknown) {\n return value && typeof value === \"object\" && \"type\" in value\n ? value as AstNode\n : undefined;\n}\n\nfunction asNodeArray(value: unknown) {\n return Array.isArray(value)\n ? value.map(asNode).filter((node): node is AstNode => Boolean(node))\n : [];\n}\n\nfunction identifierName(value: unknown) {\n const node = asNode(value);\n return node?.type === \"Identifier\" ? String(node.name) : undefined;\n}\n\nfunction propertyName(value: unknown) {\n const node = asNode(value);\n return node?.type === \"Identifier\" || node?.type === \"Literal\"\n ? String(node.name ?? node.value)\n : undefined;\n}\n","import { existsSync } from \"node:fs\";\nimport type { IncomingMessage } from \"node:http\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { dirname, join, resolve, relative, sep } from \"node:path\";\nimport MagicString from \"magic-string\";\nimport {\n type ConfigEnv,\n parseAst,\n type Plugin,\n type UserConfig,\n type ViteDevServer,\n} from \"vite\";\nimport { renderDocument } from \"../document\";\nimport type {\n LinkTag,\n ResolvedMetadata,\n ScriptTag,\n} from \"../document\";\nimport { PACKAGE_NAME } from \"../package-name\";\nimport { generateRoutes } from \"../routing/generate\";\nimport {\n createRouteManifest,\n findRouteMatch,\n type RouteManifest,\n} from \"../router\";\nimport {\n handleRequestWithManifest,\n renderNotFoundResponse,\n renderPageDocument,\n type PageRenderer,\n} from \"../server\";\nimport {\n type RouteImporter,\n type RouteModule,\n} from \"../route\";\nimport {\n UnsupportedMethodError,\n toWebRequest,\n writeNotImplemented,\n writeWebResponse,\n} from \"../node/http\";\nimport { createFontAssetHandler } from \"../node/font\";\nimport { createImageOptimizer } from \"../node/image\";\nimport { renderStreamingPageResponse } from \"../node/streaming\";\nimport type { FontContribution } from \"../platform/fonts\";\nimport { parseImageVariantPath } from \"../platform/image-url\";\nimport type { ImagePolicy } from \"../platform/images\";\nimport { createCspNonce } from \"../security/policy\";\nimport {\n verifyRoutePolicyFile,\n type StaticPolicyFinding,\n} from \"./policy-verification\";\nimport type {\n StaticFileHeaderPatternRule,\n VercelStaticDeployment,\n} from \"../static\";\n\nexport type DemiurgeVitePluginOptions = {\n document?: {\n lang?: string;\n title?: string;\n };\n // The fonts that the application self-hosts. The development server serves\n // the same URLs that the build publishes.\n fonts?: FontContribution;\n // The image policy that the application passes to `planImageTransform` and\n // to `Image`. The development server serves the optimizer path from it.\n images?: ImagePolicy;\n routesDir?: string;\n static?: {\n deployment?: VercelStaticDeployment;\n headers?: readonly StaticFileHeaderPatternRule[];\n };\n styles?: false | string;\n typedRoutes?: boolean | {\n outputFile?: string;\n };\n};\n\nexport type DemiurgeVitePluginApi = {\n demiurge: true;\n fonts?: FontContribution;\n images?: ImagePolicy;\n staticDeployment?: VercelStaticDeployment;\n staticFileHeaders?: readonly StaticFileHeaderPatternRule[];\n};\n\nconst CLIENT_ENTRY_ID = \"virtual:demiurge/client-entry\";\nconst DEV_CLIENT_ENTRY_PATH = `/@id/${CLIENT_ENTRY_ID}`;\nconst RESOLVED_CLIENT_ENTRY_ID = `\\0${CLIENT_ENTRY_ID}`;\nconst SERVER_ENTRY_ID = \"virtual:demiurge/server-entry\";\nconst RESOLVED_SERVER_ENTRY_ID = `\\0${SERVER_ENTRY_ID}`;\nconst DEFAULT_TYPED_ROUTES_OUTPUT = \".demiurge/route-manifest.d.ts\";\nexport function demiurge(options: DemiurgeVitePluginOptions = {}): Plugin {\n let root = process.cwd();\n let isBuild = false;\n const viteNoncePlaceholder = `demiurge-${createCspNonce()}`;\n\n return {\n api: {\n demiurge: true,\n fonts: options.fonts,\n images: options.images,\n staticDeployment: options.static?.deployment,\n staticFileHeaders: options.static?.headers,\n } satisfies DemiurgeVitePluginApi,\n enforce: \"post\",\n name: \"demiurge\",\n config(config, environment) {\n return createViteConfig(config, environment, viteNoncePlaceholder);\n },\n configResolved(config) {\n root = config.root;\n isBuild = config.command === \"build\";\n },\n resolveId(id) {\n if (id === CLIENT_ENTRY_ID) {\n return RESOLVED_CLIENT_ENTRY_ID;\n }\n\n if (id === SERVER_ENTRY_ID) {\n return RESOLVED_SERVER_ENTRY_ID;\n }\n\n return null;\n },\n load(id) {\n if (id === RESOLVED_CLIENT_ENTRY_ID) {\n return createClientEntrySource(root, options);\n }\n\n if (id === RESOLVED_SERVER_ENTRY_ID) {\n return createServerEntrySource(root, options);\n }\n\n return null;\n },\n transform: {\n order: \"post\",\n handler(code, id, transformOptions) {\n if (!isRouteSource(root, options, id)) {\n return null;\n }\n\n if (transformOptions?.ssr) {\n return isBuild ? null : protectSsrImportMeta(code, id);\n }\n\n const transformed = stripClientPageData(code);\n return transformed === code ? null : { code: transformed, map: null };\n },\n },\n generateBundle(_outputOptions, bundle) {\n const entry = Object.values(bundle).find(\n (item) =>\n item.type === \"chunk\" &&\n item.isEntry &&\n item.facadeModuleId === RESOLVED_CLIENT_ENTRY_ID,\n );\n\n if (!entry) {\n return;\n }\n\n const styles = Object.values(bundle)\n .filter(\n (asset): asset is Extract<(typeof bundle)[string], { type: \"asset\" }> =>\n asset.type === \"asset\" && asset.fileName.endsWith(\".css\"),\n )\n .map((asset) => `/${asset.fileName}`);\n const clientEntry = `/${entry.fileName}`;\n\n this.emitFile({\n fileName: \"index.html\",\n source: createDocumentHtml({\n entrySrc: clientEntry,\n lang: options.document?.lang,\n styles,\n title: options.document?.title,\n }),\n type: \"asset\",\n });\n this.emitFile({\n fileName: \"demiurge-manifest.json\",\n source: JSON.stringify({ clientEntry, styles }, null, 2),\n type: \"asset\",\n });\n },\n async buildStart() {\n if (isBuild) {\n await assertRootNotFoundRoute(root, options);\n const findings = await verifyRoutePolicies(root, options);\n\n if (findings.length) {\n throw new Error(formatStaticPolicyFindings(findings));\n }\n }\n\n if (!options.typedRoutes) {\n return;\n }\n\n await generateTypedRoutes(root, options);\n },\n configureServer(server) {\n const reportPolicyFindings = async () => {\n const findings = await verifyRoutePolicies(server.config.root, options);\n\n for (const finding of findings) {\n server.config.logger.warn(formatStaticPolicyFinding(finding));\n }\n };\n // A single editor save can fire several watcher events, and a branch\n // switch fires one per route file. Collapse a burst into one scan, and\n // chain scans so two never walk the route tree at the same time.\n let policyVerificationTimer: ReturnType<typeof setTimeout> | undefined;\n let policyVerificationRun = Promise.resolve();\n const runPolicyVerification = () => {\n policyVerificationRun = policyVerificationRun\n .then(reportPolicyFindings)\n .catch(() => {\n // Vite reports route read and syntax errors through its module pipeline.\n });\n };\n const startPolicyVerification = () => {\n if (policyVerificationTimer) {\n clearTimeout(policyVerificationTimer);\n }\n\n policyVerificationTimer = setTimeout(() => {\n policyVerificationTimer = undefined;\n runPolicyVerification();\n }, policyVerificationDebounceMs);\n policyVerificationTimer.unref?.();\n };\n\n server.httpServer?.once(\"close\", () => {\n if (policyVerificationTimer) {\n clearTimeout(policyVerificationTimer);\n policyVerificationTimer = undefined;\n }\n });\n\n runPolicyVerification();\n if (options.typedRoutes) {\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n\n void generateTypedRoutes(server.config.root, options);\n server.watcher.add(routesDir);\n server.watcher.on(\"add\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n server.watcher.on(\"change\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n server.watcher.on(\"unlink\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n } else {\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n server.watcher.add(routesDir);\n for (const event of [\"add\", \"change\", \"unlink\"] as const) {\n server.watcher.on(event, (file) => {\n if (isRouteFile(routesDir, file)) startPolicyVerification();\n });\n }\n }\n\n const optimizeImage = createDevImageOptimizer(server, options);\n const serveFont = createFontAssetHandler({\n fonts: options.fonts,\n root: server.config.root,\n });\n\n server.middlewares.use(async (request, response, next) => {\n try {\n let webRequest: Request;\n\n try {\n webRequest = toWebRequest(request, {\n // Vite performs its own configured host allowlist check before\n // Demiurge's middleware runs. Production Node listeners require\n // an explicit application allowlist instead.\n allowedHosts: [request.headers.host ?? \"localhost\"],\n });\n } catch (error) {\n if (error instanceof UnsupportedMethodError) {\n writeNotImplemented(response);\n return;\n }\n\n throw error;\n }\n\n const font = await serveFont(webRequest);\n\n if (font) {\n await writeWebResponse(response, font);\n return;\n }\n\n const image = await optimizeImage(webRequest);\n\n if (image) {\n await writeWebResponse(response, image);\n return;\n }\n\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n const manifest = await loadDevManifest(server, request, routesDir);\n const documentSecurity = createDevDocumentSecurity(\n server,\n viteNoncePlaceholder,\n );\n const result = await handleDevRequest(\n manifest,\n webRequest,\n createDevRuntimeOptions(options, documentSecurity.transform),\n );\n\n if (result === \"next\") {\n // Vite owns its own asset URLs, so an unmatched request still\n // falls through. The post middleware below is what turns whatever\n // Vite could not serve into the same negotiated not-found\n // production returns.\n next();\n return;\n }\n\n applyDevDocumentSecurity(result, documentSecurity.nonce);\n await writeWebResponse(response, result);\n } catch (error) {\n next(error);\n }\n });\n\n // The returned hook registers this after the Vite middleware. It sees\n // only requests that Vite cannot serve. `appType` is \"custom\", so no SPA\n // fallback intercepts these requests. Development and production render\n // the same negotiated not-found response for an unmatched path.\n return () => {\n server.middlewares.use(async (request, response, next) => {\n try {\n let webRequest: Request;\n\n try {\n webRequest = toWebRequest(request, {\n allowedHosts: [request.headers.host ?? \"localhost\"],\n });\n } catch (error) {\n if (error instanceof UnsupportedMethodError) {\n writeNotImplemented(response);\n return;\n }\n\n throw error;\n }\n\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n const manifest = await loadDevManifest(server, request, routesDir);\n\n warnMissingRootNotFound(manifest, routesDir);\n\n const documentSecurity = createDevDocumentSecurity(\n server,\n viteNoncePlaceholder,\n );\n const notFoundResponse = await renderNotFoundResponse(\n manifest,\n webRequest,\n createDevFallbackOptions(options, documentSecurity.transform),\n );\n applyDevDocumentSecurity(\n notFoundResponse,\n documentSecurity.nonce,\n );\n await writeWebResponse(response, notFoundResponse);\n } catch (error) {\n next(error);\n }\n });\n };\n },\n };\n}\n\ntype AstNode = {\n [key: string]: unknown;\n end: number;\n start: number;\n type: string;\n};\n\n// Vite 6 treats the `meta` token in `import.meta` as an imported reference.\n// Give an imported `meta` binding a private name before development SSR runs.\nfunction protectSsrImportMeta(code: string, id: string) {\n if (!code.includes(\"import.meta\")) {\n return null;\n }\n\n const ast = parseAst(code) as unknown as AstNode;\n const declaration = asNodeArray(ast.body).find((node) =>\n node.type === \"ImportDeclaration\" &&\n asNodeArray(node.specifiers).some((specifier) =>\n asNode(specifier.local)?.type === \"Identifier\" &&\n asNode(specifier.local)?.name === \"meta\"\n )\n );\n const specifier = declaration &&\n asNodeArray(declaration.specifiers).find((candidate) =>\n asNode(candidate.local)?.type === \"Identifier\" &&\n asNode(candidate.local)?.name === \"meta\"\n );\n const local = specifier && asNode(specifier.local);\n\n if (!declaration || !specifier || !local) {\n return null;\n }\n\n let alias = \"__demiurge_imported_meta__\";\n while (new RegExp(`\\\\b${alias}\\\\b`).test(code)) {\n alias += \"_\";\n }\n\n const editor = new MagicString(code);\n const imported = asNode(specifier.imported);\n editor.overwrite(\n local.start,\n local.end,\n imported?.start === local.start ? `meta as ${alias}` : alias,\n );\n editor.appendLeft(declaration.end, `\\nconst meta = ${alias};`);\n\n return {\n code: editor.toString(),\n map: editor.generateMap({\n hires: \"boundary\",\n includeContent: true,\n source: id,\n }),\n };\n}\n\n// Page data and document contributions are server capabilities. Vite and React\n// first parse TypeScript and JSX. The plugin then removes these capabilities\n// before Rollup follows the final client graph. This sequence excludes request\n// code and server-only imports from browser chunks. The exported document\n// bindings remain as `undefined` so the\n// route module keeps a stable shape without evaluating their initializers.\nexport function stripClientPageData(code: string) {\n const ast = parseAst(code) as unknown as AstNode;\n const dataRanges: Array<{ end: number; start: number }> = [];\n const documentRanges = findDocumentContributionRanges(ast);\n const serverImports: AstNode[] = [];\n\n walkAst(ast, (node) => {\n if (node.type === \"ImportDeclaration\" && isServerOnlyImport(node)) {\n serverImports.push(node);\n return;\n }\n\n if (node.type !== \"CallExpression\" || !isPageCallee(node.callee)) {\n return;\n }\n\n const argument = asNodeArray(node.arguments)[0];\n if (argument?.type !== \"ObjectExpression\") {\n return;\n }\n\n for (const property of asNodeArray(argument.properties)) {\n if (property.type === \"Property\" && propertyName(property.key) === \"data\") {\n dataRanges.push({ end: property.end, start: property.start });\n }\n }\n });\n\n const serverRanges = [...dataRanges, ...documentRanges];\n\n if (serverRanges.length === 0) {\n return code;\n }\n\n const removalRanges = [...serverRanges];\n for (const declaration of serverImports) {\n const localNames = asNodeArray(declaration.specifiers)\n .map((specifier) => asNode(specifier.local))\n .filter((local): local is AstNode => local?.type === \"Identifier\")\n .map((local) => String(local.name));\n const masked = maskRanges(code, [\n ...serverRanges,\n { end: declaration.end, start: declaration.start },\n ]);\n const leakedName = localNames.find((name) =>\n new RegExp(`\\\\b${escapeRegExp(name)}\\\\b`).test(masked)\n );\n\n if (leakedName) {\n throw new Error(\n `Server-only import ${JSON.stringify(leakedName)} is used by client route code. Move that use into page data, a document contribution, or a client-safe module.`,\n );\n }\n\n removalRanges.push({ end: declaration.end, start: declaration.start });\n }\n\n return replaceRanges(code, removalRanges, (range) =>\n dataRanges.includes(range) ? \"data: undefined\" :\n documentRanges.includes(range) ? \"undefined\" : \"\"\n );\n}\n\nconst documentContributionNames = new Set([\"links\", \"metadata\", \"scripts\"]);\n\nfunction findDocumentContributionRanges(ast: AstNode) {\n const exportedLocals = new Set<string>();\n\n for (const statement of asNodeArray(ast.body)) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n\n const declaration = asNode(statement.declaration);\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of asNodeArray(declaration.declarations)) {\n const id = asNode(declarator.id);\n if (\n id?.type === \"Identifier\" &&\n documentContributionNames.has(String(id.name))\n ) {\n exportedLocals.add(String(id.name));\n }\n }\n }\n\n for (const specifier of asNodeArray(statement.specifiers)) {\n const exported = propertyName(specifier.exported);\n const local = propertyName(specifier.local);\n if (exported && local && documentContributionNames.has(exported)) {\n exportedLocals.add(local);\n }\n }\n }\n\n const ranges: Array<{ end: number; start: number }> = [];\n walkAst(ast, (node) => {\n if (node.type !== \"VariableDeclarator\") return;\n const id = asNode(node.id);\n const init = asNode(node.init);\n if (\n id?.type === \"Identifier\" &&\n exportedLocals.has(String(id.name)) &&\n init\n ) {\n ranges.push({ end: init.end, start: init.start });\n }\n });\n\n return ranges;\n}\n\nfunction isRouteSource(\n root: string,\n options: DemiurgeVitePluginOptions,\n id: string,\n) {\n const file = id.split(\"?\", 1)[0] ?? id;\n const routesRoot = resolve(root, options.routesDir ?? \"src/routes\");\n const pathFromRoutes = relative(routesRoot, file);\n return pathFromRoutes !== \"\" &&\n pathFromRoutes !== \"..\" &&\n !pathFromRoutes.startsWith(`..${sep}`);\n}\n\nfunction walkAst(value: unknown, visit: (node: AstNode) => void) {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkAst(item, visit);\n return;\n }\n\n const node = value as Partial<AstNode>;\n if (typeof node.type !== \"string\") return;\n visit(node as AstNode);\n for (const [key, child] of Object.entries(node)) {\n if (!new Set([\"end\", \"loc\", \"start\", \"type\"]).has(key)) {\n walkAst(child, visit);\n }\n }\n}\n\nfunction asNode(value: unknown) {\n return value && typeof value === \"object\" && \"type\" in value\n ? value as AstNode\n : undefined;\n}\n\nfunction asNodeArray(value: unknown) {\n return Array.isArray(value)\n ? value.map(asNode).filter((node): node is AstNode => Boolean(node))\n : [];\n}\n\nfunction isPageCallee(value: unknown) {\n const callee = asNode(value);\n if (callee?.type === \"Identifier\") return callee.name === \"page\";\n return callee?.type === \"MemberExpression\" &&\n propertyName(callee.property) === \"page\";\n}\n\nfunction propertyName(value: unknown) {\n const property = asNode(value);\n return property?.type === \"Identifier\" || property?.type === \"Literal\"\n ? String(property.name ?? property.value)\n : undefined;\n}\n\nfunction isServerOnlyImport(node: AstNode) {\n const source = asNode(node.source)?.value;\n return typeof source === \"string\" &&\n /(?:^|[/.-])server(?:[/.-]|$)/.test(source);\n}\n\nfunction maskRanges(code: string, ranges: Array<{ end: number; start: number }>) {\n const characters = [...code];\n for (const { end, start } of ranges) {\n characters.fill(\" \", start, end);\n }\n return characters.join(\"\");\n}\n\nfunction replaceRanges(\n code: string,\n ranges: Array<{ end: number; start: number }>,\n replacement: (range: { end: number; start: number }) => string,\n) {\n return [...ranges]\n .sort((left, right) => right.start - left.start)\n .reduce(\n (result, range) =>\n `${result.slice(0, range.start)}${replacement(range)}${result.slice(range.end)}`,\n code,\n );\n}\n\nfunction escapeRegExp(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction createViteConfig(\n config: UserConfig,\n environment: ConfigEnv,\n viteNoncePlaceholder: string,\n): UserConfig {\n return {\n appType: \"custom\",\n build: {\n assetsInlineLimit: config.build?.assetsInlineLimit ?? 0,\n ...(environment.isSsrBuild &&\n config.build?.target === undefined &&\n config.ssr?.target !== \"webworker\"\n ? { target: \"node22.13\" }\n : {}),\n rollupOptions: {\n input: config.build?.rollupOptions?.input ?? CLIENT_ENTRY_ID,\n },\n },\n ...(environment.command === \"serve\"\n ? {\n html: { cspNonce: viteNoncePlaceholder },\n ssr: { external: [PACKAGE_NAME] },\n }\n : {}),\n };\n}\n\nexport function createClientEntrySource(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = options.routesDir ?? \"src/routes\";\n const stylesImport = createStylesImport(root, options);\n\n return `import { hydrateFileRouter } from \"${PACKAGE_NAME}\";\n${stylesImport}\n\n${createRouteMapSource(routesDir, {\n exportRoutes: false,\n includeServerOnly: false,\n })}\n\nvoid hydrateFileRouter({ routes });\n`;\n}\n\nexport function createServerEntrySource(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = options.routesDir ?? \"src/routes\";\n\n return `import { createRequestHandler } from \"${PACKAGE_NAME}\";\n\n${createRouteMapSource(routesDir, {\n exportRoutes: true,\n includeServerOnly: true,\n eagerModules: true,\n })}\n\nexport function createHandler(options = {}) {\n const { clientEntry, lang, styles, title, ...handlerOptions } = options;\n\n return createRequestHandler({\n ...handlerOptions,\n routes,\n routeModules,\n ssr: {\n clientEntry,\n lang: lang ?? ${JSON.stringify(options.document?.lang)},\n styles,\n title: title ?? ${JSON.stringify(options.document?.title)},\n },\n });\n}\n`;\n}\n\n// Both virtual entries use this function. Therefore, their prefix removal and\n// route-key formats stay equal. The server entry requires framework-attached\n// `.ts` files such as `@policy.ts` and `@middleware.ts`. Previously, a\n// `.tsx`-only glob omitted these files from production. Development still found\n// and applied them.\nfunction createRouteMapSource(\n routesDir: string,\n {\n exportRoutes,\n eagerModules = false,\n includeServerOnly,\n }: {\n eagerModules?: boolean;\n exportRoutes: boolean;\n includeServerOnly: boolean;\n },\n) {\n const routesGlobs = toRootAbsoluteGlobs(routesDir, includeServerOnly);\n const routesPrefix = toRootAbsolutePrefix(routesDir);\n\n return eagerModules\n ? `const eagerRouteModules = import.meta.glob(${JSON.stringify(routesGlobs)}, { eager: true });\nconst routePrefix = ${JSON.stringify(routesPrefix)};\nexport const routeModules = Object.fromEntries(\n Object.entries(eagerRouteModules).map(([file, module]) => [\n \\`./routes/\\${file.slice(routePrefix.length)}\\`,\n module,\n ]),\n);\n${exportRoutes ? \"export \" : \"\"}const routes = Object.fromEntries(\n Object.entries(routeModules).map(([file, module]) => [\n file,\n async () => module,\n ]),\n);`\n : `const routeModules = import.meta.glob(${JSON.stringify(routesGlobs)});\nconst routePrefix = ${JSON.stringify(routesPrefix)};\n${exportRoutes ? \"export \" : \"\"}const routes = Object.fromEntries(\n Object.entries(routeModules).map(([file, load]) => [\n \\`./routes/\\${file.slice(routePrefix.length)}\\`,\n load,\n ]),\n);`;\n}\n\n// These two files run only on the server. They control a request before the\n// route runs and do not render. A client glob would create public chunks in\n// `dist/client`. These chunks could expose credentials, authorization logic, or\n// internal host names from a middleware or policy closure.\nconst serverOnlyRouteFiles = [\"@middleware.ts\", \"@policy.ts\"];\n\nfunction toRootAbsoluteGlobs(routesDir: string, includeServerOnly: boolean) {\n const base = `/${routesDir.replace(/^\\/|\\/$/g, \"\")}`;\n const globs = [`${base}/**/*.{ts,tsx}`];\n\n if (!includeServerOnly) {\n globs.push(\n ...serverOnlyRouteFiles.flatMap((fileName) => [\n `!${base}/${fileName}`,\n `!${base}/**/${fileName}`,\n ]),\n );\n }\n\n return globs;\n}\n\nfunction toRootAbsolutePrefix(routesDir: string) {\n return `/${routesDir.replace(/^\\/|\\/$/g, \"\")}/`;\n}\n\nfunction createStylesImport(\n root: string,\n options: DemiurgeVitePluginOptions,\n) {\n if (options.styles === false) {\n return \"\";\n }\n\n const stylesFile = options.styles ?? \"src/styles.css\";\n const resolvedStylesFile = resolve(root, stylesFile);\n\n return existsSync(resolvedStylesFile)\n ? `import ${JSON.stringify(`/${stylesFile.replace(/^\\/+/, \"\")}`)};`\n : \"\";\n}\n\n// Development serves the same image URLs that production serves. A static\n// loader path describes its own transform, so the same optimizer answers\n// both loaders without any build output.\nexport function createDevImageOptimizer(\n server: ViteDevServer,\n options: DemiurgeVitePluginOptions,\n) {\n const publicDir = server.config.publicDir;\n const optimizerPath = options.images?.optimizerPath ?? \"/_demiurge/image\";\n\n if (!publicDir) {\n return async () => null;\n }\n\n return createImageOptimizer({\n policy: options.images,\n resolveVariant: (pathname) =>\n parseImageVariantPath(pathname, optimizerPath),\n root: publicDir,\n });\n}\n\n// Development renders through the production pipeline. It adds the virtual\n// client entry, the Vite HTML transform, and a development flag for stack\n// traces. The shared handler makes all security and routing decisions.\nfunction createDevRuntimeOptions(\n options: DemiurgeVitePluginOptions,\n transformDocument: (html: string) => Promise<string>,\n) {\n return {\n dev: true,\n ssr: createDevSsrOptions(options),\n transformDocument,\n renderPage: async (\n match: Parameters<PageRenderer>[0],\n renderOptions: Parameters<PageRenderer>[1],\n ) => {\n if (match.render.mode === \"streaming\") {\n return await renderStreamingPageResponse(match, {\n ...renderOptions,\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n transformDocument,\n });\n }\n\n const html = await transformDocument(\n renderPageDocument(match, {\n ...renderOptions,\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n }),\n );\n\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n },\n };\n}\n\nfunction createDevDocumentSecurity(\n server: ViteDevServer,\n viteNoncePlaceholder: string,\n) {\n const nonce = createCspNonce();\n const shieldNonce = createCspNonce();\n\n return {\n nonce,\n transform: async (html: string) => {\n const shielded = shieldViteNonceTargets(html, shieldNonce);\n const transformed = await server.transformIndexHtml(\"/\", shielded);\n\n return replaceNonceAttribute(\n replaceNonceAttribute(transformed, shieldNonce),\n viteNoncePlaceholder,\n nonce,\n );\n },\n };\n}\n\nfunction shieldViteNonceTargets(html: string, nonce: string) {\n const lowerHtml = html.toLowerCase();\n let cursor = 0;\n let output = \"\";\n\n while (cursor < html.length) {\n const tagStart = html.indexOf(\"<\", cursor);\n\n if (tagStart === -1) {\n return output + html.slice(cursor);\n }\n\n output += html.slice(cursor, tagStart);\n\n if (lowerHtml.startsWith(\"<!--\", tagStart)) {\n const commentEnd = lowerHtml.indexOf(\"-->\", tagStart + 4);\n const end = commentEnd === -1 ? html.length : commentEnd + 3;\n output += html.slice(tagStart, end);\n cursor = end;\n continue;\n }\n\n const name = lowerHtml.slice(tagStart).match(/^<\\s*(script|style|link)\\b/)?.[1];\n\n if (!name) {\n output += \"<\";\n cursor = tagStart + 1;\n continue;\n }\n\n const tagEnd = findHtmlTagEnd(html, tagStart);\n\n if (tagEnd === -1) {\n return output + html.slice(tagStart);\n }\n\n const openingTag = html.slice(tagStart, tagEnd + 1);\n output += /(?:^|\\s)nonce(?:\\s|=|>)/i.test(openingTag)\n ? openingTag\n : addNonceAttribute(openingTag, nonce);\n cursor = tagEnd + 1;\n\n if (name === \"script\" || name === \"style\") {\n const closeStart = lowerHtml.indexOf(`</${name}`, cursor);\n\n if (closeStart === -1) {\n return output + html.slice(cursor);\n }\n\n output += html.slice(cursor, closeStart);\n cursor = closeStart;\n }\n }\n\n return output;\n}\n\nfunction findHtmlTagEnd(html: string, start: number) {\n let quote: \"\\\"\" | \"'\" | undefined;\n\n for (let index = start + 1; index < html.length; index++) {\n const character = html[index];\n\n if (quote) {\n if (character === quote) quote = undefined;\n continue;\n }\n\n if (character === \"\\\"\" || character === \"'\") {\n quote = character;\n } else if (character === \">\") {\n return index;\n }\n }\n\n return -1;\n}\n\nfunction addNonceAttribute(openingTag: string, nonce: string) {\n const insertion = /\\/\\s*>$/.test(openingTag)\n ? openingTag.lastIndexOf(\"/\")\n : openingTag.length - 1;\n\n return `${openingTag.slice(0, insertion)} nonce=\"${nonce}\"${openingTag.slice(insertion)}`;\n}\n\nfunction replaceNonceAttribute(\n html: string,\n current: string,\n replacement?: string,\n) {\n const pattern = new RegExp(\n `(\\\\snonce\\\\s*=\\\\s*)([\"'])${escapeRegExp(current)}\\\\2`,\n \"g\",\n );\n\n return html.replace(\n pattern,\n replacement ? `$1\"${replacement}\"` : \"\",\n );\n}\n\nfunction applyDevDocumentSecurity(response: Response, nonce: string) {\n const contentType = response.headers.get(\"content-type\");\n const csp = response.headers.get(\"content-security-policy\");\n\n if (!contentType?.toLowerCase().startsWith(\"text/html\") || !csp) {\n return;\n }\n\n const source = `'nonce-${nonce}'`;\n const withScriptNonce = addCspSource(\n csp,\n [\"script-src-elem\", \"script-src\"],\n \"script-src\",\n source,\n );\n const withStyleNonce = allowsUnsafeInline(\n withScriptNonce,\n [\"style-src-elem\", \"style-src\"],\n )\n ? withScriptNonce\n : addCspSource(\n withScriptNonce,\n [\"style-src-elem\", \"style-src\"],\n \"style-src\",\n source,\n );\n\n response.headers.set(\"content-security-policy\", withStyleNonce);\n response.headers.set(\"cache-control\", \"private, no-store\");\n}\n\nfunction addCspSource(\n csp: string,\n directiveNames: readonly string[],\n fallbackDirectiveName: \"script-src\" | \"style-src\",\n source: string,\n) {\n const directives = csp.split(\";\").map((directive) => directive.trim());\n const directiveIndex = findCspDirectiveIndex(directives, directiveNames);\n\n const defaultDirective = directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n );\n\n if (directiveIndex === -1 && !defaultDirective) return csp;\n\n const [currentName, ...currentSources] =\n (directiveIndex === -1 ? defaultDirective! : directives[directiveIndex]!)\n .split(/\\s+/);\n const updatedDirective = [\n directiveIndex === -1 ? fallbackDirectiveName : currentName!,\n ...new Set([\n ...currentSources.filter((current) => current !== \"'none'\"),\n source,\n ]),\n ].join(\" \");\n\n if (directiveIndex === -1) {\n directives.push(updatedDirective);\n } else {\n directives[directiveIndex] = updatedDirective;\n }\n\n return directives.join(\"; \");\n}\n\nfunction allowsUnsafeInline(\n csp: string,\n directiveNames: readonly string[],\n) {\n const directives = csp.split(\";\").map((directive) => directive.trim());\n const directiveIndex = findCspDirectiveIndex(directives, directiveNames);\n const effectiveDirective = directiveIndex === -1\n ? directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n )\n : directives[directiveIndex];\n const sources = effectiveDirective?.split(/\\s+/).slice(1) ?? [];\n\n return sources.includes(\"'unsafe-inline'\") &&\n !sources.some((source) => /^'(?:nonce-|sha(?:256|384|512)-)/i.test(source));\n}\n\nfunction findCspDirectiveIndex(\n directives: readonly string[],\n directiveNames: readonly string[],\n) {\n for (const name of directiveNames) {\n const index = directives.findIndex((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === name\n );\n\n if (index !== -1) return index;\n }\n\n return -1;\n}\n\n// Both dev middlewares need the manifest for the same request, and building\n// it walks the routes directory. The pre middleware always runs, so the post\n// middleware reuses what it already produced rather than scanning twice on\n// every unmatched request.\nconst DEV_MANIFEST = Symbol.for(\"demiurge.devManifest\");\n\ntype DevManifestCarrier = { [DEV_MANIFEST]?: RouteManifest };\n\nasync function loadDevManifest(\n server: ViteDevServer,\n request: IncomingMessage,\n routesDir: string,\n) {\n const carrier = request as IncomingMessage & DevManifestCarrier;\n const cached = carrier[DEV_MANIFEST];\n\n if (cached) {\n return cached;\n }\n\n const manifest = createRouteManifest(\n await createDevRouteImporters(server, routesDir),\n );\n\n carrier[DEV_MANIFEST] = manifest;\n\n return manifest;\n}\n\nfunction createDevSsrOptions(options: DemiurgeVitePluginOptions) {\n return {\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n lang: options.document?.lang,\n title: options.document?.title,\n };\n}\n\nfunction createDevFallbackOptions(\n options: DemiurgeVitePluginOptions,\n transformDocument: (html: string) => Promise<string>,\n) {\n return {\n ...createDevSsrOptions(options),\n dev: true,\n transformDocument,\n };\n}\n\nconst warnedRoots = new Set<string>();\n\n// The framework built-in is a temporary fallback, not a production 404. The\n// build gate enforces this rule. This warning gives the same message earlier.\nfunction warnMissingRootNotFound(manifest: RouteManifest, routesDir: string) {\n if (\n warnedRoots.has(routesDir) ||\n manifest.fallbacks.notFound.some(\n (fallback) => fallback.fileSegments.length === 0,\n )\n ) {\n return;\n }\n\n warnedRoots.add(routesDir);\n console.warn(missingRootNotFoundMessage(join(routesDir, \"@not-found.tsx\")));\n}\n\n// The framework ships a working 404 so nothing is ever blank, and refuses to\n// let an app reach production still rendering it. A generic framework page in\n// front of real users is a failure of the framework, not of the app that never\n// got around to it.\nexport async function assertRootNotFoundRoute(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDirOption = options.routesDir ?? \"src/routes\";\n const routesDir = resolve(root, routesDirOption);\n\n if (!existsSync(routesDir)) {\n return;\n }\n\n const files = await findRouteFiles(routesDir);\n const names = files.map((file) =>\n relative(routesDir, file).split(sep).join(\"/\"),\n );\n\n if (names.some((name) => /^@not-found\\.tsx?$/.test(name))) {\n return;\n }\n\n const pageRoute = await findPageRouteFile(files);\n\n // An API-only app never wants an HTML not-found document, and nagging it\n // would be user hostile. It builds clean and gets problem+json.\n if (!pageRoute) {\n return;\n }\n\n throw new Error(\n missingRootNotFoundBuildMessage(\n routesDirOption,\n relative(routesDir, pageRoute).split(sep).join(\"/\"),\n ),\n );\n}\n\n// Page detection is a source scan rather than a module evaluation: the plugin\n// cannot execute route modules at build time. A page route is a file that\n// calls `page(...)`, which is the only way to declare one.\nasync function findPageRouteFile(files: string[]) {\n for (const file of files) {\n // Framework-attached files own no address, so they are never page routes.\n if (relative(dirname(file), file).startsWith(\"@\")) {\n continue;\n }\n\n if (declaresPageRoute(await readFile(file, \"utf8\"))) {\n return file;\n }\n }\n\n return undefined;\n}\n\n// Escaped because a package name may contain `.`, which the regex would\n// otherwise read as a wildcard.\nconst PACKAGE_NAME_PATTERN = PACKAGE_NAME.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst DEMIURGE_NAMED_IMPORT = new RegExp(\n `import\\\\s*\\\\{([^}]*)\\\\}\\\\s*from\\\\s*[\"']${PACKAGE_NAME_PATTERN}[\"']`,\n \"g\",\n);\n\n// The plugin cannot evaluate route modules during the build. Therefore, page\n// detection reads the source. It checks the import, not only the word. An API\n// application can call `db.users.page(2)` without serving an HTML document.\n// Only a page route imports `page` from the framework package.\nexport function declaresPageRoute(source: string) {\n const locals = [...source.matchAll(DEMIURGE_NAMED_IMPORT)].flatMap((match) =>\n match[1].split(\",\").flatMap((binding) => {\n const [imported, local] = binding.trim().split(/\\s+as\\s+/);\n\n // `import type { page }` cannot be called, and an alias renames what the\n // call site looks like.\n return imported.replace(/^type\\s+/, \"\") === \"page\"\n ? [local ?? imported]\n : [];\n }),\n );\n\n if (locals.length === 0) {\n return false;\n }\n\n // Strip the import statements first so the binding list is not itself\n // mistaken for a call.\n const body = source.replace(DEMIURGE_NAMED_IMPORT, \"\");\n\n return locals.some((local) => new RegExp(`\\\\b${local}\\\\s*\\\\(`).test(body));\n}\n\nexport function missingRootNotFoundBuildMessage(\n routesDir: string,\n pageRoute: string,\n) {\n return `Demiurge will not build an app with page routes and no ${routesDir}/@not-found.tsx.\n\n\"${pageRoute}\" declares a page, so a browser can reach a path this app does not serve. Decide what that looks like rather than shipping the framework built-in.\n\nCreate ${routesDir}/@not-found.tsx:\n\n export default function NotFound({ pathname }: { pathname: string }) {\n return <h1>Nothing at {pathname}</h1>;\n }\n\nIt renders inside the layouts above the requested path. Opt out with \"export const layout = false\".`;\n}\n\nexport function missingRootNotFoundMessage(notFoundFile: string) {\n return `Demiurge is serving its built-in 404 because ${notFoundFile} does not exist.\n\nCreate it before building for production:\n\n export default function NotFound({ pathname }: { pathname: string }) {\n return <h1>Nothing at {pathname}</h1>;\n }\n`;\n}\n\nexport function createDocumentHtml({\n entrySrc,\n lang,\n links,\n metadata,\n nonce,\n scripts,\n styles,\n title,\n}: {\n entrySrc: string;\n lang?: string;\n links?: LinkTag[];\n metadata?: ResolvedMetadata;\n nonce?: string;\n scripts?: ScriptTag[];\n styles?: string[];\n title?: string;\n}) {\n return renderDocument({\n entrySrc,\n lang,\n links,\n metadata,\n nonce,\n scripts,\n styles,\n title,\n });\n}\n\nasync function generateTypedRoutes(\n root: string,\n options: DemiurgeVitePluginOptions,\n) {\n const routesDir = resolve(root, options.routesDir ?? \"src/routes\");\n const outputFile = resolve(\n root,\n typeof options.typedRoutes === \"object\"\n ? options.typedRoutes.outputFile ?? DEFAULT_TYPED_ROUTES_OUTPUT\n : DEFAULT_TYPED_ROUTES_OUTPUT,\n );\n\n await generateRoutes({ outputFile, routesDir });\n}\n\nfunction isRouteFile(routesDir: string, file: string) {\n return (\n file.startsWith(routesDir) &&\n /\\.tsx?$/.test(file)\n );\n}\n\nexport async function createDevRouteImporters(\n server: ViteDevServer,\n routesDir: string,\n) {\n const files = await findRouteFiles(routesDir);\n const routes: Record<string, RouteImporter> = {};\n\n for (const file of files) {\n const routeKey = toRouteKey(routesDir, file);\n routes[routeKey] = async () =>\n (await server.ssrLoadModule(file)) as RouteModule;\n }\n\n return routes;\n}\n\nexport async function handleDevRequest(\n manifest: RouteManifest,\n request: Request,\n options: Parameters<typeof handleRequestWithManifest>[2] = {},\n) {\n const url = new URL(request.url);\n const routeMatch = findRouteMatch(manifest.routes, url.pathname);\n\n if (!routeMatch) {\n return \"next\" as const;\n }\n\n return await handleRequestWithManifest(manifest, request, options);\n}\n\nasync function findRouteFiles(directory: string) {\n const entries = await readdir(directory, {\n recursive: true,\n withFileTypes: true,\n });\n\n return entries\n .filter((entry) => entry.isFile() && /\\.tsx?$/.test(entry.name))\n .map((entry) => resolve(entry.parentPath, entry.name));\n}\n\n// Every route file is read and parsed. Without a cap, a large route tree opens\n// one descriptor per file at once, which is how this hits EMFILE rather than a\n// CPU limit.\nconst policyVerificationConcurrency = 8;\nconst policyVerificationDebounceMs = 50;\n\nasync function mapWithConcurrency<Item, Result>(\n items: readonly Item[],\n limit: number,\n task: (item: Item) => Promise<Result>,\n) {\n const results = new Array<Result>(items.length);\n let next = 0;\n\n const workers = Array.from(\n { length: Math.min(limit, items.length) },\n async () => {\n while (next < items.length) {\n const index = next++;\n results[index] = await task(items[index]!);\n }\n },\n );\n\n await Promise.all(workers);\n\n return results;\n}\n\nexport async function verifyRoutePolicies(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = resolve(root, options.routesDir ?? \"src/routes\");\n\n if (!existsSync(routesDir)) return [];\n const findings = (await mapWithConcurrency(\n await findRouteFiles(routesDir),\n policyVerificationConcurrency,\n verifyRoutePolicyFile,\n )).flat();\n\n return findings.sort((left, right) =>\n left.file.localeCompare(right.file) ||\n (left.exportName ?? \"\").localeCompare(right.exportName ?? \"\") ||\n left.code.localeCompare(right.code)\n );\n}\n\nexport function formatStaticPolicyFindings(findings: StaticPolicyFinding[]) {\n return [\n \"Demiurge found invalid static route policy:\",\n ...findings.map(formatStaticPolicyFinding),\n ].join(\"\\n\");\n}\n\nfunction formatStaticPolicyFinding(finding: StaticPolicyFinding) {\n const source = finding.exportName\n ? `${finding.file} export ${finding.exportName}`\n : finding.file;\n return `${source}: [${finding.code}] ${finding.message}`;\n}\n\nfunction toRouteKey(routesDir: string, file: string) {\n const relativePath = relative(routesDir, file).split(sep).join(\"/\");\n return `./routes/${relativePath}`;\n}\n"],"names":["PACKAGE_NAME","generateRoutes","options","routeFiles","findRouteFiles","middleware","file","toMiddlewareInfo","value","routes","toRouteInfo","route","a","b","source","renderRoutesModule","mkdir","dirname","writeFile","directory","readdir","entry","resolve","routesDir","fileSegments","relative","sep","urlSegments","segment","isRouteGroupSegment","pathVars","isAttachedFileForRoute","importPath","attachedFileSegments","routeFileSegments","index","renderMiddlewareImport","_entry","renderMiddlewareContextAlias","renderPathVarsEntry","renderConcretePathEntry","renderRequestContextEntry","pathType","name","toConcretePathType","contexts","context","pattern","part","escapeTemplate","httpMethods","responseHelpers","verifyRoutePolicyFile","readFile","verifyRoutePolicySource","loader","transformed","transformWithEsbuild","extracted","extractRouteModule","validateExtractedRouteModule","code","ast","parseAst","imports","collectCoreImports","constants","collectConstants","declarations","collectVariableInitializers","exports","collectNamedExports","capabilities","declaredMethods","policy","exportName","localName","initializer","extractRoutePolicy","isHttpMethod","capability","extractCapability","statement","asNodeArray","declaration","asNode","declarator","identifierName","specifier","exported","propertyName","local","node","helper","arguments_","optionsNode","cors","evaluateObjectProperty","securityPolicy","isRecord","property","unresolved","item","evaluateLiteral","argument","result","valueNode","document","extractSecurityPolicy","callee","objectName","preset","security","routeModule","findings","availableMethods","validateCorsPolicy","error","finding","errorMessage","method","validateRateLimit","createSecurityHeaders","toFragmentDocument","endpoints","declaresEndpoints","reportTo","validateRateLimitPolicy","message","imported","quasi","values","element","child","fallback","CLIENT_ENTRY_ID","DEV_CLIENT_ENTRY_PATH","RESOLVED_CLIENT_ENTRY_ID","SERVER_ENTRY_ID","RESOLVED_SERVER_ENTRY_ID","DEFAULT_TYPED_ROUTES_OUTPUT","demiurge","root","isBuild","viteNoncePlaceholder","createCspNonce","config","environment","createViteConfig","id","createClientEntrySource","createServerEntrySource","transformOptions","isRouteSource","protectSsrImportMeta","stripClientPageData","_outputOptions","bundle","styles","asset","clientEntry","createDocumentHtml","assertRootNotFoundRoute","verifyRoutePolicies","formatStaticPolicyFindings","generateTypedRoutes","server","reportPolicyFindings","formatStaticPolicyFinding","policyVerificationTimer","policyVerificationRun","runPolicyVerification","startPolicyVerification","policyVerificationDebounceMs","isRouteFile","event","optimizeImage","createDevImageOptimizer","serveFont","createFontAssetHandler","request","response","next","webRequest","toWebRequest","UnsupportedMethodError","writeNotImplemented","font","writeWebResponse","image","manifest","loadDevManifest","documentSecurity","createDevDocumentSecurity","handleDevRequest","createDevRuntimeOptions","applyDevDocumentSecurity","warnMissingRootNotFound","notFoundResponse","renderNotFoundResponse","createDevFallbackOptions","candidate","alias","editor","MagicString","dataRanges","documentRanges","findDocumentContributionRanges","serverImports","walkAst","isServerOnlyImport","isPageCallee","serverRanges","removalRanges","localNames","masked","maskRanges","leakedName","escapeRegExp","replaceRanges","range","documentContributionNames","exportedLocals","ranges","init","routesRoot","pathFromRoutes","visit","key","characters","end","start","replacement","left","right","stylesImport","createStylesImport","createRouteMapSource","exportRoutes","eagerModules","includeServerOnly","routesGlobs","toRootAbsoluteGlobs","routesPrefix","toRootAbsolutePrefix","serverOnlyRouteFiles","base","globs","fileName","stylesFile","resolvedStylesFile","existsSync","publicDir","optimizerPath","createImageOptimizer","pathname","parseImageVariantPath","transformDocument","createDevSsrOptions","match","renderOptions","renderStreamingPageResponse","html","renderPageDocument","nonce","shieldNonce","shielded","shieldViteNonceTargets","replaceNonceAttribute","lowerHtml","cursor","output","tagStart","commentEnd","tagEnd","findHtmlTagEnd","openingTag","addNonceAttribute","closeStart","quote","character","insertion","current","contentType","csp","withScriptNonce","addCspSource","withStyleNonce","allowsUnsafeInline","directiveNames","fallbackDirectiveName","directives","directive","directiveIndex","findCspDirectiveIndex","defaultDirective","currentName","currentSources","updatedDirective","sources","DEV_MANIFEST","carrier","cached","createRouteManifest","createDevRouteImporters","warnedRoots","missingRootNotFoundMessage","join","routesDirOption","files","pageRoute","findPageRouteFile","missingRootNotFoundBuildMessage","declaresPageRoute","PACKAGE_NAME_PATTERN","DEMIURGE_NAMED_IMPORT","locals","binding","body","notFoundFile","entrySrc","lang","links","metadata","scripts","title","renderDocument","outputFile","routeKey","toRouteKey","url","findRouteMatch","handleRequestWithManifest","policyVerificationConcurrency","mapWithConcurrency","items","limit","task","results","workers"],"mappings":";;;;;;;;;;;;AASO,MAAMA,IAAe;ACa5B,eAAsBC,GAAeC,GAAgC;AACnE,QAAMC,IAAa,MAAMC,GAAeF,EAAQ,SAAS,GACnDG,IAAaF,EAChB,IAAI,CAACG,MAASC,GAAiBL,GAASI,CAAI,CAAC,EAC7C,OAAO,CAACE,MAAmC,EAAQA,CAAM,GACtDC,IAASN,EACZ,IAAI,CAACG,MAASI,GAAYR,EAAQ,WAAWI,GAAMD,CAAU,CAAC,EAC9D,OAAO,CAACM,MAA8B,EAAQA,CAAM,EACpD,KAAK,CAACC,GAAGC,MAAMD,EAAE,QAAQ,cAAcC,EAAE,OAAO,CAAC,GAE9CC,IAASC,GAAmBN,GAAQJ,CAAU;AAEpD,eAAMW,GAAMC,EAAQf,EAAQ,UAAU,GAAG,EAAE,WAAW,IAAM,GAC5D,MAAMgB,GAAUhB,EAAQ,YAAYY,CAAM,GAEnC;AAAA,IACL,QAAAL;AAAA,IACA,QAAAK;AAAA,EAAA;AAEJ;AAEA,eAAeV,GAAee,GAAmB;AAM/C,UALgB,MAAMC,GAAQD,GAAW;AAAA,IACvC,WAAW;AAAA,IACX,eAAe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pO,CAAS,KACP,MAAMuT;AAAA,IACtB,MAAM1U,EAAemB,CAAS;AAAA,IAC9BsT;AAAA,IACAzR;AAAA,EAAA,GACC,KAAA,EAEa;AAAA,IAAK,CAACqL,GAAMC,MAC1BD,EAAK,KAAK,cAAcC,EAAM,IAAI,MACjCD,EAAK,cAAc,IAAI,cAAcC,EAAM,cAAc,EAAE,KAC5DD,EAAK,KAAK,cAAcC,EAAM,IAAI;AAAA,EAAA,IAVD,CAAA;AAYrC;AAEO,SAAStE,GAA2BlD,GAAiC;AAC1E,SAAO;AAAA,IACL;AAAA,IACA,GAAGA,EAAS,IAAIsD,EAAyB;AAAA,EAAA,EACzC,KAAK;AAAA,CAAI;AACb;AAEA,SAASA,GAA0BlD,GAA8B;AAI/D,SAAO,GAHQA,EAAQ,aACnB,GAAGA,EAAQ,IAAI,WAAWA,EAAQ,UAAU,KAC5CA,EAAQ,IACI,MAAMA,EAAQ,IAAI,KAAKA,EAAQ,OAAO;AACxD;AAEA,SAASmN,GAAWlT,GAAmBjB,GAAc;AAEnD,SAAO,YADcmB,EAASF,GAAWjB,CAAI,EAAE,MAAMoB,CAAG,EAAE,KAAK,GAAG,CACnC;AACjC;"}
@@ -3,21 +3,39 @@ import type { LinkTag, ResolvedMetadata, ScriptTag } from "../document";
3
3
  import { type RouteManifest } from "../router";
4
4
  import { handleRequestWithManifest } from "../server";
5
5
  import { type RouteImporter } from "../route";
6
+ import type { FontContribution } from "../platform/fonts";
7
+ import type { ImagePolicy } from "../platform/images";
8
+ import { type StaticPolicyFinding } from "./policy-verification";
9
+ import type { StaticFileHeaderPatternRule, VercelStaticDeployment } from "../static";
6
10
  export type DemiurgeVitePluginOptions = {
7
11
  document?: {
8
12
  lang?: string;
9
13
  title?: string;
10
14
  };
15
+ fonts?: FontContribution;
16
+ images?: ImagePolicy;
11
17
  routesDir?: string;
18
+ static?: {
19
+ deployment?: VercelStaticDeployment;
20
+ headers?: readonly StaticFileHeaderPatternRule[];
21
+ };
12
22
  styles?: false | string;
13
23
  typedRoutes?: boolean | {
14
24
  outputFile?: string;
15
25
  };
16
26
  };
27
+ export type DemiurgeVitePluginApi = {
28
+ demiurge: true;
29
+ fonts?: FontContribution;
30
+ images?: ImagePolicy;
31
+ staticDeployment?: VercelStaticDeployment;
32
+ staticFileHeaders?: readonly StaticFileHeaderPatternRule[];
33
+ };
17
34
  export declare function demiurge(options?: DemiurgeVitePluginOptions): Plugin;
18
35
  export declare function stripClientPageData(code: string): string;
19
36
  export declare function createClientEntrySource(root: string, options?: DemiurgeVitePluginOptions): string;
20
37
  export declare function createServerEntrySource(root: string, options?: DemiurgeVitePluginOptions): string;
38
+ export declare function createDevImageOptimizer(server: ViteDevServer, options: DemiurgeVitePluginOptions): import("../node").StaticFileHandler;
21
39
  export declare function assertRootNotFoundRoute(root: string, options?: DemiurgeVitePluginOptions): Promise<void>;
22
40
  export declare function declaresPageRoute(source: string): boolean;
23
41
  export declare function missingRootNotFoundBuildMessage(routesDir: string, pageRoute: string): string;
@@ -34,4 +52,6 @@ export declare function createDocumentHtml({ entrySrc, lang, links, metadata, no
34
52
  }): string;
35
53
  export declare function createDevRouteImporters(server: ViteDevServer, routesDir: string): Promise<Record<string, RouteImporter>>;
36
54
  export declare function handleDevRequest(manifest: RouteManifest, request: Request, options?: Parameters<typeof handleRequestWithManifest>[2]): Promise<Response | "next">;
55
+ export declare function verifyRoutePolicies(root: string, options?: DemiurgeVitePluginOptions): Promise<StaticPolicyFinding[]>;
56
+ export declare function formatStaticPolicyFindings(findings: StaticPolicyFinding[]): string;
37
57
  //# sourceMappingURL=plugin.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/vite/plugin.ts"],"names":[],"mappings":"AAKA,OAAO,EAGL,KAAK,MAAM,EAEX,KAAK,aAAa,EACnB,MAAM,MAAM,CAAC;AAEd,OAAO,KAAK,EACV,OAAO,EACP,gBAAgB,EAChB,SAAS,EACV,MAAM,aAAa,CAAC;A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AAED,wBAAgB,0BAA0B,CAAC,YAAY,EAAE,MAAM,UAS9D;AAED,wBAAgB,kBAAkB,CAAC,EACjC,QAAQ,EACR,IAAI,EACJ,KAAK,EACL,QAAQ,EACR,KAAK,EACL,OAAO,EACP,MAAM,EACN,KAAK,GACN,EAAE;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC;IAClB,QAAQ,CAAC,EAAE,gBAAgB,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,UAWA;AAwBD,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,aAAa,EACrB,SAAS,EAAE,MAAM,0CAYlB;AAED,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,aAAa,EACvB,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAAC,CAAC,CAAM,8BAU9D;AA0CD,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,yBAA8B,kCAgBxC;AAED,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,mBAAmB,EAAE,UAKzE"}
@@ -0,0 +1,10 @@
1
+ export type StaticPolicyFinding = {
2
+ code: "cors-invalid" | "cors-method-unavailable" | "rate-limit-invalid" | "security-header-render-failed";
3
+ exportName?: string;
4
+ file: string;
5
+ message: string;
6
+ severity: "error";
7
+ };
8
+ export declare function verifyRoutePolicyFile(file: string): Promise<StaticPolicyFinding[]>;
9
+ export declare function verifyRoutePolicySource(source: string, file: string): Promise<StaticPolicyFinding[]>;
10
+ //# sourceMappingURL=policy-verification.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy-verification.d.ts","sourceRoot":"","sources":["../../src/vite/policy-verification.ts"],"names":[],"mappings":"AAsBA,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,EAAE,cAAc,GAAG,yBAAyB,GAAG,oBAAoB,GACrE,+BAA+B,CAAC;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,OAAO,CAAC;CACnB,CAAC;AAmCF,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,MAAM,kCAGvD;AAED,wBAAsB,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,kCAUzE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@demiurgejs/core",
3
- "version": "0.1.1",
3
+ "version": "0.2.0-beta.2",
4
4
  "description": "A React framework for secure routing, server rendering, and framework-managed HTML documents.",
5
5
  "license": "MIT",
6
6
  "author": "North Shore Software Labs",
@@ -19,10 +19,15 @@
19
19
  "router",
20
20
  "ssr",
21
21
  "vite",
22
- "node"
22
+ "node",
23
+ "edge"
23
24
  ],
24
25
  "type": "module",
26
+ "bin": {
27
+ "demiurge": "./bin/demiurge.mjs"
28
+ },
25
29
  "files": [
30
+ "bin",
26
31
  "dist",
27
32
  "LICENSE",
28
33
  "README.md"
@@ -32,6 +37,10 @@
32
37
  "types": "./dist/index.d.ts",
33
38
  "default": "./dist/index.js"
34
39
  },
40
+ "./adapter/testing": {
41
+ "types": "./dist/adapter/testing.d.ts",
42
+ "default": "./dist/adapter/testing.js"
43
+ },
35
44
  "./internal/testing": {
36
45
  "types": "./dist/internal/testing.d.ts",
37
46
  "default": "./dist/internal/testing.js"
@@ -48,6 +57,18 @@
48
57
  "types": "./dist/node/index.d.ts",
49
58
  "default": "./dist/node/index.js"
50
59
  },
60
+ "./edge": {
61
+ "types": "./dist/edge/index.d.ts",
62
+ "default": "./dist/edge/index.js"
63
+ },
64
+ "./kv": {
65
+ "types": "./dist/kv/index.d.ts",
66
+ "default": "./dist/kv/index.js"
67
+ },
68
+ "./redis": {
69
+ "types": "./dist/redis/index.d.ts",
70
+ "default": "./dist/redis/index.js"
71
+ },
51
72
  "./static": {
52
73
  "types": "./dist/static/index.d.ts",
53
74
  "default": "./dist/static/index.js"
@@ -69,11 +90,23 @@
69
90
  "provenance": true
70
91
  },
71
92
  "peerDependencies": {
93
+ "@vercel/routing-utils": "6.5.0",
94
+ "ioredis": "^5.0.0",
72
95
  "react": "^19.0.0",
73
96
  "react-dom": "^19.0.0",
97
+ "sharp": "^0.35.0",
74
98
  "vite": "^6.0.7"
75
99
  },
76
100
  "peerDependenciesMeta": {
101
+ "@vercel/routing-utils": {
102
+ "optional": true
103
+ },
104
+ "ioredis": {
105
+ "optional": true
106
+ },
107
+ "sharp": {
108
+ "optional": true
109
+ },
77
110
  "vite": {
78
111
  "optional": true
79
112
  }
@@ -83,11 +116,14 @@
83
116
  "@types/node": "^22.13.0",
84
117
  "@types/react": "^19.0.2",
85
118
  "@types/react-dom": "^19.0.2",
119
+ "@vercel/routing-utils": "6.5.0",
86
120
  "@vitejs/plugin-react": "^4.3.4",
87
121
  "@vitest/coverage-v8": "^4.1.10",
122
+ "ioredis": "^5.4.1",
88
123
  "jsdom": "^30.0.1",
89
124
  "react": "^19.0.0",
90
125
  "react-dom": "^19.0.0",
126
+ "sharp": "^0.35.3",
91
127
  "typescript": "^5.7.2",
92
128
  "vite": "^6.0.7",
93
129
  "vitest": "^4.1.10"