@orkestrel/server 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1695 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _orkestrel_contract = require("@orkestrel/contract");
3
+ //#region src/core/constants.ts
4
+ /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
5
+ var DEFAULT_DRAIN_MS = 1e4;
6
+ /**
7
+ * The `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
8
+ * an instance thrown by ANOTHER copy of this package (the dual-package
9
+ * hazard — a version-skewed or workspace-linked duplicate install), where
10
+ * `instanceof` alone fails because the two copies' `HTTPError` constructors
11
+ * are distinct objects.
12
+ *
13
+ * @remarks
14
+ * `Symbol.for` interns the symbol on the GLOBAL symbol registry, so every
15
+ * copy of this package that evaluates this key resolves the SAME symbol
16
+ * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,
17
+ * unequal symbol per copy and defeat the whole point of a cross-copy brand.
18
+ */
19
+ var HTTP_ERROR_BRAND = Symbol.for("@orkestrel/server.HTTPError");
20
+ /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
21
+ var DEFAULT_BODY_LIMIT = 1048576;
22
+ /**
23
+ * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
24
+ * the body pipeline's byte-counting `TransformStream` enforces when
25
+ * transparently decompressing a `Content-Encoding` request body.
26
+ *
27
+ * @remarks
28
+ * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
29
+ * can inflate by many orders of magnitude — a classic decompression bomb.
30
+ * Capping the decompressed byte count makes the pipe ABORT the moment the
31
+ * output would exceed this, BEFORE the full bomb is materialized, so the
32
+ * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
33
+ * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
34
+ * consumer raises it via {@link import('./types.js').BodyOptions}
35
+ * `decompression` for a workload that genuinely ships larger decompressed
36
+ * bodies.
37
+ */
38
+ var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
39
+ /**
40
+ * The SSE response headers the `openStream` seam always sets.
41
+ *
42
+ * @remarks
43
+ * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
44
+ * keeps a proxy from caching the stream; `keep-alive` holds the connection
45
+ * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
46
+ * events flush promptly rather than batching. Frozen so a consumer can read
47
+ * but never mutate the shared default; `openStream` merges any
48
+ * {@link import('./types.js').StreamOptions.headers} UNDER these.
49
+ */
50
+ var SSE_HEADERS = Object.freeze({
51
+ "Content-Type": "text/event-stream; charset=utf-8",
52
+ "Cache-Control": "no-cache",
53
+ Connection: "keep-alive",
54
+ "X-Accel-Buffering": "no"
55
+ });
56
+ /**
57
+ * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
58
+ * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
59
+ * / control-char-bearing incoming id is REJECTED (a fresh id is minted
60
+ * instead) rather than ever riding into a response header or `context.state`
61
+ * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
62
+ * shared default.
63
+ */
64
+ var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
65
+ /**
66
+ * The set of bare `Content-Type`s `isCompressibleType` treats as
67
+ * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
68
+ * `+xml`) rules that helper also applies.
69
+ *
70
+ * @remarks
71
+ * The text-shaped application types worth compressing (JSON / JavaScript /
72
+ * XML / SVG / WASM / a few document formats) — NOT already-compressed
73
+ * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
74
+ * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
75
+ * but never mutates the shared default.
76
+ */
77
+ var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
78
+ "application/json",
79
+ "application/javascript",
80
+ "application/xml",
81
+ "application/xhtml+xml",
82
+ "application/rss+xml",
83
+ "application/atom+xml",
84
+ "application/ld+json",
85
+ "application/manifest+json",
86
+ "application/vnd.api+json",
87
+ "application/wasm",
88
+ "image/svg+xml",
89
+ "application/pdf"
90
+ ]);
91
+ /**
92
+ * The default {@link Encoding} content-codings the substrate offers, in
93
+ * PREFERENCE order — `gzip` / `deflate`.
94
+ *
95
+ * @remarks
96
+ * `identity` (no compression) is always implicitly acceptable and is NOT
97
+ * listed here — it is the fall-through when a client accepts none of these.
98
+ * Brotli is omitted per the core's `CompressionStream`-only decision (see
99
+ * {@link Encoding}). Frozen so a consumer can read but never mutate the
100
+ * shared default.
101
+ */
102
+ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
103
+ //#endregion
104
+ //#region src/core/errors.ts
105
+ /**
106
+ * An error a handler (or middleware) throws to produce an HTTP response of a
107
+ * specific status.
108
+ *
109
+ * @remarks
110
+ * Carries the HTTP `status` to send and an optional `context` record (the
111
+ * offending field / value). The server's built-in error boundary catches it
112
+ * and renders a response of `status` with the error's `message` as the body
113
+ * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's
114
+ * deliberate signal), unlike a generic throw whose message is hidden unless
115
+ * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
116
+ * specific statuses, or throw it directly. Narrow a caught value with
117
+ * {@link isHTTPError}.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * import { HTTPError } from '@src/core'
122
+ *
123
+ * const handler = async (request: Request): Promise<Response> => {
124
+ * const user = await find(new URL(request.url).searchParams.get('id'))
125
+ * if (user === undefined) throw new HTTPError(404, 'user not found')
126
+ * return Response.json(user)
127
+ * }
128
+ * ```
129
+ */
130
+ var HTTPError = class extends Error {
131
+ status;
132
+ context;
133
+ [HTTP_ERROR_BRAND] = true;
134
+ constructor(status, message, context) {
135
+ super(message);
136
+ this.name = "HTTPError";
137
+ this.status = status;
138
+ this.context = context;
139
+ }
140
+ };
141
+ /**
142
+ * The {@link HTTPError} thrown when a request body exceeds the body
143
+ * pipeline's size limit — a `413 Content Too Large`.
144
+ *
145
+ * @remarks
146
+ * Thrown by `readBody` (and the middleware context's cached `body()`) when
147
+ * the received bytes exceed the configured {@link
148
+ * import('./types.js').BodyOptions.limit}, carrying the `limit` in its
149
+ * `context`. The server's error boundary renders it as a 413.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * import { ContentTooLargeError, isHTTPError } from '@src/core'
154
+ *
155
+ * try {
156
+ * await readBody(request, { limit: 1024 })
157
+ * } catch (error) {
158
+ * if (isHTTPError(error)) console.log(error.status) // 413
159
+ * }
160
+ * ```
161
+ */
162
+ var ContentTooLargeError = class extends HTTPError {
163
+ constructor(limit) {
164
+ super(413, `request body exceeds the ${limit}-byte limit`, { limit });
165
+ this.name = "ContentTooLargeError";
166
+ }
167
+ };
168
+ /**
169
+ * Narrow an unknown caught value to an {@link HTTPError} (including its
170
+ * subclasses, e.g. {@link ContentTooLargeError}).
171
+ *
172
+ * @param value - The value to test (typically a `catch` binding)
173
+ * @returns `true` when `value` is an {@link HTTPError}
174
+ *
175
+ * @remarks
176
+ * Tries `instanceof` first, then falls back to a total structural check for
177
+ * an instance built by a DIFFERENT copy of this package (the dual-package
178
+ * hazard — version skew, a linked workspace duplicate) whose `HTTPError`
179
+ * constructor is a distinct object from this copy's: the value must carry
180
+ * the cross-copy brand (interned via `Symbol.for`, so every copy resolves the
181
+ * same key) AND expose the exact fields the server's error boundary reads off
182
+ * a recognized `HTTPError` — a numeric `status` and a string `message`. A
183
+ * plain object that merely carries a `status` WITHOUT the brand is rejected.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * import { isHTTPError } from '@src/core'
188
+ *
189
+ * try {
190
+ * await handle(request)
191
+ * } catch (error) {
192
+ * if (isHTTPError(error)) console.log(error.status, error.message)
193
+ * }
194
+ * ```
195
+ */
196
+ function isHTTPError(value) {
197
+ if (value instanceof HTTPError) return true;
198
+ if (typeof value !== "object" || value === null) return false;
199
+ if (!(HTTP_ERROR_BRAND in value) || value[HTTP_ERROR_BRAND] !== true) return false;
200
+ if (!("status" in value) || !("message" in value)) return false;
201
+ return (0, _orkestrel_contract.isNumber)(value.status) && (0, _orkestrel_contract.isString)(value.message);
202
+ }
203
+ //#endregion
204
+ //#region src/core/helpers.ts
205
+ /**
206
+ * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
207
+ * handler into one request handler — the frozen middleware seam (§5.1).
208
+ *
209
+ * @remarks
210
+ * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
211
+ * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
212
+ * `terminal`. Each middleware's `next` may be called with a substituted
213
+ * `Request` (the downstream chain then sees that request instead of the
214
+ * original), called with no argument (the original request continues
215
+ * downstream), or NOT called at all (a short-circuit — the middleware's own
216
+ * returned `Response` is sent, and everything downstream never runs). A
217
+ * SECOND call to the same `next` within one middleware invocation REJECTS —
218
+ * each link runs the chain at most once, so a middleware cannot fork the
219
+ * request into two divergent downstream runs.
220
+ *
221
+ * @typeParam TState - The consumer's opaque per-request state type
222
+ * @param middleware - The ordered chain, outermost first
223
+ * @param terminal - The innermost handler the chain ultimately reaches
224
+ * @returns A single `(request, context) => Promise<Response>` handler running the whole onion
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {
229
+ * const response = await next()
230
+ * response.headers.set('X-Powered-By', 'orkestrel')
231
+ * return response
232
+ * }
233
+ *
234
+ * const handle = compose([withHeader], async () => new Response('ok'))
235
+ * ```
236
+ */
237
+ function compose(middleware, terminal) {
238
+ return async (request, context) => {
239
+ const dispatch = (index, currentRequest) => {
240
+ const layer = middleware[index];
241
+ if (layer === void 0) return terminal(currentRequest, context);
242
+ let called = false;
243
+ const next = (nextRequest) => {
244
+ if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
245
+ called = true;
246
+ return dispatch(index + 1, nextRequest ?? currentRequest);
247
+ };
248
+ return Promise.resolve(layer(currentRequest, context, next));
249
+ };
250
+ return dispatch(0, request);
251
+ };
252
+ }
253
+ /**
254
+ * Parse a raw `Cookie:` request header into a `name → value` lookup.
255
+ *
256
+ * @remarks
257
+ * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
258
+ * cookie-pair separator never precedes it), while every later segment has its
259
+ * inter-pair separator (ASCII space/tab) stripped before parsing — so a
260
+ * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
261
+ * {@link isCookieName} rather than silently reconciling into a
262
+ * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
263
+ * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
264
+ * malformed header yields an empty record, never throws (AGENTS §14).
265
+ *
266
+ * @param header - The raw `Cookie` header value (possibly `undefined`)
267
+ * @returns A record of every parsed cookie, `name → decoded value`
268
+ *
269
+ * @example
270
+ * ```ts
271
+ * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }
272
+ * ```
273
+ */
274
+ function parseCookies(header) {
275
+ const out = {};
276
+ if (header === void 0) return out;
277
+ const segments = header.split(";");
278
+ for (let index = 0; index < segments.length; index += 1) {
279
+ const raw = segments[index] ?? "";
280
+ const segment = index === 0 ? raw : raw.replace(/^[ \t]+/, "");
281
+ const eq = segment.indexOf("=");
282
+ if (eq < 0) continue;
283
+ const name = segment.slice(0, eq);
284
+ if (!isCookieName(name)) continue;
285
+ out[name] = decodeCookieValue(segment.slice(eq + 1).trim());
286
+ }
287
+ return out;
288
+ }
289
+ /**
290
+ * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
291
+ * cookie-token chars with NO surrounding (or interior) whitespace.
292
+ *
293
+ * @remarks
294
+ * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
295
+ * which excludes every whitespace char (ASCII and Unicode) plus controls,
296
+ * separators, and `=`. The {@link parseCookies} hardening that stops a
297
+ * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
298
+ *
299
+ * @param value - The candidate cookie name
300
+ * @returns `true` when `value` is a valid, whitespace-free cookie token
301
+ *
302
+ * @example
303
+ * ```ts
304
+ * isCookieName('__Host-session') // true
305
+ * isCookieName(' __Host-session') // false — whitespace-padded
306
+ * ```
307
+ */
308
+ function isCookieName(value) {
309
+ return /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(value);
310
+ }
311
+ /**
312
+ * Decode a cookie value with `decodeURIComponent`, falling back to the raw
313
+ * text when the value is not valid percent-encoding.
314
+ *
315
+ * @param raw - The raw (trimmed) cookie value
316
+ * @returns The URL-decoded value, or the raw value when decoding would throw
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * decodeCookieValue('a%20b') // 'a b'
321
+ * decodeCookieValue('%') // '%' — malformed escape stays literal
322
+ * ```
323
+ */
324
+ function decodeCookieValue(raw) {
325
+ try {
326
+ return decodeURIComponent(raw);
327
+ } catch {
328
+ return raw;
329
+ }
330
+ }
331
+ /**
332
+ * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
333
+ * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
334
+ * attributes with before emitting them.
335
+ *
336
+ * @remarks
337
+ * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
338
+ * folded header), ASCII/Unicode whitespace, or a C0/DEL control char
339
+ * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`
340
+ * directive. Total — never throws (a bad value returns `false`).
341
+ *
342
+ * @param value - The candidate attribute value (a `Domain` or `Path`)
343
+ * @returns `true` when `value` carries no separator / whitespace / control char
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * isCookieAttribute('/app') // true
348
+ * isCookieAttribute('/a\r\nSet-Cookie: x=y') // false
349
+ * ```
350
+ */
351
+ function isCookieAttribute(value) {
352
+ for (const char of value) {
353
+ if (char === ";" || char === "," || /\s/.test(char)) return false;
354
+ const code = char.codePointAt(0);
355
+ if (code !== void 0 && (code < 32 || code === 127)) return false;
356
+ }
357
+ return true;
358
+ }
359
+ /**
360
+ * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
361
+ *
362
+ * @remarks
363
+ * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
364
+ * appends the present {@link CookieOptions} attributes in canonical order:
365
+ * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
366
+ * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
367
+ * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
368
+ * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
369
+ * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
370
+ * the `secure` option (the spec requires it); an un-resolved `undefined`
371
+ * `secure` here falls to OFF — request-aware callers resolve it first via
372
+ * {@link resolveSecure}.
373
+ *
374
+ * @param name - The cookie name
375
+ * @param value - The cookie value (URL-encoded into the output)
376
+ * @param options - The {@link CookieOptions} attributes; see its fields for defaults
377
+ * @returns The `Set-Cookie` header value
378
+ * @throws {HTTPError} When `domain` or `path` carries an injection char
379
+ *
380
+ * @example
381
+ * ```ts
382
+ * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'
383
+ * ```
384
+ */
385
+ function serializeCookie(name, value, options) {
386
+ const sameSite = options?.sameSite ?? "Lax";
387
+ const domain = options?.domain;
388
+ if (domain !== void 0 && !isCookieAttribute(domain)) throw new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`);
389
+ const path = options?.path ?? "/";
390
+ if (!isCookieAttribute(path)) throw new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`);
391
+ const secure = sameSite === "None" || options?.secure === true;
392
+ const parts = [`${name}=${encodeURIComponent(value)}`];
393
+ if (domain !== void 0) parts.push(`Domain=${domain}`);
394
+ parts.push(`Path=${path}`);
395
+ if (options?.maxAge !== void 0) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`);
396
+ if (options?.httpOnly !== false) parts.push("HttpOnly");
397
+ if (secure) parts.push("Secure");
398
+ parts.push(`SameSite=${sameSite}`);
399
+ return parts.join("; ");
400
+ }
401
+ /**
402
+ * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
403
+ * `secure` setting and whether the request arrived over TLS.
404
+ *
405
+ * @remarks
406
+ * `true` / `false` are explicit overrides. `undefined` (the secure default —
407
+ * the option omitted) resolves to `encrypted` — `Secure` on a TLS
408
+ * connection, off over plaintext HTTP — so a production HTTPS deployment
409
+ * gets `Secure` automatically while local-dev HTTP still works.
410
+ *
411
+ * @param secure - The {@link CookieOptions} `secure` setting
412
+ * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
413
+ * @returns The concrete `Secure` flag to emit
414
+ *
415
+ * @example
416
+ * ```ts
417
+ * resolveSecure(undefined, true) // true
418
+ * resolveSecure(undefined, false) // false
419
+ * resolveSecure(false, true) // false — explicit override wins
420
+ * ```
421
+ */
422
+ function resolveSecure(secure, encrypted) {
423
+ if (secure === true || secure === false) return secure;
424
+ return encrypted;
425
+ }
426
+ /**
427
+ * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
428
+ * clobbering a prior one.
429
+ *
430
+ * @remarks
431
+ * `Headers.append` already accumulates repeated headers (unlike node's
432
+ * `setHeader`), so this is a thin, self-documenting wrapper naming the
433
+ * cookie-append intent — the primitive {@link writeSignedCookie} /
434
+ * {@link clearCookie} use.
435
+ *
436
+ * @param headers - The response `Headers` to write into
437
+ * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
438
+ *
439
+ * @example
440
+ * ```ts
441
+ * const headers = new Headers()
442
+ * appendCookie(headers, serializeCookie('a', '1'))
443
+ * appendCookie(headers, serializeCookie('b', '2'))
444
+ * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
445
+ * ```
446
+ */
447
+ function appendCookie(headers, cookie) {
448
+ headers.append("set-cookie", cookie);
449
+ }
450
+ /**
451
+ * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
452
+ * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
453
+ *
454
+ * @remarks
455
+ * The cookie value is `await signToken(value, { secret })`
456
+ * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
457
+ * cookie — the same secret rotation and tamper rejection, no second HMAC
458
+ * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
459
+ * signing is asynchronous (§3 of the proposal).
460
+ *
461
+ * @param headers - The response `Headers` to write into
462
+ * @param name - The cookie name
463
+ * @param value - The opaque value to sign into the cookie
464
+ * @param secret - The {@link TokenSecret} to sign with (the first secret signs)
465
+ * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * const headers = new Headers()
470
+ * await writeSignedCookie(headers, 'session', 'user-1', 'secret')
471
+ * ```
472
+ */
473
+ async function writeSignedCookie(headers, name, value, secret, options) {
474
+ appendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options));
475
+ }
476
+ /**
477
+ * Read + verify a SIGNED cookie off a request — TOTAL, returning the
478
+ * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
479
+ *
480
+ * @remarks
481
+ * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
482
+ * and verifies it with {@link verifyToken} against `secret` (a rotation list
483
+ * accepts a cookie signed by any of its secrets). ANY failure — an absent
484
+ * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
485
+ *
486
+ * @param request - The `Request` to read the `Cookie` header from
487
+ * @param name - The cookie name to read
488
+ * @param secret - The {@link TokenSecret} (or rotation list) to verify against
489
+ * @returns The embedded value when the cookie is present + valid, else `undefined`
490
+ *
491
+ * @example
492
+ * ```ts
493
+ * const value = await readSignedCookie(request, 'session', 'secret')
494
+ * ```
495
+ */
496
+ async function readSignedCookie(request, name, secret) {
497
+ const cookie = parseCookies(request.headers.get("cookie") ?? void 0)[name];
498
+ return cookie === void 0 ? void 0 : verifyToken(cookie, secret);
499
+ }
500
+ /**
501
+ * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
502
+ *
503
+ * @remarks
504
+ * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
505
+ * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
506
+ * a cookie when those MATCH the one it set).
507
+ *
508
+ * @param headers - The response `Headers` to write into
509
+ * @param name - The cookie name to clear
510
+ * @param options - The {@link CookieOptions} that must match the original cookie
511
+ *
512
+ * @example
513
+ * ```ts
514
+ * const headers = new Headers()
515
+ * clearCookie(headers, 'session')
516
+ * ```
517
+ */
518
+ function clearCookie(headers, name, options) {
519
+ appendCookie(headers, serializeCookie(name, "", {
520
+ ...options,
521
+ maxAge: 0
522
+ }));
523
+ }
524
+ /**
525
+ * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
526
+ * {@link verifyToken} use, and the signature encoding for the HMAC.
527
+ *
528
+ * @param bytes - The bytes to encode
529
+ * @returns The base64url string (no padding)
530
+ *
531
+ * @example
532
+ * ```ts
533
+ * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
534
+ * ```
535
+ */
536
+ function encodeBase64Url(bytes) {
537
+ let binary = "";
538
+ for (const byte of bytes) binary += String.fromCharCode(byte);
539
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
540
+ }
541
+ /**
542
+ * Decode a base64url string back into its bytes — the inverse of
543
+ * {@link encodeBase64Url}.
544
+ *
545
+ * @remarks
546
+ * Restores the standard base64 alphabet + padding before decoding with
547
+ * `atob`. THROWS `DOMException` on a malformed input — callers on the
548
+ * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
549
+ *
550
+ * @param value - The base64url string to decode
551
+ * @returns The decoded bytes
552
+ * @throws {DOMException} When `value` is not valid base64url
553
+ *
554
+ * @example
555
+ * ```ts
556
+ * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
557
+ * ```
558
+ */
559
+ function decodeBase64Url(value) {
560
+ const restored = value.replace(/-/g, "+").replace(/_/g, "/");
561
+ const padding = restored.length % 4 === 0 ? "" : "=".repeat(4 - restored.length % 4);
562
+ const binary = atob(restored + padding);
563
+ const bytes = new Uint8Array(binary.length);
564
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
565
+ return bytes;
566
+ }
567
+ /**
568
+ * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
569
+ *
570
+ * @remarks
571
+ * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
572
+ * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
573
+ * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
574
+ * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
575
+ * {@link TokenSecret} (the current secret, or the head of a rotation list).
576
+ * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
577
+ * misconfigured secret with no usable entry THROWS an {@link HTTPError}
578
+ * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
579
+ * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
580
+ *
581
+ * @param value - The opaque value to embed (a session id, a deployment marker)
582
+ * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}
583
+ * @returns The signed `<payload>.<signature>` token string
584
+ * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
585
+ *
586
+ * @example
587
+ * ```ts
588
+ * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })
589
+ * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined
590
+ * ```
591
+ */
592
+ async function signToken(value, options) {
593
+ const secret = normalizeSecret(options.secret)[0];
594
+ if (secret === void 0) throw new HTTPError(500, "signToken requires at least one secret");
595
+ const exp = options.ttl !== void 0 ? Date.now() + options.ttl : void 0;
596
+ const encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({
597
+ value,
598
+ exp
599
+ })));
600
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
601
+ name: "HMAC",
602
+ hash: "SHA-256"
603
+ }, false, ["sign"]);
604
+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(encoded));
605
+ return `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`;
606
+ }
607
+ /**
608
+ * Verify a stateless token and return its embedded value — TOTAL, never throws.
609
+ *
610
+ * @remarks
611
+ * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
612
+ * value containing dots survives), and checks the payload's HMAC-SHA256
613
+ * signature against EACH {@link TokenSecret} candidate via
614
+ * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
615
+ * retired, §3 of the proposal), accepting the token on the first match (the
616
+ * rotation path). It then decodes + narrows the payload (`isRecord` +
617
+ * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
618
+ * rejects an expired token. ANY failure — a malformed token, a bad signature,
619
+ * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
620
+ * yields `undefined` rather than throwing.
621
+ *
622
+ * @param token - The candidate token string (from a request header/cookie)
623
+ * @param secret - The {@link TokenSecret} (or rotation list) to verify against
624
+ * @returns The embedded value when the token is valid + unexpired, else `undefined`
625
+ *
626
+ * @example
627
+ * ```ts
628
+ * await verifyToken('bad.token', 'shh') // undefined — never throws
629
+ * ```
630
+ */
631
+ async function verifyToken(token, secret) {
632
+ const secrets = normalizeSecret(secret);
633
+ if (secrets.length === 0) return void 0;
634
+ const dot = token.lastIndexOf(".");
635
+ if (dot < 0) return void 0;
636
+ const encoded = token.slice(0, dot);
637
+ const signatureText = token.slice(dot + 1);
638
+ try {
639
+ const signature = decodeBase64Url(signatureText);
640
+ const data = new TextEncoder().encode(encoded);
641
+ for (const candidate of secrets) {
642
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(candidate), {
643
+ name: "HMAC",
644
+ hash: "SHA-256"
645
+ }, false, ["verify"]);
646
+ if (await crypto.subtle.verify("HMAC", key, signature, data)) return decodeTokenPayload(encoded);
647
+ }
648
+ return;
649
+ } catch {
650
+ return;
651
+ }
652
+ }
653
+ /**
654
+ * Decode + narrow a signed token's base64url JSON payload, honoring its
655
+ * expiry — the shared decode step {@link verifyToken} applies after a
656
+ * signature match.
657
+ *
658
+ * @remarks
659
+ * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
660
+ * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
661
+ * TOTAL — any decode/shape/expiry failure yields `undefined`.
662
+ *
663
+ * @param encoded - The base64url-encoded payload segment (before the last `.`)
664
+ * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
665
+ */
666
+ function decodeTokenPayload(encoded) {
667
+ try {
668
+ const text = new TextDecoder().decode(decodeBase64Url(encoded));
669
+ const payload = JSON.parse(text);
670
+ if (!(0, _orkestrel_contract.isRecord)(payload)) return void 0;
671
+ if (typeof payload.value !== "string") return void 0;
672
+ if (payload.exp !== void 0 && typeof payload.exp !== "number") return void 0;
673
+ if (payload.exp !== void 0 && Date.now() >= payload.exp) return void 0;
674
+ return payload.value;
675
+ } catch {
676
+ return;
677
+ }
678
+ }
679
+ /**
680
+ * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
681
+ * backs both {@link signToken} and {@link verifyToken}.
682
+ *
683
+ * @remarks
684
+ * A single string becomes a one-element list; a rotation list is copied. Any
685
+ * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
686
+ * emptiness test; each kept secret is stored VERBATIM). The first kept
687
+ * element is the signing secret; all kept are accepted on verify.
688
+ *
689
+ * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
690
+ * @returns The kept (non-blank) secrets, in order — empty when none is usable
691
+ *
692
+ * @example
693
+ * ```ts
694
+ * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']
695
+ * ```
696
+ */
697
+ function normalizeSecret(secret) {
698
+ return (typeof secret === "string" ? [secret] : [...secret]).filter((entry) => entry.trim().length > 0);
699
+ }
700
+ /**
701
+ * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
702
+ * into its q-sorted entries.
703
+ *
704
+ * @remarks
705
+ * Splits on `,`; for each part takes the token before the first `;`
706
+ * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
707
+ * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
708
+ * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
709
+ * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
710
+ * the header's own order within a tie — a single pass with no backtracking,
711
+ * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
712
+ * empty/malformed header yields `[]`/best-effort entries, never throws.
713
+ *
714
+ * @param header - The raw weighted header value
715
+ * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending
716
+ *
717
+ * @example
718
+ * ```ts
719
+ * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')
720
+ * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]
721
+ * ```
722
+ */
723
+ function parseAcceptHeader(header) {
724
+ const entries = [];
725
+ for (const part of header.split(",")) {
726
+ const trimmed = part.trim();
727
+ if (trimmed.length === 0) continue;
728
+ const semicolon = trimmed.indexOf(";");
729
+ const value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase();
730
+ if (value.length === 0) continue;
731
+ let q = 1;
732
+ if (semicolon !== -1) {
733
+ const match = /;\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon));
734
+ if (match !== null) {
735
+ const parsed = Number(match[1]);
736
+ if (Number.isFinite(parsed)) q = Math.min(1, Math.max(0, parsed));
737
+ }
738
+ }
739
+ entries.push({
740
+ value,
741
+ q
742
+ });
743
+ }
744
+ return entries.map((entry, index) => ({
745
+ entry,
746
+ index
747
+ })).sort((a, b) => b.entry.q - a.entry.q || a.index - b.index).map((ranked) => ranked.entry);
748
+ }
749
+ /**
750
+ * The client's quality (q) for one content-coding from the parsed
751
+ * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
752
+ * server-preference selection.
753
+ *
754
+ * @remarks
755
+ * Prefers an EXACT named match (including an explicit `;q=0` rejection);
756
+ * failing that, a bare `*` wildcard's q applies. A coding that is neither
757
+ * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
758
+ * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
759
+ *
760
+ * @param entries - The parsed {@link AcceptEntry} list
761
+ * @param coding - The candidate coding to score
762
+ * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
763
+ *
764
+ * @example
765
+ * ```ts
766
+ * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
767
+ * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
768
+ * ```
769
+ */
770
+ function codingQuality(entries, coding) {
771
+ const named = entries.find((entry) => entry.value === coding);
772
+ if (named !== void 0) return named.q;
773
+ return entries.find((entry) => entry.value === "*")?.q ?? 0;
774
+ }
775
+ /**
776
+ * Select the best content-coding for an `Accept-Encoding` header from the
777
+ * codings the server offers.
778
+ *
779
+ * @remarks
780
+ * Parses the header ({@link parseAcceptHeader}) and scores each `available`
781
+ * coding in the SERVER's preference order ({@link codingQuality}), keeping
782
+ * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
783
+ * client-side tie). Returns `undefined` when the client accepts none of
784
+ * `available` (identity — no compression). TOTAL on hostile input.
785
+ *
786
+ * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
787
+ * @param header - The raw `Accept-Encoding` header value
788
+ * @param available - The codings the server offers, in preference (tie-break) order
789
+ * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
790
+ *
791
+ * @example
792
+ * ```ts
793
+ * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
794
+ * ```
795
+ */
796
+ function negotiateEncoding(header, available) {
797
+ if (available.length === 0) return void 0;
798
+ const entries = parseAcceptHeader(header);
799
+ let best;
800
+ let bestQuality = 0;
801
+ for (const coding of available) {
802
+ const quality = codingQuality(entries, coding);
803
+ if (quality > bestQuality) {
804
+ best = coding;
805
+ bestQuality = quality;
806
+ }
807
+ }
808
+ return best;
809
+ }
810
+ /**
811
+ * Rank + quality of one `candidate` media type against the parsed `Accept`
812
+ * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
813
+ * uses to score each `available` candidate.
814
+ *
815
+ * @remarks
816
+ * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the
817
+ * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact
818
+ * `;q=0` entry explicitly rejects the candidate outright (returns
819
+ * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
820
+ * (less specific) coverage, so a later more-specific match can still allow
821
+ * it. Among multiple matching entries, the lowest `rank` wins, and among a
822
+ * rank tie the highest `q` wins.
823
+ *
824
+ * @param entries - The parsed {@link AcceptEntry} list
825
+ * @param candidate - The candidate media type to score (e.g. `'text/html'`)
826
+ * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
827
+ *
828
+ * @example
829
+ * ```ts
830
+ * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')
831
+ * // { q: 1, rank: 0 }
832
+ * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }
833
+ * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
834
+ * ```
835
+ */
836
+ function matchMediaType(entries, candidate) {
837
+ const slash = candidate.indexOf("/");
838
+ const type = slash === -1 ? candidate : candidate.slice(0, slash);
839
+ let best;
840
+ for (const entry of entries) {
841
+ let rank;
842
+ if (entry.value === candidate) rank = 0;
843
+ else if (entry.value === `${type}/*`) rank = 1;
844
+ else if (entry.value === "*/*") rank = 2;
845
+ if (rank === void 0) continue;
846
+ if (entry.q === 0) {
847
+ if (rank === 0) return void 0;
848
+ continue;
849
+ }
850
+ if (best === void 0 || rank < best.rank || rank === best.rank && entry.q > best.q) best = {
851
+ q: entry.q,
852
+ rank
853
+ };
854
+ }
855
+ return best;
856
+ }
857
+ /**
858
+ * The client's quality for one `candidate` language from the parsed
859
+ * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
860
+ *
861
+ * @remarks
862
+ * Prefers an exact match, then a primary-tag prefix match (`en` accepts
863
+ * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
864
+ * is an explicit rejection).
865
+ *
866
+ * @param entries - The parsed {@link AcceptEntry} list
867
+ * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
868
+ * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
869
+ *
870
+ * @example
871
+ * ```ts
872
+ * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
873
+ * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
874
+ * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
875
+ * ```
876
+ */
877
+ function languageQuality(entries, candidate) {
878
+ const lower = candidate.toLowerCase();
879
+ const primary = lower.split("-")[0];
880
+ let named;
881
+ let prefixed;
882
+ let wildcard;
883
+ for (const entry of entries) {
884
+ const entryPrimary = entry.value.split("-")[0];
885
+ if (entry.value === lower) named = entry.q;
886
+ else if (entryPrimary === primary) {
887
+ if (prefixed === void 0) prefixed = entry.q;
888
+ } else if (entry.value === "*") wildcard = entry.q;
889
+ }
890
+ if (named !== void 0) return named;
891
+ if (prefixed !== void 0) return prefixed;
892
+ return wildcard ?? 0;
893
+ }
894
+ /**
895
+ * Whether a `Content-Type` is worth compressing.
896
+ *
897
+ * @remarks
898
+ * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
899
+ * type, a `+json`/`+xml` structured suffix, or one of the explicit
900
+ * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
901
+ * binary (`image/png`, `application/zip`) is NOT compressible. An
902
+ * absent/empty type is not compressible. TOTAL.
903
+ *
904
+ * @param type - The response `Content-Type` header value (with or without parameters)
905
+ * @returns `true` when the type is text-shaped and worth compressing
906
+ *
907
+ * @example
908
+ * ```ts
909
+ * isCompressibleType('application/json; charset=utf-8') // true
910
+ * isCompressibleType('image/png') // false
911
+ * ```
912
+ */
913
+ function isCompressibleType(type) {
914
+ const semicolon = type.indexOf(";");
915
+ const bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase();
916
+ if (bare.length === 0) return false;
917
+ if (bare.startsWith("text/")) return true;
918
+ if (bare.endsWith("+json") || bare.endsWith("+xml")) return true;
919
+ return COMPRESSIBLE_TYPES.has(bare);
920
+ }
921
+ /**
922
+ * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
923
+ *
924
+ * @remarks
925
+ * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
926
+ * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
927
+ * default, encoding-AGNOSTIC, so the tag survives a downstream content
928
+ * re-encoding (gzip) and still matches on revalidation — or a STRONG one
929
+ * (`"<hash>"`, byte-identity) when `weak` is `false`.
930
+ *
931
+ * @param body - The full (uncompressed) response body to hash
932
+ * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
933
+ * @returns The `ETag` header value
934
+ *
935
+ * @example
936
+ * ```ts
937
+ * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/"…sha256-hex…"'
938
+ * ```
939
+ */
940
+ async function computeBodyETag(body, weak = true) {
941
+ const digest = await crypto.subtle.digest("SHA-256", body);
942
+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
943
+ return weak ? `W/"${hex}"` : `"${hex}"`;
944
+ }
945
+ /**
946
+ * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
947
+ * comparison body — the reduction {@link matchesETag} applies to both sides
948
+ * before the RFC 7232 §2.3.2 weak comparison.
949
+ *
950
+ * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
951
+ * @returns The tag with any leading `W/` removed (the quotes preserved)
952
+ *
953
+ * @example
954
+ * ```ts
955
+ * unwrapETag('W/"abc"') // '"abc"'
956
+ * ```
957
+ */
958
+ function unwrapETag(tag) {
959
+ const trimmed = tag.trim();
960
+ return trimmed.startsWith("W/") ? trimmed.slice(2) : trimmed;
961
+ }
962
+ /**
963
+ * Whether a request's `If-None-Match` header matches a resource's current
964
+ * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
965
+ *
966
+ * @remarks
967
+ * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
968
+ * listed tag matches), or the `*` wildcard (matches ANY current
969
+ * representation — only a list of exactly `*` is the wildcard). Comparison is
970
+ * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
971
+ * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
972
+ * malformed/empty header matches nothing, never throws.
973
+ *
974
+ * @param header - The raw `If-None-Match` header value
975
+ * @param etag - The resource's current `ETag`
976
+ * @returns `true` when the conditional matches (the caller answers `304`)
977
+ *
978
+ * @example
979
+ * ```ts
980
+ * matchesETag('"abc", W/"def"', 'W/"abc"') // true — weak comparison
981
+ * matchesETag('*', 'W/"anything"') // true — wildcard
982
+ * ```
983
+ */
984
+ function matchesETag(header, etag) {
985
+ const trimmed = header.trim();
986
+ if (trimmed === "*") return true;
987
+ const target = unwrapETag(etag);
988
+ for (const member of trimmed.split(",")) {
989
+ const candidate = member.trim();
990
+ if (candidate.length === 0) continue;
991
+ if (unwrapETag(candidate) === target) return true;
992
+ }
993
+ return false;
994
+ }
995
+ /**
996
+ * Parse an HTTP `Range` request header against a known resource `size` —
997
+ * TOTAL, returning a {@link RangeSpec} or `undefined`.
998
+ *
999
+ * @remarks
1000
+ * Handles the three single-range `bytes=` forms — closed (`start-end`), open
1001
+ * (`start-`), and suffix (`-suffixLength`) — clamping the window to
1002
+ * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
1003
+ * `{ satisfiable: true, start, end }` for an overlapping range,
1004
+ * `{ satisfiable: false }` for a range wholly past the resource, and
1005
+ * `undefined` for the "serve the whole resource" case: an ABSENT header, a
1006
+ * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
1007
+ * supported), or any malformed/non-finite bound. NEVER throws on a hostile
1008
+ * header.
1009
+ *
1010
+ * @param header - The raw `Range` header value
1011
+ * @param size - The resource's total byte length
1012
+ * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource
1013
+ *
1014
+ * @example
1015
+ * ```ts
1016
+ * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
1017
+ * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
1018
+ * ```
1019
+ */
1020
+ function parseRange(header, size) {
1021
+ if (header === void 0) return void 0;
1022
+ const match = /^bytes=(.*)$/.exec(header.trim());
1023
+ if (match === null) return void 0;
1024
+ const spec = match[1].trim();
1025
+ if (spec.includes(",")) return void 0;
1026
+ const dash = spec.indexOf("-");
1027
+ if (dash < 0) return void 0;
1028
+ const startText = spec.slice(0, dash).trim();
1029
+ const endText = spec.slice(dash + 1).trim();
1030
+ if (startText === "") {
1031
+ const suffix = Number(endText);
1032
+ if (endText === "" || !Number.isInteger(suffix) || suffix <= 0) return void 0;
1033
+ if (size === 0) return { satisfiable: false };
1034
+ return {
1035
+ satisfiable: true,
1036
+ start: Math.max(0, size - suffix),
1037
+ end: size - 1
1038
+ };
1039
+ }
1040
+ const start = Number(startText);
1041
+ if (!Number.isInteger(start) || start < 0) return void 0;
1042
+ if (start >= size) return { satisfiable: false };
1043
+ if (endText === "") return {
1044
+ satisfiable: true,
1045
+ start,
1046
+ end: size - 1
1047
+ };
1048
+ const end = Number(endText);
1049
+ if (!Number.isInteger(end) || end < start) return void 0;
1050
+ return {
1051
+ satisfiable: true,
1052
+ start,
1053
+ end: Math.min(end, size - 1)
1054
+ };
1055
+ }
1056
+ /**
1057
+ * Resolve the `Access-Control-Allow-Origin` value for a request.
1058
+ *
1059
+ * @remarks
1060
+ * `'*'` and a single origin string pass straight through. An allow-list
1061
+ * echoes the request's `Origin` only when it is present in the list, else
1062
+ * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
1063
+ * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1064
+ * NEVER reflected even if `'null'` were listed, closing the hostile-context
1065
+ * cross-origin-access hole.
1066
+ *
1067
+ * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
1068
+ * @param requestOrigin - The request's `Origin` header value, if present
1069
+ * @returns The allow-origin value to send, or `undefined` to set no header
1070
+ *
1071
+ * @example
1072
+ * ```ts
1073
+ * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'
1074
+ * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected
1075
+ * ```
1076
+ */
1077
+ function resolveOrigin(origin, requestOrigin) {
1078
+ if ((0, _orkestrel_contract.isString)(origin)) return origin;
1079
+ if (!(0, _orkestrel_contract.isString)(requestOrigin)) return void 0;
1080
+ if (requestOrigin === "null") return void 0;
1081
+ return origin.includes(requestOrigin) ? requestOrigin : void 0;
1082
+ }
1083
+ /**
1084
+ * Merge a `Vary` value into an existing `Vary` header without duplication.
1085
+ *
1086
+ * @remarks
1087
+ * Splits `existing` on `,`, trims each member, and appends `value` only when
1088
+ * no existing member already matches it case-insensitively (`Vary` header
1089
+ * names are case-insensitive). Preserves the existing members' order and
1090
+ * appends the new one last.
1091
+ *
1092
+ * @param existing - The current `Vary` header value, if any
1093
+ * @param value - The header name to ensure is listed
1094
+ * @returns The merged `Vary` value
1095
+ *
1096
+ * @example
1097
+ * ```ts
1098
+ * mergeVary(undefined, 'Origin') // 'Origin'
1099
+ * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)
1100
+ * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'
1101
+ * ```
1102
+ */
1103
+ function mergeVary(existing, value) {
1104
+ const members = existing === void 0 ? [] : existing.split(",").map((member) => member.trim()).filter((member) => member.length > 0);
1105
+ return members.some((member) => member.toLowerCase() === value.toLowerCase()) ? members.join(", ") : [...members, value].join(", ");
1106
+ }
1107
+ /**
1108
+ * Resolve one opt-out, value-bearing security header.
1109
+ *
1110
+ * @remarks
1111
+ * The shared "a `string` value, or `false` to omit, or a default when unset"
1112
+ * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
1113
+ * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
1114
+ * override, `undefined` (unset) ⇒ `fallback` (the secure default).
1115
+ *
1116
+ * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default
1117
+ * @param fallback - The secure-default value used when `value` is unset
1118
+ * @returns The header value to set, or `undefined` to omit the header
1119
+ *
1120
+ * @example
1121
+ * ```ts
1122
+ * resolveSecurityHeader(undefined, 'DENY') // 'DENY'
1123
+ * resolveSecurityHeader(false, 'DENY') // undefined — omitted
1124
+ * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override
1125
+ * ```
1126
+ */
1127
+ function resolveSecurityHeader(value, fallback) {
1128
+ if (value === false) return void 0;
1129
+ return value ?? fallback;
1130
+ }
1131
+ /**
1132
+ * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1133
+ * header + `context.state`.
1134
+ *
1135
+ * @remarks
1136
+ * A request id is echoed RAW into a response header and log lines, so an
1137
+ * untrusted one is a header-injection + log-injection + DoS vector. This
1138
+ * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
1139
+ * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
1140
+ * TOTAL — never throws.
1141
+ *
1142
+ * @param value - The candidate incoming request id
1143
+ * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
1144
+ *
1145
+ * @example
1146
+ * ```ts
1147
+ * isValidRequestId('req_abc-123') // true
1148
+ * isValidRequestId('bad\r\nheader') // false
1149
+ * ```
1150
+ */
1151
+ function isValidRequestId(value) {
1152
+ return REQUEST_ID_PATTERN.test(value);
1153
+ }
1154
+ /**
1155
+ * Compute the `/64` network of a full IPv6 address, or `undefined` when the
1156
+ * input is not a plain IPv6 address to collapse.
1157
+ *
1158
+ * @remarks
1159
+ * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
1160
+ * is the identity) or any string that does not expand to exactly eight
1161
+ * hextets. Expands a single `::` into the missing zero hextets, takes the
1162
+ * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
1163
+ * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
1164
+ * first. Total — a malformed address returns `undefined`.
1165
+ *
1166
+ * @param address - The candidate IPv6 address
1167
+ * @returns The `/64` network string, or `undefined` when not a plain IPv6 address
1168
+ *
1169
+ * @example
1170
+ * ```ts
1171
+ * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1172
+ * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1173
+ * ```
1174
+ */
1175
+ function ipv6Network(address) {
1176
+ if (/^::ffff:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i.test(address)) return void 0;
1177
+ const percent = address.indexOf("%");
1178
+ const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
1179
+ if (halves.length > 2) return void 0;
1180
+ const head = halves[0] === "" ? [] : halves[0].split(":");
1181
+ const tail = halves.length === 2 ? halves[1] === "" ? [] : halves[1].split(":") : [];
1182
+ let groups;
1183
+ if (halves.length === 2) {
1184
+ const missing = 8 - head.length - tail.length;
1185
+ if (missing < 0) return void 0;
1186
+ groups = [
1187
+ ...head,
1188
+ ...Array.from({ length: missing }, () => "0"),
1189
+ ...tail
1190
+ ];
1191
+ } else groups = head;
1192
+ if (groups.length !== 8) return void 0;
1193
+ const prefix = [];
1194
+ for (const group of groups.slice(0, 4)) {
1195
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return void 0;
1196
+ prefix.push(Number.parseInt(group, 16).toString(16));
1197
+ }
1198
+ return `${prefix.join(":")}::/64`;
1199
+ }
1200
+ /**
1201
+ * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
1202
+ * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
1203
+ *
1204
+ * @remarks
1205
+ * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
1206
+ * per-`/128` rate limit is trivially bypassed by rotating host bits — the
1207
+ * real identity is the `/64` network. Delegates the IPv6 collapse to
1208
+ * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
1209
+ * a malformed string) is kept unchanged.
1210
+ *
1211
+ * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
1212
+ * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
1213
+ *
1214
+ * @example
1215
+ * ```ts
1216
+ * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1217
+ * clientRateKey('192.0.2.1') // '192.0.2.1'
1218
+ * ```
1219
+ */
1220
+ function clientRateKey(address) {
1221
+ return ipv6Network(address) ?? address;
1222
+ }
1223
+ /**
1224
+ * Serialize one {@link SSEMessage} to the SSE wire.
1225
+ *
1226
+ * @remarks
1227
+ * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
1228
+ * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1229
+ * (so a consuming parser's multi-`data` concat reproduces the original
1230
+ * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
1231
+ * a `data:` line), then the terminating blank line.
1232
+ *
1233
+ * @param message - The event to serialize
1234
+ * @returns The SSE wire text for the event (terminated by a blank line)
1235
+ *
1236
+ * @example
1237
+ * ```ts
1238
+ * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\ndata: hello\n\n'
1239
+ * serializeEvent({ data: 'multi\nline' }) // 'data: multi\ndata: line\n\n'
1240
+ * ```
1241
+ */
1242
+ function serializeEvent(message) {
1243
+ const lines = [];
1244
+ if (message.event !== void 0) lines.push(`event: ${message.event}`);
1245
+ if (message.id !== void 0) lines.push(`id: ${message.id}`);
1246
+ if (message.retry !== void 0) lines.push(`retry: ${message.retry}`);
1247
+ for (const segment of message.data.split(/\r\n|\r|\n/)) lines.push(`data: ${segment}`);
1248
+ return `${lines.join("\n")}\n\n`;
1249
+ }
1250
+ /**
1251
+ * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1252
+ * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
1253
+ *
1254
+ * @remarks
1255
+ * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
1256
+ * merged under any `options.headers` (a seam-owned key is never overridden),
1257
+ * at `options.status` (default `200`). The returned {@link StreamInterface}'s
1258
+ * `write` serializes one message ({@link serializeEvent}) and enqueues it;
1259
+ * `comment` writes a `: text` keep-alive line a conforming parser ignores;
1260
+ * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
1261
+ * by `end()`, or the consumer cancelled the stream), so a late write never
1262
+ * throws.
1263
+ *
1264
+ * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
1265
+ * @returns The {@link StreamInterface} handle
1266
+ *
1267
+ * @example
1268
+ * ```ts
1269
+ * const stream = openStream()
1270
+ * stream.write({ event: 'token', data: 'hello' })
1271
+ * stream.end()
1272
+ * // return stream.response from the route handler
1273
+ * ```
1274
+ */
1275
+ function openStream(options) {
1276
+ const encoder = new TextEncoder();
1277
+ let closed = false;
1278
+ let controller;
1279
+ const body = new ReadableStream({
1280
+ start(streamController) {
1281
+ controller = streamController;
1282
+ },
1283
+ cancel() {
1284
+ closed = true;
1285
+ }
1286
+ });
1287
+ const headers = new Headers({
1288
+ ...SSE_HEADERS,
1289
+ ...options?.headers
1290
+ });
1291
+ const response = new Response(body, {
1292
+ status: options?.status ?? 200,
1293
+ headers
1294
+ });
1295
+ const enqueue = (text) => {
1296
+ if (closed || controller === void 0) return;
1297
+ controller.enqueue(encoder.encode(text));
1298
+ };
1299
+ return {
1300
+ response,
1301
+ get closed() {
1302
+ return closed;
1303
+ },
1304
+ write(message) {
1305
+ enqueue(serializeEvent(message));
1306
+ },
1307
+ comment(text) {
1308
+ enqueue(`: ${text}\n\n`);
1309
+ },
1310
+ end() {
1311
+ if (closed) return;
1312
+ closed = true;
1313
+ controller?.close();
1314
+ }
1315
+ };
1316
+ }
1317
+ /**
1318
+ * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1319
+ * or `prototype` — the three keys that, assigned onto a normal object, can
1320
+ * reach and mutate `Object.prototype`.
1321
+ *
1322
+ * @param key - The candidate object key
1323
+ * @returns `true` when `key` is one of the three prototype-pollution keys
1324
+ *
1325
+ * @example
1326
+ * ```ts
1327
+ * isDangerousKey('__proto__') // true
1328
+ * isDangerousKey('name') // false
1329
+ * ```
1330
+ */
1331
+ function isDangerousKey(key) {
1332
+ return key === "__proto__" || key === "constructor" || key === "prototype";
1333
+ }
1334
+ /**
1335
+ * Recursively STRIP the prototype-pollution keys from a parsed value IN
1336
+ * PLACE.
1337
+ *
1338
+ * @remarks
1339
+ * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
1340
+ * enumerable `__proto__` DATA property — but that own key becomes a
1341
+ * pollution gadget the moment a downstream deep-merge copies it onto a live
1342
+ * object. This walks the value and `delete`s any own {@link isDangerousKey}
1343
+ * key at every depth, recursing into nested objects + array elements.
1344
+ * Primitives/`null` pass through untouched. Total — never throws. Mutates the
1345
+ * freshly-parsed value (which nothing else holds yet).
1346
+ *
1347
+ * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
1348
+ * @returns The same `value`, with every dangerous key removed at every depth
1349
+ *
1350
+ * @example
1351
+ * ```ts
1352
+ * scrubPrototype(JSON.parse('{"__proto__":{"polluted":true},"name":"ok"}'))
1353
+ * // { name: 'ok' } — the __proto__ key is gone
1354
+ * ```
1355
+ */
1356
+ function scrubPrototype(value) {
1357
+ if (Array.isArray(value)) {
1358
+ for (const item of value) scrubPrototype(item);
1359
+ return value;
1360
+ }
1361
+ if ((0, _orkestrel_contract.isRecord)(value)) {
1362
+ for (const key of Object.keys(value)) {
1363
+ if (isDangerousKey(key)) {
1364
+ Reflect.deleteProperty(value, key);
1365
+ continue;
1366
+ }
1367
+ scrubPrototype(value[key]);
1368
+ }
1369
+ return value;
1370
+ }
1371
+ return value;
1372
+ }
1373
+ /**
1374
+ * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
1375
+ *
1376
+ * @remarks
1377
+ * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
1378
+ * throwing a {@link ContentTooLargeError} (413) the instant the running total
1379
+ * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
1380
+ * collecting an unbounded body. A bodyless request (`request.body === null`)
1381
+ * resolves an empty array. A non-positive `limit` means unbounded.
1382
+ *
1383
+ * @param request - The `Request` to drain
1384
+ * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
1385
+ * @returns The full request body as one `Uint8Array`
1386
+ * @throws {ContentTooLargeError} When the body exceeds `limit`
1387
+ *
1388
+ * @example
1389
+ * ```ts
1390
+ * const bytes = await collectRequestBody(request, 1_048_576)
1391
+ * ```
1392
+ */
1393
+ async function collectRequestBody(request, limit) {
1394
+ if (request.body === null) return /* @__PURE__ */ new Uint8Array(0);
1395
+ const reader = request.body.getReader();
1396
+ const chunks = [];
1397
+ let total = 0;
1398
+ for (;;) {
1399
+ const { done, value } = await reader.read();
1400
+ if (done) break;
1401
+ total += value.byteLength;
1402
+ if (limit > 0 && total > limit) {
1403
+ await reader.cancel();
1404
+ throw new ContentTooLargeError(limit);
1405
+ }
1406
+ chunks.push(value);
1407
+ }
1408
+ const merged = new Uint8Array(total);
1409
+ let offset = 0;
1410
+ for (const chunk of chunks) {
1411
+ merged.set(chunk, offset);
1412
+ offset += chunk.byteLength;
1413
+ }
1414
+ return merged;
1415
+ }
1416
+ /**
1417
+ * Narrow a raw `Content-Encoding` header value to a decompressible
1418
+ * {@link Encoding} — the boundary guard {@link readBody} uses to decide
1419
+ * whether a request body needs transparent decompression.
1420
+ *
1421
+ * @remarks
1422
+ * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1423
+ * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
1424
+ * the proposal). An absent header, `identity`, an unknown value, or a
1425
+ * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1426
+ * TOTAL — never asserts the loose `string | null` header.
1427
+ *
1428
+ * @param header - The raw `Content-Encoding` header value
1429
+ * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
1430
+ *
1431
+ * @example
1432
+ * ```ts
1433
+ * requestEncoding('gzip') // 'gzip'
1434
+ * requestEncoding('br') // undefined — unsupported by DecompressionStream
1435
+ * ```
1436
+ */
1437
+ function requestEncoding(header) {
1438
+ if (!(0, _orkestrel_contract.isString)(header)) return void 0;
1439
+ const value = header.trim().toLowerCase();
1440
+ return value === "gzip" || value === "deflate" ? value : void 0;
1441
+ }
1442
+ /**
1443
+ * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
1444
+ * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
1445
+ * the zip-bomb defense.
1446
+ *
1447
+ * @remarks
1448
+ * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
1449
+ * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
1450
+ * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
1451
+ * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
1452
+ * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
1453
+ * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
1454
+ * (never conflated with the cap). A non-positive `cap` means uncapped.
1455
+ *
1456
+ * @param bytes - The compressed bytes to decompress
1457
+ * @param encoding - The {@link Encoding} the bytes are compressed with
1458
+ * @param cap - The maximum decompressed byte count; a non-positive value means uncapped
1459
+ * @returns The decompressed bytes
1460
+ * @throws {ContentTooLargeError} When decompressed output would exceed `cap`
1461
+ * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)
1462
+ */
1463
+ async function decompressRequestBody(bytes, encoding, cap) {
1464
+ let total = 0;
1465
+ const capStream = new TransformStream({ transform(chunk, controller) {
1466
+ total += chunk.byteLength;
1467
+ if (cap > 0 && total > cap) {
1468
+ controller.error(new ContentTooLargeError(cap));
1469
+ return;
1470
+ }
1471
+ controller.enqueue(chunk);
1472
+ } });
1473
+ const reader = new ReadableStream({ start(controller) {
1474
+ controller.enqueue(bytes);
1475
+ controller.close();
1476
+ } }).pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream).getReader();
1477
+ const chunks = [];
1478
+ let size = 0;
1479
+ try {
1480
+ for (;;) {
1481
+ const { done, value } = await reader.read();
1482
+ if (done) break;
1483
+ chunks.push(value);
1484
+ size += value.byteLength;
1485
+ }
1486
+ } catch (error) {
1487
+ if (error instanceof ContentTooLargeError) throw error;
1488
+ throw new HTTPError(400, "malformed compressed request body");
1489
+ }
1490
+ const merged = new Uint8Array(size);
1491
+ let offset = 0;
1492
+ for (const chunk of chunks) {
1493
+ merged.set(chunk, offset);
1494
+ offset += chunk.byteLength;
1495
+ }
1496
+ return merged;
1497
+ }
1498
+ /**
1499
+ * Collect + decode a `Request` body — the shared body-collection pipeline
1500
+ * surfaced to middleware and handlers as the middleware context's cached
1501
+ * `body()`.
1502
+ *
1503
+ * @remarks
1504
+ * Collects the wire body capped at `options.limit` bytes ({@link
1505
+ * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),
1506
+ * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body
1507
+ * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
1508
+ * `options.decompression`, default {@link
1509
+ * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1510
+ * content type: `application/json` is parsed via `@orkestrel/contract`'s
1511
+ * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1512
+ * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1513
+ * decodes to `undefined`.
1514
+ *
1515
+ * @param request - The `Request` to read the body from
1516
+ * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1517
+ * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
1518
+ * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1519
+ * @throws {HTTPError} When the compressed body is corrupt (400)
1520
+ *
1521
+ * @example
1522
+ * ```ts
1523
+ * const body = await readBody(request, { limit: 1_048_576 })
1524
+ * ```
1525
+ */
1526
+ async function readBody(request, options) {
1527
+ const limit = options?.limit ?? 1048576;
1528
+ const decompression = options?.decompression ?? 16777216;
1529
+ const wire = await collectRequestBody(request, limit);
1530
+ const encoding = requestEncoding(request.headers.get("content-encoding"));
1531
+ const bytes = encoding === void 0 ? wire : await decompressRequestBody(wire, encoding, decompression);
1532
+ if (bytes.length === 0) return void 0;
1533
+ const contentType = request.headers.get("content-type");
1534
+ const semicolon = contentType === null ? -1 : contentType.indexOf(";");
1535
+ const bareType = contentType === null ? "" : (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase();
1536
+ const text = new TextDecoder().decode(bytes);
1537
+ if (bareType === "application/json") return scrubPrototype((0, _orkestrel_contract.parseJSON)(text));
1538
+ return text;
1539
+ }
1540
+ //#endregion
1541
+ //#region src/core/Negotiator.ts
1542
+ /**
1543
+ * The content-negotiation machine over the weighted `Accept` family — a
1544
+ * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
1545
+ * {@link NegotiatorInterface}.
1546
+ *
1547
+ * @remarks
1548
+ * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
1549
+ * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
1550
+ * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
1551
+ * rest of the substrate uses — one parser, never two. `format` reads the
1552
+ * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
1553
+ * the winner — or answers `406 Not Acceptable`.
1554
+ *
1555
+ * @example
1556
+ * ```ts
1557
+ * const negotiator = new Negotiator()
1558
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
1559
+ * // 'text/html'
1560
+ * ```
1561
+ */
1562
+ var Negotiator = class {
1563
+ negotiate(header, available) {
1564
+ if (available.length === 0) return void 0;
1565
+ const entries = parseAcceptHeader(header);
1566
+ if (entries.length === 0) return available[0];
1567
+ let best;
1568
+ let bestQuality = 0;
1569
+ let bestRank = Number.POSITIVE_INFINITY;
1570
+ for (const candidate of available) {
1571
+ const match = matchMediaType(entries, candidate);
1572
+ if (match === void 0) continue;
1573
+ const { q, rank } = match;
1574
+ if (q > bestQuality || q === bestQuality && rank < bestRank) {
1575
+ best = candidate;
1576
+ bestQuality = q;
1577
+ bestRank = rank;
1578
+ }
1579
+ }
1580
+ return best;
1581
+ }
1582
+ encoding(header, available) {
1583
+ return negotiateEncoding(header, available);
1584
+ }
1585
+ language(header, available) {
1586
+ if (available.length === 0) return void 0;
1587
+ const entries = parseAcceptHeader(header);
1588
+ if (entries.length === 0) return available[0];
1589
+ let best;
1590
+ let bestQuality = 0;
1591
+ for (const candidate of available) {
1592
+ const quality = languageQuality(entries, candidate);
1593
+ if (quality > bestQuality) {
1594
+ best = candidate;
1595
+ bestQuality = quality;
1596
+ }
1597
+ }
1598
+ return best;
1599
+ }
1600
+ /**
1601
+ * @remarks
1602
+ * Errors thrown by the negotiated handler propagate UNMODIFIED — the
1603
+ * server boundary classifies them, never this negotiator.
1604
+ */
1605
+ async format(request, context, handlers) {
1606
+ const keys = Object.keys(handlers);
1607
+ const header = request.headers.get("accept");
1608
+ const type = header === null ? keys[0] : this.negotiate(header, keys);
1609
+ if (type === void 0) return new Response("Not Acceptable", { status: 406 });
1610
+ const handler = handlers[type];
1611
+ if (handler === void 0) return new Response("Not Acceptable", { status: 406 });
1612
+ return handler(request, context);
1613
+ }
1614
+ };
1615
+ //#endregion
1616
+ //#region src/core/factories.ts
1617
+ /**
1618
+ * Create a {@link NegotiatorInterface} — the reusable content-negotiation
1619
+ * machine over the weighted `Accept` family.
1620
+ *
1621
+ * @remarks
1622
+ * Prefer this over `new Negotiator()` at call sites that only need the
1623
+ * interface.
1624
+ *
1625
+ * @returns A {@link NegotiatorInterface}
1626
+ *
1627
+ * @example
1628
+ * ```ts
1629
+ * import { createNegotiator } from '@src/core'
1630
+ *
1631
+ * const negotiator = createNegotiator()
1632
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
1633
+ * // 'text/html'
1634
+ * ```
1635
+ */
1636
+ function createNegotiator() {
1637
+ return new Negotiator();
1638
+ }
1639
+ //#endregion
1640
+ exports.COMPRESSIBLE_TYPES = COMPRESSIBLE_TYPES;
1641
+ exports.ContentTooLargeError = ContentTooLargeError;
1642
+ exports.DEFAULT_BODY_LIMIT = DEFAULT_BODY_LIMIT;
1643
+ exports.DEFAULT_DECOMPRESSED_LIMIT = DEFAULT_DECOMPRESSED_LIMIT;
1644
+ exports.DEFAULT_DRAIN_MS = DEFAULT_DRAIN_MS;
1645
+ exports.DEFAULT_ENCODINGS = DEFAULT_ENCODINGS;
1646
+ exports.HTTPError = HTTPError;
1647
+ exports.HTTP_ERROR_BRAND = HTTP_ERROR_BRAND;
1648
+ exports.Negotiator = Negotiator;
1649
+ exports.REQUEST_ID_PATTERN = REQUEST_ID_PATTERN;
1650
+ exports.SSE_HEADERS = SSE_HEADERS;
1651
+ exports.appendCookie = appendCookie;
1652
+ exports.clearCookie = clearCookie;
1653
+ exports.clientRateKey = clientRateKey;
1654
+ exports.codingQuality = codingQuality;
1655
+ exports.collectRequestBody = collectRequestBody;
1656
+ exports.compose = compose;
1657
+ exports.computeBodyETag = computeBodyETag;
1658
+ exports.createNegotiator = createNegotiator;
1659
+ exports.decodeBase64Url = decodeBase64Url;
1660
+ exports.decodeCookieValue = decodeCookieValue;
1661
+ exports.decodeTokenPayload = decodeTokenPayload;
1662
+ exports.decompressRequestBody = decompressRequestBody;
1663
+ exports.encodeBase64Url = encodeBase64Url;
1664
+ exports.ipv6Network = ipv6Network;
1665
+ exports.isCompressibleType = isCompressibleType;
1666
+ exports.isCookieAttribute = isCookieAttribute;
1667
+ exports.isCookieName = isCookieName;
1668
+ exports.isDangerousKey = isDangerousKey;
1669
+ exports.isHTTPError = isHTTPError;
1670
+ exports.isValidRequestId = isValidRequestId;
1671
+ exports.languageQuality = languageQuality;
1672
+ exports.matchMediaType = matchMediaType;
1673
+ exports.matchesETag = matchesETag;
1674
+ exports.mergeVary = mergeVary;
1675
+ exports.negotiateEncoding = negotiateEncoding;
1676
+ exports.normalizeSecret = normalizeSecret;
1677
+ exports.openStream = openStream;
1678
+ exports.parseAcceptHeader = parseAcceptHeader;
1679
+ exports.parseCookies = parseCookies;
1680
+ exports.parseRange = parseRange;
1681
+ exports.readBody = readBody;
1682
+ exports.readSignedCookie = readSignedCookie;
1683
+ exports.requestEncoding = requestEncoding;
1684
+ exports.resolveOrigin = resolveOrigin;
1685
+ exports.resolveSecure = resolveSecure;
1686
+ exports.resolveSecurityHeader = resolveSecurityHeader;
1687
+ exports.scrubPrototype = scrubPrototype;
1688
+ exports.serializeCookie = serializeCookie;
1689
+ exports.serializeEvent = serializeEvent;
1690
+ exports.signToken = signToken;
1691
+ exports.unwrapETag = unwrapETag;
1692
+ exports.verifyToken = verifyToken;
1693
+ exports.writeSignedCookie = writeSignedCookie;
1694
+
1695
+ //# sourceMappingURL=index.cjs.map