@orkestrel/server 0.0.17 → 0.0.19

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.
@@ -9,51 +9,59 @@ let _orkestrel_timeout = require("@orkestrel/timeout");
9
9
  let _orkestrel_router_server = require("@orkestrel/router/server");
10
10
  let _orkestrel_emitter = require("@orkestrel/emitter");
11
11
  //#region src/server/constants.ts
12
- /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
12
+ /**
13
+ * Names the default graceful-stop deadline `stop()` gives in-flight requests and
14
+ * claimed upgraded sockets, `10_000` ms.
15
+ */
13
16
  var DEFAULT_DRAIN_MS = 1e4;
14
17
  /**
15
- * The `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
16
- * an instance thrown by ANOTHER copy of this package (the dual-package
17
- * hazard — a version-skewed or workspace-linked duplicate install), where
18
- * `instanceof` alone fails because the two copies' `HTTPError` constructors
19
- * are distinct objects.
18
+ * Names the `Symbol.for`-interned brand `HTTPError` carries,
19
+ * `@orkestrel/server.HTTPError`, so `isHTTPError` recognizes an instance across
20
+ * package copies. A consumer never sets it by hand.
20
21
  *
21
22
  * @remarks
22
- * `Symbol.for` interns the symbol on the GLOBAL symbol registry, so every
23
- * copy of this package that evaluates this key resolves the SAME symbol
23
+ * The brand exists for the dual-package hazard — a version-skewed or
24
+ * workspace-linked duplicate install — where `instanceof` alone fails because
25
+ * each copy's `HTTPError` constructor is a distinct object.
26
+ * `Symbol.for` interns the symbol on the global symbol registry, so every
27
+ * copy of this package that evaluates this key resolves the same symbol
24
28
  * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,
25
29
  * unequal symbol per copy and defeat the whole point of a cross-copy brand.
26
30
  */
27
31
  var HTTP_ERROR_BRAND = Symbol.for("@orkestrel/server.HTTPError");
28
- /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
32
+ /**
33
+ * Names the default maximum request body size `readBody` accepts before a 413,
34
+ * `1_048_576` bytes.
35
+ */
29
36
  var DEFAULT_BODY_LIMIT = 1048576;
30
37
  /**
31
- * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
32
- * the body pipeline's byte-counting `TransformStream` enforces when
33
- * transparently decompressing a `Content-Encoding` request body.
38
+ * Names the default maximum decompressed request body size, `16_777_216` bytes — the
39
+ * zip-bomb cap the body pipeline's byte-counting `TransformStream` enforces when
40
+ * it transparently decompresses a `Content-Encoding` request body.
34
41
  *
35
42
  * @remarks
36
43
  * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
37
44
  * can inflate by many orders of magnitude — a classic decompression bomb.
38
- * Capping the decompressed byte count makes the pipe ABORT the moment the
39
- * output would exceed this, BEFORE the full bomb is materialized, so the
45
+ * Capping the decompressed byte count makes the pipe abort the moment the
46
+ * output would exceed this, before the full bomb is materialized, so the
40
47
  * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
41
48
  * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
42
- * consumer raises it via {@link import('./types.js').BodyOptions}
49
+ * consumer raises it through {@link import('./types.js').BodyOptions}
43
50
  * `decompression` for a workload that genuinely ships larger decompressed
44
51
  * bodies.
45
52
  */
46
53
  var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
47
54
  /**
48
- * The SSE response headers the `openStream` seam always sets.
55
+ * Holds the SSE response headers a `Stream` sets on its response, merged under any
56
+ * caller `headers` so a caller repeating one of these keys replaces its value.
49
57
  *
50
58
  * @remarks
51
59
  * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
52
60
  * keeps a proxy from caching the stream; `keep-alive` holds the connection
53
61
  * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
54
62
  * events flush promptly rather than batching. Frozen so a consumer can read
55
- * but never mutate the shared default; `openStream` merges any
56
- * {@link import('./types.js').StreamOptions.headers} UNDER these.
63
+ * but never mutate the shared default; the merged keys are
64
+ * {@link import('./types.js').StreamOptions.headers}.
57
65
  */
58
66
  var SSE_HEADERS = Object.freeze({
59
67
  "Content-Type": "text/event-stream; charset=utf-8",
@@ -62,27 +70,31 @@ var SSE_HEADERS = Object.freeze({
62
70
  "X-Accel-Buffering": "no"
63
71
  });
64
72
  /**
65
- * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
66
- * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
67
- * / control-char-bearing incoming id is REJECTED (a fresh id is minted
68
- * instead) rather than ever riding into a response header or `context.state`
69
- * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
70
- * shared default.
73
+ * Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
74
+ * to match, `^[A-Za-z0-9_-]{1,200}$`.
75
+ *
76
+ * @remarks
77
+ * An incoming id carrying CRLF, a log-injection payload, a control character,
78
+ * or more characters than the pattern admits fails the match and is rejected —
79
+ * a fresh id is minted instead — so it never rides into a response header or
80
+ * `context.state`. Frozen so a consumer can read but never mutate the shared
81
+ * default.
71
82
  */
72
83
  var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
73
84
  /**
74
- * The set of bare `Content-Type`s `isCompressibleType` treats as
75
- * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
76
- * `+xml`) rules that helper also applies.
85
+ * Holds the bare `Content-Type` values `isCompressibleType` treats as compressible,
86
+ * beyond the `text/*` prefix and structured-suffix (`+json`, `+xml`) rules that
87
+ * helper also applies.
77
88
  *
78
89
  * @remarks
79
90
  * The text-shaped application types worth compressing (JSON / JavaScript /
80
- * XML / SVG / WASM / a few document formats) — NOT already-compressed
91
+ * XML / SVG / WASM / a few document formats) — never already-compressed
81
92
  * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
82
- * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
83
- * but never mutates the shared default.
93
+ * `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
94
+ * withholds `add` / `delete` / `clear` from the shared default, so a consumer
95
+ * reads it without reaching a mutator.
84
96
  */
85
- var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
97
+ var COMPRESSIBLE_TYPES = Object.freeze(/* @__PURE__ */ new Set([
86
98
  "application/json",
87
99
  "application/javascript",
88
100
  "application/xml",
@@ -95,13 +107,13 @@ var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
95
107
  "application/wasm",
96
108
  "image/svg+xml",
97
109
  "application/pdf"
98
- ]);
110
+ ]));
99
111
  /**
100
- * The default {@link Encoding} content-codings the substrate offers, in
101
- * PREFERENCE order — `gzip` / `deflate`.
112
+ * Lists the default {@link Encoding} content-codings the substrate offers, in
113
+ * preference order — `gzip` then `deflate`.
102
114
  *
103
115
  * @remarks
104
- * `identity` (no compression) is always implicitly acceptable and is NOT
116
+ * `identity` (no compression) is always implicitly acceptable and is not
105
117
  * listed here — it is the fall-through when a client accepts none of these.
106
118
  * Brotli is omitted per the core's `CompressionStream`-only decision (see
107
119
  * {@link Encoding}). Frozen so a consumer can read but never mutate the
@@ -111,18 +123,19 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
111
123
  //#endregion
112
124
  //#region src/server/errors.ts
113
125
  /**
114
- * An error a handler (or middleware) throws to produce an HTTP response of a
126
+ * Represents an error a handler (or middleware) throws to produce an HTTP response of a
115
127
  * specific status.
116
128
  *
117
129
  * @remarks
118
130
  * Carries the HTTP `status` to send and an optional `context` record (the
119
131
  * offending field / value). The server's built-in error boundary catches it
120
132
  * and renders a response of `status` with the error's `message` as the body
121
- * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's
133
+ * — so an `HTTPError`'s message is always client-facing (it is the handler's
122
134
  * deliberate signal), unlike a generic throw whose message is hidden unless
123
135
  * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
124
136
  * specific statuses, or throw it directly. Narrow a caught value with
125
- * {@link isHTTPError}.
137
+ * {@link isHTTPError}. The machine-readable discriminator is `status`; there is
138
+ * no separate `code`.
126
139
  *
127
140
  * @example
128
141
  * ```ts
@@ -147,7 +160,7 @@ var HTTPError = class extends Error {
147
160
  }
148
161
  };
149
162
  /**
150
- * The {@link HTTPError} thrown when a request body exceeds the body
163
+ * Represents the {@link HTTPError} thrown when a request body exceeds the body
151
164
  * pipeline's size limit — a `413 Content Too Large`.
152
165
  *
153
166
  * @remarks
@@ -174,21 +187,22 @@ var ContentTooLargeError = class extends HTTPError {
174
187
  }
175
188
  };
176
189
  /**
177
- * Narrow an unknown caught value to an {@link HTTPError} (including its
178
- * subclasses, e.g. {@link ContentTooLargeError}).
190
+ * Narrows an unknown caught value to an {@link HTTPError}, including a subclass such
191
+ * as {@link ContentTooLargeError}, and recognizes an instance from another copy of
192
+ * this package through a structural brand fallback.
179
193
  *
180
194
  * @param value - The value to test (typically a `catch` binding)
181
- * @returns `true` when `value` is an {@link HTTPError}
195
+ * @returns True if `value` is an {@link HTTPError}; false otherwise
182
196
  *
183
197
  * @remarks
184
198
  * Tries `instanceof` first, then falls back to a total structural check for
185
- * an instance built by a DIFFERENT copy of this package (the dual-package
199
+ * an instance built by a different copy of this package (the dual-package
186
200
  * hazard — version skew, a linked workspace duplicate) whose `HTTPError`
187
201
  * constructor is a distinct object from this copy's: the value must carry
188
- * the cross-copy brand (interned via `Symbol.for`, so every copy resolves the
189
- * same key) AND expose the exact fields the server's error boundary reads off
202
+ * the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
203
+ * same key) and expose the exact fields the server's error boundary reads off
190
204
  * a recognized `HTTPError` — a numeric `status` and a string `message`. A
191
- * plain object that merely carries a `status` WITHOUT the brand is rejected.
205
+ * plain object that merely carries a `status` without the brand is rejected.
192
206
  *
193
207
  * @example
194
208
  * ```ts
@@ -208,21 +222,112 @@ function isHTTPError(value) {
208
222
  if (!("status" in value) || !("message" in value)) return false;
209
223
  return (0, _orkestrel_contract.isNumber)(value.status) && (0, _orkestrel_contract.isString)(value.message);
210
224
  }
225
+ /**
226
+ * Represents the error this package raises when a caller programmed a call the
227
+ * entity refuses, carrying `'STATUS'` or `'NEXT'` as its code.
228
+ *
229
+ * @remarks
230
+ * Carries a machine-readable {@link ServerErrorCode} and an optional `context`
231
+ * record naming the offending facts. This is a programmer error, so it carries
232
+ * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
233
+ * invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
234
+ * middleware into the request boundary, which reaches it as a generic 500 with
235
+ * the message hidden unless `expose` is set. Throw an {@link HTTPError} for a
236
+ * client-facing fault instead. Narrow a caught value with
237
+ * {@link isServerError}.
238
+ *
239
+ * @example
240
+ * ```ts
241
+ * import { ServerError } from '@src/server'
242
+ *
243
+ * const error = new ServerError('STATUS', "server cannot start from 'listening'", {
244
+ * status: 'listening',
245
+ * })
246
+ * error.code // 'STATUS'
247
+ * ```
248
+ */
249
+ var ServerError = class extends Error {
250
+ code;
251
+ context;
252
+ constructor(code, message, context) {
253
+ super(message);
254
+ this.name = "ServerError";
255
+ this.code = code;
256
+ if (context !== void 0) this.context = context;
257
+ }
258
+ };
259
+ /**
260
+ * Narrows an unknown caught value to a {@link ServerError} — the code-bearing refusal
261
+ * of a call the caller programmed.
262
+ *
263
+ * @param value - The value to test (typically a `catch` binding)
264
+ * @returns True if `value` is a {@link ServerError}; false otherwise
265
+ *
266
+ * @remarks
267
+ * Recognizes an instance built by this copy of the package. A `ServerError`
268
+ * is raised by a `Server` to the caller that invoked it directly, so both sides
269
+ * hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
270
+ * consumer here.
271
+ *
272
+ * @example
273
+ * ```ts
274
+ * import { createServer, isServerError } from '@src/server'
275
+ * import { createDispatcher } from '@orkestrel/router'
276
+ *
277
+ * const server = createServer({ dispatcher: createDispatcher(), state: () => ({}) })
278
+ * await server.start()
279
+ * try {
280
+ * await server.start()
281
+ * } catch (error) {
282
+ * if (isServerError(error)) console.log(error.code) // 'STATUS'
283
+ * }
284
+ * await server.stop()
285
+ * ```
286
+ */
287
+ function isServerError(value) {
288
+ return value instanceof ServerError;
289
+ }
290
+ //#endregion
291
+ //#region src/server/validators.ts
292
+ /**
293
+ * Checks whether a `node:net` `server.address()` return is the structured
294
+ * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
295
+ * or `null` — the total, never-throwing narrow `discoverPort`
296
+ * and the `Server`'s own port resolution read the bound port through.
297
+ *
298
+ * @remarks
299
+ * Checks the `address`, `family`, and `port` members `node:net` declares as
300
+ * `string`, `string`, and `number`.
301
+ *
302
+ * @param value - The `server.address()` return (`AddressInfo | string | null`)
303
+ * @returns True if `value` is an `AddressInfo`; false otherwise
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * import { isAddressInfo } from '@src/server'
308
+ *
309
+ * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
310
+ * isAddressInfo(null) // false
311
+ * ```
312
+ */
313
+ function isAddressInfo(value) {
314
+ return (0, _orkestrel_contract.isRecord)(value) && (0, _orkestrel_contract.isString)(value.address) && (0, _orkestrel_contract.isString)(value.family) && (0, _orkestrel_contract.isNumber)(value.port);
315
+ }
211
316
  //#endregion
212
317
  //#region src/server/helpers.ts
213
318
  /**
214
- * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
215
- * handler into one request handler — the frozen middleware seam (§5.1).
319
+ * Composes an ordered chain of {@link MiddlewareHandler} layers around a `terminal`
320
+ * handler into one request handler — the frozen middleware seam.
216
321
  *
217
322
  * @remarks
218
- * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
219
- * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
323
+ * `middleware[0]` runs outermost: it is invoked first, and its call to `next`
324
+ * runs `middleware[1]`, and so on until the last middleware's `next` invokes
220
325
  * `terminal`. Each middleware's `next` may be called with a substituted
221
326
  * `Request` (the downstream chain then sees that request instead of the
222
327
  * original), called with no argument (the original request continues
223
- * downstream), or NOT called at all (a short-circuit — the middleware's own
328
+ * downstream), or not called at all (a short-circuit — the middleware's own
224
329
  * returned `Response` is sent, and everything downstream never runs). A
225
- * SECOND call to the same `next` within one middleware invocation REJECTS —
330
+ * second call to the same `next` within one middleware invocation rejects —
226
331
  * each link runs the chain at most once, so a middleware cannot fork the
227
332
  * request into two divergent downstream runs.
228
333
  *
@@ -246,7 +351,8 @@ function compose(middleware, terminal) {
246
351
  return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
247
352
  }
248
353
  /**
249
- * Wrap one middleware layer around its downstream handler.
354
+ * Wraps one middleware layer around its downstream handler, enforcing the one-call
355
+ * `next` invariant.
250
356
  *
251
357
  * @remarks
252
358
  * The returned handler enforces the one-call `next` invariant while preserving
@@ -269,24 +375,24 @@ function wrapMiddleware(layer, next) {
269
375
  return async (request, context) => {
270
376
  let called = false;
271
377
  return Promise.resolve(layer(request, context, (nextRequest) => {
272
- if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
378
+ if (called) return Promise.reject(new ServerError("NEXT", "next() was already called by this middleware"));
273
379
  called = true;
274
380
  return next(nextRequest ?? request, context);
275
381
  }));
276
382
  };
277
383
  }
278
384
  /**
279
- * Parse a raw `Cookie:` request header into a `name → value` lookup.
385
+ * Parses a raw `Cookie:` request header into a `name → value` lookup.
280
386
  *
281
387
  * @remarks
282
- * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
388
+ * Splits on `;`; the first segment keeps any leading whitespace (a genuine
283
389
  * cookie-pair separator never precedes it), while every later segment has its
284
390
  * inter-pair separator (ASCII space/tab) stripped before parsing — so a
285
- * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
391
+ * whitespace-padded name (`' __Host-x=evil'`) is rejected by
286
392
  * {@link isCookieName} rather than silently reconciling into a
287
393
  * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
288
- * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
289
- * malformed header yields an empty record, never throws (AGENTS §14).
394
+ * name, is skipped; a later duplicate name wins. Total — an absent/empty/
395
+ * malformed header yields an empty record, never throws.
290
396
  *
291
397
  * @param header - The raw `Cookie` header value (possibly `undefined`)
292
398
  * @returns A record of every parsed cookie, `name → decoded value`
@@ -312,8 +418,8 @@ function parseCookies(header) {
312
418
  return out;
313
419
  }
314
420
  /**
315
- * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
316
- * cookie-token chars with NO surrounding (or interior) whitespace.
421
+ * Checks whether a string is a valid RFC 6265 cookie name — a non-empty run of
422
+ * cookie-token characters with no surrounding or interior whitespace.
317
423
  *
318
424
  * @remarks
319
425
  * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
@@ -322,7 +428,7 @@ function parseCookies(header) {
322
428
  * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
323
429
  *
324
430
  * @param value - The candidate cookie name
325
- * @returns `true` when `value` is a valid, whitespace-free cookie token
431
+ * @returns True if `value` is a valid, whitespace-free cookie token; false otherwise
326
432
  *
327
433
  * @example
328
434
  * ```ts
@@ -334,7 +440,7 @@ function isCookieName(value) {
334
440
  return /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(value);
335
441
  }
336
442
  /**
337
- * Decode a cookie value with `decodeURIComponent`, falling back to the raw
443
+ * Decodes a cookie value with `decodeURIComponent`, falling back to the raw
338
444
  * text when the value is not valid percent-encoding.
339
445
  *
340
446
  * @param raw - The raw (trimmed) cookie value
@@ -354,9 +460,9 @@ function decodeCookieValue(raw) {
354
460
  }
355
461
  }
356
462
  /**
357
- * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
358
- * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
359
- * attributes with before emitting them.
463
+ * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute value —
464
+ * the guard {@link serializeCookie} applies to a `Domain` and a `Path` before it
465
+ * emits them.
360
466
  *
361
467
  * @remarks
362
468
  * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
@@ -365,7 +471,7 @@ function decodeCookieValue(raw) {
365
471
  * directive. Total — never throws (a bad value returns `false`).
366
472
  *
367
473
  * @param value - The candidate attribute value (a `Domain` or `Path`)
368
- * @returns `true` when `value` carries no separator / whitespace / control char
474
+ * @returns True if `value` carries no separator / whitespace / control char; false otherwise
369
475
  *
370
476
  * @example
371
477
  * ```ts
@@ -382,18 +488,17 @@ function isCookieAttribute(value) {
382
488
  return true;
383
489
  }
384
490
  /**
385
- * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
491
+ * Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
386
492
  *
387
493
  * @remarks
388
494
  * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
389
495
  * appends the present {@link CookieOptions} attributes in canonical order:
390
496
  * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
391
- * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
392
- * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
393
- * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
394
- * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
497
+ * (default off), `SameSite` (default `Lax`). `Domain` / `Path` are validated
498
+ * with {@link isCookieAttribute} and throw an {@link HTTPError} on an
499
+ * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is always `Secure` regardless of
395
500
  * the `secure` option (the spec requires it); an un-resolved `undefined`
396
- * `secure` here falls to OFF — request-aware callers resolve it first via
501
+ * `secure` here falls to off — request-aware callers resolve it first through
397
502
  * {@link resolveSecure}.
398
503
  *
399
504
  * @param name - The cookie name
@@ -424,7 +529,7 @@ function serializeCookie(name, value, options) {
424
529
  return parts.join("; ");
425
530
  }
426
531
  /**
427
- * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
532
+ * Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}
428
533
  * `secure` setting and whether the request arrived over TLS.
429
534
  *
430
535
  * @remarks
@@ -434,7 +539,10 @@ function serializeCookie(name, value, options) {
434
539
  * gets `Secure` automatically while local-dev HTTP still works.
435
540
  *
436
541
  * @param secure - The {@link CookieOptions} `secure` setting
437
- * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
542
+ * @param encrypted - The connection's TLS flag
543
+ * ({@link import('./types.js').Connection.encrypted}). If `true`, an omitted
544
+ * `secure` resolves to `Secure`; if `false`, an omitted `secure` resolves to
545
+ * no `Secure` attribute.
438
546
  * @returns The concrete `Secure` flag to emit
439
547
  *
440
548
  * @example
@@ -449,39 +557,15 @@ function resolveSecure(secure, encrypted) {
449
557
  return encrypted;
450
558
  }
451
559
  /**
452
- * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
453
- * clobbering a prior one.
454
- *
455
- * @remarks
456
- * `Headers.append` already accumulates repeated headers (unlike node's
457
- * `setHeader`), so this is a thin, self-documenting wrapper naming the
458
- * cookie-append intent — the primitive {@link writeSignedCookie} /
459
- * {@link clearCookie} use.
460
- *
461
- * @param headers - The response `Headers` to write into
462
- * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
463
- *
464
- * @example
465
- * ```ts
466
- * const headers = new Headers()
467
- * appendCookie(headers, serializeCookie('a', '1'))
468
- * appendCookie(headers, serializeCookie('b', '2'))
469
- * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
470
- * ```
471
- */
472
- function appendCookie(headers, cookie) {
473
- headers.append("set-cookie", cookie);
474
- }
475
- /**
476
- * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
477
- * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
560
+ * Writes a signed cookie — HMAC-signs `value` with {@link signToken} and
561
+ * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
478
562
  *
479
563
  * @remarks
480
564
  * The cookie value is `await signToken(value, { secret })`
481
565
  * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
482
566
  * cookie — the same secret rotation and tamper rejection, no second HMAC
483
- * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
484
- * signing is asynchronous (§3 of the proposal).
567
+ * scheme. Appends (never clobbers) through `Headers.append`, which accumulates
568
+ * repeated headers. Async — WebCrypto signing is asynchronous.
485
569
  *
486
570
  * @param headers - The response `Headers` to write into
487
571
  * @param name - The cookie name
@@ -496,16 +580,16 @@ function appendCookie(headers, cookie) {
496
580
  * ```
497
581
  */
498
582
  async function writeSignedCookie(headers, name, value, secret, options) {
499
- appendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options));
583
+ headers.append("set-cookie", serializeCookie(name, await signToken(value, { secret }), options));
500
584
  }
501
585
  /**
502
- * Read + verify a SIGNED cookie off a request — TOTAL, returning the
586
+ * Reads and verifies a signed cookie off a request — total, returning the
503
587
  * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
504
588
  *
505
589
  * @remarks
506
590
  * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
507
591
  * and verifies it with {@link verifyToken} against `secret` (a rotation list
508
- * accepts a cookie signed by any of its secrets). ANY failure — an absent
592
+ * accepts a cookie signed by any of its secrets). Any failure — an absent
509
593
  * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
510
594
  *
511
595
  * @param request - The `Request` to read the `Cookie` header from
@@ -523,12 +607,12 @@ async function readSignedCookie(request, name, secret) {
523
607
  return cookie === void 0 ? void 0 : verifyToken(cookie, secret);
524
608
  }
525
609
  /**
526
- * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
610
+ * Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
527
611
  *
528
612
  * @remarks
529
613
  * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
530
614
  * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
531
- * a cookie when those MATCH the one it set).
615
+ * a cookie when those match the one it set).
532
616
  *
533
617
  * @param headers - The response `Headers` to write into
534
618
  * @param name - The cookie name to clear
@@ -541,23 +625,23 @@ async function readSignedCookie(request, name, secret) {
541
625
  * ```
542
626
  */
543
627
  function clearCookie(headers, name, options) {
544
- appendCookie(headers, serializeCookie(name, "", {
628
+ headers.append("set-cookie", serializeCookie(name, "", {
545
629
  ...options,
546
630
  maxAge: 0
547
631
  }));
548
632
  }
549
633
  /**
550
- * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
634
+ * Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
551
635
  *
552
636
  * @remarks
553
637
  * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
554
638
  * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
555
639
  * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
556
- * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
640
+ * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the first
557
641
  * {@link TokenSecret} (the current secret, or the head of a rotation list).
558
- * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
559
- * misconfigured secret with no usable entry THROWS an {@link HTTPError}
560
- * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
642
+ * Blank/whitespace-only secrets are ignored ({@link normalizeSecret}); a
643
+ * misconfigured secret with no usable entry throws an {@link HTTPError}
644
+ * (`500`) — fail-closed, a programmer error. Verify with
561
645
  * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
562
646
  *
563
647
  * @param value - The opaque value to embed (a session id, a deployment marker)
@@ -587,19 +671,19 @@ async function signToken(value, options) {
587
671
  return `${encoded}.${(0, _orkestrel_codec.encodeBase64URL)(new Uint8Array(signature))}`;
588
672
  }
589
673
  /**
590
- * Verify a stateless token and return its embedded value — TOTAL, never throws.
674
+ * Verifies a stateless token and returns its embedded value — total, never throws.
591
675
  *
592
676
  * @remarks
593
- * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
677
+ * The inverse of {@link signToken}: splits the token on its last `.` (so a
594
678
  * value containing dots survives), decodes the signature with
595
679
  * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
596
680
  * base64url is refused there, before any key import — and checks the payload's
597
- * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate via
681
+ * HMAC-SHA256 signature against each {@link TokenSecret} candidate through
598
682
  * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
599
- * retired, §3 of the proposal), accepting the token on the first match (the
683
+ * retired), accepting the token on the first match (the
600
684
  * rotation path). It then decodes + narrows the payload (`isRecord` +
601
- * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
602
- * rejects an expired token. ANY failure — a malformed token, a bad signature,
685
+ * `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
686
+ * token. Any failure — a malformed token, a bad signature,
603
687
  * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
604
688
  * yields `undefined` rather than throwing.
605
689
  *
@@ -635,15 +719,15 @@ async function verifyToken(token, secret) {
635
719
  }
636
720
  }
637
721
  /**
638
- * Decode + narrow a signed token's base64url JSON payload, honoring its
722
+ * Decodes and narrows a signed token's base64url JSON payload, honoring its
639
723
  * expiry — the shared decode step {@link verifyToken} applies after a
640
724
  * signature match.
641
725
  *
642
726
  * @remarks
643
727
  * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
644
728
  * non-canonical base64url segment answers `undefined` rather than throwing),
645
- * reads it as UTF-8 JSON, narrows it to a record with a string `value`
646
- * (AGENTS §14 — never `as`), and rejects an expired `exp`. TOTAL — any
729
+ * reads it as UTF-8 JSON, narrows it to a record with a string `value` without
730
+ * `as`, and rejects an expired `exp`. Total — any
647
731
  * decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
648
732
  * throws, and its `catch` answers `undefined` too.
649
733
  *
@@ -665,13 +749,13 @@ function decodeTokenPayload(encoded) {
665
749
  }
666
750
  }
667
751
  /**
668
- * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
669
- * backs both {@link signToken} and {@link verifyToken}.
752
+ * Normalizes a {@link TokenSecret} to a concrete list of usable secrets — the list
753
+ * behind both {@link signToken} and {@link verifyToken}.
670
754
  *
671
755
  * @remarks
672
756
  * A single string becomes a one-element list; a rotation list is copied. Any
673
- * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
674
- * emptiness test; each kept secret is stored VERBATIM). The first kept
757
+ * blank/whitespace-only entry is dropped (`.trim()` is used only for that
758
+ * emptiness test; each kept secret is stored verbatim). The first kept
675
759
  * element is the signing secret; all kept are accepted on verify.
676
760
  *
677
761
  * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
@@ -686,17 +770,17 @@ function normalizeSecret(secret) {
686
770
  return (typeof secret === "string" ? [secret] : [...secret]).filter((entry) => entry.trim().length > 0);
687
771
  }
688
772
  /**
689
- * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
773
+ * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
690
774
  * into its q-sorted entries.
691
775
  *
692
776
  * @remarks
693
777
  * Splits on `,`; for each part takes the token before the first `;`
694
778
  * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
695
779
  * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
696
- * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
697
- * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
780
+ * back to `1`). A `;q=0` entry is kept (an explicit rejection a caller must
781
+ * honor). The result is sorted by `q` descending, a stable sort preserving
698
782
  * the header's own order within a tie — a single pass with no backtracking,
699
- * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
783
+ * so parsing stays linear in the header length (ReDoS-safe). Total — an
700
784
  * empty/malformed header yields `[]`/best-effort entries, never throws.
701
785
  *
702
786
  * @param header - The raw weighted header value
@@ -735,12 +819,12 @@ function parseAcceptHeader(header) {
735
819
  })).sort((a, b) => b.entry.q - a.entry.q || a.index - b.index).map((ranked) => ranked.entry);
736
820
  }
737
821
  /**
738
- * The client's quality (q) for one content-coding from the parsed
739
- * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
740
- * server-preference selection.
822
+ * Computes the client's quality (q) for one content-coding from the parsed
823
+ * `Accept-Encoding` entries — the scoring leaf {@link resolveCoding} runs over
824
+ * each offered coding.
741
825
  *
742
826
  * @remarks
743
- * Prefers an EXACT named match (including an explicit `;q=0` rejection);
827
+ * Prefers an exact named match (including an explicit `;q=0` rejection);
744
828
  * failing that, a bare `*` wildcard's q applies. A coding that is neither
745
829
  * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
746
830
  * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
@@ -751,43 +835,46 @@ function parseAcceptHeader(header) {
751
835
  *
752
836
  * @example
753
837
  * ```ts
754
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
755
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
838
+ * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
839
+ * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
756
840
  * ```
757
841
  */
758
- function codingQuality(entries, coding) {
842
+ function computeCodingQuality(entries, coding) {
759
843
  const named = entries.find((entry) => entry.value === coding);
760
844
  if (named !== void 0) return named.q;
761
845
  return entries.find((entry) => entry.value === "*")?.q ?? 0;
762
846
  }
763
847
  /**
764
- * Select the best content-coding for an `Accept-Encoding` header from the
765
- * codings the server offers.
848
+ * Picks the highest-scoring content-coding the server offers against already
849
+ * parsed `Accept-Encoding` entries — the shared selection leaf behind
850
+ * {@link negotiateEncoding} and a `Negotiator`'s `encoding` axis.
766
851
  *
767
852
  * @remarks
768
- * Parses the header ({@link parseAcceptHeader}) and scores each `available`
769
- * coding in the SERVER's preference order ({@link codingQuality}), keeping
770
- * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
771
- * client-side tie). Returns `undefined` when the client accepts none of
772
- * `available` (identity — no compression). TOTAL on hostile input.
853
+ * The single selection leaf behind both doors onto this axis —
854
+ * {@link negotiateEncoding} for a raw header, and `Negotiator.encoding` for the
855
+ * entity — so the scoring loop has one implementation. Scores each `available`
856
+ * coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
857
+ * keeps the earlier-offered coding on a client-side tie, which is what makes
858
+ * `available` the server's preference order. An empty `available` list, and a
859
+ * list the client rejects outright, both yield `undefined` (identity — no
860
+ * compression). Total on hostile input.
773
861
  *
774
862
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
775
- * @param header - The raw `Accept-Encoding` header value
863
+ * @param entries - The parsed {@link AcceptEntry} list
776
864
  * @param available - The codings the server offers, in preference (tie-break) order
777
- * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
865
+ * @returns The winning coding, or `undefined` when none of `available` is acceptable
778
866
  *
779
867
  * @example
780
868
  * ```ts
781
- * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
869
+ * resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'
870
+ * resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined
782
871
  * ```
783
872
  */
784
- function negotiateEncoding(header, available) {
785
- if (available.length === 0) return void 0;
786
- const entries = parseAcceptHeader(header);
873
+ function resolveCoding(entries, available) {
787
874
  let best;
788
875
  let bestQuality = 0;
789
876
  for (const coding of available) {
790
- const quality = codingQuality(entries, coding);
877
+ const quality = computeCodingQuality(entries, coding);
791
878
  if (quality > bestQuality) {
792
879
  best = coding;
793
880
  bestQuality = quality;
@@ -796,7 +883,32 @@ function negotiateEncoding(header, available) {
796
883
  return best;
797
884
  }
798
885
  /**
799
- * Rank + quality of one `candidate` media type against the parsed `Accept`
886
+ * Selects the best content-coding for a raw `Accept-Encoding` header from the
887
+ * codings the server offers.
888
+ *
889
+ * @remarks
890
+ * Parses the header ({@link parseAcceptHeader}) and hands the entries to
891
+ * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
892
+ * the two doors onto this axis cannot drift. Returns `undefined` when the
893
+ * client accepts none of `available` (identity — no compression). Total on
894
+ * hostile input.
895
+ *
896
+ * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
897
+ * @param header - The raw `Accept-Encoding` header value
898
+ * @param available - The codings the server offers, in preference (tie-break) order
899
+ * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
900
+ *
901
+ * @example
902
+ * ```ts
903
+ * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
904
+ * ```
905
+ */
906
+ function negotiateEncoding(header, available) {
907
+ if (available.length === 0) return void 0;
908
+ return resolveCoding(parseAcceptHeader(header), available);
909
+ }
910
+ /**
911
+ * Reports the rank and quality of one `candidate` media type against the parsed `Accept`
800
912
  * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
801
913
  * uses to score each `available` candidate.
802
914
  *
@@ -810,8 +922,8 @@ function negotiateEncoding(header, available) {
810
922
  * rank tie the highest `q` wins.
811
923
  *
812
924
  * @param entries - The parsed {@link AcceptEntry} list
813
- * @param candidate - The candidate media type to score (e.g. `'text/html'`)
814
- * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
925
+ * @param candidate - The candidate media type to score (for example `'text/html'`)
926
+ * @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
815
927
  *
816
928
  * @example
817
929
  * ```ts
@@ -843,8 +955,9 @@ function matchMediaType(entries, candidate) {
843
955
  return best;
844
956
  }
845
957
  /**
846
- * The client's quality for one `candidate` language from the parsed
847
- * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
958
+ * Computes the client's quality for one `candidate` language from the parsed
959
+ * `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language`
960
+ * axis runs over each offered tag.
848
961
  *
849
962
  * @remarks
850
963
  * Prefers an exact match, then a primary-tag prefix match (`en` accepts
@@ -852,17 +965,17 @@ function matchMediaType(entries, candidate) {
852
965
  * is an explicit rejection).
853
966
  *
854
967
  * @param entries - The parsed {@link AcceptEntry} list
855
- * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
968
+ * @param candidate - The candidate language tag to score (for example `'en-US'`)
856
969
  * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
857
970
  *
858
971
  * @example
859
972
  * ```ts
860
- * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
861
- * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
862
- * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
973
+ * computeLanguageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
974
+ * computeLanguageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
975
+ * computeLanguageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
863
976
  * ```
864
977
  */
865
- function languageQuality(entries, candidate) {
978
+ function computeLanguageQuality(entries, candidate) {
866
979
  const lower = candidate.toLowerCase();
867
980
  const primary = lower.split("-")[0];
868
981
  let named;
@@ -880,17 +993,17 @@ function languageQuality(entries, candidate) {
880
993
  return wildcard ?? 0;
881
994
  }
882
995
  /**
883
- * Whether a `Content-Type` is worth compressing.
996
+ * Checks whether a `Content-Type` is worth compressing.
884
997
  *
885
998
  * @remarks
886
999
  * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
887
1000
  * type, a `+json`/`+xml` structured suffix, or one of the explicit
888
1001
  * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
889
- * binary (`image/png`, `application/zip`) is NOT compressible. An
890
- * absent/empty type is not compressible. TOTAL.
1002
+ * binary (`image/png`, `application/zip`) is not compressible. An
1003
+ * absent/empty type is not compressible. Total.
891
1004
  *
892
1005
  * @param type - The response `Content-Type` header value (with or without parameters)
893
- * @returns `true` when the type is text-shaped and worth compressing
1006
+ * @returns True if the type is text-shaped and worth compressing; false otherwise
894
1007
  *
895
1008
  * @example
896
1009
  * ```ts
@@ -907,17 +1020,18 @@ function isCompressibleType(type) {
907
1020
  return COMPRESSIBLE_TYPES.has(bare);
908
1021
  }
909
1022
  /**
910
- * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
1023
+ * Computes a content `ETag` over a fully-buffered response body by using WebCrypto.
911
1024
  *
912
1025
  * @remarks
913
1026
  * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
914
- * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
915
- * default, encoding-AGNOSTIC, so the tag survives a downstream content
916
- * re-encoding (gzip) and still matches on revalidation — or a STRONG one
1027
+ * digest as a weak validator (`W/"<hash>"`) when `weak` is `true` — the
1028
+ * default, encoding-agnostic, so the tag survives a downstream content
1029
+ * re-encoding (gzip) and still matches on revalidation — or a strong one
917
1030
  * (`"<hash>"`, byte-identity) when `weak` is `false`.
918
1031
  *
919
1032
  * @param body - The full (uncompressed) response body to hash
920
- * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
1033
+ * @param weak - If `true` (the default), returns a weak `W/"…"` validator; if
1034
+ * `false`, returns a strong `"…"` one.
921
1035
  * @returns The `ETag` header value
922
1036
  *
923
1037
  * @example
@@ -927,12 +1041,12 @@ function isCompressibleType(type) {
927
1041
  */
928
1042
  async function computeBodyETag(body, weak = true) {
929
1043
  const digest = await crypto.subtle.digest("SHA-256", body);
930
- const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
1044
+ const hex = (0, _orkestrel_codec.encodeHex)(new Uint8Array(digest));
931
1045
  return weak ? `W/"${hex}"` : `"${hex}"`;
932
1046
  }
933
1047
  /**
934
- * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
935
- * comparison body — the reduction {@link matchesETag} applies to both sides
1048
+ * Strips the weak indicator (`W/`) from an entity-tag, returning its opaque
1049
+ * comparison body — the reduction {@link matchesETag} applies to each side
936
1050
  * before the RFC 7232 §2.3.2 weak comparison.
937
1051
  *
938
1052
  * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
@@ -948,20 +1062,20 @@ function unwrapETag(tag) {
948
1062
  return trimmed.startsWith("W/") ? trimmed.slice(2) : trimmed;
949
1063
  }
950
1064
  /**
951
- * Whether a request's `If-None-Match` header matches a resource's current
952
- * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
1065
+ * Checks whether a request's `If-None-Match` header matches a resource's current
1066
+ * `ETag` — the RFC 7232 §2.3.2 weak comparison.
953
1067
  *
954
1068
  * @remarks
955
- * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
956
- * listed tag matches), or the `*` wildcard (matches ANY current
1069
+ * `If-None-Match` is a comma-separated list of entity-tags (matches if any
1070
+ * listed tag matches), or the `*` wildcard (matches any current
957
1071
  * representation — only a list of exactly `*` is the wildcard). Comparison is
958
- * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
959
- * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
1072
+ * weak: `W/"abc"` and `"abc"` are equal (each side's weak prefix is stripped
1073
+ * through {@link unwrapETag} before comparing the opaque body). Total — a
960
1074
  * malformed/empty header matches nothing, never throws.
961
1075
  *
962
1076
  * @param header - The raw `If-None-Match` header value
963
1077
  * @param etag - The resource's current `ETag`
964
- * @returns `true` when the conditional matches (the caller answers `304`)
1078
+ * @returns True if the conditional matches (the caller answers `304`); false otherwise
965
1079
  *
966
1080
  * @example
967
1081
  * ```ts
@@ -981,18 +1095,18 @@ function matchesETag(header, etag) {
981
1095
  return false;
982
1096
  }
983
1097
  /**
984
- * Parse an HTTP `Range` request header against a known resource `size` —
985
- * TOTAL, returning a {@link RangeSpec} or `undefined`.
1098
+ * Parses an HTTP `Range` request header against a known resource `size` —
1099
+ * total, returning a {@link RangeSpec} or `undefined`.
986
1100
  *
987
1101
  * @remarks
988
1102
  * Handles the three single-range `bytes=` forms — closed (`start-end`), open
989
1103
  * (`start-`), and suffix (`-suffixLength`) — clamping the window to
990
- * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
1104
+ * `[0, size - 1]` (the HTTP inclusive-end convention). Returns
991
1105
  * `{ satisfiable: true, start, end }` for an overlapping range,
992
1106
  * `{ satisfiable: false }` for a range wholly past the resource, and
993
- * `undefined` for the "serve the whole resource" case: an ABSENT header, a
994
- * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
995
- * supported), or any malformed/non-finite bound. NEVER throws on a hostile
1107
+ * `undefined` for the "serve the whole resource" case: an absent header, a
1108
+ * non-`bytes` unit, a multi-range header (`a-b, c-d` — refused outright, not
1109
+ * supported), or any malformed/non-finite bound. Never throws on a hostile
996
1110
  * header.
997
1111
  *
998
1112
  * @param header - The raw `Range` header value
@@ -1044,14 +1158,14 @@ function parseRange(header, size) {
1044
1158
  };
1045
1159
  }
1046
1160
  /**
1047
- * Resolve the `Access-Control-Allow-Origin` value for a request.
1161
+ * Resolves the `Access-Control-Allow-Origin` value for a request.
1048
1162
  *
1049
1163
  * @remarks
1050
1164
  * `'*'` and a single origin string pass straight through. An allow-list
1051
1165
  * echoes the request's `Origin` only when it is present in the list, else
1052
- * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
1166
+ * `undefined` (no header set). Security: the literal `'null'` origin — sent
1053
1167
  * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1054
- * NEVER reflected even if `'null'` were listed, closing the hostile-context
1168
+ * never reflected even if `'null'` were listed, closing the hostile-context
1055
1169
  * cross-origin-access hole.
1056
1170
  *
1057
1171
  * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
@@ -1071,7 +1185,7 @@ function resolveOrigin(origin, requestOrigin) {
1071
1185
  return origin.includes(requestOrigin) ? requestOrigin : void 0;
1072
1186
  }
1073
1187
  /**
1074
- * Merge a `Vary` value into an existing `Vary` header without duplication.
1188
+ * Merges a `Vary` value into an existing `Vary` header without duplication.
1075
1189
  *
1076
1190
  * @remarks
1077
1191
  * Splits `existing` on `,`, trims each member, and appends `value` only when
@@ -1095,11 +1209,11 @@ function mergeVary(existing, value) {
1095
1209
  return members.some((member) => member.toLowerCase() === value.toLowerCase()) ? members.join(", ") : [...members, value].join(", ");
1096
1210
  }
1097
1211
  /**
1098
- * Resolve one opt-out, value-bearing security header.
1212
+ * Resolves one opt-out, value-bearing security header.
1099
1213
  *
1100
1214
  * @remarks
1101
1215
  * The shared "a `string` value, or `false` to omit, or a default when unset"
1102
- * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
1216
+ * resolution (a value-or-off union, not a behavioral toggle):
1103
1217
  * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
1104
1218
  * override, `undefined` (unset) ⇒ `fallback` (the secure default).
1105
1219
  *
@@ -1119,18 +1233,18 @@ function resolveSecurityHeader(value, fallback) {
1119
1233
  return value ?? fallback;
1120
1234
  }
1121
1235
  /**
1122
- * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1123
- * header + `context.state`.
1236
+ * Checks whether a client-supplied `X-Request-ID` is safe to echo into a response
1237
+ * header and `context.state`.
1124
1238
  *
1125
1239
  * @remarks
1126
- * A request id is echoed RAW into a response header and log lines, so an
1240
+ * A request id is echoed raw into a response header and log lines, so an
1127
1241
  * untrusted one is a header-injection + log-injection + DoS vector. This
1128
1242
  * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
1129
1243
  * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
1130
- * TOTAL — never throws.
1244
+ * Total — never throws.
1131
1245
  *
1132
1246
  * @param value - The candidate incoming request id
1133
- * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
1247
+ * @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
1134
1248
  *
1135
1249
  * @example
1136
1250
  * ```ts
@@ -1142,14 +1256,14 @@ function isValidRequestId(value) {
1142
1256
  return REQUEST_ID_PATTERN.test(value);
1143
1257
  }
1144
1258
  /**
1145
- * Compute the `/64` network of a full IPv6 address, or `undefined` when the
1259
+ * Computes the `/64` network of a full IPv6 address, or `undefined` when the
1146
1260
  * input is not a plain IPv6 address to collapse.
1147
1261
  *
1148
1262
  * @remarks
1149
1263
  * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
1150
1264
  * is the identity) or any string that does not expand to exactly eight
1151
1265
  * hextets. Expands a single `::` into the missing zero hextets, takes the
1152
- * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
1266
+ * first four (the `/64` prefix), normalizes each (lower-case, no leading
1153
1267
  * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
1154
1268
  * first. Total — a malformed address returns `undefined`.
1155
1269
  *
@@ -1158,11 +1272,11 @@ function isValidRequestId(value) {
1158
1272
  *
1159
1273
  * @example
1160
1274
  * ```ts
1161
- * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1162
- * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1275
+ * computeIPv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1276
+ * computeIPv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1163
1277
  * ```
1164
1278
  */
1165
- function ipv6Network(address) {
1279
+ function computeIPv6Network(address) {
1166
1280
  if (/^::ffff:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i.test(address)) return void 0;
1167
1281
  const percent = address.indexOf("%");
1168
1282
  const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
@@ -1192,33 +1306,33 @@ function ipv6Network(address) {
1192
1306
  return `${prefix.join(":")}::/64`;
1193
1307
  }
1194
1308
  /**
1195
- * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
1309
+ * Collapses a client IP into its rate-limit bucket key — an IPv6 address to
1196
1310
  * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
1197
1311
  *
1198
1312
  * @remarks
1199
- * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
1313
+ * A residential/mobile IPv6 user is routinely handed a whole `/64`, so a
1200
1314
  * per-`/128` rate limit is trivially bypassed by rotating host bits — the
1201
1315
  * real identity is the `/64` network. Delegates the IPv6 collapse to
1202
- * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
1316
+ * {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
1203
1317
  * a malformed string) is kept unchanged.
1204
1318
  *
1205
- * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
1319
+ * @param address - The raw connection peer address ({@link import('./types.js').Connection.ip})
1206
1320
  * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
1207
1321
  *
1208
1322
  * @example
1209
1323
  * ```ts
1210
- * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1211
- * clientRateKey('192.0.2.1') // '192.0.2.1'
1324
+ * computeClientKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1325
+ * computeClientKey('192.0.2.1') // '192.0.2.1'
1212
1326
  * ```
1213
1327
  */
1214
- function clientRateKey(address) {
1215
- return ipv6Network(address) ?? address;
1328
+ function computeClientKey(address) {
1329
+ return computeIPv6Network(address) ?? address;
1216
1330
  }
1217
1331
  /**
1218
- * Serialize one {@link SSEMessage} to the SSE wire.
1332
+ * Serializes one {@link SSEMessage} to the SSE wire.
1219
1333
  *
1220
1334
  * @remarks
1221
- * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
1335
+ * Emits an `event:`/`id:`/`retry:` line for each present field, then one
1222
1336
  * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1223
1337
  * (so a consuming parser's multi-`data` concat reproduces the original
1224
1338
  * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
@@ -1242,129 +1356,12 @@ function serializeEvent(message) {
1242
1356
  return `${lines.join("\n")}\n\n`;
1243
1357
  }
1244
1358
  /**
1245
- * Enqueue encoded text into an open byte stream.
1246
- *
1247
- * @param controller - The stream controller, when the stream has started
1248
- * @param encoder - The encoder used for the stream's byte representation
1249
- * @param closed - Whether the stream has already ended or been cancelled
1250
- * @param text - The text to encode and enqueue
1251
- * @returns Nothing
1252
- *
1253
- * @example
1254
- * ```ts
1255
- * const body = new ReadableStream<Uint8Array>({
1256
- * start(controller) {
1257
- * enqueueStreamText(controller, new TextEncoder(), false, 'hello')
1258
- * },
1259
- * })
1260
- * ```
1261
- */
1262
- function enqueueStreamText(controller, encoder, closed, text) {
1263
- if (closed || controller === void 0) return;
1264
- controller.enqueue(encoder.encode(text));
1265
- }
1266
- /**
1267
- * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1268
- * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
1269
- *
1270
- * @remarks
1271
- * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
1272
- * merged under any `options.headers` (a seam-owned key is never overridden),
1273
- * at `options.status` (default `200`). The returned {@link StreamInterface}'s
1274
- * `write` serializes one message ({@link serializeEvent}), enqueues it, and
1275
- * returns whether the controller still has positive desired size. A producer
1276
- * receiving `false` can await `drain()`; its event-driven promise resolves on
1277
- * the next consumer pull that restores capacity, or on stream closure.
1278
- * `comment` writes a `: text` keep-alive line a conforming parser ignores;
1279
- * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
1280
- * by `end()`, or the consumer cancelled the stream), so a late write never
1281
- * throws.
1282
- *
1283
- * This readiness reflects only the process-local `ReadableStream` queue — it
1284
- * is not proof that a remote peer consumed bytes. When the response pump
1285
- * honors its socket sink's drain state, socket pressure stops body pulls and
1286
- * therefore keeps this queue full, allowing a cooperative producer to bound
1287
- * buffering. Ignoring the return value preserves the prior unconditional-
1288
- * enqueue behavior. The default stream strategy counts chunks rather than
1289
- * their byte length, so a byte-bounded producer must also cap each message.
1290
- * Return `response` before awaiting a `false` write, because the consumer
1291
- * cannot pull until it receives the response.
1292
- *
1293
- * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
1294
- * @returns The {@link StreamInterface} handle
1295
- *
1296
- * @example
1297
- * ```ts
1298
- * const stream = openStream()
1299
- * void Promise.resolve().then(async () => {
1300
- * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
1301
- * stream.end()
1302
- * })
1303
- * // return stream.response from the route handler
1304
- * ```
1305
- */
1306
- function openStream(options) {
1307
- const encoder = new TextEncoder();
1308
- let closed = false;
1309
- let controller;
1310
- let wakeup;
1311
- const body = new ReadableStream({
1312
- start(streamController) {
1313
- controller = streamController;
1314
- },
1315
- pull(streamController) {
1316
- if (streamController.desiredSize === null || streamController.desiredSize <= 0) return;
1317
- wakeup?.resolve();
1318
- wakeup = void 0;
1319
- },
1320
- cancel() {
1321
- closed = true;
1322
- wakeup?.resolve();
1323
- wakeup = void 0;
1324
- }
1325
- });
1326
- const headers = new Headers({
1327
- ...SSE_HEADERS,
1328
- ...options?.headers
1329
- });
1330
- return {
1331
- response: new Response(body, {
1332
- status: options?.status ?? 200,
1333
- headers
1334
- }),
1335
- get closed() {
1336
- return closed;
1337
- },
1338
- write(message) {
1339
- if (closed || controller === void 0) return false;
1340
- enqueueStreamText(controller, encoder, closed, serializeEvent(message));
1341
- return controller.desiredSize !== null && controller.desiredSize > 0;
1342
- },
1343
- comment(text) {
1344
- enqueueStreamText(controller, encoder, closed, `: ${text}\n\n`);
1345
- },
1346
- drain() {
1347
- const desired = controller?.desiredSize;
1348
- if (closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
1349
- wakeup ??= Promise.withResolvers();
1350
- return wakeup.promise;
1351
- },
1352
- end() {
1353
- if (closed) return;
1354
- closed = true;
1355
- controller?.close();
1356
- wakeup?.resolve();
1357
- wakeup = void 0;
1358
- }
1359
- };
1360
- }
1361
- /**
1362
- * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1363
- * or `prototype` — the three keys that, assigned onto a normal object, can
1364
- * reach and mutate `Object.prototype`.
1359
+ * Checks whether a key is a prototype-pollution vector — `__proto__`,
1360
+ * `constructor`, or `prototype`, each of which can reach and mutate
1361
+ * `Object.prototype` when it is assigned onto a normal object.
1365
1362
  *
1366
1363
  * @param key - The candidate object key
1367
- * @returns `true` when `key` is one of the three prototype-pollution keys
1364
+ * @returns True if `key` is one of the three prototype-pollution keys; false otherwise
1368
1365
  *
1369
1366
  * @example
1370
1367
  * ```ts
@@ -1376,12 +1373,11 @@ function isDangerousKey(key) {
1376
1373
  return key === "__proto__" || key === "constructor" || key === "prototype";
1377
1374
  }
1378
1375
  /**
1379
- * Recursively STRIP the prototype-pollution keys from a parsed value IN
1380
- * PLACE.
1376
+ * Strips the prototype-pollution keys from a parsed value in place, recursively.
1381
1377
  *
1382
1378
  * @remarks
1383
- * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
1384
- * enumerable `__proto__` DATA property — but that own key becomes a
1379
+ * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an own,
1380
+ * enumerable `__proto__` data property — but that own key becomes a
1385
1381
  * pollution gadget the moment a downstream deep-merge copies it onto a live
1386
1382
  * object. This walks the value and `delete`s any own {@link isDangerousKey}
1387
1383
  * key at every depth, recursing into nested objects + array elements.
@@ -1399,7 +1395,7 @@ function isDangerousKey(key) {
1399
1395
  */
1400
1396
  function scrubPrototype(value) {
1401
1397
  if (Array.isArray(value)) {
1402
- for (const item of value) scrubPrototype(item);
1398
+ for (const member of value) scrubPrototype(member);
1403
1399
  return value;
1404
1400
  }
1405
1401
  if ((0, _orkestrel_contract.isRecord)(value)) {
@@ -1415,12 +1411,12 @@ function scrubPrototype(value) {
1415
1411
  return value;
1416
1412
  }
1417
1413
  /**
1418
- * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
1414
+ * Collects a `Request` body into a single `Uint8Array`, enforcing a size limit.
1419
1415
  *
1420
1416
  * @remarks
1421
1417
  * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
1422
1418
  * throwing a {@link ContentTooLargeError} (413) the instant the running total
1423
- * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
1419
+ * exceeds `limit` — before the rest of the stream is buffered — rather than
1424
1420
  * collecting an unbounded body. A bodyless request (`request.body === null`)
1425
1421
  * resolves an empty array. A non-positive `limit` means unbounded.
1426
1422
  *
@@ -1458,41 +1454,41 @@ async function collectRequestBody(request, limit) {
1458
1454
  return merged;
1459
1455
  }
1460
1456
  /**
1461
- * Narrow a raw `Content-Encoding` header value to a decompressible
1462
- * {@link Encoding} — the boundary guard {@link readBody} uses to decide
1457
+ * Parses a raw `Content-Encoding` header value into a decompressible
1458
+ * {@link Encoding} — the boundary {@link readBody} coerces through to decide
1463
1459
  * whether a request body needs transparent decompression.
1464
1460
  *
1465
1461
  * @remarks
1466
- * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1467
- * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
1468
- * the proposal). An absent header, `identity`, an unknown value, or a
1462
+ * Lower-cases + trims and returns the matching {@link Encoding} only for
1463
+ * `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
1464
+ * absent header, `identity`, an unknown value, or a
1469
1465
  * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1470
- * TOTAL — never asserts the loose `string | null` header.
1466
+ * Total — never asserts the loose `string | null` header.
1471
1467
  *
1472
1468
  * @param header - The raw `Content-Encoding` header value
1473
1469
  * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
1474
1470
  *
1475
1471
  * @example
1476
1472
  * ```ts
1477
- * requestEncoding('gzip') // 'gzip'
1478
- * requestEncoding('br') // undefined — unsupported by DecompressionStream
1473
+ * parseEncoding('gzip') // 'gzip'
1474
+ * parseEncoding('br') // undefined — unsupported by DecompressionStream
1479
1475
  * ```
1480
1476
  */
1481
- function requestEncoding(header) {
1477
+ function parseEncoding(header) {
1482
1478
  if (!(0, _orkestrel_contract.isString)(header)) return void 0;
1483
1479
  const value = header.trim().toLowerCase();
1484
1480
  return value === "gzip" || value === "deflate" ? value : void 0;
1485
1481
  }
1486
1482
  /**
1487
- * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
1488
- * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
1483
+ * Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
1484
+ * transparently through `DecompressionStream`, capping the decompressed output —
1489
1485
  * the zip-bomb defense.
1490
1486
  *
1491
1487
  * @remarks
1492
1488
  * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
1493
- * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
1489
+ * `TransformStream` that aborts the pipe the instant the running decompressed
1494
1490
  * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
1495
- * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
1491
+ * has no `maxOutputLength` knob. A cap breach surfaces
1496
1492
  * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
1497
1493
  * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
1498
1494
  * (never conflated with the cap). A non-positive `cap` means uncapped.
@@ -1540,9 +1536,10 @@ async function decompressRequestBody(bytes, encoding, cap) {
1540
1536
  return merged;
1541
1537
  }
1542
1538
  /**
1543
- * Collect + decode a `Request` body — the shared body-collection pipeline
1539
+ * Collects and decodes a `Request` body — the shared body-collection pipeline
1544
1540
  * surfaced to middleware and handlers as the middleware context's cached
1545
- * `body()`.
1541
+ * `body()`. An empty body and a malformed `application/json` body each decode to
1542
+ * `undefined`.
1546
1543
  *
1547
1544
  * @remarks
1548
1545
  * Collects the wire body capped at `options.limit` bytes ({@link
@@ -1551,14 +1548,18 @@ async function decompressRequestBody(bytes, encoding, cap) {
1551
1548
  * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
1552
1549
  * `options.decompression`, default {@link
1553
1550
  * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1554
- * content type: `application/json` is parsed via `@orkestrel/contract`'s
1551
+ * content type: `application/json` is parsed by using `@orkestrel/contract`'s
1555
1552
  * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1556
- * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1557
- * decodes to `undefined`.
1553
+ * scrubPrototype}); any other type decodes as UTF-8 text.
1554
+ *
1555
+ * A malformed JSON body is total: it decodes rather than throwing, so a handler
1556
+ * that must reject one checks for `undefined` itself, and nothing in the returned
1557
+ * value tells an empty body from a malformed one.
1558
1558
  *
1559
1559
  * @param request - The `Request` to read the body from
1560
1560
  * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1561
- * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
1561
+ * @returns The parsed JSON value, the raw text, or `undefined` — for an empty
1562
+ * body, and for an `application/json` body whose text is not valid JSON
1562
1563
  * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1563
1564
  * @throws {HTTPError} When the compressed body is corrupt (400)
1564
1565
  *
@@ -1571,7 +1572,7 @@ async function readBody(request, options) {
1571
1572
  const limit = options?.limit ?? 1048576;
1572
1573
  const decompression = options?.decompression ?? 16777216;
1573
1574
  const wire = await collectRequestBody(request, limit);
1574
- const encoding = requestEncoding(request.headers.get("content-encoding"));
1575
+ const encoding = parseEncoding(request.headers.get("content-encoding"));
1575
1576
  const bytes = encoding === void 0 ? wire : await decompressRequestBody(wire, encoding, decompression);
1576
1577
  if (bytes.length === 0) return void 0;
1577
1578
  const contentType = request.headers.get("content-type");
@@ -1582,30 +1583,17 @@ async function readBody(request, options) {
1582
1583
  return text;
1583
1584
  }
1584
1585
  /**
1585
- * Whether a `node:net` `server.address()` return is the structured
1586
- * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
1587
- * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
1588
- * and the `Server`'s own port resolution read the bound port through.
1589
- *
1590
- * @param value - The `server.address()` return (`AddressInfo | string | null`)
1591
- * @returns `true` when `value` is an `AddressInfo` with a numeric `port`
1592
- *
1593
- * @example
1594
- * ```ts
1595
- * import { isAddressInfo } from '@src/server'
1586
+ * Binds and closes a throwaway TCP server to resolve one available port.
1596
1587
  *
1597
- * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
1598
- * isAddressInfo(null) // false
1599
- * ```
1600
- */
1601
- function isAddressInfo(value) {
1602
- return (0, _orkestrel_contract.isRecord)(value) && (0, _orkestrel_contract.isNumber)(value.port);
1603
- }
1604
- /**
1605
- * Bind and close a throwaway TCP server to resolve one available port.
1588
+ * @remarks
1589
+ * The probe always closes, including on the rejection path. A listener whose
1590
+ * address is not an {@link import('node:net').AddressInfo} — a pipe listener,
1591
+ * which a numeric `port` cannot request — has no port to report, so this
1592
+ * rejects rather than substituting a number.
1606
1593
  *
1607
1594
  * @param port - The requested port, with `0` selecting an ephemeral port
1608
1595
  * @returns The bound port after the probe server has closed
1596
+ * @throws {TypeError} When the bound listener's address carries no numeric port
1609
1597
  *
1610
1598
  * @example
1611
1599
  * ```ts
@@ -1618,29 +1606,35 @@ async function probePort(port) {
1618
1606
  probe.listen(port);
1619
1607
  await listening;
1620
1608
  const address = probe.address();
1621
- const resolved = isAddressInfo(address) ? address.port : 0;
1622
1609
  const closed = (0, node_events.once)(probe, "close");
1623
1610
  probe.close();
1624
1611
  await closed;
1625
- return resolved;
1612
+ if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
1613
+ return address.port;
1626
1614
  }
1627
1615
  /**
1628
- * Find a FREE TCP port — bind a throwaway `node:net` server, read the
1629
- * OS-assigned port, close it, and resolve that port.
1616
+ * Finds a free TCP port — binds a throwaway `node:net` server on a `preferred`
1617
+ * port where one is given and on an ephemeral port otherwise, reads the bound
1618
+ * port, closes the server, and resolves that port.
1630
1619
  *
1631
1620
  * @remarks
1632
1621
  * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
1633
- * and returns it. With a `preferred` port it tries THAT port first and
1634
- * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
1622
+ * and returns it. With a `preferred` port it tries that port first and
1623
+ * returns it when free; if already in use (`EADDRINUSE`) it falls back to an
1635
1624
  * ephemeral free port rather than rejecting — a caller always gets a usable
1636
1625
  * port. It binds then immediately closes a probe server, so the returned
1637
1626
  * port is free at the instant of the probe (an inherent TOCTOU race — bind it
1638
1627
  * promptly). Rejects only on an unexpected listen error other than a taken
1639
- * `preferred` port (e.g. a permission fault).
1628
+ * `preferred` port (for example, a permission fault). A listener whose address is not
1629
+ * an {@link import('node:net').AddressInfo} — a pipe listener, which this
1630
+ * package's options cannot request — rejects with a `TypeError` rather than
1631
+ * reporting `0`, because `0` is this package's own request for an ephemeral
1632
+ * port and never means an unknown one.
1640
1633
  *
1641
1634
  * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
1642
1635
  * fall back to an ephemeral port
1643
1636
  * @returns A free TCP port number
1637
+ * @throws {TypeError} When the bound listener's address carries no numeric port
1644
1638
  *
1645
1639
  * @example
1646
1640
  * ```ts
@@ -1661,14 +1655,14 @@ async function discoverPort(preferred) {
1661
1655
  //#endregion
1662
1656
  //#region src/server/Negotiator.ts
1663
1657
  /**
1664
- * The content-negotiation machine over the weighted `Accept` family — a
1665
- * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
1658
+ * Represents the content-negotiation machine over the weighted `Accept` family — a
1659
+ * reusable, cross-middleware entity rather than a middleware. Implements exactly
1666
1660
  * {@link NegotiatorInterface}.
1667
1661
  *
1668
1662
  * @remarks
1669
1663
  * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
1670
1664
  * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
1671
- * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
1665
+ * sibling axes and reuse the same {@link parseAcceptHeader} q-value parser the
1672
1666
  * rest of the substrate uses — one parser, never two. `format` reads the
1673
1667
  * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
1674
1668
  * the winner — or answers `406 Not Acceptable`.
@@ -1701,7 +1695,8 @@ var Negotiator = class {
1701
1695
  return best;
1702
1696
  }
1703
1697
  encoding(header, available) {
1704
- return negotiateEncoding(header, available);
1698
+ if (available.length === 0) return void 0;
1699
+ return resolveCoding(parseAcceptHeader(header), available);
1705
1700
  }
1706
1701
  language(header, available) {
1707
1702
  if (available.length === 0) return void 0;
@@ -1710,7 +1705,7 @@ var Negotiator = class {
1710
1705
  let best;
1711
1706
  let bestQuality = 0;
1712
1707
  for (const candidate of available) {
1713
- const quality = languageQuality(entries, candidate);
1708
+ const quality = computeLanguageQuality(entries, candidate);
1714
1709
  if (quality > bestQuality) {
1715
1710
  best = candidate;
1716
1711
  bestQuality = quality;
@@ -1719,8 +1714,11 @@ var Negotiator = class {
1719
1714
  return best;
1720
1715
  }
1721
1716
  /**
1717
+ * Dispatches the request to the handler its `Accept` header negotiates,
1718
+ * answering 406 when none matches.
1719
+ *
1722
1720
  * @remarks
1723
- * Errors thrown by the negotiated handler propagate UNMODIFIED — the
1721
+ * Errors thrown by the negotiated handler propagate unmodified — the
1724
1722
  * server boundary classifies them, never this negotiator.
1725
1723
  */
1726
1724
  async format(request, context, handlers) {
@@ -1736,39 +1734,39 @@ var Negotiator = class {
1736
1734
  //#endregion
1737
1735
  //#region src/server/Server.ts
1738
1736
  /**
1739
- * The HTTP server facade — an observable `node:http` lifecycle composing this
1737
+ * Represents the HTTP server facade — an observable `node:http` lifecycle composing this
1740
1738
  * module's own middleware onion around a consumed `@orkestrel/router`
1741
- * dispatcher.
1739
+ * dispatcher. Implements exactly {@link ServerInterface}.
1742
1740
  *
1743
1741
  * @typeParam TState - The consumer's opaque per-request state type
1744
1742
  *
1745
1743
  * @remarks
1746
- * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1744
+ * - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
1747
1745
  * server, binds the configured {@link ServerOptions.host} / {@link
1748
- * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1746
+ * ServerOptions.port} (omitted/`0` port ⇒ ephemeral, resolved from the
1749
1747
  * bound address), exposes that {@link AddressInfo} through `address`, observes
1750
1748
  * caller cancellation plus the configured `timeouts.start` deadline while the
1751
1749
  * bind is pending, and transitions `idle → starting → listening`. A
1752
1750
  * cancelled or expired bind closes its partial server and resets to `idle` for
1753
1751
  * another start. `stop()` transitions
1754
1752
  * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1755
- * so in-flight handlers observe cancellation, drains in-flight requests AND
1753
+ * so in-flight handlers observe cancellation, drains in-flight requests and
1756
1754
  * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1757
1755
  * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1758
1756
  * still open. `destroy()` is the idempotent final teardown.
1759
1757
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1760
- * `close`); a `Request` is built via the router's `buildRequest`, its
1761
- * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
1758
+ * `close`); a `Request` is built through the router's `buildRequest`, its
1759
+ * `signal` linked to this run's stop signal through `@orkestrel/abort`'s
1762
1760
  * `linkSignal` (a fresh `Request` is constructed with the linked signal —
1763
- * `buildRequest`'s own abort, armed by BOTH request-side and response-side
1764
- * teardown, composes with the server's stop signal via `AbortSignal.any`,
1765
- * so a handler awaiting `request.signal` observes BOTH); `context.state` is built via
1761
+ * `buildRequest`'s own abort, armed by request-side and response-side
1762
+ * teardown, composes with the server's stop signal through `AbortSignal.any`,
1763
+ * so a handler awaiting `request.signal` observes either); `context.state` is built through
1766
1764
  * {@link ServerOptions.state} from the connection facts; the composed
1767
1765
  * middleware onion runs, terminating in `dispatcher.handle`; the result is
1768
- * written back via `sendResponse`.
1769
- * - **The built-in boundary** wraps the WHOLE per-request chain, including
1766
+ * written back through `sendResponse`.
1767
+ * - **The built-in boundary** wraps the whole per-request chain, including
1770
1768
  * setup: `buildRequest` runs behind its own inner boundary that maps a
1771
- * throw (e.g. a malformed `Host` header) to a silent `400` with no
1769
+ * throw (for example, a malformed `Host` header) to a silent `400` with no
1772
1770
  * `error` emit; everything after (`Request` reconstruction, connection
1773
1771
  * facts, `state`, the composed onion, and `dispatcher.handle`) runs
1774
1772
  * behind the outer boundary — a thrown `HTTPError` renders as its status +
@@ -1780,15 +1778,15 @@ var Negotiator = class {
1780
1778
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1781
1779
  * throwing handler is treated as declined and surfaced on `error`, an
1782
1780
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1783
- * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1781
+ * A claimed socket joins `#upgraded` until it closes: the claimant still
1784
1782
  * owns it, and the tracking exists because node detaches an upgraded socket
1785
1783
  * from the set its own close calls walk, so nothing else can end it.
1786
- * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
1784
+ * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
1787
1785
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1788
- * routes it to the `error` OPTION (not the domain `error` event).
1786
+ * routes it to the `error` option rather than to the domain `error` event.
1789
1787
  */
1790
1788
  var Server = class {
1791
- id = crypto.randomUUID();
1789
+ #id;
1792
1790
  #dispatcher;
1793
1791
  #state;
1794
1792
  #middleware;
@@ -1821,6 +1819,7 @@ var Server = class {
1821
1819
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1822
1820
  const sockets = options.sockets ?? {};
1823
1821
  for (const [name, value] of Object.entries(sockets)) if (value !== void 0 && (!(0, _orkestrel_contract.isInteger)(value) || value < 0)) throw new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`);
1822
+ this.#id = crypto.randomUUID();
1824
1823
  this.#dispatcher = options.dispatcher;
1825
1824
  this.#state = options.state;
1826
1825
  this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
@@ -1837,8 +1836,8 @@ var Server = class {
1837
1836
  ...options.error === void 0 ? {} : { error: options.error }
1838
1837
  });
1839
1838
  }
1840
- get #inflight() {
1841
- return this.#pending + this.#upgraded.size;
1839
+ get id() {
1840
+ return this.#id;
1842
1841
  }
1843
1842
  get status() {
1844
1843
  return this.#status;
@@ -1864,7 +1863,7 @@ var Server = class {
1864
1863
  this.#upgradeHandlers.push(handler);
1865
1864
  }
1866
1865
  start(signal) {
1867
- if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
1866
+ if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(new ServerError("STATUS", `server cannot start from '${this.#status}'`, { status: this.#status }));
1868
1867
  this.#status = "starting";
1869
1868
  this.#abort = (0, _orkestrel_abort.createAbort)();
1870
1869
  const server = (0, node_http.createServer)((request, response) => this.#handle(request, response));
@@ -1998,17 +1997,13 @@ var Server = class {
1998
1997
  else socket.destroy();
1999
1998
  this.#emitter.emit("upgrade", request, handled);
2000
1999
  }
2001
- #resolvePort(server) {
2002
- const address = server.address();
2003
- if (isAddressInfo(address)) return address.port;
2004
- return 0;
2005
- }
2006
2000
  async #listen(server, signal) {
2007
2001
  const deadline = this.#timeouts.start === void 0 ? void 0 : (0, _orkestrel_timeout.createTimeout)({ ms: this.#timeouts.start });
2008
2002
  const startup = deadline === void 0 ? signal : (0, _orkestrel_abort.linkSignal)(deadline.signal, signal);
2009
2003
  const binding = (0, _orkestrel_abort.createAbort)();
2010
2004
  const relay = startup === void 0 ? void 0 : (0, node_events.addAbortListener)(startup, () => binding.abort(startup.reason));
2011
2005
  let listening;
2006
+ let port;
2012
2007
  try {
2013
2008
  signal?.throwIfAborted();
2014
2009
  deadline?.start();
@@ -2022,6 +2017,9 @@ var Server = class {
2022
2017
  signal: binding.signal
2023
2018
  });
2024
2019
  await listening;
2020
+ const address = server.address();
2021
+ if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
2022
+ port = address.port;
2025
2023
  } catch (error) {
2026
2024
  const expired = deadline?.expired === true;
2027
2025
  const cancelled = startup?.aborted === true;
@@ -2039,7 +2037,6 @@ var Server = class {
2039
2037
  relay?.[Symbol.dispose]();
2040
2038
  deadline?.clear();
2041
2039
  }
2042
- const port = this.#resolvePort(server);
2043
2040
  this.#port = port;
2044
2041
  this.#status = "listening";
2045
2042
  this.#emitter.emit("start", port);
@@ -2061,6 +2058,9 @@ var Server = class {
2061
2058
  } else server.closeIdleConnections();
2062
2059
  });
2063
2060
  }
2061
+ get #inflight() {
2062
+ return this.#pending + this.#upgraded.size;
2063
+ }
2064
2064
  #enter() {
2065
2065
  if (this.#inflight === 0) this.#wakeup = (0, _orkestrel_abort.createAbort)();
2066
2066
  }
@@ -2093,56 +2093,208 @@ var Server = class {
2093
2093
  }
2094
2094
  };
2095
2095
  //#endregion
2096
- //#region src/server/factories.ts
2096
+ //#region src/server/Stream.ts
2097
2097
  /**
2098
- * Create a {@link NegotiatorInterface} — the reusable content-negotiation
2099
- * machine over the weighted `Accept` family.
2098
+ * Represents the Server-Sent-Events handle over an open, fetch-standard streaming
2099
+ * `Response`. Implements exactly {@link StreamInterface}.
2100
2100
  *
2101
2101
  * @remarks
2102
- * Prefer this over `new Negotiator()` at call sites that only need the
2103
- * interface.
2102
+ * Builds the `Response` at construction from
2103
+ * {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
2104
+ * merged over them, at `options.status` (default `200`). A caller repeating one
2105
+ * of those keys therefore replaces the seam's value, in any casing. The
2106
+ * instance owns the stream's
2107
+ * controller, its text encoder, the closed flag, and the parked producer's
2108
+ * wakeup, so the whole handle is one entity rather than a closure over four
2109
+ * bindings.
2110
+ *
2111
+ * `write` serializes one message ({@link serializeEvent}), enqueues it, and
2112
+ * returns whether the controller still has positive desired size. A producer
2113
+ * receiving `false` awaits `drain()`; that promise resolves on the next
2114
+ * consumer pull restoring capacity, or on stream closure. `comment` writes a
2115
+ * `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
2116
+ * stream. Every method is a safe no-op once `closed` (ended by `end()`, or
2117
+ * the consumer cancelled the stream), so a late write never throws.
2118
+ *
2119
+ * The readiness signal reflects only the process-local `ReadableStream`
2120
+ * queue — it is not proof that a remote peer consumed bytes. When the response
2121
+ * pump honors its socket sink's drain state, socket pressure stops body pulls
2122
+ * and therefore keeps this queue full, letting a cooperative producer bound
2123
+ * its buffering. Ignoring the return value preserves an unconditional-enqueue
2124
+ * producer. The default stream strategy counts chunks rather than their byte
2125
+ * length, so a byte-bounded producer must also cap each message. Return
2126
+ * `response` before awaiting a `false` write, because the consumer cannot pull
2127
+ * until it receives the response.
2128
+ *
2129
+ * @example
2130
+ * ```ts
2131
+ * import { Stream } from '@src/server'
2132
+ *
2133
+ * const stream = new Stream()
2134
+ * void Promise.resolve().then(async () => {
2135
+ * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
2136
+ * stream.comment('keep-alive')
2137
+ * stream.end()
2138
+ * })
2139
+ * // return stream.response from the route handler
2140
+ * ```
2141
+ */
2142
+ var Stream = class {
2143
+ #encoder = new TextEncoder();
2144
+ #response;
2145
+ #controller;
2146
+ #closed = false;
2147
+ #wakeup;
2148
+ constructor(options) {
2149
+ const body = new ReadableStream({
2150
+ start: this.#attach.bind(this),
2151
+ pull: this.#pull.bind(this),
2152
+ cancel: this.#cancel.bind(this)
2153
+ });
2154
+ const headers = new Headers(SSE_HEADERS);
2155
+ for (const [name, value] of Object.entries(options?.headers ?? {})) headers.set(name, value);
2156
+ this.#response = new Response(body, {
2157
+ status: options?.status ?? 200,
2158
+ headers
2159
+ });
2160
+ }
2161
+ get response() {
2162
+ return this.#response;
2163
+ }
2164
+ get closed() {
2165
+ return this.#closed;
2166
+ }
2167
+ write(message) {
2168
+ if (this.#closed || this.#controller === void 0) return false;
2169
+ this.#enqueue(serializeEvent(message));
2170
+ return this.#controller.desiredSize !== null && this.#controller.desiredSize > 0;
2171
+ }
2172
+ comment(text) {
2173
+ this.#enqueue(`: ${text}\n\n`);
2174
+ }
2175
+ drain() {
2176
+ const desired = this.#controller?.desiredSize;
2177
+ if (this.#closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
2178
+ this.#wakeup ??= Promise.withResolvers();
2179
+ return this.#wakeup.promise;
2180
+ }
2181
+ end() {
2182
+ if (this.#closed) return;
2183
+ this.#closed = true;
2184
+ this.#controller?.close();
2185
+ this.#settle();
2186
+ }
2187
+ #attach(controller) {
2188
+ this.#controller = controller;
2189
+ }
2190
+ #pull(controller) {
2191
+ if (controller.desiredSize === null || controller.desiredSize <= 0) return;
2192
+ this.#settle();
2193
+ }
2194
+ #cancel() {
2195
+ this.#closed = true;
2196
+ this.#settle();
2197
+ }
2198
+ #enqueue(text) {
2199
+ if (this.#closed || this.#controller === void 0) return;
2200
+ this.#controller.enqueue(this.#encoder.encode(text));
2201
+ }
2202
+ #settle() {
2203
+ this.#wakeup?.resolve();
2204
+ this.#wakeup = void 0;
2205
+ }
2206
+ };
2207
+ //#endregion
2208
+ //#region src/server/factories.ts
2209
+ /**
2210
+ * Creates a {@link NegotiatorInterface} — the reusable content-negotiation
2211
+ * machine over the weighted `Accept` family.
2104
2212
  *
2105
2213
  * @returns A {@link NegotiatorInterface}
2106
2214
  *
2107
2215
  * @example
2108
2216
  * ```ts
2217
+ * import type { MiddlewareContext } from '@src/server'
2109
2218
  * import { createNegotiator } from '@src/server'
2110
2219
  *
2220
+ * declare const context: MiddlewareContext<Record<string, never>>
2221
+ *
2111
2222
  * const negotiator = createNegotiator()
2112
- * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
2113
- * // 'text/html'
2223
+ * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html']) // 'text/html'
2224
+ * negotiator.encoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
2225
+ * negotiator.language('en-US, en;q=0.8, fr;q=0.5', ['en', 'fr']) // 'en'
2226
+ * await negotiator.format(new Request('http://x'), context, {
2227
+ * 'application/json': (_request, _context) => Response.json({ ok: true }),
2228
+ * })
2114
2229
  * ```
2115
2230
  */
2116
2231
  function createNegotiator() {
2117
2232
  return new Negotiator();
2118
2233
  }
2119
2234
  /**
2120
- * Create a {@link ServerInterface} — the node face's HTTP server facade over
2235
+ * Creates a {@link ServerInterface} — the node face's HTTP server facade over
2121
2236
  * a consumed `@orkestrel/router` dispatcher.
2122
2237
  *
2123
2238
  * @typeParam TState - The consumer's opaque per-request state type
2124
2239
  * @param options - {@link ServerOptions}
2125
2240
  * @returns A {@link ServerInterface}, not yet started
2126
2241
  *
2127
- * @example
2242
+ * @example Quickstart: dispatcher, middleware, lifecycle
2128
2243
  * ```ts
2129
- * import { createServer } from '@src/server'
2244
+ * import type { MiddlewareHandler } from '@orkestrel/server'
2245
+ * import { createServer } from '@orkestrel/server'
2130
2246
  * import { createDispatcher } from '@orkestrel/router'
2131
2247
  *
2132
- * const dispatcher = createDispatcher<{ readonly ip?: string }>()
2248
+ * interface State {
2249
+ * readonly requestId: string
2250
+ * readonly ip: string | undefined
2251
+ * }
2252
+ *
2253
+ * const dispatcher = createDispatcher<State>()
2133
2254
  * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
2134
2255
  *
2135
- * const server = createServer({
2256
+ * const logRequestId: MiddlewareHandler<State> = async (_request, context, next) => {
2257
+ * const response = await next()
2258
+ * response.headers.set('X-Request-ID', context.state.requestId)
2259
+ * return response
2260
+ * }
2261
+ *
2262
+ * const server = createServer<State>({
2136
2263
  * dispatcher,
2137
- * state: (connection) => ({ ip: connection.ip }),
2264
+ * state: (connection) => ({ requestId: crypto.randomUUID(), ip: connection.ip }),
2138
2265
  * })
2266
+ * server.use(logRequestId)
2139
2267
  * const port = await server.start()
2140
2268
  * await server.stop()
2269
+ * await server.destroy()
2141
2270
  * ```
2142
2271
  */
2143
2272
  function createServer(options) {
2144
2273
  return new Server(options);
2145
2274
  }
2275
+ /**
2276
+ * Creates a {@link StreamInterface} — a generic Server-Sent-Events stream whose
2277
+ * `response` is a fetch-standard streaming `Response` a route returns.
2278
+ *
2279
+ * @param options - {@link StreamOptions}
2280
+ * @returns A {@link StreamInterface} whose stream is open
2281
+ *
2282
+ * @example
2283
+ * ```ts
2284
+ * import { createStream } from '@src/server'
2285
+ *
2286
+ * const stream = createStream()
2287
+ * void Promise.resolve().then(async () => {
2288
+ * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
2289
+ * stream.comment('keep-alive')
2290
+ * stream.end()
2291
+ * })
2292
+ * // return stream.response from the route handler
2293
+ * ```
2294
+ */
2295
+ function createStream(options) {
2296
+ return new Stream(options);
2297
+ }
2146
2298
  //#endregion
2147
2299
  exports.COMPRESSIBLE_TYPES = COMPRESSIBLE_TYPES;
2148
2300
  exports.ContentTooLargeError = ContentTooLargeError;
@@ -2156,42 +2308,44 @@ exports.Negotiator = Negotiator;
2156
2308
  exports.REQUEST_ID_PATTERN = REQUEST_ID_PATTERN;
2157
2309
  exports.SSE_HEADERS = SSE_HEADERS;
2158
2310
  exports.Server = Server;
2159
- exports.appendCookie = appendCookie;
2311
+ exports.ServerError = ServerError;
2312
+ exports.Stream = Stream;
2160
2313
  exports.clearCookie = clearCookie;
2161
- exports.clientRateKey = clientRateKey;
2162
- exports.codingQuality = codingQuality;
2163
2314
  exports.collectRequestBody = collectRequestBody;
2164
2315
  exports.compose = compose;
2165
2316
  exports.computeBodyETag = computeBodyETag;
2317
+ exports.computeClientKey = computeClientKey;
2318
+ exports.computeCodingQuality = computeCodingQuality;
2319
+ exports.computeIPv6Network = computeIPv6Network;
2320
+ exports.computeLanguageQuality = computeLanguageQuality;
2166
2321
  exports.createNegotiator = createNegotiator;
2167
2322
  exports.createServer = createServer;
2323
+ exports.createStream = createStream;
2168
2324
  exports.decodeCookieValue = decodeCookieValue;
2169
2325
  exports.decodeTokenPayload = decodeTokenPayload;
2170
2326
  exports.decompressRequestBody = decompressRequestBody;
2171
2327
  exports.discoverPort = discoverPort;
2172
- exports.enqueueStreamText = enqueueStreamText;
2173
- exports.ipv6Network = ipv6Network;
2174
2328
  exports.isAddressInfo = isAddressInfo;
2175
2329
  exports.isCompressibleType = isCompressibleType;
2176
2330
  exports.isCookieAttribute = isCookieAttribute;
2177
2331
  exports.isCookieName = isCookieName;
2178
2332
  exports.isDangerousKey = isDangerousKey;
2179
2333
  exports.isHTTPError = isHTTPError;
2334
+ exports.isServerError = isServerError;
2180
2335
  exports.isValidRequestId = isValidRequestId;
2181
- exports.languageQuality = languageQuality;
2182
2336
  exports.matchMediaType = matchMediaType;
2183
2337
  exports.matchesETag = matchesETag;
2184
2338
  exports.mergeVary = mergeVary;
2185
2339
  exports.negotiateEncoding = negotiateEncoding;
2186
2340
  exports.normalizeSecret = normalizeSecret;
2187
- exports.openStream = openStream;
2188
2341
  exports.parseAcceptHeader = parseAcceptHeader;
2189
2342
  exports.parseCookies = parseCookies;
2343
+ exports.parseEncoding = parseEncoding;
2190
2344
  exports.parseRange = parseRange;
2191
2345
  exports.probePort = probePort;
2192
2346
  exports.readBody = readBody;
2193
2347
  exports.readSignedCookie = readSignedCookie;
2194
- exports.requestEncoding = requestEncoding;
2348
+ exports.resolveCoding = resolveCoding;
2195
2349
  exports.resolveOrigin = resolveOrigin;
2196
2350
  exports.resolveSecure = resolveSecure;
2197
2351
  exports.resolveSecurityHeader = resolveSecurityHeader;