prunelle 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,27 @@
1
+ // A request body read as string fields, for plugin routes that take a form or a JSON object.
2
+
3
+ /**
4
+ * The string fields of a JSON object, urlencoded or multipart body, the last of a repeated name winning.
5
+ * Files, numbers, arrays and nested objects are dropped, and any other content type gives no field.
6
+ * The record has no prototype, so `__proto__` and `constructor` are plain fields. A malformed body throws.
7
+ */
8
+ export async function readStringFields(request: Request): Promise<Record<string, string>> {
9
+ const fields: Record<string, string> = Object.create(null)
10
+ const contentType = (request.headers.get('content-type') ?? '').toLowerCase()
11
+ if (contentType.includes('application/json')) {
12
+ const raw: unknown = await request.json()
13
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
14
+ return fields
15
+ for (const [name, value] of Object.entries(raw)) {
16
+ if (typeof value === 'string')
17
+ fields[name] = value
18
+ }
19
+ }
20
+ else if (contentType.includes('application/x-www-form-urlencoded') || contentType.includes('multipart/form-data')) {
21
+ for (const [name, value] of (await request.formData()).entries()) {
22
+ if (typeof value === 'string')
23
+ fields[name] = value
24
+ }
25
+ }
26
+ return fields
27
+ }
@@ -0,0 +1,73 @@
1
+ // A request path, percent-decoded once for every lookup: the asset, public and prerendered maps, the middleware scopes, and the routers with their params.
2
+
3
+ const UNSAFE_ENCODED_RE = /%(?:2f|5c|00)/i
4
+
5
+ class DecodedPath {
6
+ #segments: readonly string[] | undefined
7
+
8
+ constructor(
9
+ /** Every segment decoded; undefined when one encodes a separator or NUL, so no file, page or prerendered lookup can match it. */
10
+ readonly staticPath: string | undefined,
11
+ /** Safe segments decoded and the others left encoded, so encoding a letter cannot step past a middleware scope. */
12
+ readonly scopedPath: string,
13
+ /** Indexes in `segments` of those left encoded. */
14
+ readonly encoded: ReadonlySet<number> | undefined,
15
+ segments?: readonly string[],
16
+ ) {
17
+ this.#segments = segments
18
+ }
19
+
20
+ /** The segments of `scopedPath` after its leading slash, one trailing slash dropped. */
21
+ get segments(): readonly string[] {
22
+ if (this.#segments === undefined) {
23
+ const path = this.scopedPath.length > 1 && this.scopedPath.endsWith('/') ? this.scopedPath.slice(0, -1) : this.scopedPath
24
+ this.#segments = path === '/' ? [] : path.slice(1).split('/')
25
+ }
26
+ return this.#segments
27
+ }
28
+ }
29
+
30
+ export type RequestPath = DecodedPath
31
+
32
+ /** Decodes a URL pathname segment by segment; undefined for a malformed escape, which the server answers 400. */
33
+ export function decodeRequestPath(pathname: string): RequestPath | undefined {
34
+ if (!pathname.includes('%'))
35
+ return new DecodedPath(pathname, pathname, undefined)
36
+ const parts = pathname.split('/')
37
+ let encoded: Set<number> | undefined
38
+ for (let i = 1; i < parts.length; i++) {
39
+ const part = parts[i]!
40
+ if (!part.includes('%'))
41
+ continue
42
+ let decoded: string
43
+ try {
44
+ decoded = decodeURIComponent(part)
45
+ }
46
+ catch {
47
+ return undefined
48
+ }
49
+ if (UNSAFE_ENCODED_RE.test(part))
50
+ (encoded ??= new Set()).add(i - 1)
51
+ else
52
+ parts[i] = decoded
53
+ }
54
+ const scopedPath = parts.join('/')
55
+ return new DecodedPath(encoded === undefined ? scopedPath : undefined, scopedPath, encoded)
56
+ }
57
+
58
+ /** A path prunelle already holds decoded, such as a route's or a public file's, taken as it is. */
59
+ export function literalPath(path: string): RequestPath {
60
+ return new DecodedPath(path, path, undefined)
61
+ }
62
+
63
+ /** The path made of the first `count` segments of `path`. */
64
+ export function pathPrefix(path: RequestPath, count: number): RequestPath {
65
+ const segments = path.segments.slice(0, count)
66
+ const joined = `/${segments.join('/')}`
67
+ let encoded: Set<number> | undefined
68
+ for (const index of path.encoded ?? []) {
69
+ if (index < count)
70
+ (encoded ??= new Set()).add(index)
71
+ }
72
+ return new DecodedPath(encoded === undefined ? joined : undefined, joined, encoded, segments)
73
+ }
@@ -0,0 +1,22 @@
1
+ // The request a server action called from server code runs in, entered by the action registry on the dynamic path only.
2
+
3
+ import type { ActionRegistry } from './action-registry'
4
+ import type { RequestContext } from './http'
5
+ import { AsyncLocalStorage } from 'node:async_hooks'
6
+
7
+ export interface RequestScope {
8
+ ctx: RequestContext
9
+ actions: ActionRegistry
10
+ }
11
+
12
+ const STORAGE_KEY = Symbol.for('pru.requestScope')
13
+ // One storage per process: a test's own copy of prunelle and the app's bundled one must see the same request.
14
+ const storage: AsyncLocalStorage<RequestScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RequestScope> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RequestScope>())
15
+
16
+ export function runInRequest<T>(scope: RequestScope, fn: () => T): T {
17
+ return storage.run(scope, fn)
18
+ }
19
+
20
+ export function currentRequest(): RequestScope | undefined {
21
+ return storage.getStore()
22
+ }
@@ -0,0 +1,541 @@
1
+ // Bounded in-memory route response cache with stale-while-revalidate (SWR) and per-encoding compression reuse.
2
+
3
+ import type { CompressionCache, CompressionEncoding } from './compress'
4
+ import type { RequestContext } from './http'
5
+ import { ACTION_ERROR_COOKIE } from './action'
6
+ import { markCompressionHandled, mergeVaryValue, pickEncoding } from './compress'
7
+ import { etagMatches } from './http'
8
+ import { hasRegionHeader } from './region'
9
+
10
+ export interface RouteCacheSpec {
11
+ /** Fresh lifetime in milliseconds. */
12
+ maxAgeMs: number
13
+ /** Stale-while-revalidate window in milliseconds (defaults to `maxAgeMs`). */
14
+ swrMs: number
15
+ /** Normalized `Cache-Control` header value (`public, s-maxage=..., stale-while-revalidate=...`). */
16
+ cacheControl: string
17
+ }
18
+
19
+ export interface RouteCacheOptions {
20
+ /** Maximum cached responses kept in memory (default: 500). */
21
+ maxEntries?: number | undefined
22
+ /** Maximum total bytes across cached responses and their compressed variants (default: 32 MiB). */
23
+ maxBytes?: number | undefined
24
+ /** Backoff cooldown in milliseconds after a failed SWR revalidation before retrying (default: 5000). */
25
+ failureCooldownMs?: number | undefined
26
+ }
27
+
28
+ export interface RouteCacheSingleflightResult {
29
+ entry: CachedRouteEntry | undefined
30
+ html: string
31
+ headers: Record<string, string>
32
+ }
33
+
34
+ export interface CachedRouteEntry {
35
+ /** The key it is stored under, so a holder can tell whether it is still the stored entry. */
36
+ key: string
37
+ html: string
38
+ bytes: number
39
+ headers: Record<string, string>
40
+ createdAt: number
41
+ freshUntil: number
42
+ staleUntil: number
43
+ spec: RouteCacheSpec
44
+ /** Weak validator of `html`, so a revisit can get a 304. */
45
+ etag: string
46
+ compressed: Partial<Record<CompressionEncoding, Uint8Array<ArrayBuffer> | null>>
47
+ }
48
+
49
+ export type RouteCacheLookup =
50
+ | { status: 'fresh', entry: CachedRouteEntry }
51
+ | { status: 'stale', entry: CachedRouteEntry }
52
+
53
+ const DEFAULT_MAX_ENTRIES = 500
54
+ const DEFAULT_MAX_BYTES = 32 * 1024 * 1024
55
+ const DEFAULT_FAILURE_COOLDOWN_MS = 5_000
56
+ const MIN_COMPRESS_BYTES = 256
57
+ const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i
58
+ // Campaign and click identifiers: they change who is counted, never what the page shows.
59
+ const TRACKING_PARAM_RE = /^(?:utm_.+|gclid|gbraid|wbraid|dclid|fbclid|msclkid|mc_cid|mc_eid)$/
60
+ const TRACKING_SEARCH_RE = /[?&](?:utm_|(?:gclid|gbraid|wbraid|dclid|fbclid|msclkid|mc_cid|mc_eid)(?:[=&]|$))/
61
+
62
+ const UNIT_MS: Record<string, number> = {
63
+ ms: 1,
64
+ s: 1000,
65
+ m: 60_000,
66
+ h: 3_600_000,
67
+ d: 86_400_000,
68
+ }
69
+
70
+ /** Parses a duration string (`'500ms'`, `'30s'`, `'5m'`, `'1h'`, `'1d'`) or number of seconds into milliseconds. */
71
+ export function parseCacheDuration(value: unknown, allowZero = false): number | undefined {
72
+ if (typeof value === 'number') {
73
+ if (!Number.isFinite(value) || (allowZero ? value < 0 : value <= 0))
74
+ return undefined
75
+ return Math.round(value * 1000)
76
+ }
77
+ if (typeof value !== 'string')
78
+ return undefined
79
+ const match = DURATION_RE.exec(value.trim())
80
+ if (match === null)
81
+ return undefined
82
+ const amount = Number(match[1])
83
+ const unit = UNIT_MS[match[2]!.toLowerCase()]
84
+ if (!Number.isFinite(amount) || unit === undefined)
85
+ return undefined
86
+ const ms = Math.round(amount * unit)
87
+ if (!Number.isFinite(ms) || (allowZero ? ms < 0 : ms <= 0))
88
+ return undefined
89
+ return ms
90
+ }
91
+
92
+ /** Formats milliseconds into the cleanest short duration token (`1h`, `30s`, `500ms`). */
93
+ export function formatCacheDuration(ms: number): string {
94
+ if (ms === 0)
95
+ return '0s'
96
+ if (ms % 86_400_000 === 0)
97
+ return `${ms / 86_400_000}d`
98
+ if (ms % 3_600_000 === 0)
99
+ return `${ms / 3_600_000}h`
100
+ if (ms % 60_000 === 0)
101
+ return `${ms / 60_000}m`
102
+ if (ms % 1000 === 0)
103
+ return `${ms / 1000}s`
104
+ return `${ms}ms`
105
+ }
106
+
107
+ /** The `Cache-Control` of a cached route under an app `_middleware.ts`: the middleware may gate it, so only the server's own cache, behind the middleware, keeps the render. */
108
+ export const GATED_ROUTE_CACHE_CONTROL = 'private, no-cache'
109
+
110
+ /** Builds a normalized `RouteCacheSpec` with its `Cache-Control` header value. */
111
+ export function buildRouteCacheSpec(maxAgeMs: number, swrMs: number = maxAgeMs): RouteCacheSpec {
112
+ const maxAgeSec = Math.max(1, Math.round(maxAgeMs / 1000))
113
+ const swrSec = swrMs === 0 ? 0 : Math.max(1, Math.round(swrMs / 1000))
114
+ return {
115
+ maxAgeMs,
116
+ swrMs,
117
+ cacheControl: `public, s-maxage=${maxAgeSec}, stale-while-revalidate=${swrSec}`,
118
+ }
119
+ }
120
+
121
+ /** Formats a `RouteCacheSpec` concisely for `prunelle inspect`. */
122
+ export function formatCacheSpec(spec: RouteCacheSpec): string {
123
+ const maxAge = formatCacheDuration(spec.maxAgeMs)
124
+ if (spec.swrMs === spec.maxAgeMs)
125
+ return maxAge
126
+ return `${maxAge},swr=${formatCacheDuration(spec.swrMs)}`
127
+ }
128
+
129
+ /** Returns a copy of `headers` with `cache-control` set to `cacheControl`. */
130
+ export function withCacheControl(headers: Record<string, string>, cacheControl: string): Record<string, string> {
131
+ return { ...headers, 'cache-control': cacheControl }
132
+ }
133
+
134
+ /** Builds a host-scoped cache key so multi-domain deployments never poison one host from another; tracking parameters are left out, so a campaign link reuses the page. */
135
+ export function routeCacheKey(url: URL): string {
136
+ if (!TRACKING_SEARCH_RE.test(url.search))
137
+ return `${url.host}${url.pathname}${url.search}`
138
+ const kept: string[] = []
139
+ for (const part of url.search.slice(1).split('&')) {
140
+ if (part.length === 0)
141
+ continue
142
+ const eq = part.indexOf('=')
143
+ const name = eq === -1 ? part : part.slice(0, eq)
144
+ if (!TRACKING_PARAM_RE.test(name))
145
+ kept.push(part)
146
+ }
147
+ return `${url.host}${url.pathname}${kept.length === 0 ? '' : `?${kept.join('&')}`}`
148
+ }
149
+
150
+ function weakEtagOf(html: string): string {
151
+ return `W/"${Bun.hash(html).toString(36)}"`
152
+ }
153
+
154
+ /** Whether a request is eligible to read from or populate the shared route cache. */
155
+ export function isCacheableRequest(request: Request): boolean {
156
+ if (request.method !== 'GET' && request.method !== 'HEAD')
157
+ return false
158
+ if (hasRegionHeader(request))
159
+ return false
160
+ const cookie = request.headers.get('cookie')
161
+ if (cookie !== null && cookie.includes(`${ACTION_ERROR_COOKIE}=`))
162
+ return false
163
+ return true
164
+ }
165
+
166
+ function compressCachedHtml(html: string, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
167
+ const rawSize = Buffer.byteLength(html, 'utf8')
168
+ if (rawSize < MIN_COMPRESS_BYTES)
169
+ return null
170
+ const buf = (encoding === 'zstd' ? Bun.zstdCompressSync(html, { level: 3 }) : Bun.gzipSync(html, { level: 6 })) as Uint8Array<ArrayBuffer>
171
+ return buf.byteLength < rawSize ? buf : null
172
+ }
173
+
174
+ /** Bounded LRU cache for rendered HTML routes with stale-while-revalidate deduplication. */
175
+ export class RouteCache {
176
+ readonly #map = new Map<string, CachedRouteEntry>()
177
+ readonly #revalidating = new Set<string>()
178
+ readonly #inflight = new Map<string, Promise<RouteCacheSingleflightResult | undefined>>()
179
+ readonly #failedUntil = new Map<string, number>()
180
+ readonly #maxEntries: number
181
+ readonly #maxBytes: number
182
+ readonly #failureCooldownMs: number
183
+ #totalBytes = 0
184
+
185
+ constructor(options?: RouteCacheOptions) {
186
+ const entries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES
187
+ const bytes = options?.maxBytes ?? DEFAULT_MAX_BYTES
188
+ const cooldown = options?.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS
189
+ this.#maxEntries = Number.isFinite(entries) && entries > 0 ? Math.floor(entries) : 0
190
+ this.#maxBytes = Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : 0
191
+ this.#failureCooldownMs = Number.isFinite(cooldown) && cooldown >= 0 ? Math.floor(cooldown) : DEFAULT_FAILURE_COOLDOWN_MS
192
+ }
193
+
194
+ get size(): number {
195
+ return this.#map.size
196
+ }
197
+
198
+ get bytes(): number {
199
+ return this.#totalBytes
200
+ }
201
+
202
+ hasInflight(key: string): boolean {
203
+ return this.#revalidating.has(key) || this.#inflight.has(key)
204
+ }
205
+
206
+ getInflight(key: string): Promise<RouteCacheSingleflightResult | undefined> | undefined {
207
+ return this.#inflight.get(key)
208
+ }
209
+
210
+ trackInflight(key: string, promise: Promise<RouteCacheSingleflightResult | undefined>): void {
211
+ this.#inflight.set(key, promise)
212
+ const cleanup = (): void => {
213
+ if (this.#inflight.get(key) === promise)
214
+ this.#inflight.delete(key)
215
+ }
216
+ void promise.then(cleanup, cleanup)
217
+ }
218
+
219
+ clear(): void {
220
+ this.#map.clear()
221
+ this.#failedUntil.clear()
222
+ this.#totalBytes = 0
223
+ }
224
+
225
+ delete(key: string): void {
226
+ const prev = this.#map.get(key)
227
+ if (prev === undefined)
228
+ return
229
+ this.#map.delete(key)
230
+ this.#totalBytes -= prev.bytes
231
+ }
232
+
233
+ /** Looks up `key`, refreshing LRU recency on fresh/stale hits and deleting expired entries. */
234
+ lookup(key: string, now = Date.now()): RouteCacheLookup | undefined {
235
+ const entry = this.#map.get(key)
236
+ if (entry === undefined)
237
+ return undefined
238
+ if (now >= entry.staleUntil) {
239
+ this.#map.delete(key)
240
+ this.#totalBytes -= entry.bytes
241
+ return undefined
242
+ }
243
+ this.#map.delete(key)
244
+ this.#map.set(key, entry)
245
+ return now < entry.freshUntil
246
+ ? { status: 'fresh', entry }
247
+ : { status: 'stale', entry }
248
+ }
249
+
250
+ /** Stores rendered HTML and headers under `key`, evicting LRU entries to enforce both caps. */
251
+ set(key: string, html: string, headers: Record<string, string>, spec: RouteCacheSpec, now = Date.now()): CachedRouteEntry | undefined {
252
+ const rawBytes = Buffer.byteLength(html, 'utf8')
253
+ if (this.#maxEntries <= 0 || this.#maxBytes <= 0 || rawBytes > this.#maxBytes)
254
+ return undefined
255
+ this.#failedUntil.delete(key)
256
+ const prev = this.#map.get(key)
257
+ if (prev !== undefined) {
258
+ this.#totalBytes -= prev.bytes
259
+ this.#map.delete(key)
260
+ }
261
+ const entry: CachedRouteEntry = {
262
+ key,
263
+ html,
264
+ bytes: rawBytes,
265
+ headers,
266
+ createdAt: now,
267
+ freshUntil: now + spec.maxAgeMs,
268
+ staleUntil: now + spec.maxAgeMs + spec.swrMs,
269
+ spec,
270
+ etag: weakEtagOf(html),
271
+ compressed: {},
272
+ }
273
+ this.#map.set(key, entry)
274
+ this.#totalBytes += rawBytes
275
+ this.#evict(key)
276
+ return entry
277
+ }
278
+
279
+ /** Schedules a deduplicated background revalidation for `key`, backing off briefly on failure and reporting via `onError`. */
280
+ revalidate(key: string, task: () => Promise<void>, onError: (error: unknown) => void, now = Date.now()): boolean {
281
+ if (this.#revalidating.has(key))
282
+ return false
283
+ const cooldownUntil = this.#failedUntil.get(key)
284
+ if (cooldownUntil !== undefined) {
285
+ if (now < cooldownUntil)
286
+ return false
287
+ this.#failedUntil.delete(key)
288
+ }
289
+ this.#revalidating.add(key)
290
+ void Promise.resolve()
291
+ .then(task)
292
+ .then(() => {
293
+ this.#failedUntil.delete(key)
294
+ })
295
+ .catch((error: unknown) => {
296
+ if (this.#failureCooldownMs > 0) {
297
+ this.#failedUntil.set(key, Date.now() + this.#failureCooldownMs)
298
+ this.#pruneCooldowns()
299
+ }
300
+ onError(error)
301
+ })
302
+ .finally(() => {
303
+ this.#revalidating.delete(key)
304
+ })
305
+ return true
306
+ }
307
+
308
+ #pruneCooldowns(): void {
309
+ const cap = Math.max(this.#maxEntries * 2, 1000)
310
+ if (this.#failedUntil.size <= cap)
311
+ return
312
+ const now = Date.now()
313
+ for (const [k, until] of this.#failedUntil) {
314
+ if (now >= until)
315
+ this.#failedUntil.delete(k)
316
+ }
317
+ }
318
+
319
+ /** Builds a 200 HTML response for a cache hit (`age` included, precompressed variant reused). */
320
+ respondHit(
321
+ entry: CachedRouteEntry,
322
+ request: Request,
323
+ requestId: string,
324
+ compressCache: CompressionCache | undefined,
325
+ now = Date.now(),
326
+ ): Response {
327
+ const age = String(Math.max(0, Math.floor((now - entry.createdAt) / 1000)))
328
+ return this.#buildResponse(entry, entry.html, entry.headers, request, requestId, compressCache, age)
329
+ }
330
+
331
+ /** Builds a 200 HTML response for a freshly rendered miss (stored in cache when it fits). */
332
+ respondMiss(
333
+ entry: CachedRouteEntry | undefined,
334
+ html: string,
335
+ headers: Record<string, string>,
336
+ request: Request,
337
+ requestId: string,
338
+ compressCache: CompressionCache | undefined,
339
+ serverTiming?: string,
340
+ ): Response {
341
+ return this.#buildResponse(entry, html, headers, request, requestId, compressCache, undefined, serverTiming)
342
+ }
343
+
344
+ #buildResponse(
345
+ entry: CachedRouteEntry | undefined,
346
+ html: string,
347
+ baseHeaders: Record<string, string>,
348
+ request: Request,
349
+ requestId: string,
350
+ compressCache: CompressionCache | undefined,
351
+ age?: string,
352
+ serverTiming?: string,
353
+ ): Response {
354
+ const headers: Record<string, string> = { ...baseHeaders, 'x-request-id': requestId, 'etag': entry?.etag ?? weakEtagOf(html) }
355
+ if (age !== undefined)
356
+ headers.age = age
357
+ if (serverTiming !== undefined)
358
+ headers['server-timing'] = serverTiming
359
+ if (etagMatches(request.headers.get('if-none-match'), headers.etag!))
360
+ return markCompressionHandled(new Response(null, { status: 304, headers }))
361
+
362
+ if (compressCache !== undefined) {
363
+ headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
364
+ if (request.method !== 'HEAD') {
365
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
366
+ if (enc !== undefined) {
367
+ const compressed = this.#getOrCompress(entry, html, enc)
368
+ if (compressed !== null) {
369
+ headers['content-encoding'] = enc
370
+ return markCompressionHandled(new Response(compressed, { status: 200, headers }))
371
+ }
372
+ }
373
+ }
374
+ }
375
+ return markCompressionHandled(new Response(request.method === 'HEAD' ? null : html, { status: 200, headers }))
376
+ }
377
+
378
+ #getOrCompress(entry: CachedRouteEntry | undefined, html: string, enc: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
379
+ if (entry !== undefined) {
380
+ const existing = entry.compressed[enc]
381
+ if (existing !== undefined)
382
+ return existing
383
+ }
384
+ const buf = compressCachedHtml(html, enc)
385
+ if (entry !== undefined) {
386
+ if (buf === null) {
387
+ entry.compressed[enc] = null
388
+ }
389
+ else if (this.#map.get(entry.key) === entry && entry.bytes + buf.byteLength <= this.#maxBytes) {
390
+ entry.compressed[enc] = buf
391
+ entry.bytes += buf.byteLength
392
+ this.#totalBytes += buf.byteLength
393
+ this.#evictEntry(entry)
394
+ }
395
+ }
396
+ return buf
397
+ }
398
+
399
+ #evict(keepKey?: string): void {
400
+ while (this.#map.size > this.#maxEntries || this.#totalBytes > this.#maxBytes) {
401
+ const oldest = this.#map.keys().next()
402
+ if (oldest.done)
403
+ break
404
+ const key = oldest.value
405
+ if (key === keepKey && this.#map.size === 1)
406
+ break
407
+ const evicted = this.#map.get(key)!
408
+ this.#map.delete(key)
409
+ this.#totalBytes -= evicted.bytes
410
+ }
411
+ }
412
+
413
+ #evictEntry(keep: CachedRouteEntry): void {
414
+ while (this.#totalBytes > this.#maxBytes) {
415
+ let victimKey: string | undefined
416
+ for (const [k, v] of this.#map) {
417
+ if (v !== keep) {
418
+ victimKey = k
419
+ break
420
+ }
421
+ }
422
+ if (victimKey === undefined)
423
+ break
424
+ const evicted = this.#map.get(victimKey)!
425
+ this.#map.delete(victimKey)
426
+ this.#totalBytes -= evicted.bytes
427
+ }
428
+ }
429
+ }
430
+
431
+ /** Looks up a cached hit and schedules background revalidation when stale. */
432
+ export function serveCachedHit(
433
+ routeCache: RouteCache,
434
+ key: string,
435
+ request: Request,
436
+ requestId: string,
437
+ compressCache: CompressionCache | undefined,
438
+ revalidate: () => Promise<void>,
439
+ onError: (error: unknown) => void,
440
+ ): Response | undefined {
441
+ const hit = routeCache.lookup(key)
442
+ if (hit === undefined)
443
+ return undefined
444
+ if (hit.status === 'stale')
445
+ routeCache.revalidate(key, revalidate, onError)
446
+ return routeCache.respondHit(hit.entry, request, requestId, compressCache)
447
+ }
448
+
449
+ /** Creates a `RouteCache` unless disabled (`dev`, build prerendering, or `routeCache: false`). */
450
+ export function createRouteCache(option: RouteCacheOptions | false | undefined, disabled = false): RouteCache | undefined {
451
+ if (disabled || option === false)
452
+ return undefined
453
+ return new RouteCache(option)
454
+ }
455
+
456
+ const PRIVATE_HEADER_NAMES = new Set(['cookie', 'authorization'])
457
+ const BULK_HEADER_KEYS = new Set<PropertyKey>(['entries', 'values', 'keys', 'forEach', 'toJSON', 'getSetCookie', Symbol.iterator])
458
+
459
+ export interface PrivateReadTracker {
460
+ readonly ctx: RequestContext
461
+ readonly locals: RequestContext['locals']
462
+ readonly consent: RequestContext['consent']
463
+ readonly didReadPrivate: () => boolean
464
+ }
465
+
466
+ function wrapTrackedHeaders(headers: Headers, mark: () => void): Headers {
467
+ return new Proxy(headers, {
468
+ get(target, prop) {
469
+ if (prop === 'get' || prop === 'has') {
470
+ const fn = target[prop].bind(target) as (name: string) => unknown
471
+ return (name: string) => {
472
+ if (PRIVATE_HEADER_NAMES.has(String(name).toLowerCase()))
473
+ mark()
474
+ return fn(name)
475
+ }
476
+ }
477
+ if (BULK_HEADER_KEYS.has(prop) || (typeof prop === 'string' && PRIVATE_HEADER_NAMES.has(prop.toLowerCase())))
478
+ mark()
479
+ const value = Reflect.get(target, prop, target)
480
+ return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
481
+ },
482
+ ownKeys(target) {
483
+ mark()
484
+ return Reflect.ownKeys(target)
485
+ },
486
+ })
487
+ }
488
+
489
+ /** Tracks runtime reads of per-visitor request data on a cached route so private HTML is never stored or shared. */
490
+ export function trackPrivateReads(ctx: RequestContext): PrivateReadTracker {
491
+ let readPrivate = false
492
+ const mark = (): void => { readPrivate = true }
493
+ const locals = new Proxy(ctx.locals, {
494
+ get(target, prop, receiver) {
495
+ mark()
496
+ return Reflect.get(target, prop, receiver)
497
+ },
498
+ has(target, prop) {
499
+ mark()
500
+ return Reflect.has(target, prop)
501
+ },
502
+ ownKeys(target) {
503
+ mark()
504
+ return Reflect.ownKeys(target)
505
+ },
506
+ })
507
+ const consent: RequestContext['consent'] = ctx.consent !== undefined
508
+ ? new Proxy(ctx.consent, {
509
+ get(target, prop) {
510
+ mark()
511
+ const value = Reflect.get(target, prop, target)
512
+ return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
513
+ },
514
+ })
515
+ : ctx.consent
516
+ let headersProxy: Headers | undefined
517
+ const request = new Proxy(ctx.request, {
518
+ get(target, prop) {
519
+ if (prop === 'headers')
520
+ return headersProxy ??= wrapTrackedHeaders(target.headers, mark)
521
+ const value = Reflect.get(target, prop, target)
522
+ return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
523
+ },
524
+ })
525
+ const trackedCtx: RequestContext = {
526
+ url: ctx.url,
527
+ params: ctx.params,
528
+ requestId: ctx.requestId,
529
+ region: ctx.region,
530
+ json: ctx.json,
531
+ text: ctx.text,
532
+ redirect: ctx.redirect,
533
+ deny: ctx.deny,
534
+ get request() { return request },
535
+ get cookies() { mark(); return ctx.cookies },
536
+ get locals() { return locals },
537
+ get consent() { mark(); return consent },
538
+ get ip() { mark(); return ctx.ip },
539
+ }
540
+ return { ctx: trackedCtx, locals, consent, didReadPrivate: () => readPrivate }
541
+ }