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