@orkestrel/server 0.0.17 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,20 @@
1
1
  import { isFiniteNumber, isFunction, isInteger, isNumber, isRecord, isString, parseJSON } from "@orkestrel/contract";
2
2
  import { addAbortListener, once } from "node:events";
3
3
  import { createServer as createServer$1 } from "node:net";
4
- import { decodeBase64URL, encodeBase64URL } from "@orkestrel/codec";
4
+ import { decodeBase64URL, encodeBase64URL, encodeHex } from "@orkestrel/codec";
5
5
  import { createServer as createServer$2 } from "node:http";
6
6
  import { createAbort, linkSignal } from "@orkestrel/abort";
7
7
  import { createTimeout } from "@orkestrel/timeout";
8
8
  import { buildRequest, isEncryptedSocket, sendResponse } from "@orkestrel/router/server";
9
9
  import { Emitter } from "@orkestrel/emitter";
10
10
  //#region src/server/constants.ts
11
- /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
11
+ /**
12
+ * Names the default graceful-stop deadline (ms) the server gives in-flight
13
+ * requests on `stop()`.
14
+ */
12
15
  var DEFAULT_DRAIN_MS = 1e4;
13
16
  /**
14
- * The `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
17
+ * Names the `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes
15
18
  * an instance thrown by ANOTHER copy of this package (the dual-package
16
19
  * hazard — a version-skewed or workspace-linked duplicate install), where
17
20
  * `instanceof` alone fails because the two copies' `HTTPError` constructors
@@ -24,10 +27,10 @@ var DEFAULT_DRAIN_MS = 1e4;
24
27
  * unequal symbol per copy and defeat the whole point of a cross-copy brand.
25
28
  */
26
29
  var HTTP_ERROR_BRAND = Symbol.for("@orkestrel/server.HTTPError");
27
- /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
30
+ /** Names the default maximum request body size (bytes) `readBody` accepts before a 413. */
28
31
  var DEFAULT_BODY_LIMIT = 1048576;
29
32
  /**
30
- * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
33
+ * Names the default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
31
34
  * the body pipeline's byte-counting `TransformStream` enforces when
32
35
  * transparently decompressing a `Content-Encoding` request body.
33
36
  *
@@ -38,21 +41,22 @@ var DEFAULT_BODY_LIMIT = 1048576;
38
41
  * output would exceed this, BEFORE the full bomb is materialized, so the
39
42
  * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
40
43
  * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
41
- * consumer raises it via {@link import('./types.js').BodyOptions}
44
+ * consumer raises it through {@link import('./types.js').BodyOptions}
42
45
  * `decompression` for a workload that genuinely ships larger decompressed
43
46
  * bodies.
44
47
  */
45
48
  var DEFAULT_DECOMPRESSED_LIMIT = 16777216;
46
49
  /**
47
- * The SSE response headers the `openStream` seam always sets.
50
+ * Holds the SSE response headers a `Stream` always sets on its response.
48
51
  *
49
52
  * @remarks
50
53
  * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
51
54
  * keeps a proxy from caching the stream; `keep-alive` holds the connection
52
55
  * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
53
56
  * events flush promptly rather than batching. Frozen so a consumer can read
54
- * but never mutate the shared default; `openStream` merges any
55
- * {@link import('./types.js').StreamOptions.headers} UNDER these.
57
+ * but never mutate the shared default; a `Stream` merges any
58
+ * {@link import('./types.js').StreamOptions.headers} OVER these, so a caller
59
+ * repeating one of these keys replaces its value.
56
60
  */
57
61
  var SSE_HEADERS = Object.freeze({
58
62
  "Content-Type": "text/event-stream; charset=utf-8",
@@ -61,16 +65,15 @@ var SSE_HEADERS = Object.freeze({
61
65
  "X-Accel-Buffering": "no"
62
66
  });
63
67
  /**
64
- * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
68
+ * Defines the strict charset `isValidRequestId` requires an incoming `X-Request-ID`
65
69
  * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
66
70
  * / control-char-bearing incoming id is REJECTED (a fresh id is minted
67
- * instead) rather than ever riding into a response header or `context.state`
68
- * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
69
- * shared default.
71
+ * instead) rather than ever riding into a response header or `context.state`.
72
+ * Frozen so a consumer can read but never mutate the shared default.
70
73
  */
71
74
  var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
72
75
  /**
73
- * The set of bare `Content-Type`s `isCompressibleType` treats as
76
+ * Holds the set of bare `Content-Type`s `isCompressibleType` treats as
74
77
  * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
75
78
  * `+xml`) rules that helper also applies.
76
79
  *
@@ -78,10 +81,11 @@ var REQUEST_ID_PATTERN = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/);
78
81
  * The text-shaped application types worth compressing (JSON / JavaScript /
79
82
  * XML / SVG / WASM / a few document formats) — NOT already-compressed
80
83
  * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
81
- * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
82
- * but never mutates the shared default.
84
+ * `woff2`), which gzip/deflate would only bloat. The declared `ReadonlySet`
85
+ * withholds `add` / `delete` / `clear` from the shared default, so a consumer
86
+ * reads it without reaching a mutator.
83
87
  */
84
- var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
88
+ var COMPRESSIBLE_TYPES = Object.freeze(/* @__PURE__ */ new Set([
85
89
  "application/json",
86
90
  "application/javascript",
87
91
  "application/xml",
@@ -94,9 +98,9 @@ var COMPRESSIBLE_TYPES = /* @__PURE__ */ new Set([
94
98
  "application/wasm",
95
99
  "image/svg+xml",
96
100
  "application/pdf"
97
- ]);
101
+ ]));
98
102
  /**
99
- * The default {@link Encoding} content-codings the substrate offers, in
103
+ * Lists the default {@link Encoding} content-codings the substrate offers, in
100
104
  * PREFERENCE order — `gzip` / `deflate`.
101
105
  *
102
106
  * @remarks
@@ -110,7 +114,7 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
110
114
  //#endregion
111
115
  //#region src/server/errors.ts
112
116
  /**
113
- * An error a handler (or middleware) throws to produce an HTTP response of a
117
+ * Represents an error a handler (or middleware) throws to produce an HTTP response of a
114
118
  * specific status.
115
119
  *
116
120
  * @remarks
@@ -121,7 +125,8 @@ var DEFAULT_ENCODINGS = Object.freeze(["gzip", "deflate"]);
121
125
  * deliberate signal), unlike a generic throw whose message is hidden unless
122
126
  * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
123
127
  * specific statuses, or throw it directly. Narrow a caught value with
124
- * {@link isHTTPError}.
128
+ * {@link isHTTPError}. The machine-readable discriminator is `status`; there is
129
+ * no separate `code`.
125
130
  *
126
131
  * @example
127
132
  * ```ts
@@ -146,7 +151,7 @@ var HTTPError = class extends Error {
146
151
  }
147
152
  };
148
153
  /**
149
- * The {@link HTTPError} thrown when a request body exceeds the body
154
+ * Represents the {@link HTTPError} thrown when a request body exceeds the body
150
155
  * pipeline's size limit — a `413 Content Too Large`.
151
156
  *
152
157
  * @remarks
@@ -173,18 +178,18 @@ var ContentTooLargeError = class extends HTTPError {
173
178
  }
174
179
  };
175
180
  /**
176
- * Narrow an unknown caught value to an {@link HTTPError} (including its
181
+ * Narrows an unknown caught value to an {@link HTTPError} (including its
177
182
  * subclasses, e.g. {@link ContentTooLargeError}).
178
183
  *
179
184
  * @param value - The value to test (typically a `catch` binding)
180
- * @returns `true` when `value` is an {@link HTTPError}
185
+ * @returns True if `value` is an {@link HTTPError}; false otherwise
181
186
  *
182
187
  * @remarks
183
188
  * Tries `instanceof` first, then falls back to a total structural check for
184
189
  * an instance built by a DIFFERENT copy of this package (the dual-package
185
190
  * hazard — version skew, a linked workspace duplicate) whose `HTTPError`
186
191
  * constructor is a distinct object from this copy's: the value must carry
187
- * the cross-copy brand (interned via `Symbol.for`, so every copy resolves the
192
+ * the cross-copy brand (interned by using `Symbol.for`, so every copy resolves the
188
193
  * same key) AND expose the exact fields the server's error boundary reads off
189
194
  * a recognized `HTTPError` — a numeric `status` and a string `message`. A
190
195
  * plain object that merely carries a `status` WITHOUT the brand is rejected.
@@ -207,11 +212,101 @@ function isHTTPError(value) {
207
212
  if (!("status" in value) || !("message" in value)) return false;
208
213
  return isNumber(value.status) && isString(value.message);
209
214
  }
215
+ /**
216
+ * Represents the error this package raises when a caller programmed a call the
217
+ * entity refuses.
218
+ *
219
+ * @remarks
220
+ * Carries a machine-readable {@link ServerErrorCode} and an optional `context`
221
+ * record naming the offending facts. This is a PROGRAMMER error, so it carries
222
+ * no HTTP `status`: a `'STATUS'` lifecycle refusal is raised to the caller that
223
+ * invoked the lifecycle method, and a `'NEXT'` double-`next` refusal escapes its
224
+ * middleware into the request boundary, which reaches it as a generic 500 with
225
+ * the message hidden unless `expose` is set. Throw an {@link HTTPError} for a
226
+ * client-facing fault instead. Narrow a caught value with
227
+ * {@link isServerError}.
228
+ *
229
+ * @example
230
+ * ```ts
231
+ * import { ServerError } from '@src/server'
232
+ *
233
+ * const error = new ServerError('STATUS', "server cannot start from 'listening'", {
234
+ * status: 'listening',
235
+ * })
236
+ * error.code // 'STATUS'
237
+ * ```
238
+ */
239
+ var ServerError = class extends Error {
240
+ code;
241
+ context;
242
+ constructor(code, message, context) {
243
+ super(message);
244
+ this.name = "ServerError";
245
+ this.code = code;
246
+ if (context !== void 0) this.context = context;
247
+ }
248
+ };
249
+ /**
250
+ * Narrows an unknown caught value to a {@link ServerError}.
251
+ *
252
+ * @param value - The value to test (typically a `catch` binding)
253
+ * @returns True if `value` is a {@link ServerError}; false otherwise
254
+ *
255
+ * @remarks
256
+ * Recognizes an instance built by THIS copy of the package. A `ServerError`
257
+ * is raised by a `Server` to the caller that just invoked it, so both sides
258
+ * hold the same copy and the cross-copy brand {@link isHTTPError} needs has no
259
+ * consumer here.
260
+ *
261
+ * @example
262
+ * ```ts
263
+ * import { createServer, isServerError } from '@src/server'
264
+ * import { createDispatcher } from '@orkestrel/router'
265
+ *
266
+ * const server = createServer({ dispatcher: createDispatcher(), state: () => ({}) })
267
+ * await server.start()
268
+ * try {
269
+ * await server.start()
270
+ * } catch (error) {
271
+ * if (isServerError(error)) console.log(error.code) // 'STATUS'
272
+ * }
273
+ * await server.stop()
274
+ * ```
275
+ */
276
+ function isServerError(value) {
277
+ return value instanceof ServerError;
278
+ }
279
+ //#endregion
280
+ //#region src/server/validators.ts
281
+ /**
282
+ * Checks whether a `node:net` `server.address()` return is the structured
283
+ * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
284
+ * or `null` — the total, never-throwing narrow `discoverPort`
285
+ * and the `Server`'s own port resolution read the bound port through.
286
+ *
287
+ * @remarks
288
+ * Checks the `address`, `family`, and `port` members `node:net` declares as
289
+ * `string`, `string`, and `number`.
290
+ *
291
+ * @param value - The `server.address()` return (`AddressInfo | string | null`)
292
+ * @returns True if `value` is an `AddressInfo`; false otherwise
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * import { isAddressInfo } from '@src/server'
297
+ *
298
+ * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
299
+ * isAddressInfo(null) // false
300
+ * ```
301
+ */
302
+ function isAddressInfo(value) {
303
+ return isRecord(value) && isString(value.address) && isString(value.family) && isNumber(value.port);
304
+ }
210
305
  //#endregion
211
306
  //#region src/server/helpers.ts
212
307
  /**
213
- * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
214
- * handler into one request handler — the frozen middleware seam (§5.1).
308
+ * Composes an ordered chain of {@link MiddlewareHandler}s around a `terminal`
309
+ * handler into one request handler — the frozen middleware seam.
215
310
  *
216
311
  * @remarks
217
312
  * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
@@ -245,7 +340,7 @@ function compose(middleware, terminal) {
245
340
  return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
246
341
  }
247
342
  /**
248
- * Wrap one middleware layer around its downstream handler.
343
+ * Wraps one middleware layer around its downstream handler.
249
344
  *
250
345
  * @remarks
251
346
  * The returned handler enforces the one-call `next` invariant while preserving
@@ -268,14 +363,14 @@ function wrapMiddleware(layer, next) {
268
363
  return async (request, context) => {
269
364
  let called = false;
270
365
  return Promise.resolve(layer(request, context, (nextRequest) => {
271
- if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
366
+ if (called) return Promise.reject(new ServerError("NEXT", "next() was already called by this middleware"));
272
367
  called = true;
273
368
  return next(nextRequest ?? request, context);
274
369
  }));
275
370
  };
276
371
  }
277
372
  /**
278
- * Parse a raw `Cookie:` request header into a `name → value` lookup.
373
+ * Parses a raw `Cookie:` request header into a `name → value` lookup.
279
374
  *
280
375
  * @remarks
281
376
  * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
@@ -285,7 +380,7 @@ function wrapMiddleware(layer, next) {
285
380
  * {@link isCookieName} rather than silently reconciling into a
286
381
  * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
287
382
  * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
288
- * malformed header yields an empty record, never throws (AGENTS §14).
383
+ * malformed header yields an empty record, never throws.
289
384
  *
290
385
  * @param header - The raw `Cookie` header value (possibly `undefined`)
291
386
  * @returns A record of every parsed cookie, `name → decoded value`
@@ -311,7 +406,7 @@ function parseCookies(header) {
311
406
  return out;
312
407
  }
313
408
  /**
314
- * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
409
+ * Checks whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
315
410
  * cookie-token chars with NO surrounding (or interior) whitespace.
316
411
  *
317
412
  * @remarks
@@ -321,7 +416,7 @@ function parseCookies(header) {
321
416
  * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
322
417
  *
323
418
  * @param value - The candidate cookie name
324
- * @returns `true` when `value` is a valid, whitespace-free cookie token
419
+ * @returns True if `value` is a valid, whitespace-free cookie token; false otherwise
325
420
  *
326
421
  * @example
327
422
  * ```ts
@@ -333,7 +428,7 @@ function isCookieName(value) {
333
428
  return /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/.test(value);
334
429
  }
335
430
  /**
336
- * Decode a cookie value with `decodeURIComponent`, falling back to the raw
431
+ * Decodes a cookie value with `decodeURIComponent`, falling back to the raw
337
432
  * text when the value is not valid percent-encoding.
338
433
  *
339
434
  * @param raw - The raw (trimmed) cookie value
@@ -353,7 +448,7 @@ function decodeCookieValue(raw) {
353
448
  }
354
449
  }
355
450
  /**
356
- * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
451
+ * Checks whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
357
452
  * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
358
453
  * attributes with before emitting them.
359
454
  *
@@ -364,7 +459,7 @@ function decodeCookieValue(raw) {
364
459
  * directive. Total — never throws (a bad value returns `false`).
365
460
  *
366
461
  * @param value - The candidate attribute value (a `Domain` or `Path`)
367
- * @returns `true` when `value` carries no separator / whitespace / control char
462
+ * @returns True if `value` carries no separator / whitespace / control char; false otherwise
368
463
  *
369
464
  * @example
370
465
  * ```ts
@@ -381,7 +476,7 @@ function isCookieAttribute(value) {
381
476
  return true;
382
477
  }
383
478
  /**
384
- * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
479
+ * Serializes a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
385
480
  *
386
481
  * @remarks
387
482
  * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
@@ -389,10 +484,9 @@ function isCookieAttribute(value) {
389
484
  * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
390
485
  * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
391
486
  * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
392
- * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
393
- * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
487
+ * injection attempt (a programmer misconfiguration — never a silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
394
488
  * the `secure` option (the spec requires it); an un-resolved `undefined`
395
- * `secure` here falls to OFF — request-aware callers resolve it first via
489
+ * `secure` here falls to OFF — request-aware callers resolve it first through
396
490
  * {@link resolveSecure}.
397
491
  *
398
492
  * @param name - The cookie name
@@ -423,7 +517,7 @@ function serializeCookie(name, value, options) {
423
517
  return parts.join("; ");
424
518
  }
425
519
  /**
426
- * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
520
+ * Resolves a cookie's effective `Secure` flag from its {@link CookieOptions}
427
521
  * `secure` setting and whether the request arrived over TLS.
428
522
  *
429
523
  * @remarks
@@ -433,7 +527,10 @@ function serializeCookie(name, value, options) {
433
527
  * gets `Secure` automatically while local-dev HTTP still works.
434
528
  *
435
529
  * @param secure - The {@link CookieOptions} `secure` setting
436
- * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
530
+ * @param encrypted - The connection's TLS flag
531
+ * ({@link import('./types.js').Connection.encrypted}). If `true`, an omitted
532
+ * `secure` resolves to `Secure`; if `false`, an omitted `secure` resolves to
533
+ * no `Secure` attribute.
437
534
  * @returns The concrete `Secure` flag to emit
438
535
  *
439
536
  * @example
@@ -448,39 +545,15 @@ function resolveSecure(secure, encrypted) {
448
545
  return encrypted;
449
546
  }
450
547
  /**
451
- * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
452
- * clobbering a prior one.
453
- *
454
- * @remarks
455
- * `Headers.append` already accumulates repeated headers (unlike node's
456
- * `setHeader`), so this is a thin, self-documenting wrapper naming the
457
- * cookie-append intent — the primitive {@link writeSignedCookie} /
458
- * {@link clearCookie} use.
459
- *
460
- * @param headers - The response `Headers` to write into
461
- * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
462
- *
463
- * @example
464
- * ```ts
465
- * const headers = new Headers()
466
- * appendCookie(headers, serializeCookie('a', '1'))
467
- * appendCookie(headers, serializeCookie('b', '2'))
468
- * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
469
- * ```
470
- */
471
- function appendCookie(headers, cookie) {
472
- headers.append("set-cookie", cookie);
473
- }
474
- /**
475
- * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
476
- * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
548
+ * Writes a SIGNED cookie — HMAC-signs `value` with {@link signToken} and
549
+ * appends it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
477
550
  *
478
551
  * @remarks
479
552
  * The cookie value is `await signToken(value, { secret })`
480
553
  * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
481
554
  * cookie — the same secret rotation and tamper rejection, no second HMAC
482
- * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
483
- * signing is asynchronous (§3 of the proposal).
555
+ * scheme. Appends (never clobbers) through `Headers.append`, which accumulates
556
+ * repeated headers. Async — WebCrypto signing is asynchronous.
484
557
  *
485
558
  * @param headers - The response `Headers` to write into
486
559
  * @param name - The cookie name
@@ -495,10 +568,10 @@ function appendCookie(headers, cookie) {
495
568
  * ```
496
569
  */
497
570
  async function writeSignedCookie(headers, name, value, secret, options) {
498
- appendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options));
571
+ headers.append("set-cookie", serializeCookie(name, await signToken(value, { secret }), options));
499
572
  }
500
573
  /**
501
- * Read + verify a SIGNED cookie off a request — TOTAL, returning the
574
+ * Reads + verifies a SIGNED cookie off a request — TOTAL, returning the
502
575
  * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
503
576
  *
504
577
  * @remarks
@@ -522,7 +595,7 @@ async function readSignedCookie(request, name, secret) {
522
595
  return cookie === void 0 ? void 0 : verifyToken(cookie, secret);
523
596
  }
524
597
  /**
525
- * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
598
+ * Clears a cookie — appends a `Set-Cookie` that expires it immediately (`Max-Age=0`).
526
599
  *
527
600
  * @remarks
528
601
  * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
@@ -540,23 +613,23 @@ async function readSignedCookie(request, name, secret) {
540
613
  * ```
541
614
  */
542
615
  function clearCookie(headers, name, options) {
543
- appendCookie(headers, serializeCookie(name, "", {
616
+ headers.append("set-cookie", serializeCookie(name, "", {
544
617
  ...options,
545
618
  maxAge: 0
546
619
  }));
547
620
  }
548
621
  /**
549
- * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
622
+ * Signs a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
550
623
  *
551
624
  * @remarks
552
625
  * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
553
626
  * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
554
627
  * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
555
- * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
628
+ * the signature), signed by using `crypto.subtle.sign('HMAC', …)` under the FIRST
556
629
  * {@link TokenSecret} (the current secret, or the head of a rotation list).
557
630
  * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
558
631
  * misconfigured secret with no usable entry THROWS an {@link HTTPError}
559
- * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
632
+ * (`500`) — fail-closed, a programmer error. Verify with
560
633
  * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
561
634
  *
562
635
  * @param value - The opaque value to embed (a session id, a deployment marker)
@@ -586,19 +659,19 @@ async function signToken(value, options) {
586
659
  return `${encoded}.${encodeBase64URL(new Uint8Array(signature))}`;
587
660
  }
588
661
  /**
589
- * Verify a stateless token and return its embedded value — TOTAL, never throws.
662
+ * Verifies a stateless token and returns its embedded value — TOTAL, never throws.
590
663
  *
591
664
  * @remarks
592
665
  * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
593
666
  * value containing dots survives), decodes the signature with
594
667
  * `@orkestrel/codec`'s `decodeBase64URL` — a signature that is not canonical
595
668
  * base64url is refused there, before any key import — and checks the payload's
596
- * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate via
669
+ * HMAC-SHA256 signature against EACH {@link TokenSecret} candidate through
597
670
  * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
598
- * retired, §3 of the proposal), accepting the token on the first match (the
671
+ * retired), accepting the token on the first match (the
599
672
  * rotation path). It then decodes + narrows the payload (`isRecord` +
600
- * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
601
- * rejects an expired token. ANY failure — a malformed token, a bad signature,
673
+ * `typeof`, never `as`) and, when an expiry was bound in, rejects an expired
674
+ * token. ANY failure — a malformed token, a bad signature,
602
675
  * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
603
676
  * yields `undefined` rather than throwing.
604
677
  *
@@ -634,15 +707,15 @@ async function verifyToken(token, secret) {
634
707
  }
635
708
  }
636
709
  /**
637
- * Decode + narrow a signed token's base64url JSON payload, honoring its
710
+ * Decodes + narrows a signed token's base64url JSON payload, honoring its
638
711
  * expiry — the shared decode step {@link verifyToken} applies after a
639
712
  * signature match.
640
713
  *
641
714
  * @remarks
642
715
  * Decodes the payload with `@orkestrel/codec`'s `decodeBase64URL` (total — a
643
716
  * non-canonical base64url segment answers `undefined` rather than throwing),
644
- * reads it as UTF-8 JSON, narrows it to a record with a string `value`
645
- * (AGENTS §14 — never `as`), and rejects an expired `exp`. TOTAL — any
717
+ * reads it as UTF-8 JSON, narrows it to a record with a string `value` without
718
+ * `as`, and rejects an expired `exp`. TOTAL — any
646
719
  * decode/shape/expiry failure yields `undefined`; only `JSON.parse` still
647
720
  * throws, and its `catch` answers `undefined` too.
648
721
  *
@@ -664,7 +737,7 @@ function decodeTokenPayload(encoded) {
664
737
  }
665
738
  }
666
739
  /**
667
- * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
740
+ * Normalizes a {@link TokenSecret} to a concrete list of USABLE secrets —
668
741
  * backs both {@link signToken} and {@link verifyToken}.
669
742
  *
670
743
  * @remarks
@@ -685,7 +758,7 @@ function normalizeSecret(secret) {
685
758
  return (typeof secret === "string" ? [secret] : [...secret]).filter((entry) => entry.trim().length > 0);
686
759
  }
687
760
  /**
688
- * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
761
+ * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
689
762
  * into its q-sorted entries.
690
763
  *
691
764
  * @remarks
@@ -734,9 +807,9 @@ function parseAcceptHeader(header) {
734
807
  })).sort((a, b) => b.entry.q - a.entry.q || a.index - b.index).map((ranked) => ranked.entry);
735
808
  }
736
809
  /**
737
- * The client's quality (q) for one content-coding from the parsed
738
- * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
739
- * server-preference selection.
810
+ * Computes the client's quality (q) for one content-coding from the parsed
811
+ * `Accept-Encoding` entries — the scoring leaf {@link resolveCoding} runs over
812
+ * each offered coding.
740
813
  *
741
814
  * @remarks
742
815
  * Prefers an EXACT named match (including an explicit `;q=0` rejection);
@@ -750,43 +823,45 @@ function parseAcceptHeader(header) {
750
823
  *
751
824
  * @example
752
825
  * ```ts
753
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
754
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
826
+ * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
827
+ * computeCodingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
755
828
  * ```
756
829
  */
757
- function codingQuality(entries, coding) {
830
+ function computeCodingQuality(entries, coding) {
758
831
  const named = entries.find((entry) => entry.value === coding);
759
832
  if (named !== void 0) return named.q;
760
833
  return entries.find((entry) => entry.value === "*")?.q ?? 0;
761
834
  }
762
835
  /**
763
- * Select the best content-coding for an `Accept-Encoding` header from the
764
- * codings the server offers.
836
+ * Picks the highest-scoring content-coding the server offers against already
837
+ * parsed `Accept-Encoding` entries.
765
838
  *
766
839
  * @remarks
767
- * Parses the header ({@link parseAcceptHeader}) and scores each `available`
768
- * coding in the SERVER's preference order ({@link codingQuality}), keeping
769
- * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
770
- * client-side tie). Returns `undefined` when the client accepts none of
771
- * `available` (identity — no compression). TOTAL on hostile input.
840
+ * The single selection leaf behind both doors onto this axis —
841
+ * {@link negotiateEncoding} for a raw header, and `Negotiator.encoding` for the
842
+ * entity — so the scoring loop has one implementation. Scores each `available`
843
+ * coding with {@link computeCodingQuality} and keeps the highest; a strict `>`
844
+ * keeps the earlier-offered coding on a client-side tie, which is what makes
845
+ * `available` the SERVER's preference order. An empty `available` list, and a
846
+ * list the client rejects outright, both yield `undefined` (identity — no
847
+ * compression). TOTAL on hostile input.
772
848
  *
773
849
  * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
774
- * @param header - The raw `Accept-Encoding` header value
850
+ * @param entries - The parsed {@link AcceptEntry} list
775
851
  * @param available - The codings the server offers, in preference (tie-break) order
776
- * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
852
+ * @returns The winning coding, or `undefined` when none of `available` is acceptable
777
853
  *
778
854
  * @example
779
855
  * ```ts
780
- * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
856
+ * resolveCoding(parseAcceptHeader('gzip;q=1.0, deflate;q=0.8'), ['gzip', 'deflate']) // 'gzip'
857
+ * resolveCoding(parseAcceptHeader('br;q=1.0'), ['gzip']) // undefined
781
858
  * ```
782
859
  */
783
- function negotiateEncoding(header, available) {
784
- if (available.length === 0) return void 0;
785
- const entries = parseAcceptHeader(header);
860
+ function resolveCoding(entries, available) {
786
861
  let best;
787
862
  let bestQuality = 0;
788
863
  for (const coding of available) {
789
- const quality = codingQuality(entries, coding);
864
+ const quality = computeCodingQuality(entries, coding);
790
865
  if (quality > bestQuality) {
791
866
  best = coding;
792
867
  bestQuality = quality;
@@ -795,7 +870,32 @@ function negotiateEncoding(header, available) {
795
870
  return best;
796
871
  }
797
872
  /**
798
- * Rank + quality of one `candidate` media type against the parsed `Accept`
873
+ * Selects the best content-coding for a raw `Accept-Encoding` header from the
874
+ * codings the server offers.
875
+ *
876
+ * @remarks
877
+ * Parses the header ({@link parseAcceptHeader}) and hands the entries to
878
+ * {@link resolveCoding}, the same selection leaf `Negotiator.encoding` runs, so
879
+ * the two doors onto this axis cannot drift. Returns `undefined` when the
880
+ * client accepts none of `available` (identity — no compression). TOTAL on
881
+ * hostile input.
882
+ *
883
+ * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
884
+ * @param header - The raw `Accept-Encoding` header value
885
+ * @param available - The codings the server offers, in preference (tie-break) order
886
+ * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
887
+ *
888
+ * @example
889
+ * ```ts
890
+ * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
891
+ * ```
892
+ */
893
+ function negotiateEncoding(header, available) {
894
+ if (available.length === 0) return void 0;
895
+ return resolveCoding(parseAcceptHeader(header), available);
896
+ }
897
+ /**
898
+ * Reports the rank + quality of one `candidate` media type against the parsed `Accept`
799
899
  * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
800
900
  * uses to score each `available` candidate.
801
901
  *
@@ -810,7 +910,7 @@ function negotiateEncoding(header, available) {
810
910
  *
811
911
  * @param entries - The parsed {@link AcceptEntry} list
812
912
  * @param candidate - The candidate media type to score (e.g. `'text/html'`)
813
- * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
913
+ * @returns The {@link MediaMatch} for the best matching entry, or `undefined` when nothing matches
814
914
  *
815
915
  * @example
816
916
  * ```ts
@@ -842,8 +942,9 @@ function matchMediaType(entries, candidate) {
842
942
  return best;
843
943
  }
844
944
  /**
845
- * The client's quality for one `candidate` language from the parsed
846
- * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
945
+ * Computes the client's quality for one `candidate` language from the parsed
946
+ * `Accept-Language` entries — the scoring leaf the `Negotiator`'s `language`
947
+ * axis runs over each offered tag.
847
948
  *
848
949
  * @remarks
849
950
  * Prefers an exact match, then a primary-tag prefix match (`en` accepts
@@ -856,12 +957,12 @@ function matchMediaType(entries, candidate) {
856
957
  *
857
958
  * @example
858
959
  * ```ts
859
- * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
860
- * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
861
- * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
960
+ * computeLanguageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
961
+ * computeLanguageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
962
+ * computeLanguageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
862
963
  * ```
863
964
  */
864
- function languageQuality(entries, candidate) {
965
+ function computeLanguageQuality(entries, candidate) {
865
966
  const lower = candidate.toLowerCase();
866
967
  const primary = lower.split("-")[0];
867
968
  let named;
@@ -879,7 +980,7 @@ function languageQuality(entries, candidate) {
879
980
  return wildcard ?? 0;
880
981
  }
881
982
  /**
882
- * Whether a `Content-Type` is worth compressing.
983
+ * Checks whether a `Content-Type` is worth compressing.
883
984
  *
884
985
  * @remarks
885
986
  * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
@@ -889,7 +990,7 @@ function languageQuality(entries, candidate) {
889
990
  * absent/empty type is not compressible. TOTAL.
890
991
  *
891
992
  * @param type - The response `Content-Type` header value (with or without parameters)
892
- * @returns `true` when the type is text-shaped and worth compressing
993
+ * @returns True if the type is text-shaped and worth compressing; false otherwise
893
994
  *
894
995
  * @example
895
996
  * ```ts
@@ -906,7 +1007,7 @@ function isCompressibleType(type) {
906
1007
  return COMPRESSIBLE_TYPES.has(bare);
907
1008
  }
908
1009
  /**
909
- * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
1010
+ * Computes a CONTENT `ETag` over a fully-buffered response body by using WebCrypto.
910
1011
  *
911
1012
  * @remarks
912
1013
  * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
@@ -916,7 +1017,8 @@ function isCompressibleType(type) {
916
1017
  * (`"<hash>"`, byte-identity) when `weak` is `false`.
917
1018
  *
918
1019
  * @param body - The full (uncompressed) response body to hash
919
- * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
1020
+ * @param weak - If `true` (the default), returns a weak `W/"…"` validator; if
1021
+ * `false`, returns a strong `"…"` one.
920
1022
  * @returns The `ETag` header value
921
1023
  *
922
1024
  * @example
@@ -926,11 +1028,11 @@ function isCompressibleType(type) {
926
1028
  */
927
1029
  async function computeBodyETag(body, weak = true) {
928
1030
  const digest = await crypto.subtle.digest("SHA-256", body);
929
- const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
1031
+ const hex = encodeHex(new Uint8Array(digest));
930
1032
  return weak ? `W/"${hex}"` : `"${hex}"`;
931
1033
  }
932
1034
  /**
933
- * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
1035
+ * Strips the WEAK indicator (`W/`) from an entity-tag, returning its opaque
934
1036
  * comparison body — the reduction {@link matchesETag} applies to both sides
935
1037
  * before the RFC 7232 §2.3.2 weak comparison.
936
1038
  *
@@ -947,7 +1049,7 @@ function unwrapETag(tag) {
947
1049
  return trimmed.startsWith("W/") ? trimmed.slice(2) : trimmed;
948
1050
  }
949
1051
  /**
950
- * Whether a request's `If-None-Match` header matches a resource's current
1052
+ * Checks whether a request's `If-None-Match` header matches a resource's current
951
1053
  * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
952
1054
  *
953
1055
  * @remarks
@@ -955,12 +1057,12 @@ function unwrapETag(tag) {
955
1057
  * listed tag matches), or the `*` wildcard (matches ANY current
956
1058
  * representation — only a list of exactly `*` is the wildcard). Comparison is
957
1059
  * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
958
- * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
1060
+ * through {@link unwrapETag} before comparing the opaque body). TOTAL — a
959
1061
  * malformed/empty header matches nothing, never throws.
960
1062
  *
961
1063
  * @param header - The raw `If-None-Match` header value
962
1064
  * @param etag - The resource's current `ETag`
963
- * @returns `true` when the conditional matches (the caller answers `304`)
1065
+ * @returns True if the conditional matches (the caller answers `304`); false otherwise
964
1066
  *
965
1067
  * @example
966
1068
  * ```ts
@@ -980,7 +1082,7 @@ function matchesETag(header, etag) {
980
1082
  return false;
981
1083
  }
982
1084
  /**
983
- * Parse an HTTP `Range` request header against a known resource `size` —
1085
+ * Parses an HTTP `Range` request header against a known resource `size` —
984
1086
  * TOTAL, returning a {@link RangeSpec} or `undefined`.
985
1087
  *
986
1088
  * @remarks
@@ -1043,7 +1145,7 @@ function parseRange(header, size) {
1043
1145
  };
1044
1146
  }
1045
1147
  /**
1046
- * Resolve the `Access-Control-Allow-Origin` value for a request.
1148
+ * Resolves the `Access-Control-Allow-Origin` value for a request.
1047
1149
  *
1048
1150
  * @remarks
1049
1151
  * `'*'` and a single origin string pass straight through. An allow-list
@@ -1070,7 +1172,7 @@ function resolveOrigin(origin, requestOrigin) {
1070
1172
  return origin.includes(requestOrigin) ? requestOrigin : void 0;
1071
1173
  }
1072
1174
  /**
1073
- * Merge a `Vary` value into an existing `Vary` header without duplication.
1175
+ * Merges a `Vary` value into an existing `Vary` header without duplication.
1074
1176
  *
1075
1177
  * @remarks
1076
1178
  * Splits `existing` on `,`, trims each member, and appends `value` only when
@@ -1094,11 +1196,11 @@ function mergeVary(existing, value) {
1094
1196
  return members.some((member) => member.toLowerCase() === value.toLowerCase()) ? members.join(", ") : [...members, value].join(", ");
1095
1197
  }
1096
1198
  /**
1097
- * Resolve one opt-out, value-bearing security header.
1199
+ * Resolves one opt-out, value-bearing security header.
1098
1200
  *
1099
1201
  * @remarks
1100
1202
  * The shared "a `string` value, or `false` to omit, or a default when unset"
1101
- * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
1203
+ * resolution (a value-or-off union, not a behavioral toggle):
1102
1204
  * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
1103
1205
  * override, `undefined` (unset) ⇒ `fallback` (the secure default).
1104
1206
  *
@@ -1118,7 +1220,7 @@ function resolveSecurityHeader(value, fallback) {
1118
1220
  return value ?? fallback;
1119
1221
  }
1120
1222
  /**
1121
- * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1223
+ * Checks whether a client-supplied `X-Request-ID` is SAFE to echo into a response
1122
1224
  * header + `context.state`.
1123
1225
  *
1124
1226
  * @remarks
@@ -1129,7 +1231,7 @@ function resolveSecurityHeader(value, fallback) {
1129
1231
  * TOTAL — never throws.
1130
1232
  *
1131
1233
  * @param value - The candidate incoming request id
1132
- * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
1234
+ * @returns True if `value` is a safe, bounded, charset-clean correlation id; false otherwise
1133
1235
  *
1134
1236
  * @example
1135
1237
  * ```ts
@@ -1141,7 +1243,7 @@ function isValidRequestId(value) {
1141
1243
  return REQUEST_ID_PATTERN.test(value);
1142
1244
  }
1143
1245
  /**
1144
- * Compute the `/64` network of a full IPv6 address, or `undefined` when the
1246
+ * Computes the `/64` network of a full IPv6 address, or `undefined` when the
1145
1247
  * input is not a plain IPv6 address to collapse.
1146
1248
  *
1147
1249
  * @remarks
@@ -1157,11 +1259,11 @@ function isValidRequestId(value) {
1157
1259
  *
1158
1260
  * @example
1159
1261
  * ```ts
1160
- * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1161
- * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1262
+ * computeIPv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
1263
+ * computeIPv6Network('192.0.2.1') // undefined — IPv4, not collapsed
1162
1264
  * ```
1163
1265
  */
1164
- function ipv6Network(address) {
1266
+ function computeIPv6Network(address) {
1165
1267
  if (/^::ffff:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/i.test(address)) return void 0;
1166
1268
  const percent = address.indexOf("%");
1167
1269
  const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
@@ -1191,30 +1293,30 @@ function ipv6Network(address) {
1191
1293
  return `${prefix.join(":")}::/64`;
1192
1294
  }
1193
1295
  /**
1194
- * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
1296
+ * Collapses a client IP into its rate-limit BUCKET key — an IPv6 address to
1195
1297
  * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
1196
1298
  *
1197
1299
  * @remarks
1198
1300
  * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
1199
1301
  * per-`/128` rate limit is trivially bypassed by rotating host bits — the
1200
1302
  * real identity is the `/64` network. Delegates the IPv6 collapse to
1201
- * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
1303
+ * {@link computeIPv6Network}; anything it returns `undefined` for (an IPv4 address,
1202
1304
  * a malformed string) is kept unchanged.
1203
1305
  *
1204
- * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
1306
+ * @param address - The raw connection peer address ({@link import('./types.js').Connection.ip})
1205
1307
  * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
1206
1308
  *
1207
1309
  * @example
1208
1310
  * ```ts
1209
- * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1210
- * clientRateKey('192.0.2.1') // '192.0.2.1'
1311
+ * computeClientKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
1312
+ * computeClientKey('192.0.2.1') // '192.0.2.1'
1211
1313
  * ```
1212
1314
  */
1213
- function clientRateKey(address) {
1214
- return ipv6Network(address) ?? address;
1315
+ function computeClientKey(address) {
1316
+ return computeIPv6Network(address) ?? address;
1215
1317
  }
1216
1318
  /**
1217
- * Serialize one {@link SSEMessage} to the SSE wire.
1319
+ * Serializes one {@link SSEMessage} to the SSE wire.
1218
1320
  *
1219
1321
  * @remarks
1220
1322
  * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
@@ -1241,129 +1343,12 @@ function serializeEvent(message) {
1241
1343
  return `${lines.join("\n")}\n\n`;
1242
1344
  }
1243
1345
  /**
1244
- * Enqueue encoded text into an open byte stream.
1245
- *
1246
- * @param controller - The stream controller, when the stream has started
1247
- * @param encoder - The encoder used for the stream's byte representation
1248
- * @param closed - Whether the stream has already ended or been cancelled
1249
- * @param text - The text to encode and enqueue
1250
- * @returns Nothing
1251
- *
1252
- * @example
1253
- * ```ts
1254
- * const body = new ReadableStream<Uint8Array>({
1255
- * start(controller) {
1256
- * enqueueStreamText(controller, new TextEncoder(), false, 'hello')
1257
- * },
1258
- * })
1259
- * ```
1260
- */
1261
- function enqueueStreamText(controller, encoder, closed, text) {
1262
- if (closed || controller === void 0) return;
1263
- controller.enqueue(encoder.encode(text));
1264
- }
1265
- /**
1266
- * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1267
- * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
1268
- *
1269
- * @remarks
1270
- * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
1271
- * merged under any `options.headers` (a seam-owned key is never overridden),
1272
- * at `options.status` (default `200`). The returned {@link StreamInterface}'s
1273
- * `write` serializes one message ({@link serializeEvent}), enqueues it, and
1274
- * returns whether the controller still has positive desired size. A producer
1275
- * receiving `false` can await `drain()`; its event-driven promise resolves on
1276
- * the next consumer pull that restores capacity, or on stream closure.
1277
- * `comment` writes a `: text` keep-alive line a conforming parser ignores;
1278
- * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
1279
- * by `end()`, or the consumer cancelled the stream), so a late write never
1280
- * throws.
1281
- *
1282
- * This readiness reflects only the process-local `ReadableStream` queue — it
1283
- * is not proof that a remote peer consumed bytes. When the response pump
1284
- * honors its socket sink's drain state, socket pressure stops body pulls and
1285
- * therefore keeps this queue full, allowing a cooperative producer to bound
1286
- * buffering. Ignoring the return value preserves the prior unconditional-
1287
- * enqueue behavior. The default stream strategy counts chunks rather than
1288
- * their byte length, so a byte-bounded producer must also cap each message.
1289
- * Return `response` before awaiting a `false` write, because the consumer
1290
- * cannot pull until it receives the response.
1291
- *
1292
- * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
1293
- * @returns The {@link StreamInterface} handle
1294
- *
1295
- * @example
1296
- * ```ts
1297
- * const stream = openStream()
1298
- * void Promise.resolve().then(async () => {
1299
- * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
1300
- * stream.end()
1301
- * })
1302
- * // return stream.response from the route handler
1303
- * ```
1304
- */
1305
- function openStream(options) {
1306
- const encoder = new TextEncoder();
1307
- let closed = false;
1308
- let controller;
1309
- let wakeup;
1310
- const body = new ReadableStream({
1311
- start(streamController) {
1312
- controller = streamController;
1313
- },
1314
- pull(streamController) {
1315
- if (streamController.desiredSize === null || streamController.desiredSize <= 0) return;
1316
- wakeup?.resolve();
1317
- wakeup = void 0;
1318
- },
1319
- cancel() {
1320
- closed = true;
1321
- wakeup?.resolve();
1322
- wakeup = void 0;
1323
- }
1324
- });
1325
- const headers = new Headers({
1326
- ...SSE_HEADERS,
1327
- ...options?.headers
1328
- });
1329
- return {
1330
- response: new Response(body, {
1331
- status: options?.status ?? 200,
1332
- headers
1333
- }),
1334
- get closed() {
1335
- return closed;
1336
- },
1337
- write(message) {
1338
- if (closed || controller === void 0) return false;
1339
- enqueueStreamText(controller, encoder, closed, serializeEvent(message));
1340
- return controller.desiredSize !== null && controller.desiredSize > 0;
1341
- },
1342
- comment(text) {
1343
- enqueueStreamText(controller, encoder, closed, `: ${text}\n\n`);
1344
- },
1345
- drain() {
1346
- const desired = controller?.desiredSize;
1347
- if (closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
1348
- wakeup ??= Promise.withResolvers();
1349
- return wakeup.promise;
1350
- },
1351
- end() {
1352
- if (closed) return;
1353
- closed = true;
1354
- controller?.close();
1355
- wakeup?.resolve();
1356
- wakeup = void 0;
1357
- }
1358
- };
1359
- }
1360
- /**
1361
- * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1346
+ * Checks whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
1362
1347
  * or `prototype` — the three keys that, assigned onto a normal object, can
1363
1348
  * reach and mutate `Object.prototype`.
1364
1349
  *
1365
1350
  * @param key - The candidate object key
1366
- * @returns `true` when `key` is one of the three prototype-pollution keys
1351
+ * @returns True if `key` is one of the three prototype-pollution keys; false otherwise
1367
1352
  *
1368
1353
  * @example
1369
1354
  * ```ts
@@ -1375,8 +1360,8 @@ function isDangerousKey(key) {
1375
1360
  return key === "__proto__" || key === "constructor" || key === "prototype";
1376
1361
  }
1377
1362
  /**
1378
- * Recursively STRIP the prototype-pollution keys from a parsed value IN
1379
- * PLACE.
1363
+ * Strips the prototype-pollution keys from a parsed value IN PLACE,
1364
+ * recursively.
1380
1365
  *
1381
1366
  * @remarks
1382
1367
  * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
@@ -1398,7 +1383,7 @@ function isDangerousKey(key) {
1398
1383
  */
1399
1384
  function scrubPrototype(value) {
1400
1385
  if (Array.isArray(value)) {
1401
- for (const item of value) scrubPrototype(item);
1386
+ for (const member of value) scrubPrototype(member);
1402
1387
  return value;
1403
1388
  }
1404
1389
  if (isRecord(value)) {
@@ -1414,7 +1399,7 @@ function scrubPrototype(value) {
1414
1399
  return value;
1415
1400
  }
1416
1401
  /**
1417
- * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
1402
+ * Collects a `Request` body into a single `Uint8Array`, enforcing a size limit.
1418
1403
  *
1419
1404
  * @remarks
1420
1405
  * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
@@ -1457,14 +1442,14 @@ async function collectRequestBody(request, limit) {
1457
1442
  return merged;
1458
1443
  }
1459
1444
  /**
1460
- * Narrow a raw `Content-Encoding` header value to a decompressible
1461
- * {@link Encoding} — the boundary guard {@link readBody} uses to decide
1445
+ * Parses a raw `Content-Encoding` header value into a decompressible
1446
+ * {@link Encoding} — the boundary {@link readBody} coerces through to decide
1462
1447
  * whether a request body needs transparent decompression.
1463
1448
  *
1464
1449
  * @remarks
1465
1450
  * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1466
- * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
1467
- * the proposal). An absent header, `identity`, an unknown value, or a
1451
+ * `gzip` / `deflate` (the two `DecompressionStream`-supported codings). An
1452
+ * absent header, `identity`, an unknown value, or a
1468
1453
  * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1469
1454
  * TOTAL — never asserts the loose `string | null` header.
1470
1455
  *
@@ -1473,25 +1458,25 @@ async function collectRequestBody(request, limit) {
1473
1458
  *
1474
1459
  * @example
1475
1460
  * ```ts
1476
- * requestEncoding('gzip') // 'gzip'
1477
- * requestEncoding('br') // undefined — unsupported by DecompressionStream
1461
+ * parseEncoding('gzip') // 'gzip'
1462
+ * parseEncoding('br') // undefined — unsupported by DecompressionStream
1478
1463
  * ```
1479
1464
  */
1480
- function requestEncoding(header) {
1465
+ function parseEncoding(header) {
1481
1466
  if (!isString(header)) return void 0;
1482
1467
  const value = header.trim().toLowerCase();
1483
1468
  return value === "gzip" || value === "deflate" ? value : void 0;
1484
1469
  }
1485
1470
  /**
1486
- * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
1487
- * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
1471
+ * Decompresses an already-collected, `gzip`/`deflate`-encoded byte sequence
1472
+ * transparently through `DecompressionStream`, capping the DECOMPRESSED output —
1488
1473
  * the zip-bomb defense.
1489
1474
  *
1490
1475
  * @remarks
1491
1476
  * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
1492
1477
  * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
1493
1478
  * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
1494
- * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
1479
+ * has no `maxOutputLength` knob. A cap breach surfaces
1495
1480
  * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
1496
1481
  * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
1497
1482
  * (never conflated with the cap). A non-positive `cap` means uncapped.
@@ -1539,7 +1524,7 @@ async function decompressRequestBody(bytes, encoding, cap) {
1539
1524
  return merged;
1540
1525
  }
1541
1526
  /**
1542
- * Collect + decode a `Request` body — the shared body-collection pipeline
1527
+ * Collects + decodes a `Request` body — the shared body-collection pipeline
1543
1528
  * surfaced to middleware and handlers as the middleware context's cached
1544
1529
  * `body()`.
1545
1530
  *
@@ -1550,14 +1535,20 @@ async function decompressRequestBody(bytes, encoding, cap) {
1550
1535
  * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
1551
1536
  * `options.decompression`, default {@link
1552
1537
  * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1553
- * content type: `application/json` is parsed via `@orkestrel/contract`'s
1538
+ * content type: `application/json` is parsed by using `@orkestrel/contract`'s
1554
1539
  * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1555
1540
  * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1556
1541
  * decodes to `undefined`.
1557
1542
  *
1543
+ * A malformed JSON body is total: it decodes to `undefined` rather than
1544
+ * throwing, so a handler that must reject one checks for `undefined` itself.
1545
+ * That makes `undefined` the answer for two distinct inputs, and nothing in the
1546
+ * returned value tells them apart.
1547
+ *
1558
1548
  * @param request - The `Request` to read the body from
1559
1549
  * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1560
- * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
1550
+ * @returns The parsed JSON value, the raw text, or `undefined` — for an empty
1551
+ * body, and for an `application/json` body whose text is not valid JSON
1561
1552
  * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1562
1553
  * @throws {HTTPError} When the compressed body is corrupt (400)
1563
1554
  *
@@ -1570,7 +1561,7 @@ async function readBody(request, options) {
1570
1561
  const limit = options?.limit ?? 1048576;
1571
1562
  const decompression = options?.decompression ?? 16777216;
1572
1563
  const wire = await collectRequestBody(request, limit);
1573
- const encoding = requestEncoding(request.headers.get("content-encoding"));
1564
+ const encoding = parseEncoding(request.headers.get("content-encoding"));
1574
1565
  const bytes = encoding === void 0 ? wire : await decompressRequestBody(wire, encoding, decompression);
1575
1566
  if (bytes.length === 0) return void 0;
1576
1567
  const contentType = request.headers.get("content-type");
@@ -1581,30 +1572,17 @@ async function readBody(request, options) {
1581
1572
  return text;
1582
1573
  }
1583
1574
  /**
1584
- * Whether a `node:net` `server.address()` return is the structured
1585
- * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
1586
- * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
1587
- * and the `Server`'s own port resolution read the bound port through.
1575
+ * Binds and closes a throwaway TCP server to resolve one available port.
1588
1576
  *
1589
- * @param value - The `server.address()` return (`AddressInfo | string | null`)
1590
- * @returns `true` when `value` is an `AddressInfo` with a numeric `port`
1591
- *
1592
- * @example
1593
- * ```ts
1594
- * import { isAddressInfo } from '@src/server'
1595
- *
1596
- * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
1597
- * isAddressInfo(null) // false
1598
- * ```
1599
- */
1600
- function isAddressInfo(value) {
1601
- return isRecord(value) && isNumber(value.port);
1602
- }
1603
- /**
1604
- * Bind and close a throwaway TCP server to resolve one available port.
1577
+ * @remarks
1578
+ * The probe always closes, including on the rejection path. A listener whose
1579
+ * address is not an {@link import('node:net').AddressInfo} — a pipe listener,
1580
+ * which a numeric `port` cannot request — has no port to report, so this
1581
+ * rejects rather than substituting a number.
1605
1582
  *
1606
1583
  * @param port - The requested port, with `0` selecting an ephemeral port
1607
1584
  * @returns The bound port after the probe server has closed
1585
+ * @throws {TypeError} When the bound listener's address carries no numeric port
1608
1586
  *
1609
1587
  * @example
1610
1588
  * ```ts
@@ -1617,15 +1595,15 @@ async function probePort(port) {
1617
1595
  probe.listen(port);
1618
1596
  await listening;
1619
1597
  const address = probe.address();
1620
- const resolved = isAddressInfo(address) ? address.port : 0;
1621
1598
  const closed = once(probe, "close");
1622
1599
  probe.close();
1623
1600
  await closed;
1624
- return resolved;
1601
+ if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
1602
+ return address.port;
1625
1603
  }
1626
1604
  /**
1627
- * Find a FREE TCP port — bind a throwaway `node:net` server, read the
1628
- * OS-assigned port, close it, and resolve that port.
1605
+ * Finds a FREE TCP port — binds a throwaway `node:net` server, reads the
1606
+ * OS-assigned port, closes it, and resolves that port.
1629
1607
  *
1630
1608
  * @remarks
1631
1609
  * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
@@ -1635,11 +1613,16 @@ async function probePort(port) {
1635
1613
  * port. It binds then immediately closes a probe server, so the returned
1636
1614
  * port is free at the instant of the probe (an inherent TOCTOU race — bind it
1637
1615
  * promptly). Rejects only on an unexpected listen error other than a taken
1638
- * `preferred` port (e.g. a permission fault).
1616
+ * `preferred` port (e.g. a permission fault). A listener whose address is not
1617
+ * an {@link import('node:net').AddressInfo} — a pipe listener, which this
1618
+ * package's options cannot request — rejects with a `TypeError` rather than
1619
+ * reporting `0`, because `0` is this package's own request for an ephemeral
1620
+ * port and never means an unknown one.
1639
1621
  *
1640
1622
  * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
1641
1623
  * fall back to an ephemeral port
1642
1624
  * @returns A free TCP port number
1625
+ * @throws {TypeError} When the bound listener's address carries no numeric port
1643
1626
  *
1644
1627
  * @example
1645
1628
  * ```ts
@@ -1660,7 +1643,7 @@ async function discoverPort(preferred) {
1660
1643
  //#endregion
1661
1644
  //#region src/server/Negotiator.ts
1662
1645
  /**
1663
- * The content-negotiation machine over the weighted `Accept` family — a
1646
+ * Represents the content-negotiation machine over the weighted `Accept` family — a
1664
1647
  * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
1665
1648
  * {@link NegotiatorInterface}.
1666
1649
  *
@@ -1700,7 +1683,8 @@ var Negotiator = class {
1700
1683
  return best;
1701
1684
  }
1702
1685
  encoding(header, available) {
1703
- return negotiateEncoding(header, available);
1686
+ if (available.length === 0) return void 0;
1687
+ return resolveCoding(parseAcceptHeader(header), available);
1704
1688
  }
1705
1689
  language(header, available) {
1706
1690
  if (available.length === 0) return void 0;
@@ -1709,7 +1693,7 @@ var Negotiator = class {
1709
1693
  let best;
1710
1694
  let bestQuality = 0;
1711
1695
  for (const candidate of available) {
1712
- const quality = languageQuality(entries, candidate);
1696
+ const quality = computeLanguageQuality(entries, candidate);
1713
1697
  if (quality > bestQuality) {
1714
1698
  best = candidate;
1715
1699
  bestQuality = quality;
@@ -1718,6 +1702,9 @@ var Negotiator = class {
1718
1702
  return best;
1719
1703
  }
1720
1704
  /**
1705
+ * Dispatches the request to the handler its `Accept` header negotiates,
1706
+ * answering 406 when none matches.
1707
+ *
1721
1708
  * @remarks
1722
1709
  * Errors thrown by the negotiated handler propagate UNMODIFIED — the
1723
1710
  * server boundary classifies them, never this negotiator.
@@ -1735,14 +1722,14 @@ var Negotiator = class {
1735
1722
  //#endregion
1736
1723
  //#region src/server/Server.ts
1737
1724
  /**
1738
- * The HTTP server facade — an observable `node:http` lifecycle composing this
1725
+ * Represents the HTTP server facade — an observable `node:http` lifecycle composing this
1739
1726
  * module's own middleware onion around a consumed `@orkestrel/router`
1740
1727
  * dispatcher.
1741
1728
  *
1742
1729
  * @typeParam TState - The consumer's opaque per-request state type
1743
1730
  *
1744
1731
  * @remarks
1745
- * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1732
+ * - **Lifecycle.** `start(signal?)` builds the underlying `node:http`
1746
1733
  * server, binds the configured {@link ServerOptions.host} / {@link
1747
1734
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1748
1735
  * bound address), exposes that {@link AddressInfo} through `address`, observes
@@ -1756,15 +1743,15 @@ var Negotiator = class {
1756
1743
  * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1757
1744
  * still open. `destroy()` is the idempotent final teardown.
1758
1745
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1759
- * `close`); a `Request` is built via the router's `buildRequest`, its
1760
- * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
1746
+ * `close`); a `Request` is built through the router's `buildRequest`, its
1747
+ * `signal` LINKED to this run's stop signal through `@orkestrel/abort`'s
1761
1748
  * `linkSignal` (a fresh `Request` is constructed with the linked signal —
1762
1749
  * `buildRequest`'s own abort, armed by BOTH request-side and response-side
1763
- * teardown, composes with the server's stop signal via `AbortSignal.any`,
1764
- * so a handler awaiting `request.signal` observes BOTH); `context.state` is built via
1750
+ * teardown, composes with the server's stop signal through `AbortSignal.any`,
1751
+ * so a handler awaiting `request.signal` observes BOTH); `context.state` is built through
1765
1752
  * {@link ServerOptions.state} from the connection facts; the composed
1766
1753
  * middleware onion runs, terminating in `dispatcher.handle`; the result is
1767
- * written back via `sendResponse`.
1754
+ * written back through `sendResponse`.
1768
1755
  * - **The built-in boundary** wraps the WHOLE per-request chain, including
1769
1756
  * setup: `buildRequest` runs behind its own inner boundary that maps a
1770
1757
  * throw (e.g. a malformed `Host` header) to a silent `400` with no
@@ -1782,12 +1769,12 @@ var Negotiator = class {
1782
1769
  * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1783
1770
  * owns it, and the tracking exists because node detaches an upgraded socket
1784
1771
  * from the set its own close calls walk, so nothing else can end it.
1785
- * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
1772
+ * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
1786
1773
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1787
1774
  * routes it to the `error` OPTION (not the domain `error` event).
1788
1775
  */
1789
1776
  var Server = class {
1790
- id = crypto.randomUUID();
1777
+ #id;
1791
1778
  #dispatcher;
1792
1779
  #state;
1793
1780
  #middleware;
@@ -1820,6 +1807,7 @@ var Server = class {
1820
1807
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1821
1808
  const sockets = options.sockets ?? {};
1822
1809
  for (const [name, value] of Object.entries(sockets)) if (value !== void 0 && (!isInteger(value) || value < 0)) throw new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`);
1810
+ this.#id = crypto.randomUUID();
1823
1811
  this.#dispatcher = options.dispatcher;
1824
1812
  this.#state = options.state;
1825
1813
  this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
@@ -1836,8 +1824,8 @@ var Server = class {
1836
1824
  ...options.error === void 0 ? {} : { error: options.error }
1837
1825
  });
1838
1826
  }
1839
- get #inflight() {
1840
- return this.#pending + this.#upgraded.size;
1827
+ get id() {
1828
+ return this.#id;
1841
1829
  }
1842
1830
  get status() {
1843
1831
  return this.#status;
@@ -1863,7 +1851,7 @@ var Server = class {
1863
1851
  this.#upgradeHandlers.push(handler);
1864
1852
  }
1865
1853
  start(signal) {
1866
- if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
1854
+ if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(new ServerError("STATUS", `server cannot start from '${this.#status}'`, { status: this.#status }));
1867
1855
  this.#status = "starting";
1868
1856
  this.#abort = createAbort();
1869
1857
  const server = createServer$2((request, response) => this.#handle(request, response));
@@ -1997,17 +1985,13 @@ var Server = class {
1997
1985
  else socket.destroy();
1998
1986
  this.#emitter.emit("upgrade", request, handled);
1999
1987
  }
2000
- #resolvePort(server) {
2001
- const address = server.address();
2002
- if (isAddressInfo(address)) return address.port;
2003
- return 0;
2004
- }
2005
1988
  async #listen(server, signal) {
2006
1989
  const deadline = this.#timeouts.start === void 0 ? void 0 : createTimeout({ ms: this.#timeouts.start });
2007
1990
  const startup = deadline === void 0 ? signal : linkSignal(deadline.signal, signal);
2008
1991
  const binding = createAbort();
2009
1992
  const relay = startup === void 0 ? void 0 : addAbortListener(startup, () => binding.abort(startup.reason));
2010
1993
  let listening;
1994
+ let port;
2011
1995
  try {
2012
1996
  signal?.throwIfAborted();
2013
1997
  deadline?.start();
@@ -2021,6 +2005,9 @@ var Server = class {
2021
2005
  signal: binding.signal
2022
2006
  });
2023
2007
  await listening;
2008
+ const address = server.address();
2009
+ if (!isAddressInfo(address)) throw new TypeError("server bound a listener with no resolvable AddressInfo");
2010
+ port = address.port;
2024
2011
  } catch (error) {
2025
2012
  const expired = deadline?.expired === true;
2026
2013
  const cancelled = startup?.aborted === true;
@@ -2038,7 +2025,6 @@ var Server = class {
2038
2025
  relay?.[Symbol.dispose]();
2039
2026
  deadline?.clear();
2040
2027
  }
2041
- const port = this.#resolvePort(server);
2042
2028
  this.#port = port;
2043
2029
  this.#status = "listening";
2044
2030
  this.#emitter.emit("start", port);
@@ -2060,6 +2046,9 @@ var Server = class {
2060
2046
  } else server.closeIdleConnections();
2061
2047
  });
2062
2048
  }
2049
+ get #inflight() {
2050
+ return this.#pending + this.#upgraded.size;
2051
+ }
2063
2052
  #enter() {
2064
2053
  if (this.#inflight === 0) this.#wakeup = createAbort();
2065
2054
  }
@@ -2092,14 +2081,122 @@ var Server = class {
2092
2081
  }
2093
2082
  };
2094
2083
  //#endregion
2095
- //#region src/server/factories.ts
2084
+ //#region src/server/Stream.ts
2096
2085
  /**
2097
- * Create a {@link NegotiatorInterface} — the reusable content-negotiation
2098
- * machine over the weighted `Accept` family.
2086
+ * Represents the Server-Sent-Events handle over an open, fetch-standard streaming
2087
+ * `Response`. Implements exactly {@link StreamInterface}.
2099
2088
  *
2100
2089
  * @remarks
2101
- * Prefer this over `new Negotiator()` at call sites that only need the
2102
- * interface.
2090
+ * Builds the `Response` at construction from
2091
+ * {@link import('./constants.js').SSE_HEADERS} with any `options.headers`
2092
+ * merged OVER them, at `options.status` (default `200`). A caller repeating one
2093
+ * of those keys therefore replaces the seam's value, in any casing. The
2094
+ * instance owns the stream's
2095
+ * controller, its text encoder, the closed flag, and the parked producer's
2096
+ * wakeup, so the whole handle is one entity rather than a closure over four
2097
+ * bindings.
2098
+ *
2099
+ * `write` serializes one message ({@link serializeEvent}), enqueues it, and
2100
+ * returns whether the controller still has positive desired size. A producer
2101
+ * receiving `false` awaits `drain()`; that promise resolves on the next
2102
+ * consumer pull restoring capacity, or on stream closure. `comment` writes a
2103
+ * `: text` keep-alive line a conforming SSE parser ignores; `end` closes the
2104
+ * stream. Every method is a SAFE NO-OP once `closed` (ended by `end()`, or
2105
+ * the consumer cancelled the stream), so a late write never throws.
2106
+ *
2107
+ * The readiness signal reflects only the process-local `ReadableStream`
2108
+ * queue — it is not proof that a remote peer consumed bytes. When the response
2109
+ * pump honors its socket sink's drain state, socket pressure stops body pulls
2110
+ * and therefore keeps this queue full, letting a cooperative producer bound
2111
+ * its buffering. Ignoring the return value preserves an unconditional-enqueue
2112
+ * producer. The default stream strategy counts chunks rather than their byte
2113
+ * length, so a byte-bounded producer must also cap each message. Return
2114
+ * `response` before awaiting a `false` write, because the consumer cannot pull
2115
+ * until it receives the response.
2116
+ *
2117
+ * @example
2118
+ * ```ts
2119
+ * import { Stream } from '@src/server'
2120
+ *
2121
+ * const stream = new Stream()
2122
+ * void Promise.resolve().then(async () => {
2123
+ * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
2124
+ * stream.comment('keep-alive')
2125
+ * stream.end()
2126
+ * })
2127
+ * // return stream.response from the route handler
2128
+ * ```
2129
+ */
2130
+ var Stream = class {
2131
+ #encoder = new TextEncoder();
2132
+ #response;
2133
+ #controller;
2134
+ #closed = false;
2135
+ #wakeup;
2136
+ constructor(options) {
2137
+ const body = new ReadableStream({
2138
+ start: this.#attach.bind(this),
2139
+ pull: this.#pull.bind(this),
2140
+ cancel: this.#cancel.bind(this)
2141
+ });
2142
+ const headers = new Headers(SSE_HEADERS);
2143
+ for (const [name, value] of Object.entries(options?.headers ?? {})) headers.set(name, value);
2144
+ this.#response = new Response(body, {
2145
+ status: options?.status ?? 200,
2146
+ headers
2147
+ });
2148
+ }
2149
+ get response() {
2150
+ return this.#response;
2151
+ }
2152
+ get closed() {
2153
+ return this.#closed;
2154
+ }
2155
+ write(message) {
2156
+ if (this.#closed || this.#controller === void 0) return false;
2157
+ this.#enqueue(serializeEvent(message));
2158
+ return this.#controller.desiredSize !== null && this.#controller.desiredSize > 0;
2159
+ }
2160
+ comment(text) {
2161
+ this.#enqueue(`: ${text}\n\n`);
2162
+ }
2163
+ drain() {
2164
+ const desired = this.#controller?.desiredSize;
2165
+ if (this.#closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
2166
+ this.#wakeup ??= Promise.withResolvers();
2167
+ return this.#wakeup.promise;
2168
+ }
2169
+ end() {
2170
+ if (this.#closed) return;
2171
+ this.#closed = true;
2172
+ this.#controller?.close();
2173
+ this.#settle();
2174
+ }
2175
+ #attach(controller) {
2176
+ this.#controller = controller;
2177
+ }
2178
+ #pull(controller) {
2179
+ if (controller.desiredSize === null || controller.desiredSize <= 0) return;
2180
+ this.#settle();
2181
+ }
2182
+ #cancel() {
2183
+ this.#closed = true;
2184
+ this.#settle();
2185
+ }
2186
+ #enqueue(text) {
2187
+ if (this.#closed || this.#controller === void 0) return;
2188
+ this.#controller.enqueue(this.#encoder.encode(text));
2189
+ }
2190
+ #settle() {
2191
+ this.#wakeup?.resolve();
2192
+ this.#wakeup = void 0;
2193
+ }
2194
+ };
2195
+ //#endregion
2196
+ //#region src/server/factories.ts
2197
+ /**
2198
+ * Creates a {@link NegotiatorInterface} — the reusable content-negotiation
2199
+ * machine over the weighted `Accept` family.
2103
2200
  *
2104
2201
  * @returns A {@link NegotiatorInterface}
2105
2202
  *
@@ -2116,7 +2213,7 @@ function createNegotiator() {
2116
2213
  return new Negotiator();
2117
2214
  }
2118
2215
  /**
2119
- * Create a {@link ServerInterface} — the node face's HTTP server facade over
2216
+ * Creates a {@link ServerInterface} — the node face's HTTP server facade over
2120
2217
  * a consumed `@orkestrel/router` dispatcher.
2121
2218
  *
2122
2219
  * @typeParam TState - The consumer's opaque per-request state type
@@ -2142,7 +2239,30 @@ function createNegotiator() {
2142
2239
  function createServer(options) {
2143
2240
  return new Server(options);
2144
2241
  }
2242
+ /**
2243
+ * Creates a {@link StreamInterface} — a generic Server-Sent-Events stream whose
2244
+ * `response` is a fetch-standard streaming `Response` a route returns.
2245
+ *
2246
+ * @param options - {@link StreamOptions}
2247
+ * @returns A {@link StreamInterface} whose stream is open
2248
+ *
2249
+ * @example
2250
+ * ```ts
2251
+ * import { createStream } from '@src/server'
2252
+ *
2253
+ * const stream = createStream()
2254
+ * void Promise.resolve().then(async () => {
2255
+ * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
2256
+ * stream.comment('keep-alive')
2257
+ * stream.end()
2258
+ * })
2259
+ * // return stream.response from the route handler
2260
+ * ```
2261
+ */
2262
+ function createStream(options) {
2263
+ return new Stream(options);
2264
+ }
2145
2265
  //#endregion
2146
- export { COMPRESSIBLE_TYPES, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SSE_HEADERS, Server, appendCookie, clearCookie, clientRateKey, codingQuality, collectRequestBody, compose, computeBodyETag, createNegotiator, createServer, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, enqueueStreamText, ipv6Network, isAddressInfo, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isValidRequestId, languageQuality, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, openStream, parseAcceptHeader, parseCookies, parseRange, probePort, readBody, readSignedCookie, requestEncoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
2266
+ export { COMPRESSIBLE_TYPES, ContentTooLargeError, DEFAULT_BODY_LIMIT, DEFAULT_DECOMPRESSED_LIMIT, DEFAULT_DRAIN_MS, DEFAULT_ENCODINGS, HTTPError, HTTP_ERROR_BRAND, Negotiator, REQUEST_ID_PATTERN, SSE_HEADERS, Server, ServerError, Stream, clearCookie, collectRequestBody, compose, computeBodyETag, computeClientKey, computeCodingQuality, computeIPv6Network, computeLanguageQuality, createNegotiator, createServer, createStream, decodeCookieValue, decodeTokenPayload, decompressRequestBody, discoverPort, isAddressInfo, isCompressibleType, isCookieAttribute, isCookieName, isDangerousKey, isHTTPError, isServerError, isValidRequestId, matchMediaType, matchesETag, mergeVary, negotiateEncoding, normalizeSecret, parseAcceptHeader, parseCookies, parseEncoding, parseRange, probePort, readBody, readSignedCookie, resolveCoding, resolveOrigin, resolveSecure, resolveSecurityHeader, scrubPrototype, serializeCookie, serializeEvent, signToken, unwrapETag, verifyToken, wrapMiddleware, writeSignedCookie };
2147
2267
 
2148
2268
  //# sourceMappingURL=index.js.map