@demiurgejs/core 0.1.1 → 0.2.0-beta.1
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.
- package/README.md +3 -0
- package/bin/demiurge.mjs +51 -0
- package/dist/chunks/request-metadata-DwEO1EAS.js +477 -0
- package/dist/chunks/request-metadata-DwEO1EAS.js.map +1 -0
- package/dist/chunks/{streaming-DN1DnbRE.js → streaming-Ci6vf3BB.js} +117 -107
- package/dist/chunks/streaming-Ci6vf3BB.js.map +1 -0
- package/dist/chunks/{testing-DR3eQAvY.js → testing-DBjVCN5v.js} +2384 -1942
- package/dist/chunks/testing-DBjVCN5v.js.map +1 -0
- package/dist/cli.d.ts +42 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +164 -0
- package/dist/cli.js.map +1 -0
- package/dist/document/index.d.ts +2 -2
- package/dist/document/index.d.ts.map +1 -1
- package/dist/document/render.d.ts +1 -1
- package/dist/document/render.d.ts.map +1 -1
- package/dist/document/scripts.d.ts +22 -0
- package/dist/document/scripts.d.ts.map +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +817 -969
- package/dist/index.js.map +1 -1
- package/dist/internal/testing.js +15 -14
- package/dist/internal/testing.js.map +1 -1
- package/dist/node/index.js +3 -3
- package/dist/node/streaming.d.ts +2 -0
- package/dist/node/streaming.d.ts.map +1 -1
- package/dist/route/action.d.ts +11 -11
- package/dist/route/action.d.ts.map +1 -1
- package/dist/route/index.d.ts +2 -1
- package/dist/route/index.d.ts.map +1 -1
- package/dist/route/middleware.d.ts +7 -0
- package/dist/route/middleware.d.ts.map +1 -0
- package/dist/route/page.d.ts +2 -2
- package/dist/route/page.d.ts.map +1 -1
- package/dist/route/response.d.ts +19 -19
- package/dist/route/response.d.ts.map +1 -1
- package/dist/route/types.d.ts +55 -31
- package/dist/route/types.d.ts.map +1 -1
- package/dist/route/webhook.d.ts +1 -1
- package/dist/router/manifest.d.ts +1 -0
- package/dist/router/manifest.d.ts.map +1 -1
- package/dist/routing/generate.d.ts +2 -0
- package/dist/routing/generate.d.ts.map +1 -1
- package/dist/routing/index.d.ts +1 -1
- package/dist/routing/index.d.ts.map +1 -1
- package/dist/routing/types.d.ts +2 -0
- package/dist/routing/types.d.ts.map +1 -1
- package/dist/security/cors.d.ts.map +1 -1
- package/dist/security/index.d.ts +4 -2
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/policy.d.ts +31 -2
- package/dist/security/policy.d.ts.map +1 -1
- package/dist/security/types.d.ts +27 -13
- package/dist/security/types.d.ts.map +1 -1
- package/dist/security/verification.d.ts +8 -0
- package/dist/security/verification.d.ts.map +1 -0
- package/dist/server/errors.d.ts.map +1 -1
- package/dist/server/not-found.d.ts.map +1 -1
- package/dist/server/render-tree.d.ts +6 -1
- package/dist/server/render-tree.d.ts.map +1 -1
- package/dist/server/request-handler.d.ts +4 -1
- package/dist/server/request-handler.d.ts.map +1 -1
- package/dist/server/ssr.d.ts +1 -0
- package/dist/server/ssr.d.ts.map +1 -1
- package/dist/static/index.d.ts +10 -0
- package/dist/static/index.d.ts.map +1 -1
- package/dist/static/index.js +579 -139
- package/dist/static/index.js.map +1 -1
- package/dist/static/preview.d.ts +8 -0
- package/dist/static/preview.d.ts.map +1 -0
- package/dist/static/vercel.d.ts +31 -0
- package/dist/static/vercel.d.ts.map +1 -0
- package/dist/vite/index.d.ts +3 -2
- package/dist/vite/index.d.ts.map +1 -1
- package/dist/vite/index.js +754 -326
- package/dist/vite/index.js.map +1 -1
- package/dist/vite/plugin.d.ts +13 -0
- package/dist/vite/plugin.d.ts.map +1 -1
- package/dist/vite/policy-verification.d.ts +10 -0
- package/dist/vite/policy-verification.d.ts.map +1 -0
- package/package.json +6 -1
- package/dist/chunks/index-BnX9Qxbm.js +0 -44
- package/dist/chunks/index-BnX9Qxbm.js.map +0 -1
- package/dist/chunks/ssr-BJejKlkZ.js +0 -275
- package/dist/chunks/ssr-BJejKlkZ.js.map +0 -1
- package/dist/chunks/streaming-DN1DnbRE.js.map +0 -1
- package/dist/chunks/testing-DR3eQAvY.js.map +0 -1
package/dist/static/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/static/index.ts"],"sourcesContent":["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 createRouteManifest,\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 { createMemoryRateLimitStore, cspHash } from \"../security\";\nimport {\n CONTENT_HASHED_FILE_NAME_PATTERN,\n IMMUTABLE_FILE_CACHE_CONTROL,\n REVALIDATED_FILE_CACHE_CONTROL,\n} from \"../static-files\";\n\nconst STATIC_MANIFEST_FILE = \"demiurge-static-manifest.json\";\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 version: 1;\n};\n\nexport type StaticOutputFileHeaderRule = {\n headers: Record<string, string>;\n pattern: string;\n};\n\nexport type GenerateStaticOutputOptions = {\n onError?: RequestErrorReporter;\n origin?: string;\n outDir: string;\n routes: Record<string, RouteImporter>;\n ssr?: SsrOptions;\n};\n\ntype PendingOutput = StaticOutputEntry & {\n body: string;\n};\n\ntype OutputKind = \"document\" | \"resource\";\n\ntype PlannedOutput = {\n file: string;\n kind: OutputKind;\n pathname: string;\n};\n\nexport async function generateStaticOutput(\n options: GenerateStaticOutputOptions,\n): Promise<StaticOutputManifest> {\n const origin = normalizeOrigin(options.origin);\n const outDir = resolve(options.outDir);\n const manifest = createRouteManifest(options.routes);\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 pending.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: createStaticFileHeaderRules(),\n version: 1,\n };\n\n await writeOutput(outDir, pending, outputManifest);\n\n return outputManifest;\n}\n\nfunction createStaticFileHeaderRules(): StaticOutputFileHeaderRule[] {\n return [\n {\n headers: { \"cache-control\": IMMUTABLE_FILE_CACHE_CONTROL },\n pattern: CONTENT_HASHED_FILE_NAME_PATTERN.source,\n },\n {\n headers: { \"cache-control\": REVALIDATED_FILE_CACHE_CONTROL },\n 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\"),\n );\n await validateInlineElements(\n pathname,\n html,\n \"style\",\n effectiveSources(directives, \"style-src\"),\n );\n\n const styleSources = effectiveSources(directives, \"style-src\");\n\n if (\n styleSources &&\n /\\sstyle\\s*=/i.test(html) &&\n !styleSources.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(directives: Map<string, string[]>, name: string) {\n return directives.get(name) ?? directives.get(\"default-src\");\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\" && /(?:^|\\s)src\\s*=/i.test(element.attributes)) {\n continue;\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 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 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 entry of entries) {\n const file = resolveContained(staging, entry.file);\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, entry.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(entries.map((entry) => entry.file));\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 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 return value.entries.flatMap((entry) =>\n typeof entry.file === \"string\" &&\n isSafeRelativeFile(entry.file)\n ? [entry.file]\n : []\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":["STATIC_MANIFEST_FILE","staticAdapter","defineAdapter","generateStaticOutput","options","origin","normalizeOrigin","outDir","resolve","manifest","createRouteManifest","routeKinds","validateStaticRoutes","paths","collectStaticRoutePaths","assertStaticPageApp","path","outputEntries","planOutputEntries","rateLimitStore","createMemoryRateLimitStore","pending","ssr","entry","request","createStaticRequest","response","handleRequestWithManifest","prepareDocumentOutput","prepareResourceOutput","notFoundResponse","renderNotFoundResponse","error","site","left","right","outputManifest","_body","createStaticFileHeaderRules","writeOutput","IMMUTABLE_FILE_CACHE_CONTROL","CONTENT_HASHED_FILE_NAME_PATTERN","REVALIDATED_FILE_CACHE_CONTROL","value","pageCount","fallback","route","routeModule","unsupportedMethods","staticUnsupportedMethods","assertStaticResource","method","file","capability","reason","outputs","seenFiles","seenPathnames","kind","pathname","pathnameToDocumentFile","pathnameToResourceFile","portableFile","conflict","seenFile","segment","decoded","assertPortableSegment","invalidWindowsName","character","expectedStatus","contentType","html","coverStructuredDataHashes","validateStaticCsp","sortedHeaders","headers","markerPattern","STRUCTURED_DATA_ATTRIBUTE","elements","findRawTextElements","element","hashes","cspHash","headerName","csp","addScriptHashes","directives","directive","scriptIndex","defaultDirective","current","sources","source","scriptDirective","parseCsp","validateInlineElements","effectiveSources","styleSources","rawDirective","name","tagName","hash","lowerHtml","opening","closing","cursor","start","openEnd","closeStart","closeEnd","entries","parent","dirname","mkdir","staging","mkdtemp","join","resolveContained","writeFile","previousFiles","readPreviousOutputFiles","cp","currentFiles","rm","readFile","isSafeRelativeFile","root","resolvedRoot","resolvedFile","relative","sep"],"mappings":";;;;;;;;;AA8BA,MAAMA,IAAuB,iCAEhBC,KAAgBC,EAAc;AAAA,EACzC,MAAM;AAAA,EACN,cAAc;AAAA,IACZ,cAAc;AAAA,EAAA;AAElB,CAAC;AAyCD,eAAsBC,GACpBC,GAC+B;AAC/B,QAAMC,IAASC,EAAgBF,EAAQ,MAAM,GACvCG,IAASC,EAAQJ,EAAQ,MAAM,GAC/BK,IAAWC,EAAoBN,EAAQ,MAAM,GAC7CO,IAAa,MAAMC,EAAqBH,CAAQ,GAChDI,IAAQ,MAAMC,EAAwBL,GAAU;AAAA,IACpD,kBAAkB;AAAA,EAAA,CACnB;AAED,EAAAM;AAAA,IACEN;AAAA,IACAI,EAAM,OAAO,CAACG,MAASL,EAAW,IAAIK,EAAK,IAAI,MAAM,UAAU,EAAE;AAAA,EAAA;AAGnE,QAAMC,IAAgBC;AAAA,IACpBL,EAAM,IAAI,CAACG,OAAU;AAAA,MACnB,MAAML,EAAW,IAAIK,EAAK,IAAI,KAAK;AAAA,MACnC,UAAUA,EAAK;AAAA,IAAA,EACf;AAAA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AO,EAAE,SAAS,IAAI;AACtC;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../src/static/preview.ts","../../src/static/vercel.ts","../../src/static/index.ts"],"sourcesContent":["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 { 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};\n\nexport type VercelStaticDeployment = {\n adapter: \"vercel\";\n cache: VercelStaticCacheRule[];\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 };\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 routes: Route[] = [];\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\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\";\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 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 onError?: RequestErrorReporter;\n origin?: string;\n outDir: string;\n routes: Record<string, RouteImporter>;\n ssr?: SsrOptions;\n staticFileHeaders?: readonly StaticFileHeaderPatternRule[];\n};\n\ntype PendingOutput = StaticOutputEntry & {\n body: 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 pending.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 version: 1,\n };\n\n await writeOutput(outDir, pending, 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(\"&\", \"&\");\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 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 entry of entries) {\n const file = resolveContained(staging, entry.file);\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, entry.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(entries.map((entry) => entry.file));\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 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 return value.entries.flatMap((entry) =>\n typeof entry.file === \"string\" &&\n isSafeRelativeFile(entry.file)\n ? [entry.file]\n : []\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":["STATIC_MANIFEST_FILE","contentTypes","createStaticPreviewServer","options","root","resolve","manifest","parseStaticManifest","readFile","entries","entry","entriesByFile","rules","rule","server","createServer","request","response","url","pathname","routePath","writeEntry","file","resolvePreviewFile","declaredFile","relative","sep","declaredEntry","body","type","extname","fileName","expression","applyHeaders","error","isMissingFile","fallback","resolvePromise","reject","onError","method","resolveDeclaredFile","headers","name","value","resolveContained","resolved","pathFromRoot","source","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","filePath","exactPathPattern","withoutContentType","translateFileHeaderPattern","route","fallbackHeaders","normalized","normalizeRoutes","createOverride","override","contentType","naturalPath","escaped","pattern","CONTENT_HASHED_FILE_NAME_PATTERN","translateFileNamePattern","startsAtBasename","endsAtBasename","cache","transformed","getTransformedRoutes","left","right","fromLeft","fromRight","isSameOrChildPath","staticAdapter","defineAdapter","staticRouteLoadConcurrency","loadRouteModules","modules","next","workers","index","load","generateStaticOutput","routeModules","validateRouteModules","origin","normalizeOrigin","outDir","routeKinds","validateStaticRoutes","paths","collectStaticRoutePaths","assertStaticPageApp","path","outputEntries","planOutputEntries","rateLimitStore","createMemoryRateLimitStore","pending","ssr","createStaticRequest","handleRequestWithManifest","prepareDocumentOutput","prepareResourceOutput","notFoundResponse","renderNotFoundResponse","site","outputManifest","_body","createStaticFileHeaderRules","writeOutput","patternRules","baseline","loadBaselineFileSecurityPolicy","baselineHeaders","renderStaticFileHeaders","assertValidFileHeaderPattern","mergeSecurityPolicies","IMMUTABLE_FILE_CACHE_CONTROL","REVALIDATED_FILE_CACHE_CONTROL","policy","createSecurityHeaders","pageCount","routeModule","unsupportedMethods","staticUnsupportedMethods","assertStaticResource","capability","reason","outputs","seenFiles","seenPathnames","kind","pathnameToDocumentFile","pathnameToResourceFile","portableFile","conflict","seenFile","segment","decoded","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","sources","scriptDirective","parseCsp","validateInlineElements","effectiveSources","styleAttributeSources","rawDirective","names","tagName","src","readHtmlAttribute","allowsStaticScriptSource","hash","attributes","scriptUrl","sourceUrl","hostnameMatches","pathMatches","lowerHtml","opening","closing","cursor","start","openEnd","closeStart","closeEnd","parent","staging","previousFiles","readPreviousOutputFiles","currentFiles","isSafeRelativeFile","resolvedRoot","resolvedFile"],"mappings":";;;;;;;;;;AASA,MAAMA,KAAuB,iCAQvBC,KAAuC;AAAA,EAC3C,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,gBAAgB;AAAA,EAChB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,UAAU;AACZ;AAEA,eAAsBC,GACpBC,GACiB;AACjB,QAAMC,IAAOC,EAAQF,EAAQ,MAAM,GAC7BG,IAAWC;AAAA,IACf,MAAMC,EAASH,EAAQD,GAAMJ,EAAoB,GAAG,MAAM;AAAA,EAAA,GAEtDS,IAAU,IAAI;AAAA,IAClBH,EAAS,QAAQ,IAAI,CAACI,MAAU,CAACA,EAAM,UAAUA,CAAK,CAAC;AAAA,EAAA,GAEnDC,IAAgB,IAAI;AAAA,IACxBL,EAAS,QAAQ,IAAI,CAACI,MAAU,CAACA,EAAM,MAAMA,CAAK,CAAC;AAAA,EAAA,GAE/CE,IAAQN,EAAS,gBAAgB,IAAI,CAACO,OAAU;AAAA,IACpD,GAAGA;AAAA,IACH,YAAY,IAAI,OAAOA,EAAK,OAAO;AAAA,EAAA,EACnC,GAEIC,IAASC,GAAa,OAAOC,GAASC,MAAa;AACvD,QAAI;AACF,UAAID,EAAQ,WAAW,SAASA,EAAQ,WAAW,QAAQ;AACzD,QAAAC,EAAS,UAAU,KAAK,EAAE,OAAO,aAAa,GAC9CA,EAAS,IAAA;AACT;AAAA,MACF;AAEA,YAAMC,IAAM,IAAI,IAAIF,EAAQ,OAAO,KAA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;AACE,UAAMoD,EAAGqJ,GAAS,EAAE,OAAO,IAAM,WAAW,IAAM;AAAA,EACpD;AACF;AAEA,eAAeE,GAAwBzG,GAAgB;AACrD,MAAI;AACF,UAAMxE,IAAS,MAAMxC,EAAS6D,EAAKmD,GAAQxH,CAAoB,GAAG,MAAM,GAClE4C,IAAQ,KAAK,MAAMI,CAAM;AAM/B,WACEJ,EAAM,YAAY,YAClBA,EAAM,YAAY,KAClB,CAAC,MAAM,QAAQA,EAAM,OAAO,IAErB,CAAA,IAGFA,EAAM,QAAQ;AAAA,MAAQ,CAAClC,MAC5B,OAAOA,EAAM,QAAS,YACpByN,EAAmBzN,EAAM,IAAI,IAC3B,CAACA,EAAM,IAAI,IACX,CAAA;AAAA,IAAC;AAAA,EAET,QAAQ;AACN,WAAO,CAAA;AAAA,EACT;AACF;AAEA,SAASmC,EAAiBzC,GAAckB,GAAc;AACpD,MAAI,CAAC6M,EAAmB7M,CAAI;AAC1B,UAAM,IAAI,MAAM,6DAA6D,KAAK,UAAUA,CAAI,CAAC,GAAG;AAGtG,QAAM8M,IAAe/N,EAAQD,CAAI,GAC3BiO,IAAehO,EAAQ+N,GAAc9M,CAAI;AAE/C,MAAIG,EAAS2M,GAAcC,CAAY,EAAE,MAAM3M,CAAG,EAAE,SAAS,IAAI;AAC/D,UAAM,IAAI,MAAM,oDAAoD,KAAK,UAAUJ,CAAI,CAAC,GAAG;AAG7F,SAAO+M;AACT;AAEA,SAASF,EAAmB7M,GAAc;AACxC,SAAO,EAAQA,KACb,CAACA,EAAK,WAAW,GAAG,KACpB,CAACA,EAAK,WAAW,IAAI,KACrB,CAACA,EAAK,MAAM,OAAO,EAAE,SAAS,IAAI;AACtC;"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Server } from "node:http";
|
|
2
|
+
export type StaticPreviewOptions = {
|
|
3
|
+
host?: string;
|
|
4
|
+
outDir: string;
|
|
5
|
+
port?: number;
|
|
6
|
+
};
|
|
7
|
+
export declare function createStaticPreviewServer(options: StaticPreviewOptions): Promise<Server>;
|
|
8
|
+
//# sourceMappingURL=preview.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"preview.d.ts","sourceRoot":"","sources":["../../src/static/preview.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,MAAM,EAAE,MAAM,WAAW,CAAC;AAWtD,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAAC;AAsBF,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,MAAM,CAAC,CAoGjB"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type Route } from "@vercel/routing-utils";
|
|
2
|
+
import type { StaticOutputManifest } from "./index";
|
|
3
|
+
export type VercelStaticCacheRule = {
|
|
4
|
+
source: string;
|
|
5
|
+
value: string;
|
|
6
|
+
};
|
|
7
|
+
export type VercelStaticOptions = {
|
|
8
|
+
cache?: VercelStaticCacheRule[];
|
|
9
|
+
};
|
|
10
|
+
export type VercelStaticDeployment = {
|
|
11
|
+
adapter: "vercel";
|
|
12
|
+
cache: VercelStaticCacheRule[];
|
|
13
|
+
};
|
|
14
|
+
export type VercelOutputRoute = Route;
|
|
15
|
+
export type VercelOutputConfig = {
|
|
16
|
+
overrides: Record<string, {
|
|
17
|
+
contentType?: string;
|
|
18
|
+
path?: string;
|
|
19
|
+
}>;
|
|
20
|
+
routes: VercelOutputRoute[];
|
|
21
|
+
version: 3;
|
|
22
|
+
};
|
|
23
|
+
export declare function vercelStatic(options?: VercelStaticOptions): VercelStaticDeployment;
|
|
24
|
+
export declare function generateVercelStaticOutput(options: {
|
|
25
|
+
deployment: VercelStaticDeployment;
|
|
26
|
+
manifest: StaticOutputManifest;
|
|
27
|
+
outDir: string;
|
|
28
|
+
projectRoot: string;
|
|
29
|
+
}): Promise<string>;
|
|
30
|
+
export declare function createVercelOutputConfig(manifest: StaticOutputManifest, deployment: VercelStaticDeployment): VercelOutputConfig;
|
|
31
|
+
//# sourceMappingURL=vercel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vercel.d.ts","sourceRoot":"","sources":["../../src/static/vercel.ts"],"names":[],"mappings":"AASA,OAAO,EAIL,KAAK,KAAK,EACX,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAEV,oBAAoB,EACrB,MAAM,SAAS,CAAC;AAKjB,MAAM,MAAM,qBAAqB,GAAG;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,KAAK,CAAC,EAAE,qBAAqB,EAAE,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG;IACnC,OAAO,EAAE,QAAQ,CAAC;IAClB,KAAK,EAAE,qBAAqB,EAAE,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAEtC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE;QACxB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,IAAI,CAAC,EAAE,MAAM,CAAC;KACf,CAAC,CAAC;IACH,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,OAAO,EAAE,CAAC,CAAC;CACZ,CAAC;AAEF,wBAAgB,YAAY,CAC1B,OAAO,GAAE,mBAAwB,GAChC,sBAAsB,CAQxB;AAED,wBAAsB,0BAA0B,CAAC,OAAO,EAAE;IACxD,UAAU,EAAE,sBAAsB,CAAC;IACnC,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;CACrB,mBAyCA;AAED,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,oBAAoB,EAC9B,UAAU,EAAE,sBAAsB,GACjC,kBAAkB,CA0FpB"}
|
package/dist/vite/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { demiurge } from "./plugin";
|
|
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, } from "./plugin";
|
|
3
|
-
export
|
|
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 { verifyRoutePolicySource as unstable_verifyRoutePolicySource, } from "./policy-verification";
|
|
4
|
+
export type { DemiurgeVitePluginApi, DemiurgeVitePluginOptions, } from "./plugin";
|
|
4
5
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/vite/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EACL,uBAAuB,IAAI,gCAAgC,EAC3D,iBAAiB,IAAI,0BAA0B,EAC/C,uBAAuB,IAAI,gCAAgC,EAC3D,uBAAuB,IAAI,gCAAgC,EAC3D,kBAAkB,IAAI,2BAA2B,EACjD,uBAAuB,IAAI,gCAAgC,EAC3D,gBAAgB,IAAI,yBAAyB,EAC7C,mBAAmB,IAAI,4BAA4B,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/vite/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EACL,uBAAuB,IAAI,gCAAgC,EAC3D,iBAAiB,IAAI,0BAA0B,EAC/C,uBAAuB,IAAI,gCAAgC,EAC3D,uBAAuB,IAAI,gCAAgC,EAC3D,kBAAkB,IAAI,2BAA2B,EACjD,uBAAuB,IAAI,gCAAgC,EAC3D,gBAAgB,IAAI,yBAAyB,EAC7C,mBAAmB,IAAI,4BAA4B,EACnD,mBAAmB,IAAI,4BAA4B,EACnD,0BAA0B,IAAI,mCAAmC,GAClE,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,uBAAuB,IAAI,gCAAgC,GAC5D,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EACV,qBAAqB,EACrB,yBAAyB,GAC1B,MAAM,UAAU,CAAC"}
|