@demiurgejs/core 0.2.0-beta.2 → 0.2.0-beta.3

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 (106) hide show
  1. package/dist/adapter/testing.js.map +1 -1
  2. package/dist/browser/file-router.d.ts.map +1 -1
  3. package/dist/chunks/{document-shell-D1xo6cEA.js → document-shell-WoM8yZlR.js} +2 -2
  4. package/dist/chunks/{document-shell-D1xo6cEA.js.map → document-shell-WoM8yZlR.js.map} +1 -1
  5. package/dist/chunks/{image-codec-BGTx_t5K.js → image-codec-Di53WpcH.js} +2 -2
  6. package/dist/chunks/{image-codec-BGTx_t5K.js.map → image-codec-Di53WpcH.js.map} +1 -1
  7. package/dist/chunks/{images-B9MqcjSA.js → images-Edar3eU1.js} +2 -2
  8. package/dist/chunks/{images-B9MqcjSA.js.map → images-Edar3eU1.js.map} +1 -1
  9. package/dist/chunks/{request-metadata-D5NrT8ks.js → request-metadata-DaIYq4Ea.js} +214 -179
  10. package/dist/chunks/request-metadata-DaIYq4Ea.js.map +1 -0
  11. package/dist/chunks/{streaming-BQ1bykDo.js → streaming-D0fGAuiO.js} +5 -5
  12. package/dist/chunks/streaming-D0fGAuiO.js.map +1 -0
  13. package/dist/chunks/{testing-B_iMFYz_.js → testing-CRflAw4X.js} +1228 -1074
  14. package/dist/chunks/testing-CRflAw4X.js.map +1 -0
  15. package/dist/data/cache.d.ts +8 -0
  16. package/dist/data/cache.d.ts.map +1 -1
  17. package/dist/data/idempotency.d.ts.map +1 -1
  18. package/dist/data/index.d.ts +3 -1
  19. package/dist/data/index.d.ts.map +1 -1
  20. package/dist/data/testing.d.ts.map +1 -1
  21. package/dist/data/testing.js +94 -72
  22. package/dist/data/testing.js.map +1 -1
  23. package/dist/data/tiered.d.ts +7 -0
  24. package/dist/data/tiered.d.ts.map +1 -0
  25. package/dist/document/deferred-scripts.d.ts.map +1 -1
  26. package/dist/document/hydration.d.ts.map +1 -1
  27. package/dist/document/index.d.ts +1 -0
  28. package/dist/document/index.d.ts.map +1 -1
  29. package/dist/document/trusted-types.d.ts +10 -0
  30. package/dist/document/trusted-types.d.ts.map +1 -0
  31. package/dist/edge/index.js +3 -3
  32. package/dist/index.d.ts +6 -6
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +768 -432
  35. package/dist/index.js.map +1 -1
  36. package/dist/internal/testing.js +9 -9
  37. package/dist/kv/index.d.ts +2 -0
  38. package/dist/kv/index.d.ts.map +1 -1
  39. package/dist/kv/index.js +71 -48
  40. package/dist/kv/index.js.map +1 -1
  41. package/dist/kv/rate-limit-store.d.ts +8 -0
  42. package/dist/kv/rate-limit-store.d.ts.map +1 -0
  43. package/dist/kv/store.d.ts.map +1 -1
  44. package/dist/node/http.d.ts.map +1 -1
  45. package/dist/node/image.d.ts.map +1 -1
  46. package/dist/node/index.d.ts.map +1 -1
  47. package/dist/node/index.js +3 -3
  48. package/dist/node/index.js.map +1 -1
  49. package/dist/node/static.d.ts.map +1 -1
  50. package/dist/node/streaming.d.ts.map +1 -1
  51. package/dist/platform/images.d.ts.map +1 -1
  52. package/dist/platform/index.d.ts +5 -1
  53. package/dist/platform/index.d.ts.map +1 -1
  54. package/dist/platform/observability.d.ts +2 -1
  55. package/dist/platform/observability.d.ts.map +1 -1
  56. package/dist/platform/web-vitals-client.d.ts +32 -0
  57. package/dist/platform/web-vitals-client.d.ts.map +1 -0
  58. package/dist/platform/web-vitals.d.ts +78 -0
  59. package/dist/platform/web-vitals.d.ts.map +1 -0
  60. package/dist/redis/index.d.ts +2 -0
  61. package/dist/redis/index.d.ts.map +1 -1
  62. package/dist/redis/index.js +84 -46
  63. package/dist/redis/index.js.map +1 -1
  64. package/dist/redis/rate-limit-store.d.ts +8 -0
  65. package/dist/redis/rate-limit-store.d.ts.map +1 -0
  66. package/dist/redis/store.d.ts.map +1 -1
  67. package/dist/route/action.d.ts.map +1 -1
  68. package/dist/route/middleware.d.ts.map +1 -1
  69. package/dist/route/response.d.ts.map +1 -1
  70. package/dist/router/index.d.ts +1 -1
  71. package/dist/router/index.d.ts.map +1 -1
  72. package/dist/router/manifest.d.ts +1 -0
  73. package/dist/router/manifest.d.ts.map +1 -1
  74. package/dist/security/cookies.d.ts +26 -0
  75. package/dist/security/cookies.d.ts.map +1 -0
  76. package/dist/security/env.d.ts.map +1 -1
  77. package/dist/security/fetch-metadata.d.ts +29 -0
  78. package/dist/security/fetch-metadata.d.ts.map +1 -0
  79. package/dist/security/index.d.ts +5 -1
  80. package/dist/security/index.d.ts.map +1 -1
  81. package/dist/security/policy.d.ts.map +1 -1
  82. package/dist/security/rate-limit.d.ts +6 -3
  83. package/dist/security/rate-limit.d.ts.map +1 -1
  84. package/dist/security/request.d.ts.map +1 -1
  85. package/dist/security/types.d.ts +72 -3
  86. package/dist/security/types.d.ts.map +1 -1
  87. package/dist/server/index.d.ts +1 -1
  88. package/dist/server/index.d.ts.map +1 -1
  89. package/dist/server/request-handler.d.ts +6 -2
  90. package/dist/server/request-handler.d.ts.map +1 -1
  91. package/dist/static/index.d.ts.map +1 -1
  92. package/dist/static/index.js +4 -4
  93. package/dist/static/index.js.map +1 -1
  94. package/dist/vite/index.d.ts +3 -0
  95. package/dist/vite/index.d.ts.map +1 -1
  96. package/dist/vite/index.js +1030 -666
  97. package/dist/vite/index.js.map +1 -1
  98. package/dist/vite/plugin.d.ts +2 -0
  99. package/dist/vite/plugin.d.ts.map +1 -1
  100. package/dist/vite/policy-verification.d.ts.map +1 -1
  101. package/dist/vite/route-audit.d.ts +50 -0
  102. package/dist/vite/route-audit.d.ts.map +1 -0
  103. package/package.json +1 -1
  104. package/dist/chunks/request-metadata-D5NrT8ks.js.map +0 -1
  105. package/dist/chunks/streaming-BQ1bykDo.js.map +0 -1
  106. package/dist/chunks/testing-B_iMFYz_.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/static/images.ts","../../src/static/preview.ts","../../src/static/vercel.ts","../../src/static/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { relative, resolve, sep } from \"node:path\";\nimport {\n negotiateImageFormat,\n transformImage,\n} from \"../platform/image-codec\";\nimport {\n collectImageVariantPaths,\n defaultImageOptimizerPath,\n parseImageVariantPath,\n} from \"../platform/image-url\";\nimport { isAllowedImageSource, type ImagePolicy } from \"../platform/images\";\n\nexport type EmittedImageVariant = {\n body: Uint8Array;\n file: string;\n};\n\nexport type EmitImageVariantsOptions = {\n // Every document that the build rendered. A variant reaches the output\n // only when a document references it.\n documents: readonly string[];\n // The directory that already holds the client build, including every file\n // that the Vite public directory contributed.\n outDir: string;\n policy?: ImagePolicy;\n};\n\n// The static build owns every byte it publishes. It reads the variant paths\n// back out of the rendered documents. No state then has to cross the boundary\n// between the application bundle and the build process.\nexport async function emitImageVariants(\n options: EmitImageVariantsOptions,\n): Promise<EmittedImageVariant[]> {\n const outDir = resolve(options.outDir);\n const policy = options.policy ?? {};\n const optimizerPath = policy.optimizerPath ?? defaultImageOptimizerPath;\n const paths = new Set(\n options.documents.flatMap((document) =>\n collectImageVariantPaths(document, optimizerPath)\n ),\n );\n const emitted: EmittedImageVariant[] = [];\n const sources = new Map<string, Uint8Array>();\n\n for (const pathname of [...paths].sort()) {\n const descriptor = parseImageVariantPath(pathname, optimizerPath);\n\n if (!descriptor) {\n throw new Error(\n `Static output references image variant ${JSON.stringify(pathname)}, which does not describe a transform the build can emit.`,\n );\n }\n\n if (!isAllowedImageSource(descriptor.src, policy)) {\n throw new Error(\n `Image source ${JSON.stringify(descriptor.src)} is not allowed by the image policy.`,\n );\n }\n\n const sourceFile = resolveSourceFile(outDir, descriptor.src);\n let source = sources.get(sourceFile);\n\n if (!source) {\n source = await readSourceImage(sourceFile, descriptor.src);\n sources.set(sourceFile, source);\n }\n\n const encoded = await transformImage(source, {\n format: negotiateImageFormat(descriptor, null),\n quality: descriptor.quality,\n width: descriptor.width,\n });\n\n emitted.push({ body: encoded.body, file: pathname.slice(1) });\n }\n\n return emitted;\n}\n\n// A document that a static build publishes cannot reach a request-time\n// optimizer. The build stops rather than publish a dead image URL.\nexport function assertNoOptimizerImages(\n documents: readonly string[],\n policy: ImagePolicy = {},\n) {\n const optimizerPath = policy.optimizerPath ?? defaultImageOptimizerPath;\n const pattern = new RegExp(`${optimizerPath.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\?`);\n\n for (const document of documents) {\n if (pattern.test(document)) {\n throw new Error(\n 'Static output references the request-time image optimizer, which a static build cannot serve. Set loader: \"static\" in the image policy, or deploy a runtime adapter.',\n );\n }\n }\n}\n\nasync function readSourceImage(sourceFile: string, src: string) {\n try {\n return new Uint8Array(await readFile(sourceFile));\n } catch (error) {\n throw new Error(\n `Demiurge could not read the source image ${JSON.stringify(src)} from the build output.`,\n { cause: error },\n );\n }\n}\n\nfunction resolveSourceFile(outDir: string, src: string) {\n let decoded: string;\n\n try {\n decoded = decodeURIComponent(src);\n } catch {\n throw new Error(`Image source is not valid UTF-8: ${JSON.stringify(src)}.`);\n }\n\n const file = resolve(outDir, `.${decoded}`);\n\n if (relative(outDir, file).split(sep).includes(\"..\")) {\n throw new Error(\n `Image source escaped the build output directory: ${JSON.stringify(src)}.`,\n );\n }\n\n return file;\n}\n","import { createServer, type Server } from \"node:http\";\nimport { readFile } from \"node:fs/promises\";\nimport { extname, relative, resolve, sep } from \"node:path\";\nimport type {\n StaticOutputEntry,\n StaticOutputFileHeaderRule,\n StaticOutputManifest,\n} from \"./index\";\n\nconst STATIC_MANIFEST_FILE = \"demiurge-static-manifest.json\";\n\nexport type StaticPreviewOptions = {\n host?: string;\n outDir: string;\n port?: number;\n};\n\nconst contentTypes: Record<string, string> = {\n \".avif\": \"image/avif\",\n \".css\": \"text/css; charset=utf-8\",\n \".gif\": \"image/gif\",\n \".html\": \"text/html; charset=utf-8\",\n \".ico\": \"image/x-icon\",\n \".jpeg\": \"image/jpeg\",\n \".jpg\": \"image/jpeg\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".png\": \"image/png\",\n \".svg\": \"image/svg+xml\",\n \".txt\": \"text/plain; charset=utf-8\",\n \".webmanifest\": \"application/manifest+json\",\n \".webp\": \"image/webp\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n};\n\nexport async function createStaticPreviewServer(\n options: StaticPreviewOptions,\n): Promise<Server> {\n const root = resolve(options.outDir);\n const manifest = parseStaticManifest(\n await readFile(resolve(root, STATIC_MANIFEST_FILE), \"utf8\"),\n );\n const entries = new Map(\n manifest.entries.map((entry) => [entry.pathname, entry]),\n );\n const entriesByFile = new Map(\n manifest.entries.map((entry) => [entry.file, entry]),\n );\n const rules = manifest.fileHeaderRules.map((rule) => ({\n ...rule,\n expression: new RegExp(rule.pattern),\n }));\n\n const server = createServer(async (request, response) => {\n try {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n response.writeHead(405, { allow: \"GET, HEAD\" });\n response.end();\n return;\n }\n\n const url = new URL(request.url ?? \"/\", \"http://demiurge.local\");\n let pathname: string;\n\n try {\n pathname = decodeURIComponent(url.pathname);\n } catch {\n response.writeHead(400, {\n \"content-type\": \"text/plain; charset=utf-8\",\n });\n response.end(\"The request path is not valid UTF-8.\");\n return;\n }\n\n const routePath = pathname.replace(/\\/$/, \"\") || \"/\";\n const entry = entries.get(routePath);\n\n if (entry) {\n await writeEntry(root, entry, request.method, response);\n return;\n }\n\n const file = resolvePreviewFile(root, pathname);\n if (file) {\n try {\n const declaredFile = relative(root, file).split(sep).join(\"/\");\n const declaredEntry = entriesByFile.get(declaredFile);\n if (declaredEntry) {\n await writeEntry(root, declaredEntry, request.method, response);\n return;\n }\n\n const body = await readFile(file);\n const type = contentTypes[extname(file).toLowerCase()];\n if (type) response.setHeader(\"content-type\", type);\n\n const fileName = pathname.split(\"/\").at(-1) ?? \"\";\n const rule = rules.find(({ expression }) => expression.test(fileName));\n applyHeaders(response, rule?.headers ?? {});\n response.writeHead(200);\n response.end(request.method === \"HEAD\" ? undefined : body);\n return;\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n }\n }\n\n const fallback = entries.get(\"*\");\n if (!fallback) {\n response.writeHead(404);\n response.end();\n return;\n }\n\n await writeEntry(root, fallback, request.method, response);\n } catch {\n response.writeHead(500, {\n \"content-type\": \"text/plain; charset=utf-8\",\n });\n response.end(\"Demiurge could not serve the static output.\");\n }\n });\n\n await new Promise<void>((resolvePromise, reject) => {\n const onError = (error: Error) => reject(error);\n server.once(\"error\", onError);\n server.listen(\n options.port ?? 4173,\n options.host ?? \"localhost\",\n () => {\n server.off(\"error\", onError);\n resolvePromise();\n },\n );\n });\n\n return server;\n}\n\nasync function writeEntry(\n root: string,\n entry: StaticOutputEntry,\n method: string | undefined,\n response: import(\"node:http\").ServerResponse,\n) {\n const file = resolveDeclaredFile(root, entry.file);\n const body = await readFile(file);\n applyHeaders(response, entry.headers);\n response.writeHead(entry.status);\n response.end(method === \"HEAD\" ? undefined : body);\n}\n\nfunction applyHeaders(\n response: import(\"node:http\").ServerResponse,\n headers: Record<string, string>,\n) {\n for (const [name, value] of Object.entries(headers)) {\n response.setHeader(name, value);\n }\n}\n\nfunction resolvePreviewFile(root: string, pathname: string) {\n if (pathname.endsWith(\"/\")) return undefined;\n return resolveContained(root, `.${pathname}`);\n}\n\nfunction resolveDeclaredFile(root: string, file: string) {\n const resolved = resolveContained(root, file);\n if (!resolved) {\n throw new Error(`Static preview file is outside the output directory: ${JSON.stringify(file)}.`);\n }\n return resolved;\n}\n\nfunction resolveContained(root: string, file: string) {\n if (\n !file ||\n file.startsWith(\"/\") ||\n file.startsWith(\"\\\\\") ||\n file.split(/[\\\\/]/).includes(\"..\")\n ) {\n return undefined;\n }\n const resolved = resolve(root, file);\n const pathFromRoot = relative(root, resolved);\n return pathFromRoot !== \"..\" &&\n !pathFromRoot.startsWith(`..${sep}`)\n ? resolved\n : undefined;\n}\n\nfunction parseStaticManifest(source: string): StaticOutputManifest {\n let value: unknown;\n try {\n value = JSON.parse(source);\n } catch {\n throw new Error(\"The static output manifest is not valid JSON.\");\n }\n\n if (!isRecord(value) || value.adapter !== \"static\" || value.version !== 1) {\n throw new Error(\"The static output manifest has an unsupported format.\");\n }\n if (!Array.isArray(value.entries) || !Array.isArray(value.fileHeaderRules)) {\n throw new Error(\"The static output manifest does not contain header rules and entries.\");\n }\n\n const entries = value.entries.map(parseEntry);\n const fileHeaderRules = value.fileHeaderRules.map(parseRule);\n const pathnames = new Set<string>();\n for (const entry of entries) {\n if (pathnames.has(entry.pathname)) {\n throw new Error(`The static output manifest repeats pathname ${JSON.stringify(entry.pathname)}.`);\n }\n pathnames.add(entry.pathname);\n }\n\n return { adapter: \"static\", entries, fileHeaderRules, version: 1 };\n}\n\nfunction parseEntry(value: unknown): StaticOutputEntry {\n if (\n !isRecord(value) ||\n typeof value.file !== \"string\" ||\n typeof value.pathname !== \"string\" ||\n (value.status !== 200 && value.status !== 404) ||\n !isStringRecord(value.headers)\n ) {\n throw new Error(\"The static output manifest contains an invalid entry.\");\n }\n resolveDeclaredFile(\"/demiurge-manifest-root\", value.file);\n return {\n file: value.file,\n headers: value.headers,\n pathname: value.pathname,\n status: value.status,\n };\n}\n\nfunction parseRule(value: unknown): StaticOutputFileHeaderRule {\n if (\n !isRecord(value) ||\n typeof value.pattern !== \"string\" ||\n !isStringRecord(value.headers)\n ) {\n throw new Error(\"The static output manifest contains an invalid file header rule.\");\n }\n try {\n new RegExp(value.pattern);\n } catch {\n throw new Error(\"The static output manifest contains an invalid file header pattern.\");\n }\n return { headers: value.headers, pattern: value.pattern };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n return isRecord(value) && Object.values(value).every(\n (item) => typeof item === \"string\",\n );\n}\n\nfunction isMissingFile(error: unknown) {\n return error instanceof Error && \"code\" in error &&\n (error.code === \"EISDIR\" || error.code === \"ENOENT\");\n}\n","import {\n cp,\n mkdir,\n mkdtemp,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport {\n getTransformedRoutes,\n normalizeRoutes,\n type Header,\n type Route,\n} from \"@vercel/routing-utils\";\nimport { validateCorsPolicy } from \"../security\";\nimport type { CorsPolicy } from \"../security\";\nimport { CONTENT_HASHED_FILE_NAME_PATTERN } from \"../static-files\";\nimport type {\n StaticOutputEntry,\n StaticOutputManifest,\n} from \"./index\";\n\nconst CLIENT_MANIFEST_FILE = \"demiurge-manifest.json\";\nconst STATIC_MANIFEST_FILE = \"demiurge-static-manifest.json\";\n\nexport type VercelStaticCacheRule = {\n source: string;\n value: string;\n};\n\nexport type VercelStaticOptions = {\n cache?: VercelStaticCacheRule[];\n cors?: CorsPolicy;\n};\n\nexport type VercelStaticDeployment = {\n adapter: \"vercel\";\n cache: VercelStaticCacheRule[];\n cors?: CorsPolicy;\n};\n\nexport type VercelOutputRoute = Route;\n\nexport type VercelOutputConfig = {\n overrides: Record<string, {\n contentType?: string;\n path?: string;\n }>;\n routes: VercelOutputRoute[];\n version: 3;\n};\n\nexport function vercelStatic(\n options: VercelStaticOptions = {},\n): VercelStaticDeployment {\n return {\n adapter: \"vercel\",\n cache: options.cache?.map((rule) => ({\n source: rule.source,\n value: rule.value,\n })) ?? [],\n cors: options.cors,\n };\n}\n\nexport async function generateVercelStaticOutput(options: {\n deployment: VercelStaticDeployment;\n manifest: StaticOutputManifest;\n outDir: string;\n projectRoot: string;\n}) {\n validateVercelDeployment(options.deployment);\n\n const projectRoot = resolve(options.projectRoot);\n const sourceRoot = resolve(options.outDir);\n const outputRoot = resolve(projectRoot, \".vercel/output\");\n if (pathsOverlap(sourceRoot, outputRoot)) {\n throw new Error(\n \"The static output directory must not overlap the Vercel output directory.\",\n );\n }\n\n const outputParent = dirname(outputRoot);\n await mkdir(outputParent, { recursive: true });\n const stagingRoot = await mkdtemp(join(outputParent, \"output-demiurge-\"));\n\n try {\n const staticRoot = join(stagingRoot, \"static\");\n await cp(sourceRoot, staticRoot, {\n filter: (source) => {\n const file = relative(sourceRoot, source).split(sep).join(\"/\");\n return file !== CLIENT_MANIFEST_FILE && file !== STATIC_MANIFEST_FILE;\n },\n recursive: true,\n });\n await writeFile(\n join(stagingRoot, \"config.json\"),\n `${JSON.stringify(createVercelOutputConfig(\n options.manifest,\n options.deployment,\n ), null, 2)}\\n`,\n );\n\n await rm(outputRoot, { force: true, recursive: true });\n await rename(stagingRoot, outputRoot);\n } catch (error) {\n await rm(stagingRoot, { force: true, recursive: true });\n throw error;\n }\n\n return outputRoot;\n}\n\nexport function createVercelOutputConfig(\n manifest: StaticOutputManifest,\n deployment: VercelStaticDeployment,\n): VercelOutputConfig {\n const fallback = manifest.entries.find((entry) => entry.pathname === \"*\");\n if (!fallback) {\n throw new Error(\"Vercel output requires a static fallback entry.\");\n }\n\n const applicationRoutes = transformApplicationCache(deployment.cache);\n const corsOrigin = resolveVercelCorsOrigin(deployment.cors, manifest.origin);\n // Vercel adds `access-control-allow-origin: *` to every static response on\n // its own. This route states an explicit value instead, so a policy the\n // application never declared never reaches a deployed response. It comes\n // first so every later route in the sequence keeps it, the same pattern\n // the file header rules use for the cache policy.\n const routes: Route[] = [\n {\n continue: true,\n headers: { \"access-control-allow-origin\": corsOrigin },\n src: \"^/.*$\",\n },\n ];\n\n for (const entry of manifest.entries) {\n if (entry.pathname === \"*\") continue;\n const filePath = `/${entry.file}`;\n if (filePath !== entry.pathname) {\n routes.push({\n continue: true,\n dest: entry.pathname,\n src: exactPathPattern(filePath),\n });\n }\n }\n\n for (const entry of manifest.entries) {\n const headers = withoutContentType(entry.headers);\n if (Object.keys(headers).length === 0) continue;\n const pathname = entry.pathname === \"*\" ? `/${entry.file}` : entry.pathname;\n routes.push({\n continue: true,\n headers,\n src: exactPathPattern(pathname),\n });\n }\n\n routes.push(...applicationRoutes);\n\n for (const entry of manifest.entries) {\n if (entry.pathname === \"*\") {\n routes.push({\n dest: `/${entry.file}`,\n src: exactPathPattern(`/${entry.file}`),\n status: 404,\n });\n continue;\n }\n routes.push({\n dest: entry.pathname === \"/\" ? `/${entry.file}` : entry.pathname,\n src: exactPathPattern(entry.pathname),\n });\n }\n\n routes.push({ handle: \"hit\" });\n for (const rule of [...manifest.fileHeaderRules].reverse()) {\n routes.push({\n continue: true,\n headers: { ...rule.headers },\n src: translateFileHeaderPattern(rule.pattern),\n });\n }\n // Vercel applies every matching route in order, and a later route replaces\n // an earlier header of the same name. The hit phase runs after the routing\n // phase, so a framework file rule would replace the cache policy that the\n // application declared. The application rules repeat here to keep the last\n // word for a served file.\n routes.push(...applicationRoutes.map((route) => ({ ...route })));\n\n routes.push({ handle: \"error\" });\n const fallbackHeaders = withoutContentType(fallback.headers);\n if (Object.keys(fallbackHeaders).length > 0) {\n routes.push({\n continue: true,\n headers: fallbackHeaders,\n src: \"^/.*$\",\n });\n }\n routes.push(...applicationRoutes.map((route) => ({ ...route })));\n routes.push({ dest: `/${fallback.file}`, src: \"^/.*$\", status: 404 });\n\n const normalized = normalizeRoutes(routes);\n if (normalized.error || !normalized.routes) {\n throw new Error(\n `Vercel rejected the generated routes: ${normalized.error?.message ?? \"The route list is empty.\"}`,\n );\n }\n\n return {\n overrides: Object.fromEntries(\n manifest.entries.map((entry) => [entry.file, createOverride(entry)]),\n ),\n routes: normalized.routes,\n version: 3,\n };\n}\n\nfunction createOverride(entry: StaticOutputEntry) {\n const override: { contentType?: string; path?: string } = {};\n const contentType = entry.headers[\"content-type\"];\n if (contentType) override.contentType = contentType;\n\n if (entry.pathname !== \"*\") {\n const naturalPath = entry.file === \"index.html\"\n ? \"/\"\n : `/${entry.file}`;\n if (entry.pathname !== naturalPath) {\n override.path = entry.pathname.slice(1);\n }\n }\n\n return override;\n}\n\nfunction exactPathPattern(pathname: string) {\n const escaped = pathname.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return pathname === \"/\" ? \"^/$\" : `^${escaped}/?$`;\n}\n\nfunction withoutContentType(headers: Record<string, string>) {\n return Object.fromEntries(\n Object.entries(headers).filter(([name]) => name.toLowerCase() !== \"content-type\"),\n );\n}\n\nfunction translateFileHeaderPattern(pattern: string) {\n if (pattern === \".*\") {\n return \"^/.*$\";\n }\n if (pattern === CONTENT_HASHED_FILE_NAME_PATTERN.source) {\n return \"^/(?:.*/)?[^/]*-[A-Za-z0-9_-]{8,}\\\\.[A-Za-z0-9]+$\";\n }\n\n return `^/${translateFileNamePattern(pattern)}$`;\n}\n\n// Demiurge tests a static file header pattern against the file basename with\n// an unanchored `RegExp.test(...)`. The pattern can match anywhere in the\n// name. Vercel matches `src` against the complete pathname, which always\n// carries a directory prefix. This rebuilds the basename test as a pathname\n// pattern. A leading `^` pins the match to the start of the basename. A\n// trailing `$` pins it to the end. Without an anchor, the match can begin or\n// end anywhere in the basename.\nfunction translateFileNamePattern(pattern: string) {\n const startsAtBasename = pattern.startsWith(\"^\");\n const endsAtBasename = pattern.endsWith(\"$\") && !pattern.endsWith(\"\\\\$\");\n const body = pattern.slice(\n startsAtBasename ? 1 : 0,\n endsAtBasename ? -1 : undefined,\n );\n const prefix = startsAtBasename ? \"(?:.*/)?\" : \"(?:.*/)?[^/]*\";\n const suffix = endsAtBasename ? \"\" : \"[^/]*\";\n\n return `${prefix}(?:${body})${suffix}`;\n}\n\nfunction transformApplicationCache(cache: VercelStaticCacheRule[]) {\n const headers: Header[] = cache.map((rule) => ({\n headers: [{ key: \"cache-control\", value: rule.value }],\n source: rule.source,\n }));\n const transformed = getTransformedRoutes({ headers });\n if (transformed.error || !transformed.routes) {\n throw new Error(\n `A Vercel static header rule is not valid: ${transformed.error?.message ?? \"The route list is empty.\"}`,\n );\n }\n return transformed.routes;\n}\n\n// A static response cannot vary `access-control-allow-origin` by request, so\n// this resolves the declared policy to the single value the Vercel output\n// can serve. A declared policy always wins. Without one, the value falls\n// back to the build origin so a stray platform wildcard never survives.\nfunction resolveVercelCorsOrigin(\n cors: CorsPolicy | undefined,\n origin: string | undefined,\n): string {\n if (cors) {\n validateCorsPolicy(cors);\n\n if (cors.origins === \"*\") {\n return \"*\";\n }\n\n if (cors.origins.length === 1) {\n return cors.origins[0]!;\n }\n\n throw new Error(\n \"A Vercel static CORS policy must declare the wildcard origin or exactly one origin. A static response cannot vary access-control-allow-origin by request.\",\n );\n }\n\n if (!origin) {\n throw new Error(\n \"Vercel static output requires a build origin to emit access-control-allow-origin. Pass --origin, set SITE_ORIGIN, or declare a Vercel CORS policy.\",\n );\n }\n\n return origin;\n}\n\nfunction validateVercelDeployment(deployment: VercelStaticDeployment) {\n if (deployment.adapter !== \"vercel\" || !Array.isArray(deployment.cache)) {\n throw new Error(\"The Vercel static adapter configuration is not valid.\");\n }\n\n for (const rule of deployment.cache) {\n if (\n !rule ||\n typeof rule !== \"object\" ||\n typeof rule.source !== \"string\" ||\n !rule.source ||\n typeof rule.value !== \"string\" ||\n !rule.value\n ) {\n throw new Error(\"A Vercel static header rule is not valid.\");\n }\n }\n}\n\nfunction pathsOverlap(left: string, right: string) {\n const fromLeft = relative(left, right);\n const fromRight = relative(right, left);\n return isSameOrChildPath(fromLeft) || isSameOrChildPath(fromRight);\n}\n\nfunction isSameOrChildPath(pathname: string) {\n return !pathname ||\n (pathname !== \"..\" && !pathname.startsWith(`..${sep}`) &&\n !pathname.startsWith(\"/\"));\n}\n","import {\n cp,\n mkdir,\n mkdtemp,\n readFile,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport { defineAdapter } from \"../adapter\";\nimport { STRUCTURED_DATA_ATTRIBUTE } from \"../document/render\";\nimport {\n collectStaticRoutePaths,\n type RouteManifest,\n} from \"../router\";\nimport type { RouteCapability, RouteImporter, RouteModule } from \"../route\";\nimport {\n handleRequestWithManifest,\n renderNotFoundResponse,\n type RequestErrorReporter,\n type SsrOptions,\n} from \"../server\";\nimport {\n createMemoryRateLimitStore,\n createSecurityHeaders,\n cspHash,\n mergeSecurityPolicies,\n validateRouteModules,\n type SecurityHeaderPolicy,\n type SecurityPolicy,\n} from \"../security\";\nimport {\n CONTENT_HASHED_FILE_NAME_PATTERN,\n IMMUTABLE_FILE_CACHE_CONTROL,\n REVALIDATED_FILE_CACHE_CONTROL,\n} from \"../static-files\";\nimport { resolveFontAssets } from \"../platform/font-assets\";\nimport type { FontContribution } from \"../platform/fonts\";\nimport type { ImagePolicy } from \"../platform/images\";\nimport { assertNoOptimizerImages, emitImageVariants } from \"./images\";\n\nconst STATIC_MANIFEST_FILE = \"demiurge-static-manifest.json\";\n\nexport { createStaticPreviewServer } from \"./preview\";\nexport type { StaticPreviewOptions } from \"./preview\";\nexport {\n createVercelOutputConfig,\n generateVercelStaticOutput,\n vercelStatic,\n} from \"./vercel\";\nexport type {\n VercelOutputConfig,\n VercelOutputRoute,\n VercelStaticDeployment,\n VercelStaticCacheRule,\n VercelStaticOptions,\n} from \"./vercel\";\n\nexport const staticAdapter = defineAdapter({\n name: \"static\",\n capabilities: {\n staticOutput: true,\n },\n});\n\nexport type StaticOutputEntry = {\n file: string;\n headers: Record<string, string>;\n pathname: string;\n status: 200 | 404;\n};\n\nexport type StaticOutputManifest = {\n adapter: \"static\";\n entries: StaticOutputEntry[];\n fileHeaderRules: StaticOutputFileHeaderRule[];\n // Self-hosted font files and the stylesheet that declares them. They are\n // plain output files as well, so the framework file header rules cover them.\n fontFiles?: string[];\n // Optimized image files that the build emitted. They are plain output\n // files rather than route entries. A host therefore serves them with the\n // framework file header rules and no route rule of their own.\n imageFiles?: string[];\n // The normalized build origin. The Vercel static generator falls back to\n // this value for `access-control-allow-origin` when the deployment\n // declares no CORS policy of its own. A manifest that a caller builds by\n // hand, such as a static preview fixture, can omit this field.\n origin?: string;\n version: 1;\n};\n\nexport type StaticOutputFileHeaderRule = {\n headers: Record<string, string>;\n pattern: string;\n};\n\n// A pattern rule declares the same typed `SecurityHeaderPolicy` as the root\n// and route policies. One header keeps one spelling in every place that\n// declares it. `pattern` is an ECMAScript regular expression tested against\n// the file basename, the same convention as the framework's built-in file\n// header rules.\nexport type StaticFileHeaderPatternRule = {\n headers: SecurityHeaderPolicy;\n pattern: string;\n};\n\nexport type GenerateStaticOutputOptions = {\n // The font declaration that the application passed to the Vite plugin. The\n // build reads every source it names and publishes the file from this origin.\n fonts?: FontContribution;\n // The image policy that the application declared in the Vite plugin. The\n // build reads it to find and validate the variants it must emit.\n images?: ImagePolicy;\n onError?: RequestErrorReporter;\n origin?: string;\n outDir: string;\n // The project directory that a local font source resolves against. A font\n // file therefore does not have to sit in the public directory.\n root?: string;\n routes: Record<string, RouteImporter>;\n ssr?: SsrOptions;\n staticFileHeaders?: readonly StaticFileHeaderPatternRule[];\n};\n\ntype PendingOutput = StaticOutputEntry & {\n body: string;\n};\n\ntype PendingAsset = {\n body: Uint8Array;\n file: string;\n};\n\ntype OutputKind = \"document\" | \"resource\";\n\ntype PlannedOutput = {\n file: string;\n kind: OutputKind;\n pathname: string;\n};\n\nconst staticRouteLoadConcurrency = 8;\n\nasync function loadRouteModules(\n routes: Readonly<Record<string, RouteImporter>>,\n) {\n const entries = Object.entries(routes);\n const modules = new Array<readonly [string, RouteModule]>(entries.length);\n let next = 0;\n\n const workers = Array.from(\n { length: Math.min(staticRouteLoadConcurrency, entries.length) },\n async () => {\n while (next < entries.length) {\n const index = next++;\n const [file, load] = entries[index]!;\n\n try {\n modules[index] = [file, await load()];\n } catch (error) {\n throw new Error(\n `Demiurge could not load route module ${JSON.stringify(file)}.`,\n { cause: error },\n );\n }\n }\n },\n );\n\n await Promise.all(workers);\n\n return Object.fromEntries(modules) as Record<string, RouteModule>;\n}\n\nexport async function generateStaticOutput(\n options: GenerateStaticOutputOptions,\n): Promise<StaticOutputManifest> {\n const routeModules = await loadRouteModules(options.routes);\n const manifest = validateRouteModules(routeModules, {\n adapter: staticAdapter,\n });\n\n const origin = normalizeOrigin(options.origin);\n const outDir = resolve(options.outDir);\n const routeKinds = await validateStaticRoutes(manifest);\n const paths = await collectStaticRoutePaths(manifest, {\n includeResources: true,\n });\n\n assertStaticPageApp(\n manifest,\n paths.filter((path) => routeKinds.get(path.file) === \"document\").length,\n );\n\n const outputEntries = planOutputEntries(\n paths.map((path) => ({\n kind: routeKinds.get(path.file) ?? \"resource\",\n pathname: path.pathname,\n })),\n );\n const rateLimitStore = createMemoryRateLimitStore();\n const pending: PendingOutput[] = [];\n const ssr = { ...options.ssr, navigation: \"document\" as const };\n\n for (const entry of outputEntries) {\n const request = createStaticRequest(origin, entry.pathname, entry.kind);\n const response = await handleRequestWithManifest(manifest, request, {\n onError: options.onError,\n rateLimitStore,\n ssr,\n });\n\n pending.push(\n entry.kind === \"document\"\n ? await prepareDocumentOutput(entry, response, 200)\n : await prepareResourceOutput(entry, response),\n );\n }\n\n const notFoundResponse = await renderNotFoundResponse(\n manifest,\n createStaticRequest(origin, \"/404\", \"document\"),\n {\n ...ssr,\n onError: (error, site) =>\n options.onError?.(error, { pathname: \"/404\", site }),\n },\n );\n pending.push(\n await prepareDocumentOutput(\n {\n file: \"404.html\",\n pathname: \"*\",\n },\n notFoundResponse,\n 404,\n ),\n );\n\n const documents = pending.map((entry) => entry.body);\n\n assertNoOptimizerImages(documents, options.images);\n\n const images = await emitImageVariants({\n documents,\n outDir,\n policy: options.images,\n });\n // The font set is a declaration rather than a render result, so the build\n // publishes every font the application declared. A document reaches them\n // through the stylesheet that `fontLinks` adds.\n const fonts = await resolveFontAssets({\n fonts: options.fonts,\n root: options.root ?? process.cwd(),\n });\n\n pending.sort((left, right) => left.file.localeCompare(right.file));\n images.sort((left, right) => left.file.localeCompare(right.file));\n fonts.sort((left, right) => left.file.localeCompare(right.file));\n\n const outputManifest: StaticOutputManifest = {\n adapter: \"static\",\n entries: pending.map(({ body: _body, ...entry }) => entry),\n fileHeaderRules: await createStaticFileHeaderRules(\n manifest,\n options.staticFileHeaders ?? [],\n ),\n fontFiles: fonts.map((asset) => asset.file),\n imageFiles: images.map((image) => image.file),\n origin,\n version: 1,\n };\n\n await writeOutput(outDir, pending, [...images, ...fonts], outputManifest);\n\n return outputManifest;\n}\n\nasync function createStaticFileHeaderRules(\n manifest: RouteManifest,\n patternRules: readonly StaticFileHeaderPatternRule[],\n): Promise<StaticOutputFileHeaderRule[]> {\n const baseline = await loadBaselineFileSecurityPolicy(manifest);\n const baselineHeaders = renderStaticFileHeaders(baseline);\n\n return [\n ...patternRules.map((rule) => {\n assertValidFileHeaderPattern(rule.pattern);\n\n return {\n headers: renderStaticFileHeaders(\n mergeSecurityPolicies(baseline, { headers: rule.headers }),\n ),\n pattern: rule.pattern,\n };\n }),\n {\n headers: {\n ...baselineHeaders,\n \"cache-control\": IMMUTABLE_FILE_CACHE_CONTROL,\n },\n pattern: CONTENT_HASHED_FILE_NAME_PATTERN.source,\n },\n {\n headers: {\n ...baselineHeaders,\n \"cache-control\": REVALIDATED_FILE_CACHE_CONTROL,\n },\n pattern: \".*\",\n },\n ];\n}\n\n// The baseline is the full document header set minus the Content Security\n// Policy. It derives from the root `@policy.ts` document policy, the same\n// declaration that governs route documents. CSP is excluded because the\n// framework cannot hash a file it did not render. Trusted Types is excluded\n// with it. A browser reads Trusted Types from the Content-Security-Policy\n// header only.\nasync function loadBaselineFileSecurityPolicy(\n manifest: RouteManifest,\n): Promise<SecurityPolicy> {\n const rootPolicyRoute = manifest.policies.find(\n (policy) => policy.fileSegments.length === 0,\n );\n const rootModule = await rootPolicyRoute?.load();\n\n return { headers: rootModule?.policy?.document?.headers };\n}\n\nfunction renderStaticFileHeaders(policy: SecurityPolicy) {\n return Object.fromEntries(createSecurityHeaders(policy, {}).entries());\n}\n\nfunction assertValidFileHeaderPattern(pattern: string) {\n try {\n new RegExp(pattern);\n } catch {\n throw new Error(\n `Static file header pattern is not a valid regular expression: ${JSON.stringify(pattern)}.`,\n );\n }\n}\n\nfunction normalizeOrigin(value: string | undefined) {\n let origin: URL;\n\n try {\n origin = new URL(value ?? \"http://demiurge.local\");\n } catch {\n throw new Error(\n `Static output origin must be an absolute HTTP(S) origin: ${JSON.stringify(value)}.`,\n );\n }\n\n if (\n (origin.protocol !== \"http:\" && origin.protocol !== \"https:\") ||\n origin.username ||\n origin.password ||\n origin.pathname !== \"/\" ||\n origin.search ||\n origin.hash\n ) {\n throw new Error(\n `Static output origin must be an HTTP(S) origin without credentials, a path, query, or hash: ${JSON.stringify(value)}.`,\n );\n }\n\n return origin.origin;\n}\n\nfunction assertStaticPageApp(manifest: RouteManifest, pageCount: number) {\n if (pageCount === 0) {\n throw new Error(\"Static output requires at least one page route.\");\n }\n\n const hasRootNotFound = manifest.fallbacks.notFound.some(\n (fallback) => fallback.fileSegments.length === 0,\n );\n\n if (!hasRootNotFound) {\n throw new Error(\n \"Static output requires a root @not-found.tsx so 404.html is app-owned.\",\n );\n }\n}\n\nasync function validateStaticRoutes(manifest: RouteManifest) {\n const routeKinds = new Map<string, OutputKind>();\n\n for (const route of manifest.routes) {\n const routeModule = await route.load();\n const unsupportedMethods = staticUnsupportedMethods(routeModule);\n\n if (unsupportedMethods.length > 0) {\n throw new Error(\n `Static route ${JSON.stringify(route.file)} exports unsupported methods ${unsupportedMethods.join(\", \")}. Deploy a runtime adapter for request-time methods.`,\n );\n }\n\n if (!routeModule.GET) {\n throw new Error(\n `Static route ${JSON.stringify(route.file)} does not export GET and cannot produce an output file.`,\n );\n }\n\n if (routeModule.GET.kind === \"page\") {\n routeKinds.set(route.file, \"document\");\n continue;\n }\n\n assertStaticResource(route.file, routeModule.GET);\n routeKinds.set(route.file, \"resource\");\n }\n\n return routeKinds;\n}\n\nfunction staticUnsupportedMethods(routeModule: RouteModule) {\n return ([\"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\", \"HEAD\"] as const)\n .filter((method) => routeModule[method] !== undefined);\n}\n\nfunction assertStaticResource(file: string, capability: RouteCapability) {\n if (\n (capability.kind === \"text\" ||\n capability.kind === \"html\" ||\n capability.kind === \"json\") &&\n typeof capability.value !== \"function\"\n ) {\n return;\n }\n\n const reason = \"value\" in capability && typeof capability.value === \"function\"\n ? `uses a request-dependent ${capability.kind} value`\n : `uses the ${capability.kind} response helper`;\n\n throw new Error(\n `Static route ${JSON.stringify(file)} ${reason} and cannot produce a fixed output file. Use a fixed text, html, or json value, or deploy a runtime adapter.`,\n );\n}\n\nfunction planOutputEntries(\n outputs: Array<{ kind: OutputKind; pathname: string }>,\n) {\n const seenFiles = new Map<string, string>();\n const seenPathnames = new Set<string>();\n\n return outputs.map(({ kind, pathname }) => {\n if (seenPathnames.has(pathname)) {\n throw new Error(`Static output collected duplicate pathname ${JSON.stringify(pathname)}.`);\n }\n\n seenPathnames.add(pathname);\n\n const file = kind === \"document\"\n ? pathnameToDocumentFile(pathname)\n : pathnameToResourceFile(pathname);\n const portableFile = file.toLocaleLowerCase(\"en-US\");\n const conflict = [...seenFiles.entries()].find(([seenFile]) =>\n seenFile === portableFile ||\n seenFile.startsWith(`${portableFile}/`) ||\n portableFile.startsWith(`${seenFile}/`)\n );\n\n if (conflict) {\n throw new Error(\n `Static paths ${JSON.stringify(conflict[1])} and ${JSON.stringify(pathname)} map to the same portable output file or to a file and directory conflict.`,\n );\n }\n\n seenFiles.set(portableFile, pathname);\n\n return { file, kind, pathname };\n });\n}\n\nfunction pathnameToDocumentFile(pathname: string) {\n if (!pathname.startsWith(\"/\") || pathname.includes(\"?\") || pathname.includes(\"#\")) {\n throw new Error(`Static output received invalid pathname ${JSON.stringify(pathname)}.`);\n }\n\n if (pathname === \"/\") {\n return \"index.html\";\n }\n\n const segments = pathname.split(\"/\").slice(1).map((segment) => {\n let decoded: string;\n\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n throw new Error(`Static output pathname is not valid UTF-8: ${JSON.stringify(pathname)}.`);\n }\n\n assertPortableSegment(decoded, pathname);\n return decoded;\n });\n\n return [...segments, \"index.html\"].join(\"/\");\n}\n\nfunction pathnameToResourceFile(pathname: string) {\n if (pathname === \"/\") {\n throw new Error(\"A static resource route cannot own the root pathname.\");\n }\n\n const documentFile = pathnameToDocumentFile(pathname);\n return documentFile.slice(0, -\"/index.html\".length);\n}\n\nfunction assertPortableSegment(segment: string, pathname: string) {\n const invalidWindowsName = /[<>:\"|?*]/.test(segment) ||\n [...segment].some((character) => character.charCodeAt(0) <= 31) ||\n /[. ]$/.test(segment) ||\n /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\.|$)/i.test(segment);\n\n if (\n !segment ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\") ||\n invalidWindowsName\n ) {\n throw new Error(\n `Static pathname ${JSON.stringify(pathname)} contains a segment that is unsafe or not portable as a file name: ${JSON.stringify(segment)}.`,\n );\n }\n}\n\nfunction createStaticRequest(\n origin: string,\n pathname: string,\n kind: OutputKind,\n) {\n return new Request(`${origin}${pathname}`, {\n headers: { accept: kind === \"document\" ? \"text/html\" : \"*/*\" },\n });\n}\n\nasync function prepareDocumentOutput(\n entry: { file: string; pathname: string },\n response: Response,\n expectedStatus: 200 | 404,\n): Promise<PendingOutput> {\n if (response.status !== expectedStatus) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} returned status ${response.status}; expected ${expectedStatus}.`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n\n if (!contentType?.toLowerCase().startsWith(\"text/html\")) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} returned ${JSON.stringify(contentType)} instead of text/html.`,\n );\n }\n\n if (response.headers.has(\"set-cookie\")) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} attempted to set a cookie. Build artifacts cannot contain per-user response state.`,\n );\n }\n\n const html = await coverStructuredDataHashes(\n await response.text(),\n response.headers,\n );\n await validateStaticCsp(entry.pathname, html, response.headers);\n\n return {\n file: entry.file,\n headers: sortedHeaders(response.headers),\n body: html,\n pathname: entry.pathname,\n status: expectedStatus,\n };\n}\n\nasync function prepareResourceOutput(\n entry: PlannedOutput,\n response: Response,\n): Promise<PendingOutput> {\n if (response.status !== 200) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} returned status ${response.status}; expected 200.`,\n );\n }\n\n if (response.headers.has(\"set-cookie\")) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} attempted to set a cookie. Build artifacts cannot contain per-user response state.`,\n );\n }\n\n return {\n file: entry.file,\n headers: sortedHeaders(response.headers),\n body: await response.text(),\n pathname: entry.pathname,\n status: 200,\n };\n}\n\nasync function coverStructuredDataHashes(html: string, headers: Headers) {\n const markerPattern = new RegExp(\n `(?:^|\\\\s)${STRUCTURED_DATA_ATTRIBUTE}(?:\\\\s|$)`,\n );\n const elements = findRawTextElements(html, \"script\")\n .filter((element) => markerPattern.test(element.attributes));\n\n if (elements.length === 0) {\n return html;\n }\n\n const hashes = await Promise.all(\n elements.map((element) => cspHash(element.content)),\n );\n\n for (const headerName of [\n \"content-security-policy\",\n \"content-security-policy-report-only\",\n ]) {\n const csp = headers.get(headerName);\n if (csp) {\n headers.set(headerName, addScriptHashes(csp, hashes));\n }\n }\n\n return html.replace(\n new RegExp(`\\\\s${STRUCTURED_DATA_ATTRIBUTE}(?=\\\\s|>)`, \"g\"),\n \"\",\n );\n}\n\nfunction addScriptHashes(csp: string, hashes: readonly string[]) {\n const directives = csp.split(\";\")\n .map((directive) => directive.trim())\n .filter(Boolean);\n const scriptIndex = directives.findIndex((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"script-src\"\n );\n const defaultDirective = directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n );\n const current = scriptIndex === -1 ? defaultDirective : directives[scriptIndex];\n\n if (!current) {\n return csp;\n }\n\n const sources = current.split(/\\s+/).slice(1)\n .filter((source) => source !== \"'none'\");\n const scriptDirective = [\n \"script-src\",\n ...new Set([...sources, ...hashes]),\n ].join(\" \");\n\n if (scriptIndex === -1) {\n directives.push(scriptDirective);\n } else {\n directives[scriptIndex] = scriptDirective;\n }\n\n return directives.join(\"; \");\n}\n\nasync function validateStaticCsp(\n pathname: string,\n html: string,\n headers: Headers,\n) {\n const csp = headers.get(\"content-security-policy\");\n\n if (!csp) {\n return;\n }\n\n if (/'nonce-[^']+'/i.test(csp) || /\\snonce\\s*=/i.test(html)) {\n throw new Error(\n `Static output for ${JSON.stringify(pathname)} uses a nonce-backed CSP. Use security.static() with stable hashes or a runtime adapter that injects a fresh nonce.`,\n );\n }\n\n const directives = parseCsp(csp);\n\n await validateInlineElements(\n pathname,\n html,\n \"script\",\n effectiveSources(directives, \"script-src\", \"default-src\"),\n );\n await validateInlineElements(\n pathname,\n html,\n \"style\",\n effectiveSources(\n directives,\n \"style-src-elem\",\n \"style-src\",\n \"default-src\",\n ),\n );\n\n const styleAttributeSources = effectiveSources(\n directives,\n \"style-src-attr\",\n \"style-src\",\n \"default-src\",\n );\n\n if (\n styleAttributeSources &&\n /\\sstyle\\s*=/i.test(html) &&\n !styleAttributeSources.includes(\"'unsafe-inline'\")\n ) {\n throw new Error(\n `Static output for ${JSON.stringify(pathname)} contains an inline style attribute that its CSP does not allow. Move the style into a stylesheet or explicitly allow inline styles.`,\n );\n }\n}\n\nfunction parseCsp(value: string) {\n const directives = new Map<string, string[]>();\n\n for (const rawDirective of value.split(\";\")) {\n const [name, ...sources] = rawDirective.trim().split(/\\s+/);\n\n if (name) {\n directives.set(name.toLowerCase(), sources);\n }\n }\n\n return directives;\n}\n\nfunction effectiveSources(\n directives: Map<string, string[]>,\n ...names: string[]\n) {\n for (const name of names) {\n const sources = directives.get(name);\n\n if (sources) {\n return sources;\n }\n }\n\n return undefined;\n}\n\nasync function validateInlineElements(\n pathname: string,\n html: string,\n tagName: \"script\" | \"style\",\n sources: string[] | undefined,\n) {\n if (!sources || sources.includes(\"'unsafe-inline'\")) {\n return;\n }\n\n for (const element of findRawTextElements(html, tagName)) {\n if (tagName === \"script\") {\n const src = readHtmlAttribute(element.attributes, \"src\");\n\n if (src) {\n if (!allowsStaticScriptSource(sources, src)) {\n throw new Error(\n `Static output for ${JSON.stringify(pathname)} contains script ${JSON.stringify(src)} that the effective script-src directive does not allow. Add its origin to security.needs.script or the route CSP policy.`,\n );\n }\n\n continue;\n }\n }\n\n if (!element.content) {\n continue;\n }\n\n const hash = await cspHash(element.content);\n\n if (!sources.includes(hash)) {\n throw new Error(\n `Static output for ${JSON.stringify(pathname)} contains an inline ${tagName} without the required CSP hash ${hash}.`,\n );\n }\n }\n}\n\nfunction readHtmlAttribute(attributes: string, name: string) {\n const match = attributes.match(\n new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*[\"']([^\"']+)[\"']`, \"i\"),\n );\n\n return match?.[1]?.replaceAll(\"&amp;\", \"&\");\n}\n\nfunction allowsStaticScriptSource(\n sources: string[] | undefined,\n src: string,\n) {\n if (!sources) {\n return true;\n }\n\n if (sources.includes(\"'none'\")) {\n return false;\n }\n\n if (\n sources.includes(\"'strict-dynamic'\") &&\n sources.some((source) =>\n source.startsWith(\"'nonce-\") || /^'sha(?:256|384|512)-/.test(source)\n )\n ) {\n return false;\n }\n\n if (sources.includes(\"*\")) {\n return true;\n }\n\n if (sources.includes(\"'self'\") && src.startsWith(\"/\") && !src.startsWith(\"//\")) {\n return true;\n }\n\n if (src.startsWith(\"https:\") && sources.includes(\"https:\")) {\n return true;\n }\n\n if (src.startsWith(\"http:\") && sources.includes(\"http:\")) {\n return true;\n }\n\n let scriptUrl: URL;\n try {\n scriptUrl = new URL(src, \"https://demiurge.invalid\");\n } catch {\n return false;\n }\n\n return sources.some((source) => {\n if (source.startsWith(\"'\")) {\n return false;\n }\n\n let sourceUrl: URL;\n try {\n sourceUrl = new URL(source);\n } catch {\n return false;\n }\n\n const hostnameMatches = sourceUrl.hostname.startsWith(\"*.\")\n ? scriptUrl.hostname.endsWith(sourceUrl.hostname.slice(1)) &&\n scriptUrl.hostname !== sourceUrl.hostname.slice(2)\n : scriptUrl.hostname === sourceUrl.hostname;\n const pathMatches = sourceUrl.pathname === \"/\" ||\n sourceUrl.pathname.endsWith(\"/\")\n ? scriptUrl.pathname.startsWith(sourceUrl.pathname)\n : scriptUrl.pathname === sourceUrl.pathname;\n\n return scriptUrl.protocol === sourceUrl.protocol &&\n hostnameMatches &&\n scriptUrl.port === sourceUrl.port &&\n pathMatches;\n });\n}\n\nfunction findRawTextElements(html: string, tagName: \"script\" | \"style\") {\n const lowerHtml = html.toLowerCase();\n const elements: Array<{ attributes: string; content: string }> = [];\n const opening = `<${tagName}`;\n const closing = `</${tagName}`;\n let cursor = 0;\n\n while (cursor < html.length) {\n const start = lowerHtml.indexOf(opening, cursor);\n\n if (start === -1) {\n break;\n }\n\n const openEnd = lowerHtml.indexOf(\">\", start + opening.length);\n const closeStart = openEnd === -1\n ? -1\n : lowerHtml.indexOf(closing, openEnd + 1);\n const closeEnd = closeStart === -1\n ? -1\n : lowerHtml.indexOf(\">\", closeStart + closing.length);\n\n if (openEnd === -1 || closeStart === -1 || closeEnd === -1) {\n throw new Error(`Static output contains an unclosed <${tagName}> element.`);\n }\n\n elements.push({\n attributes: html.slice(start + opening.length, openEnd),\n content: html.slice(openEnd + 1, closeStart),\n });\n cursor = closeEnd + 1;\n }\n\n return elements;\n}\n\nfunction sortedHeaders(headers: Headers) {\n return Object.fromEntries(\n [...headers.entries()].sort(([left], [right]) => left.localeCompare(right)),\n );\n}\n\nasync function writeOutput(\n outDir: string,\n entries: PendingOutput[],\n assets: PendingAsset[],\n manifest: StaticOutputManifest,\n) {\n const parent = dirname(outDir);\n await mkdir(parent, { recursive: true });\n const staging = await mkdtemp(join(parent, \".demiurge-static-\"));\n\n try {\n for (const output of [...entries, ...assets]) {\n const file = resolveContained(staging, output.file);\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, output.body);\n }\n\n await writeFile(\n join(staging, STATIC_MANIFEST_FILE),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n );\n\n const previousFiles = await readPreviousOutputFiles(outDir);\n await mkdir(outDir, { recursive: true });\n await cp(staging, outDir, { recursive: true, force: true });\n\n const currentFiles = new Set(\n [...entries, ...assets].map((output) => output.file),\n );\n\n for (const file of previousFiles) {\n if (!currentFiles.has(file)) {\n await rm(resolveContained(outDir, file), { force: true });\n }\n }\n } finally {\n await rm(staging, { force: true, recursive: true });\n }\n}\n\nasync function readPreviousOutputFiles(outDir: string) {\n try {\n const source = await readFile(join(outDir, STATIC_MANIFEST_FILE), \"utf8\");\n const value = JSON.parse(source) as {\n adapter?: unknown;\n entries?: Array<{ file?: unknown }>;\n fontFiles?: unknown;\n imageFiles?: unknown;\n version?: unknown;\n };\n\n if (\n value.adapter !== \"static\" ||\n value.version !== 1 ||\n !Array.isArray(value.entries)\n ) {\n return [];\n }\n\n const fontFiles = Array.isArray(value.fontFiles) ? value.fontFiles : [];\n const imageFiles = Array.isArray(value.imageFiles) ? value.imageFiles : [];\n\n return [\n ...value.entries.map((entry) => entry.file),\n ...fontFiles,\n ...imageFiles,\n ].flatMap((file) =>\n typeof file === \"string\" && isSafeRelativeFile(file) ? [file] : []\n );\n } catch {\n return [];\n }\n}\n\nfunction resolveContained(root: string, file: string) {\n if (!isSafeRelativeFile(file)) {\n throw new Error(`Static output file must stay inside the output directory: ${JSON.stringify(file)}.`);\n }\n\n const resolvedRoot = resolve(root);\n const resolvedFile = resolve(resolvedRoot, file);\n\n if (relative(resolvedRoot, resolvedFile).split(sep).includes(\"..\")) {\n throw new Error(`Static output file escaped the output directory: ${JSON.stringify(file)}.`);\n }\n\n return resolvedFile;\n}\n\nfunction isSafeRelativeFile(file: string) {\n return Boolean(file) &&\n !file.startsWith(\"/\") &&\n !file.startsWith(\"\\\\\") &&\n !file.split(/[\\\\/]/).includes(\"..\");\n}\n"],"names":["emitImageVariants","options","outDir","resolve","policy","optimizerPath","defaultImageOptimizerPath","paths","document","collectImageVariantPaths","emitted","sources","pathname","descriptor","parseImageVariantPath","isAllowedImageSource","sourceFile","resolveSourceFile","source","readSourceImage","encoded","transformImage","negotiateImageFormat","assertNoOptimizerImages","documents","pattern","src","readFile","error","decoded","file","relative","sep","STATIC_MANIFEST_FILE","contentTypes","createStaticPreviewServer","root","manifest","parseStaticManifest","entries","entry","entriesByFile","rules","rule","server","createServer","request","response","url","routePath","writeEntry","resolvePreviewFile","declaredFile","declaredEntry","body","type","extname","fileName","expression","applyHeaders","isMissingFile","fallback","resolvePromise","reject","onError","method","resolveDeclaredFile","headers","name","value","resolveContained","resolved","pathFromRoot","isRecord","parseEntry","fileHeaderRules","parseRule","pathnames","isStringRecord","item","CLIENT_MANIFEST_FILE","vercelStatic","generateVercelStaticOutput","validateVercelDeployment","projectRoot","sourceRoot","outputRoot","pathsOverlap","outputParent","dirname","mkdir","stagingRoot","mkdtemp","join","staticRoot","cp","writeFile","createVercelOutputConfig","rm","rename","deployment","applicationRoutes","transformApplicationCache","routes","resolveVercelCorsOrigin","filePath","exactPathPattern","withoutContentType","translateFileHeaderPattern","route","fallbackHeaders","normalized","normalizeRoutes","createOverride","override","contentType","naturalPath","escaped","CONTENT_HASHED_FILE_NAME_PATTERN","translateFileNamePattern","startsAtBasename","endsAtBasename","cache","transformed","getTransformedRoutes","cors","origin","validateCorsPolicy","left","right","fromLeft","fromRight","isSameOrChildPath","staticAdapter","defineAdapter","staticRouteLoadConcurrency","loadRouteModules","modules","next","workers","index","load","generateStaticOutput","routeModules","validateRouteModules","normalizeOrigin","routeKinds","validateStaticRoutes","collectStaticRoutePaths","assertStaticPageApp","path","outputEntries","planOutputEntries","rateLimitStore","createMemoryRateLimitStore","pending","ssr","createStaticRequest","handleRequestWithManifest","prepareDocumentOutput","prepareResourceOutput","notFoundResponse","renderNotFoundResponse","site","images","fonts","resolveFontAssets","outputManifest","_body","createStaticFileHeaderRules","asset","image","writeOutput","patternRules","baseline","loadBaselineFileSecurityPolicy","baselineHeaders","renderStaticFileHeaders","assertValidFileHeaderPattern","mergeSecurityPolicies","IMMUTABLE_FILE_CACHE_CONTROL","REVALIDATED_FILE_CACHE_CONTROL","createSecurityHeaders","pageCount","routeModule","unsupportedMethods","staticUnsupportedMethods","assertStaticResource","capability","reason","outputs","seenFiles","seenPathnames","kind","pathnameToDocumentFile","pathnameToResourceFile","portableFile","conflict","seenFile","segment","assertPortableSegment","invalidWindowsName","character","expectedStatus","html","coverStructuredDataHashes","validateStaticCsp","sortedHeaders","markerPattern","STRUCTURED_DATA_ATTRIBUTE","elements","findRawTextElements","element","hashes","cspHash","headerName","csp","addScriptHashes","directives","directive","scriptIndex","defaultDirective","current","scriptDirective","parseCsp","validateInlineElements","effectiveSources","styleAttributeSources","rawDirective","names","tagName","readHtmlAttribute","allowsStaticScriptSource","hash","attributes","scriptUrl","sourceUrl","hostnameMatches","pathMatches","lowerHtml","opening","closing","cursor","start","openEnd","closeStart","closeEnd","assets","parent","staging","output","previousFiles","readPreviousOutputFiles","currentFiles","fontFiles","imageFiles","isSafeRelativeFile","resolvedRoot","resolvedFile"],"mappings":";;;;;;;;;;;;AA+BA,eAAsBA,GACpBC,GACgC;AAChC,QAAMC,IAASC,EAAQF,EAAQ,MAAM,GAC/BG,IAASH,EAAQ,UAAU,CAAA,GAC3BI,IAAgBD,EAAO,iBAAiBE,GACxCC,IAAQ,IAAI;AAAA,IAChBN,EAAQ,UAAU;AAAA,MAAQ,CAACO,MACzBC,GAAyBD,GAAUH,CAAa;AAAA,IAAA;AAAA,EAClD,GAEIK,IAAiC,CAAA,GACjCC,wBAAc,IAAA;AAEpB,aAAWC,KAAY,CAAC,GAAGL,CAAK,EAAE,QAAQ;AACxC,UAAMM,IAAaC,GAAsBF,GAAUP,CAAa;AAEhE,QAAI,CAACQ;AACH,YAAM,IAAI;AAAA,QACR,0CAA0C,KAAK,UAAUD,CAAQ,CAAC;AAAA,MAAA;AAItE,QAAI,CAACG,GAAqBF,EAAW,KAAKT,CAAM;AAC9C,YAAM,IAAI;AAAA,QACR,gBAAgB,KAAK,UAAUS,EAAW,GAAG,CAAC;AAAA,MAAA;AAIlD,UAAMG,IAAaC,GAAkBf,GA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B,CAACA,EAAK,WAAW,IAAI,KACrB,CAACA,EAAK,MAAM,OAAO,EAAE,SAAS,IAAI;AACtC;"}
1
+ {"version":3,"file":"index.js","sources":["../../src/static/images.ts","../../src/static/preview.ts","../../src/static/vercel.ts","../../src/static/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { relative, resolve, sep } from \"node:path\";\nimport {\n negotiateImageFormat,\n transformImage,\n} from \"../platform/image-codec\";\nimport {\n collectImageVariantPaths,\n defaultImageOptimizerPath,\n parseImageVariantPath,\n} from \"../platform/image-url\";\nimport { isAllowedImageSource, type ImagePolicy } from \"../platform/images\";\n\nexport type EmittedImageVariant = {\n body: Uint8Array;\n file: string;\n};\n\nexport type EmitImageVariantsOptions = {\n // Every document that the build rendered. A variant reaches the output\n // only when a document references it.\n documents: readonly string[];\n // The directory that already holds the client build, including every file\n // that the Vite public directory contributed.\n outDir: string;\n policy?: ImagePolicy;\n};\n\n// The static build owns every byte it publishes. It reads the variant paths\n// back out of the rendered documents. No state then has to cross the boundary\n// between the application bundle and the build process.\nexport async function emitImageVariants(\n options: EmitImageVariantsOptions,\n): Promise<EmittedImageVariant[]> {\n const outDir = resolve(options.outDir);\n const policy = options.policy ?? {};\n const optimizerPath = policy.optimizerPath ?? defaultImageOptimizerPath;\n const paths = new Set(\n options.documents.flatMap((document) =>\n collectImageVariantPaths(document, optimizerPath)\n ),\n );\n const emitted: EmittedImageVariant[] = [];\n const sources = new Map<string, Uint8Array>();\n\n for (const pathname of [...paths].sort()) {\n const descriptor = parseImageVariantPath(pathname, optimizerPath);\n\n if (!descriptor) {\n throw new Error(\n `Static output references image variant ${JSON.stringify(pathname)}, which does not describe a transform the build can emit.`,\n );\n }\n\n if (!isAllowedImageSource(descriptor.src, policy)) {\n throw new Error(\n `Image source ${JSON.stringify(descriptor.src)} is not allowed by the image policy.`,\n );\n }\n\n const sourceFile = resolveSourceFile(outDir, descriptor.src);\n let source = sources.get(sourceFile);\n\n if (!source) {\n source = await readSourceImage(sourceFile, descriptor.src);\n sources.set(sourceFile, source);\n }\n\n const encoded = await transformImage(source, {\n format: negotiateImageFormat(descriptor, null),\n quality: descriptor.quality,\n width: descriptor.width,\n });\n\n emitted.push({ body: encoded.body, file: pathname.slice(1) });\n }\n\n return emitted;\n}\n\n// A document that a static build publishes cannot reach a request-time\n// optimizer. The build stops rather than publish a dead image URL.\nexport function assertNoOptimizerImages(\n documents: readonly string[],\n policy: ImagePolicy = {},\n) {\n const optimizerPath = policy.optimizerPath ?? defaultImageOptimizerPath;\n const pattern = new RegExp(`${optimizerPath.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\?`);\n\n for (const document of documents) {\n if (pattern.test(document)) {\n throw new Error(\n 'Static output references the request-time image optimizer, which a static build cannot serve. Set loader: \"static\" in the image policy, or deploy a runtime adapter.',\n );\n }\n }\n}\n\nasync function readSourceImage(sourceFile: string, src: string) {\n try {\n return new Uint8Array(await readFile(sourceFile));\n } catch (error) {\n throw new Error(\n `Demiurge could not read the source image ${JSON.stringify(src)} from the build output.`,\n { cause: error },\n );\n }\n}\n\nfunction resolveSourceFile(outDir: string, src: string) {\n let decoded: string;\n\n try {\n decoded = decodeURIComponent(src);\n } catch {\n throw new Error(`Image source is not valid UTF-8: ${JSON.stringify(src)}.`);\n }\n\n const file = resolve(outDir, `.${decoded}`);\n\n if (relative(outDir, file).split(sep).includes(\"..\")) {\n throw new Error(\n `Image source escaped the build output directory: ${JSON.stringify(src)}.`,\n );\n }\n\n return file;\n}\n","import { createServer, type Server } from \"node:http\";\nimport { readFile } from \"node:fs/promises\";\nimport { extname, relative, resolve, sep } from \"node:path\";\nimport type {\n StaticOutputEntry,\n StaticOutputFileHeaderRule,\n StaticOutputManifest,\n} from \"./index\";\n\nconst STATIC_MANIFEST_FILE = \"demiurge-static-manifest.json\";\n\nexport type StaticPreviewOptions = {\n host?: string;\n outDir: string;\n port?: number;\n};\n\nconst contentTypes: Record<string, string> = {\n \".avif\": \"image/avif\",\n \".css\": \"text/css; charset=utf-8\",\n \".gif\": \"image/gif\",\n \".html\": \"text/html; charset=utf-8\",\n \".ico\": \"image/x-icon\",\n \".jpeg\": \"image/jpeg\",\n \".jpg\": \"image/jpeg\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".png\": \"image/png\",\n \".svg\": \"image/svg+xml\",\n \".txt\": \"text/plain; charset=utf-8\",\n \".webmanifest\": \"application/manifest+json\",\n \".webp\": \"image/webp\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n};\n\nexport async function createStaticPreviewServer(\n options: StaticPreviewOptions,\n): Promise<Server> {\n const root = resolve(options.outDir);\n const manifest = parseStaticManifest(\n await readFile(resolve(root, STATIC_MANIFEST_FILE), \"utf8\"),\n );\n const entries = new Map(\n manifest.entries.map((entry) => [entry.pathname, entry]),\n );\n const entriesByFile = new Map(\n manifest.entries.map((entry) => [entry.file, entry]),\n );\n const rules = manifest.fileHeaderRules.map((rule) => ({\n ...rule,\n expression: new RegExp(rule.pattern),\n }));\n\n const server = createServer(async (request, response) => {\n try {\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n response.writeHead(405, { allow: \"GET, HEAD\" });\n response.end();\n return;\n }\n\n const url = new URL(request.url ?? \"/\", \"http://demiurge.local\");\n let pathname: string;\n\n try {\n pathname = decodeURIComponent(url.pathname);\n } catch {\n response.writeHead(400, {\n \"content-type\": \"text/plain; charset=utf-8\",\n });\n response.end(\"The request path is not valid UTF-8.\");\n return;\n }\n\n const routePath = pathname.replace(/\\/$/, \"\") || \"/\";\n const entry = entries.get(routePath);\n\n if (entry) {\n await writeEntry(root, entry, request.method, response);\n return;\n }\n\n const file = resolvePreviewFile(root, pathname);\n if (file) {\n try {\n const declaredFile = relative(root, file).split(sep).join(\"/\");\n const declaredEntry = entriesByFile.get(declaredFile);\n if (declaredEntry) {\n await writeEntry(root, declaredEntry, request.method, response);\n return;\n }\n\n const body = await readFile(file);\n const type = contentTypes[extname(file).toLowerCase()];\n if (type) response.setHeader(\"content-type\", type);\n\n const fileName = pathname.split(\"/\").at(-1) ?? \"\";\n const rule = rules.find(({ expression }) => expression.test(fileName));\n applyHeaders(response, rule?.headers ?? {});\n response.writeHead(200);\n response.end(request.method === \"HEAD\" ? undefined : body);\n return;\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n }\n }\n\n const fallback = entries.get(\"*\");\n if (!fallback) {\n response.writeHead(404);\n response.end();\n return;\n }\n\n await writeEntry(root, fallback, request.method, response);\n } catch {\n response.writeHead(500, {\n \"content-type\": \"text/plain; charset=utf-8\",\n });\n response.end(\"Demiurge could not serve the static output.\");\n }\n });\n\n await new Promise<void>((resolvePromise, reject) => {\n const onError = (error: Error) => reject(error);\n server.once(\"error\", onError);\n server.listen(\n options.port ?? 4173,\n options.host ?? \"localhost\",\n () => {\n server.off(\"error\", onError);\n resolvePromise();\n },\n );\n });\n\n return server;\n}\n\nasync function writeEntry(\n root: string,\n entry: StaticOutputEntry,\n method: string | undefined,\n response: import(\"node:http\").ServerResponse,\n) {\n const file = resolveDeclaredFile(root, entry.file);\n const body = await readFile(file);\n applyHeaders(response, entry.headers);\n response.writeHead(entry.status);\n response.end(method === \"HEAD\" ? undefined : body);\n}\n\nfunction applyHeaders(\n response: import(\"node:http\").ServerResponse,\n headers: Record<string, string>,\n) {\n for (const [name, value] of Object.entries(headers)) {\n response.setHeader(name, value);\n }\n}\n\nfunction resolvePreviewFile(root: string, pathname: string) {\n if (pathname.endsWith(\"/\")) return undefined;\n return resolveContained(root, `.${pathname}`);\n}\n\nfunction resolveDeclaredFile(root: string, file: string) {\n const resolved = resolveContained(root, file);\n if (!resolved) {\n throw new Error(`Static preview file is outside the output directory: ${JSON.stringify(file)}.`);\n }\n return resolved;\n}\n\nfunction resolveContained(root: string, file: string) {\n if (\n !file ||\n file.startsWith(\"/\") ||\n file.startsWith(\"\\\\\") ||\n file.split(/[\\\\/]/).includes(\"..\")\n ) {\n return undefined;\n }\n const resolved = resolve(root, file);\n const pathFromRoot = relative(root, resolved);\n return pathFromRoot !== \"..\" &&\n !pathFromRoot.startsWith(`..${sep}`)\n ? resolved\n : undefined;\n}\n\nfunction parseStaticManifest(source: string): StaticOutputManifest {\n let value: unknown;\n try {\n value = JSON.parse(source);\n } catch {\n throw new Error(\"The static output manifest is not valid JSON.\");\n }\n\n if (!isRecord(value) || value.adapter !== \"static\" || value.version !== 1) {\n throw new Error(\"The static output manifest has an unsupported format.\");\n }\n if (!Array.isArray(value.entries) || !Array.isArray(value.fileHeaderRules)) {\n throw new Error(\"The static output manifest does not contain header rules and entries.\");\n }\n\n const entries = value.entries.map(parseEntry);\n const fileHeaderRules = value.fileHeaderRules.map(parseRule);\n const pathnames = new Set<string>();\n for (const entry of entries) {\n if (pathnames.has(entry.pathname)) {\n throw new Error(`The static output manifest repeats pathname ${JSON.stringify(entry.pathname)}.`);\n }\n pathnames.add(entry.pathname);\n }\n\n return { adapter: \"static\", entries, fileHeaderRules, version: 1 };\n}\n\nfunction parseEntry(value: unknown): StaticOutputEntry {\n if (\n !isRecord(value) ||\n typeof value.file !== \"string\" ||\n typeof value.pathname !== \"string\" ||\n (value.status !== 200 && value.status !== 404) ||\n !isStringRecord(value.headers)\n ) {\n throw new Error(\"The static output manifest contains an invalid entry.\");\n }\n resolveDeclaredFile(\"/demiurge-manifest-root\", value.file);\n return {\n file: value.file,\n headers: value.headers,\n pathname: value.pathname,\n status: value.status,\n };\n}\n\nfunction parseRule(value: unknown): StaticOutputFileHeaderRule {\n if (\n !isRecord(value) ||\n typeof value.pattern !== \"string\" ||\n !isStringRecord(value.headers)\n ) {\n throw new Error(\"The static output manifest contains an invalid file header rule.\");\n }\n try {\n new RegExp(value.pattern);\n } catch {\n throw new Error(\"The static output manifest contains an invalid file header pattern.\");\n }\n return { headers: value.headers, pattern: value.pattern };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n return isRecord(value) && Object.values(value).every(\n (item) => typeof item === \"string\",\n );\n}\n\nfunction isMissingFile(error: unknown) {\n return error instanceof Error && \"code\" in error &&\n (error.code === \"EISDIR\" || error.code === \"ENOENT\");\n}\n","import {\n cp,\n mkdir,\n mkdtemp,\n rename,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport {\n getTransformedRoutes,\n normalizeRoutes,\n type Header,\n type Route,\n} from \"@vercel/routing-utils\";\nimport { validateCorsPolicy } from \"../security\";\nimport type { CorsPolicy } from \"../security\";\nimport { CONTENT_HASHED_FILE_NAME_PATTERN } from \"../static-files\";\nimport type {\n StaticOutputEntry,\n StaticOutputManifest,\n} from \"./index\";\n\nconst CLIENT_MANIFEST_FILE = \"demiurge-manifest.json\";\nconst STATIC_MANIFEST_FILE = \"demiurge-static-manifest.json\";\n\nexport type VercelStaticCacheRule = {\n source: string;\n value: string;\n};\n\nexport type VercelStaticOptions = {\n cache?: VercelStaticCacheRule[];\n cors?: CorsPolicy;\n};\n\nexport type VercelStaticDeployment = {\n adapter: \"vercel\";\n cache: VercelStaticCacheRule[];\n cors?: CorsPolicy;\n};\n\nexport type VercelOutputRoute = Route;\n\nexport type VercelOutputConfig = {\n overrides: Record<string, {\n contentType?: string;\n path?: string;\n }>;\n routes: VercelOutputRoute[];\n version: 3;\n};\n\nexport function vercelStatic(\n options: VercelStaticOptions = {},\n): VercelStaticDeployment {\n return {\n adapter: \"vercel\",\n cache: options.cache?.map((rule) => ({\n source: rule.source,\n value: rule.value,\n })) ?? [],\n cors: options.cors,\n };\n}\n\nexport async function generateVercelStaticOutput(options: {\n deployment: VercelStaticDeployment;\n manifest: StaticOutputManifest;\n outDir: string;\n projectRoot: string;\n}) {\n validateVercelDeployment(options.deployment);\n\n const projectRoot = resolve(options.projectRoot);\n const sourceRoot = resolve(options.outDir);\n const outputRoot = resolve(projectRoot, \".vercel/output\");\n if (pathsOverlap(sourceRoot, outputRoot)) {\n throw new Error(\n \"The static output directory must not overlap the Vercel output directory.\",\n );\n }\n\n const outputParent = dirname(outputRoot);\n await mkdir(outputParent, { recursive: true });\n const stagingRoot = await mkdtemp(join(outputParent, \"output-demiurge-\"));\n\n try {\n const staticRoot = join(stagingRoot, \"static\");\n await cp(sourceRoot, staticRoot, {\n filter: (source) => {\n const file = relative(sourceRoot, source).split(sep).join(\"/\");\n return file !== CLIENT_MANIFEST_FILE && file !== STATIC_MANIFEST_FILE;\n },\n recursive: true,\n });\n await writeFile(\n join(stagingRoot, \"config.json\"),\n `${JSON.stringify(createVercelOutputConfig(\n options.manifest,\n options.deployment,\n ), null, 2)}\\n`,\n );\n\n await rm(outputRoot, { force: true, recursive: true });\n await rename(stagingRoot, outputRoot);\n } catch (error) {\n await rm(stagingRoot, { force: true, recursive: true });\n throw error;\n }\n\n return outputRoot;\n}\n\nexport function createVercelOutputConfig(\n manifest: StaticOutputManifest,\n deployment: VercelStaticDeployment,\n): VercelOutputConfig {\n const fallback = manifest.entries.find((entry) => entry.pathname === \"*\");\n if (!fallback) {\n throw new Error(\"Vercel output requires a static fallback entry.\");\n }\n\n const applicationRoutes = transformApplicationCache(deployment.cache);\n const corsOrigin = resolveVercelCorsOrigin(deployment.cors, manifest.origin);\n // Vercel adds `access-control-allow-origin: *` to every static response on\n // its own. This route states an explicit value instead, so a policy the\n // application never declared never reaches a deployed response. It comes\n // first so every later route in the sequence keeps it, the same pattern\n // the file header rules use for the cache policy.\n const routes: Route[] = [\n {\n continue: true,\n headers: { \"access-control-allow-origin\": corsOrigin },\n src: \"^/.*$\",\n },\n ];\n\n for (const entry of manifest.entries) {\n if (entry.pathname === \"*\") continue;\n const filePath = `/${entry.file}`;\n if (filePath !== entry.pathname) {\n routes.push({\n continue: true,\n dest: entry.pathname,\n src: exactPathPattern(filePath),\n });\n }\n }\n\n for (const entry of manifest.entries) {\n const headers = withoutContentType(entry.headers);\n if (Object.keys(headers).length === 0) continue;\n const pathname = entry.pathname === \"*\" ? `/${entry.file}` : entry.pathname;\n routes.push({\n continue: true,\n headers,\n src: exactPathPattern(pathname),\n });\n }\n\n routes.push(...applicationRoutes);\n\n for (const entry of manifest.entries) {\n if (entry.pathname === \"*\") {\n routes.push({\n dest: `/${entry.file}`,\n src: exactPathPattern(`/${entry.file}`),\n status: 404,\n });\n continue;\n }\n routes.push({\n dest: entry.pathname === \"/\" ? `/${entry.file}` : entry.pathname,\n src: exactPathPattern(entry.pathname),\n });\n }\n\n routes.push({ handle: \"hit\" });\n for (const rule of [...manifest.fileHeaderRules].reverse()) {\n routes.push({\n continue: true,\n headers: { ...rule.headers },\n src: translateFileHeaderPattern(rule.pattern),\n });\n }\n // Vercel applies every matching route in order, and a later route replaces\n // an earlier header of the same name. The hit phase runs after the routing\n // phase, so a framework file rule would replace the cache policy that the\n // application declared. The application rules repeat here to keep the last\n // word for a served file.\n routes.push(...applicationRoutes.map((route) => ({ ...route })));\n\n routes.push({ handle: \"error\" });\n const fallbackHeaders = withoutContentType(fallback.headers);\n if (Object.keys(fallbackHeaders).length > 0) {\n routes.push({\n continue: true,\n headers: fallbackHeaders,\n src: \"^/.*$\",\n });\n }\n routes.push(...applicationRoutes.map((route) => ({ ...route })));\n routes.push({ dest: `/${fallback.file}`, src: \"^/.*$\", status: 404 });\n\n const normalized = normalizeRoutes(routes);\n if (normalized.error || !normalized.routes) {\n throw new Error(\n `Vercel rejected the generated routes: ${normalized.error?.message ?? \"The route list is empty.\"}`,\n );\n }\n\n return {\n overrides: Object.fromEntries(\n manifest.entries.map((entry) => [entry.file, createOverride(entry)]),\n ),\n routes: normalized.routes,\n version: 3,\n };\n}\n\nfunction createOverride(entry: StaticOutputEntry) {\n const override: { contentType?: string; path?: string } = {};\n const contentType = entry.headers[\"content-type\"];\n if (contentType) override.contentType = contentType;\n\n if (entry.pathname !== \"*\") {\n const naturalPath = entry.file === \"index.html\"\n ? \"/\"\n : `/${entry.file}`;\n if (entry.pathname !== naturalPath) {\n override.path = entry.pathname.slice(1);\n }\n }\n\n return override;\n}\n\nfunction exactPathPattern(pathname: string) {\n const escaped = pathname.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return pathname === \"/\" ? \"^/$\" : `^${escaped}/?$`;\n}\n\nfunction withoutContentType(headers: Record<string, string>) {\n return Object.fromEntries(\n Object.entries(headers).filter(([name]) => name.toLowerCase() !== \"content-type\"),\n );\n}\n\nfunction translateFileHeaderPattern(pattern: string) {\n if (pattern === \".*\") {\n return \"^/.*$\";\n }\n if (pattern === CONTENT_HASHED_FILE_NAME_PATTERN.source) {\n return \"^/(?:.*/)?[^/]*-[A-Za-z0-9_-]{8,}\\\\.[A-Za-z0-9]+$\";\n }\n\n return `^/${translateFileNamePattern(pattern)}$`;\n}\n\n// Demiurge tests a static file header pattern against the file basename with\n// an unanchored `RegExp.test(...)`. The pattern can match anywhere in the\n// name. Vercel matches `src` against the complete pathname, which always\n// carries a directory prefix. This rebuilds the basename test as a pathname\n// pattern. A leading `^` pins the match to the start of the basename. A\n// trailing `$` pins it to the end. Without an anchor, the match can begin or\n// end anywhere in the basename.\nfunction translateFileNamePattern(pattern: string) {\n const startsAtBasename = pattern.startsWith(\"^\");\n const endsAtBasename = pattern.endsWith(\"$\") && !pattern.endsWith(\"\\\\$\");\n const body = pattern.slice(\n startsAtBasename ? 1 : 0,\n endsAtBasename ? -1 : undefined,\n );\n const prefix = startsAtBasename ? \"(?:.*/)?\" : \"(?:.*/)?[^/]*\";\n const suffix = endsAtBasename ? \"\" : \"[^/]*\";\n\n return `${prefix}(?:${body})${suffix}`;\n}\n\nfunction transformApplicationCache(cache: VercelStaticCacheRule[]) {\n const headers: Header[] = cache.map((rule) => ({\n headers: [{ key: \"cache-control\", value: rule.value }],\n source: rule.source,\n }));\n const transformed = getTransformedRoutes({ headers });\n if (transformed.error || !transformed.routes) {\n throw new Error(\n `A Vercel static header rule is not valid: ${transformed.error?.message ?? \"The route list is empty.\"}`,\n );\n }\n return transformed.routes;\n}\n\n// A static response cannot vary `access-control-allow-origin` by request, so\n// this resolves the declared policy to the single value the Vercel output\n// can serve. A declared policy always wins. Without one, the value falls\n// back to the build origin so a stray platform wildcard never survives.\nfunction resolveVercelCorsOrigin(\n cors: CorsPolicy | undefined,\n origin: string | undefined,\n): string {\n if (cors) {\n validateCorsPolicy(cors);\n\n if (cors.origins === \"*\") {\n return \"*\";\n }\n\n if (cors.origins.length === 1) {\n return cors.origins[0]!;\n }\n\n throw new Error(\n \"A Vercel static CORS policy must declare the wildcard origin or exactly one origin. A static response cannot vary access-control-allow-origin by request.\",\n );\n }\n\n if (!origin) {\n throw new Error(\n \"Vercel static output requires a build origin to emit access-control-allow-origin. Pass --origin, set SITE_ORIGIN, or declare a Vercel CORS policy.\",\n );\n }\n\n return origin;\n}\n\nfunction validateVercelDeployment(deployment: VercelStaticDeployment) {\n if (deployment.adapter !== \"vercel\" || !Array.isArray(deployment.cache)) {\n throw new Error(\"The Vercel static adapter configuration is not valid.\");\n }\n\n for (const rule of deployment.cache) {\n if (\n !rule ||\n typeof rule !== \"object\" ||\n typeof rule.source !== \"string\" ||\n !rule.source ||\n typeof rule.value !== \"string\" ||\n !rule.value\n ) {\n throw new Error(\"A Vercel static header rule is not valid.\");\n }\n }\n}\n\nfunction pathsOverlap(left: string, right: string) {\n const fromLeft = relative(left, right);\n const fromRight = relative(right, left);\n return isSameOrChildPath(fromLeft) || isSameOrChildPath(fromRight);\n}\n\nfunction isSameOrChildPath(pathname: string) {\n return !pathname ||\n (pathname !== \"..\" && !pathname.startsWith(`..${sep}`) &&\n !pathname.startsWith(\"/\"));\n}\n","import {\n cp,\n mkdir,\n mkdtemp,\n readFile,\n rm,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport { defineAdapter } from \"../adapter\";\nimport { STRUCTURED_DATA_ATTRIBUTE } from \"../document/render\";\nimport {\n collectStaticRoutePaths,\n type RouteManifest,\n} from \"../router\";\nimport type { RouteCapability, RouteImporter, RouteModule } from \"../route\";\nimport {\n handleRequestWithManifest,\n renderNotFoundResponse,\n type RequestErrorReporter,\n type SsrOptions,\n} from \"../server\";\nimport {\n createMemoryRateLimitStore,\n createSecurityHeaders,\n cspHash,\n mergeSecurityPolicies,\n validateRouteModules,\n type SecurityHeaderPolicy,\n type SecurityPolicy,\n} from \"../security\";\nimport {\n CONTENT_HASHED_FILE_NAME_PATTERN,\n IMMUTABLE_FILE_CACHE_CONTROL,\n REVALIDATED_FILE_CACHE_CONTROL,\n} from \"../static-files\";\nimport { resolveFontAssets } from \"../platform/font-assets\";\nimport type { FontContribution } from \"../platform/fonts\";\nimport type { ImagePolicy } from \"../platform/images\";\nimport { assertNoOptimizerImages, emitImageVariants } from \"./images\";\n\nconst STATIC_MANIFEST_FILE = \"demiurge-static-manifest.json\";\n\nexport { createStaticPreviewServer } from \"./preview\";\nexport type { StaticPreviewOptions } from \"./preview\";\nexport {\n createVercelOutputConfig,\n generateVercelStaticOutput,\n vercelStatic,\n} from \"./vercel\";\nexport type {\n VercelOutputConfig,\n VercelOutputRoute,\n VercelStaticDeployment,\n VercelStaticCacheRule,\n VercelStaticOptions,\n} from \"./vercel\";\n\nexport const staticAdapter = defineAdapter({\n name: \"static\",\n capabilities: {\n staticOutput: true,\n },\n});\n\nexport type StaticOutputEntry = {\n file: string;\n headers: Record<string, string>;\n pathname: string;\n status: 200 | 404;\n};\n\nexport type StaticOutputManifest = {\n adapter: \"static\";\n entries: StaticOutputEntry[];\n fileHeaderRules: StaticOutputFileHeaderRule[];\n // Self-hosted font files and the stylesheet that declares them. They are\n // plain output files as well, so the framework file header rules cover them.\n fontFiles?: string[];\n // Optimized image files that the build emitted. They are plain output\n // files rather than route entries. A host therefore serves them with the\n // framework file header rules and no route rule of their own.\n imageFiles?: string[];\n // The normalized build origin. The Vercel static generator falls back to\n // this value for `access-control-allow-origin` when the deployment\n // declares no CORS policy of its own. A manifest that a caller builds by\n // hand, such as a static preview fixture, can omit this field.\n origin?: string;\n version: 1;\n};\n\nexport type StaticOutputFileHeaderRule = {\n headers: Record<string, string>;\n pattern: string;\n};\n\n// A pattern rule declares the same typed `SecurityHeaderPolicy` as the root\n// and route policies. One header keeps one spelling in every place that\n// declares it. `pattern` is an ECMAScript regular expression tested against\n// the file basename, the same convention as the framework's built-in file\n// header rules.\nexport type StaticFileHeaderPatternRule = {\n headers: SecurityHeaderPolicy;\n pattern: string;\n};\n\nexport type GenerateStaticOutputOptions = {\n // The font declaration that the application passed to the Vite plugin. The\n // build reads every source it names and publishes the file from this origin.\n fonts?: FontContribution;\n // The image policy that the application declared in the Vite plugin. The\n // build reads it to find and validate the variants it must emit.\n images?: ImagePolicy;\n onError?: RequestErrorReporter;\n origin?: string;\n outDir: string;\n // The project directory that a local font source resolves against. A font\n // file therefore does not have to sit in the public directory.\n root?: string;\n routes: Record<string, RouteImporter>;\n ssr?: SsrOptions;\n staticFileHeaders?: readonly StaticFileHeaderPatternRule[];\n};\n\ntype PendingOutput = StaticOutputEntry & {\n body: string;\n};\n\ntype PendingAsset = {\n body: Uint8Array;\n file: string;\n};\n\ntype OutputKind = \"document\" | \"resource\";\n\ntype PlannedOutput = {\n file: string;\n kind: OutputKind;\n pathname: string;\n};\n\nconst staticRouteLoadConcurrency = 8;\n\nasync function loadRouteModules(\n routes: Readonly<Record<string, RouteImporter>>,\n) {\n const entries = Object.entries(routes);\n const modules = new Array<readonly [string, RouteModule]>(entries.length);\n let next = 0;\n\n const workers = Array.from(\n { length: Math.min(staticRouteLoadConcurrency, entries.length) },\n async () => {\n while (next < entries.length) {\n const index = next++;\n const [file, load] = entries[index]!;\n\n try {\n modules[index] = [file, await load()];\n } catch (error) {\n throw new Error(\n `Demiurge could not load route module ${JSON.stringify(file)}.`,\n { cause: error },\n );\n }\n }\n },\n );\n\n await Promise.all(workers);\n\n // TYPE-EVIDENCE: Object.fromEntries builds a record whose values are the loaded route modules. The cast labels the keys and values.\n return Object.fromEntries(modules) as Record<string, RouteModule>;\n}\n\nexport async function generateStaticOutput(\n options: GenerateStaticOutputOptions,\n): Promise<StaticOutputManifest> {\n const routeModules = await loadRouteModules(options.routes);\n const manifest = validateRouteModules(routeModules, {\n adapter: staticAdapter,\n });\n\n const origin = normalizeOrigin(options.origin);\n const outDir = resolve(options.outDir);\n const routeKinds = await validateStaticRoutes(manifest);\n const paths = await collectStaticRoutePaths(manifest, {\n includeResources: true,\n });\n\n assertStaticPageApp(\n manifest,\n paths.filter((path) => routeKinds.get(path.file) === \"document\").length,\n );\n\n const outputEntries = planOutputEntries(\n paths.map((path) => ({\n kind: routeKinds.get(path.file) ?? \"resource\",\n pathname: path.pathname,\n })),\n );\n const rateLimitStore = createMemoryRateLimitStore();\n const pending: PendingOutput[] = [];\n const ssr = { ...options.ssr, navigation: \"document\" as const };\n\n for (const entry of outputEntries) {\n const request = createStaticRequest(origin, entry.pathname, entry.kind);\n const response = await handleRequestWithManifest(manifest, request, {\n onError: options.onError,\n rateLimitStore,\n ssr,\n });\n\n pending.push(\n entry.kind === \"document\"\n ? await prepareDocumentOutput(entry, response, 200)\n : await prepareResourceOutput(entry, response),\n );\n }\n\n const notFoundResponse = await renderNotFoundResponse(\n manifest,\n createStaticRequest(origin, \"/404\", \"document\"),\n {\n ...ssr,\n onError: (error, site) =>\n options.onError?.(error, { pathname: \"/404\", site }),\n },\n );\n pending.push(\n await prepareDocumentOutput(\n {\n file: \"404.html\",\n pathname: \"*\",\n },\n notFoundResponse,\n 404,\n ),\n );\n\n const documents = pending.map((entry) => entry.body);\n\n assertNoOptimizerImages(documents, options.images);\n\n const images = await emitImageVariants({\n documents,\n outDir,\n policy: options.images,\n });\n // The font set is a declaration rather than a render result, so the build\n // publishes every font the application declared. A document reaches them\n // through the stylesheet that `fontLinks` adds.\n const fonts = await resolveFontAssets({\n fonts: options.fonts,\n root: options.root ?? process.cwd(),\n });\n\n pending.sort((left, right) => left.file.localeCompare(right.file));\n images.sort((left, right) => left.file.localeCompare(right.file));\n fonts.sort((left, right) => left.file.localeCompare(right.file));\n\n const outputManifest: StaticOutputManifest = {\n adapter: \"static\",\n entries: pending.map(({ body: _body, ...entry }) => entry),\n fileHeaderRules: await createStaticFileHeaderRules(\n manifest,\n options.staticFileHeaders ?? [],\n ),\n fontFiles: fonts.map((asset) => asset.file),\n imageFiles: images.map((image) => image.file),\n origin,\n version: 1,\n };\n\n await writeOutput(outDir, pending, [...images, ...fonts], outputManifest);\n\n return outputManifest;\n}\n\nasync function createStaticFileHeaderRules(\n manifest: RouteManifest,\n patternRules: readonly StaticFileHeaderPatternRule[],\n): Promise<StaticOutputFileHeaderRule[]> {\n const baseline = await loadBaselineFileSecurityPolicy(manifest);\n const baselineHeaders = renderStaticFileHeaders(baseline);\n\n return [\n ...patternRules.map((rule) => {\n assertValidFileHeaderPattern(rule.pattern);\n\n return {\n headers: renderStaticFileHeaders(\n mergeSecurityPolicies(baseline, { headers: rule.headers }),\n ),\n pattern: rule.pattern,\n };\n }),\n {\n headers: {\n ...baselineHeaders,\n \"cache-control\": IMMUTABLE_FILE_CACHE_CONTROL,\n },\n pattern: CONTENT_HASHED_FILE_NAME_PATTERN.source,\n },\n {\n headers: {\n ...baselineHeaders,\n \"cache-control\": REVALIDATED_FILE_CACHE_CONTROL,\n },\n pattern: \".*\",\n },\n ];\n}\n\n// The baseline is the full document header set minus the Content Security\n// Policy. It derives from the root `@policy.ts` document policy, the same\n// declaration that governs route documents. CSP is excluded because the\n// framework cannot hash a file it did not render. Trusted Types is excluded\n// with it. A browser reads Trusted Types from the Content-Security-Policy\n// header only.\nasync function loadBaselineFileSecurityPolicy(\n manifest: RouteManifest,\n): Promise<SecurityPolicy> {\n const rootPolicyRoute = manifest.policies.find(\n (policy) => policy.fileSegments.length === 0,\n );\n const rootModule = await rootPolicyRoute?.load();\n\n return { headers: rootModule?.policy?.document?.headers };\n}\n\nfunction renderStaticFileHeaders(policy: SecurityPolicy) {\n return Object.fromEntries(createSecurityHeaders(policy, {}).entries());\n}\n\nfunction assertValidFileHeaderPattern(pattern: string) {\n try {\n new RegExp(pattern);\n } catch {\n throw new Error(\n `Static file header pattern is not a valid regular expression: ${JSON.stringify(pattern)}.`,\n );\n }\n}\n\nfunction normalizeOrigin(value: string | undefined) {\n let origin: URL;\n\n try {\n origin = new URL(value ?? \"http://demiurge.local\");\n } catch {\n throw new Error(\n `Static output origin must be an absolute HTTP(S) origin: ${JSON.stringify(value)}.`,\n );\n }\n\n if (\n (origin.protocol !== \"http:\" && origin.protocol !== \"https:\") ||\n origin.username ||\n origin.password ||\n origin.pathname !== \"/\" ||\n origin.search ||\n origin.hash\n ) {\n throw new Error(\n `Static output origin must be an HTTP(S) origin without credentials, a path, query, or hash: ${JSON.stringify(value)}.`,\n );\n }\n\n return origin.origin;\n}\n\nfunction assertStaticPageApp(manifest: RouteManifest, pageCount: number) {\n if (pageCount === 0) {\n throw new Error(\"Static output requires at least one page route.\");\n }\n\n const hasRootNotFound = manifest.fallbacks.notFound.some(\n (fallback) => fallback.fileSegments.length === 0,\n );\n\n if (!hasRootNotFound) {\n throw new Error(\n \"Static output requires a root @not-found.tsx so 404.html is app-owned.\",\n );\n }\n}\n\nasync function validateStaticRoutes(manifest: RouteManifest) {\n const routeKinds = new Map<string, OutputKind>();\n\n for (const route of manifest.routes) {\n const routeModule = await route.load();\n const unsupportedMethods = staticUnsupportedMethods(routeModule);\n\n if (unsupportedMethods.length > 0) {\n throw new Error(\n `Static route ${JSON.stringify(route.file)} exports unsupported methods ${unsupportedMethods.join(\", \")}. Deploy a runtime adapter for request-time methods.`,\n );\n }\n\n if (!routeModule.GET) {\n throw new Error(\n `Static route ${JSON.stringify(route.file)} does not export GET and cannot produce an output file.`,\n );\n }\n\n if (routeModule.GET.kind === \"page\") {\n routeKinds.set(route.file, \"document\");\n continue;\n }\n\n assertStaticResource(route.file, routeModule.GET);\n routeKinds.set(route.file, \"resource\");\n }\n\n return routeKinds;\n}\n\nfunction staticUnsupportedMethods(routeModule: RouteModule) {\n return ([\"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\", \"HEAD\"] as const)\n .filter((method) => routeModule[method] !== undefined);\n}\n\nfunction assertStaticResource(file: string, capability: RouteCapability) {\n if (\n (capability.kind === \"text\" ||\n capability.kind === \"html\" ||\n capability.kind === \"json\") &&\n typeof capability.value !== \"function\"\n ) {\n return;\n }\n\n const reason = \"value\" in capability && typeof capability.value === \"function\"\n ? `uses a request-dependent ${capability.kind} value`\n : `uses the ${capability.kind} response helper`;\n\n throw new Error(\n `Static route ${JSON.stringify(file)} ${reason} and cannot produce a fixed output file. Use a fixed text, html, or json value, or deploy a runtime adapter.`,\n );\n}\n\nfunction planOutputEntries(\n outputs: Array<{ kind: OutputKind; pathname: string }>,\n) {\n const seenFiles = new Map<string, string>();\n const seenPathnames = new Set<string>();\n\n return outputs.map(({ kind, pathname }) => {\n if (seenPathnames.has(pathname)) {\n throw new Error(`Static output collected duplicate pathname ${JSON.stringify(pathname)}.`);\n }\n\n seenPathnames.add(pathname);\n\n const file = kind === \"document\"\n ? pathnameToDocumentFile(pathname)\n : pathnameToResourceFile(pathname);\n const portableFile = file.toLocaleLowerCase(\"en-US\");\n const conflict = [...seenFiles.entries()].find(([seenFile]) =>\n seenFile === portableFile ||\n seenFile.startsWith(`${portableFile}/`) ||\n portableFile.startsWith(`${seenFile}/`)\n );\n\n if (conflict) {\n throw new Error(\n `Static paths ${JSON.stringify(conflict[1])} and ${JSON.stringify(pathname)} map to the same portable output file or to a file and directory conflict.`,\n );\n }\n\n seenFiles.set(portableFile, pathname);\n\n return { file, kind, pathname };\n });\n}\n\nfunction pathnameToDocumentFile(pathname: string) {\n if (!pathname.startsWith(\"/\") || pathname.includes(\"?\") || pathname.includes(\"#\")) {\n throw new Error(`Static output received invalid pathname ${JSON.stringify(pathname)}.`);\n }\n\n if (pathname === \"/\") {\n return \"index.html\";\n }\n\n const segments = pathname.split(\"/\").slice(1).map((segment) => {\n let decoded: string;\n\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n throw new Error(`Static output pathname is not valid UTF-8: ${JSON.stringify(pathname)}.`);\n }\n\n assertPortableSegment(decoded, pathname);\n return decoded;\n });\n\n return [...segments, \"index.html\"].join(\"/\");\n}\n\nfunction pathnameToResourceFile(pathname: string) {\n if (pathname === \"/\") {\n throw new Error(\"A static resource route cannot own the root pathname.\");\n }\n\n const documentFile = pathnameToDocumentFile(pathname);\n return documentFile.slice(0, -\"/index.html\".length);\n}\n\nfunction assertPortableSegment(segment: string, pathname: string) {\n const invalidWindowsName = /[<>:\"|?*]/.test(segment) ||\n [...segment].some((character) => character.charCodeAt(0) <= 31) ||\n /[. ]$/.test(segment) ||\n /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\\.|$)/i.test(segment);\n\n if (\n !segment ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\") ||\n invalidWindowsName\n ) {\n throw new Error(\n `Static pathname ${JSON.stringify(pathname)} contains a segment that is unsafe or not portable as a file name: ${JSON.stringify(segment)}.`,\n );\n }\n}\n\nfunction createStaticRequest(\n origin: string,\n pathname: string,\n kind: OutputKind,\n) {\n return new Request(`${origin}${pathname}`, {\n headers: { accept: kind === \"document\" ? \"text/html\" : \"*/*\" },\n });\n}\n\nasync function prepareDocumentOutput(\n entry: { file: string; pathname: string },\n response: Response,\n expectedStatus: 200 | 404,\n): Promise<PendingOutput> {\n if (response.status !== expectedStatus) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} returned status ${response.status}; expected ${expectedStatus}.`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n\n if (!contentType?.toLowerCase().startsWith(\"text/html\")) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} returned ${JSON.stringify(contentType)} instead of text/html.`,\n );\n }\n\n if (response.headers.has(\"set-cookie\")) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} attempted to set a cookie. Build artifacts cannot contain per-user response state.`,\n );\n }\n\n const html = await coverStructuredDataHashes(\n await response.text(),\n response.headers,\n );\n await validateStaticCsp(entry.pathname, html, response.headers);\n\n return {\n file: entry.file,\n headers: sortedHeaders(response.headers),\n body: html,\n pathname: entry.pathname,\n status: expectedStatus,\n };\n}\n\nasync function prepareResourceOutput(\n entry: PlannedOutput,\n response: Response,\n): Promise<PendingOutput> {\n if (response.status !== 200) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} returned status ${response.status}; expected 200.`,\n );\n }\n\n if (response.headers.has(\"set-cookie\")) {\n throw new Error(\n `Static output for ${JSON.stringify(entry.pathname)} attempted to set a cookie. Build artifacts cannot contain per-user response state.`,\n );\n }\n\n return {\n file: entry.file,\n headers: sortedHeaders(response.headers),\n body: await response.text(),\n pathname: entry.pathname,\n status: 200,\n };\n}\n\nasync function coverStructuredDataHashes(html: string, headers: Headers) {\n const markerPattern = new RegExp(\n `(?:^|\\\\s)${STRUCTURED_DATA_ATTRIBUTE}(?:\\\\s|$)`,\n );\n const elements = findRawTextElements(html, \"script\")\n .filter((element) => markerPattern.test(element.attributes));\n\n if (elements.length === 0) {\n return html;\n }\n\n const hashes = await Promise.all(\n elements.map((element) => cspHash(element.content)),\n );\n\n for (const headerName of [\n \"content-security-policy\",\n \"content-security-policy-report-only\",\n ]) {\n const csp = headers.get(headerName);\n if (csp) {\n headers.set(headerName, addScriptHashes(csp, hashes));\n }\n }\n\n return html.replace(\n new RegExp(`\\\\s${STRUCTURED_DATA_ATTRIBUTE}(?=\\\\s|>)`, \"g\"),\n \"\",\n );\n}\n\nfunction addScriptHashes(csp: string, hashes: readonly string[]) {\n const directives = csp.split(\";\")\n .map((directive) => directive.trim())\n .filter(Boolean);\n const scriptIndex = directives.findIndex((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"script-src\"\n );\n const defaultDirective = directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n );\n const current = scriptIndex === -1 ? defaultDirective : directives[scriptIndex];\n\n if (!current) {\n return csp;\n }\n\n const sources = current.split(/\\s+/).slice(1)\n .filter((source) => source !== \"'none'\");\n const scriptDirective = [\n \"script-src\",\n ...new Set([...sources, ...hashes]),\n ].join(\" \");\n\n if (scriptIndex === -1) {\n directives.push(scriptDirective);\n } else {\n directives[scriptIndex] = scriptDirective;\n }\n\n return directives.join(\"; \");\n}\n\nasync function validateStaticCsp(\n pathname: string,\n html: string,\n headers: Headers,\n) {\n const csp = headers.get(\"content-security-policy\");\n\n if (!csp) {\n return;\n }\n\n if (/'nonce-[^']+'/i.test(csp) || /\\snonce\\s*=/i.test(html)) {\n throw new Error(\n `Static output for ${JSON.stringify(pathname)} uses a nonce-backed CSP. Use security.static() with stable hashes or a runtime adapter that injects a fresh nonce.`,\n );\n }\n\n const directives = parseCsp(csp);\n\n await validateInlineElements(\n pathname,\n html,\n \"script\",\n effectiveSources(directives, \"script-src\", \"default-src\"),\n );\n await validateInlineElements(\n pathname,\n html,\n \"style\",\n effectiveSources(\n directives,\n \"style-src-elem\",\n \"style-src\",\n \"default-src\",\n ),\n );\n\n const styleAttributeSources = effectiveSources(\n directives,\n \"style-src-attr\",\n \"style-src\",\n \"default-src\",\n );\n\n if (\n styleAttributeSources &&\n /\\sstyle\\s*=/i.test(html) &&\n !styleAttributeSources.includes(\"'unsafe-inline'\")\n ) {\n throw new Error(\n `Static output for ${JSON.stringify(pathname)} contains an inline style attribute that its CSP does not allow. Move the style into a stylesheet or explicitly allow inline styles.`,\n );\n }\n}\n\nfunction parseCsp(value: string) {\n const directives = new Map<string, string[]>();\n\n for (const rawDirective of value.split(\";\")) {\n const [name, ...sources] = rawDirective.trim().split(/\\s+/);\n\n if (name) {\n directives.set(name.toLowerCase(), sources);\n }\n }\n\n return directives;\n}\n\nfunction effectiveSources(\n directives: Map<string, string[]>,\n ...names: string[]\n) {\n for (const name of names) {\n const sources = directives.get(name);\n\n if (sources) {\n return sources;\n }\n }\n\n return undefined;\n}\n\nasync function validateInlineElements(\n pathname: string,\n html: string,\n tagName: \"script\" | \"style\",\n sources: string[] | undefined,\n) {\n if (!sources || sources.includes(\"'unsafe-inline'\")) {\n return;\n }\n\n for (const element of findRawTextElements(html, tagName)) {\n if (tagName === \"script\") {\n const src = readHtmlAttribute(element.attributes, \"src\");\n\n if (src) {\n if (!allowsStaticScriptSource(sources, src)) {\n throw new Error(\n `Static output for ${JSON.stringify(pathname)} contains script ${JSON.stringify(src)} that the effective script-src directive does not allow. Add its origin to security.needs.script or the route CSP policy.`,\n );\n }\n\n continue;\n }\n }\n\n if (!element.content) {\n continue;\n }\n\n const hash = await cspHash(element.content);\n\n if (!sources.includes(hash)) {\n throw new Error(\n `Static output for ${JSON.stringify(pathname)} contains an inline ${tagName} without the required CSP hash ${hash}.`,\n );\n }\n }\n}\n\nfunction readHtmlAttribute(attributes: string, name: string) {\n const match = attributes.match(\n new RegExp(`(?:^|\\\\s)${name}\\\\s*=\\\\s*[\"']([^\"']+)[\"']`, \"i\"),\n );\n\n return match?.[1]?.replaceAll(\"&amp;\", \"&\");\n}\n\nfunction allowsStaticScriptSource(\n sources: string[] | undefined,\n src: string,\n) {\n if (!sources) {\n return true;\n }\n\n if (sources.includes(\"'none'\")) {\n return false;\n }\n\n if (\n sources.includes(\"'strict-dynamic'\") &&\n sources.some((source) =>\n source.startsWith(\"'nonce-\") || /^'sha(?:256|384|512)-/.test(source)\n )\n ) {\n return false;\n }\n\n if (sources.includes(\"*\")) {\n return true;\n }\n\n if (sources.includes(\"'self'\") && src.startsWith(\"/\") && !src.startsWith(\"//\")) {\n return true;\n }\n\n if (src.startsWith(\"https:\") && sources.includes(\"https:\")) {\n return true;\n }\n\n if (src.startsWith(\"http:\") && sources.includes(\"http:\")) {\n return true;\n }\n\n let scriptUrl: URL;\n try {\n scriptUrl = new URL(src, \"https://demiurge.invalid\");\n } catch {\n return false;\n }\n\n return sources.some((source) => {\n if (source.startsWith(\"'\")) {\n return false;\n }\n\n let sourceUrl: URL;\n try {\n sourceUrl = new URL(source);\n } catch {\n return false;\n }\n\n const hostnameMatches = sourceUrl.hostname.startsWith(\"*.\")\n ? scriptUrl.hostname.endsWith(sourceUrl.hostname.slice(1)) &&\n scriptUrl.hostname !== sourceUrl.hostname.slice(2)\n : scriptUrl.hostname === sourceUrl.hostname;\n const pathMatches = sourceUrl.pathname === \"/\" ||\n sourceUrl.pathname.endsWith(\"/\")\n ? scriptUrl.pathname.startsWith(sourceUrl.pathname)\n : scriptUrl.pathname === sourceUrl.pathname;\n\n return scriptUrl.protocol === sourceUrl.protocol &&\n hostnameMatches &&\n scriptUrl.port === sourceUrl.port &&\n pathMatches;\n });\n}\n\nfunction findRawTextElements(html: string, tagName: \"script\" | \"style\") {\n const lowerHtml = html.toLowerCase();\n const elements: Array<{ attributes: string; content: string }> = [];\n const opening = `<${tagName}`;\n const closing = `</${tagName}`;\n let cursor = 0;\n\n while (cursor < html.length) {\n const start = lowerHtml.indexOf(opening, cursor);\n\n if (start === -1) {\n break;\n }\n\n const openEnd = lowerHtml.indexOf(\">\", start + opening.length);\n const closeStart = openEnd === -1\n ? -1\n : lowerHtml.indexOf(closing, openEnd + 1);\n const closeEnd = closeStart === -1\n ? -1\n : lowerHtml.indexOf(\">\", closeStart + closing.length);\n\n if (openEnd === -1 || closeStart === -1 || closeEnd === -1) {\n throw new Error(`Static output contains an unclosed <${tagName}> element.`);\n }\n\n elements.push({\n attributes: html.slice(start + opening.length, openEnd),\n content: html.slice(openEnd + 1, closeStart),\n });\n cursor = closeEnd + 1;\n }\n\n return elements;\n}\n\nfunction sortedHeaders(headers: Headers) {\n return Object.fromEntries(\n [...headers.entries()].sort(([left], [right]) => left.localeCompare(right)),\n );\n}\n\nasync function writeOutput(\n outDir: string,\n entries: PendingOutput[],\n assets: PendingAsset[],\n manifest: StaticOutputManifest,\n) {\n const parent = dirname(outDir);\n await mkdir(parent, { recursive: true });\n const staging = await mkdtemp(join(parent, \".demiurge-static-\"));\n\n try {\n for (const output of [...entries, ...assets]) {\n const file = resolveContained(staging, output.file);\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, output.body);\n }\n\n await writeFile(\n join(staging, STATIC_MANIFEST_FILE),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n );\n\n const previousFiles = await readPreviousOutputFiles(outDir);\n await mkdir(outDir, { recursive: true });\n await cp(staging, outDir, { recursive: true, force: true });\n\n const currentFiles = new Set(\n [...entries, ...assets].map((output) => output.file),\n );\n\n for (const file of previousFiles) {\n if (!currentFiles.has(file)) {\n await rm(resolveContained(outDir, file), { force: true });\n }\n }\n } finally {\n await rm(staging, { force: true, recursive: true });\n }\n}\n\nasync function readPreviousOutputFiles(outDir: string) {\n try {\n const source = await readFile(join(outDir, STATIC_MANIFEST_FILE), \"utf8\");\n // TYPE-EVIDENCE: the manifest file is JSON that the static build serialized. The cast describes its expected shape before validation.\n const value = JSON.parse(source) as {\n adapter?: unknown;\n entries?: Array<{ file?: unknown }>;\n fontFiles?: unknown;\n imageFiles?: unknown;\n version?: unknown;\n };\n\n if (\n value.adapter !== \"static\" ||\n value.version !== 1 ||\n !Array.isArray(value.entries)\n ) {\n return [];\n }\n\n const fontFiles = Array.isArray(value.fontFiles) ? value.fontFiles : [];\n const imageFiles = Array.isArray(value.imageFiles) ? value.imageFiles : [];\n\n return [\n ...value.entries.map((entry) => entry.file),\n ...fontFiles,\n ...imageFiles,\n ].flatMap((file) =>\n typeof file === \"string\" && isSafeRelativeFile(file) ? [file] : []\n );\n } catch {\n return [];\n }\n}\n\nfunction resolveContained(root: string, file: string) {\n if (!isSafeRelativeFile(file)) {\n throw new Error(`Static output file must stay inside the output directory: ${JSON.stringify(file)}.`);\n }\n\n const resolvedRoot = resolve(root);\n const resolvedFile = resolve(resolvedRoot, file);\n\n if (relative(resolvedRoot, resolvedFile).split(sep).includes(\"..\")) {\n throw new Error(`Static output file escaped the output directory: ${JSON.stringify(file)}.`);\n }\n\n return resolvedFile;\n}\n\nfunction isSafeRelativeFile(file: string) {\n return Boolean(file) &&\n !file.startsWith(\"/\") &&\n !file.startsWith(\"\\\\\") &&\n !file.split(/[\\\\/]/).includes(\"..\");\n}\n"],"names":["emitImageVariants","options","outDir","resolve","policy","optimizerPath","defaultImageOptimizerPath","paths","document","collectImageVariantPaths","emitted","sources","pathname","descriptor","parseImageVariantPath","isAllowedImageSource","sourceFile","resolveSourceFile","source","readSourceImage","encoded","transformImage","negotiateImageFormat","assertNoOptimizerImages","documents","pattern","src","readFile","error","decoded","file","relative","sep","STATIC_MANIFEST_FILE","contentTypes","createStaticPreviewServer","root","manifest","parseStaticManifest","entries","entry","entriesByFile","rules","rule","server","createServer","request","response","url","routePath","writeEntry","resolvePreviewFile","declaredFile","declaredEntry","body","type","extname","fileName","expression","applyHeaders","isMissingFile","fallback","resolvePromise","reject","onError","method","resolveDeclaredFile","headers","name","value","resolveContained","resolved","pathFromRoot","isRecord","parseEntry","fileHeaderRules","parseRule","pathnames","isStringRecord","item","CLIENT_MANIFEST_FILE","vercelStatic","generateVercelStaticOutput","validateVercelDeployment","projectRoot","sourceRoot","outputRoot","pathsOverlap","outputParent","dirname","mkdir","stagingRoot","mkdtemp","join","staticRoot","cp","writeFile","createVercelOutputConfig","rm","rename","deployment","applicationRoutes","transformApplicationCache","routes","resolveVercelCorsOrigin","filePath","exactPathPattern","withoutContentType","translateFileHeaderPattern","route","fallbackHeaders","normalized","normalizeRoutes","createOverride","override","contentType","naturalPath","escaped","CONTENT_HASHED_FILE_NAME_PATTERN","translateFileNamePattern","startsAtBasename","endsAtBasename","cache","transformed","getTransformedRoutes","cors","origin","validateCorsPolicy","left","right","fromLeft","fromRight","isSameOrChildPath","staticAdapter","defineAdapter","staticRouteLoadConcurrency","loadRouteModules","modules","next","workers","index","load","generateStaticOutput","routeModules","validateRouteModules","normalizeOrigin","routeKinds","validateStaticRoutes","collectStaticRoutePaths","assertStaticPageApp","path","outputEntries","planOutputEntries","rateLimitStore","createMemoryRateLimitStore","pending","ssr","createStaticRequest","handleRequestWithManifest","prepareDocumentOutput","prepareResourceOutput","notFoundResponse","renderNotFoundResponse","site","images","fonts","resolveFontAssets","outputManifest","_body","createStaticFileHeaderRules","asset","image","writeOutput","patternRules","baseline","loadBaselineFileSecurityPolicy","baselineHeaders","renderStaticFileHeaders","assertValidFileHeaderPattern","mergeSecurityPolicies","IMMUTABLE_FILE_CACHE_CONTROL","REVALIDATED_FILE_CACHE_CONTROL","createSecurityHeaders","pageCount","routeModule","unsupportedMethods","staticUnsupportedMethods","assertStaticResource","capability","reason","outputs","seenFiles","seenPathnames","kind","pathnameToDocumentFile","pathnameToResourceFile","portableFile","conflict","seenFile","segment","assertPortableSegment","invalidWindowsName","character","expectedStatus","html","coverStructuredDataHashes","validateStaticCsp","sortedHeaders","markerPattern","STRUCTURED_DATA_ATTRIBUTE","elements","findRawTextElements","element","hashes","cspHash","headerName","csp","addScriptHashes","directives","directive","scriptIndex","defaultDirective","current","scriptDirective","parseCsp","validateInlineElements","effectiveSources","styleAttributeSources","rawDirective","names","tagName","readHtmlAttribute","allowsStaticScriptSource","hash","attributes","scriptUrl","sourceUrl","hostnameMatches","pathMatches","lowerHtml","opening","closing","cursor","start","openEnd","closeStart","closeEnd","assets","parent","staging","output","previousFiles","readPreviousOutputFiles","currentFiles","fontFiles","imageFiles","isSafeRelativeFile","resolvedRoot","resolvedFile"],"mappings":";;;;;;;;;;;;AA+BA,eAAsBA,GACpBC,GACgC;AAChC,QAAMC,IAASC,EAAQF,EAAQ,MAAM,GAC/BG,IAASH,EAAQ,UAAU,CAAA,GAC3BI,IAAgBD,EAAO,iBAAiBE,GACxCC,IAAQ,IAAI;AAAA,IAChBN,EAAQ,UAAU;AAAA,MAAQ,CAACO,MACzBC,GAAyBD,GAAUH,CAAa;AAAA,IAAA;AAAA,EAClD,GAEIK,IAAiC,CAAA,GACjCC,wBAAc,IAAA;AAEpB,aAAWC,KAAY,CAAC,GAAGL,CAAK,EAAE,QAAQ;AACxC,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AQiC,CAAI,GAC3B8N,IAAe/P,EAAQ8P,GAAcnO,CAAI;AAE/C,MAAIC,EAASkO,GAAcC,CAAY,EAAE,MAAMlO,CAAG,EAAE,SAAS,IAAI;AAC/D,UAAM,IAAI,MAAM,oDAAoD,KAAK,UAAUF,CAAI,CAAC,GAAG;AAG7F,SAAOoO;AACT;AAEA,SAASF,EAAmBlO,GAAc;AACxC,SAAO,EAAQA,KACb,CAACA,EAAK,WAAW,GAAG,KACpB,CAACA,EAAK,WAAW,IAAI,KACrB,CAACA,EAAK,MAAM,OAAO,EAAE,SAAS,IAAI;AACtC;"}
@@ -1,5 +1,8 @@
1
1
  export { demiurge } from "./plugin";
2
2
  export { assertRootNotFoundRoute as unstable_assertRootNotFoundRoute, declaresPageRoute as unstable_declaresPageRoute, createClientEntrySource as unstable_createClientEntrySource, createServerEntrySource as unstable_createServerEntrySource, createDocumentHtml as unstable_createDocumentHtml, createDevRouteImporters as unstable_createDevRouteImporters, handleDevRequest as unstable_handleDevRequest, stripClientPageData as unstable_stripClientPageData, verifyRoutePolicies as unstable_verifyRoutePolicies, formatStaticPolicyFindings as unstable_formatStaticPolicyFindings, } from "./plugin";
3
+ export { isRouteAuditEnabled as unstable_isRouteAuditEnabled, } from "./plugin";
3
4
  export { verifyRoutePolicySource as unstable_verifyRoutePolicySource, } from "./policy-verification";
5
+ export { createRouteAudit as unstable_createRouteAudit, renderRouteAuditDocument as unstable_renderRouteAuditDocument, ROUTE_AUDIT_PATH as unstable_ROUTE_AUDIT_PATH, } from "./route-audit";
4
6
  export type { DemiurgeVitePluginApi, DemiurgeVitePluginOptions, } from "./plugin";
7
+ export type { RouteAudit, RouteAuditCacheRead, RouteAuditRoute, RouteAuditScript, } from "./route-audit";
5
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,C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