@demiurgejs/core 0.2.0-beta.2 → 0.2.0-beta.4
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 +13 -11
- package/bin/demiurge.mjs +30 -12
- package/dist/adapter/testing.js.map +1 -1
- package/dist/browser/file-router.d.ts +388 -5
- package/dist/browser/file-router.d.ts.map +1 -1
- package/dist/browser/focus.d.ts +20 -0
- package/dist/browser/focus.d.ts.map +1 -0
- package/dist/browser/index.d.ts +7 -1
- package/dist/browser/index.d.ts.map +1 -1
- package/dist/browser/mutation-action.d.ts +81 -0
- package/dist/browser/mutation-action.d.ts.map +1 -0
- package/dist/chunks/document-shell-CpJnFtSC.js +36 -0
- package/dist/chunks/document-shell-CpJnFtSC.js.map +1 -0
- package/dist/chunks/env-startup-DOBYWlZD.js +257 -0
- package/dist/chunks/env-startup-DOBYWlZD.js.map +1 -0
- package/dist/chunks/{image-codec-BGTx_t5K.js → image-codec-BmzWnH6W.js} +2 -2
- package/dist/chunks/{image-codec-BGTx_t5K.js.map → image-codec-BmzWnH6W.js.map} +1 -1
- package/dist/chunks/{images-B9MqcjSA.js → images-BQ80950B.js} +99 -91
- package/dist/chunks/images-BQ80950B.js.map +1 -0
- package/dist/chunks/index-BVk9zWbe.js +832 -0
- package/dist/chunks/index-BVk9zWbe.js.map +1 -0
- package/dist/chunks/manifest-vO6c0G0W.js +19 -0
- package/dist/chunks/manifest-vO6c0G0W.js.map +1 -0
- package/dist/chunks/plugin-BQgMiHxa.js +1827 -0
- package/dist/chunks/plugin-BQgMiHxa.js.map +1 -0
- package/dist/chunks/session-store-ChModVcq.js +92 -0
- package/dist/chunks/session-store-ChModVcq.js.map +1 -0
- package/dist/chunks/static-files-ehaD1kE7.js +51 -0
- package/dist/chunks/static-files-ehaD1kE7.js.map +1 -0
- package/dist/chunks/{streaming-BQ1bykDo.js → streaming-BEbPN7Uk.js} +163 -163
- package/dist/chunks/streaming-BEbPN7Uk.js.map +1 -0
- package/dist/chunks/testing-DueXbMo4.js +4167 -0
- package/dist/chunks/testing-DueXbMo4.js.map +1 -0
- package/dist/chunks/vite-DO70kZA6.js +259 -0
- package/dist/chunks/vite-DO70kZA6.js.map +1 -0
- package/dist/cli.d.ts +17 -25
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +159 -124
- package/dist/cli.js.map +1 -1
- package/dist/config/define.d.ts +3 -0
- package/dist/config/define.d.ts.map +1 -0
- package/dist/config/index.d.ts +7 -0
- package/dist/config/index.d.ts.map +1 -0
- package/dist/config/index.js +78 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/load.d.ts +12 -0
- package/dist/config/load.d.ts.map +1 -0
- package/dist/config/types.d.ts +64 -0
- package/dist/config/types.d.ts.map +1 -0
- package/dist/config/validate.d.ts +9 -0
- package/dist/config/validate.d.ts.map +1 -0
- package/dist/config/vite.d.ts +12 -0
- package/dist/config/vite.d.ts.map +1 -0
- package/dist/data/cache.d.ts +10 -0
- package/dist/data/cache.d.ts.map +1 -1
- package/dist/data/idempotency.d.ts.map +1 -1
- package/dist/data/index.d.ts +3 -1
- package/dist/data/index.d.ts.map +1 -1
- package/dist/data/testing.d.ts.map +1 -1
- package/dist/data/testing.js +94 -72
- package/dist/data/testing.js.map +1 -1
- package/dist/data/tiered.d.ts +7 -0
- package/dist/data/tiered.d.ts.map +1 -0
- package/dist/deployment/testing.d.ts +25 -0
- package/dist/deployment/testing.d.ts.map +1 -0
- package/dist/deployment/testing.js +171 -0
- package/dist/deployment/testing.js.map +1 -0
- package/dist/document/deferred-scripts.d.ts.map +1 -1
- package/dist/document/hydration.d.ts +9 -0
- package/dist/document/hydration.d.ts.map +1 -1
- package/dist/document/index.d.ts +5 -2
- package/dist/document/index.d.ts.map +1 -1
- package/dist/document/metadata.d.ts +8 -0
- package/dist/document/metadata.d.ts.map +1 -1
- package/dist/document/navigation.d.ts +28 -0
- package/dist/document/navigation.d.ts.map +1 -0
- package/dist/document/render.d.ts +3 -1
- package/dist/document/render.d.ts.map +1 -1
- package/dist/document/seo.d.ts.map +1 -1
- package/dist/document/trusted-types.d.ts +10 -0
- package/dist/document/trusted-types.d.ts.map +1 -0
- package/dist/edge/assets.d.ts.map +1 -1
- package/dist/edge/index.js +55 -73
- package/dist/edge/index.js.map +1 -1
- package/dist/index.d.ts +15 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2078 -573
- package/dist/index.js.map +1 -1
- package/dist/internal/testing.js +11 -11
- package/dist/kv/index.d.ts +4 -0
- package/dist/kv/index.d.ts.map +1 -1
- package/dist/kv/index.js +180 -60
- package/dist/kv/index.js.map +1 -1
- package/dist/kv/rate-limit-store.d.ts +8 -0
- package/dist/kv/rate-limit-store.d.ts.map +1 -0
- package/dist/kv/session-store.d.ts +20 -0
- package/dist/kv/session-store.d.ts.map +1 -0
- package/dist/kv/store.d.ts.map +1 -1
- package/dist/manifest.d.ts +10 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/node/http.d.ts.map +1 -1
- package/dist/node/image.d.ts.map +1 -1
- package/dist/node/index.d.ts +3 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +251 -178
- package/dist/node/index.js.map +1 -1
- package/dist/node/serve.d.ts +47 -0
- package/dist/node/serve.d.ts.map +1 -0
- package/dist/node/static.d.ts.map +1 -1
- package/dist/node/streaming.d.ts.map +1 -1
- package/dist/platform/fonts.d.ts.map +1 -1
- package/dist/platform/image-url.d.ts.map +1 -1
- package/dist/platform/images.d.ts.map +1 -1
- package/dist/platform/index.d.ts +5 -1
- package/dist/platform/index.d.ts.map +1 -1
- package/dist/platform/observability.d.ts +2 -1
- package/dist/platform/observability.d.ts.map +1 -1
- package/dist/platform/url.d.ts +19 -0
- package/dist/platform/url.d.ts.map +1 -0
- package/dist/platform/web-vitals-client.d.ts +32 -0
- package/dist/platform/web-vitals-client.d.ts.map +1 -0
- package/dist/platform/web-vitals.d.ts +78 -0
- package/dist/platform/web-vitals.d.ts.map +1 -0
- package/dist/redis/index.d.ts +4 -0
- package/dist/redis/index.d.ts.map +1 -1
- package/dist/redis/index.js +209 -54
- package/dist/redis/index.js.map +1 -1
- package/dist/redis/rate-limit-store.d.ts +8 -0
- package/dist/redis/rate-limit-store.d.ts.map +1 -0
- package/dist/redis/session-store.d.ts +9 -0
- package/dist/redis/session-store.d.ts.map +1 -0
- package/dist/redis/store.d.ts.map +1 -1
- package/dist/route/index.d.ts +2 -2
- package/dist/route/index.d.ts.map +1 -1
- package/dist/route/middleware.d.ts.map +1 -1
- package/dist/route/mutation.d.ts +97 -0
- package/dist/route/mutation.d.ts.map +1 -0
- package/dist/route/response.d.ts.map +1 -1
- package/dist/route/types.d.ts +6 -1
- package/dist/route/types.d.ts.map +1 -1
- package/dist/router/index.d.ts +1 -1
- package/dist/router/index.d.ts.map +1 -1
- package/dist/router/manifest.d.ts +9 -0
- package/dist/router/manifest.d.ts.map +1 -1
- package/dist/router/navigation-data.d.ts +9 -1
- package/dist/router/navigation-data.d.ts.map +1 -1
- package/dist/routing/generate.d.ts +3 -0
- package/dist/routing/generate.d.ts.map +1 -1
- package/dist/routing/index.d.ts +3 -1
- package/dist/routing/index.d.ts.map +1 -1
- package/dist/routing/locale.d.ts +43 -0
- package/dist/routing/locale.d.ts.map +1 -0
- package/dist/routing/types.d.ts +12 -0
- package/dist/routing/types.d.ts.map +1 -1
- package/dist/security/cookie-session.d.ts +43 -0
- package/dist/security/cookie-session.d.ts.map +1 -0
- package/dist/security/cookies.d.ts +26 -0
- package/dist/security/cookies.d.ts.map +1 -0
- package/dist/security/csrf.d.ts +1 -1
- package/dist/security/csrf.d.ts.map +1 -1
- package/dist/security/env-startup.d.ts +15 -0
- package/dist/security/env-startup.d.ts.map +1 -0
- package/dist/security/env.d.ts +25 -6
- package/dist/security/env.d.ts.map +1 -1
- package/dist/security/fetch-metadata.d.ts +29 -0
- package/dist/security/fetch-metadata.d.ts.map +1 -0
- package/dist/security/index.d.ts +14 -2
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/policy.d.ts.map +1 -1
- package/dist/security/rate-limit.d.ts +6 -3
- package/dist/security/rate-limit.d.ts.map +1 -1
- package/dist/security/report.d.ts.map +1 -1
- package/dist/security/request.d.ts.map +1 -1
- package/dist/security/session-manager.d.ts +32 -0
- package/dist/security/session-manager.d.ts.map +1 -0
- package/dist/security/session-store.d.ts +51 -0
- package/dist/security/session-store.d.ts.map +1 -0
- package/dist/security/testing.d.ts +10 -0
- package/dist/security/testing.d.ts.map +1 -0
- package/dist/security/testing.js +145 -0
- package/dist/security/testing.js.map +1 -0
- package/dist/security/types.d.ts +73 -3
- package/dist/security/types.d.ts.map +1 -1
- package/dist/server/document-shell.d.ts.map +1 -1
- package/dist/server/errors.d.ts +1 -0
- package/dist/server/errors.d.ts.map +1 -1
- package/dist/server/index.d.ts +2 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/not-found.d.ts +1 -0
- package/dist/server/not-found.d.ts.map +1 -1
- package/dist/server/render-tree.d.ts.map +1 -1
- package/dist/server/request-handler.d.ts +10 -2
- package/dist/server/request-handler.d.ts.map +1 -1
- package/dist/server/request-metadata.d.ts +1 -0
- package/dist/server/request-metadata.d.ts.map +1 -1
- package/dist/server/ssr.d.ts +2 -0
- package/dist/server/ssr.d.ts.map +1 -1
- package/dist/static/index.d.ts +2 -0
- package/dist/static/index.d.ts.map +1 -1
- package/dist/static/index.js +380 -363
- package/dist/static/index.js.map +1 -1
- package/dist/static/preview.d.ts.map +1 -1
- package/dist/static/vercel.d.ts +11 -2
- package/dist/static/vercel.d.ts.map +1 -1
- package/dist/static-files.d.ts +12 -0
- package/dist/static-files.d.ts.map +1 -1
- package/dist/type-guards.d.ts +19 -0
- package/dist/type-guards.d.ts.map +1 -0
- package/dist/vite/env-boundary.d.ts +14 -0
- package/dist/vite/env-boundary.d.ts.map +1 -0
- package/dist/vite/index.d.ts +8 -3
- package/dist/vite/index.d.ts.map +1 -1
- package/dist/vite/index.js +22 -1196
- package/dist/vite/index.js.map +1 -1
- package/dist/vite/plugin.d.ts +8 -1
- package/dist/vite/plugin.d.ts.map +1 -1
- package/dist/vite/policy-verification.d.ts.map +1 -1
- package/dist/vite/route-audit.d.ts +50 -0
- package/dist/vite/route-audit.d.ts.map +1 -0
- package/package.json +19 -6
- package/dist/chunks/document-shell-D1xo6cEA.js +0 -35
- package/dist/chunks/document-shell-D1xo6cEA.js.map +0 -1
- package/dist/chunks/images-B9MqcjSA.js.map +0 -1
- package/dist/chunks/request-metadata-D5NrT8ks.js +0 -642
- package/dist/chunks/request-metadata-D5NrT8ks.js.map +0 -1
- package/dist/chunks/static-files-DUjHw-4H.js +0 -11
- package/dist/chunks/static-files-DUjHw-4H.js.map +0 -1
- package/dist/chunks/streaming-BQ1bykDo.js.map +0 -1
- package/dist/chunks/testing-B_iMFYz_.js +0 -3321
- package/dist/chunks/testing-B_iMFYz_.js.map +0 -1
- package/dist/route/action.d.ts +0 -33
- package/dist/route/action.d.ts.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/data/idempotency.ts","../src/document/seo.ts","../src/route/action.ts","../src/route/page.ts","../src/route/middleware.ts","../src/route/webhook.ts","../src/security/env.ts","../src/security/report.ts","../src/security/upload.ts","../src/security/websocket.ts","../src/browser/file-router.tsx","../src/platform/image.tsx","../src/platform/analytics.ts","../src/platform/observability.ts"],"sourcesContent":["import {\n parseCacheDuration,\n serializeCacheKey,\n type CacheDuration,\n type CacheKey,\n} from \"./cache\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type IdempotencyRequest<TResult> = {\n fn: () => MaybePromise<TResult>;\n key: CacheKey;\n ttl?: CacheDuration;\n};\n\nexport type IdempotencyResult<TResult> = {\n key: string;\n replayed: boolean;\n value: TResult;\n};\n\nexport type IdempotencyStore = {\n run: <TResult>(\n request: IdempotencyRequest<TResult>,\n ) => Promise<IdempotencyResult<TResult>>;\n};\n\ntype IdempotencyEntry<TResult> = {\n expiresAt: number;\n pending: boolean;\n value: Promise<TResult>;\n};\n\nexport type MemoryIdempotencyStoreOptions = {\n defaultTtl?: CacheDuration;\n maximumEntries?: number;\n now?: () => number;\n};\n\nconst defaultIdempotencyTtl = \"24h\";\nconst defaultMaximumEntries = 10_000;\n\nexport function createMemoryIdempotencyStore(\n options: MemoryIdempotencyStoreOptions = {},\n): IdempotencyStore {\n const now = options.now ?? Date.now;\n const defaultTtl = options.defaultTtl ?? defaultIdempotencyTtl;\n const maximumEntries = options.maximumEntries ?? defaultMaximumEntries;\n\n if (!Number.isSafeInteger(maximumEntries) || maximumEntries <= 0) {\n throw new Error(\n \"Demiurge idempotency maximumEntries must be a positive integer.\",\n );\n }\n\n const defaultTtlMs = parseCacheDuration(defaultTtl);\n\n if (!Number.isFinite(defaultTtlMs)) {\n throw new Error(\"Demiurge idempotency defaultTtl must be finite.\");\n }\n\n const entries = new Map<string, IdempotencyEntry<unknown>>();\n\n return {\n async run<TResult>(request: IdempotencyRequest<TResult>) {\n const key = serializeCacheKey(request.key);\n const currentTime = now();\n sweepExpiredIdempotencyEntries(entries, currentTime);\n const existing = entries.get(key);\n\n if (existing && (existing.pending || existing.expiresAt > currentTime)) {\n return {\n key,\n replayed: true,\n value: await (existing.value as Promise<TResult>),\n };\n }\n\n if (entries.size >= maximumEntries) {\n evictOldestCompletedIdempotencyEntry(entries);\n }\n\n if (entries.size >= maximumEntries) {\n throw new Error(\n \"Demiurge idempotency store is at capacity with in-flight mutations.\",\n );\n }\n\n const value = Promise.resolve().then(request.fn);\n const entry: IdempotencyEntry<TResult> = {\n expiresAt: Number.POSITIVE_INFINITY,\n pending: true,\n value,\n };\n\n entries.set(key, entry);\n\n try {\n const result = await value;\n entry.pending = false;\n entry.expiresAt = now() + parseCacheDuration(request.ttl ?? defaultTtl);\n\n return {\n key,\n replayed: false,\n value: result,\n };\n } catch (error) {\n if (entries.get(key) === entry) {\n entries.delete(key);\n }\n\n throw error;\n }\n },\n };\n}\n\nfunction sweepExpiredIdempotencyEntries(\n entries: Map<string, IdempotencyEntry<unknown>>,\n now: number,\n) {\n for (const [key, entry] of entries) {\n if (!entry.pending && entry.expiresAt <= now) {\n entries.delete(key);\n }\n }\n}\n\nfunction evictOldestCompletedIdempotencyEntry(\n entries: Map<string, IdempotencyEntry<unknown>>,\n) {\n for (const [key, entry] of entries) {\n if (!entry.pending) {\n entries.delete(key);\n return;\n }\n }\n}\n\nexport function runIdempotentMutation<TResult>(\n store: IdempotencyStore,\n request: IdempotencyRequest<TResult>,\n) {\n return store.run(request);\n}\n","export type SitemapChangeFrequency =\n | \"always\"\n | \"hourly\"\n | \"daily\"\n | \"weekly\"\n | \"monthly\"\n | \"yearly\"\n | \"never\";\n\nexport type SitemapAlternate = {\n href: string;\n hrefLang: string;\n};\n\nexport type SitemapEntry = {\n alternates?: readonly SitemapAlternate[];\n changeFrequency?: SitemapChangeFrequency;\n lastModified?: Date | string;\n priority?: number;\n url: string;\n};\n\nexport type Sitemap = {\n entries: readonly SitemapEntry[];\n};\n\nexport type RobotsDirective = {\n allow?: string | readonly string[];\n disallow?: string | readonly string[];\n userAgent: string | readonly string[];\n};\n\nexport type Robots = {\n host?: string;\n rules?: readonly RobotsDirective[];\n sitemap?: string | readonly string[];\n};\n\nexport type OgImage = {\n background?: string;\n brand?: string;\n foreground?: string;\n height?: number;\n subtitle?: string;\n title: string;\n width?: number;\n};\n\nexport function defineSitemap(entries: readonly SitemapEntry[]): Sitemap {\n return {\n entries,\n };\n}\n\nexport function renderSitemap(sitemap: Sitemap) {\n const hasAlternates = sitemap.entries.some((entry) => entry.alternates?.length);\n\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n `<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"${hasAlternates ? ' xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"' : \"\"}>`,\n ...sitemap.entries.map(renderSitemapEntry),\n \"</urlset>\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport function defineRobots(options: Robots): Robots {\n return options;\n}\n\nexport function defineOgImage(options: OgImage): OgImage {\n return options;\n}\n\nexport function renderRobots(robots: Robots) {\n const lines: string[] = [];\n\n for (const rule of robots.rules ?? []) {\n for (const userAgent of toArray(rule.userAgent)) {\n lines.push(`User-agent: ${userAgent}`);\n }\n\n for (const allow of toArray(rule.allow)) {\n lines.push(`Allow: ${allow}`);\n }\n\n for (const disallow of toArray(rule.disallow)) {\n lines.push(`Disallow: ${disallow}`);\n }\n\n lines.push(\"\");\n }\n\n if (robots.host) {\n lines.push(`Host: ${robots.host}`);\n }\n\n for (const sitemap of toArray(robots.sitemap)) {\n lines.push(`Sitemap: ${sitemap}`);\n }\n\n return `${lines.join(\"\\n\").replace(/\\n+$/, \"\")}\\n`;\n}\n\nexport function renderOgImageSvg(image: OgImage) {\n const width = image.width ?? 1200;\n const height = image.height ?? 630;\n const background = image.background ?? \"#101820\";\n const foreground = image.foreground ?? \"#ffffff\";\n const title = clampText(image.title, 120);\n const subtitle = image.subtitle ? clampText(image.subtitle, 160) : undefined;\n const brand = image.brand ? clampText(image.brand, 80) : undefined;\n\n validateOgImageDimensions(width, height);\n\n return [\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"0 0 ${width} ${height}\" role=\"img\" aria-label=\"${escapeXmlAttribute(title)}\">`,\n ` <rect width=\"100%\" height=\"100%\" fill=\"${escapeXmlAttribute(background)}\" />`,\n brand\n ? ` <text x=\"72\" y=\"96\" fill=\"${escapeXmlAttribute(foreground)}\" font-family=\"Inter, ui-sans-serif, system-ui, sans-serif\" font-size=\"32\" font-weight=\"700\">${escapeXml(brand)}</text>`\n : null,\n ` <text x=\"72\" y=\"${subtitle ? 300 : 340}\" fill=\"${escapeXmlAttribute(foreground)}\" font-family=\"Inter, ui-sans-serif, system-ui, sans-serif\" font-size=\"76\" font-weight=\"800\">${escapeXml(title)}</text>`,\n subtitle\n ? ` <text x=\"72\" y=\"392\" fill=\"${escapeXmlAttribute(foreground)}\" fill-opacity=\"0.78\" font-family=\"Inter, ui-sans-serif, system-ui, sans-serif\" font-size=\"38\" font-weight=\"500\">${escapeXml(subtitle)}</text>`\n : null,\n \"</svg>\",\n ].filter((line): line is string => Boolean(line)).join(\"\\n\");\n}\n\nexport function renderOgImageResponse(image: OgImage) {\n return new Response(renderOgImageSvg(image), {\n headers: {\n \"cache-control\": \"public, max-age=31536000, immutable\",\n \"content-type\": \"image/svg+xml; charset=utf-8\",\n },\n });\n}\n\nfunction renderSitemapEntry(entry: SitemapEntry) {\n return [\n \" <url>\",\n ` <loc>${escapeXml(entry.url)}</loc>`,\n entry.lastModified\n ? ` <lastmod>${escapeXml(formatLastModified(entry.lastModified))}</lastmod>`\n : null,\n entry.changeFrequency\n ? ` <changefreq>${entry.changeFrequency}</changefreq>`\n : null,\n entry.priority !== undefined\n ? ` <priority>${formatPriority(entry.priority)}</priority>`\n : null,\n ...(entry.alternates ?? []).map(\n (alternate) =>\n ` <xhtml:link rel=\"alternate\" hreflang=\"${escapeXmlAttribute(alternate.hrefLang)}\" href=\"${escapeXmlAttribute(alternate.href)}\" />`,\n ),\n \" </url>\",\n ].filter((line): line is string => Boolean(line)).join(\"\\n\");\n}\n\nfunction formatLastModified(value: Date | string) {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction formatPriority(priority: number) {\n if (priority < 0 || priority > 1) {\n throw new Error(\"Sitemap entry priority must be between 0 and 1.\");\n }\n\n return String(priority);\n}\n\nfunction toArray<T>(value: T | readonly T[] | undefined) {\n if (value === undefined) {\n return [];\n }\n\n return Array.isArray(value) ? value : [value];\n}\n\nfunction escapeXml(value: string) {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\");\n}\n\nfunction escapeXmlAttribute(value: string) {\n return escapeXml(value)\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\");\n}\n\nfunction clampText(value: string, maxLength: number) {\n return value.length > maxLength ? `${value.slice(0, maxLength - 3)}...` : value;\n}\n\nfunction validateOgImageDimensions(width: number, height: number) {\n if (!Number.isSafeInteger(width) || width <= 0) {\n throw new Error(\"OG image width must be a positive integer.\");\n }\n\n if (!Number.isSafeInteger(height) || height <= 0) {\n throw new Error(\"OG image height must be a positive integer.\");\n }\n}\n","import type {\n CacheDuration,\n CacheKey,\n IdempotencyStore,\n} from \"../data\";\nimport type {\n CorsPolicy,\n RouteSecurityPolicy,\n} from \"../security\";\nimport type {\n HttpRouteContext,\n MaybePromise,\n ResponseCapability,\n RouteRequestContextFor,\n ServerTimingInput,\n} from \"./types\";\nimport { response, toResponse } from \"./response\";\n\nexport type ActionInput<\n TInput,\n TPath extends string = string,\n TValues extends object = RouteRequestContextFor<TPath>,\n> = (\n context: HttpRouteContext<TPath, TValues>,\n) => MaybePromise<TInput>;\n\nexport type ActionContext<\n TInput,\n TPath extends string = string,\n TValues extends object = RouteRequestContextFor<TPath>,\n> = HttpRouteContext<TPath, TValues> & {\n input: TInput;\n};\n\nexport type ActionIdempotency<\n TInput,\n TPath extends string = string,\n TValues extends object = RouteRequestContextFor<TPath>,\n> = {\n key: CacheKey | ((context: ActionContext<TInput, TPath, TValues>) => CacheKey);\n store: IdempotencyStore;\n ttl?: CacheDuration;\n};\n\nexport type ActionOptions<\n TInput,\n TPath extends string = string,\n TValues extends object = RouteRequestContextFor<TPath>,\n> = {\n cors?: CorsPolicy;\n handler: (\n context: ActionContext<TInput, TPath, TValues>,\n ) => MaybePromise<Response | ResponseCapability<TPath, TValues>>;\n idempotency?: ActionIdempotency<TInput, TPath, TValues>;\n input?: ActionInput<TInput, TPath, TValues>;\n security?: RouteSecurityPolicy;\n timing?: ServerTimingInput;\n};\n\nexport function action<\n TInput = undefined,\n TPath extends string = string,\n TValues extends object = RouteRequestContextFor<TPath>,\n>(\n options: ActionOptions<TInput, TPath, TValues>,\n) {\n return response<TPath, TValues>(\n async (context) => {\n const input = options.input\n ? await options.input(context)\n : undefined as TInput;\n const actionContext = {\n ...context,\n input,\n } as unknown as ActionContext<TInput, TPath, TValues>;\n const run = async () => await resolveActionResult(\n await options.handler(actionContext),\n context,\n );\n\n if (!options.idempotency) {\n return await run();\n }\n\n const key = typeof options.idempotency.key === \"function\"\n ? options.idempotency.key(actionContext)\n : options.idempotency.key;\n const result = await options.idempotency.store.run({\n fn: run,\n key,\n ttl: options.idempotency.ttl,\n });\n\n return result.value;\n },\n {\n cors: options.cors,\n security: options.security,\n timing: options.timing,\n },\n );\n}\n\nexport const actionInput = {\n async formData({ request }: HttpRouteContext) {\n return await request.formData();\n },\n async json({ request }: HttpRouteContext) {\n return await request.json() as unknown;\n },\n async text({ request }: HttpRouteContext) {\n return await request.text();\n },\n};\n\nasync function resolveActionResult<\n TPath extends string,\n TValues extends object,\n>(\n result: Response | ResponseCapability<TPath, TValues>,\n context: HttpRouteContext<TPath, TValues>,\n) {\n if (result instanceof Response) {\n return result;\n }\n\n return await toResponse(result, context);\n}\n","import type { ComponentType } from \"react\";\nimport type {\n PageCapability,\n PageOptions,\n RouteProps,\n RouteRequestContextFor,\n} from \"./types\";\n\nexport function page<const TPath extends string = string>(\n options: ComponentType<RouteProps<TPath>>,\n): PageCapability<TPath>;\nexport function page<\n const TPath extends string = string,\n TData = undefined,\n TValues extends object = RouteRequestContextFor<TPath>,\n>(\n options: PageOptions<TPath, TData, TValues>,\n): PageCapability<TPath, TData, TValues>;\nexport function page<\n const TPath extends string = string,\n TData = undefined,\n TValues extends object = RouteRequestContextFor<TPath>,\n>(\n options: PageOptions<TPath, TData, TValues> | ComponentType<RouteProps<TPath>>,\n): PageCapability<TPath, TData, TValues> | PageCapability<TPath> {\n if (typeof options === \"function\") {\n return {\n kind: \"page\",\n render: { mode: \"ssr\" },\n view: options,\n } satisfies PageCapability<TPath>;\n }\n\n return {\n data: options.data,\n kind: \"page\",\n layout: options.layout,\n render: options.render ?? { mode: \"ssr\" },\n view: options.view,\n } as PageCapability<TPath, TData, TValues>;\n}\n","import type {\n HttpRouteContext,\n MaybePromise,\n MiddlewareContextContribution,\n RouteMiddleware,\n RouteMiddlewareNext,\n} from \"./types\";\n\n/**\n * Declares the request-context values that a middleware can read and write.\n * The framework passes one carrier to every inherited middleware in a request.\n */\nexport function defineMiddleware<TValues extends object>(\n middleware: (\n context: HttpRouteContext<string, TValues>,\n next: RouteMiddlewareNext,\n ) => MaybePromise<Response>,\n): RouteMiddleware<string, TValues> & MiddlewareContextContribution<TValues> {\n return middleware as RouteMiddleware<string, TValues> &\n MiddlewareContextContribution<TValues>;\n}\n","import type {\n HttpRouteContext,\n MaybePromise,\n RawResponseCapability,\n} from \"./types\";\n\nexport type WebhookHmacEncoding = \"base64\" | \"hex\";\nexport type WebhookHmacAlgorithm = \"SHA-256\" | \"SHA-384\" | \"SHA-512\";\n\nexport type WebhookHmacContext = HttpRouteContext & {\n rawBody: Uint8Array;\n text: () => string;\n};\n\nexport type WebhookHmacOptions = {\n algorithm?: WebhookHmacAlgorithm;\n encoding?: WebhookHmacEncoding;\n handler: (context: WebhookHmacContext) => MaybePromise<Response>;\n header?: string;\n prefix?: false | string;\n secret: string;\n};\n\nexport const webhook = {\n hmac(options: WebhookHmacOptions) {\n return {\n kind: \"response\",\n response: async (context) => {\n const rawBody = new Uint8Array(await context.request.arrayBuffer());\n const signature = context.request.headers.get(\n options.header ?? \"x-webhook-signature\",\n );\n\n if (!signature) {\n return new Response(\"Missing webhook signature.\", {\n status: 401,\n });\n }\n\n if (!(await verifyHmacSignature(rawBody, signature, options))) {\n return new Response(\"Invalid webhook signature.\", {\n status: 401,\n });\n }\n\n return await options.handler({\n ...context,\n rawBody,\n text: () => new TextDecoder().decode(rawBody),\n });\n },\n security: {\n csrf: false,\n },\n } satisfies RawResponseCapability;\n },\n};\n\nasync function verifyHmacSignature(\n rawBody: Uint8Array,\n suppliedSignature: string,\n options: WebhookHmacOptions,\n) {\n const algorithm = options.algorithm ?? \"SHA-256\";\n const encoding = options.encoding ?? \"hex\";\n const normalized = normalizeSignature(\n suppliedSignature,\n algorithm,\n options.prefix,\n );\n const signature = decodeSignature(normalized, encoding);\n\n if (!signature) {\n return false;\n }\n\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(options.secret),\n {\n hash: algorithm,\n name: \"HMAC\",\n },\n false,\n [\"verify\"],\n );\n return await globalThis.crypto.subtle.verify(\n \"HMAC\",\n key,\n signature,\n Uint8Array.from(rawBody).buffer,\n );\n}\n\nfunction normalizeSignature(\n signature: string,\n algorithm: WebhookHmacAlgorithm,\n configuredPrefix: false | string | undefined,\n) {\n const trimmed = signature.trim();\n const prefix =\n configuredPrefix === undefined\n ? `${algorithm.toLowerCase().replace(\"-\", \"\")}=`\n : configuredPrefix;\n\n if (prefix !== false && trimmed.startsWith(prefix)) {\n return trimmed.slice(prefix.length).trim();\n }\n\n return trimmed;\n}\n\nfunction decodeSignature(value: string, encoding: WebhookHmacEncoding) {\n if (encoding === \"hex\") {\n if (!/^(?:[0-9a-f]{2})+$/i.test(value)) {\n return null;\n }\n\n return Uint8Array.from(value.match(/.{2}/g) ?? [], (pair) =>\n Number.parseInt(pair, 16),\n );\n }\n\n if (\n !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(\n value,\n )\n ) {\n return null;\n }\n\n try {\n const binary =\n typeof atob === \"function\"\n ? atob(value)\n : Buffer.from(value, \"base64\").toString(\"binary\");\n\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n } catch {\n return null;\n }\n}\n","export type EnvSource = Record<string, string | undefined>;\n\nexport type EnvValidationIssue = {\n code: \"invalid\" | \"missing\";\n key: string;\n message: string;\n};\n\nexport class EnvValidationError extends Error {\n issues: EnvValidationIssue[];\n\n constructor(issues: EnvValidationIssue[]) {\n super(formatEnvValidationError(issues));\n this.name = \"EnvValidationError\";\n this.issues = issues;\n }\n}\n\nexport type EnvVariable<T, Optional extends boolean = false> = {\n optional: Optional;\n parse: (key: string, value: string) => T;\n sensitive: boolean;\n};\n\nexport type EnvSchema = Record<string, EnvVariable<unknown, boolean>>;\n\nexport type InferEnvSchema<Schema extends EnvSchema> = {\n [Key in keyof Schema]: Schema[Key] extends EnvVariable<infer Value, infer Optional>\n ? Optional extends true\n ? Value | undefined\n : Value\n : never;\n};\n\ntype RequiredEnvVariableOptions = {\n optional?: false;\n};\n\ntype OptionalEnvVariableOptions = {\n optional: true;\n};\n\ntype EnvVariableOptions = RequiredEnvVariableOptions | OptionalEnvVariableOptions;\n\ntype RequiredStringEnvOptions = RequiredEnvVariableOptions & {\n minLength?: number;\n};\n\ntype OptionalStringEnvOptions = OptionalEnvVariableOptions & {\n minLength?: number;\n};\n\ntype StringEnvOptions = RequiredStringEnvOptions | OptionalStringEnvOptions;\n\ntype RequiredUrlEnvOptions = RequiredEnvVariableOptions & {\n protocols?: readonly string[];\n};\n\ntype OptionalUrlEnvOptions = OptionalEnvVariableOptions & {\n protocols?: readonly string[];\n};\n\ntype UrlEnvOptions = RequiredUrlEnvOptions | OptionalUrlEnvOptions;\n\ntype RequiredIntegerEnvOptions = RequiredEnvVariableOptions & {\n max?: number;\n min?: number;\n};\n\ntype OptionalIntegerEnvOptions = OptionalEnvVariableOptions & {\n max?: number;\n min?: number;\n};\n\ntype IntegerEnvOptions = RequiredIntegerEnvOptions | OptionalIntegerEnvOptions;\n\nexport function defineEnvSchema<Schema extends EnvSchema>(schema: Schema) {\n return schema;\n}\n\nexport function validateEnv<Schema extends EnvSchema>(\n schema: Schema,\n source: EnvSource,\n): InferEnvSchema<Schema> {\n const issues: EnvValidationIssue[] = [];\n const values: Partial<Record<keyof Schema, unknown>> = {};\n\n for (const key of Object.keys(schema) as Array<keyof Schema>) {\n const variable = schema[key];\n const rawValue = source[String(key)];\n\n if (rawValue === undefined || rawValue === \"\") {\n if (variable.optional) {\n values[key] = undefined;\n continue;\n }\n\n issues.push({\n code: \"missing\",\n key: String(key),\n message: `Environment variable ${String(key)} is required.`,\n });\n continue;\n }\n\n try {\n values[key] = variable.parse(String(key), rawValue);\n } catch (error) {\n issues.push({\n code: \"invalid\",\n key: String(key),\n message: error instanceof Error\n ? error.message\n : `Environment variable ${String(key)} is invalid.`,\n });\n }\n }\n\n if (issues.length) {\n throw new EnvValidationError(issues);\n }\n\n return values as InferEnvSchema<Schema>;\n}\n\nfunction booleanEnv(options: OptionalEnvVariableOptions): EnvVariable<boolean, true>;\nfunction booleanEnv(options?: RequiredEnvVariableOptions): EnvVariable<boolean, false>;\nfunction booleanEnv(options: EnvVariableOptions = {}) {\n return createVariable(options, false, (key, value) => {\n if (value === \"true\" || value === \"1\") {\n return true;\n }\n\n if (value === \"false\" || value === \"0\") {\n return false;\n }\n\n throw new Error(`Environment variable ${key} must be true, false, 1, or 0.`);\n });\n}\n\nfunction enumEnv<const Values extends readonly [string, ...string[]]>(\n values: Values,\n options: OptionalEnvVariableOptions,\n): EnvVariable<Values[number], true>;\nfunction enumEnv<const Values extends readonly [string, ...string[]]>(\n values: Values,\n options?: RequiredEnvVariableOptions,\n): EnvVariable<Values[number], false>;\nfunction enumEnv<const Values extends readonly [string, ...string[]]>(\n values: Values,\n options: EnvVariableOptions = {},\n) {\n return createVariable(options, false, (key, value) => {\n if (values.includes(value)) {\n return value;\n }\n\n throw new Error(\n `Environment variable ${key} must be one of: ${values.join(\", \")}.`,\n );\n });\n}\n\nfunction integerEnv(options: OptionalIntegerEnvOptions): EnvVariable<number, true>;\nfunction integerEnv(options?: RequiredIntegerEnvOptions): EnvVariable<number, false>;\nfunction integerEnv(options: IntegerEnvOptions = {}) {\n return createVariable(options, false, (key, value) => {\n if (!/^-?\\d+$/.test(value)) {\n throw new Error(`Environment variable ${key} must be an integer.`);\n }\n\n const parsed = Number(value);\n\n if (!Number.isSafeInteger(parsed)) {\n throw new Error(`Environment variable ${key} must be a safe integer.`);\n }\n\n if (options.min !== undefined && parsed < options.min) {\n throw new Error(\n `Environment variable ${key} must be greater than or equal to ${options.min}.`,\n );\n }\n\n if (options.max !== undefined && parsed > options.max) {\n throw new Error(\n `Environment variable ${key} must be less than or equal to ${options.max}.`,\n );\n }\n\n return parsed;\n });\n}\n\nfunction secretEnv(options: OptionalStringEnvOptions): EnvVariable<string, true>;\nfunction secretEnv(options?: RequiredStringEnvOptions): EnvVariable<string, false>;\nfunction secretEnv(options: StringEnvOptions = {}) {\n return createVariable(options, true, (key, value) =>\n parseString(key, value, options),\n );\n}\n\nfunction stringEnv(options: OptionalStringEnvOptions): EnvVariable<string, true>;\nfunction stringEnv(options?: RequiredStringEnvOptions): EnvVariable<string, false>;\nfunction stringEnv(options: StringEnvOptions = {}) {\n return createVariable(options, false, (key, value) =>\n parseString(key, value, options),\n );\n}\n\nfunction urlEnv(options: OptionalUrlEnvOptions): EnvVariable<URL, true>;\nfunction urlEnv(options?: RequiredUrlEnvOptions): EnvVariable<URL, false>;\nfunction urlEnv(options: UrlEnvOptions = {}) {\n return createVariable(options, false, (key, value) => {\n let url: URL;\n\n try {\n url = new URL(value);\n } catch {\n throw new Error(`Environment variable ${key} must be a valid URL.`);\n }\n\n if (\n options.protocols?.length &&\n !options.protocols.includes(url.protocol)\n ) {\n throw new Error(\n `Environment variable ${key} must use one of these protocols: ${options.protocols.join(\", \")}.`,\n );\n }\n\n return url;\n });\n}\n\nexport const env = {\n boolean: booleanEnv,\n enum: enumEnv,\n integer: integerEnv,\n secret: secretEnv,\n string: stringEnv,\n url: urlEnv,\n};\n\nfunction createVariable<T>(\n options: EnvVariableOptions,\n sensitive: boolean,\n parse: (key: string, value: string) => T,\n): EnvVariable<T, boolean> {\n return {\n optional: options.optional ?? false,\n parse,\n sensitive,\n };\n}\n\nfunction parseString(\n key: string,\n value: string,\n options: StringEnvOptions,\n) {\n if (options.minLength !== undefined && value.length < options.minLength) {\n throw new Error(\n `Environment variable ${key} must be at least ${options.minLength} characters.`,\n );\n }\n\n return value;\n}\n\nfunction formatEnvValidationError(issues: EnvValidationIssue[]) {\n if (issues.length === 1) {\n return issues[0].message;\n }\n\n return `Environment validation failed with ${issues.length} issues.`;\n}\n","import {\n limitRequestBody,\n parseBodySize,\n RequestBodyTooLargeError,\n} from \"./request\";\n\ntype MaybePromise<T> = Promise<T> | T;\n\nexport type SecurityReportPayload = unknown;\n\nexport type SecurityReportHandlerOptions = {\n maxBodySize?: number | `${number}${\"b\" | \"gb\" | \"kb\" | \"mb\"}`;\n onReport?: (\n report: SecurityReportPayload,\n context: SecurityReportContext,\n ) => MaybePromise<void>;\n};\n\nexport type SecurityReportContext = {\n index: number;\n request: Request;\n};\n\nexport function createSecurityReportHandler(\n options: SecurityReportHandlerOptions = {},\n) {\n return async function handleSecurityReport(request: Request) {\n if (request.method.toUpperCase() !== \"POST\") {\n return new Response(null, {\n headers: {\n allow: \"POST\",\n },\n status: 405,\n });\n }\n\n const contentTypeResponse = enforceReportContentType(request);\n\n if (contentTypeResponse) {\n return contentTypeResponse;\n }\n\n const bodySizeResponse = enforceReportBodySize(options, request);\n\n if (bodySizeResponse) {\n return bodySizeResponse;\n }\n\n if (options.maxBodySize !== undefined) {\n request = limitRequestBody({ maxBodySize: options.maxBodySize }, request);\n }\n\n let payload: unknown;\n\n try {\n payload = await request.json();\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return new Response(\"Security report body too large.\", { status: 413 });\n }\n\n return new Response(\"Invalid security report JSON.\", {\n status: 400,\n });\n }\n\n const reports = normalizeSecurityReports(payload);\n\n for (let index = 0; index < reports.length; index += 1) {\n await options.onReport?.(reports[index], {\n index,\n request,\n });\n }\n\n return new Response(null, {\n status: 204,\n });\n };\n}\n\nconst supportedReportContentTypes = new Set([\n \"application/csp-report\",\n \"application/reports+json\",\n]);\n\nfunction enforceReportContentType(request: Request) {\n const value = request.headers.get(\"content-type\");\n\n // Keep direct/programmatic calls compatible. Browser-generated reports\n // always send one of the two media types below.\n if (!value) {\n return null;\n }\n\n const mediaType = value.split(\";\", 1)[0]?.trim().toLowerCase();\n\n if (mediaType && supportedReportContentTypes.has(mediaType)) {\n return null;\n }\n\n return new Response(\"Unsupported security report Content-Type.\", {\n status: 415,\n });\n}\n\nfunction enforceReportBodySize(\n options: SecurityReportHandlerOptions,\n request: Request,\n) {\n if (options.maxBodySize === undefined) {\n return null;\n }\n\n const contentLength = request.headers.get(\"content-length\");\n\n if (!contentLength) {\n return null;\n }\n\n if (!/^\\d+$/.test(contentLength)) {\n return new Response(\"Invalid Content-Length.\", {\n status: 400,\n });\n }\n\n const declaredSize = Number(contentLength);\n\n if (!Number.isSafeInteger(declaredSize)) {\n return new Response(\"Invalid Content-Length.\", {\n status: 400,\n });\n }\n\n if (declaredSize > parseBodySize(options.maxBodySize)) {\n return new Response(\"Security report body too large.\", {\n status: 413,\n });\n }\n\n return null;\n}\n\nfunction normalizeSecurityReports(payload: unknown) {\n if (Array.isArray(payload)) {\n return payload;\n }\n\n if (isObject(payload) && \"csp-report\" in payload) {\n return [payload[\"csp-report\"]];\n }\n\n return [payload];\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n","import { parseBodySize } from \"./request\";\nimport type { RequestSecurityPolicy } from \"./types\";\n\nexport type UploadFilePolicy = {\n maxSize?: RequestSecurityPolicy[\"maxBodySize\"];\n required?: boolean;\n types?: readonly string[];\n};\n\nexport type UploadPolicy = {\n files: Record<string, UploadFilePolicy>;\n maxTotalSize?: RequestSecurityPolicy[\"maxBodySize\"];\n};\n\nexport type UploadValidationIssue = {\n code:\n | \"file-missing\"\n | \"file-too-large\"\n | \"file-type-not-allowed\"\n | \"total-upload-too-large\";\n field: string;\n message: string;\n};\n\nexport type UploadValidationResult = {\n files: Record<string, File[]>;\n issues: UploadValidationIssue[];\n ok: boolean;\n totalSize: number;\n};\n\nexport function validateUploads(\n formData: FormData,\n policy: UploadPolicy,\n): UploadValidationResult {\n const files: Record<string, File[]> = {};\n const issues: UploadValidationIssue[] = [];\n let totalSize = 0;\n\n for (const [field, filePolicy] of Object.entries(policy.files)) {\n const fieldFiles = formData.getAll(field).filter(isFile);\n files[field] = fieldFiles;\n\n if (filePolicy.required && fieldFiles.length === 0) {\n issues.push({\n code: \"file-missing\",\n field,\n message: `Upload field ${field} requires at least one file.`,\n });\n }\n\n for (const file of fieldFiles) {\n totalSize += file.size;\n validateFile(field, file, filePolicy, issues);\n }\n }\n\n if (\n policy.maxTotalSize !== undefined &&\n totalSize > parseBodySize(policy.maxTotalSize)\n ) {\n issues.push({\n code: \"total-upload-too-large\",\n field: \"*\",\n message: `Uploaded files exceed the maximum total size of ${policy.maxTotalSize}.`,\n });\n }\n\n return {\n files,\n issues,\n ok: issues.length === 0,\n totalSize,\n };\n}\n\nfunction validateFile(\n field: string,\n file: File,\n policy: UploadFilePolicy,\n issues: UploadValidationIssue[],\n) {\n if (policy.maxSize !== undefined && file.size > parseBodySize(policy.maxSize)) {\n issues.push({\n code: \"file-too-large\",\n field,\n message: `Upload field ${field} contains ${file.name || \"a file\"} larger than ${policy.maxSize}.`,\n });\n }\n\n if (policy.types?.length && !isAllowedFileType(file.type, policy.types)) {\n issues.push({\n code: \"file-type-not-allowed\",\n field,\n message: `Upload field ${field} contains ${file.name || \"a file\"} with disallowed type ${file.type || \"unknown\"}.`,\n });\n }\n}\n\nfunction isAllowedFileType(type: string, allowedTypes: readonly string[]) {\n return allowedTypes.some((allowedType) => {\n if (allowedType.endsWith(\"/*\")) {\n return type.startsWith(allowedType.slice(0, -1));\n }\n\n return type === allowedType;\n });\n}\n\nfunction isFile(value: FormDataEntryValue): value is File {\n return value instanceof File;\n}\n","export type WebSocketOriginPolicy = {\n allowMissingOrigin?: boolean;\n origins: \"same-origin\" | readonly string[];\n};\n\nexport type WebSocketOriginCheck = {\n allowed: boolean;\n expected: \"same-origin\" | readonly string[];\n origin: string | null;\n reason?: \"invalid-origin\" | \"missing-origin\" | \"origin-not-allowed\";\n};\n\nexport function checkWebSocketOrigin(\n policy: WebSocketOriginPolicy,\n request: Request,\n): WebSocketOriginCheck {\n const origin = request.headers.get(\"origin\");\n\n if (!origin) {\n return {\n allowed: Boolean(policy.allowMissingOrigin),\n expected: policy.origins,\n origin,\n reason: policy.allowMissingOrigin ? undefined : \"missing-origin\",\n };\n }\n\n const normalizedOrigin = normalizeOrigin(origin);\n\n if (!normalizedOrigin) {\n return {\n allowed: false,\n expected: policy.origins,\n origin,\n reason: \"invalid-origin\",\n };\n }\n\n const allowed = isAllowedOrigin(policy, normalizedOrigin, request);\n\n return {\n allowed,\n expected: policy.origins,\n origin: normalizedOrigin,\n reason: allowed ? undefined : \"origin-not-allowed\",\n };\n}\n\nexport function enforceWebSocketOrigin(\n policy: WebSocketOriginPolicy | undefined,\n request: Request,\n) {\n if (!policy) {\n return null;\n }\n\n const check = checkWebSocketOrigin(policy, request);\n\n if (check.allowed) {\n return null;\n }\n\n return new Response(\"WebSocket origin not allowed.\", {\n status: 403,\n });\n}\n\nfunction isAllowedOrigin(\n policy: WebSocketOriginPolicy,\n origin: string,\n request: Request,\n) {\n if (policy.origins === \"same-origin\") {\n return origin === new URL(request.url).origin;\n }\n\n return policy.origins.some((allowedOrigin) =>\n originMatches(allowedOrigin, origin),\n );\n}\n\nfunction originMatches(allowedOrigin: string, actualOrigin: string) {\n if (allowedOrigin === \"null\") {\n return actualOrigin === \"null\";\n }\n\n return normalizeOrigin(allowedOrigin) === actualOrigin;\n}\n\nfunction normalizeOrigin(origin: string) {\n if (origin === \"null\") {\n return origin;\n }\n\n try {\n // Origin is a serialized origin, not an arbitrary URL. `new URL()` alone\n // would silently discard a path, query, fragment, or credentials and could\n // turn a malformed attacker-supplied header into an allowed origin.\n if (origin !== origin.trim()) {\n return null;\n }\n\n const schemeSeparator = origin.indexOf(\"://\");\n\n if (schemeSeparator === -1) {\n return null;\n }\n\n const authority = origin.slice(schemeSeparator + 3);\n\n if (!authority || /[/?#]/.test(authority)) {\n return null;\n }\n\n const url = new URL(origin);\n\n if (\n (url.protocol !== \"http:\" && url.protocol !== \"https:\") ||\n url.username ||\n url.password\n ) {\n return null;\n }\n\n return url.origin;\n } catch {\n return null;\n }\n}\n","import {\n Component,\n ComponentType,\n MouseEvent,\n ReactNode,\n createContext,\n createElement,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n HYDRATION_FALLBACK_ATTRIBUTE,\n HYDRATION_ROOT_ATTRIBUTE,\n readInitialRouteData,\n startDeferredScripts,\n type InitialRouteData,\n} from \"../document\";\nimport {\n HTTP_ERROR_STATUSES,\n httpError,\n isHttpError,\n type NotFoundProps,\n type RouteErrorProps,\n type RouteImporter,\n} from \"../route\";\nimport {\n createRouteManifest,\n loadErrorFallback,\n loadLoadingFallback,\n loadPageRoute,\n NAVIGATION_DATA_HEADER,\n NAVIGATION_DATA_REQUEST,\n NAVIGATION_DATA_RESPONSE,\n NAVIGATION_ERROR_RESPONSE,\n NAVIGATION_NOT_FOUND_RESPONSE,\n type PendingRouteMatch,\n} from \"../router\";\nimport { BuiltInNotFound } from \"../server/fallbacks\";\nimport { href, type AppHref, type LinkTarget, type LinkTo } from \"../routing\";\n\nexport type NavigationDataLoader = (\n request: Request,\n) => Promise<InitialRouteData>;\n\nexport type FileRouterOptions = {\n initialMatch?: PendingRouteMatch;\n loadNavigationData?: NavigationDataLoader;\n navigation?: \"document\" | \"server\";\n routes: Record<string, RouteImporter>;\n loading?: ComponentType;\n notFound?: ComponentType<NotFoundProps>;\n};\n\nexport function createFileRouter(options: FileRouterOptions) {\n const manifest = createRouteManifest(options.routes);\n const navigationDataLoader = options.loadNavigationData ?? loadNavigationData;\n\n return function FileRouter() {\n const [location, setLocation] = useState(() => getCurrentLocation());\n const [match, setMatch] = useState<PendingRouteMatch>(\n () => options.initialMatch ?? { status: \"loading\" },\n );\n const initialMatchPending = useRef(Boolean(options.initialMatch));\n const navigationSequence = useRef(0);\n\n useEffect(() => {\n function onPopState() {\n setLocation(getCurrentLocation());\n }\n\n window.addEventListener(\"popstate\", onPopState);\n return () => window.removeEventListener(\"popstate\", onPopState);\n }, []);\n\n useEffect(() => {\n let cancelled = false;\n let settled = false;\n const sequence = ++navigationSequence.current;\n const controller = new AbortController();\n const isCurrent = () =>\n !cancelled && sequence === navigationSequence.current;\n\n if (\n initialMatchPending.current &&\n getMatchPathname(options.initialMatch) === location.pathname\n ) {\n initialMatchPending.current = false;\n return () => {\n cancelled = true;\n };\n }\n\n setMatch({ status: \"loading\" });\n loadLoadingFallback(manifest, location.pathname).then((Loading) => {\n if (isCurrent() && !settled && Loading) {\n setMatch({ loading: Loading, status: \"loading\" });\n }\n }).catch(() => {\n // Loading UI is optional. A malformed pathname or broken loading\n // module must not become an unhandled rejection while the main route\n // pipeline resolves the controlled error state.\n });\n const request = new Request(location.href, { signal: controller.signal });\n Promise.resolve(navigationDataLoader(request))\n .then((initialData) =>\n loadPageRoute(\n manifest,\n location.pathname,\n request,\n initialData,\n undefined,\n { documentContributions: false },\n ),\n )\n .then((nextMatch) => {\n settled = true;\n if (isCurrent()) {\n setMatch(nextMatch);\n }\n })\n .catch(async (error: unknown) => {\n settled = true;\n\n if (!isCurrent() || controller.signal.aborted) {\n return;\n }\n\n const ErrorFallback = await loadErrorFallback(\n manifest,\n location.pathname,\n );\n\n if (isCurrent()) {\n setMatch({\n Error: ErrorFallback,\n error,\n pathname: location.pathname,\n status: \"error\",\n });\n }\n });\n\n return () => {\n cancelled = true;\n controller.abort();\n };\n }, [location.pathname, location.search]);\n\n const router = useMemo(\n () => ({\n navigation: options.navigation ?? \"server\",\n push(to: string) {\n const previous = getCurrentLocation();\n window.history.pushState(null, \"\", to);\n const next = getCurrentLocation();\n setLocation(next);\n\n if (\n previous.pathname === next.pathname &&\n previous.search === next.search &&\n previous.hash !== next.hash\n ) {\n scrollToHash(next.hash);\n }\n },\n }),\n [],\n );\n\n return createElement(RouterContext.Provider, {\n value: router,\n children: createElement(RouteRenderer, {\n key: `${location.pathname}${location.search}`,\n Loading: options.loading,\n NotFound: options.notFound,\n match,\n }),\n });\n };\n}\n\n// Hydration is safe only when the client reproduces the server output. The\n// client replaces a page document when its route no longer matches. The client\n// hydrates a document that the server marked as a 404. This action preserves\n// the layouts that the server resolved.\nfunction isHydratableMatch(match: PendingRouteMatch, root: Element) {\n const fallback = root.getAttribute(HYDRATION_FALLBACK_ATTRIBUTE);\n\n return match.status === \"not-found\"\n ? fallback === \"not-found\"\n : match.status === \"ready\" && fallback === null;\n}\n\nfunction getMatchPathname(match: PendingRouteMatch | undefined) {\n if (!match) {\n return undefined;\n }\n\n if (match.status === \"ready\") {\n return match.match.pathname;\n }\n\n return match.status === \"loading\" ? undefined : match.pathname;\n}\n\nexport type HydrateFileRouterOptions = Omit<\n FileRouterOptions,\n \"initialMatch\"\n> & {\n initialData?: InitialRouteData;\n root?: Element;\n};\n\nexport async function hydrateFileRouter(options: HydrateFileRouterOptions) {\n const root = options.root ?? document.getElementById(\"root\");\n\n if (!root) {\n throw new Error(\n \"Demiurge expected a #root element in the framework document.\",\n );\n }\n\n const manifest = createRouteManifest(options.routes);\n const navigationDataLoader = options.loadNavigationData ?? loadNavigationData;\n const initialData = options.initialData ?? readInitialRouteData(document);\n const match = await loadPageRoute(\n manifest,\n window.location.pathname,\n new Request(window.location.href),\n initialData ?? await navigationDataLoader(new Request(window.location.href)),\n undefined,\n { documentContributions: false },\n );\n const hydratable = isHydratableMatch(match, root);\n const Router = createFileRouter(\n hydratable\n ? {\n ...options,\n initialMatch: match,\n loadNavigationData: navigationDataLoader,\n navigation: initialData?.navigation ?? options.navigation,\n }\n : {\n ...options,\n loadNavigationData: navigationDataLoader,\n navigation: initialData?.navigation ?? options.navigation,\n },\n );\n const { createRoot, hydrateRoot } = resolveReactDomClient(\n await import(\"react-dom/client\"),\n );\n\n // Only documents rendered by the framework server carry markup to hydrate.\n // A static shell has an empty root, so hydrating it would mismatch. A\n // server-rendered 404 carries markup too, and hydrating it is what keeps the\n // layouts the server resolved from being torn down on the client.\n if (hydratable && root.hasAttribute(HYDRATION_ROOT_ATTRIBUTE)) {\n hydrateRoot(root, createElement(Router));\n startDeferredScripts();\n return;\n }\n\n root.replaceChildren();\n createRoot(root).render(createElement(Router));\n startDeferredScripts();\n}\n\ntype ReactDomClientApi = Pick<\n typeof import(\"react-dom/client\"),\n \"createRoot\" | \"hydrateRoot\"\n>;\n\ntype ReactDomClientModule = Partial<ReactDomClientApi> & {\n default?: ReactDomClientApi;\n};\n\nexport function resolveReactDomClient(module: ReactDomClientModule) {\n const client = typeof module.createRoot === \"function\" &&\n typeof module.hydrateRoot === \"function\"\n ? module as ReactDomClientApi\n : module.default;\n\n if (\n !client ||\n typeof client.createRoot !== \"function\" ||\n typeof client.hydrateRoot !== \"function\"\n ) {\n throw new Error(\n \"Demiurge could not load the React DOM client from the Vite module.\",\n );\n }\n\n return client;\n}\n\nexport function Link<const TTo extends AppHref>(\n props: LinkTo<TTo> & {\n children: ReactNode;\n className?: string;\n },\n) {\n const router = useRouter();\n const to = href(props as LinkTarget<TTo>);\n\n return (\n <a\n className={props.className}\n href={to}\n onClick={(event) => {\n if (\n router.navigation === \"server\" &&\n shouldHandleLinkClick(event)\n ) {\n event.preventDefault();\n router.push(to);\n }\n }}\n >\n {props.children}\n </a>\n );\n}\n\nfunction RouteRenderer({\n Loading,\n NotFound,\n match,\n}: {\n Loading?: ComponentType;\n NotFound?: ComponentType<{ pathname: string }>;\n match: PendingRouteMatch;\n}) {\n if (match.status === \"loading\") {\n const AppLoading = match.loading ?? Loading;\n\n return AppLoading ? createElement(AppLoading) : null;\n }\n\n if (match.status === \"not-found\") {\n const AppNotFound = match.notFound ?? NotFound ?? BuiltInNotFound;\n\n return match.layouts.reduceRight<ReactNode>(\n (children, Layout) =>\n createElement(Layout, {\n children,\n path: {},\n pathname: match.pathname,\n }),\n createElement(AppNotFound, { pathname: match.pathname }),\n );\n }\n\n if (match.status === \"error\") {\n return match.Error\n ? createElement(match.Error, {\n error: match.error,\n pathname: match.pathname,\n status: errorStatus(match.error),\n })\n : null;\n }\n\n const { data, error, page, layouts, path, pathname } = match.match;\n const pageElement = createElement(page, { data, path, pathname });\n const routeElement = layouts.reduceRight<ReactNode>(\n (children, Layout) => createElement(Layout, { path, pathname, children }),\n pageElement,\n );\n\n return createElement(RouteErrorBoundary, {\n Error: error,\n children: routeElement,\n pathname,\n });\n}\n\nclass RouteErrorBoundary extends Component<\n {\n children: ReactNode;\n Error?: ComponentType<RouteErrorProps>;\n pathname: string;\n },\n { error?: unknown }\n> {\n static getDerivedStateFromError(error: unknown) {\n return { error };\n }\n\n override state: { error?: unknown } = {};\n\n override componentDidUpdate(previousProps: {\n children: ReactNode;\n Error?: ComponentType<RouteErrorProps>;\n pathname: string;\n }) {\n if (\n this.state.error !== undefined &&\n previousProps.pathname !== this.props.pathname\n ) {\n this.setState({ error: undefined });\n }\n }\n\n override render() {\n if (this.state.error !== undefined) {\n return this.props.Error\n ? createElement(this.props.Error, {\n error: this.state.error,\n pathname: this.props.pathname,\n status: errorStatus(this.state.error),\n })\n : null;\n }\n\n return this.props.children;\n }\n}\n\nfunction errorStatus(error: unknown) {\n return isHttpError(error) ? error.status : 500;\n}\n\nfunction getCurrentLocation() {\n return {\n hash: window.location.hash,\n href: window.location.href,\n pathname: window.location.pathname,\n search: window.location.search,\n };\n}\n\nasync function loadNavigationData(request: Request) {\n const headers = new Headers(request.headers);\n headers.set(\"accept\", \"application/json\");\n headers.set(NAVIGATION_DATA_HEADER, NAVIGATION_DATA_REQUEST);\n const response = await fetch(new Request(request, {\n credentials: \"same-origin\",\n headers,\n }));\n const kind = response.headers.get(NAVIGATION_DATA_HEADER);\n\n if (kind === NAVIGATION_DATA_RESPONSE) {\n const value = await response.json() as Partial<InitialRouteData>;\n\n if (value.hasData !== true) {\n throw new Error(\"Demiurge received malformed navigation route data.\");\n }\n\n return { data: value.data, hasData: true };\n }\n\n if (kind === NAVIGATION_NOT_FOUND_RESPONSE) {\n return { hasData: true };\n }\n\n if (kind === NAVIGATION_ERROR_RESPONSE || !response.ok) {\n const problem = await readProblem(response);\n const status = HTTP_ERROR_STATUSES.includes(\n response.status as (typeof HTTP_ERROR_STATUSES)[number],\n )\n ? response.status as (typeof HTTP_ERROR_STATUSES)[number]\n : 500;\n\n throw httpError(status, {\n detail: typeof problem?.detail === \"string\" ? problem.detail : undefined,\n title: typeof problem?.title === \"string\" ? problem.title : undefined,\n });\n }\n\n throw new Error(\n \"Demiurge expected a navigation data response from the application server.\",\n );\n}\n\nasync function readProblem(response: Response) {\n try {\n return await response.json() as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\nfunction scrollToHash(hash: string) {\n queueMicrotask(() => {\n if (!hash) {\n window.scrollTo?.(0, 0);\n return;\n }\n\n let id: string;\n try {\n id = decodeURIComponent(hash.slice(1));\n } catch {\n id = hash.slice(1);\n }\n document.getElementById(id)?.scrollIntoView?.();\n });\n}\n\nfunction shouldHandleLinkClick(event: MouseEvent<HTMLAnchorElement>) {\n return (\n event.button === 0 &&\n !event.metaKey &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.shiftKey\n );\n}\n\ntype RouterApi = {\n navigation: \"document\" | \"server\";\n push(to: string): void;\n};\n\nconst RouterContext = createContext<RouterApi>({\n navigation: \"document\",\n push(to) {\n window.location.href = to;\n },\n});\n\nfunction useRouter() {\n return useContext(RouterContext);\n}\n","import {\n planImageTransform,\n type ImagePolicy,\n type ImageTransformOptions,\n} from \"./images\";\n\nexport type ImageProps = ImageTransformOptions & {\n className?: string;\n id?: string;\n policy?: ImagePolicy;\n};\n\n// The component is the surface that connects the planner to the build. A\n// rendered `Image` emits a self-describing variant path in `src`/`srcSet`.\n// The static build scans the rendered document for that path, and the\n// runtime optimizer parses it back into a real transform request.\nexport function Image({ className, id, policy, ...options }: ImageProps) {\n const plan = planImageTransform(options, policy);\n\n return (\n <img\n alt={plan.alt}\n className={className}\n decoding={plan.decoding}\n fetchPriority={plan.fetchPriority}\n height={plan.height}\n id={id}\n loading={plan.loading}\n sizes={plan.sizes}\n src={plan.src}\n srcSet={plan.srcSet}\n width={plan.width}\n />\n );\n}\n","import { script, type ScriptTag } from \"../document\";\nimport type { CspSource, RoutePolicy, RouteSecurityNeeds } from \"../security/types\";\n\nexport type AnalyticsConsent = boolean | \"required\";\n\nexport type AnalyticsProvider = \"opentelemetry\" | \"plausible\" | \"sentry\";\n\n/**\n * An integration descriptor. `scripts` goes into `export const scripts` and\n * `needs` goes into the route policy. The build compares the two, so wiring\n * only one half fails with a diagnostic that names the missing directive.\n */\nexport type AnalyticsIntegration = {\n consent: AnalyticsConsent;\n kind: \"analytics\";\n needs: RouteSecurityNeeds;\n provider: AnalyticsProvider;\n scripts: readonly ScriptTag[];\n};\n\nexport type PlausibleAnalyticsOptions = {\n consent?: AnalyticsConsent;\n domain: string;\n endpoint?: string;\n strategy?: ScriptTag[\"strategy\"];\n};\n\nexport type PlausibleAnalytics = AnalyticsIntegration & {\n domain: string;\n provider: \"plausible\";\n};\n\nexport type SentryAnalyticsOptions = {\n consent?: AnalyticsConsent;\n dsn: string;\n loaderHost?: string;\n strategy?: ScriptTag[\"strategy\"];\n};\n\nexport type SentryAnalytics = AnalyticsIntegration & {\n ingestOrigin: string;\n projectId: string;\n provider: \"sentry\";\n};\n\nexport type OpenTelemetryAnalyticsOptions = {\n consent?: AnalyticsConsent;\n endpoint: string;\n script?: string;\n strategy?: ScriptTag[\"strategy\"];\n};\n\nexport type OpenTelemetryAnalytics = AnalyticsIntegration & {\n endpoint: string;\n provider: \"opentelemetry\";\n};\n\nconst sentryLoaderHost = \"https://js.sentry-cdn.com\";\n\nexport const analytics = {\n /**\n * Plausible loads one script and posts events to its own API. The snippet\n * carries configuration in `data-domain`, so no inline code is involved.\n * `endpoint` accepts a same-origin path prefix for a proxied deployment.\n */\n plausible(options: PlausibleAnalyticsOptions): PlausibleAnalytics {\n const domain = normalizeDomain(options.domain);\n const endpoint = parseEndpoint(options.endpoint ?? \"https://plausible.io\");\n\n return {\n consent: options.consent ?? false,\n domain,\n kind: \"analytics\",\n needs: {\n connect: [endpoint.source],\n script: [endpoint.source],\n },\n provider: \"plausible\",\n scripts: [\n script({\n dataApi: `${endpoint.base}/api/event`,\n dataDomain: domain,\n defer: true,\n needs: { connect: [endpoint.source] },\n purpose: \"analytics\",\n src: `${endpoint.base}/js/script.js`,\n strategy: options.strategy ?? \"afterInteractive\",\n }),\n ],\n };\n },\n /**\n * The Sentry loader script carries the DSN in its own filename, so a page\n * needs no inline configuration call. Events go to the DSN host, which is\n * why the integration also declares a `connect-src` need.\n */\n sentry(options: SentryAnalyticsOptions): SentryAnalytics {\n const dsn = parseSentryDsn(options.dsn);\n const loader = parseHttpsOrigin(\n options.loaderHost ?? sentryLoaderHost,\n \"Sentry loader host\",\n );\n\n return {\n consent: options.consent ?? false,\n ingestOrigin: dsn.origin,\n kind: \"analytics\",\n needs: {\n connect: [dsn.origin],\n script: [loader],\n },\n projectId: dsn.projectId,\n provider: \"sentry\",\n scripts: [\n script({\n crossOrigin: \"anonymous\",\n needs: { connect: [dsn.origin] },\n purpose: \"error-monitoring\",\n src: `${loader}/${dsn.publicKey}.min.js`,\n // Errors thrown before the app is interactive are the ones an\n // application can least afford to lose.\n strategy: options.strategy ?? \"beforeInteractive\",\n }),\n ],\n };\n },\n /**\n * OpenTelemetry publishes no hosted browser loader. Browser instrumentation\n * is application code bundled from npm packages, so this helper describes\n * the part a policy has to know about: the OTLP endpoint the exporter posts\n * to, and an optional same-origin entry script that starts the SDK.\n */\n openTelemetry(\n options: OpenTelemetryAnalyticsOptions,\n ): OpenTelemetryAnalytics {\n const endpoint = parseEndpoint(options.endpoint);\n const entry = options.script;\n\n if (entry !== undefined && !entry.startsWith(\"/\")) {\n throw new Error(\n \"OpenTelemetry browser instrumentation must be a same-origin script path.\",\n );\n }\n\n return {\n consent: options.consent ?? false,\n endpoint: endpoint.base || \"/\",\n kind: \"analytics\",\n needs: entry\n ? { connect: [endpoint.source], script: [\"'self'\"] }\n : { connect: [endpoint.source] },\n provider: \"opentelemetry\",\n scripts: entry\n ? [\n script({\n needs: { connect: [endpoint.source] },\n purpose: \"observability\",\n src: entry,\n strategy: options.strategy ?? \"module\",\n }),\n ]\n : [],\n };\n },\n /** Merges the CSP needs of every integration into one route policy. */\n policy(...integrations: readonly AnalyticsIntegration[]): RoutePolicy {\n const needs: { -readonly [Key in keyof RouteSecurityNeeds]: CspSource[] } =\n {};\n\n for (const integration of integrations) {\n for (const need of [\"connect\", \"img\", \"script\"] as const) {\n const sources = integration.needs[need];\n\n if (!sources || sources.length === 0) {\n continue;\n }\n\n needs[need] = [...new Set([...(needs[need] ?? []), ...sources])];\n }\n }\n\n return { security: { needs } };\n },\n /** Collects the script contributions of every integration. */\n scripts(...integrations: readonly AnalyticsIntegration[]): ScriptTag[] {\n return integrations.flatMap((integration) => [...integration.scripts]);\n },\n};\n\nfunction normalizeDomain(domain: string) {\n const normalized = domain.trim();\n\n if (!normalized || normalized.includes(\"/\") || normalized.includes(\" \")) {\n throw new Error(\"Analytics domain must be a hostname without a path.\");\n }\n\n return normalized;\n}\n\n// An endpoint is either a vendor origin or a same-origin path prefix. A proxied\n// deployment serves the vendor through the application origin, which `'self'`\n// already covers, so the returned CSP source differs in that case.\nfunction parseEndpoint(endpoint: string) {\n if (endpoint.startsWith(\"/\")) {\n if (endpoint.startsWith(\"//\")) {\n throw new Error(\"Analytics endpoint must not be a scheme-relative URL.\");\n }\n\n return {\n base: endpoint === \"/\" ? \"\" : endpoint.replace(/\\/+$/, \"\"),\n source: \"'self'\" as CspSource,\n };\n }\n\n const url = parseAbsoluteEndpoint(endpoint);\n\n return { base: url.origin, source: url.origin as CspSource };\n}\n\nfunction parseAbsoluteEndpoint(endpoint: string) {\n let url: URL;\n\n try {\n url = new URL(endpoint);\n } catch {\n throw new Error(\"Analytics endpoint must be an absolute URL.\");\n }\n\n if (url.protocol !== \"https:\") {\n throw new Error(\"Analytics endpoint must use HTTPS.\");\n }\n\n return url;\n}\n\nfunction parseHttpsOrigin(value: string, label: string) {\n let url: URL;\n\n try {\n url = new URL(value);\n } catch {\n throw new Error(`${label} must be an absolute URL.`);\n }\n\n if (url.protocol !== \"https:\") {\n throw new Error(`${label} must use HTTPS.`);\n }\n\n return url.origin;\n}\n\n// A Sentry DSN is https://<publicKey>@<host>/<projectId>. Every part the\n// browser needs comes from it, so an application configures one value.\nfunction parseSentryDsn(dsn: string) {\n let url: URL;\n\n try {\n url = new URL(dsn);\n } catch {\n throw new Error(\"Sentry DSN must be an absolute URL.\");\n }\n\n if (url.protocol !== \"https:\") {\n throw new Error(\"Sentry DSN must use HTTPS.\");\n }\n\n const projectId = url.pathname.replace(/^\\//, \"\");\n\n if (!url.username || url.password) {\n throw new Error(\n \"Sentry DSN must carry a public key and no secret key.\",\n );\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(projectId)) {\n throw new Error(\"Sentry DSN must end with a project identifier.\");\n }\n\n return {\n origin: url.origin,\n projectId,\n publicKey: url.username,\n };\n}\n","export type ObservabilityValue =\n | boolean\n | null\n | number\n | string\n | readonly ObservabilityValue[]\n | { readonly [key: string]: ObservabilityValue };\n\nexport type RequestSignal = {\n duration?: number;\n method: string;\n pathname: string;\n status?: number;\n attributes?: Readonly<Record<string, ObservabilityValue>>;\n};\n\nexport type ServerStartSignal = {\n adapter?: string;\n attributes?: Readonly<Record<string, ObservabilityValue>>;\n timestamp?: number;\n};\n\nexport type TraceSignal = {\n attributes?: Readonly<Record<string, ObservabilityValue>>;\n duration?: number;\n name: string;\n status?: \"error\" | \"ok\" | \"unset\";\n traceId?: string;\n};\n\nexport type WebVitalName = \"CLS\" | \"FCP\" | \"FID\" | \"INP\" | \"LCP\" | \"TTFB\";\n\nexport type WebVitalSignal = {\n id?: string;\n name: WebVitalName;\n navigationType?: string;\n rating?: \"good\" | \"needs-improvement\" | \"poor\";\n value: number;\n attributes?: Readonly<Record<string, ObservabilityValue>>;\n};\n\nexport type InstrumentationEvent =\n | { kind: \"request\"; signal: RequestSignal }\n | { kind: \"server-start\"; signal: ServerStartSignal }\n | { kind: \"trace\"; signal: TraceSignal }\n | { kind: \"web-vital\"; signal: WebVitalSignal };\n\nexport type InstrumentationHandler<T> = (signal: T) => void | Promise<void>;\n\nexport type InstrumentationOptions = {\n onEvent?: InstrumentationHandler<InstrumentationEvent>;\n request?: InstrumentationHandler<RequestSignal>;\n serverStart?: InstrumentationHandler<ServerStartSignal>;\n trace?: InstrumentationHandler<TraceSignal>;\n webVitals?: InstrumentationHandler<WebVitalSignal>;\n};\n\nexport type Instrumentation = {\n request: (signal: RequestSignal) => Promise<void>;\n serverStart: (signal?: ServerStartSignal) => Promise<void>;\n trace: (signal: TraceSignal) => Promise<void>;\n reportWebVitals: (signal: WebVitalSignal) => Promise<void>;\n};\n\nexport function defineInstrumentation(\n options: InstrumentationOptions = {},\n): Instrumentation {\n return {\n async request(signal) {\n await dispatch({ kind: \"request\", signal }, options);\n },\n async serverStart(signal = {}) {\n await dispatch({ kind: \"server-start\", signal }, options);\n },\n async trace(signal) {\n await dispatch({ kind: \"trace\", signal }, options);\n },\n async reportWebVitals(signal) {\n await dispatch({ kind: \"web-vital\", signal }, options);\n },\n };\n}\n\nasync function dispatch(\n event: InstrumentationEvent,\n options: InstrumentationOptions,\n) {\n await options.onEvent?.(event);\n\n if (event.kind === \"request\") {\n await options.request?.(event.signal);\n } else if (event.kind === \"server-start\") {\n await options.serverStart?.(event.signal);\n } else if (event.kind === \"trace\") {\n await options.trace?.(event.signal);\n } else {\n await options.webVitals?.(event.signal);\n }\n}\n"],"names":["defaultIdempotencyTtl","defaultMaximumEntries","createMemoryIdempotencyStore","options","now","defaultTtl","maximumEntries","defaultTtlMs","parseCacheDuration","entries","request","key","serializeCacheKey","currentTime","sweepExpiredIdempotencyEntries","existing","evictOldestCompletedIdempotencyEntry","value","entry","result","error","runIdempotentMutation","store","defineSitemap","renderSitemap","sitemap","renderSitemapEntry","defineRobots","defineOgImage","renderRobots","robots","lines","rule","userAgent","toArray","allow","disallow","renderOgImageSvg","image","width","height","background","foreground","title","clampText","subtitle","brand","validateOgImageDimensions","escapeXmlAttribute","escapeXml","line","renderOgImageResponse","formatLastModified","formatPriority","alternate","priority","maxLength","action","response","context","input","actionContext","run","resolveActionResult","actionInput","toResponse","page","defineMiddleware","middleware","webhook","rawBody","signature","verifyHmacSignature","suppliedSignature","algorithm","encoding","normalized","normalizeSignature","decodeSignature","configuredPrefix","trimmed","prefix","pair","binary","character","EnvValidationError","issues","formatEnvValidationError","defineEnvSchema","schema","validateEnv","source","values","variable","rawValue","booleanEnv","createVariable","enumEnv","integerEnv","parsed","secretEnv","parseString","stringEnv","urlEnv","url","env","sensitive","parse","createSecurityReportHandler","contentTypeResponse","enforceReportContentType","bodySizeResponse","enforceReportBodySize","limitRequestBody","payload","RequestBodyTooLargeError","reports","normalizeSecurityReports","index","supportedReportContentTypes","mediaType","contentLength","declaredSize","parseBodySize","isObject","validateUploads","formData","policy","files","totalSize","field","filePolicy","fieldFiles","isFile","file","validateFile","isAllowedFileType","type","allowedTypes","allowedType","checkWebSocketOrigin","origin","normalizedOrigin","normalizeOrigin","allowed","isAllowedOrigin","enforceWebSocketOrigin","allowedOrigin","originMatches","actualOrigin","schemeSeparator","authority","createFileRouter","manifest","createRouteManifest","navigationDataLoader","loadNavigationData","location","setLocation","useState","getCurrentLocation","match","setMatch","initialMatchPending","useRef","navigationSequence","useEffect","onPopState","cancelled","settled","sequence","controller","isCurrent","getMatchPathname","loadLoadingFallback","Loading","initialData","loadPageRoute","nextMatch","ErrorFallback","loadErrorFallback","router","useMemo","to","previous","next","scrollToHash","createElement","RouterContext","RouteRenderer","isHydratableMatch","root","fallback","HYDRATION_FALLBACK_ATTRIBUTE","hydrateFileRouter","readInitialRouteData","hydratable","Router","createRoot","hydrateRoot","resolveReactDomClient","HYDRATION_ROOT_ATTRIBUTE","startDeferredScripts","module","client","Link","props","useRouter","href","jsx","event","shouldHandleLinkClick","NotFound","AppLoading","AppNotFound","BuiltInNotFound","children","Layout","errorStatus","data","layouts","path","pathname","pageElement","routeElement","RouteErrorBoundary","Component","previousProps","isHttpError","headers","NAVIGATION_DATA_HEADER","NAVIGATION_DATA_REQUEST","kind","NAVIGATION_DATA_RESPONSE","NAVIGATION_NOT_FOUND_RESPONSE","NAVIGATION_ERROR_RESPONSE","problem","readProblem","status","HTTP_ERROR_STATUSES","httpError","hash","id","createContext","useContext","Image","className","plan","planImageTransform","sentryLoaderHost","analytics","domain","normalizeDomain","endpoint","parseEndpoint","script","dsn","parseSentryDsn","loader","parseHttpsOrigin","integrations","needs","integration","need","sources","parseAbsoluteEndpoint","label","projectId","defineInstrumentation","signal","dispatch"],"mappings":";;;;;;;;;AAuCA,MAAMA,KAAwB,OACxBC,KAAwB;AAEvB,SAASC,GACdC,IAAyC,IACvB;AAClB,QAAMC,IAAMD,EAAQ,OAAO,KAAK,KAC1BE,IAAaF,EAAQ,cAAcH,IACnCM,IAAiBH,EAAQ,kBAAkBF;AAEjD,MAAI,CAAC,OAAO,cAAcK,CAAc,KAAKA,KAAkB;AAC7D,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,QAAMC,IAAeC,EAAmBH,CAAU;AAElD,MAAI,CAAC,OAAO,SAASE,CAAY;AAC/B,UAAM,IAAI,MAAM,iDAAiD;AAGnE,QAAME,wBAAc,IAAA;AAEpB,SAAO;AAAA,IACL,MAAM,IAAaC,GAAsC;AACvD,YAAMC,IAAMC,EAAkBF,EAAQ,GAAG,GACnCG,IAAcT,EAAA;AACpB,MAAAU,GAA+BL,GAASI,CAAW;AACnD,YAAME,IAAWN,EAAQ,IAAIE,CAAG;AAEhC,UAAII,MAAaA,EAAS,WAAWA,EAAS,YAAYF;AACxD,eAAO;AAAA,UACL,KAAAF;AAAA,UACA,UAAU;AAAA,UACV,OAAO,MAAOI,EAAS;AAAA,QAAA;AAQ3B,UAJIN,EAAQ,QAAQH,KAClBU,GAAqCP,CAAO,GAG1CA,EAAQ,QAAQH;AAClB,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAIJ,YAAMW,IAAQ,QAAQ,QAAA,EAAU,KAAKP,EAAQ,EA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AU1Q,CAAO;AAAA,IAC1D;AAAA,IACA,MAAM,MAAM0Q,GAAQ;AAClB,YAAMC,EAAS,EAAE,MAAM,SAAS,QAAAD,EAAA,GAAU1Q,CAAO;AAAA,IACnD;AAAA,IACA,MAAM,gBAAgB0Q,GAAQ;AAC5B,YAAMC,EAAS,EAAE,MAAM,aAAa,QAAAD,EAAA,GAAU1Q,CAAO;AAAA,IACvD;AAAA,EAAA;AAEJ;AAEA,eAAe2Q,EACb5D,GACA/M,GACA;AACA,QAAMA,EAAQ,UAAU+M,CAAK,GAEzBA,EAAM,SAAS,YACjB,MAAM/M,EAAQ,UAAU+M,EAAM,MAAM,IAC3BA,EAAM,SAAS,iBACxB,MAAM/M,EAAQ,cAAc+M,EAAM,MAAM,IAC/BA,EAAM,SAAS,UACxB,MAAM/M,EAAQ,QAAQ+M,EAAM,MAAM,IAElC,MAAM/M,EAAQ,YAAY+M,EAAM,MAAM;AAE1C;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/document/seo.ts","../src/data/idempotency.ts","../src/route/page.ts","../src/route/middleware.ts","../src/route/webhook.ts","../src/security/cookies.ts","../src/security/cookie-session.ts","../src/security/session-manager.ts","../src/security/report.ts","../src/security/upload.ts","../src/security/websocket.ts","../src/browser/focus.tsx","../src/browser/mutation-action.ts","../src/browser/file-router.tsx","../src/platform/image.tsx","../src/platform/analytics.ts","../src/platform/observability.ts","../src/platform/web-vitals.ts","../src/platform/web-vitals-client.ts"],"sourcesContent":["import { IMMUTABLE_FILE_CACHE_CONTROL } from \"../static-files\";\n\nexport type SitemapChangeFrequency =\n | \"always\"\n | \"hourly\"\n | \"daily\"\n | \"weekly\"\n | \"monthly\"\n | \"yearly\"\n | \"never\";\n\nexport type SitemapAlternate = {\n href: string;\n hrefLang: string;\n};\n\nexport type SitemapEntry = {\n alternates?: readonly SitemapAlternate[];\n changeFrequency?: SitemapChangeFrequency;\n lastModified?: Date | string;\n priority?: number;\n url: string;\n};\n\nexport type Sitemap = {\n entries: readonly SitemapEntry[];\n};\n\nexport type RobotsDirective = {\n allow?: string | readonly string[];\n disallow?: string | readonly string[];\n userAgent: string | readonly string[];\n};\n\nexport type Robots = {\n host?: string;\n rules?: readonly RobotsDirective[];\n sitemap?: string | readonly string[];\n};\n\nexport type OgImage = {\n background?: string;\n brand?: string;\n foreground?: string;\n height?: number;\n subtitle?: string;\n title: string;\n width?: number;\n};\n\nexport function defineSitemap(entries: readonly SitemapEntry[]): Sitemap {\n return {\n entries: entries.map((entry) => ({\n ...entry,\n alternates: normalizeSitemapAlternates(entry.alternates ?? []),\n })),\n };\n}\n\nfunction normalizeSitemapAlternates(\n alternates: readonly SitemapAlternate[],\n) {\n const byLanguage = new Map<string, string>();\n const byUrl = new Map<string, string>();\n\n for (const alternate of alternates) {\n const language = alternate.hrefLang.toLowerCase();\n let href: string;\n try {\n href = new URL(alternate.href).href;\n } catch {\n throw new Error(\n `Sitemap alternate URL must be absolute: ${JSON.stringify(alternate.href)}.`,\n );\n }\n const previousHref = byLanguage.get(language);\n const previousLanguage = byUrl.get(href);\n if (previousHref && previousHref !== href) {\n throw new Error(`Sitemap language ${JSON.stringify(alternate.hrefLang)} has conflicting URLs.`);\n }\n if (\n previousLanguage &&\n previousLanguage !== language &&\n previousLanguage !== \"x-default\" &&\n language !== \"x-default\"\n ) {\n throw new Error(`Sitemap URL ${JSON.stringify(alternate.href)} has conflicting languages.`);\n }\n byLanguage.set(language, href);\n byUrl.set(href, language);\n }\n\n return [...byLanguage].map(([hrefLang, href]) => ({ href, hrefLang }));\n}\n\nexport function renderSitemap(sitemap: Sitemap) {\n const hasAlternates = sitemap.entries.some((entry) => entry.alternates?.length);\n\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n `<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"${hasAlternates ? ' xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"' : \"\"}>`,\n ...sitemap.entries.map(renderSitemapEntry),\n \"</urlset>\",\n \"\",\n ].join(\"\\n\");\n}\n\nexport function defineRobots(options: Robots): Robots {\n return options;\n}\n\nexport function defineOgImage(options: OgImage): OgImage {\n return options;\n}\n\nexport function renderRobots(robots: Robots) {\n const lines: string[] = [];\n\n for (const rule of robots.rules ?? []) {\n for (const userAgent of toArray(rule.userAgent)) {\n lines.push(`User-agent: ${userAgent}`);\n }\n\n for (const allow of toArray(rule.allow)) {\n lines.push(`Allow: ${allow}`);\n }\n\n for (const disallow of toArray(rule.disallow)) {\n lines.push(`Disallow: ${disallow}`);\n }\n\n lines.push(\"\");\n }\n\n if (robots.host) {\n lines.push(`Host: ${robots.host}`);\n }\n\n for (const sitemap of toArray(robots.sitemap)) {\n lines.push(`Sitemap: ${sitemap}`);\n }\n\n return `${lines.join(\"\\n\").replace(/\\n+$/, \"\")}\\n`;\n}\n\nexport function renderOgImageSvg(image: OgImage) {\n const width = image.width ?? 1200;\n const height = image.height ?? 630;\n const background = image.background ?? \"#101820\";\n const foreground = image.foreground ?? \"#ffffff\";\n const title = clampText(image.title, 120);\n const subtitle = image.subtitle ? clampText(image.subtitle, 160) : undefined;\n const brand = image.brand ? clampText(image.brand, 80) : undefined;\n\n validateOgImageDimensions(width, height);\n\n return [\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"0 0 ${width} ${height}\" role=\"img\" aria-label=\"${escapeXmlAttribute(title)}\">`,\n ` <rect width=\"100%\" height=\"100%\" fill=\"${escapeXmlAttribute(background)}\" />`,\n brand\n ? ` <text x=\"72\" y=\"96\" fill=\"${escapeXmlAttribute(foreground)}\" font-family=\"Inter, ui-sans-serif, system-ui, sans-serif\" font-size=\"32\" font-weight=\"700\">${escapeXml(brand)}</text>`\n : null,\n ` <text x=\"72\" y=\"${subtitle ? 300 : 340}\" fill=\"${escapeXmlAttribute(foreground)}\" font-family=\"Inter, ui-sans-serif, system-ui, sans-serif\" font-size=\"76\" font-weight=\"800\">${escapeXml(title)}</text>`,\n subtitle\n ? ` <text x=\"72\" y=\"392\" fill=\"${escapeXmlAttribute(foreground)}\" fill-opacity=\"0.78\" font-family=\"Inter, ui-sans-serif, system-ui, sans-serif\" font-size=\"38\" font-weight=\"500\">${escapeXml(subtitle)}</text>`\n : null,\n \"</svg>\",\n ].filter((line): line is string => Boolean(line)).join(\"\\n\");\n}\n\nexport function renderOgImageResponse(image: OgImage) {\n return new Response(renderOgImageSvg(image), {\n headers: {\n \"cache-control\": IMMUTABLE_FILE_CACHE_CONTROL,\n \"content-type\": \"image/svg+xml; charset=utf-8\",\n },\n });\n}\n\nfunction renderSitemapEntry(entry: SitemapEntry) {\n return [\n \" <url>\",\n ` <loc>${escapeXml(entry.url)}</loc>`,\n entry.lastModified\n ? ` <lastmod>${escapeXml(formatLastModified(entry.lastModified))}</lastmod>`\n : null,\n entry.changeFrequency\n ? ` <changefreq>${entry.changeFrequency}</changefreq>`\n : null,\n entry.priority !== undefined\n ? ` <priority>${formatPriority(entry.priority)}</priority>`\n : null,\n ...(entry.alternates ?? []).map(\n (alternate) =>\n ` <xhtml:link rel=\"alternate\" hreflang=\"${escapeXmlAttribute(alternate.hrefLang)}\" href=\"${escapeXmlAttribute(alternate.href)}\" />`,\n ),\n \" </url>\",\n ].filter((line): line is string => Boolean(line)).join(\"\\n\");\n}\n\nfunction formatLastModified(value: Date | string) {\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction formatPriority(priority: number) {\n if (priority < 0 || priority > 1) {\n throw new Error(\"Sitemap entry priority must be between 0 and 1.\");\n }\n\n return String(priority);\n}\n\nfunction toArray<T>(value: T | readonly T[] | undefined) {\n if (value === undefined) {\n return [];\n }\n\n return Array.isArray(value) ? value : [value];\n}\n\nfunction escapeXml(value: string) {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\");\n}\n\nfunction escapeXmlAttribute(value: string) {\n return escapeXml(value)\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\");\n}\n\nfunction clampText(value: string, maxLength: number) {\n return value.length > maxLength ? `${value.slice(0, maxLength - 3)}...` : value;\n}\n\nfunction validateOgImageDimensions(width: number, height: number) {\n if (!Number.isSafeInteger(width) || width <= 0) {\n throw new Error(\"OG image width must be a positive integer.\");\n }\n\n if (!Number.isSafeInteger(height) || height <= 0) {\n throw new Error(\"OG image height must be a positive integer.\");\n }\n}\n","import {\n parseCacheDuration,\n serializeCacheKey,\n type CacheDuration,\n type CacheKey,\n} from \"./cache\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type IdempotencyRequest<TResult> = {\n fn: () => MaybePromise<TResult>;\n key: CacheKey;\n ttl?: CacheDuration;\n};\n\nexport type IdempotencyResult<TResult> = {\n key: string;\n replayed: boolean;\n value: TResult;\n};\n\nexport type IdempotencyStore = {\n run: <TResult>(\n request: IdempotencyRequest<TResult>,\n ) => Promise<IdempotencyResult<TResult>>;\n};\n\ntype IdempotencyEntry<TResult> = {\n expiresAt: number;\n pending: boolean;\n value: Promise<TResult>;\n};\n\nexport type MemoryIdempotencyStoreOptions = {\n defaultTtl?: CacheDuration;\n maximumEntries?: number;\n now?: () => number;\n};\n\nconst defaultIdempotencyTtl = \"24h\";\nconst defaultMaximumEntries = 10_000;\n\nexport function createMemoryIdempotencyStore(\n options: MemoryIdempotencyStoreOptions = {},\n): IdempotencyStore {\n const now = options.now ?? Date.now;\n const defaultTtl = options.defaultTtl ?? defaultIdempotencyTtl;\n const maximumEntries = options.maximumEntries ?? defaultMaximumEntries;\n\n if (!Number.isSafeInteger(maximumEntries) || maximumEntries <= 0) {\n throw new Error(\n \"Demiurge idempotency maximumEntries must be a positive integer.\",\n );\n }\n\n const defaultTtlMs = parseCacheDuration(defaultTtl);\n\n if (!Number.isFinite(defaultTtlMs)) {\n throw new Error(\"Demiurge idempotency defaultTtl must be finite.\");\n }\n\n const entries = new Map<string, IdempotencyEntry<unknown>>();\n\n return {\n async run<TResult>(request: IdempotencyRequest<TResult>) {\n const key = serializeCacheKey(request.key);\n const currentTime = now();\n sweepExpiredIdempotencyEntries(entries, currentTime);\n const existing = entries.get(key);\n\n if (existing && (existing.pending || existing.expiresAt > currentTime)) {\n // TYPE-EVIDENCE: the entry stores the promise from a request typed TResult. The cast restores that generic type.\n const stored = await (existing.value as Promise<TResult>);\n return {\n key,\n replayed: true,\n value: cloneIdempotencyResult(stored),\n };\n }\n\n if (entries.size >= maximumEntries) {\n evictOldestCompletedIdempotencyEntry(entries);\n }\n\n if (entries.size >= maximumEntries) {\n throw new Error(\n \"Demiurge idempotency store is at capacity with in-flight mutations.\",\n );\n }\n\n const value = Promise.resolve().then(request.fn);\n const entry: IdempotencyEntry<TResult> = {\n expiresAt: Number.POSITIVE_INFINITY,\n pending: true,\n value,\n };\n\n entries.set(key, entry);\n\n try {\n const result = await value;\n entry.pending = false;\n entry.expiresAt = now() + parseCacheDuration(request.ttl ?? defaultTtl);\n\n return {\n key,\n replayed: false,\n value: cloneIdempotencyResult(result),\n };\n } catch (error) {\n if (entries.get(key) === entry) {\n entries.delete(key);\n }\n\n throw error;\n }\n },\n };\n}\n\nfunction cloneIdempotencyResult<TResult>(value: TResult): TResult {\n if (!(value instanceof Response)) return value;\n // TYPE-EVIDENCE: Response.clone() has the same runtime type and representation as the stored Response value.\n return value.clone() as TResult;\n}\n\nfunction sweepExpiredIdempotencyEntries(\n entries: Map<string, IdempotencyEntry<unknown>>,\n now: number,\n) {\n for (const [key, entry] of entries) {\n if (!entry.pending && entry.expiresAt <= now) {\n entries.delete(key);\n }\n }\n}\n\nfunction evictOldestCompletedIdempotencyEntry(\n entries: Map<string, IdempotencyEntry<unknown>>,\n) {\n for (const [key, entry] of entries) {\n if (!entry.pending) {\n entries.delete(key);\n return;\n }\n }\n}\n\nexport function runIdempotentMutation<TResult>(\n store: IdempotencyStore,\n request: IdempotencyRequest<TResult>,\n) {\n return store.run(request);\n}\n","import type { ComponentType } from \"react\";\nimport type {\n PageCapability,\n PageOptions,\n RouteProps,\n RouteRequestContextFor,\n} from \"./types\";\n\nexport function page<const TPath extends string = string>(\n options: ComponentType<RouteProps<TPath>>,\n): PageCapability<TPath>;\nexport function page<\n const TPath extends string = string,\n TData = undefined,\n TValues extends object = RouteRequestContextFor<TPath>,\n>(\n options: PageOptions<TPath, TData, TValues>,\n): PageCapability<TPath, TData, TValues>;\nexport function page<\n const TPath extends string = string,\n TData = undefined,\n TValues extends object = RouteRequestContextFor<TPath>,\n>(\n options: PageOptions<TPath, TData, TValues> | ComponentType<RouteProps<TPath>>,\n): PageCapability<TPath, TData, TValues> | PageCapability<TPath> {\n if (typeof options === \"function\") {\n return {\n kind: \"page\",\n render: { mode: \"ssr\" },\n view: options,\n } satisfies PageCapability<TPath>;\n }\n\n // TYPE-EVIDENCE: the object literal carries the fields that the page capability type requires. The cast asserts that structural match.\n return {\n data: options.data,\n kind: \"page\",\n layout: options.layout,\n render: options.render ?? { mode: \"ssr\" },\n view: options.view,\n } as PageCapability<TPath, TData, TValues>;\n}\n","import type {\n HttpRouteContext,\n MaybePromise,\n MiddlewareContextContribution,\n RouteMiddleware,\n RouteMiddlewareNext,\n} from \"./types\";\n\n/**\n * Declares the request-context values that a middleware can read and write.\n * The framework passes one carrier to every inherited middleware in a request.\n */\nexport function defineMiddleware<TValues extends object>(\n middleware: (\n context: HttpRouteContext<string, TValues>,\n next: RouteMiddlewareNext,\n ) => MaybePromise<Response>,\n): RouteMiddleware<string, TValues> & MiddlewareContextContribution<TValues> {\n // TYPE-EVIDENCE: the middleware function matches the declared route middleware signature. The cast adds the context contribution marker type.\n return middleware as RouteMiddleware<string, TValues> &\n MiddlewareContextContribution<TValues>;\n}\n","import type {\n HttpRouteContext,\n MaybePromise,\n RawResponseCapability,\n} from \"./types\";\n\nexport type WebhookHmacEncoding = \"base64\" | \"hex\";\nexport type WebhookHmacAlgorithm = \"SHA-256\" | \"SHA-384\" | \"SHA-512\";\n\nexport type WebhookHmacContext = HttpRouteContext & {\n rawBody: Uint8Array;\n text: () => string;\n};\n\nexport type WebhookHmacOptions = {\n algorithm?: WebhookHmacAlgorithm;\n encoding?: WebhookHmacEncoding;\n handler: (context: WebhookHmacContext) => MaybePromise<Response>;\n header?: string;\n prefix?: false | string;\n secret: string;\n};\n\nexport const webhook = {\n hmac(options: WebhookHmacOptions) {\n return {\n kind: \"response\",\n response: async (context) => {\n const rawBody = new Uint8Array(await context.request.arrayBuffer());\n const signature = context.request.headers.get(\n options.header ?? \"x-webhook-signature\",\n );\n\n if (!signature) {\n return new Response(\"Missing webhook signature.\", {\n status: 401,\n });\n }\n\n if (!(await verifyHmacSignature(rawBody, signature, options))) {\n return new Response(\"Invalid webhook signature.\", {\n status: 401,\n });\n }\n\n return await options.handler({\n ...context,\n rawBody,\n text: () => new TextDecoder().decode(rawBody),\n });\n },\n security: {\n csrf: false,\n },\n } satisfies RawResponseCapability;\n },\n};\n\nasync function verifyHmacSignature(\n rawBody: Uint8Array,\n suppliedSignature: string,\n options: WebhookHmacOptions,\n) {\n const algorithm = options.algorithm ?? \"SHA-256\";\n const encoding = options.encoding ?? \"hex\";\n const normalized = normalizeSignature(\n suppliedSignature,\n algorithm,\n options.prefix,\n );\n const signature = decodeSignature(normalized, encoding);\n\n if (!signature) {\n return false;\n }\n\n const key = await globalThis.crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(options.secret),\n {\n hash: algorithm,\n name: \"HMAC\",\n },\n false,\n [\"verify\"],\n );\n return await globalThis.crypto.subtle.verify(\n \"HMAC\",\n key,\n signature,\n Uint8Array.from(rawBody).buffer,\n );\n}\n\nfunction normalizeSignature(\n signature: string,\n algorithm: WebhookHmacAlgorithm,\n configuredPrefix: false | string | undefined,\n) {\n const trimmed = signature.trim();\n const prefix =\n configuredPrefix === undefined\n ? `${algorithm.toLowerCase().replace(\"-\", \"\")}=`\n : configuredPrefix;\n\n if (prefix !== false && trimmed.startsWith(prefix)) {\n return trimmed.slice(prefix.length).trim();\n }\n\n return trimmed;\n}\n\nfunction decodeSignature(value: string, encoding: WebhookHmacEncoding) {\n if (encoding === \"hex\") {\n if (!/^(?:[0-9a-f]{2})+$/i.test(value)) {\n return null;\n }\n\n return Uint8Array.from(value.match(/.{2}/g) ?? [], (pair) =>\n Number.parseInt(pair, 16),\n );\n }\n\n if (\n !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(\n value,\n )\n ) {\n return null;\n }\n\n try {\n const binary =\n typeof atob === \"function\"\n ? atob(value)\n : Buffer.from(value, \"base64\").toString(\"binary\");\n\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n } catch {\n return null;\n }\n}\n","import { parseCookieHeader } from \"./csrf\";\n\n// Cookie prefixes are the one cookie control that the browser enforces without\n// server cooperation. A browser refuses a `__Host-` cookie that lacks `Secure`,\n// that lacks `Path=/`, or that carries a `Domain` attribute. A browser also\n// refuses a `__Secure-` cookie that lacks `Secure`. A refused cookie is\n// dropped without a network error, so a mistake looks like a lost session\n// rather than a policy failure. These helpers make the invariants explicit and\n// report a violation before the response leaves the server.\nexport type CookieScope = \"host\" | \"none\" | \"secure\";\n\nexport type CookieSameSite = \"Lax\" | \"None\" | \"Strict\";\n\nexport type SecureCookieDeclaration = {\n domain?: string;\n expires?: Date;\n httpOnly?: boolean;\n maxAge?: number;\n name: string;\n path?: string;\n sameSite?: CookieSameSite;\n scope?: CookieScope;\n secure?: boolean;\n value: string;\n};\n\n// The part of a declaration that determines a cookie's identity rather than\n// one write's payload. An application declares this once, in a module both\n// the route and the client bundle import. It spreads the definition into\n// `createSecureCookie({ ...definition, value })` on the server, and passes it\n// straight to `readSecureCookie(definition)` on the client. Neither side\n// retypes the name or the scope, so a rename in one place changes both.\nexport type SecureCookieDefinition = Omit<SecureCookieDeclaration, \"value\">;\n\nexport type CookieIssueCode =\n | \"cookie-domain-not-allowed\"\n | \"cookie-max-age-invalid\"\n | \"cookie-name-carries-prefix\"\n | \"cookie-name-invalid\"\n | \"cookie-path-not-allowed\"\n | \"cookie-same-site-none-requires-secure\"\n | \"cookie-scope-requires-secure\"\n | \"cookie-too-large\";\n\nexport type CookieIssue = {\n code: CookieIssueCode;\n message: string;\n name: string;\n};\n\nconst namePattern = /^[!#$%&'*+\\-.^_`|~A-Za-z0-9]+$/;\nconst prefixes: Record<CookieScope, string> = {\n host: \"__Host-\",\n none: \"\",\n secure: \"__Secure-\",\n};\n// Browsers keep about 4096 bytes for one cookie, including the name, the value,\n// and the attributes. A larger cookie is dropped without a report.\nconst maxCookieBytes = 4096;\n\nexport function secureCookieName(name: string, scope: CookieScope = \"host\") {\n return `${prefixes[scope]}${name}`;\n}\n\nexport function validateSecureCookie(\n declaration: SecureCookieDeclaration,\n): CookieIssue[] {\n const scope = declaration.scope ?? \"host\";\n const name = secureCookieName(declaration.name, scope);\n const issues: CookieIssue[] = [];\n const report = (code: CookieIssueCode, message: string) => {\n issues.push({ code, message, name });\n };\n\n if (!namePattern.test(declaration.name)) {\n report(\n \"cookie-name-invalid\",\n `Cookie name ${JSON.stringify(declaration.name)} contains a character that a cookie name cannot hold. Use letters, digits, or the token characters that RFC 6265 allows.`,\n );\n }\n\n // Demiurge adds the prefix from the declared scope. A name that already holds\n // a prefix is reported, because a silent rename would change the cookie that\n // the application reads back.\n if (\n declaration.name.startsWith(\"__Host-\") ||\n declaration.name.startsWith(\"__Secure-\")\n ) {\n report(\n \"cookie-name-carries-prefix\",\n `Cookie name ${JSON.stringify(declaration.name)} already carries a prefix. Remove the prefix from name and declare scope ${JSON.stringify(scope === \"none\" ? \"host\" : scope)} instead.`,\n );\n }\n\n if (scope !== \"none\" && declaration.secure === false) {\n report(\n \"cookie-scope-requires-secure\",\n `Cookie ${name} uses scope ${JSON.stringify(scope)}, so it requires Secure. Remove secure: false, or declare scope \"none\" for a cookie that a browser must accept over plain HTTP.`,\n );\n }\n\n if (scope === \"host\" && declaration.domain !== undefined) {\n report(\n \"cookie-domain-not-allowed\",\n `Cookie ${name} uses scope \"host\", so it cannot carry a Domain attribute. Remove domain, or declare scope \"secure\" to share the cookie with subdomains.`,\n );\n }\n\n if (scope === \"host\" && declaration.path !== undefined && declaration.path !== \"/\") {\n report(\n \"cookie-path-not-allowed\",\n `Cookie ${name} uses scope \"host\", so it requires Path=/. Remove path, or declare scope \"secure\" for a cookie that a path must limit.`,\n );\n }\n\n if (declaration.sameSite === \"None\" && declaration.secure === false) {\n report(\n \"cookie-same-site-none-requires-secure\",\n `Cookie ${name} declares SameSite=None, so it requires Secure. Remove secure: false, or declare a SameSite policy of \"Lax\" or \"Strict\".`,\n );\n }\n\n if (\n declaration.maxAge !== undefined &&\n (!Number.isInteger(declaration.maxAge) || declaration.maxAge < 0)\n ) {\n report(\n \"cookie-max-age-invalid\",\n `Cookie ${name} declares maxAge ${JSON.stringify(declaration.maxAge)}. Use a whole number of seconds that is zero or greater.`,\n );\n }\n\n if (issues.length === 0) {\n const size = new TextEncoder().encode(serialize(declaration, scope, name)).length;\n\n if (size > maxCookieBytes) {\n report(\n \"cookie-too-large\",\n `Cookie ${name} serializes to ${size} bytes, and a browser drops a cookie above ${maxCookieBytes} bytes. Store the payload on the server and keep an identifier in the cookie.`,\n );\n }\n }\n\n return issues;\n}\n\n// A page reads a cookie only where the application chose `httpOnly: false`.\n// This helper computes the same prefixed name `createSecureCookie` wrote, so\n// browser code never hardcodes a `__Host-`/`__Secure-` prefix by hand.\n// Pass the same `SecureCookieDefinition` the route spread into\n// `createSecureCookie(...)`. A rename or a scope change in that declaration\n// then reaches both the write and the read. A bare name is also accepted for\n// a cookie with no shared definition. Returns `undefined` outside a browser\n// and for a cookie that is absent.\nexport function readSecureCookie(\n reference: SecureCookieDefinition | string,\n scope: CookieScope = \"host\",\n) {\n if (typeof document === \"undefined\") {\n return undefined;\n }\n\n const definition: SecureCookieDefinition =\n typeof reference === \"string\" ? { name: reference, scope } : reference;\n\n return parseCookieHeader(document.cookie).get(\n secureCookieName(definition.name, definition.scope ?? \"host\"),\n );\n}\n\nexport function createSecureCookie(declaration: SecureCookieDeclaration) {\n const issues = validateSecureCookie(declaration);\n\n if (issues.length > 0) {\n throw new Error(\n `Demiurge rejected a cookie declaration. ${issues.map((issue) => issue.message).join(\" \")}`,\n );\n }\n\n const scope = declaration.scope ?? \"host\";\n\n return serialize(declaration, scope, secureCookieName(declaration.name, scope));\n}\n\nfunction serialize(\n declaration: SecureCookieDeclaration,\n scope: CookieScope,\n name: string,\n) {\n // The defaults carry the safe answer. A session cookie stays out of page\n // script, stays on the origin that set it, and travels only over HTTPS. An\n // application opts out of one default at a time, and the opt-out stays\n // visible in the route source.\n const attributes = [`${name}=${encodeURIComponent(declaration.value)}`];\n const path = scope === \"host\" ? \"/\" : declaration.path ?? \"/\";\n\n attributes.push(`Path=${path}`);\n\n if (scope !== \"host\" && declaration.domain !== undefined) {\n attributes.push(`Domain=${declaration.domain}`);\n }\n\n if (declaration.expires) {\n attributes.push(`Expires=${declaration.expires.toUTCString()}`);\n }\n\n if (declaration.maxAge !== undefined) {\n attributes.push(`Max-Age=${declaration.maxAge}`);\n }\n\n attributes.push(`SameSite=${declaration.sameSite ?? \"Lax\"}`);\n\n // A JavaScript-readable cookie is the narrow exception. The double-submit\n // CSRF token is the one case that needs it, because page script must copy the\n // token into a request header.\n if (declaration.httpOnly ?? true) {\n attributes.push(\"HttpOnly\");\n }\n\n if (scope !== \"none\" || (declaration.secure ?? true)) {\n attributes.push(\"Secure\");\n }\n\n return attributes.join(\"; \");\n}\n","import {\n createSecureCookie,\n secureCookieName,\n type CookieSameSite,\n type CookieScope,\n} from \"./cookies\";\nimport { parseCookieHeader } from \"./csrf\";\nimport { isPlainObject } from \"../type-guards\";\nimport type { SessionData, SessionRecord } from \"./session-store\";\n\nconst defaultAbsoluteExpirationMs = 7 * 24 * 60 * 60 * 1000;\nconst defaultIdleExpirationMs = 24 * 60 * 60 * 1000;\nconst sessionIdentifierBytes = 32;\n\nexport type SessionCookieKey = {\n id: string;\n value: Uint8Array;\n};\n\nexport type SessionCookieDefinition = {\n domain?: string;\n httpOnly?: boolean;\n name?: string;\n path?: string;\n sameSite?: CookieSameSite;\n scope?: CookieScope;\n secure?: boolean;\n};\n\nexport type CookieSessionOptions = {\n absoluteExpirationMs?: number;\n cookie?: SessionCookieDefinition;\n idleExpirationMs?: false | number;\n keys: readonly SessionCookieKey[];\n now?: () => number;\n randomBytes?: (length: number) => Uint8Array;\n renewal?: boolean;\n};\n\nexport type CookieSessionCreateOptions = {\n absoluteExpirationMs?: number;\n idleExpirationMs?: false | number;\n};\n\nexport type CookieSession<TData extends SessionData> = {\n commit: () => Promise<readonly string[]>;\n create: (\n data: TData,\n options?: CookieSessionCreateOptions,\n ) => SessionRecord<TData>;\n destroy: () => void;\n get: () => SessionRecord<TData> | undefined;\n rotate: (data?: TData) => SessionRecord<TData>;\n update: (data: TData) => SessionRecord<TData>;\n};\n\nexport type CookieSessionManager<TData extends SessionData> = {\n cookieName: string;\n open: (request: Request) => Promise<CookieSession<TData>>;\n};\n\ntype DecodedSession<TData extends SessionData> = {\n currentKey: boolean;\n record: SessionRecord<TData>;\n};\n\ntype SessionCodec<TData extends SessionData> = {\n decode: (value: string) => Promise<DecodedSession<TData> | undefined>;\n encode: (record: SessionRecord<TData>) => Promise<string>;\n};\n\nexport function createSignedCookieSession<\n TData extends SessionData,\n>(options: CookieSessionOptions): CookieSessionManager<TData> {\n const resolved = resolveOptions(options);\n return createCookieSessionManager(resolved, signedCodec<TData>(resolved.keys));\n}\n\nexport function createEncryptedCookieSession<\n TData extends SessionData,\n>(options: CookieSessionOptions): CookieSessionManager<TData> {\n const resolved = resolveOptions(options);\n\n for (const key of resolved.keys) {\n if (key.value.byteLength !== 32) {\n throw new Error(\n `Demiurge encrypted cookie session key ${JSON.stringify(key.id)} must contain exactly 32 bytes for AES-256-GCM.`,\n );\n }\n }\n\n return createCookieSessionManager(\n resolved,\n encryptedCodec<TData>(resolved.keys, resolved.randomBytes),\n );\n}\n\ntype ResolvedOptions = {\n absoluteExpirationMs: number;\n cookie: Required<Pick<SessionCookieDefinition, \"name\">> &\n Omit<SessionCookieDefinition, \"name\">;\n idleExpirationMs: false | number;\n keys: readonly SessionCookieKey[];\n now: () => number;\n randomBytes: (length: number) => Uint8Array;\n renewal: boolean;\n};\n\nfunction createCookieSessionManager<TData extends SessionData>(\n options: ResolvedOptions,\n codec: SessionCodec<TData>,\n): CookieSessionManager<TData> {\n const cookieName = secureCookieName(\n options.cookie.name,\n options.cookie.scope ?? \"host\",\n );\n\n return {\n cookieName,\n async open(request) {\n const rawCookie = parseCookieHeader(request.headers.get(\"cookie\") ?? \"\")\n .get(cookieName);\n const now = options.now();\n const decoded = rawCookie ? await codec.decode(rawCookie) : undefined;\n let record = decoded?.record;\n let destroyCookie = Boolean(rawCookie && !decoded);\n let dirty = Boolean(decoded && !decoded.currentKey);\n\n if (record && isExpired(record, now)) {\n record = undefined;\n destroyCookie = true;\n dirty = false;\n } else if (\n record &&\n options.renewal &&\n options.idleExpirationMs !== false &&\n record.idleExpiresAt !== undefined &&\n record.idleExpiresAt - now <= options.idleExpirationMs / 4\n ) {\n record = {\n ...record,\n idleExpiresAt: Math.min(\n record.expiresAt,\n now + options.idleExpirationMs,\n ),\n version: record.version + 1,\n };\n dirty = true;\n }\n\n const requireRecord = () => {\n if (!record) {\n throw new Error(\n \"Demiurge cannot change a session that does not exist. Create the session first.\",\n );\n }\n\n return record;\n };\n\n const setRecord = (next: SessionRecord<TData>) => {\n record = cloneRecord(next);\n destroyCookie = false;\n dirty = true;\n return cloneRecord(next);\n };\n\n return {\n async commit() {\n if (destroyCookie) {\n return [destroyedCookie(options.cookie)];\n }\n\n if (!record || !dirty) {\n return [];\n }\n\n return [createSecureCookie({\n ...options.cookie,\n expires: new Date(record.expiresAt),\n value: await codec.encode(record),\n })];\n },\n create(data, createOptions = {}) {\n if (record) {\n throw new Error(\n \"Demiurge cannot create a session when one already exists. Rotate or update the current session.\",\n );\n }\n\n const createdAt = options.now();\n const absoluteExpirationMs = validateLifetime(\n \"absoluteExpirationMs\",\n createOptions.absoluteExpirationMs ?? options.absoluteExpirationMs,\n );\n const idleExpirationMs = createOptions.idleExpirationMs === undefined\n ? options.idleExpirationMs\n : validateIdleLifetime(createOptions.idleExpirationMs);\n const expiresAt = createdAt + absoluteExpirationMs;\n\n return setRecord({\n createdAt,\n data: cloneData(data),\n expiresAt,\n id: randomIdentifier(options.randomBytes),\n ...(idleExpirationMs === false\n ? {}\n : {\n idleExpiresAt: Math.min(\n expiresAt,\n createdAt + idleExpirationMs,\n ),\n }),\n version: 0,\n });\n },\n destroy() {\n record = undefined;\n destroyCookie = true;\n dirty = false;\n },\n get() {\n return record ? cloneRecord(record) : undefined;\n },\n rotate(data) {\n const current = requireRecord();\n return setRecord({\n ...current,\n data: data === undefined ? current.data : cloneData(data),\n id: randomIdentifier(options.randomBytes),\n version: current.version + 1,\n });\n },\n update(data) {\n const current = requireRecord();\n return setRecord({\n ...current,\n data: cloneData(data),\n version: current.version + 1,\n });\n },\n };\n },\n };\n}\n\nfunction resolveOptions(options: CookieSessionOptions): ResolvedOptions {\n const keys = validateKeys(options.keys);\n const absoluteExpirationMs = validateLifetime(\n \"absoluteExpirationMs\",\n options.absoluteExpirationMs ?? defaultAbsoluteExpirationMs,\n );\n const idleExpirationMs = validateIdleLifetime(\n options.idleExpirationMs ?? defaultIdleExpirationMs,\n );\n\n return {\n absoluteExpirationMs,\n cookie: { ...options.cookie, name: options.cookie?.name ?? \"session\" },\n idleExpirationMs,\n keys,\n now: options.now ?? Date.now,\n randomBytes: options.randomBytes ?? secureRandomBytes,\n renewal: options.renewal ?? true,\n };\n}\n\nfunction validateKeys(keys: readonly SessionCookieKey[]) {\n if (keys.length === 0) {\n throw new Error(\n \"Demiurge cookie sessions require at least one key. Put the current key first.\",\n );\n }\n\n const identifiers = new Set<string>();\n\n for (const key of keys) {\n if (!/^[A-Za-z0-9_-]+$/.test(key.id)) {\n throw new Error(\n \"Demiurge cookie session key identifiers can use only letters, digits, underscores, and hyphens.\",\n );\n }\n\n if (identifiers.has(key.id)) {\n throw new Error(\n `Demiurge cookie session key identifier ${JSON.stringify(key.id)} is not unique.`,\n );\n }\n\n if (key.value.byteLength < 32) {\n throw new Error(\n `Demiurge cookie session key ${JSON.stringify(key.id)} must contain at least 32 bytes.`,\n );\n }\n\n identifiers.add(key.id);\n }\n\n return [...keys];\n}\n\nfunction validateLifetime(name: string, value: number) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(\n `Demiurge cookie session ${name} must be a positive whole number of milliseconds.`,\n );\n }\n\n return value;\n}\n\nfunction validateIdleLifetime(value: false | number) {\n return value === false ? false : validateLifetime(\"idleExpirationMs\", value);\n}\n\nfunction signedCodec<TData extends SessionData>(\n keys: readonly SessionCookieKey[],\n): SessionCodec<TData> {\n return {\n async decode(value) {\n const parts = value.split(\".\");\n\n if (parts.length !== 4 || parts[0] !== \"s1\") {\n return undefined;\n }\n\n const keyIndex = keys.findIndex((key) => key.id === parts[1]);\n const key = keys[keyIndex];\n const payload = decodeBase64Url(parts[2]);\n const signature = decodeBase64Url(parts[3]);\n\n if (!key || !payload || !signature) {\n return undefined;\n }\n\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n toArrayBuffer(key.value),\n { hash: \"SHA-256\", name: \"HMAC\" },\n false,\n [\"verify\"],\n );\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n cryptoKey,\n toArrayBuffer(signature),\n toArrayBuffer(encodeText(`s1.${key.id}.${parts[2]}`)),\n );\n\n if (!valid) {\n return undefined;\n }\n\n const record = parseRecord<TData>(payload);\n return record ? { currentKey: keyIndex === 0, record } : undefined;\n },\n async encode(record) {\n const key = keys[0];\n const payload = encodeBase64Url(encodeText(JSON.stringify(record)));\n const unsigned = `s1.${key.id}.${payload}`;\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n toArrayBuffer(key.value),\n { hash: \"SHA-256\", name: \"HMAC\" },\n false,\n [\"sign\"],\n );\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n cryptoKey,\n toArrayBuffer(encodeText(unsigned)),\n );\n return `${unsigned}.${encodeBase64Url(new Uint8Array(signature))}`;\n },\n };\n}\n\nfunction encryptedCodec<TData extends SessionData>(\n keys: readonly SessionCookieKey[],\n randomBytes: (length: number) => Uint8Array,\n): SessionCodec<TData> {\n return {\n async decode(value) {\n const parts = value.split(\".\");\n\n if (parts.length !== 4 || parts[0] !== \"e1\") {\n return undefined;\n }\n\n const keyIndex = keys.findIndex((key) => key.id === parts[1]);\n const key = keys[keyIndex];\n const nonce = decodeBase64Url(parts[2]);\n const ciphertext = decodeBase64Url(parts[3]);\n\n if (!key || nonce?.byteLength !== 12 || !ciphertext) {\n return undefined;\n }\n\n try {\n const cryptoKey = await importEncryptionKey(key);\n const plaintext = await crypto.subtle.decrypt(\n {\n additionalData: toArrayBuffer(encodeText(`e1.${key.id}`)),\n iv: toArrayBuffer(nonce),\n name: \"AES-GCM\",\n },\n cryptoKey,\n toArrayBuffer(ciphertext),\n );\n const record = parseRecord<TData>(new Uint8Array(plaintext));\n return record ? { currentKey: keyIndex === 0, record } : undefined;\n } catch {\n return undefined;\n }\n },\n async encode(record) {\n const key = keys[0];\n const nonce = randomBytes(12);\n\n if (nonce.byteLength !== 12) {\n throw new Error(\n \"Demiurge cookie session randomBytes returned an incorrect byte count.\",\n );\n }\n\n const cryptoKey = await importEncryptionKey(key);\n const ciphertext = await crypto.subtle.encrypt(\n {\n additionalData: toArrayBuffer(encodeText(`e1.${key.id}`)),\n iv: toArrayBuffer(nonce),\n name: \"AES-GCM\",\n },\n cryptoKey,\n toArrayBuffer(encodeText(JSON.stringify(record))),\n );\n return `e1.${key.id}.${encodeBase64Url(nonce)}.${encodeBase64Url(new Uint8Array(ciphertext))}`;\n },\n };\n}\n\nasync function importEncryptionKey(key: SessionCookieKey) {\n return await crypto.subtle.importKey(\n \"raw\",\n toArrayBuffer(key.value),\n \"AES-GCM\",\n false,\n [\"decrypt\", \"encrypt\"],\n );\n}\n\nfunction parseRecord<TData extends SessionData>(\n bytes: Uint8Array,\n): SessionRecord<TData> | undefined {\n try {\n const value: unknown = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n\n if (\n !isPlainObject(value) ||\n !isSafeTimestamp(value.createdAt) ||\n !isSafeTimestamp(value.expiresAt) ||\n typeof value.id !== \"string\" ||\n !/^[A-Za-z0-9_-]{43}$/.test(value.id) ||\n !isNonNegativeInteger(value.version) ||\n (value.idleExpiresAt !== undefined &&\n !isSafeTimestamp(value.idleExpiresAt)) ||\n !isSessionData(value.data)\n ) {\n return undefined;\n }\n\n // TYPE-EVIDENCE: validation above proves each field and the recursive session data shape.\n return value as SessionRecord<TData>;\n } catch {\n return undefined;\n }\n}\n\nfunction isSafeTimestamp(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isSessionData(value: unknown): value is SessionData {\n if (\n value === null ||\n typeof value === \"boolean\" ||\n typeof value === \"string\"\n ) {\n return true;\n }\n\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n\n if (Array.isArray(value)) {\n return value.every(isSessionData);\n }\n\n return isPlainObject(value) && Object.values(value).every(isSessionData);\n}\n\nfunction isExpired(record: SessionRecord, now: number) {\n return record.expiresAt <= now ||\n (record.idleExpiresAt !== undefined && record.idleExpiresAt <= now);\n}\n\nfunction destroyedCookie(cookie: ResolvedOptions[\"cookie\"]) {\n return createSecureCookie({\n ...cookie,\n expires: new Date(0),\n maxAge: 0,\n value: \"\",\n });\n}\n\nfunction randomIdentifier(randomBytes: (length: number) => Uint8Array) {\n const bytes = randomBytes(sessionIdentifierBytes);\n\n if (bytes.byteLength !== sessionIdentifierBytes) {\n throw new Error(\n \"Demiurge cookie session randomBytes returned an incorrect byte count.\",\n );\n }\n\n return encodeBase64Url(bytes);\n}\n\nfunction secureRandomBytes(length: number) {\n return crypto.getRandomValues(new Uint8Array(length));\n}\n\nfunction cloneData<TData extends SessionData>(data: TData): TData {\n if (!isSessionData(data)) {\n throw new Error(\n \"Demiurge session data must contain only finite JSON values.\",\n );\n }\n\n return structuredClone(data);\n}\n\nfunction cloneRecord<TData extends SessionData>(record: SessionRecord<TData>) {\n return structuredClone(record);\n}\n\nfunction encodeText(value: string) {\n return new TextEncoder().encode(value);\n}\n\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n return Uint8Array.from(bytes).buffer;\n}\n\nfunction encodeBase64Url(bytes: Uint8Array) {\n let binary = \"\";\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/, \"\");\n}\n\nfunction decodeBase64Url(value: string) {\n if (!/^[A-Za-z0-9_-]+$/.test(value)) {\n return undefined;\n }\n\n try {\n const padding = \"=\".repeat((4 - value.length % 4) % 4);\n const binary = atob(value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\") + padding);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n } catch {\n return undefined;\n }\n}\n","import {\n createSecureCookie,\n secureCookieName,\n} from \"./cookies\";\nimport type {\n CookieSessionCreateOptions,\n SessionCookieDefinition,\n SessionCookieKey,\n} from \"./cookie-session\";\nimport { parseCookieHeader } from \"./csrf\";\nimport type {\n SessionData,\n SessionRecord,\n SessionStore,\n SessionStoreWriteResult,\n} from \"./session-store\";\n\nconst defaultAbsoluteExpirationMs = 7 * 24 * 60 * 60 * 1000;\nconst defaultIdleExpirationMs = 24 * 60 * 60 * 1000;\n\nexport type SessionManagerOptions<TData extends SessionData> = {\n absoluteExpirationMs?: number;\n cookie?: SessionCookieDefinition;\n idleExpirationMs?: false | number;\n keys: readonly SessionCookieKey[];\n now?: () => number;\n randomBytes?: (length: number) => Uint8Array;\n renewal?: boolean;\n store: SessionStore<TData>;\n};\n\nexport type ServerSession<TData extends SessionData> = {\n commit: () => Promise<readonly string[]>;\n create: (\n data: TData,\n options?: CookieSessionCreateOptions,\n ) => Promise<SessionRecord<TData>>;\n destroy: () => Promise<void>;\n get: () => SessionRecord<TData> | undefined;\n rotate: (data?: TData) => Promise<SessionRecord<TData>>;\n update: (data: TData) => Promise<SessionRecord<TData>>;\n};\n\nexport type SessionManager<TData extends SessionData> = {\n cookieName: string;\n open: (request: Request) => Promise<ServerSession<TData>>;\n};\n\nexport class SessionStoreConflictError extends Error {\n constructor(operation: string) {\n super(\n `Demiurge session ${operation} conflicted with another request. Load the current session before another lifecycle operation.`,\n );\n this.name = \"SessionStoreConflictError\";\n }\n}\n\nexport class SessionStoreUnavailableError extends Error {\n constructor(operation: string) {\n super(\n `Demiurge session ${operation} failed because the session store is unavailable.`,\n );\n this.name = \"SessionStoreUnavailableError\";\n }\n}\n\nexport function createSessionManager<TData extends SessionData>(\n input: SessionManagerOptions<TData>,\n): SessionManager<TData> {\n const options = resolveOptions(input);\n const cookieName = secureCookieName(\n options.cookie.name,\n options.cookie.scope ?? \"host\",\n );\n\n return {\n cookieName,\n async open(request) {\n const rawCookie = parseCookieHeader(request.headers.get(\"cookie\") ?? \"\")\n .get(cookieName);\n const decoded = rawCookie\n ? await verifyIdentifier(rawCookie, options.keys)\n : undefined;\n const now = options.now();\n let record = decoded\n ? await options.store.read(decoded.id, now)\n : undefined;\n let destroyCookie = Boolean(rawCookie && (!decoded || !record));\n let dirty = Boolean(record && decoded && !decoded.currentKey);\n\n if (\n record &&\n options.renewal &&\n options.idleExpirationMs !== false &&\n record.idleExpiresAt !== undefined &&\n record.idleExpiresAt - now <= options.idleExpirationMs / 4\n ) {\n const renewed = await options.store.update({\n ...withoutVersion(record),\n idleExpiresAt: Math.min(\n record.expiresAt,\n now + options.idleExpirationMs,\n ),\n }, record.version);\n\n if (renewed.status === \"stored\") {\n record = renewed.record;\n dirty = true;\n } else if (renewed.status === \"conflict\") {\n record = await options.store.read(record.id, now);\n destroyCookie = !record;\n } else {\n throw new SessionStoreUnavailableError(\"renewal\");\n }\n }\n\n const requireRecord = () => {\n if (!record) {\n throw new Error(\n \"Demiurge cannot change a session that does not exist. Create the session first.\",\n );\n }\n\n return record;\n };\n\n const accept = (\n result: SessionStoreWriteResult<TData>,\n operation: string,\n ) => {\n if (result.status === \"conflict\") {\n throw new SessionStoreConflictError(operation);\n }\n\n if (result.status === \"unavailable\") {\n throw new SessionStoreUnavailableError(operation);\n }\n\n record = cloneRecord(result.record);\n destroyCookie = false;\n dirty = true;\n return cloneRecord(result.record);\n };\n\n return {\n async commit() {\n if (destroyCookie) {\n return [destroyedCookie(options.cookie)];\n }\n\n if (!record || !dirty) {\n return [];\n }\n\n return [createSecureCookie({\n ...options.cookie,\n expires: new Date(record.expiresAt),\n value: await signIdentifier(record.id, options.keys[0]),\n })];\n },\n async create(data, createOptions = {}) {\n if (record) {\n throw new Error(\n \"Demiurge cannot create a session when one already exists. Rotate or update the current session.\",\n );\n }\n\n const createdAt = options.now();\n const absoluteExpirationMs = validateLifetime(\n \"absoluteExpirationMs\",\n createOptions.absoluteExpirationMs ?? options.absoluteExpirationMs,\n );\n const idleExpirationMs = createOptions.idleExpirationMs === undefined\n ? options.idleExpirationMs\n : validateIdleLifetime(createOptions.idleExpirationMs);\n const expiresAt = createdAt + absoluteExpirationMs;\n const candidate = {\n createdAt,\n data: cloneData(data),\n expiresAt,\n id: randomIdentifier(options.randomBytes),\n ...(idleExpirationMs === false\n ? {}\n : {\n idleExpiresAt: Math.min(\n expiresAt,\n createdAt + idleExpirationMs,\n ),\n }),\n };\n\n return accept(await options.store.create(candidate), \"creation\");\n },\n async destroy() {\n if (record) {\n await options.store.destroy(record.id);\n }\n\n record = undefined;\n destroyCookie = true;\n dirty = false;\n },\n get() {\n return record ? cloneRecord(record) : undefined;\n },\n async rotate(data) {\n const current = requireRecord();\n const candidate = {\n ...withoutVersion(current),\n data: data === undefined ? current.data : cloneData(data),\n id: randomIdentifier(options.randomBytes),\n };\n return accept(\n await options.store.rotate(current.id, candidate, current.version),\n \"rotation\",\n );\n },\n async update(data) {\n const current = requireRecord();\n return accept(\n await options.store.update({\n ...withoutVersion(current),\n data: cloneData(data),\n }, current.version),\n \"update\",\n );\n },\n };\n },\n };\n}\n\ntype ResolvedOptions<TData extends SessionData> = {\n absoluteExpirationMs: number;\n cookie: Required<Pick<SessionCookieDefinition, \"name\">> &\n Omit<SessionCookieDefinition, \"name\">;\n idleExpirationMs: false | number;\n keys: readonly SessionCookieKey[];\n now: () => number;\n randomBytes: (length: number) => Uint8Array;\n renewal: boolean;\n store: SessionStore<TData>;\n};\n\nfunction resolveOptions<TData extends SessionData>(\n input: SessionManagerOptions<TData>,\n): ResolvedOptions<TData> {\n if (!input.store || typeof input.store.read !== \"function\") {\n throw new Error(\n \"Demiurge session manager requires a SessionStore implementation.\",\n );\n }\n\n const keys = validateKeys(input.keys);\n return {\n absoluteExpirationMs: validateLifetime(\n \"absoluteExpirationMs\",\n input.absoluteExpirationMs ?? defaultAbsoluteExpirationMs,\n ),\n cookie: { ...input.cookie, name: input.cookie?.name ?? \"session\" },\n idleExpirationMs: validateIdleLifetime(\n input.idleExpirationMs ?? defaultIdleExpirationMs,\n ),\n keys,\n now: input.now ?? Date.now,\n randomBytes: input.randomBytes ?? secureRandomBytes,\n renewal: input.renewal ?? true,\n store: input.store,\n };\n}\n\nfunction validateKeys(keys: readonly SessionCookieKey[]) {\n if (keys.length === 0) {\n throw new Error(\n \"Demiurge session manager requires at least one key. Put the current key first.\",\n );\n }\n\n const identifiers = new Set<string>();\n\n for (const key of keys) {\n if (!/^[A-Za-z0-9_-]+$/.test(key.id) || identifiers.has(key.id)) {\n throw new Error(\n \"Demiurge session manager key identifiers must be unique token values.\",\n );\n }\n\n if (key.value.byteLength < 32) {\n throw new Error(\n `Demiurge session manager key ${JSON.stringify(key.id)} must contain at least 32 bytes.`,\n );\n }\n\n identifiers.add(key.id);\n }\n\n return [...keys];\n}\n\nasync function signIdentifier(id: string, key: SessionCookieKey) {\n const unsigned = `i1.${key.id}.${id}`;\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n toArrayBuffer(key.value),\n { hash: \"SHA-256\", name: \"HMAC\" },\n false,\n [\"sign\"],\n );\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n cryptoKey,\n toArrayBuffer(new TextEncoder().encode(unsigned)),\n );\n return `${unsigned}.${encodeBase64Url(new Uint8Array(signature))}`;\n}\n\nasync function verifyIdentifier(\n value: string,\n keys: readonly SessionCookieKey[],\n) {\n const parts = value.split(\".\");\n\n if (\n parts.length !== 4 ||\n parts[0] !== \"i1\" ||\n !/^[A-Za-z0-9_-]{43}$/.test(parts[2])\n ) {\n return undefined;\n }\n\n const keyIndex = keys.findIndex((key) => key.id === parts[1]);\n const key = keys[keyIndex];\n const signature = decodeBase64Url(parts[3]);\n\n if (!key || !signature) {\n return undefined;\n }\n\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n toArrayBuffer(key.value),\n { hash: \"SHA-256\", name: \"HMAC\" },\n false,\n [\"verify\"],\n );\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n cryptoKey,\n toArrayBuffer(signature),\n toArrayBuffer(new TextEncoder().encode(parts.slice(0, 3).join(\".\"))),\n );\n return valid\n ? { currentKey: keyIndex === 0, id: parts[2] }\n : undefined;\n}\n\nfunction withoutVersion<TData extends SessionData>(record: SessionRecord<TData>) {\n const { version: _version, ...candidate } = record;\n return candidate;\n}\n\nfunction destroyedCookie(cookie: ResolvedOptions<SessionData>[\"cookie\"]) {\n return createSecureCookie({\n ...cookie,\n expires: new Date(0),\n maxAge: 0,\n value: \"\",\n });\n}\n\nfunction validateLifetime(name: string, value: number) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(\n `Demiurge session manager ${name} must be a positive whole number of milliseconds.`,\n );\n }\n\n return value;\n}\n\nfunction validateIdleLifetime(value: false | number) {\n return value === false ? false : validateLifetime(\"idleExpirationMs\", value);\n}\n\nfunction randomIdentifier(randomBytes: (length: number) => Uint8Array) {\n const bytes = randomBytes(32);\n\n if (bytes.byteLength !== 32) {\n throw new Error(\n \"Demiurge session manager randomBytes returned an incorrect byte count.\",\n );\n }\n\n return encodeBase64Url(bytes);\n}\n\nfunction secureRandomBytes(length: number) {\n return crypto.getRandomValues(new Uint8Array(length));\n}\n\nfunction cloneData<TData extends SessionData>(data: TData): TData {\n if (!isSessionData(data)) {\n throw new Error(\n \"Demiurge session data must contain only finite JSON values.\",\n );\n }\n\n return structuredClone(data);\n}\n\nfunction isSessionData(value: unknown): value is SessionData {\n if (\n value === null ||\n typeof value === \"boolean\" ||\n typeof value === \"string\"\n ) {\n return true;\n }\n\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n\n if (Array.isArray(value)) {\n return value.every(isSessionData);\n }\n\n return typeof value === \"object\" && value !== null &&\n Object.values(value).every(isSessionData);\n}\n\nfunction cloneRecord<TData extends SessionData>(record: SessionRecord<TData>) {\n return structuredClone(record);\n}\n\nfunction encodeBase64Url(bytes: Uint8Array) {\n let binary = \"\";\n\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n\n return btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/, \"\");\n}\n\nfunction decodeBase64Url(value: string) {\n if (!/^[A-Za-z0-9_-]+$/.test(value)) {\n return undefined;\n }\n\n try {\n const padding = \"=\".repeat((4 - value.length % 4) % 4);\n const binary = atob(value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\") + padding);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n } catch {\n return undefined;\n }\n}\n\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n return Uint8Array.from(bytes).buffer;\n}\n","import {\n limitRequestBody,\n parseBodySize,\n RequestBodyTooLargeError,\n} from \"./request\";\nimport { isObjectLike } from \"../type-guards\";\n\ntype MaybePromise<T> = Promise<T> | T;\n\nexport type SecurityReportPayload = unknown;\n\nexport type SecurityReportHandlerOptions = {\n maxBodySize?: number | `${number}${\"b\" | \"gb\" | \"kb\" | \"mb\"}`;\n onReport?: (\n report: SecurityReportPayload,\n context: SecurityReportContext,\n ) => MaybePromise<void>;\n};\n\nexport type SecurityReportContext = {\n index: number;\n request: Request;\n};\n\nexport function createSecurityReportHandler(\n options: SecurityReportHandlerOptions = {},\n) {\n return async function handleSecurityReport(request: Request) {\n if (request.method.toUpperCase() !== \"POST\") {\n return new Response(null, {\n headers: {\n allow: \"POST\",\n },\n status: 405,\n });\n }\n\n const contentTypeResponse = enforceReportContentType(request);\n\n if (contentTypeResponse) {\n return contentTypeResponse;\n }\n\n const bodySizeResponse = enforceReportBodySize(options, request);\n\n if (bodySizeResponse) {\n return bodySizeResponse;\n }\n\n if (options.maxBodySize !== undefined) {\n request = limitRequestBody({ maxBodySize: options.maxBodySize }, request);\n }\n\n let payload: unknown;\n\n try {\n payload = await request.json();\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return new Response(\"Security report body too large.\", { status: 413 });\n }\n\n return new Response(\"Invalid security report JSON.\", {\n status: 400,\n });\n }\n\n const reports = normalizeSecurityReports(payload);\n\n for (let index = 0; index < reports.length; index += 1) {\n await options.onReport?.(reports[index], {\n index,\n request,\n });\n }\n\n return new Response(null, {\n status: 204,\n });\n };\n}\n\nconst supportedReportContentTypes = new Set([\n \"application/csp-report\",\n \"application/reports+json\",\n]);\n\nfunction enforceReportContentType(request: Request) {\n const value = request.headers.get(\"content-type\");\n\n // Keep direct/programmatic calls compatible. Browser-generated reports\n // always send one of the two media types below.\n if (!value) {\n return null;\n }\n\n const mediaType = value.split(\";\", 1)[0]?.trim().toLowerCase();\n\n if (mediaType && supportedReportContentTypes.has(mediaType)) {\n return null;\n }\n\n return new Response(\"Unsupported security report Content-Type.\", {\n status: 415,\n });\n}\n\nfunction enforceReportBodySize(\n options: SecurityReportHandlerOptions,\n request: Request,\n) {\n if (options.maxBodySize === undefined) {\n return null;\n }\n\n const contentLength = request.headers.get(\"content-length\");\n\n if (!contentLength) {\n return null;\n }\n\n if (!/^\\d+$/.test(contentLength)) {\n return new Response(\"Invalid Content-Length.\", {\n status: 400,\n });\n }\n\n const declaredSize = Number(contentLength);\n\n if (!Number.isSafeInteger(declaredSize)) {\n return new Response(\"Invalid Content-Length.\", {\n status: 400,\n });\n }\n\n if (declaredSize > parseBodySize(options.maxBodySize)) {\n return new Response(\"Security report body too large.\", {\n status: 413,\n });\n }\n\n return null;\n}\n\nfunction normalizeSecurityReports(payload: unknown) {\n if (Array.isArray(payload)) {\n return payload;\n }\n\n if (isObjectLike(payload) && \"csp-report\" in payload) {\n return [payload[\"csp-report\"]];\n }\n\n return [payload];\n}\n","import { parseBodySize } from \"./request\";\nimport type { RequestSecurityPolicy } from \"./types\";\n\nexport type UploadFilePolicy = {\n maxSize?: RequestSecurityPolicy[\"maxBodySize\"];\n required?: boolean;\n types?: readonly string[];\n};\n\nexport type UploadPolicy = {\n files: Record<string, UploadFilePolicy>;\n maxTotalSize?: RequestSecurityPolicy[\"maxBodySize\"];\n};\n\nexport type UploadValidationIssue = {\n code:\n | \"file-missing\"\n | \"file-too-large\"\n | \"file-type-not-allowed\"\n | \"total-upload-too-large\";\n field: string;\n message: string;\n};\n\nexport type UploadValidationResult = {\n files: Record<string, File[]>;\n issues: UploadValidationIssue[];\n ok: boolean;\n totalSize: number;\n};\n\nexport function validateUploads(\n formData: FormData,\n policy: UploadPolicy,\n): UploadValidationResult {\n const files: Record<string, File[]> = {};\n const issues: UploadValidationIssue[] = [];\n let totalSize = 0;\n\n for (const [field, filePolicy] of Object.entries(policy.files)) {\n const fieldFiles = formData.getAll(field).filter(isFile);\n files[field] = fieldFiles;\n\n if (filePolicy.required && fieldFiles.length === 0) {\n issues.push({\n code: \"file-missing\",\n field,\n message: `Upload field ${field} requires at least one file.`,\n });\n }\n\n for (const file of fieldFiles) {\n totalSize += file.size;\n validateFile(field, file, filePolicy, issues);\n }\n }\n\n if (\n policy.maxTotalSize !== undefined &&\n totalSize > parseBodySize(policy.maxTotalSize)\n ) {\n issues.push({\n code: \"total-upload-too-large\",\n field: \"*\",\n message: `Uploaded files exceed the maximum total size of ${policy.maxTotalSize}.`,\n });\n }\n\n return {\n files,\n issues,\n ok: issues.length === 0,\n totalSize,\n };\n}\n\nfunction validateFile(\n field: string,\n file: File,\n policy: UploadFilePolicy,\n issues: UploadValidationIssue[],\n) {\n if (policy.maxSize !== undefined && file.size > parseBodySize(policy.maxSize)) {\n issues.push({\n code: \"file-too-large\",\n field,\n message: `Upload field ${field} contains ${file.name || \"a file\"} larger than ${policy.maxSize}.`,\n });\n }\n\n if (policy.types?.length && !isAllowedFileType(file.type, policy.types)) {\n issues.push({\n code: \"file-type-not-allowed\",\n field,\n message: `Upload field ${field} contains ${file.name || \"a file\"} with disallowed type ${file.type || \"unknown\"}.`,\n });\n }\n}\n\nfunction isAllowedFileType(type: string, allowedTypes: readonly string[]) {\n return allowedTypes.some((allowedType) => {\n if (allowedType.endsWith(\"/*\")) {\n return type.startsWith(allowedType.slice(0, -1));\n }\n\n return type === allowedType;\n });\n}\n\nfunction isFile(value: FormDataEntryValue): value is File {\n return value instanceof File;\n}\n","export type WebSocketOriginPolicy = {\n allowMissingOrigin?: boolean;\n origins: \"same-origin\" | readonly string[];\n};\n\nexport type WebSocketOriginCheck = {\n allowed: boolean;\n expected: \"same-origin\" | readonly string[];\n origin: string | null;\n reason?: \"invalid-origin\" | \"missing-origin\" | \"origin-not-allowed\";\n};\n\nexport function checkWebSocketOrigin(\n policy: WebSocketOriginPolicy,\n request: Request,\n): WebSocketOriginCheck {\n const origin = request.headers.get(\"origin\");\n\n if (!origin) {\n return {\n allowed: Boolean(policy.allowMissingOrigin),\n expected: policy.origins,\n origin,\n reason: policy.allowMissingOrigin ? undefined : \"missing-origin\",\n };\n }\n\n const normalizedOrigin = normalizeOrigin(origin);\n\n if (!normalizedOrigin) {\n return {\n allowed: false,\n expected: policy.origins,\n origin,\n reason: \"invalid-origin\",\n };\n }\n\n const allowed = isAllowedOrigin(policy, normalizedOrigin, request);\n\n return {\n allowed,\n expected: policy.origins,\n origin: normalizedOrigin,\n reason: allowed ? undefined : \"origin-not-allowed\",\n };\n}\n\nexport function enforceWebSocketOrigin(\n policy: WebSocketOriginPolicy | undefined,\n request: Request,\n) {\n if (!policy) {\n return null;\n }\n\n const check = checkWebSocketOrigin(policy, request);\n\n if (check.allowed) {\n return null;\n }\n\n return new Response(\"WebSocket origin not allowed.\", {\n status: 403,\n });\n}\n\nfunction isAllowedOrigin(\n policy: WebSocketOriginPolicy,\n origin: string,\n request: Request,\n) {\n if (policy.origins === \"same-origin\") {\n return origin === new URL(request.url).origin;\n }\n\n return policy.origins.some((allowedOrigin) =>\n originMatches(allowedOrigin, origin),\n );\n}\n\nfunction originMatches(allowedOrigin: string, actualOrigin: string) {\n if (allowedOrigin === \"null\") {\n return actualOrigin === \"null\";\n }\n\n return normalizeOrigin(allowedOrigin) === actualOrigin;\n}\n\nfunction normalizeOrigin(origin: string) {\n if (origin === \"null\") {\n return origin;\n }\n\n try {\n // Origin is a serialized origin, not an arbitrary URL. `new URL()` alone\n // would silently discard a path, query, fragment, or credentials and could\n // turn a malformed attacker-supplied header into an allowed origin.\n if (origin !== origin.trim()) {\n return null;\n }\n\n const schemeSeparator = origin.indexOf(\"://\");\n\n if (schemeSeparator === -1) {\n return null;\n }\n\n const authority = origin.slice(schemeSeparator + 3);\n\n if (!authority || /[/?#]/.test(authority)) {\n return null;\n }\n\n const url = new URL(origin);\n\n if (\n (url.protocol !== \"http:\" && url.protocol !== \"https:\") ||\n url.username ||\n url.password\n ) {\n return null;\n }\n\n return url.origin;\n } catch {\n return null;\n }\n}\n","import {\n createContext,\n createElement,\n useCallback,\n useContext,\n useMemo,\n useRef,\n type ComponentPropsWithRef,\n type ElementType,\n type ForwardedRef,\n type RefCallback,\n type ReactNode,\n} from \"react\";\n\nexport type RouteFocusBoundaryElement = Element & {\n focus?: (options?: FocusOptions) => void;\n};\n\nexport type RouteFocusRegistration = {\n register(element: RouteFocusBoundaryElement): () => void;\n focus(): boolean;\n};\n\nexport const RouteFocusContext = createContext<RouteFocusRegistration>({\n register: () => () => undefined,\n focus: () => false,\n});\n\nexport type RouteFocusBoundaryProps<\n TAs extends ElementType = \"div\",\n> = {\n as?: TAs;\n} & Omit<ComponentPropsWithRef<TAs>, \"as\" | \"tabIndex\">;\n\nexport function useRouteFocusBoundary<\n TElement extends RouteFocusBoundaryElement = RouteFocusBoundaryElement,\n>() {\n const registration = useContext(RouteFocusContext);\n const cleanup = useRef<(() => void) | undefined>(undefined);\n const ref = useCallback<RefCallback<TElement>>((element) => {\n cleanup.current?.();\n cleanup.current = undefined;\n\n if (element) {\n cleanup.current = registration.register(element);\n }\n }, [registration]);\n\n return useMemo(() => ({\n ref,\n tabIndex: -1 as const,\n }), [ref]);\n}\n\nexport function RouteFocusBoundary<\n TAs extends ElementType = \"div\",\n>(props: RouteFocusBoundaryProps<TAs> & { children?: ReactNode }) {\n const { as, children, ref, ...elementProps } = props;\n const boundary = useRouteFocusBoundary();\n const composedRef = useCallback((element: RouteFocusBoundaryElement | null) => {\n if (element) {\n boundary.ref(element);\n assignRef(ref, element);\n return;\n }\n\n // The application ref must clear before the router removes registration.\n assignRef(ref, null);\n boundary.ref(null);\n }, [boundary.ref, ref]);\n\n return createElement(as ?? \"div\", {\n ...elementProps,\n ...boundary,\n ref: composedRef,\n children,\n });\n}\n\nfunction assignRef<T>(ref: ForwardedRef<T> | undefined, value: T | null) {\n if (typeof ref === \"function\") {\n ref(value);\n } else if (ref) {\n ref.current = value;\n }\n}\n","import {\n MUTATION_REQUEST_HEADER,\n MUTATION_REQUEST_VALUE,\n MUTATION_RESPONSE_MEDIA_TYPE,\n type MutationValidation,\n type MutationValidationIssue,\n} from \"../route\";\nimport {\n href,\n type MutationDataFor,\n type MutationFieldsFor,\n type MutationMethodFor,\n type MutationRoute,\n type PathValue,\n type PathVarsFor,\n type RoutePathVars,\n} from \"../routing\";\nimport { useActionState, useMemo } from \"react\";\nimport { isPlainObject } from \"../type-guards\";\n\nconst mutationFormActionMetadata = Symbol(\"Demiurge mutation form action\");\ndeclare const mutationFormActionResult: unique symbol;\n\nexport type MutationResult<TData = unknown, TField extends string = string> =\n | { version: 1; status: \"success\"; data?: TData; revalidate?: boolean }\n | { version: 1; status: \"invalid\"; validation: MutationValidation<TField> }\n | { version: 1; status: \"redirect\"; location: string; history: \"push\" | \"replace\" }\n | { version: 1; status: \"failed\"; message?: string };\n\nexport type MutationAction<TData = unknown, TField extends string = string> = (\n previousState: MutationResult<TData, TField> | undefined,\n formData: FormData,\n) => Promise<MutationResult<TData, TField>>;\n\nexport type MutationFormAction<TData = unknown, TField extends string = string> =\n ((formData: FormData) => void) & {\n readonly [mutationFormActionMetadata]: {\n method: \"POST\";\n url: string;\n };\n readonly [mutationFormActionResult]?: MutationResult<TData, TField>;\n };\n\ntype MutationActionPath<TRoute extends MutationRoute> =\n TRoute extends keyof RoutePathVars & string\n ? keyof PathVarsFor<TRoute> extends never\n ? { path?: never }\n : { path: PathVarsFor<TRoute> }\n : { path?: Record<string, PathValue> };\n\nexport type MutationActionOptions<\n TRoute extends MutationRoute,\n TMethod extends MutationMethodFor<TRoute> = MutationMethodFor<TRoute>,\n> = {\n method: TMethod;\n route: TRoute;\n} & MutationActionPath<TRoute>;\n\ntype MutationRouter = {\n redirect(location: string, history: \"push\" | \"replace\", controller: AbortController): void;\n refresh(): Promise<void>;\n};\n\ntype MutationInvocation<TData, TField extends string> = {\n controller: AbortController;\n promise: Promise<MutationResult<TData, TField>>;\n};\n\nlet mutationRouter: MutationRouter | undefined;\nconst pendingMutationControllers = new Set<AbortController>();\n\nexport function registerMutationRouter(router: MutationRouter) {\n mutationRouter = router;\n return () => {\n if (mutationRouter === router) mutationRouter = undefined;\n };\n}\n\nexport function abortMutationActions(except?: AbortController) {\n for (const controller of pendingMutationControllers) {\n if (controller !== except) controller.abort();\n }\n}\n\nexport function createMutationAction<\n TData = never,\n const TRoute extends MutationRoute = MutationRoute,\n const TMethod extends MutationMethodFor<TRoute> = MutationMethodFor<TRoute>,\n>(options: MutationActionOptions<TRoute, TMethod>): MutationAction<\n [TData] extends [never] ? MutationDataFor<TRoute, TMethod> : TData,\n MutationFieldsFor<TRoute, TMethod>\n> {\n type ResultData = [TData] extends [never]\n ? MutationDataFor<TRoute, TMethod>\n : TData;\n type ResultField = MutationFieldsFor<TRoute, TMethod>;\n let current: MutationInvocation<ResultData, ResultField> | undefined;\n\n return (previousState, formData) => {\n current?.controller.abort();\n const controller = new AbortController();\n const invocation: MutationInvocation<ResultData, ResultField> = {\n controller,\n // TYPE-EVIDENCE: the function assigns the promise before it exposes the invocation.\n promise: undefined as never,\n };\n pendingMutationControllers.add(controller);\n\n // TYPE-EVIDENCE: MutationActionPath applies the same generated path requirement as LinkTo.\n const url = href({\n to: options.route,\n ...(options.path === undefined ? {} : { path: options.path }),\n } as never);\n const request = submitMutation<ResultData, ResultField>({\n body: formData,\n method: options.method,\n signal: controller.signal,\n url,\n });\n\n invocation.promise = request.then(async (result) => {\n if (current !== invocation) return await current!.promise;\n if (result.status === \"redirect\") {\n const destination = validateMutationRedirect(result.location);\n if (!destination) return mutationFailure(\"The mutation returned an unsafe redirect.\");\n abortMutationActions(controller);\n mutationRouter?.redirect(destination, result.history, controller);\n } else if (result.status === \"success\" && result.revalidate) {\n await mutationRouter?.refresh();\n }\n if (controller.signal.aborted) {\n return previousState ?? mutationFailure(\"The mutation was cancelled.\");\n }\n return current === invocation ? result : await current!.promise;\n }).catch(async (error: unknown) => {\n if (current !== invocation) return await current!.promise;\n if (controller.signal.aborted && previousState) return previousState;\n if (controller.signal.aborted) return mutationFailure(\"The mutation was cancelled.\");\n throw error;\n }).finally(() => {\n pendingMutationControllers.delete(controller);\n });\n current = invocation;\n return invocation.promise;\n };\n}\n\nexport function useMutationAction<\n TData = never,\n const TRoute extends MutationRoute = MutationRoute,\n const TMethod extends MutationMethodFor<TRoute> = MutationMethodFor<TRoute>,\n>(\n options: MutationActionOptions<TRoute, TMethod> & { method: TMethod & \"POST\" },\n initialState?: MutationResult<\n [TData] extends [never] ? MutationDataFor<TRoute, TMethod> : TData,\n MutationFieldsFor<TRoute, TMethod>\n >,\n) {\n type ResultData = [TData] extends [never]\n ? MutationDataFor<TRoute, TMethod>\n : TData;\n type ResultField = MutationFieldsFor<TRoute, TMethod>;\n // TYPE-EVIDENCE: MutationActionPath applies the generated path requirement that href expects.\n const url = href({\n to: options.route,\n ...(options.path === undefined ? {} : { path: options.path }),\n } as never);\n const mutation = useMemo(\n () => {\n const generated = createMutationAction(options);\n // TYPE-EVIDENCE: ResultData either keeps the generated data type or applies the caller's explicit data refinement.\n return generated as MutationAction<ResultData, ResultField>;\n },\n [options.method, url],\n );\n const [state, dispatch, pending] = useActionState<\n MutationResult<ResultData, ResultField> | undefined,\n FormData\n >(mutation, initialState);\n const action = useMemo(() => {\n const branded = (formData: FormData) => dispatch(formData);\n Object.defineProperty(branded, mutationFormActionMetadata, {\n value: { method: \"POST\", url },\n });\n // TYPE-EVIDENCE: the wrapper has the FormData dispatch signature and the metadata property required by MutationFormAction.\n return branded as MutationFormAction<ResultData, ResultField>;\n }, [dispatch, url]);\n\n return [state, action, pending] as const;\n}\n\nexport function mutationFormActionDetails(action: MutationFormAction) {\n return action[mutationFormActionMetadata];\n}\n\nexport async function submitMutation<TData = unknown, TField extends string = string>(options: {\n body: BodyInit;\n contentType?: string;\n method: string;\n signal: AbortSignal;\n url: string;\n}) {\n const { result } = await performMutationRequest<TData, TField>(options);\n if (!result) {\n throw new Error(\"Demiurge expected a versioned mutation result.\");\n }\n return result;\n}\n\nexport async function performMutationRequest<TData = unknown, TField extends string = string>(options: {\n body: BodyInit;\n contentType?: string;\n method: string;\n signal: AbortSignal;\n url: string;\n}) {\n const response = await fetch(options.url, {\n body: options.body,\n credentials: \"same-origin\",\n headers: {\n accept: MUTATION_RESPONSE_MEDIA_TYPE,\n [MUTATION_REQUEST_HEADER]: MUTATION_REQUEST_VALUE,\n ...(options.contentType ? { \"content-type\": options.contentType } : {}),\n },\n method: options.method,\n redirect: \"manual\",\n signal: options.signal,\n });\n return { response, result: await readMutationResult<TData, TField>(response) };\n}\n\nexport async function readMutationResult<TData = unknown, TField extends string = string>(\n response: Response,\n): Promise<MutationResult<TData, TField> | undefined> {\n const mediaType = response.headers.get(\"content-type\");\n if (!mediaType) return undefined;\n const [type, ...parameters] = mediaType?.split(\";\").map((value) => value.trim().toLowerCase()) ?? [];\n const mutationType = MUTATION_RESPONSE_MEDIA_TYPE.split(\";\")[0];\n if (type !== mutationType) return undefined;\n if (parameters.length !== 1 || parameters[0] !== \"v=1\") {\n throw new Error(\"Demiurge received a malformed versioned mutation result.\");\n }\n\n let value: unknown;\n try {\n value = await response.clone().json();\n } catch {\n throw new Error(\"Demiurge received a malformed versioned mutation result.\");\n }\n if (!isPlainObject(value) || value.version !== 1 || typeof value.status !== \"string\") {\n throw new Error(\"Demiurge received a malformed versioned mutation result.\");\n }\n if (value.status === \"success\") {\n if (!hasOnlyKeys(value, [\"data\", \"revalidate\", \"status\", \"version\"]) ||\n (value.revalidate !== undefined && typeof value.revalidate !== \"boolean\") ||\n (\"data\" in value && !isJsonValue(value.data))) throw malformedResult();\n // TYPE-EVIDENCE: TData describes application-owned JSON data. The parser validates the complete value before this assertion.\n return { version: 1, status: \"success\", ...(value.data === undefined ? {} : { data: value.data as TData }), ...(value.revalidate === undefined ? {} : { revalidate: value.revalidate }) };\n }\n if (value.status === \"invalid\") {\n if (!hasOnlyKeys(value, [\"status\", \"validation\", \"version\"]) ||\n !isMutationValidation(value.validation)) throw malformedResult();\n // TYPE-EVIDENCE: the parser validates every validation issue and path. TField supplies the application field-name refinement.\n return { version: 1, status: \"invalid\", validation: value.validation as MutationValidation<TField> };\n }\n if (value.status === \"failed\") {\n if (!hasOnlyKeys(value, [\"message\", \"status\", \"version\"]) ||\n (value.message !== undefined && typeof value.message !== \"string\")) throw malformedResult();\n return { version: 1, status: \"failed\", ...(value.message === undefined ? {} : { message: value.message }) };\n }\n if (value.status === \"redirect\" && typeof value.location === \"string\" &&\n (value.history === \"push\" || value.history === \"replace\") &&\n hasOnlyKeys(value, [\"history\", \"location\", \"status\", \"version\"])) {\n return { version: 1, status: \"redirect\", location: value.location, history: value.history };\n }\n throw malformedResult();\n}\n\nexport function validateMutationRedirect(location: string) {\n try {\n const destination = new URL(location, window.location.href);\n if (destination.protocol !== window.location.protocol) return undefined;\n if (destination.origin !== window.location.origin) return undefined;\n if (destination.username || destination.password) return undefined;\n return `${destination.pathname}${destination.search}${destination.hash}`;\n } catch {\n return undefined;\n }\n}\n\nfunction mutationFailure(message: string): MutationResult<never, never> {\n return { version: 1, status: \"failed\", message };\n}\n\nfunction malformedResult() {\n return new Error(\"Demiurge received a malformed mutation result.\");\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]) {\n return Object.keys(value).every((key) => keys.includes(key));\n}\n\nfunction isMutationValidation(value: unknown): value is MutationValidation {\n return isPlainObject(value) && hasOnlyKeys(value, [\"issues\"]) &&\n Array.isArray(value.issues) && value.issues.every(isMutationValidationIssue);\n}\n\nfunction isMutationValidationIssue(value: unknown): value is MutationValidationIssue {\n return isPlainObject(value) && hasOnlyKeys(value, [\"code\", \"message\", \"path\"]) &&\n typeof value.code === \"string\" && typeof value.message === \"string\" &&\n Array.isArray(value.path) &&\n (value.path.length === 0 || typeof value.path[0] === \"string\") &&\n value.path.every((part) => typeof part === \"string\" || typeof part === \"number\");\n}\n\nfunction isJsonValue(value: unknown): boolean {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(isJsonValue);\n return isPlainObject(value) && Object.values(value).every(isJsonValue);\n}\n","import {\n AnchorHTMLAttributes,\n ButtonHTMLAttributes,\n Component,\n ComponentType,\n ForwardedRef,\n FormEvent,\n FormHTMLAttributes,\n Fragment,\n MouseEvent,\n ReactNode,\n createContext,\n createElement,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useId,\n useRef,\n useState,\n} from \"react\";\nimport {\n RouteFocusContext,\n type RouteFocusBoundaryElement,\n} from \"./focus\";\nimport {\n applyNavigationDocument,\n announceNavigation as updateNavigationStatus,\n ensureNavigationStatusRegion,\n HYDRATION_FALLBACK_ATTRIBUTE,\n HYDRATION_ROOT_ATTRIBUTE,\n readInitialRouteData,\n startDeferredScripts,\n type InitialRouteData,\n} from \"../document\";\nimport {\n HTTP_ERROR_STATUSES,\n httpError,\n isHttpError,\n type NotFoundProps,\n type RouteErrorProps,\n type RouteImporter,\n} from \"../route\";\nimport {\n createRouteManifest,\n loadErrorFallback,\n loadLoadingFallback,\n loadPageRoute,\n NAVIGATION_DATA_HEADER,\n NAVIGATION_DATA_REQUEST,\n NAVIGATION_DATA_RESPONSE,\n NAVIGATION_ERROR_RESPONSE,\n NAVIGATION_NOT_FOUND_RESPONSE,\n type PendingRouteMatch,\n} from \"../router\";\nimport { BuiltInNotFound } from \"../server/fallbacks\";\nimport { applicationPathname, href, localizeHref, resolveLocale, type AppHref, type AppLocale, type LinkTarget, type LinkTo, type LocaleConfiguration } from \"../routing\";\nimport {\n abortMutationActions,\n mutationFormActionDetails,\n performMutationRequest,\n registerMutationRouter,\n type MutationFormAction,\n type MutationResult,\n validateMutationRedirect,\n} from \"./mutation-action\";\n\nexport type NavigationDataLoader = (\n request: Request,\n) => Promise<InitialRouteData>;\n\nexport type NavigationCommit = {\n url: URL;\n kind: \"push\" | \"replace\" | \"pop\";\n outcome: \"ready\" | \"not-found\" | \"error\";\n title: string;\n};\n\nexport type NavigationScrollContext = NavigationCommit & {\n navigation: NavigationCommit[\"kind\"];\n position?: { x: number; y: number };\n};\n\nexport type NavigationScrollOption =\n | false\n | \"top\"\n | ((context: NavigationScrollContext) => void);\n\nexport type NavigationAccessibility = {\n announce?: \"title\" | false | ((context: NavigationCommit) => string | null);\n};\n\nexport type MutationNavigationState<TData = unknown, TField extends string = string> =\n | { state: \"idle\"; form?: HTMLFormElement; submissionKey?: string; result?: MutationResult<TData, TField> }\n | { state: \"submitting\"; form: HTMLFormElement; submissionKey?: string; formData: FormData }\n | { state: \"loading\"; form: HTMLFormElement; submissionKey?: string; formData: FormData; result?: Extract<MutationResult<TData, TField>, { status: \"success\" }> }\n | { state: \"invalid\"; form: HTMLFormElement; submissionKey?: string; formData: FormData; result: Extract<MutationResult<TData, TField>, { status: \"invalid\" }> }\n | { state: \"error\"; form: HTMLFormElement; submissionKey?: string; formData: FormData; response?: Response };\n\nexport type FormProps =\n | (Omit<FormHTMLAttributes<HTMLFormElement>, \"action\"> & {\n action?: string;\n locale?: AppLocale;\n submissionKey?: string;\n })\n | (Omit<FormHTMLAttributes<HTMLFormElement>, \"action\" | \"method\"> & {\n action: MutationFormAction;\n locale?: AppLocale;\n method?: never;\n submissionKey?: never;\n });\n\nexport type MutationSubmitProps =\n Omit<ButtonHTMLAttributes<HTMLButtonElement>, \"formAction\" | \"formMethod\"> & {\n formAction: MutationFormAction;\n formMethod?: never;\n locale?: AppLocale;\n };\n\nexport type FileRouterOptions = {\n initialMatch?: PendingRouteMatch;\n loadNavigationData?: NavigationDataLoader;\n navigation?: \"document\" | \"server\";\n routes: Record<string, RouteImporter>;\n locales?: LocaleConfiguration;\n locale?: string;\n loading?: ComponentType;\n navigationAccessibility?: NavigationAccessibility;\n navigationScroll?: NavigationScrollOption;\n notFound?: ComponentType<NotFoundProps>;\n};\n\nexport function createFileRouter(options: FileRouterOptions) {\n const manifest = createRouteManifest(options.routes);\n const navigationDataLoader = options.loadNavigationData ?? loadNavigationData;\n\n return function FileRouter() {\n const [location, setLocation] = useState(() => getCurrentLocation());\n const [locale, setLocale] = useState(options.locale);\n const routePathname = applicationPathname(location.pathname, options.locales);\n const lastLocation = useRef(location);\n const [match, setMatch] = useState<PendingRouteMatch>(\n () => options.initialMatch ?? { status: \"loading\" },\n );\n const initialMatchPending = useRef(Boolean(options.initialMatch));\n const initialNavigationPending = useRef(true);\n const navigationSequence = useRef(0);\n const routeLoadController = useRef<AbortController | undefined>(undefined);\n const routeLoadCause = useRef<\"navigation\" | \"refresh\">(\"navigation\");\n const submissionControllers = useRef(new Map<string, AbortController>());\n const submissionStates = useRef(new Map<string, MutationNavigationState>());\n const [submissionVersion, setSubmissionVersion] = useState(0);\n const [routeRefresh, setRouteRefresh] = useState(0);\n const routeRefreshWaiters = useRef(new Set<() => void>());\n const [resolvedRouteVersion, setResolvedRouteVersion] = useState(0);\n const navigationKind = useRef<\"push\" | \"replace\" | \"pop\">(\"push\");\n const [pendingCommit, setPendingCommit] = useState<NavigationCommit | null>(null);\n const [committed, setCommitted] = useState<NavigationCommit | null>(null);\n const pendingCommitRef = useRef<NavigationCommit | null>(null);\n pendingCommitRef.current = pendingCommit;\n const pendingScroll = useRef<PendingScroll | undefined>(undefined);\n const pendingPopPosition = useRef<ScrollPosition | undefined>(undefined);\n const activeHistoryEntry = useRef<string | undefined>(undefined);\n const restoringScroll = useRef(false);\n const scrollPositions = useRef(new Map<string, ScrollPosition>());\n const boundaryRegistrations = useRef<{\n element: RouteFocusBoundaryElement;\n order: number;\n }[]>([]);\n const nextBoundaryOrder = useRef(0);\n\n function saveCurrentScrollPosition() {\n const entry = activeHistoryEntry.current;\n const position = currentScrollPosition();\n if (entry) scrollPositions.current.set(entry, position);\n rememberScrollPosition(entry, position);\n }\n const focusRegistration = useMemo(() => ({\n register(element: RouteFocusBoundaryElement) {\n const registration = {\n element,\n order: nextBoundaryOrder.current++,\n };\n if (\n boundaryRegistrations.current.length > 0 &&\n typeof process !== \"undefined\" &&\n process.env.NODE_ENV !== \"production\"\n ) {\n console.warn(\n \"Demiurge found more than one RouteFocusBoundary. The first boundary remains active.\",\n );\n }\n boundaryRegistrations.current.push(registration);\n\n return () => {\n const index = boundaryRegistrations.current.indexOf(registration);\n if (index !== -1) boundaryRegistrations.current.splice(index, 1);\n };\n },\n focus() {\n const active = boundaryRegistrations.current\n .slice()\n .sort((left, right) => left.order - right.order)[0]?.element;\n if (!active || !active.isConnected || typeof active.focus !== \"function\") {\n return false;\n }\n\n try {\n active.focus({ preventScroll: true });\n } catch {\n active.focus();\n }\n return true;\n },\n }), []);\n\n useLayoutEffect(() => {\n if (options.navigation !== \"document\") {\n ensureNavigationStatusRegion();\n }\n return () => {\n boundaryRegistrations.current = [];\n };\n }, [options.navigation]);\n\n useEffect(() => () => {\n abortMutationActions();\n for (const resolve of routeRefreshWaiters.current) resolve();\n routeRefreshWaiters.current.clear();\n for (const controller of submissionControllers.current.values()) controller.abort();\n submissionControllers.current.clear();\n submissionStates.current.clear();\n }, []);\n\n function abortSubmissions(except?: AbortController) {\n abortMutationActions(except);\n let changed = false;\n for (const [key, controller] of submissionControllers.current) {\n if (controller === except) continue;\n controller.abort();\n submissionControllers.current.delete(key);\n const state = submissionStates.current.get(key);\n if (state?.state === \"submitting\" || state?.state === \"loading\") {\n submissionStates.current.set(key, {\n state: \"idle\",\n form: state.form,\n submissionKey: state.submissionKey,\n ...(state.state === \"loading\" && state.result ? { result: state.result } : {}),\n });\n }\n changed = true;\n }\n if (changed) setSubmissionVersion((value) => value + 1);\n }\n\n function supersedeRouteLoad() {\n navigationSequence.current++;\n routeLoadController.current?.abort();\n routeLoadController.current = undefined;\n }\n\n useEffect(() => {\n if (options.navigation === \"document\") {\n return;\n }\n\n const previousRestoration = window.history.scrollRestoration;\n window.history.scrollRestoration = \"manual\";\n activeHistoryEntry.current = ensureHistoryEntry();\n saveCurrentScrollPosition();\n const onScroll = () => {\n if (!restoringScroll.current) {\n saveCurrentScrollPosition();\n }\n };\n window.addEventListener(\"scroll\", onScroll, { passive: true });\n return () => {\n window.removeEventListener(\"scroll\", onScroll);\n window.history.scrollRestoration = previousRestoration;\n };\n }, [options.navigation]);\n\n useEffect(() => {\n function onPopState() {\n abortSubmissions();\n navigationKind.current = \"pop\";\n restoringScroll.current = true;\n activeHistoryEntry.current = ensureHistoryEntry();\n pendingPopPosition.current = scrollPositions.current.get(\n activeHistoryEntry.current,\n ) ?? readScrollPosition();\n const next = getCurrentLocation();\n const previous = lastLocation.current;\n if (previous.pathname !== next.pathname || previous.search !== next.search) {\n supersedeRouteLoad();\n routeLoadCause.current = \"navigation\";\n }\n lastLocation.current = next;\n if (\n options.navigation !== \"document\" &&\n previous.pathname === next.pathname &&\n previous.search === next.search &&\n previous.hash !== next.hash\n ) {\n scrollToHash(next.hash);\n }\n setLocation(next);\n }\n\n window.addEventListener(\"popstate\", onPopState);\n return () => window.removeEventListener(\"popstate\", onPopState);\n }, []);\n\n useEffect(() => {\n let cancelled = false;\n let settled = false;\n const sequence = ++navigationSequence.current;\n const controller = new AbortController();\n routeLoadController.current = controller;\n const cause = routeLoadCause.current;\n const isCurrent = () =>\n !cancelled && sequence === navigationSequence.current;\n\n setPendingCommit(null);\n setCommitted(null);\n\n if (\n initialMatchPending.current &&\n getMatchPathname(options.initialMatch) === routePathname\n ) {\n initialMatchPending.current = false;\n initialNavigationPending.current = false;\n return () => {\n cancelled = true;\n controller.abort();\n if (routeLoadController.current === controller) {\n routeLoadController.current = undefined;\n }\n };\n }\n\n const initialNavigation = initialNavigationPending.current;\n initialNavigationPending.current = false;\n\n if (\n cause !== \"refresh\" &&\n options.navigation !== \"document\" &&\n !initialNavigation\n ) {\n pendingScroll.current = {\n navigation: navigationKind.current,\n position: navigationKind.current === \"pop\"\n ? pendingPopPosition.current\n : undefined,\n };\n pendingPopPosition.current = undefined;\n }\n\n if (cause !== \"refresh\") {\n setMatch({ status: \"loading\" });\n loadLoadingFallback(manifest, routePathname).then((Loading) => {\n if (isCurrent() && !settled && Loading) {\n setMatch({ loading: Loading, status: \"loading\" });\n }\n }).catch(() => {\n // Loading UI is optional. A malformed pathname or broken loading\n // module must not become an unhandled rejection while the main route\n // pipeline resolves the controlled error state.\n });\n }\n const request = new Request(location.href, { signal: controller.signal });\n Promise.resolve(navigationDataLoader(request))\n .then(async (initialData) => {\n const responseUrl = initialData.url ? new URL(initialData.url, location.href) : new URL(location.href);\n if (!responseUrl.hash) responseUrl.hash = location.hash;\n const responseLocale = initialData.locale ?? (\n options.locales\n ? resolveLocale(new Request(responseUrl), options.locales).locale\n : locale\n );\n return {\n initialData,\n responseUrl,\n nextMatch: await loadPageRoute(\n manifest,\n applicationPathname(responseUrl.pathname, options.locales),\n new Request(responseUrl.href, { signal: controller.signal }),\n initialData,\n undefined,\n { documentContributions: false, locale: responseLocale },\n ),\n };\n })\n .then(({ initialData, nextMatch, responseUrl }) => {\n settled = true;\n if (isCurrent()) {\n if (initialData.document) {\n applyNavigationDocument(initialData.document);\n }\n if (\"locale\" in initialData && initialData.locale) {\n setLocale(initialData.locale);\n }\n if (responseUrl.href !== location.href) {\n window.history.replaceState(window.history.state, \"\", responseUrl);\n const canonicalLocation = getCurrentLocation();\n lastLocation.current = canonicalLocation;\n setLocation(canonicalLocation);\n }\n setMatch(nextMatch);\n setResolvedRouteVersion((value) => value + 1);\n if (cause !== \"refresh\") {\n setPendingCommit({\n kind: navigationKind.current,\n outcome: nextMatch.status === \"not-found\" ? \"not-found\" : \"ready\",\n title: document.title || \"Demiurge App\",\n url: new URL(location.href),\n });\n }\n }\n })\n .catch(async (error: unknown) => {\n settled = true;\n\n if (!isCurrent() || controller.signal.aborted) {\n return;\n }\n\n const ErrorFallback = await loadErrorFallback(\n manifest,\n routePathname,\n );\n\n if (isCurrent()) {\n const navigationDocument = typeof error === \"object\" && error\n ? navigationErrorDocuments.get(error)\n : undefined;\n if (navigationDocument) {\n applyNavigationDocument(navigationDocument);\n }\n setMatch({\n Error: ErrorFallback,\n error,\n locale,\n pathname: routePathname,\n status: \"error\",\n });\n setPendingCommit(cause === \"refresh\"\n ? null\n : {\n kind: navigationKind.current,\n outcome: \"error\",\n title: navigationDocument?.title ?? \"Navigation failed\",\n url: new URL(location.href),\n });\n setResolvedRouteVersion((value) => value + 1);\n }\n });\n\n return () => {\n cancelled = true;\n controller.abort();\n if (routeLoadController.current === controller) {\n routeLoadController.current = undefined;\n }\n };\n }, [routePathname, location.pathname, location.search, routeRefresh]);\n\n useLayoutEffect(() => {\n if (!committed || options.navigation === \"document\") {\n return;\n }\n\n if (committed.url.hash) {\n if (pendingScroll.current) {\n pendingScroll.current = undefined;\n scrollToHash(committed.url.hash);\n }\n restoringScroll.current = false;\n return;\n }\n\n focusRegistration.focus();\n if (pendingScroll.current) {\n const pending = pendingScroll.current;\n pendingScroll.current = undefined;\n applyNavigationScroll(options.navigationScroll, {\n ...committed,\n kind: pending.navigation,\n navigation: pending.navigation,\n position: pending.position,\n });\n }\n restoringScroll.current = false;\n announceNavigation(committed, options.navigationAccessibility);\n }, [\n committed,\n focusRegistration,\n options.navigation,\n options.navigationAccessibility,\n options.navigationScroll,\n ]);\n\n function setSubmissionState(key: string, state: MutationNavigationState) {\n submissionStates.current.set(key, state);\n setSubmissionVersion((value) => value + 1);\n }\n\n function releaseMutationNavigation(form: HTMLFormElement, submissionKey?: string) {\n const key = mutationSubmissionKey(form, submissionKey);\n const state = submissionStates.current.get(key);\n if (state?.form !== form) return;\n if (state.state === \"loading\" && state.result) return;\n submissionControllers.current.get(key)?.abort();\n submissionControllers.current.delete(key);\n submissionStates.current.delete(key);\n setSubmissionVersion((value) => value + 1);\n }\n\n const router = useMemo(\n () => ({\n navigation: options.navigation ?? \"server\",\n locale,\n locales: options.locales,\n submissionVersion,\n getMutationNavigation(form?: HTMLFormElement, submissionKey?: string) {\n const key = mutationSubmissionKey(form, submissionKey);\n return submissionStates.current.get(key) ?? {\n state: \"idle\",\n form,\n submissionKey,\n };\n },\n releaseMutationNavigation,\n push(to: string) {\n abortSubmissions();\n restoringScroll.current = false;\n const previous = getCurrentLocation();\n navigationKind.current = \"push\";\n if (options.navigation !== \"document\") {\n saveCurrentScrollPosition();\n }\n const entry = createHistoryEntry();\n window.history.pushState(entry.state, \"\", to);\n activeHistoryEntry.current = entry.key;\n const next = getCurrentLocation();\n if (previous.pathname !== next.pathname || previous.search !== next.search) {\n supersedeRouteLoad();\n routeLoadCause.current = \"navigation\";\n }\n lastLocation.current = next;\n setLocation(next);\n\n if (\n previous.pathname === next.pathname &&\n previous.search === next.search &&\n previous.hash !== next.hash\n ) {\n scrollToHash(next.hash);\n }\n },\n replace(to: string) {\n abortSubmissions();\n restoringScroll.current = false;\n const previous = getCurrentLocation();\n navigationKind.current = \"replace\";\n if (options.navigation !== \"document\") {\n saveCurrentScrollPosition();\n }\n window.history.replaceState(\n withHistoryEntry(window.history.state, activeHistoryEntry.current),\n \"\",\n to,\n );\n const next = getCurrentLocation();\n if (previous.pathname !== next.pathname || previous.search !== next.search) {\n supersedeRouteLoad();\n routeLoadCause.current = \"navigation\";\n }\n lastLocation.current = next;\n setLocation(next);\n\n if (\n options.navigation !== \"document\" &&\n previous.pathname === next.pathname &&\n previous.search === next.search &&\n previous.hash !== next.hash\n ) {\n scrollToHash(next.hash);\n }\n },\n async submitMutation(form: HTMLFormElement, submitter: HTMLElement | null, submissionKey?: string) {\n if ((options.navigation ?? \"server\") !== \"server\") return;\n const request = createMutationRequest(form, submitter);\n if (!request) return;\n const key = mutationSubmissionKey(form, submissionKey);\n submissionControllers.current.get(key)?.abort();\n const controller = new AbortController();\n submissionControllers.current.set(key, controller);\n const formData = request.formData;\n const isCurrent = () =>\n !controller.signal.aborted && submissionControllers.current.get(key) === controller;\n setSubmissionState(key, {\n state: \"submitting\",\n form,\n submissionKey,\n formData,\n });\n let response: Response | undefined;\n try {\n const mutation = await performMutationRequest({\n body: request.body,\n contentType: request.contentType,\n method: request.method,\n signal: controller.signal,\n url: request.url,\n });\n response = mutation.response;\n if (!isCurrent()) return;\n const result = mutation.result;\n if (!isCurrent()) return;\n if (result?.status === \"invalid\") {\n setSubmissionState(key, { state: \"invalid\", form, submissionKey, formData, result });\n return;\n }\n if (result?.status === \"redirect\") {\n const destination = validateMutationRedirect(result.location);\n if (!destination) {\n setSubmissionState(key, { state: \"error\", form, submissionKey, formData, response });\n return;\n }\n supersedeRouteLoad();\n abortSubmissions(controller);\n routeLoadCause.current = \"navigation\";\n setSubmissionState(key, { state: \"loading\", form, submissionKey, formData });\n saveCurrentScrollPosition();\n if (result.history === \"replace\") {\n window.history.replaceState(\n withHistoryEntry(null, activeHistoryEntry.current),\n \"\",\n destination,\n );\n } else {\n const entry = createHistoryEntry();\n window.history.pushState(entry.state, \"\", destination);\n activeHistoryEntry.current = entry.key;\n }\n navigationKind.current = result.history;\n lastLocation.current = getCurrentLocation();\n setLocation(lastLocation.current);\n setRouteRefresh((value) => value + 1);\n return;\n }\n if (result?.status === \"failed\" || !response.ok) {\n setSubmissionState(key, { state: \"error\", form, submissionKey, formData, response });\n return;\n }\n if (result?.status === \"success\" && result.revalidate) {\n setSubmissionState(key, { state: \"loading\", form, submissionKey, formData, result });\n supersedeRouteLoad();\n routeLoadCause.current = \"refresh\";\n setRouteRefresh((value) => value + 1);\n } else {\n setSubmissionState(key, { state: \"idle\", form, submissionKey, result });\n }\n } catch {\n if (isCurrent()) {\n setSubmissionState(key, { state: \"error\", form, submissionKey, formData, response });\n }\n } finally {\n if (submissionControllers.current.get(key) === controller) {\n submissionControllers.current.delete(key);\n }\n }\n },\n }),\n [submissionVersion],\n );\n\n useLayoutEffect(() => registerMutationRouter({\n redirect(destination, history, controller) {\n supersedeRouteLoad();\n abortSubmissions(controller);\n routeLoadCause.current = \"navigation\";\n saveCurrentScrollPosition();\n if (history === \"replace\") {\n window.history.replaceState(\n withHistoryEntry(null, activeHistoryEntry.current),\n \"\",\n destination,\n );\n } else {\n const entry = createHistoryEntry();\n window.history.pushState(entry.state, \"\", destination);\n activeHistoryEntry.current = entry.key;\n }\n navigationKind.current = history;\n lastLocation.current = getCurrentLocation();\n setLocation(lastLocation.current);\n setRouteRefresh((value) => value + 1);\n },\n refresh() {\n return new Promise<void>((resolve) => {\n supersedeRouteLoad();\n routeLoadCause.current = \"refresh\";\n routeRefreshWaiters.current.add(resolve);\n setRouteRefresh((value) => value + 1);\n });\n },\n }), [locale, options.locales, options.navigation]);\n\n return createElement(RouterContext.Provider, {\n value: router,\n children: createElement(RouteFocusContext.Provider, {\n value: focusRegistration,\n children: createElement(RouteRenderer, {\n key: `${location.pathname}${location.search}`,\n Loading: options.loading,\n NotFound: options.notFound,\n match,\n pendingCommit,\n resolvedRouteVersion,\n onCommitted: (value) => {\n if (pendingCommitRef.current === value) setCommitted(value);\n },\n onRenderError: () => {\n setCommitted(pendingCommit\n ? { ...pendingCommit, outcome: \"error\", title: \"Navigation failed\" }\n : null);\n settleRouteRefreshes();\n },\n onRouteCommitted: settleRouteRefreshes,\n }),\n }),\n });\n\n function settleRouteRefreshes() {\n for (const resolve of routeRefreshWaiters.current) resolve();\n routeRefreshWaiters.current.clear();\n for (const [key, state] of submissionStates.current) {\n if (state.state === \"loading\") {\n submissionStates.current.set(key, {\n state: \"idle\",\n form: state.form,\n submissionKey: state.submissionKey,\n result: state.result,\n });\n }\n }\n setSubmissionVersion((value) => value + 1);\n }\n };\n}\n\n// Hydration is safe only when the client reproduces the server output. The\n// client replaces a page document when its route no longer matches. The client\n// hydrates a document that the server marked as a 404. This operation preserves\n// the layouts that the server resolved.\nfunction isHydratableMatch(match: PendingRouteMatch, root: Element) {\n const fallback = root.getAttribute(HYDRATION_FALLBACK_ATTRIBUTE);\n\n return match.status === \"not-found\"\n ? fallback === \"not-found\"\n : match.status === \"ready\" && fallback === null;\n}\n\nfunction getMatchPathname(match: PendingRouteMatch | undefined) {\n if (!match) {\n return undefined;\n }\n\n if (match.status === \"ready\") {\n return match.match.pathname;\n }\n\n return match.status === \"loading\" ? undefined : match.pathname;\n}\n\nexport type HydrateFileRouterOptions = Omit<\n FileRouterOptions,\n \"initialMatch\"\n> & {\n initialData?: InitialRouteData;\n root?: Element;\n};\n\nexport async function hydrateFileRouter(options: HydrateFileRouterOptions) {\n const root = options.root ?? document.getElementById(\"root\");\n\n if (!root) {\n throw new Error(\n \"Demiurge expected a #root element in the framework document.\",\n );\n }\n\n const manifest = createRouteManifest(options.routes);\n const navigationDataLoader = options.loadNavigationData ?? loadNavigationData;\n const initialData = options.initialData ?? readInitialRouteData(document);\n const match = await loadPageRoute(\n manifest,\n applicationPathname(window.location.pathname, options.locales),\n new Request(window.location.href),\n initialData ?? await navigationDataLoader(new Request(window.location.href)),\n undefined,\n { documentContributions: false, locale: initialData?.locale ?? options.locale },\n );\n const hydratable = isHydratableMatch(match, root);\n const Router = createFileRouter(\n hydratable\n ? {\n ...options,\n locale: initialData?.locale ?? options.locale,\n initialMatch: match,\n loadNavigationData: navigationDataLoader,\n navigation: initialData?.navigation ?? options.navigation,\n }\n : {\n ...options,\n loadNavigationData: navigationDataLoader,\n navigation: initialData?.navigation ?? options.navigation,\n },\n );\n const { createRoot, hydrateRoot } = resolveReactDomClient(\n await import(\"react-dom/client\"),\n );\n\n // Only documents rendered by the framework server carry markup to hydrate.\n // A static shell has an empty root, so hydrating it would mismatch. A\n // server-rendered 404 carries markup too, and hydrating it is what keeps the\n // layouts the server resolved from being torn down on the client.\n if (hydratable && root.hasAttribute(HYDRATION_ROOT_ATTRIBUTE)) {\n hydrateRoot(root, createElement(Router));\n startDeferredScripts();\n return;\n }\n\n root.replaceChildren();\n createRoot(root).render(createElement(Router));\n startDeferredScripts();\n}\n\ntype ReactDomClientApi = Pick<\n typeof import(\"react-dom/client\"),\n \"createRoot\" | \"hydrateRoot\"\n>;\n\ntype ReactDomClientModule = Partial<ReactDomClientApi> & {\n default?: ReactDomClientApi;\n};\n\nexport function resolveReactDomClient(module: ReactDomClientModule) {\n // TYPE-EVIDENCE: the runtime checks confirm both client functions exist. The module therefore matches the client API shape.\n const client = typeof module.createRoot === \"function\" &&\n typeof module.hydrateRoot === \"function\"\n ? module as ReactDomClientApi\n : module.default;\n\n if (\n !client ||\n typeof client.createRoot !== \"function\" ||\n typeof client.hydrateRoot !== \"function\"\n ) {\n throw new Error(\n \"Demiurge could not load the React DOM client from the Vite module.\",\n );\n }\n\n return client;\n}\n\ntype DataAttributes = {\n [TName in `data-${string}`]?: string | number | undefined;\n};\n\nexport type LinkProps<TTo extends AppHref = AppHref> = LinkTo<TTo> &\n Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> & {\n reloadDocument?: boolean;\n replace?: boolean;\n locale?: AppLocale;\n } & DataAttributes;\n\nfunction LinkImplementation<const TTo extends AppHref>(\n props: LinkProps<TTo>,\n ref: ForwardedRef<HTMLAnchorElement>,\n) {\n const router = useRouter();\n const {\n children,\n download,\n hash: _hash,\n locale: _locale,\n onClick,\n path: _path,\n reloadDocument,\n replace,\n search: _search,\n target,\n to: _to,\n ...anchorProps\n } = props;\n // TYPE-EVIDENCE: href reads only the typed destination fields from LinkProps.\n const baseHref = href(props as LinkTarget<TTo>);\n const explicitLocale = _locale;\n const to = router.locales && (explicitLocale ?? router.locale)\n ? localizeHref(\n baseHref,\n (explicitLocale ?? router.locale)!,\n router.locales,\n typeof window === \"undefined\" ? \"http://demiurge.local\" : window.location.href,\n )\n : baseHref;\n\n return (\n <a\n {...anchorProps}\n download={download}\n href={to}\n ref={ref}\n target={target}\n onClick={(event) => {\n onClick?.(event);\n\n if (\n router.navigation === \"server\" &&\n !reloadDocument &&\n shouldHandleLinkClick(event, { download, target, to })\n ) {\n event.preventDefault();\n if (replace) {\n router.replace(to);\n } else {\n router.push(to);\n }\n }\n }}\n >\n {children}\n </a>\n );\n}\n\nexport function Link<const TTo extends AppHref>(\n props: LinkProps<TTo> & { ref?: ForwardedRef<HTMLAnchorElement> },\n) {\n return LinkImplementation(props, props.ref ?? null);\n}\n\nconst MutationFormContext = createContext<string | undefined>(undefined);\n\nexport function Form(props: FormProps) {\n const router = useRouter();\n const routerRef = useRef(router);\n routerRef.current = router;\n const generatedKey = useId();\n const formKey = props.submissionKey ?? generatedKey;\n const formRef = useRef<HTMLFormElement | null>(null);\n const hydrated = useHydratedFormAction();\n // TYPE-EVIDENCE: FormProps permits a function action only for a branded MutationFormAction.\n const progressiveAction = typeof props.action === \"function\"\n ? props.action as MutationFormAction\n : undefined;\n const progressiveDetails = progressiveAction\n ? mutationFormActionDetails(progressiveAction)\n : undefined;\n const enhanceProgressiveAction = Boolean(\n progressiveAction && hydrated && router.navigation === \"server\",\n );\n\n useLayoutEffect(() => () => {\n if (formRef.current) {\n routerRef.current.releaseMutationNavigation(formRef.current, formKey);\n }\n }, [formKey]);\n\n function onSubmit(event: FormEvent<HTMLFormElement>) {\n // TYPE-EVIDENCE: React form props expose the same submit event handler shape at runtime.\n const applicationHandler = props.onSubmit as\n | ((value: FormEvent<HTMLFormElement>) => void)\n | undefined;\n applicationHandler?.(event);\n if (progressiveAction) return;\n if (event.defaultPrevented || router.navigation !== \"server\") return;\n // TYPE-EVIDENCE: React forwards the browser SubmitEvent as nativeEvent for form submissions.\n const submitter = (event.nativeEvent as SubmitEvent).submitter;\n if (!canInterceptMutation(event.currentTarget, submitter)) return;\n event.preventDefault();\n void router.submitMutation(\n event.currentTarget,\n submitter,\n formKey,\n );\n }\n\n const { submissionKey: _submissionKey, ...formProps } = props;\n const action = progressiveAction\n ? enhanceProgressiveAction ? progressiveAction : progressiveDetails?.url\n : formProps.action;\n const localizedAction = typeof action === \"string\" && router.locales && (props.locale ?? router.locale)\n ? localizeHref(action, (props.locale ?? router.locale)!, router.locales, typeof window === \"undefined\" ? \"http://demiurge.local\" : window.location.href)\n : action;\n return createElement(\n MutationFormContext.Provider,\n {\n value: formKey,\n children: createElement(\"form\", {\n ...formProps,\n action: localizedAction,\n locale: undefined,\n ...(progressiveAction\n ? {\n encType: enhanceProgressiveAction ? undefined : formProps.encType,\n method: enhanceProgressiveAction ? undefined : \"post\",\n onSubmit: formProps.onSubmit,\n }\n : { onSubmit }),\n ref: (element: HTMLFormElement | null) => {\n formRef.current = element;\n },\n }),\n },\n );\n}\n\nexport function MutationSubmit(props: MutationSubmitProps) {\n const router = useRouter();\n const hydrated = useHydratedFormAction();\n const details = mutationFormActionDetails(props.formAction);\n const enhance = hydrated && router.navigation === \"server\";\n const action = router.locales && (props.locale ?? router.locale)\n ? localizeHref(details.url, (props.locale ?? router.locale)!, router.locales, typeof window === \"undefined\" ? \"http://demiurge.local\" : window.location.href)\n : details.url;\n return createElement(\"button\", {\n ...props,\n locale: undefined,\n formAction: enhance ? props.formAction : action,\n formMethod: enhance ? undefined : \"post\",\n });\n}\n\nfunction useHydratedFormAction() {\n const [hydrated, setHydrated] = useState(false);\n useEffect(() => setHydrated(true), []);\n return hydrated;\n}\n\nexport function useNavigation<TData = unknown, TField extends string = string>(options?: {\n form?: HTMLFormElement;\n submissionKey?: string;\n}): MutationNavigationState<TData, TField> {\n const contextKey = useContext(MutationFormContext);\n // TYPE-EVIDENCE: the router stores MutationNavigationState values and the generic only describes its application data.\n return useRouter().getMutationNavigation(options?.form, options?.submissionKey ?? contextKey) as MutationNavigationState<TData, TField>;\n}\n\nexport function useFormNavigation<TData = unknown, TField extends string = string>(submissionKey?: string) {\n return useNavigation<TData, TField>({ submissionKey });\n}\n\nfunction RouteRenderer({\n Loading,\n NotFound,\n match,\n onRenderError,\n onCommitted,\n pendingCommit,\n resolvedRouteVersion,\n onRouteCommitted,\n}: {\n Loading?: ComponentType;\n NotFound?: ComponentType<NotFoundProps>;\n match: PendingRouteMatch;\n onCommitted: (value: NavigationCommit) => void;\n onRenderError: () => void;\n pendingCommit: NavigationCommit | null;\n resolvedRouteVersion: number;\n onRouteCommitted: () => void;\n}) {\n if (match.status === \"loading\") {\n const AppLoading = match.loading ?? Loading;\n\n return AppLoading ? createElement(AppLoading) : null;\n }\n\n if (match.status === \"not-found\") {\n const AppNotFound = match.notFound ?? NotFound ?? BuiltInNotFound;\n\n return createElement(Fragment, null, match.layouts.reduceRight<ReactNode>(\n (children, Layout) =>\n createElement(Layout, {\n children,\n locale: match.locale,\n path: {},\n pathname: match.pathname,\n }),\n createElement(AppNotFound, { locale: match.locale, pathname: match.pathname }),\n ), createElement(NavigationCommitMarker, { commit: pendingCommit, onCommit: onCommitted, onRouteCommitted, resolvedRouteVersion }));\n }\n\n if (match.status === \"error\") {\n return createElement(Fragment, null, match.Error\n ? createElement(match.Error, {\n error: match.error,\n locale: \"locale\" in match ? match.locale : undefined,\n pathname: match.pathname,\n status: errorStatus(match.error),\n })\n : null, createElement(NavigationCommitMarker, { commit: pendingCommit, onCommit: onCommitted, onRouteCommitted, resolvedRouteVersion }));\n }\n\n const { data, error, locale, page, layouts, path, pathname } = match.match;\n const pageElement = createElement(page, { data, locale, path, pathname });\n const routeElement = layouts.reduceRight<ReactNode>(\n (children, Layout) => createElement(Layout, { path, pathname, locale, children }),\n pageElement,\n );\n\n return createElement(RouteErrorBoundary, {\n Error: error,\n children: createElement(Fragment, null, routeElement, createElement(NavigationCommitMarker, { commit: pendingCommit, onCommit: onCommitted, onRouteCommitted, resolvedRouteVersion })),\n onError: onRenderError,\n pathname,\n });\n}\n\nfunction NavigationCommitMarker({\n commit,\n onCommit,\n onRouteCommitted,\n resolvedRouteVersion,\n}: {\n commit: NavigationCommit | null;\n onCommit: (value: NavigationCommit) => void;\n onRouteCommitted: () => void;\n resolvedRouteVersion: number;\n}) {\n const signaled = useRef<NavigationCommit | null>(null);\n const signaledRouteVersion = useRef(0);\n useLayoutEffect(() => {\n if (resolvedRouteVersion > signaledRouteVersion.current) {\n signaledRouteVersion.current = resolvedRouteVersion;\n onRouteCommitted();\n }\n if (commit && signaled.current !== commit) {\n signaled.current = commit;\n onCommit(commit);\n }\n }, [commit, onCommit, onRouteCommitted, resolvedRouteVersion]);\n return null;\n}\n\nclass RouteErrorBoundary extends Component<\n {\n children: ReactNode;\n Error?: ComponentType<RouteErrorProps>;\n onError: () => void;\n pathname: string;\n },\n { error?: unknown }\n> {\n static getDerivedStateFromError(error: unknown) {\n return { error };\n }\n\n override state: { error?: unknown } = {};\n\n override componentDidCatch() {\n this.props.onError();\n }\n\n override componentDidUpdate(previousProps: {\n children: ReactNode;\n Error?: ComponentType<RouteErrorProps>;\n onError: () => void;\n pathname: string;\n }) {\n if (\n this.state.error !== undefined &&\n previousProps.pathname !== this.props.pathname\n ) {\n this.setState({ error: undefined });\n }\n }\n\n override render() {\n if (this.state.error !== undefined) {\n return this.props.Error\n ? createElement(this.props.Error, {\n error: this.state.error,\n pathname: this.props.pathname,\n status: errorStatus(this.state.error),\n })\n : null;\n }\n\n return this.props.children;\n }\n}\n\nfunction errorStatus(error: unknown) {\n return isHttpError(error) ? error.status : 500;\n}\n\nfunction getCurrentLocation() {\n return {\n hash: window.location.hash,\n href: window.location.href,\n pathname: window.location.pathname,\n search: window.location.search,\n };\n}\n\ntype PendingScroll = {\n navigation: NavigationCommit[\"kind\"];\n position?: ScrollPosition;\n};\n\ntype ScrollPosition = { x: number; y: number };\n\nconst SCROLL_STATE_KEY = \"__demiurge_scroll\";\nconst HISTORY_ENTRY_STATE_KEY = \"__demiurge_history_entry\";\nlet nextHistoryEntry = 0;\n\nfunction ensureHistoryEntry() {\n const existing = readHistoryEntry(window.history.state);\n if (existing) return existing;\n const entry = createHistoryEntry(window.history.state);\n window.history.replaceState(entry.state, \"\", window.location.href);\n return entry.key;\n}\n\nfunction createHistoryEntry(state?: unknown) {\n const key = `entry:${++nextHistoryEntry}`;\n return { key, state: withHistoryEntry(state, key) };\n}\n\nfunction withHistoryEntry(state: unknown, key = `entry:${++nextHistoryEntry}`) {\n return state && typeof state === \"object\"\n ? { ...state, [HISTORY_ENTRY_STATE_KEY]: key }\n : { [HISTORY_ENTRY_STATE_KEY]: key };\n}\n\nfunction readHistoryEntry(state: unknown) {\n if (!state || typeof state !== \"object\") return undefined;\n const key = Reflect.get(state, HISTORY_ENTRY_STATE_KEY);\n return typeof key === \"string\" ? key : undefined;\n}\n\nfunction currentScrollPosition(): ScrollPosition {\n return { x: window.scrollX, y: window.scrollY };\n}\n\nfunction rememberScrollPosition(\n activeEntry?: string,\n position = currentScrollPosition(),\n) {\n const state = window.history.state;\n if (activeEntry && readHistoryEntry(state) !== activeEntry) return;\n const nextState = state && typeof state === \"object\"\n ? { ...state, [SCROLL_STATE_KEY]: position }\n : { [SCROLL_STATE_KEY]: position };\n\n try {\n window.history.replaceState(nextState, \"\", window.location.href);\n } catch {\n // A history implementation can reject state writes. Navigation remains safe.\n }\n}\n\nfunction readScrollPosition() {\n const value = window.history.state?.[SCROLL_STATE_KEY];\n return value && typeof value === \"object\" &&\n typeof value.x === \"number\" && typeof value.y === \"number\"\n ? { x: value.x, y: value.y }\n : undefined;\n}\n\nfunction applyNavigationScroll(\n option: NavigationScrollOption | undefined,\n context: NavigationScrollContext,\n) {\n if (context.kind === \"pop\" && context.url.hash) {\n return;\n }\n\n if (option === false) {\n return;\n }\n\n if (typeof option === \"function\") {\n try {\n option(context);\n } catch {\n // An application scroll callback cannot break route rendering.\n }\n return;\n }\n\n const x = context.kind === \"pop\" ? context.position?.x ?? 0 : 0;\n const y = context.kind === \"pop\" ? context.position?.y ?? 0 : 0;\n window.scrollTo?.(x, y);\n}\n\nasync function loadNavigationData(request: Request) {\n const headers = new Headers(request.headers);\n headers.set(\"accept\", \"application/json\");\n headers.set(NAVIGATION_DATA_HEADER, NAVIGATION_DATA_REQUEST);\n const response = await fetch(new Request(request, {\n credentials: \"same-origin\",\n headers,\n }));\n const kind = response.headers.get(NAVIGATION_DATA_HEADER);\n\n if (kind === NAVIGATION_DATA_RESPONSE) {\n // TYPE-EVIDENCE: the response body is JSON that the server serialized as initial route data. The next check validates the required hasData field.\n const value = await response.json() as Partial<InitialRouteData>;\n\n if (value.hasData !== true) {\n throw new Error(\"Demiurge received malformed navigation route data.\");\n }\n\n return {\n data: value.data,\n document: value.document,\n hasData: true,\n locale: value.locale,\n url: response.url,\n };\n }\n\n if (kind === NAVIGATION_NOT_FOUND_RESPONSE) {\n const value = await readNavigationPayload(response);\n return {\n document: value?.document,\n hasData: true,\n locale: value?.locale,\n url: response.url,\n };\n }\n\n if (kind === NAVIGATION_ERROR_RESPONSE || !response.ok) {\n const value = await readNavigationPayload(response);\n // TYPE-EVIDENCE: the includes check confirms the status is a member of the error status tuple. The second cast reuses that same narrowing.\n const status = HTTP_ERROR_STATUSES.includes(\n response.status as (typeof HTTP_ERROR_STATUSES)[number],\n )\n ? response.status as (typeof HTTP_ERROR_STATUSES)[number]\n : 500;\n\n const error = httpError(status, {\n detail: value?.error?.detail,\n title: value?.error?.title,\n });\n if (value?.document) {\n navigationErrorDocuments.set(error, value.document);\n }\n throw error;\n }\n\n throw new Error(\n \"Demiurge expected a navigation data response from the application server.\",\n );\n}\n\nconst navigationErrorDocuments = new WeakMap<\n object,\n InitialRouteData[\"document\"]\n>();\n\nasync function readNavigationPayload(response: Response) {\n try {\n // TYPE-EVIDENCE: a marked navigation response is serialized by createNavigationDataResponse. The server validates the resolved contribution types before serialization.\n return await response.json() as Partial<InitialRouteData>;\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"malformed versioned\")) throw error;\n return undefined;\n }\n}\n\nfunction mutationSubmissionKey(form: HTMLFormElement | undefined, submissionKey?: string) {\n if (submissionKey) return submissionKey;\n if (!form) return \"default\";\n let id = formIds.get(form);\n if (!id) {\n id = `form:${nextFormId++}`;\n formIds.set(form, id);\n }\n return id;\n}\n\nconst formIds = new WeakMap<HTMLFormElement, string>();\nlet nextFormId = 1;\n\nfunction canInterceptMutation(form: HTMLFormElement, submitter: HTMLElement | null) {\n const options = formSubmissionOptions(form, submitter);\n if (!options) return false;\n const { action, enctype, method, target } = options;\n if (![\"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method)) return false;\n if (target && target.toLowerCase() !== \"_self\") return false;\n try {\n const url = new URL(action, window.location.href);\n if (url.origin !== window.location.origin) return false;\n } catch {\n return false;\n }\n return [\"application/x-www-form-urlencoded\", \"multipart/form-data\", \"text/plain\"].includes(enctype);\n}\n\nfunction createMutationRequest(form: HTMLFormElement, submitter: HTMLElement | null) {\n if (!canInterceptMutation(form, submitter)) return undefined;\n const { action, enctype, method } = formSubmissionOptions(form, submitter)!;\n const formData = submitter\n ? new FormData(form, submitter)\n : new FormData(form);\n if (enctype === \"multipart/form-data\") {\n return { body: formData, contentType: undefined, formData, method, url: action };\n }\n if (enctype === \"application/x-www-form-urlencoded\") {\n const body = new URLSearchParams();\n for (const [name, value] of formData) {\n if (typeof value === \"string\") body.append(name, value);\n else body.append(name, value.name);\n }\n return {\n body,\n contentType: \"application/x-www-form-urlencoded;charset=UTF-8\",\n formData,\n method,\n url: action,\n };\n }\n const lines: string[] = [];\n for (const [name, value] of formData) {\n lines.push(`${name}=${typeof value === \"string\" ? value : value.name}`);\n }\n return {\n body: `${lines.join(\"\\r\\n\")}\\r\\n`,\n contentType: \"text/plain;charset=UTF-8\",\n formData,\n method,\n url: action,\n };\n}\n\nfunction formSubmissionOptions(form: HTMLFormElement, submitter: HTMLElement | null) {\n if (!isSupportedMutationSubmitter(submitter)) return undefined;\n const button = submitter instanceof HTMLButtonElement || submitter instanceof HTMLInputElement\n ? submitter\n : undefined;\n return {\n action: (submitterFormAttribute(button, \"formaction\") ?? form.action) || window.location.href,\n enctype: ((submitterFormAttribute(button, \"formenctype\") ?? form.enctype) || \"application/x-www-form-urlencoded\").toLowerCase(),\n method: ((submitterFormAttribute(button, \"formmethod\") ?? form.method) || \"get\").toUpperCase(),\n target: submitterFormAttribute(button, \"formtarget\") ?? form.target,\n };\n}\n\nfunction submitterFormAttribute(\n submitter: HTMLButtonElement | HTMLInputElement | undefined,\n name: \"formaction\" | \"formenctype\" | \"formmethod\" | \"formtarget\",\n) {\n return submitter?.hasAttribute(name) ? submitter.getAttribute(name) ?? \"\" : undefined;\n}\n\nfunction isSupportedMutationSubmitter(submitter: HTMLElement | null) {\n if (!submitter) return true;\n if (submitter instanceof HTMLButtonElement) {\n return !submitter.disabled && submitter.type === \"submit\";\n }\n return submitter instanceof HTMLInputElement &&\n !submitter.disabled && submitter.type === \"submit\";\n}\n\nfunction scrollToHash(hash: string) {\n queueMicrotask(() => {\n if (!hash) {\n window.scrollTo?.(0, 0);\n return;\n }\n\n let id: string;\n try {\n id = decodeURIComponent(hash.slice(1));\n } catch {\n id = hash.slice(1);\n }\n document.getElementById(id)?.scrollIntoView?.();\n });\n}\n\nfunction shouldHandleLinkClick(\n event: MouseEvent<HTMLAnchorElement>,\n options: {\n download?: AnchorHTMLAttributes<HTMLAnchorElement>[\"download\"];\n target?: string;\n to: string;\n },\n) {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.altKey ||\n event.ctrlKey ||\n event.shiftKey ||\n options.download !== undefined && options.download !== false ||\n options.target !== undefined && options.target.toLowerCase() !== \"_self\"\n ) {\n return false;\n }\n\n const destination = new URL(options.to, window.location.href);\n\n return (\n (destination.protocol === \"http:\" || destination.protocol === \"https:\") &&\n destination.origin === window.location.origin\n );\n}\n\nfunction announceNavigation(\n commit: NavigationCommit,\n options: NavigationAccessibility | undefined,\n) {\n const announce = options?.announce ?? \"title\";\n if (announce === false) return;\n\n let message: string | null;\n try {\n message = announce === \"title\" ? commit.title : announce(commit);\n } catch {\n return;\n }\n\n if (message) {\n announceNavigationRegion(message);\n }\n}\n\nfunction announceNavigationRegion(message: string) {\n updateNavigationStatus(message);\n}\n\ntype RouterApi = {\n locale?: string;\n locales?: LocaleConfiguration;\n navigation: \"document\" | \"server\";\n submissionVersion: number;\n push(to: string): void;\n getMutationNavigation(form?: HTMLFormElement, submissionKey?: string): MutationNavigationState;\n releaseMutationNavigation(form: HTMLFormElement, submissionKey?: string): void;\n submitMutation(form: HTMLFormElement, submitter: HTMLElement | null, submissionKey?: string): Promise<void>;\n replace(to: string): void;\n};\n\nconst RouterContext = createContext<RouterApi>({\n navigation: \"document\",\n submissionVersion: 0,\n push(to) {\n window.location.href = to;\n },\n getMutationNavigation() {\n return { state: \"idle\" };\n },\n releaseMutationNavigation() {},\n async submitMutation(form) {\n form.submit();\n },\n replace(to) {\n window.location.replace(to);\n },\n});\n\nfunction useRouter() {\n return useContext(RouterContext);\n}\n","import {\n planImageTransform,\n type ImagePolicy,\n type ImageTransformOptions,\n} from \"./images\";\n\nexport type ImageProps = ImageTransformOptions & {\n className?: string;\n id?: string;\n policy?: ImagePolicy;\n};\n\n// The component is the surface that connects the planner to the build. A\n// rendered `Image` emits a self-describing variant path in `src`/`srcSet`.\n// The static build scans the rendered document for that path, and the\n// runtime optimizer parses it back into a real transform request.\nexport function Image({ className, id, policy, ...options }: ImageProps) {\n const plan = planImageTransform(options, policy);\n\n return (\n <img\n alt={plan.alt}\n className={className}\n decoding={plan.decoding}\n fetchPriority={plan.fetchPriority}\n height={plan.height}\n id={id}\n loading={plan.loading}\n sizes={plan.sizes}\n src={plan.src}\n srcSet={plan.srcSet}\n width={plan.width}\n />\n );\n}\n","import { script, type ScriptTag } from \"../document\";\nimport type { CspSource, RoutePolicy, RouteSecurityNeeds } from \"../security/types\";\n\nexport type AnalyticsConsent = boolean | \"required\";\n\nexport type AnalyticsProvider = \"opentelemetry\" | \"plausible\" | \"sentry\";\n\n/**\n * An integration descriptor. `scripts` goes into `export const scripts` and\n * `needs` goes into the route policy. The build compares the two, so wiring\n * only one half fails with a diagnostic that names the missing directive.\n */\nexport type AnalyticsIntegration = {\n consent: AnalyticsConsent;\n kind: \"analytics\";\n needs: RouteSecurityNeeds;\n provider: AnalyticsProvider;\n scripts: readonly ScriptTag[];\n};\n\nexport type PlausibleAnalyticsOptions = {\n consent?: AnalyticsConsent;\n domain: string;\n endpoint?: string;\n strategy?: ScriptTag[\"strategy\"];\n};\n\nexport type PlausibleAnalytics = AnalyticsIntegration & {\n domain: string;\n provider: \"plausible\";\n};\n\nexport type SentryAnalyticsOptions = {\n consent?: AnalyticsConsent;\n dsn: string;\n loaderHost?: string;\n strategy?: ScriptTag[\"strategy\"];\n};\n\nexport type SentryAnalytics = AnalyticsIntegration & {\n ingestOrigin: string;\n projectId: string;\n provider: \"sentry\";\n};\n\nexport type OpenTelemetryAnalyticsOptions = {\n consent?: AnalyticsConsent;\n endpoint: string;\n script?: string;\n strategy?: ScriptTag[\"strategy\"];\n};\n\nexport type OpenTelemetryAnalytics = AnalyticsIntegration & {\n endpoint: string;\n provider: \"opentelemetry\";\n};\n\nconst sentryLoaderHost = \"https://js.sentry-cdn.com\";\n\nexport const analytics = {\n /**\n * Plausible loads one script and posts events to its own API. The snippet\n * carries configuration in `data-domain`, so no inline code is involved.\n * `endpoint` accepts a same-origin path prefix for a proxied deployment.\n */\n plausible(options: PlausibleAnalyticsOptions): PlausibleAnalytics {\n const domain = normalizeDomain(options.domain);\n const endpoint = parseEndpoint(options.endpoint ?? \"https://plausible.io\");\n\n return {\n consent: options.consent ?? false,\n domain,\n kind: \"analytics\",\n needs: {\n connect: [endpoint.source],\n script: [endpoint.source],\n },\n provider: \"plausible\",\n scripts: [\n script({\n dataApi: `${endpoint.base}/api/event`,\n dataDomain: domain,\n defer: true,\n needs: { connect: [endpoint.source] },\n purpose: \"analytics\",\n src: `${endpoint.base}/js/script.js`,\n strategy: options.strategy ?? \"afterInteractive\",\n }),\n ],\n };\n },\n /**\n * The Sentry loader script carries the DSN in its own filename, so a page\n * needs no inline configuration call. Events go to the DSN host, which is\n * why the integration also declares a `connect-src` need.\n */\n sentry(options: SentryAnalyticsOptions): SentryAnalytics {\n const dsn = parseSentryDsn(options.dsn);\n const loader = parseHttpsOrigin(\n options.loaderHost ?? sentryLoaderHost,\n \"Sentry loader host\",\n );\n\n return {\n consent: options.consent ?? false,\n ingestOrigin: dsn.origin,\n kind: \"analytics\",\n needs: {\n connect: [dsn.origin],\n script: [loader],\n },\n projectId: dsn.projectId,\n provider: \"sentry\",\n scripts: [\n script({\n crossOrigin: \"anonymous\",\n needs: { connect: [dsn.origin] },\n purpose: \"error-monitoring\",\n src: `${loader}/${dsn.publicKey}.min.js`,\n // Errors thrown before the app is interactive are the ones an\n // application can least afford to lose.\n strategy: options.strategy ?? \"beforeInteractive\",\n }),\n ],\n };\n },\n /**\n * OpenTelemetry publishes no hosted browser loader. Browser instrumentation\n * is application code bundled from npm packages, so this helper describes\n * the part a policy has to know about: the OTLP endpoint the exporter posts\n * to, and an optional same-origin entry script that starts the SDK.\n */\n openTelemetry(\n options: OpenTelemetryAnalyticsOptions,\n ): OpenTelemetryAnalytics {\n const endpoint = parseEndpoint(options.endpoint);\n const entry = options.script;\n\n if (entry !== undefined && !entry.startsWith(\"/\")) {\n throw new Error(\n \"OpenTelemetry browser instrumentation must be a same-origin script path.\",\n );\n }\n\n return {\n consent: options.consent ?? false,\n endpoint: endpoint.base || \"/\",\n kind: \"analytics\",\n needs: entry\n ? { connect: [endpoint.source], script: [\"'self'\"] }\n : { connect: [endpoint.source] },\n provider: \"opentelemetry\",\n scripts: entry\n ? [\n script({\n needs: { connect: [endpoint.source] },\n purpose: \"observability\",\n src: entry,\n strategy: options.strategy ?? \"module\",\n }),\n ]\n : [],\n };\n },\n /** Merges the CSP needs of every integration into one route policy. */\n policy(...integrations: readonly AnalyticsIntegration[]): RoutePolicy {\n const needs: { -readonly [Key in keyof RouteSecurityNeeds]: CspSource[] } =\n {};\n\n for (const integration of integrations) {\n for (const need of [\"connect\", \"img\", \"script\"] as const) {\n const sources = integration.needs[need];\n\n if (!sources || sources.length === 0) {\n continue;\n }\n\n needs[need] = [...new Set([...(needs[need] ?? []), ...sources])];\n }\n }\n\n return { security: { needs } };\n },\n /** Collects the script contributions of every integration. */\n scripts(...integrations: readonly AnalyticsIntegration[]): ScriptTag[] {\n return integrations.flatMap((integration) => [...integration.scripts]);\n },\n};\n\nfunction normalizeDomain(domain: string) {\n const normalized = domain.trim();\n\n if (!normalized || normalized.includes(\"/\") || normalized.includes(\" \")) {\n throw new Error(\"Analytics domain must be a hostname without a path.\");\n }\n\n return normalized;\n}\n\n// An endpoint is either a vendor origin or a same-origin path prefix. A proxied\n// deployment serves the vendor through the application origin, which `'self'`\n// already covers, so the returned CSP source differs in that case.\nfunction parseEndpoint(endpoint: string) {\n if (endpoint.startsWith(\"/\")) {\n if (endpoint.startsWith(\"//\")) {\n throw new Error(\"Analytics endpoint must not be a scheme-relative URL.\");\n }\n\n // TYPE-EVIDENCE: the self string literal is a valid CSP source keyword. The cast labels it as the CspSource type.\n return {\n base: endpoint === \"/\" ? \"\" : endpoint.replace(/\\/+$/, \"\"),\n source: \"'self'\" as CspSource,\n };\n }\n\n const url = parseAbsoluteEndpoint(endpoint);\n\n // TYPE-EVIDENCE: the parsed URL origin is a valid same-origin CSP source string. The cast labels it as the CspSource type.\n return { base: url.origin, source: url.origin as CspSource };\n}\n\nfunction parseAbsoluteEndpoint(endpoint: string) {\n let url: URL;\n\n try {\n url = new URL(endpoint);\n } catch {\n throw new Error(\"Analytics endpoint must be an absolute URL.\");\n }\n\n if (url.protocol !== \"https:\") {\n throw new Error(\"Analytics endpoint must use HTTPS.\");\n }\n\n return url;\n}\n\nfunction parseHttpsOrigin(value: string, label: string) {\n let url: URL;\n\n try {\n url = new URL(value);\n } catch {\n throw new Error(`${label} must be an absolute URL.`);\n }\n\n if (url.protocol !== \"https:\") {\n throw new Error(`${label} must use HTTPS.`);\n }\n\n return url.origin;\n}\n\n// A Sentry DSN is https://<publicKey>@<host>/<projectId>. Every part the\n// browser needs comes from it, so an application configures one value.\nfunction parseSentryDsn(dsn: string) {\n let url: URL;\n\n try {\n url = new URL(dsn);\n } catch {\n throw new Error(\"Sentry DSN must be an absolute URL.\");\n }\n\n if (url.protocol !== \"https:\") {\n throw new Error(\"Sentry DSN must use HTTPS.\");\n }\n\n const projectId = url.pathname.replace(/^\\//, \"\");\n\n if (!url.username || url.password) {\n throw new Error(\n \"Sentry DSN must carry a public key and no secret key.\",\n );\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(projectId)) {\n throw new Error(\"Sentry DSN must end with a project identifier.\");\n }\n\n return {\n origin: url.origin,\n projectId,\n publicKey: url.username,\n };\n}\n","export type ObservabilityValue =\n | boolean\n | null\n | number\n | string\n | readonly ObservabilityValue[]\n | { readonly [key: string]: ObservabilityValue };\n\nexport type RequestSignal = {\n duration?: number;\n method: string;\n pathname: string;\n status?: number;\n attributes?: Readonly<Record<string, ObservabilityValue>>;\n};\n\nexport type ServerStartSignal = {\n adapter?: string;\n attributes?: Readonly<Record<string, ObservabilityValue>>;\n timestamp?: number;\n};\n\nexport type TraceSignal = {\n attributes?: Readonly<Record<string, ObservabilityValue>>;\n duration?: number;\n name: string;\n status?: \"error\" | \"ok\" | \"unset\";\n traceId?: string;\n};\n\nexport type WebVitalName = \"CLS\" | \"FCP\" | \"FID\" | \"INP\" | \"LCP\" | \"TTFB\";\n\nexport type WebVitalRating = \"good\" | \"needs-improvement\" | \"poor\";\n\nexport type WebVitalSignal = {\n id?: string;\n name: WebVitalName;\n navigationType?: string;\n rating?: WebVitalRating;\n value: number;\n attributes?: Readonly<Record<string, ObservabilityValue>>;\n};\n\nexport type InstrumentationEvent =\n | { kind: \"request\"; signal: RequestSignal }\n | { kind: \"server-start\"; signal: ServerStartSignal }\n | { kind: \"trace\"; signal: TraceSignal }\n | { kind: \"web-vital\"; signal: WebVitalSignal };\n\nexport type InstrumentationHandler<T> = (signal: T) => void | Promise<void>;\n\nexport type InstrumentationOptions = {\n onEvent?: InstrumentationHandler<InstrumentationEvent>;\n request?: InstrumentationHandler<RequestSignal>;\n serverStart?: InstrumentationHandler<ServerStartSignal>;\n trace?: InstrumentationHandler<TraceSignal>;\n webVitals?: InstrumentationHandler<WebVitalSignal>;\n};\n\nexport type Instrumentation = {\n request: (signal: RequestSignal) => Promise<void>;\n serverStart: (signal?: ServerStartSignal) => Promise<void>;\n trace: (signal: TraceSignal) => Promise<void>;\n reportWebVitals: (signal: WebVitalSignal) => Promise<void>;\n};\n\nexport function defineInstrumentation(\n options: InstrumentationOptions = {},\n): Instrumentation {\n return {\n async request(signal) {\n await dispatch({ kind: \"request\", signal }, options);\n },\n async serverStart(signal = {}) {\n await dispatch({ kind: \"server-start\", signal }, options);\n },\n async trace(signal) {\n await dispatch({ kind: \"trace\", signal }, options);\n },\n async reportWebVitals(signal) {\n await dispatch({ kind: \"web-vital\", signal }, options);\n },\n };\n}\n\nasync function dispatch(\n event: InstrumentationEvent,\n options: InstrumentationOptions,\n) {\n await options.onEvent?.(event);\n\n if (event.kind === \"request\") {\n await options.request?.(event.signal);\n } else if (event.kind === \"server-start\") {\n await options.serverStart?.(event.signal);\n } else if (event.kind === \"trace\") {\n await options.trace?.(event.signal);\n } else {\n await options.webVitals?.(event.signal);\n }\n}\n","import type { CspSource, RoutePolicy, RouteSecurityNeeds } from \"../security/types\";\nimport type { WebVitalName, WebVitalRating } from \"./observability\";\nimport { isObjectLike } from \"../type-guards\";\n\nexport const WEB_VITAL_NAMES: readonly WebVitalName[] = [\n \"CLS\",\n \"FCP\",\n \"FID\",\n \"INP\",\n \"LCP\",\n \"TTFB\",\n];\n\n/** The metrics the browser collector measures without a vendor script. */\nexport const COLLECTED_WEB_VITAL_NAMES: readonly WebVitalName[] = [\n \"CLS\",\n \"FCP\",\n \"INP\",\n \"LCP\",\n \"TTFB\",\n];\n\nexport type WebVitalNavigationType =\n | \"back-forward\"\n | \"back-forward-cache\"\n | \"navigate\"\n | \"prerender\"\n | \"reload\"\n | \"restore\";\n\n// Each set is read as a set of plain strings, so a guard narrows an unknown\n// value without a type assertion.\nconst METRIC_NAMES: ReadonlySet<string> = new Set(WEB_VITAL_NAMES);\n\nconst NAVIGATION_TYPES: ReadonlySet<string> = new Set<WebVitalNavigationType>([\n \"back-forward\",\n \"back-forward-cache\",\n \"navigate\",\n \"prerender\",\n \"reload\",\n \"restore\",\n]);\n\nconst RATINGS: ReadonlySet<string> = new Set<WebVitalRating>([\n \"good\",\n \"needs-improvement\",\n \"poor\",\n]);\n\nfunction isWebVitalName(value: unknown): value is WebVitalName {\n return typeof value === \"string\" && METRIC_NAMES.has(value);\n}\n\nfunction isNavigationType(value: unknown): value is WebVitalNavigationType {\n return typeof value === \"string\" && NAVIGATION_TYPES.has(value);\n}\n\nfunction isRating(value: unknown): value is WebVitalRating {\n return typeof value === \"string\" && RATINGS.has(value);\n}\n\n/**\n * One measurement of one metric. The shape is also a `WebVitalSignal`, so an\n * application can pass a report straight to `instrumentation.reportWebVitals`.\n */\nexport type WebVitalReport = {\n id: string;\n name: WebVitalName;\n navigationType: WebVitalNavigationType;\n rating: WebVitalRating;\n url: string;\n value: number;\n};\n\n/** The body the browser collector posts to the application endpoint. */\nexport type WebVitalsBeacon = {\n metrics: readonly WebVitalReport[];\n};\n\nexport type WebVitalsOptions = {\n endpoint: string;\n metrics?: readonly WebVitalName[];\n sampleRate?: number;\n};\n\n/**\n * An integration descriptor. `needs` goes into the route policy and the rest\n * configures the browser collector. The application owns the endpoint route,\n * so the framework sends no measurement to a third party.\n */\nexport type WebVitalsIntegration = {\n endpoint: string;\n kind: \"web-vitals\";\n metrics: readonly WebVitalName[];\n needs: RouteSecurityNeeds;\n sampleRate: number;\n};\n\n/**\n * The published good and poor limits for each metric. A value at the good\n * limit or below rates `good`. A value above the poor limit rates `poor`.\n * See https://web.dev/articles/defining-core-web-vitals-thresholds.\n */\nexport const WEB_VITAL_THRESHOLDS: Readonly<\n Record<WebVitalName, { good: number; poor: number }>\n> = {\n CLS: { good: 0.1, poor: 0.25 },\n FCP: { good: 1_800, poor: 3_000 },\n FID: { good: 100, poor: 300 },\n INP: { good: 200, poor: 500 },\n LCP: { good: 2_500, poor: 4_000 },\n TTFB: { good: 800, poor: 1_800 },\n};\n\n/** Rates one measurement against the published limits for its metric. */\nexport function webVitalRating(\n name: WebVitalName,\n value: number,\n): WebVitalRating {\n const threshold = WEB_VITAL_THRESHOLDS[name];\n\n if (value <= threshold.good) {\n return \"good\";\n }\n\n return value > threshold.poor ? \"poor\" : \"needs-improvement\";\n}\n\nexport type WebVitalsBeaconResult =\n | { ok: true; metrics: readonly WebVitalReport[] }\n | { ok: false; reason: WebVitalsBeaconRejection };\n\nexport type WebVitalsBeaconRejection =\n | \"invalid-payload\"\n | \"too-many-metrics\"\n | \"unreadable-body\";\n\nexport type ReadWebVitalsBeaconOptions = {\n maxMetrics?: number;\n};\n\nconst defaultMaxMetrics = 32;\n\n/**\n * Describes the beacon endpoint and the metrics to collect. The endpoint is a\n * same-origin path or an HTTPS URL. A same-origin path needs `'self'` in\n * `connect-src`, which `webVitalsPolicy` contributes.\n */\nexport function defineWebVitals(options: WebVitalsOptions): WebVitalsIntegration {\n const endpoint = parseBeaconEndpoint(options.endpoint);\n const metrics = parseMetricNames(options.metrics);\n const sampleRate = parseSampleRate(options.sampleRate);\n\n return {\n endpoint: endpoint.url,\n kind: \"web-vitals\",\n metrics,\n needs: { connect: [endpoint.source] },\n sampleRate,\n };\n}\n\n/** Merges the CSP needs of every integration into one route policy. */\nexport function webVitalsPolicy(\n ...integrations: readonly WebVitalsIntegration[]\n): RoutePolicy {\n const connect = new Set<CspSource>();\n\n for (const integration of integrations) {\n for (const source of integration.needs.connect ?? []) {\n connect.add(source);\n }\n }\n\n if (connect.size === 0) {\n return { security: { needs: {} } };\n }\n\n return { security: { needs: { connect: [...connect] } } };\n}\n\n/**\n * Reads and validates a beacon body on the server. The result carries only\n * reports that match the contract, so a handler never forwards unchecked\n * browser input to a metrics backend.\n */\nexport async function readWebVitalsBeacon(\n request: Request,\n options: ReadWebVitalsBeaconOptions = {},\n): Promise<WebVitalsBeaconResult> {\n const maxMetrics = options.maxMetrics ?? defaultMaxMetrics;\n let payload: unknown;\n\n try {\n payload = await request.json();\n } catch {\n return { ok: false, reason: \"unreadable-body\" };\n }\n\n return parseWebVitalsBeacon(payload, maxMetrics);\n}\n\n/** The synchronous half of `readWebVitalsBeacon`, for an already parsed body. */\nexport function parseWebVitalsBeacon(\n payload: unknown,\n maxMetrics: number = defaultMaxMetrics,\n): WebVitalsBeaconResult {\n if (!isObjectLike(payload) || !Array.isArray(payload.metrics)) {\n return { ok: false, reason: \"invalid-payload\" };\n }\n\n if (payload.metrics.length > maxMetrics) {\n return { ok: false, reason: \"too-many-metrics\" };\n }\n\n const metrics: WebVitalReport[] = [];\n\n for (const entry of payload.metrics) {\n const report = parseWebVitalReport(entry);\n\n if (!report) {\n return { ok: false, reason: \"invalid-payload\" };\n }\n\n metrics.push(report);\n }\n\n return { metrics, ok: true };\n}\n\nfunction parseWebVitalReport(entry: unknown): WebVitalReport | undefined {\n if (!isObjectLike(entry)) {\n return undefined;\n }\n\n const { id, name, navigationType, rating, url, value } = entry;\n\n if (typeof id !== \"string\" || id.length === 0 || id.length > 128) {\n return undefined;\n }\n\n if (!isWebVitalName(name) || !isNavigationType(navigationType)) {\n return undefined;\n }\n\n if (!isRating(rating)) {\n return undefined;\n }\n\n if (typeof url !== \"string\" || url.length === 0 || url.length > 2048) {\n return undefined;\n }\n\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n return undefined;\n }\n\n return { id, name, navigationType, rating, url, value };\n}\n\n// The endpoint is either a same-origin path or an HTTPS collector URL. A\n// same-origin path is already covered by `'self'`, so the CSP source differs.\nfunction parseBeaconEndpoint(\n endpoint: string,\n): { source: CspSource; url: string } {\n if (endpoint.startsWith(\"/\")) {\n if (endpoint.startsWith(\"//\")) {\n throw new Error(\n \"The web vitals endpoint must not be a scheme-relative URL.\",\n );\n }\n\n return { source: \"'self'\", url: endpoint };\n }\n\n let url: URL;\n\n try {\n url = new URL(endpoint);\n } catch {\n throw new Error(\n \"The web vitals endpoint must be a same-origin path or an absolute URL.\",\n );\n }\n\n if (url.protocol !== \"https:\") {\n throw new Error(\"The web vitals endpoint must use HTTPS.\");\n }\n\n return { source: url.origin, url: url.href };\n}\n\nfunction parseMetricNames(metrics: readonly WebVitalName[] | undefined) {\n if (!metrics) {\n return COLLECTED_WEB_VITAL_NAMES;\n }\n\n const selected: WebVitalName[] = [];\n\n for (const metric of metrics) {\n if (!COLLECTED_WEB_VITAL_NAMES.includes(metric)) {\n throw new Error(\n `The browser collector does not measure ${JSON.stringify(metric)}. Demiurge collects ${COLLECTED_WEB_VITAL_NAMES.join(\", \")}.`,\n );\n }\n\n if (!selected.includes(metric)) {\n selected.push(metric);\n }\n }\n\n if (selected.length === 0) {\n throw new Error(\"A web vitals integration must collect one metric or more.\");\n }\n\n return selected;\n}\n\nfunction parseSampleRate(sampleRate: number | undefined) {\n if (sampleRate === undefined) {\n return 1;\n }\n\n if (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) {\n throw new Error(\"The web vitals sample rate must be between 0 and 1.\");\n }\n\n return sampleRate;\n}\n","import { useEffect } from \"react\";\nimport type { WebVitalName } from \"./observability\";\nimport {\n webVitalRating,\n type WebVitalNavigationType,\n type WebVitalReport,\n type WebVitalsBeacon,\n type WebVitalsIntegration,\n} from \"./web-vitals\";\n\nexport type WebVitalsTransport = (\n endpoint: string,\n beacon: WebVitalsBeacon,\n) => void;\n\nexport type CollectWebVitalsOptions = {\n onReport?: (report: WebVitalReport) => void;\n random?: () => number;\n transport?: WebVitalsTransport;\n};\n\nexport type WebVitalsProps = {\n integration: WebVitalsIntegration;\n onReport?: (report: WebVitalReport) => void;\n transport?: WebVitalsTransport;\n};\n\n// A layout shift stays in the current session window while it starts less than\n// one second after the last shift. The window also ends five seconds after its\n// first shift. The reported value is the largest window.\nconst sessionGapMs = 1_000;\nconst sessionWindowMs = 5_000;\n\n// An interaction shorter than this cannot become the reported INP value, and\n// the browser does not have to buffer it.\nconst interactionDurationThresholdMs = 40;\n\ntype LayoutShiftEntry = PerformanceEntry & {\n hadRecentInput: boolean;\n value: number;\n};\n\ntype NavigationEntry = PerformanceEntry & {\n responseStart: number;\n type: string;\n};\n\n/**\n * Measures Core Web Vitals in the browser and posts them to the endpoint of\n * the integration. The collector uses `PerformanceObserver` only, so no inline\n * script and no vendor script is involved, and a strict policy needs no\n * `script-src` source for it.\n *\n * The returned function stops every observer and sends nothing more.\n */\nexport function collectWebVitals(\n integration: WebVitalsIntegration,\n options: CollectWebVitalsOptions = {},\n): () => void {\n if (typeof window === \"undefined\" || typeof PerformanceObserver === \"undefined\") {\n return () => undefined;\n }\n\n const random = options.random ?? Math.random;\n\n if (integration.sampleRate < 1 && random() >= integration.sampleRate) {\n return () => undefined;\n }\n\n const transport = options.transport ?? sendWebVitalsBeacon;\n const wanted = new Set(integration.metrics);\n const observers: PerformanceObserver[] = [];\n const pending: WebVitalReport[] = [];\n const reported = new Set<WebVitalName>();\n let navigationType = readNavigationType();\n let clsValue = 0;\n let sessionValue = 0;\n let sessionFirst = 0;\n let sessionLast = 0;\n let lcpValue: number | undefined;\n let inpValue: number | undefined;\n let stopped = false;\n\n const report = (name: WebVitalName, value: number) => {\n if (stopped || reported.has(name)) {\n return;\n }\n\n reported.add(name);\n\n const entry: WebVitalReport = {\n id: `${name}-${Date.now()}-${Math.floor(random() * 1_000_000_000)}`,\n name,\n navigationType,\n rating: webVitalRating(name, value),\n url: window.location.href,\n value: Math.round(value * 1_000) / 1_000,\n };\n\n pending.push(entry);\n options.onReport?.(entry);\n };\n\n const flush = () => {\n if (stopped) {\n return;\n }\n\n if (lcpValue !== undefined) {\n report(\"LCP\", lcpValue);\n }\n\n if (inpValue !== undefined) {\n report(\"INP\", inpValue);\n }\n\n if (wanted.has(\"CLS\")) {\n report(\"CLS\", clsValue);\n }\n\n if (pending.length === 0) {\n return;\n }\n\n const metrics = pending.splice(0, pending.length);\n\n transport(integration.endpoint, { metrics });\n };\n\n const onVisibilityChange = () => {\n if (document.visibilityState === \"hidden\") {\n flush();\n }\n };\n\n // A page restored from the back-forward cache reuses its JavaScript\n // context, so the effect that started this collector never reruns. A\n // restored view would report nothing without this listener. Reset the\n // accumulators and tag the next report with the restore, the same way the\n // Navigation Timing entry names a real reload.\n const onPageShow = (event: PageTransitionEvent) => {\n if (!event.persisted) {\n return;\n }\n\n navigationType = \"back-forward-cache\";\n reported.clear();\n clsValue = 0;\n sessionValue = 0;\n sessionFirst = 0;\n sessionLast = 0;\n lcpValue = undefined;\n inpValue = undefined;\n\n // No new \"first-contentful-paint\" entry fires after a restore, because the\n // browser did not repaint from a blank page. Report the restore itself as\n // the paint moment, which is what a person actually experienced.\n if (wanted.has(\"FCP\")) {\n report(\"FCP\", performance.now() - event.timeStamp);\n }\n };\n\n if (wanted.has(\"TTFB\")) {\n const navigation = readNavigationEntry();\n\n if (navigation && navigation.responseStart > 0) {\n report(\"TTFB\", navigation.responseStart);\n }\n }\n\n if (wanted.has(\"FCP\")) {\n observe(observers, { buffered: true, type: \"paint\" }, (entries) => {\n for (const entry of entries) {\n if (entry.name === \"first-contentful-paint\") {\n report(\"FCP\", entry.startTime);\n }\n }\n });\n }\n\n if (wanted.has(\"LCP\")) {\n observe(\n observers,\n { buffered: true, type: \"largest-contentful-paint\" },\n (entries) => {\n const last = entries.at(-1);\n\n if (last) {\n lcpValue = last.startTime;\n }\n },\n );\n }\n\n if (wanted.has(\"CLS\")) {\n observe(observers, { buffered: true, type: \"layout-shift\" }, (entries) => {\n for (const shift of entries) {\n // TYPE-EVIDENCE: the observer subscribes to the layout-shift entry\n // type, so the browser delivers LayoutShift entries here. The cast\n // adds the two fields that lib.dom does not declare.\n const entry = shift as LayoutShiftEntry;\n\n if (entry.hadRecentInput) {\n continue;\n }\n\n const withinSession =\n sessionValue > 0 &&\n entry.startTime - sessionLast < sessionGapMs &&\n entry.startTime - sessionFirst < sessionWindowMs;\n\n if (withinSession) {\n sessionValue += entry.value;\n } else {\n sessionValue = entry.value;\n sessionFirst = entry.startTime;\n }\n\n sessionLast = entry.startTime;\n clsValue = Math.max(clsValue, sessionValue);\n }\n });\n }\n\n // The published metric is close to the 98th percentile of every\n // interaction on the page. It takes the single slowest interaction while\n // the page has 50 or fewer, then a less extreme rank as the count grows.\n // One outlier does not fix the score at its worst for the rest of the\n // visit. Ranking by percentile needs each interaction grouped by its\n // browser-assigned `interactionId`. Chrome increments that value by 7 per\n // interaction, an internal detail the specification does not guarantee.\n // This collector reports the plain maximum instead. That value matches\n // the published metric on a typical content page, and reports a worse\n // number on an interaction-heavy page or a long session. An application\n // that needs the published percentile can call\n // `instrumentation.reportWebVitals` with the output of the `web-vitals`\n // npm package instead of `defineWebVitals`.\n if (wanted.has(\"INP\")) {\n observe(\n observers,\n {\n buffered: true,\n durationThreshold: interactionDurationThresholdMs,\n type: \"event\",\n },\n (entries) => {\n for (const entry of entries) {\n inpValue = Math.max(inpValue ?? 0, entry.duration);\n }\n },\n );\n }\n\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"pagehide\", flush);\n window.addEventListener(\"pageshow\", onPageShow);\n\n return () => {\n flush();\n stopped = true;\n\n for (const observer of observers) {\n observer.disconnect();\n }\n\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"pagehide\", flush);\n window.removeEventListener(\"pageshow\", onPageShow);\n };\n}\n\n/**\n * Starts the browser collector for the lifetime of the component. Put it in a\n * layout so that every page of the application reports.\n */\nexport function WebVitals({ integration, onReport, transport }: WebVitalsProps) {\n useEffect(\n () => collectWebVitals(integration, { onReport, transport }),\n [integration, onReport, transport],\n );\n\n return null;\n}\n\n/**\n * Posts one beacon. `navigator.sendBeacon` survives a page that unloads. When\n * the browser refuses the beacon, a `keepalive` fetch takes its place.\n */\nexport function sendWebVitalsBeacon(\n endpoint: string,\n beacon: WebVitalsBeacon,\n): void {\n const body = JSON.stringify(beacon);\n\n if (typeof navigator !== \"undefined\" && typeof navigator.sendBeacon === \"function\") {\n const blob = new Blob([body], { type: \"application/json\" });\n\n if (navigator.sendBeacon(endpoint, blob)) {\n return;\n }\n }\n\n void fetch(endpoint, {\n body,\n headers: { \"content-type\": \"application/json\" },\n keepalive: true,\n method: \"POST\",\n }).catch(() => undefined);\n}\n\n// A browser that does not support an entry type throws on `observe`. The\n// collector then reports the metrics it can measure instead of failing.\nfunction observe(\n observers: PerformanceObserver[],\n init: PerformanceObserverInit & { durationThreshold?: number; type: string },\n handle: (entries: PerformanceEntryList) => void,\n) {\n try {\n const observer = new PerformanceObserver((list) => handle(list.getEntries()));\n\n observer.observe(init);\n observers.push(observer);\n } catch {\n return;\n }\n}\n\nfunction readNavigationEntry(): NavigationEntry | undefined {\n if (typeof performance === \"undefined\") {\n return undefined;\n }\n\n // TYPE-EVIDENCE: the browser returns PerformanceNavigationTiming entries for\n // the navigation entry type. The cast adds the two fields this file reads.\n return performance.getEntriesByType(\"navigation\")[0] as\n | NavigationEntry\n | undefined;\n}\n\nfunction readNavigationType(): WebVitalNavigationType {\n const navigation = readNavigationEntry();\n\n if (navigation?.type === \"back_forward\") {\n return \"back-forward\";\n }\n\n if (navigation?.type === \"reload\" || navigation?.type === \"prerender\") {\n return navigation.type;\n }\n\n return \"navigate\";\n}\n"],"names":["defineSitemap","entries","entry","normalizeSitemapAlternates","alternates","byLanguage","byUrl","alternate","language","href","previousHref","previousLanguage","hrefLang","renderSitemap","sitemap","renderSitemapEntry","defineRobots","options","defineOgImage","renderRobots","robots","lines","rule","userAgent","toArray","allow","disallow","renderOgImageSvg","image","width","height","background","foreground","title","clampText","subtitle","brand","validateOgImageDimensions","escapeXmlAttribute","escapeXml","line","renderOgImageResponse","IMMUTABLE_FILE_CACHE_CONTROL","formatLastModified","formatPriority","value","priority","maxLength","defaultIdempotencyTtl","defaultMaximumEntries","createMemoryIdempotencyStore","now","defaultTtl","maximumEntries","defaultTtlMs","parseCacheDuration","request","key","serializeCacheKey","currentTime","sweepExpiredIdempotencyEntries","existing","stored","cloneIdempotencyResult","evictOldestCompletedIdempotencyEntry","result","error","runIdempotentMutation","store","page","defineMiddleware","middleware","webhook","context","rawBody","signature","verifyHmacSignature","suppliedSignature","algorithm","encoding","normalized","normalizeSignature","decodeSignature","configuredPrefix","trimmed","prefix","pair","binary","character","namePattern","prefixes","maxCookieBytes","secureCookieName","name","scope","validateSecureCookie","declaration","issues","report","code","message","size","serialize","readSecureCookie","reference","definition","parseCookieHeader","createSecureCookie","issue","attributes","path","defaultAbsoluteExpirationMs","defaultIdleExpirationMs","sessionIdentifierBytes","createSignedCookieSession","resolved","resolveOptions","createCookieSessionManager","signedCodec","createEncryptedCookieSession","encryptedCodec","codec","cookieName","rawCookie","decoded","record","destroyCookie","dirty","isExpired","requireRecord","setRecord","next","cloneRecord","destroyedCookie","data","createOptions","createdAt","absoluteExpirationMs","validateLifetime","idleExpirationMs","validateIdleLifetime","expiresAt","cloneData","randomIdentifier","current","keys","validateKeys","secureRandomBytes","identifiers","parts","keyIndex","payload","decodeBase64Url","cryptoKey","toArrayBuffer","encodeText","parseRecord","encodeBase64Url","unsigned","randomBytes","nonce","ciphertext","importEncryptionKey","plaintext","bytes","isPlainObject","isSafeTimestamp","isNonNegativeInteger","isSessionData","cookie","length","byte","padding","SessionStoreConflictError","operation","SessionStoreUnavailableError","createSessionManager","input","verifyIdentifier","renewed","withoutVersion","accept","signIdentifier","candidate","id","_version","createSecurityReportHandler","contentTypeResponse","enforceReportContentType","bodySizeResponse","enforceReportBodySize","limitRequestBody","RequestBodyTooLargeError","reports","normalizeSecurityReports","index","supportedReportContentTypes","mediaType","contentLength","declaredSize","parseBodySize","isObjectLike","validateUploads","formData","policy","files","totalSize","field","filePolicy","fieldFiles","isFile","file","validateFile","isAllowedFileType","type","allowedTypes","allowedType","checkWebSocketOrigin","origin","normalizedOrigin","normalizeOrigin","allowed","isAllowedOrigin","enforceWebSocketOrigin","allowedOrigin","originMatches","actualOrigin","schemeSeparator","authority","url","RouteFocusContext","createContext","useRouteFocusBoundary","registration","useContext","cleanup","useRef","ref","useCallback","element","useMemo","RouteFocusBoundary","props","as","children","elementProps","boundary","composedRef","assignRef","createElement","mutationFormActionMetadata","mutationRouter","pendingMutationControllers","registerMutationRouter","router","abortMutationActions","except","controller","createMutationAction","previousState","invocation","submitMutation","destination","validateMutationRedirect","mutationFailure","useMutationAction","initialState","mutation","state","dispatch","pending","useActionState","action","branded","mutationFormActionDetails","performMutationRequest","response","MUTATION_RESPONSE_MEDIA_TYPE","MUTATION_REQUEST_HEADER","MUTATION_REQUEST_VALUE","readMutationResult","parameters","mutationType","hasOnlyKeys","isJsonValue","malformedResult","isMutationValidation","location","isMutationValidationIssue","part","createFileRouter","manifest","createRouteManifest","navigationDataLoader","loadNavigationData","setLocation","useState","getCurrentLocation","locale","setLocale","routePathname","applicationPathname","lastLocation","match","setMatch","initialMatchPending","initialNavigationPending","navigationSequence","routeLoadController","routeLoadCause","submissionControllers","submissionStates","submissionVersion","setSubmissionVersion","routeRefresh","setRouteRefresh","routeRefreshWaiters","resolvedRouteVersion","setResolvedRouteVersion","navigationKind","pendingCommit","setPendingCommit","committed","setCommitted","pendingCommitRef","pendingScroll","pendingPopPosition","activeHistoryEntry","restoringScroll","scrollPositions","boundaryRegistrations","nextBoundaryOrder","saveCurrentScrollPosition","position","currentScrollPosition","rememberScrollPosition","focusRegistration","active","left","right","useLayoutEffect","ensureNavigationStatusRegion","useEffect","resolve","abortSubmissions","changed","supersedeRouteLoad","previousRestoration","ensureHistoryEntry","onScroll","onPopState","readScrollPosition","previous","scrollToHash","cancelled","settled","sequence","cause","isCurrent","getMatchPathname","initialNavigation","loadLoadingFallback","Loading","initialData","responseUrl","responseLocale","resolveLocale","loadPageRoute","nextMatch","applyNavigationDocument","canonicalLocation","ErrorFallback","loadErrorFallback","navigationDocument","navigationErrorDocuments","applyNavigationScroll","announceNavigation","setSubmissionState","releaseMutationNavigation","form","submissionKey","mutationSubmissionKey","to","createHistoryEntry","withHistoryEntry","submitter","createMutationRequest","history","RouterContext","RouteRenderer","settleRouteRefreshes","isHydratableMatch","root","fallback","HYDRATION_FALLBACK_ATTRIBUTE","hydrateFileRouter","readInitialRouteData","hydratable","Router","createRoot","hydrateRoot","resolveReactDomClient","HYDRATION_ROOT_ATTRIBUTE","startDeferredScripts","module","client","LinkImplementation","useRouter","download","_hash","_locale","onClick","_path","reloadDocument","replace","_search","target","_to","anchorProps","baseHref","explicitLocale","localizeHref","jsx","event","shouldHandleLinkClick","Link","MutationFormContext","Form","routerRef","generatedKey","useId","formKey","formRef","hydrated","useHydratedFormAction","progressiveAction","progressiveDetails","enhanceProgressiveAction","onSubmit","applicationHandler","canInterceptMutation","_submissionKey","formProps","localizedAction","MutationSubmit","details","enhance","setHydrated","useNavigation","contextKey","useFormNavigation","NotFound","onRenderError","onCommitted","onRouteCommitted","AppLoading","AppNotFound","BuiltInNotFound","Fragment","Layout","NavigationCommitMarker","errorStatus","layouts","pathname","pageElement","routeElement","RouteErrorBoundary","commit","onCommit","signaled","signaledRouteVersion","Component","previousProps","isHttpError","SCROLL_STATE_KEY","HISTORY_ENTRY_STATE_KEY","nextHistoryEntry","readHistoryEntry","activeEntry","nextState","option","x","y","headers","NAVIGATION_DATA_HEADER","NAVIGATION_DATA_REQUEST","kind","NAVIGATION_DATA_RESPONSE","NAVIGATION_NOT_FOUND_RESPONSE","readNavigationPayload","NAVIGATION_ERROR_RESPONSE","status","HTTP_ERROR_STATUSES","httpError","formIds","nextFormId","formSubmissionOptions","enctype","method","body","isSupportedMutationSubmitter","button","submitterFormAttribute","hash","announce","announceNavigationRegion","updateNavigationStatus","Image","className","plan","planImageTransform","sentryLoaderHost","analytics","domain","normalizeDomain","endpoint","parseEndpoint","script","dsn","parseSentryDsn","loader","parseHttpsOrigin","integrations","needs","integration","need","sources","parseAbsoluteEndpoint","label","projectId","defineInstrumentation","signal","WEB_VITAL_NAMES","COLLECTED_WEB_VITAL_NAMES","METRIC_NAMES","NAVIGATION_TYPES","RATINGS","isWebVitalName","isNavigationType","isRating","WEB_VITAL_THRESHOLDS","webVitalRating","threshold","defaultMaxMetrics","defineWebVitals","parseBeaconEndpoint","metrics","parseMetricNames","sampleRate","parseSampleRate","webVitalsPolicy","connect","source","readWebVitalsBeacon","maxMetrics","parseWebVitalsBeacon","parseWebVitalReport","navigationType","rating","selected","metric","sessionGapMs","sessionWindowMs","interactionDurationThresholdMs","collectWebVitals","random","transport","sendWebVitalsBeacon","wanted","observers","reported","readNavigationType","clsValue","sessionValue","sessionFirst","sessionLast","lcpValue","inpValue","stopped","flush","onVisibilityChange","onPageShow","navigation","readNavigationEntry","observe","last","shift","observer","WebVitals","onReport","beacon","blob","init","handle","list"],"mappings":";;;;;;;;;;;;;AAkDO,SAASA,GAAcC,GAA2C;AACvE,SAAO;AAAA,IACL,SAASA,EAAQ,IAAI,CAACC,OAAW;AAAA,MAC/B,GAAGA;AAAA,MACH,YAAYC,GAA2BD,EAAM,cAAc,CAAA,CAAE;AAAA,IAAA,EAC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