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,588 @@
1
+ // HTTP helpers, MIME table, RequestContext factory, and island tag scanner for Prunelle server.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { PrunelleChild } from '../jsx-runtime'
5
+ import type { ServerErrorInfo, ServerRuntimeConfig, ServiceKey } from '../plugins/index'
6
+ import type { NormalizedConsentConfig, RequestConsent } from './consent'
7
+ import type { Cookies } from './cookies'
8
+ import type { PrunelleLocals } from './index'
9
+ import type { TrustProxy } from './security'
10
+ import { createRequestConsent } from './consent'
11
+ import { CookieStore } from './cookies'
12
+ import { nodeEnv } from './env'
13
+ import { resolveFallbackRequestId } from './health'
14
+ import { requestedRegion } from './region'
15
+ import { GATED_ROUTE_CACHE_CONTROL } from './route-cache'
16
+ import { expectedOrigin, getClientIp, isHttpsRequest } from './security'
17
+
18
+ export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
19
+
20
+ const NOT_FOUND_SYMBOL = Symbol.for('pru.notFound')
21
+ declare const NOT_FOUND_BRAND: unique symbol
22
+
23
+ export interface NotFoundResult {
24
+ readonly [NOT_FOUND_BRAND]: true
25
+ }
26
+
27
+ /** Return (or throw) from `load()` to render `_404.tsx` with HTTP status 404. */
28
+ export function notFound(): NotFoundResult {
29
+ return { [NOT_FOUND_SYMBOL]: true } as unknown as NotFoundResult
30
+ }
31
+
32
+ export function isNotFound(value: unknown): value is NotFoundResult {
33
+ return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_FOUND_SYMBOL] === true
34
+ }
35
+
36
+ /** Maps built-in (and augmented) route param matcher names to their TypeScript param value types. */
37
+ export interface ParamMatcherTypes {
38
+ integer: `${number}`
39
+ uuid: `${string}-${string}-${string}-${string}-${string}`
40
+ slug: string
41
+ }
42
+
43
+ type MatcherValue<Name extends string> = Name extends keyof ParamMatcherTypes ? ParamMatcherTypes[Name] : string
44
+
45
+ type ParseParamSpec<Spec extends string> =
46
+ Spec extends `${infer Name}=${infer Matcher}`
47
+ ? [Name, MatcherValue<Matcher>]
48
+ : [Spec, string]
49
+
50
+ type SegmentParam<Seg extends string> =
51
+ Seg extends `(${string})`
52
+ ? unknown
53
+ : Seg extends `[[${infer Spec}]]`
54
+ ? { [K in ParseParamSpec<Spec>[0]]?: ParseParamSpec<Spec>[1] | undefined }
55
+ : Seg extends `[...${infer Spec}]`
56
+ ? { [K in ParseParamSpec<Spec>[0]]: string }
57
+ : Seg extends `[${infer Spec}]`
58
+ ? { [K in ParseParamSpec<Spec>[0]]: ParseParamSpec<Spec>[1] }
59
+ : Seg extends `*${infer Spec}`
60
+ ? { [K in ParseParamSpec<Spec>[0] extends '' ? 'rest' : ParseParamSpec<Spec>[0]]: string }
61
+ : Seg extends `:${infer Spec}?`
62
+ ? { [K in ParseParamSpec<Spec>[0]]?: ParseParamSpec<Spec>[1] | undefined }
63
+ : Seg extends `:${infer Spec}`
64
+ ? { [K in ParseParamSpec<Spec>[0]]: ParseParamSpec<Spec>[1] }
65
+ : unknown
66
+
67
+ type MergeParams<A, B> = unknown extends B
68
+ ? A
69
+ : { [K in keyof (Omit<A, keyof B> & B)]: (Omit<A, keyof B> & B)[K] }
70
+
71
+ type ExtractRouteParamsRec<Path extends string, Acc = {}> =
72
+ Path extends `${infer Seg}/${infer Rest}`
73
+ ? ExtractRouteParamsRec<Rest, Seg extends '' ? Acc : MergeParams<Acc, SegmentParam<Seg>>>
74
+ : Path extends ''
75
+ ? Acc
76
+ : MergeParams<Acc, SegmentParam<Path>>
77
+
78
+ /** Extracts typed route params from a Prunelle route path (`'/notices/[id=integer]'` -> `{ id: `${number}` }`, `'/[[lang]]/about'` -> `{ lang?: string | undefined }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
79
+ export type ExtractRouteParams<Path extends string> =
80
+ string extends Path
81
+ ? Record<string, string>
82
+ : ExtractRouteParamsRec<Path>
83
+
84
+ export type LoaderFn = (...args: never[]) => unknown
85
+
86
+ /** Infers the resolved page `data` type returned by a route's `load()` function, excluding `Response` and `notFound()`. */
87
+ export type LoaderData<T extends LoaderFn> = Exclude<Awaited<ReturnType<T>>, Response | NotFoundResult>
88
+
89
+ type InferLoaderParams<T extends LoaderFn> =
90
+ Parameters<T> extends [ctx: { params: infer P }, ...unknown[]]
91
+ ? P
92
+ : Record<string, string>
93
+
94
+ /** Props passed to a Prunelle route page component. Pass `typeof load` to infer `data` (and `params` when `load` uses `RouteContext<Path>`), or a route path string when there is no `load`. */
95
+ export type PageProps<
96
+ TLoadOrPath extends LoaderFn | string | undefined = undefined,
97
+ TPath extends string = string,
98
+ > = {
99
+ params: TLoadOrPath extends string
100
+ ? ExtractRouteParams<TLoadOrPath>
101
+ : string extends TPath
102
+ ? (TLoadOrPath extends LoaderFn ? InferLoaderParams<TLoadOrPath> : Record<string, string>)
103
+ : ExtractRouteParams<TPath>
104
+ locals: PrunelleLocals
105
+ url: URL
106
+ } & (TLoadOrPath extends LoaderFn ? { data: LoaderData<TLoadOrPath> } : { data?: undefined })
107
+
108
+ /** Props passed to a Prunelle `_layout.tsx` component. */
109
+ export interface LayoutProps<Path extends string = string> {
110
+ children: PrunelleChild
111
+ params: ExtractRouteParams<Path>
112
+ locals: PrunelleLocals
113
+ url: URL
114
+ }
115
+
116
+ /** Props passed to a Prunelle status page (`_401.tsx`, `_403.tsx`, `_404.tsx`, `_429.tsx`, `_503.tsx`). */
117
+ export interface StatusPageProps<Path extends string = string> {
118
+ status: number
119
+ message: string
120
+ params: ExtractRouteParams<Path>
121
+ locals: PrunelleLocals
122
+ url: URL
123
+ }
124
+
125
+ export interface ServerOptions extends ServerRuntimeConfig {
126
+ root: string
127
+ outDir?: string | undefined
128
+ port?: number | undefined
129
+ dev?: boolean | undefined
130
+ /** @internal The address `prunelle dev` binds, from which plugins get `api.devExposed`. */
131
+ devHost?: string | undefined
132
+ nodeEnv?: string | undefined
133
+ /** @internal Imports a built server module by absolute path; `prunelle dev` passes one that keeps unchanged modules loaded. */
134
+ importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
135
+ /** @internal Hears every unhandled route, action and plugin error; `testApp().errors` fills from it. */
136
+ errorSink?: ((info: ServerErrorInfo) => void) | undefined
137
+ /** @internal The build's prerender server, which runs before the production environment exists, so plugin `requires` are not checked. */
138
+ prerender?: boolean | undefined
139
+ /** @internal True during a `--static` export, which ships static HTML directly and must enforce plugin `requires` in production. */
140
+ static?: boolean | undefined
141
+ }
142
+
143
+ export interface RequestContext<Params = Record<string, string>> {
144
+ request: Request
145
+ url: URL
146
+ params: Params
147
+ cookies: Cookies
148
+ consent: RequestConsent
149
+ locals: PrunelleLocals
150
+ ip?: string | undefined
151
+ /** Unique identifier for this request, echoed in the `x-request-id` response header and passed to `onError`. */
152
+ readonly requestId: string
153
+ /** The region a `data-pru-target` link or form asked for alone (`x-pru-region`): `load()` can skip the data the others show. */
154
+ readonly region?: string | undefined
155
+ json: (data: unknown, init?: ResponseInit) => Response
156
+ text: (body: string, init?: ResponseInit) => Response
157
+ /** A redirect to a path or a URL of this site; one to another site throws unless `{ external: true }` says the app chose that target (never one read from the request). */
158
+ redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308, options?: RedirectOptions) => Response
159
+ deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
160
+ }
161
+
162
+ /** `RequestContext` with `params` inferred from a Prunelle route pattern (e.g. `RouteContext<'/notices/[id]'>`). */
163
+ export type RouteContext<Path extends string = string> = RequestContext<ExtractRouteParams<Path>>
164
+
165
+ export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
166
+
167
+ export type PrunelleServer = ReturnType<typeof Bun.serve>
168
+
169
+ export interface PrunelleApp {
170
+ handle: (request: Request, remoteIp?: string, disableTimeout?: () => void) => Promise<Response>
171
+ serve: (port?: number, hostname?: string) => PrunelleServer
172
+ /** @internal Swaps this app's handlers into a server another app started, with no dropped connection: `prunelle start` reloads a new build with it. */
173
+ reloadInto?: (server: PrunelleServer) => void
174
+ /** Looks up a server-scoped plugin service registered during `server(api)` (e.g. `JOBS_SERVICE`). */
175
+ inject?: <T>(key: ServiceKey<T>) => T | undefined
176
+ /** Closes active long-lived streams (such as SSE) before `server.stop()` drains normal in-flight HTTP requests. */
177
+ closeStreams?: () => Promise<void>
178
+ /** @internal The security headers each response of this app carries, which the 503 of a build swap in `prunelle start` repeats. */
179
+ securityHeaders?: Readonly<Record<string, string>> | undefined
180
+ /** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
181
+ dispose?: () => Promise<void>
182
+ }
183
+
184
+ export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
185
+
186
+ export interface EmbeddedServerConfig extends ServerRuntimeConfig {
187
+ manifest: BuildManifest
188
+ modules: Record<string, unknown>
189
+ assets: Record<string, EmbeddedBody>
190
+ publicAssets?: Record<string, EmbeddedBody> | undefined
191
+ publicEtags?: Record<string, string> | undefined
192
+ prerendered?: Record<string, string> | undefined
193
+ prerenderedFiles?: Record<string, string> | undefined
194
+ /** ETags of the prerendered HTML files, by the same key; a missing one comes from the file's size and mtime. */
195
+ prerenderedEtags?: Record<string, string> | undefined
196
+ root?: string | undefined
197
+ outDir?: string | undefined
198
+ publicDir?: string | undefined
199
+ dev?: boolean | undefined
200
+ devHost?: string | undefined
201
+ nodeEnv?: string | undefined
202
+ errorSink?: ((info: ServerErrorInfo) => void) | undefined
203
+ prerender?: boolean | undefined
204
+ static?: boolean | undefined
205
+ }
206
+
207
+ export const MIME: Record<string, string> = {
208
+ '.js': 'text/javascript; charset=utf-8',
209
+ '.mjs': 'text/javascript; charset=utf-8',
210
+ '.css': 'text/css; charset=utf-8',
211
+ '.html': 'text/html; charset=utf-8',
212
+ '.json': 'application/json; charset=utf-8',
213
+ '.webmanifest': 'application/manifest+json; charset=utf-8',
214
+ '.txt': 'text/plain; charset=utf-8',
215
+ '.xml': 'application/xml; charset=utf-8',
216
+ '.svg': 'image/svg+xml',
217
+ '.png': 'image/png',
218
+ '.jpg': 'image/jpeg',
219
+ '.jpeg': 'image/jpeg',
220
+ '.gif': 'image/gif',
221
+ '.webp': 'image/webp',
222
+ '.avif': 'image/avif',
223
+ '.ico': 'image/x-icon',
224
+ '.woff2': 'font/woff2',
225
+ '.woff': 'font/woff',
226
+ '.ttf': 'font/ttf',
227
+ '.otf': 'font/otf',
228
+ '.pdf': 'application/pdf',
229
+ '.wasm': 'application/wasm',
230
+ '.mp4': 'video/mp4',
231
+ '.webm': 'video/webm',
232
+ '.map': 'application/json',
233
+ }
234
+
235
+ const ISLAND_TAG_RE = /<pru-island c="([^"]+)"([^>]*)>/g
236
+
237
+ export function extractRenderedIslands(html: string): { hasIslands: boolean, eagerChunks: string[] } {
238
+ let hasIslands = false
239
+ const eager = new Set<string>()
240
+ ISLAND_TAG_RE.lastIndex = 0
241
+ let m: RegExpExecArray | null
242
+ while ((m = ISLAND_TAG_RE.exec(html)) !== null) {
243
+ hasIslands = true
244
+ const attrs = m[2] ?? ''
245
+ if (!attrs.includes(' h="'))
246
+ eager.add(m[1]!)
247
+ }
248
+ return { hasIslands, eagerChunks: [...eager] }
249
+ }
250
+
251
+ export interface RequestContextOptions {
252
+ trustProxy?: TrustProxy | undefined
253
+ remoteIp?: string | undefined
254
+ /** The parsed `request.url`, when the caller already has it. */
255
+ url?: URL | undefined
256
+ consent?: NormalizedConsentConfig | undefined
257
+ requestId?: string | undefined
258
+ /** The app's `site` is https: cookies get `Secure` even when a proxy the server does not trust hides the scheme. */
259
+ httpsSite?: boolean | undefined
260
+ }
261
+
262
+ // None of these read the request, so every context shares them.
263
+ const json: RequestContext['json'] = (data, init) => {
264
+ const payload = JSON.stringify(data)
265
+ const headers = new Headers(init?.headers)
266
+ if (!headers.has('content-type'))
267
+ headers.set('content-type', 'application/json; charset=utf-8')
268
+ if (!headers.has('content-length'))
269
+ headers.set('content-length', String(Buffer.byteLength(payload, 'utf8')))
270
+ return new Response(payload, { ...init, headers })
271
+ }
272
+ const text: RequestContext['text'] = (body, init) => {
273
+ const headers = new Headers(init?.headers)
274
+ if (!headers.has('content-type'))
275
+ headers.set('content-type', 'text/plain; charset=utf-8')
276
+ if (!headers.has('content-length'))
277
+ headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
278
+ return new Response(body, { ...init, headers })
279
+ }
280
+ export interface DeniedInfo {
281
+ status: number
282
+ message: string
283
+ fieldErrors?: Record<string, string> | undefined
284
+ }
285
+
286
+ const DENIED_RESPONSES = new WeakMap<Response, DeniedInfo>()
287
+
288
+ /** Metadata attached to a `Response` produced by `ctx.deny()`. */
289
+ export function getDeniedInfo(res: Response): DeniedInfo | undefined {
290
+ return DENIED_RESPONSES.get(res)
291
+ }
292
+
293
+ export interface RedirectOptions {
294
+ /** Allows a target on another site: a payment page, an identity provider, a redirect rule the app wrote itself. */
295
+ external?: boolean | undefined
296
+ }
297
+
298
+ const EXTERNAL_REDIRECTS = new WeakSet<Response>()
299
+
300
+ /** Whether `res` came from `ctx.redirect(url, status, { external: true })`: the one kind of cross-site redirect an island's action call follows. */
301
+ export function isExternalRedirect(res: Response): boolean {
302
+ return EXTERNAL_REDIRECTS.has(res)
303
+ }
304
+
305
+ const REDIRECT_CONTROL_CHAR_RE = /[\u0000-\u001F\u007F]/
306
+ const NON_HIERARCHICAL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:(?!\/\/)/i
307
+
308
+ function sameOrigin(location: string, baseOrigin: string): boolean {
309
+ if (baseOrigin === 'null' || REDIRECT_CONTROL_CHAR_RE.test(location) || NON_HIERARCHICAL_SCHEME_RE.test(location.trimStart()))
310
+ return false
311
+ try {
312
+ return new URL(location, baseOrigin).origin === baseOrigin
313
+ }
314
+ catch {
315
+ return false
316
+ }
317
+ }
318
+
319
+ const makeRedirect = (request: Request, trustProxy: TrustProxy, url: URL): RequestContext['redirect'] => (location, status = 302, options) => {
320
+ const external = options?.external === true
321
+ if (!external) {
322
+ const baseOrigin = expectedOrigin(request, trustProxy, url)
323
+ if (!sameOrigin(location, baseOrigin))
324
+ throw new Error(`prunelle: ctx.redirect("${location}") leaves ${baseOrigin}: redirect to a path of this site, or pass { external: true } as the third argument when the app chose that address itself (never one read from the request, which makes an open redirect).`)
325
+ }
326
+ const res = new Response(null, { status, headers: { location } })
327
+ if (external)
328
+ EXTERNAL_REDIRECTS.add(res)
329
+ return res
330
+ }
331
+ const deny: RequestContext['deny'] = (status, message, fieldErrors) => {
332
+ const res = Response.json({ ok: false, status, error: message, fieldErrors }, { status })
333
+ DENIED_RESPONSES.set(res, { status, message, fieldErrors })
334
+ return res
335
+ }
336
+
337
+ /** RFC 9110 weak ETag comparison supporting `*`, comma-separated lists, and `W/` prefixes. */
338
+ export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
339
+ if (!ifNoneMatch)
340
+ return false
341
+ const trimmed = ifNoneMatch.trim()
342
+ if (trimmed === '*')
343
+ return true
344
+ const stripWeak = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
345
+ const target = stripWeak(etag)
346
+ for (const part of trimmed.split(',')) {
347
+ if (stripWeak(part.trim()) === target)
348
+ return true
349
+ }
350
+ return false
351
+ }
352
+
353
+ export function makeRequestContext(
354
+ request: Request,
355
+ params: Record<string, string>,
356
+ opts?: RequestContextOptions,
357
+ ): { ctx: RequestContext, cookieStore: CookieStore } {
358
+ const trustProxy = opts?.trustProxy ?? false
359
+ const remoteIp = opts?.remoteIp
360
+ const consentConfig = opts?.consent
361
+ let cachedConsent: RequestConsent | undefined
362
+ let cachedConsentRaw: string | undefined
363
+ const cookieStore = new CookieStore(
364
+ request.headers.get('cookie'),
365
+ opts?.httpsSite === true || isHttpsRequest(request, trustProxy),
366
+ category => getConsent().has(category),
367
+ )
368
+ const getConsent = (): RequestConsent => {
369
+ const raw = consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined
370
+ if (cachedConsent === undefined || raw !== cachedConsentRaw) {
371
+ cachedConsentRaw = raw
372
+ cachedConsent = createRequestConsent(raw, consentConfig)
373
+ }
374
+ return cachedConsent
375
+ }
376
+ const requestId = opts?.requestId ?? resolveFallbackRequestId(request, trustProxy)
377
+ let cachedIp: string | undefined
378
+ let ipComputed = false
379
+ const url = opts?.url ?? new URL(request.url)
380
+ const ctx: RequestContext = {
381
+ request,
382
+ url,
383
+ params,
384
+ cookies: cookieStore,
385
+ get consent() {
386
+ return getConsent()
387
+ },
388
+ locals: {},
389
+ requestId,
390
+ get ip() {
391
+ if (!ipComputed) {
392
+ ipComputed = true
393
+ cachedIp = getClientIp(request, trustProxy, remoteIp)
394
+ }
395
+ return cachedIp
396
+ },
397
+ set ip(val: string | undefined) {
398
+ ipComputed = true
399
+ cachedIp = val
400
+ },
401
+ get region() {
402
+ return requestedRegion(request)
403
+ },
404
+ json,
405
+ text,
406
+ redirect: makeRedirect(request, trustProxy, url),
407
+ deny,
408
+ }
409
+ return { ctx, cookieStore }
410
+ }
411
+
412
+ /** True when the client sent or asked for JSON: such requests get JSON errors, not pages. */
413
+ export function wantsJson(request: Request): boolean {
414
+ return (request.headers.get('accept') ?? '').toLowerCase().includes('application/json')
415
+ || (request.headers.get('content-type') ?? '').toLowerCase().includes('application/json')
416
+ }
417
+
418
+ /** True when the client explicitly accepts HTML and does not ask for JSON (e.g. browser navigation). */
419
+ export function acceptsHtml(request: Request): boolean {
420
+ if (wantsJson(request))
421
+ return false
422
+ return (request.headers.get('accept') ?? '').toLowerCase().includes('text/html')
423
+ }
424
+
425
+ const PUBLIC_CACHE_RE = /\bpublic\b/i
426
+
427
+ /** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
428
+ export async function enforceRequestBodyLimit(
429
+ request: Request,
430
+ maxBytes: number,
431
+ ): Promise<{ ok: true, request: Request } | { ok: false, aborted?: true }> {
432
+ if (request.method === 'GET' || request.method === 'HEAD' || !Number.isFinite(maxBytes) || maxBytes <= 0)
433
+ return { ok: true, request }
434
+
435
+ const clHeader = request.headers.get('content-length')
436
+ if (clHeader !== null) {
437
+ const cl = Number(clHeader)
438
+ if (Number.isFinite(cl) && cl > maxBytes)
439
+ return { ok: false }
440
+ }
441
+
442
+ // Capture headers BEFORE accessing request.body so Bun preserves FormData multipart boundaries.
443
+ const headers = new Headers(request.headers)
444
+ const body = request.body
445
+ if (body === null)
446
+ return { ok: true, request }
447
+
448
+ const reader = body.getReader()
449
+ const chunks: Uint8Array[] = []
450
+ let total = 0
451
+ try {
452
+ while (true) {
453
+ let read: Awaited<ReturnType<typeof reader.read>>
454
+ try {
455
+ read = await reader.read()
456
+ }
457
+ catch {
458
+ return { ok: false, aborted: true }
459
+ }
460
+ if (read.done)
461
+ break
462
+ const { value } = read
463
+ total += value.byteLength
464
+ if (total > maxBytes) {
465
+ try {
466
+ await reader.cancel()
467
+ }
468
+ catch {}
469
+ return { ok: false }
470
+ }
471
+ chunks.push(value)
472
+ }
473
+ }
474
+ finally {
475
+ reader.releaseLock()
476
+ }
477
+
478
+ let combined: Uint8Array<ArrayBuffer>
479
+ if (chunks.length === 1) {
480
+ const only = chunks[0]!
481
+ combined = only.buffer instanceof ArrayBuffer && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength
482
+ ? only as Uint8Array<ArrayBuffer>
483
+ : new Uint8Array(only)
484
+ }
485
+ else {
486
+ combined = new Uint8Array(total)
487
+ let offset = 0
488
+ for (let i = 0; i < chunks.length; i++) {
489
+ const chunk = chunks[i]!
490
+ combined.set(chunk, offset)
491
+ offset += chunk.byteLength
492
+ }
493
+ }
494
+
495
+ headers.delete('transfer-encoding')
496
+ return {
497
+ ok: true,
498
+ request: new Request(request.url, {
499
+ method: request.method,
500
+ headers,
501
+ body: combined,
502
+ signal: request.signal,
503
+ }),
504
+ }
505
+ }
506
+
507
+ export function applyHstsHeader(
508
+ res: Response,
509
+ request: Request,
510
+ hstsValue: string | undefined,
511
+ trustProxy: TrustProxy,
512
+ isDev = false,
513
+ resolvedEnv?: string,
514
+ httpsSite = false,
515
+ ): Response {
516
+ if (hstsValue === undefined || isDev || !(httpsSite || isHttpsRequest(request, trustProxy)))
517
+ return res
518
+ const env = resolvedEnv ?? nodeEnv()
519
+ if (env === 'development' || env === 'test')
520
+ return res
521
+ if (res.headers.has('strict-transport-security'))
522
+ return res
523
+ try {
524
+ res.headers.set('strict-transport-security', hstsValue)
525
+ return res
526
+ }
527
+ catch {
528
+ const headers = new Headers(res.headers)
529
+ headers.set('strict-transport-security', hstsValue)
530
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
531
+ }
532
+ }
533
+
534
+ /** Adds the pending cookies (when any), security headers, `x-request-id`, and dev `Server-Timing`. */
535
+ export function finalizeResponse(
536
+ res: Response,
537
+ cookieStore: CookieStore | undefined,
538
+ entries: readonly [string, string][],
539
+ requestId?: string,
540
+ serverTiming?: string,
541
+ ): Response {
542
+ const hasCookies = cookieStore?.hasChanges === true
543
+ const hasRequestId = requestId !== undefined
544
+ const hasTiming = serverTiming !== undefined && serverTiming !== ''
545
+ if (!hasCookies && entries.length === 0 && !hasRequestId && !hasTiming)
546
+ return res
547
+
548
+ const apply = (h: Headers): void => {
549
+ if (hasCookies) {
550
+ cookieStore!.applyTo(h)
551
+ const cc = h.get('cache-control')
552
+ if (cc !== null && (PUBLIC_CACHE_RE.test(cc) || cc === GATED_ROUTE_CACHE_CONTROL))
553
+ h.set('cache-control', 'private, no-store')
554
+ }
555
+ for (const [k, v] of entries) {
556
+ if (!h.has(k))
557
+ h.set(k, v)
558
+ }
559
+ if (hasRequestId && !h.has('x-request-id'))
560
+ h.set('x-request-id', requestId)
561
+ if (hasTiming)
562
+ h.set('server-timing', serverTiming)
563
+ }
564
+ // Mutate in place (no copy in Bun); a response with immutable headers (e.g. a proxied upstream fetch) is rebuilt.
565
+ try {
566
+ apply(res.headers)
567
+ return res
568
+ }
569
+ catch {
570
+ const headers = new Headers(res.headers)
571
+ apply(headers)
572
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
573
+ }
574
+ }
575
+
576
+ /** Runs `middlewares` in order around `last`; each calls `next` at most once. */
577
+ export async function runChain(ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>): Promise<Response> {
578
+ if (middlewares.length === 0)
579
+ return last()
580
+ let index = -1
581
+ const dispatch = async (i: number): Promise<Response> => {
582
+ if (i <= index)
583
+ throw new Error('prunelle: middleware called next() multiple times')
584
+ index = i
585
+ return i < middlewares.length ? middlewares[i]!(ctx, () => dispatch(i + 1)) : last()
586
+ }
587
+ return dispatch(0)
588
+ }