@orkestrel/server 0.0.3 → 0.0.5

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