@orkestrel/server 0.0.11 → 0.0.13

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.
@@ -1787,9 +1787,10 @@ var Negotiator = class {
1787
1787
  * `idle → starting → listening`. A cancelled or expired bind closes its
1788
1788
  * partial server and resets to `idle` for another start. `stop()` transitions
1789
1789
  * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1790
- * so in-flight handlers observe cancellation, drains up to the `drain`
1791
- * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1792
- * is the idempotent final teardown.
1790
+ * so in-flight handlers observe cancellation, drains in-flight requests AND
1791
+ * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1792
+ * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1793
+ * still open. `destroy()` is the idempotent final teardown.
1793
1794
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1794
1795
  * `close`); a `Request` is built via the router's `buildRequest`, its
1795
1796
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1814,6 +1815,9 @@ var Negotiator = class {
1814
1815
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1815
1816
  * throwing handler is treated as declined and surfaced on `error`, an
1816
1817
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1818
+ * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1819
+ * owns it, and the tracking exists because node detaches an upgraded socket
1820
+ * from the set its own close calls walk, so nothing else can end it.
1817
1821
  * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
1818
1822
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1819
1823
  * routes it to the `error` OPTION (not the domain `error` event).
@@ -1824,6 +1828,7 @@ var Server = class {
1824
1828
  #state;
1825
1829
  #middleware;
1826
1830
  #upgradeHandlers = [];
1831
+ #upgraded = /* @__PURE__ */ new Set();
1827
1832
  #emitter;
1828
1833
  #host;
1829
1834
  #configuredPort;
@@ -1867,6 +1872,9 @@ var Server = class {
1867
1872
  ...options.error === void 0 ? {} : { error: options.error }
1868
1873
  });
1869
1874
  }
1875
+ get #inflight() {
1876
+ return this.#pending + this.#upgraded.size;
1877
+ }
1870
1878
  get status() {
1871
1879
  return this.#status;
1872
1880
  }
@@ -1912,8 +1920,9 @@ var Server = class {
1912
1920
  await this.#drainPending(deadline.signal);
1913
1921
  deadline.clear();
1914
1922
  const pending = this.#pending;
1915
- this.#emitter.emit("drain", pending);
1916
- if (server !== void 0) await this.#close(server, pending > 0);
1923
+ const upgraded = this.#upgraded.size;
1924
+ this.#emitter.emit("drain", pending, upgraded);
1925
+ if (server !== void 0) await this.#close(server, pending + upgraded > 0);
1917
1926
  this.#http = void 0;
1918
1927
  this.#port = void 0;
1919
1928
  this.#status = "stopped";
@@ -2016,7 +2025,8 @@ var Server = class {
2016
2025
  } catch (error) {
2017
2026
  this.#emitter.emit("error", error);
2018
2027
  }
2019
- if (!handled) socket.destroy();
2028
+ if (handled) this.#trackSocket(socket);
2029
+ else socket.destroy();
2020
2030
  this.#emitter.emit("upgrade", request, handled);
2021
2031
  }
2022
2032
  #resolvePort(server) {
@@ -2076,23 +2086,40 @@ var Server = class {
2076
2086
  #close(server, force) {
2077
2087
  return new Promise((resolve) => {
2078
2088
  server.close(() => resolve());
2079
- if (force) server.closeAllConnections();
2080
- else server.closeIdleConnections();
2089
+ if (force) {
2090
+ server.closeAllConnections();
2091
+ for (const socket of this.#upgraded) socket.destroy();
2092
+ } else server.closeIdleConnections();
2081
2093
  });
2082
2094
  }
2095
+ #enter() {
2096
+ if (this.#inflight === 0) this.#wakeup = (0, _orkestrel_abort.createAbort)();
2097
+ }
2098
+ #settle() {
2099
+ if (this.#inflight === 0) this.#wakeup.abort();
2100
+ }
2083
2101
  #trackStart() {
2084
- if (this.#pending === 0) this.#wakeup = (0, _orkestrel_abort.createAbort)();
2102
+ this.#enter();
2085
2103
  this.#pending += 1;
2086
2104
  let finished = false;
2087
2105
  return () => {
2088
2106
  if (finished) return;
2089
2107
  finished = true;
2090
2108
  this.#pending -= 1;
2091
- if (this.#pending === 0) this.#wakeup.abort();
2109
+ this.#settle();
2092
2110
  };
2093
2111
  }
2112
+ #trackSocket(socket) {
2113
+ if (socket.destroyed || this.#upgraded.has(socket)) return;
2114
+ this.#enter();
2115
+ this.#upgraded.add(socket);
2116
+ socket.once("close", () => {
2117
+ this.#upgraded.delete(socket);
2118
+ this.#settle();
2119
+ });
2120
+ }
2094
2121
  async #drainPending(signal) {
2095
- if (this.#pending === 0 || signal.aborted) return;
2122
+ if (this.#inflight === 0 || signal.aborted) return;
2096
2123
  await (0, node_events.once)(AbortSignal.any([signal, this.#wakeup.signal]), "abort");
2097
2124
  }
2098
2125
  };
@@ -187,7 +187,7 @@ export declare function collectRequestBody(request: Request, limit: number): Pro
187
187
  * const handle = compose([withHeader], async () => new Response('ok'))
188
188
  * ```
189
189
  */
190
- export declare function compose<TState>(middleware: readonly MiddlewareHandler<TState>[], terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
190
+ export declare function compose<TState>(middleware: ReadonlyArray<MiddlewareHandler<TState>>, terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
191
191
 
192
192
  /**
193
193
  * The set of bare `Content-Type`s `isCompressibleType` treats as
@@ -1481,9 +1481,10 @@ export declare function serializeEvent(message: SSEMessage): string;
1481
1481
  * `idle → starting → listening`. A cancelled or expired bind closes its
1482
1482
  * partial server and resets to `idle` for another start. `stop()` transitions
1483
1483
  * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1484
- * so in-flight handlers observe cancellation, drains up to the `drain`
1485
- * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1486
- * is the idempotent final teardown.
1484
+ * so in-flight handlers observe cancellation, drains in-flight requests AND
1485
+ * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1486
+ * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1487
+ * still open. `destroy()` is the idempotent final teardown.
1487
1488
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1488
1489
  * `close`); a `Request` is built via the router's `buildRequest`, its
1489
1490
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1508,6 +1509,9 @@ export declare function serializeEvent(message: SSEMessage): string;
1508
1509
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1509
1510
  * throwing handler is treated as declined and surfaced on `error`, an
1510
1511
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1512
+ * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1513
+ * owns it, and the tracking exists because node detaches an upgraded socket
1514
+ * from the set its own close calls walk, so nothing else can end it.
1511
1515
  * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
1512
1516
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1513
1517
  * routes it to the `error` OPTION (not the domain `error` event).
@@ -1521,7 +1525,7 @@ export declare class Server<TState> implements ServerInterface<TState> {
1521
1525
  get dispatcher(): DispatcherInterface<TState>;
1522
1526
  get emitter(): EmitterInterface<ServerEventMap>;
1523
1527
  use(middleware: MiddlewareHandler<TState>): void;
1524
- use(middleware: readonly MiddlewareHandler<TState>[]): void;
1528
+ use(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void;
1525
1529
  upgrade(handler: UpgradeHandler): void;
1526
1530
  start(signal?: AbortSignal): Promise<number>;
1527
1531
  stop(): Promise<void>;
@@ -1544,9 +1548,13 @@ export declare class Server<TState> implements ServerInterface<TState> {
1544
1548
  * the per-request path; `undefined` for an upgrade-handler throw (no fetch
1545
1549
  * `Request` exists on that path — only a raw `IncomingMessage`) or a listen
1546
1550
  * failure.
1547
- * - `stop` — `stop()` began (status just moved to `'stopping'`).
1551
+ * - `stop` — `stop()` began (status just moved to `'stopping'`). An upgrade
1552
+ * handler that owns a long-lived socket closes it from here, so the drain
1553
+ * below settles instead of running out the deadline.
1548
1554
  * - `drain` — the graceful drain settled (deadline hit or all finished);
1549
- * carries the still-pending request count (`0` on a clean drain).
1555
+ * carries the still-pending request count AND the still-attached upgraded
1556
+ * socket count. Both `0` is a clean drain; either non-zero means the close
1557
+ * that follows was FORCED and cut that work.
1550
1558
  * - `response` — fired after the response has been sent, for every request
1551
1559
  * that reaches the middleware pipeline (the success path and the
1552
1560
  * outer-boundary error path); carries the method, parsed pathname, final
@@ -1564,7 +1572,7 @@ export declare type ServerEventMap = {
1564
1572
  url: URL;
1565
1573
  }];
1566
1574
  readonly stop: readonly [];
1567
- readonly drain: readonly [pending: number];
1575
+ readonly drain: readonly [pending: number, upgraded: number];
1568
1576
  readonly response: readonly [
1569
1577
  event: {
1570
1578
  method: string;
@@ -1590,7 +1598,8 @@ export declare type ServerEventMap = {
1590
1598
  * while binding, and resolves the actually-bound port. A cancelled or expired
1591
1599
  * bind closes its partial server and resets to `idle`. `stop()` refuses new
1592
1600
  * connections, fires the stop signal so in-flight handlers can observe it,
1593
- * drains up to the configured deadline, then closes. `destroy()` is the final
1601
+ * drains in-flight requests and claimed upgraded sockets up to the configured
1602
+ * deadline, then closes — forcing whatever is left. `destroy()` is the final
1594
1603
  * idempotent teardown. Per request: a `Request` is built via the router's
1595
1604
  * `buildRequest` (its signal linked to the server's stop signal), the composed
1596
1605
  * middleware onion runs terminating in `dispatcher.handle`, and the result is
@@ -1605,7 +1614,7 @@ export declare interface ServerInterface<TState> {
1605
1614
  readonly dispatcher: DispatcherInterface<TState>;
1606
1615
  readonly emitter: EmitterInterface<ServerEventMap>;
1607
1616
  use(middleware: MiddlewareHandler<TState>): void;
1608
- use(middleware: readonly MiddlewareHandler<TState>[]): void;
1617
+ use(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void;
1609
1618
  upgrade(handler: UpgradeHandler): void;
1610
1619
  /**
1611
1620
  * Bind the configured listener and resolve its actually-bound port.
@@ -1615,7 +1624,26 @@ export declare interface ServerInterface<TState> {
1615
1624
  * @returns The actually-bound TCP port
1616
1625
  */
1617
1626
  start(signal?: AbortSignal): Promise<number>;
1627
+ /**
1628
+ * Stop gracefully: refuse new connections, fire the stop signal, drain, close.
1629
+ *
1630
+ * @remarks
1631
+ * Drainable work is every in-flight request PLUS every upgraded socket a
1632
+ * handler claimed. The drain parks on that work reaching zero or the
1633
+ * `drain` deadline expiring, emits `drain` with both remaining counts, and
1634
+ * then closes — dropping idle keep-alive sockets on a clean drain, and
1635
+ * destroying every open socket (including the claimed upgraded ones node's
1636
+ * own force-close cannot reach) when either count is still non-zero. It
1637
+ * therefore always resolves; the `drain` counts say whether anything was cut.
1638
+ *
1639
+ * @returns Resolves once the listener is closed and the status is `'stopped'`
1640
+ */
1618
1641
  stop(): Promise<void>;
1642
+ /**
1643
+ * Tear down for good: force-close the listener and every socket, then the emitter.
1644
+ *
1645
+ * @returns Resolves once nothing is left open; idempotent from any state
1646
+ */
1619
1647
  destroy(): Promise<void>;
1620
1648
  }
1621
1649
 
@@ -1639,9 +1667,12 @@ export declare interface ServerInterface<TState> {
1639
1667
  * `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
1640
1668
  * guaranteed-free port up front).
1641
1669
  * @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
1642
- * server stops accepting new connections and gives in-flight requests this
1643
- * long to finish before forcing sockets closed. Defaults to
1644
- * `DEFAULT_DRAIN_MS`. Must be a non-negative finite number.
1670
+ * server stops accepting new connections and gives in-flight requests AND
1671
+ * claimed upgraded sockets this long to finish before forcing every
1672
+ * remaining socket closed. Defaults to `DEFAULT_DRAIN_MS`. Must be a
1673
+ * non-negative finite number. A long-lived upgraded socket that nothing
1674
+ * closes therefore costs `stop()` this whole budget, so a WebSocket
1675
+ * handler closes its sockets on the `stop` event to settle sooner.
1645
1676
  * @param limit - The default request-body byte cap the context's `body()`
1646
1677
  * reads through. Defaults to `DEFAULT_BODY_LIMIT`. Must be a non-negative
1647
1678
  * finite number.
@@ -1675,7 +1706,7 @@ export declare interface ServerInterface<TState> {
1675
1706
  export declare interface ServerOptions<TState> {
1676
1707
  readonly dispatcher: DispatcherInterface<TState>;
1677
1708
  readonly state: ConnectionStateFunction<TState>;
1678
- readonly middleware?: readonly MiddlewareHandler<TState>[];
1709
+ readonly middleware?: ReadonlyArray<MiddlewareHandler<TState>>;
1679
1710
  readonly host?: string;
1680
1711
  readonly port?: number;
1681
1712
  readonly drain?: number;
@@ -1907,6 +1938,16 @@ export declare function unwrapETag(tag: string): string;
1907
1938
  * connection. `request` / `socket` / `head` are node's own raw values, handed
1908
1939
  * over verbatim — no assertion at this boundary (AGENTS §14).
1909
1940
  *
1941
+ * A CLAIMED socket is TRACKED until it closes. The handler still owns it —
1942
+ * the server only watches — but `stop()` now drains that socket like an
1943
+ * in-flight request and destroys it if the `drain` deadline expires first.
1944
+ * Node detaches an upgraded socket from its own connection set, so neither
1945
+ * `closeIdleConnections()` nor `closeAllConnections()` reaches it and this
1946
+ * tracking is what lets `stop()` and `destroy()` finish at all. A handler
1947
+ * that wants a protocol-clean goodbye (a WebSocket close frame) sends it on
1948
+ * the server's `stop` event and closes the socket; the drain settles the
1949
+ * moment the last one goes.
1950
+ *
1910
1951
  * @param request - The raw `node:http` upgrade request
1911
1952
  * @param socket - The raw, now-detached `Duplex` connection
1912
1953
  * @param head - The first packet of the upgraded stream, if any
@@ -187,7 +187,7 @@ export declare function collectRequestBody(request: Request, limit: number): Pro
187
187
  * const handle = compose([withHeader], async () => new Response('ok'))
188
188
  * ```
189
189
  */
190
- export declare function compose<TState>(middleware: readonly MiddlewareHandler<TState>[], terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
190
+ export declare function compose<TState>(middleware: ReadonlyArray<MiddlewareHandler<TState>>, terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
191
191
 
192
192
  /**
193
193
  * The set of bare `Content-Type`s `isCompressibleType` treats as
@@ -1481,9 +1481,10 @@ export declare function serializeEvent(message: SSEMessage): string;
1481
1481
  * `idle → starting → listening`. A cancelled or expired bind closes its
1482
1482
  * partial server and resets to `idle` for another start. `stop()` transitions
1483
1483
  * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1484
- * so in-flight handlers observe cancellation, drains up to the `drain`
1485
- * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1486
- * is the idempotent final teardown.
1484
+ * so in-flight handlers observe cancellation, drains in-flight requests AND
1485
+ * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1486
+ * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1487
+ * still open. `destroy()` is the idempotent final teardown.
1487
1488
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1488
1489
  * `close`); a `Request` is built via the router's `buildRequest`, its
1489
1490
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1508,6 +1509,9 @@ export declare function serializeEvent(message: SSEMessage): string;
1508
1509
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1509
1510
  * throwing handler is treated as declined and surfaced on `error`, an
1510
1511
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1512
+ * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1513
+ * owns it, and the tracking exists because node detaches an upgraded socket
1514
+ * from the set its own close calls walk, so nothing else can end it.
1511
1515
  * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
1512
1516
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1513
1517
  * routes it to the `error` OPTION (not the domain `error` event).
@@ -1521,7 +1525,7 @@ export declare class Server<TState> implements ServerInterface<TState> {
1521
1525
  get dispatcher(): DispatcherInterface<TState>;
1522
1526
  get emitter(): EmitterInterface<ServerEventMap>;
1523
1527
  use(middleware: MiddlewareHandler<TState>): void;
1524
- use(middleware: readonly MiddlewareHandler<TState>[]): void;
1528
+ use(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void;
1525
1529
  upgrade(handler: UpgradeHandler): void;
1526
1530
  start(signal?: AbortSignal): Promise<number>;
1527
1531
  stop(): Promise<void>;
@@ -1544,9 +1548,13 @@ export declare class Server<TState> implements ServerInterface<TState> {
1544
1548
  * the per-request path; `undefined` for an upgrade-handler throw (no fetch
1545
1549
  * `Request` exists on that path — only a raw `IncomingMessage`) or a listen
1546
1550
  * failure.
1547
- * - `stop` — `stop()` began (status just moved to `'stopping'`).
1551
+ * - `stop` — `stop()` began (status just moved to `'stopping'`). An upgrade
1552
+ * handler that owns a long-lived socket closes it from here, so the drain
1553
+ * below settles instead of running out the deadline.
1548
1554
  * - `drain` — the graceful drain settled (deadline hit or all finished);
1549
- * carries the still-pending request count (`0` on a clean drain).
1555
+ * carries the still-pending request count AND the still-attached upgraded
1556
+ * socket count. Both `0` is a clean drain; either non-zero means the close
1557
+ * that follows was FORCED and cut that work.
1550
1558
  * - `response` — fired after the response has been sent, for every request
1551
1559
  * that reaches the middleware pipeline (the success path and the
1552
1560
  * outer-boundary error path); carries the method, parsed pathname, final
@@ -1564,7 +1572,7 @@ export declare type ServerEventMap = {
1564
1572
  url: URL;
1565
1573
  }];
1566
1574
  readonly stop: readonly [];
1567
- readonly drain: readonly [pending: number];
1575
+ readonly drain: readonly [pending: number, upgraded: number];
1568
1576
  readonly response: readonly [
1569
1577
  event: {
1570
1578
  method: string;
@@ -1590,7 +1598,8 @@ export declare type ServerEventMap = {
1590
1598
  * while binding, and resolves the actually-bound port. A cancelled or expired
1591
1599
  * bind closes its partial server and resets to `idle`. `stop()` refuses new
1592
1600
  * connections, fires the stop signal so in-flight handlers can observe it,
1593
- * drains up to the configured deadline, then closes. `destroy()` is the final
1601
+ * drains in-flight requests and claimed upgraded sockets up to the configured
1602
+ * deadline, then closes — forcing whatever is left. `destroy()` is the final
1594
1603
  * idempotent teardown. Per request: a `Request` is built via the router's
1595
1604
  * `buildRequest` (its signal linked to the server's stop signal), the composed
1596
1605
  * middleware onion runs terminating in `dispatcher.handle`, and the result is
@@ -1605,7 +1614,7 @@ export declare interface ServerInterface<TState> {
1605
1614
  readonly dispatcher: DispatcherInterface<TState>;
1606
1615
  readonly emitter: EmitterInterface<ServerEventMap>;
1607
1616
  use(middleware: MiddlewareHandler<TState>): void;
1608
- use(middleware: readonly MiddlewareHandler<TState>[]): void;
1617
+ use(middleware: ReadonlyArray<MiddlewareHandler<TState>>): void;
1609
1618
  upgrade(handler: UpgradeHandler): void;
1610
1619
  /**
1611
1620
  * Bind the configured listener and resolve its actually-bound port.
@@ -1615,7 +1624,26 @@ export declare interface ServerInterface<TState> {
1615
1624
  * @returns The actually-bound TCP port
1616
1625
  */
1617
1626
  start(signal?: AbortSignal): Promise<number>;
1627
+ /**
1628
+ * Stop gracefully: refuse new connections, fire the stop signal, drain, close.
1629
+ *
1630
+ * @remarks
1631
+ * Drainable work is every in-flight request PLUS every upgraded socket a
1632
+ * handler claimed. The drain parks on that work reaching zero or the
1633
+ * `drain` deadline expiring, emits `drain` with both remaining counts, and
1634
+ * then closes — dropping idle keep-alive sockets on a clean drain, and
1635
+ * destroying every open socket (including the claimed upgraded ones node's
1636
+ * own force-close cannot reach) when either count is still non-zero. It
1637
+ * therefore always resolves; the `drain` counts say whether anything was cut.
1638
+ *
1639
+ * @returns Resolves once the listener is closed and the status is `'stopped'`
1640
+ */
1618
1641
  stop(): Promise<void>;
1642
+ /**
1643
+ * Tear down for good: force-close the listener and every socket, then the emitter.
1644
+ *
1645
+ * @returns Resolves once nothing is left open; idempotent from any state
1646
+ */
1619
1647
  destroy(): Promise<void>;
1620
1648
  }
1621
1649
 
@@ -1639,9 +1667,12 @@ export declare interface ServerInterface<TState> {
1639
1667
  * `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
1640
1668
  * guaranteed-free port up front).
1641
1669
  * @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
1642
- * server stops accepting new connections and gives in-flight requests this
1643
- * long to finish before forcing sockets closed. Defaults to
1644
- * `DEFAULT_DRAIN_MS`. Must be a non-negative finite number.
1670
+ * server stops accepting new connections and gives in-flight requests AND
1671
+ * claimed upgraded sockets this long to finish before forcing every
1672
+ * remaining socket closed. Defaults to `DEFAULT_DRAIN_MS`. Must be a
1673
+ * non-negative finite number. A long-lived upgraded socket that nothing
1674
+ * closes therefore costs `stop()` this whole budget, so a WebSocket
1675
+ * handler closes its sockets on the `stop` event to settle sooner.
1645
1676
  * @param limit - The default request-body byte cap the context's `body()`
1646
1677
  * reads through. Defaults to `DEFAULT_BODY_LIMIT`. Must be a non-negative
1647
1678
  * finite number.
@@ -1675,7 +1706,7 @@ export declare interface ServerInterface<TState> {
1675
1706
  export declare interface ServerOptions<TState> {
1676
1707
  readonly dispatcher: DispatcherInterface<TState>;
1677
1708
  readonly state: ConnectionStateFunction<TState>;
1678
- readonly middleware?: readonly MiddlewareHandler<TState>[];
1709
+ readonly middleware?: ReadonlyArray<MiddlewareHandler<TState>>;
1679
1710
  readonly host?: string;
1680
1711
  readonly port?: number;
1681
1712
  readonly drain?: number;
@@ -1907,6 +1938,16 @@ export declare function unwrapETag(tag: string): string;
1907
1938
  * connection. `request` / `socket` / `head` are node's own raw values, handed
1908
1939
  * over verbatim — no assertion at this boundary (AGENTS §14).
1909
1940
  *
1941
+ * A CLAIMED socket is TRACKED until it closes. The handler still owns it —
1942
+ * the server only watches — but `stop()` now drains that socket like an
1943
+ * in-flight request and destroys it if the `drain` deadline expires first.
1944
+ * Node detaches an upgraded socket from its own connection set, so neither
1945
+ * `closeIdleConnections()` nor `closeAllConnections()` reaches it and this
1946
+ * tracking is what lets `stop()` and `destroy()` finish at all. A handler
1947
+ * that wants a protocol-clean goodbye (a WebSocket close frame) sends it on
1948
+ * the server's `stop` event and closes the socket; the drain settles the
1949
+ * moment the last one goes.
1950
+ *
1910
1951
  * @param request - The raw `node:http` upgrade request
1911
1952
  * @param socket - The raw, now-detached `Duplex` connection
1912
1953
  * @param head - The first packet of the upgraded stream, if any
@@ -1786,9 +1786,10 @@ var Negotiator = class {
1786
1786
  * `idle → starting → listening`. A cancelled or expired bind closes its
1787
1787
  * partial server and resets to `idle` for another start. `stop()` transitions
1788
1788
  * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1789
- * so in-flight handlers observe cancellation, drains up to the `drain`
1790
- * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1791
- * is the idempotent final teardown.
1789
+ * so in-flight handlers observe cancellation, drains in-flight requests AND
1790
+ * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1791
+ * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1792
+ * still open. `destroy()` is the idempotent final teardown.
1792
1793
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1793
1794
  * `close`); a `Request` is built via the router's `buildRequest`, its
1794
1795
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1813,6 +1814,9 @@ var Negotiator = class {
1813
1814
  * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
1814
1815
  * throwing handler is treated as declined and surfaced on `error`, an
1815
1816
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1817
+ * A CLAIMED socket joins `#upgraded` until it closes: the claimant still
1818
+ * owns it, and the tracking exists because node detaches an upgraded socket
1819
+ * from the set its own close calls walk, so nothing else can end it.
1816
1820
  * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
1817
1821
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
1818
1822
  * routes it to the `error` OPTION (not the domain `error` event).
@@ -1823,6 +1827,7 @@ var Server = class {
1823
1827
  #state;
1824
1828
  #middleware;
1825
1829
  #upgradeHandlers = [];
1830
+ #upgraded = /* @__PURE__ */ new Set();
1826
1831
  #emitter;
1827
1832
  #host;
1828
1833
  #configuredPort;
@@ -1866,6 +1871,9 @@ var Server = class {
1866
1871
  ...options.error === void 0 ? {} : { error: options.error }
1867
1872
  });
1868
1873
  }
1874
+ get #inflight() {
1875
+ return this.#pending + this.#upgraded.size;
1876
+ }
1869
1877
  get status() {
1870
1878
  return this.#status;
1871
1879
  }
@@ -1911,8 +1919,9 @@ var Server = class {
1911
1919
  await this.#drainPending(deadline.signal);
1912
1920
  deadline.clear();
1913
1921
  const pending = this.#pending;
1914
- this.#emitter.emit("drain", pending);
1915
- if (server !== void 0) await this.#close(server, pending > 0);
1922
+ const upgraded = this.#upgraded.size;
1923
+ this.#emitter.emit("drain", pending, upgraded);
1924
+ if (server !== void 0) await this.#close(server, pending + upgraded > 0);
1916
1925
  this.#http = void 0;
1917
1926
  this.#port = void 0;
1918
1927
  this.#status = "stopped";
@@ -2015,7 +2024,8 @@ var Server = class {
2015
2024
  } catch (error) {
2016
2025
  this.#emitter.emit("error", error);
2017
2026
  }
2018
- if (!handled) socket.destroy();
2027
+ if (handled) this.#trackSocket(socket);
2028
+ else socket.destroy();
2019
2029
  this.#emitter.emit("upgrade", request, handled);
2020
2030
  }
2021
2031
  #resolvePort(server) {
@@ -2075,23 +2085,40 @@ var Server = class {
2075
2085
  #close(server, force) {
2076
2086
  return new Promise((resolve) => {
2077
2087
  server.close(() => resolve());
2078
- if (force) server.closeAllConnections();
2079
- else server.closeIdleConnections();
2088
+ if (force) {
2089
+ server.closeAllConnections();
2090
+ for (const socket of this.#upgraded) socket.destroy();
2091
+ } else server.closeIdleConnections();
2080
2092
  });
2081
2093
  }
2094
+ #enter() {
2095
+ if (this.#inflight === 0) this.#wakeup = createAbort();
2096
+ }
2097
+ #settle() {
2098
+ if (this.#inflight === 0) this.#wakeup.abort();
2099
+ }
2082
2100
  #trackStart() {
2083
- if (this.#pending === 0) this.#wakeup = createAbort();
2101
+ this.#enter();
2084
2102
  this.#pending += 1;
2085
2103
  let finished = false;
2086
2104
  return () => {
2087
2105
  if (finished) return;
2088
2106
  finished = true;
2089
2107
  this.#pending -= 1;
2090
- if (this.#pending === 0) this.#wakeup.abort();
2108
+ this.#settle();
2091
2109
  };
2092
2110
  }
2111
+ #trackSocket(socket) {
2112
+ if (socket.destroyed || this.#upgraded.has(socket)) return;
2113
+ this.#enter();
2114
+ this.#upgraded.add(socket);
2115
+ socket.once("close", () => {
2116
+ this.#upgraded.delete(socket);
2117
+ this.#settle();
2118
+ });
2119
+ }
2093
2120
  async #drainPending(signal) {
2094
- if (this.#pending === 0 || signal.aborted) return;
2121
+ if (this.#inflight === 0 || signal.aborted) return;
2095
2122
  await once(AbortSignal.any([signal, this.#wakeup.signal]), "abort");
2096
2123
  }
2097
2124
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orkestrel/server",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "A typed HTTP server for the @orkestrel line — composes the @orkestrel/router dispatcher behind a managed lifecycle. Part of the @orkestrel line.",
5
5
  "keywords": [
6
6
  "fetch",
@@ -53,10 +53,11 @@
53
53
  "format": "oxfmt --config .oxfmtrc.json --write .",
54
54
  "format:check": "oxfmt --config .oxfmtrc.json --check .",
55
55
  "lint:check": "oxlint --config .oxlintrc.json --deny-warnings .",
56
- "test": "npm run test:src && npm run test:policy && npm run test:guides",
56
+ "test": "npm run test:src && npm run test:policy && npm run test:config && npm run test:guides",
57
57
  "test:src": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:server",
58
58
  "test:src:server": "vitest run --config vite.config.ts --no-cache --reporter=dot --project src:server",
59
59
  "test:policy": "vitest run --config vite.config.ts --no-cache --reporter=dot --project policy",
60
+ "test:config": "vitest run --config vite.config.ts --no-cache --reporter=dot --project config",
60
61
  "test:guides": "vitest run --config vite.config.ts --reporter=dot --project guides",
61
62
  "build": "npm run clean && npm run build:src",
62
63
  "build:src": "npm run build:src:server",
@@ -64,16 +65,17 @@
64
65
  "prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run build && npm test"
65
66
  },
66
67
  "dependencies": {
67
- "@orkestrel/abort": "^0.0.6",
68
- "@orkestrel/contract": "^0.0.11",
69
- "@orkestrel/emitter": "^0.0.6",
70
- "@orkestrel/router": "^0.0.9",
71
- "@orkestrel/timeout": "^0.0.6"
68
+ "@orkestrel/abort": "^0.0.7",
69
+ "@orkestrel/contract": "^0.0.12",
70
+ "@orkestrel/emitter": "^0.0.7",
71
+ "@orkestrel/router": "^0.0.10",
72
+ "@orkestrel/timeout": "^0.0.7"
72
73
  },
73
74
  "devDependencies": {
74
75
  "@microsoft/api-extractor": "^7.58.12",
75
- "@orkestrel/guide": "^0.0.9",
76
- "@orkestrel/scaffold": "^0.0.26",
76
+ "@orkestrel/guide": "^0.0.11",
77
+ "@orkestrel/scaffold": "^0.0.38",
78
+ "@orkestrel/test": "^0.0.6",
77
79
  "@types/node": "^26.1.2",
78
80
  "@vitest/browser-playwright": "^4.1.10",
79
81
  "oxfmt": "^0.62.0",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["#dispatcher","#state","#middleware","#upgradeHandlers","#emitter","#host","#configuredPort","#drain","#limit","#expose","#report","#timeouts","#sockets","#status","#port","#abort","#handle","#onUpgrade","#http","#listen","#drainPending","#pending","#close","#trackStart","#accept","#respond","#boundary","#createBody","#resolvePort","#wakeup"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/helpers.ts","../../../src/server/Negotiator.ts","../../../src/server/Server.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { Encoding } from './types.js'\n\n// The substrate's tunable defaults (AGENTS §5 constants file) — only the\n// constants with a real consumer inside THIS package (AGENTS §21: build\n// against a concrete consumer, not speculatively). Frozen so a consumer can\n// read but never mutate the shared default. Middleware-package-only defaults\n// (rate limiting, CSRF, sessions, static serving, multipart — Appendix A of\n// the proposal) stay OUT of this file; they belong to that package's own\n// `constants.ts`.\n\n/** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */\nexport const DEFAULT_DRAIN_MS = 10_000\n\n/**\n * The `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes\n * an instance thrown by ANOTHER copy of this package (the dual-package\n * hazard — a version-skewed or workspace-linked duplicate install), where\n * `instanceof` alone fails because the two copies' `HTTPError` constructors\n * are distinct objects.\n *\n * @remarks\n * `Symbol.for` interns the symbol on the GLOBAL symbol registry, so every\n * copy of this package that evaluates this key resolves the SAME symbol\n * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,\n * unequal symbol per copy and defeat the whole point of a cross-copy brand.\n */\nexport const HTTP_ERROR_BRAND = Symbol.for('@orkestrel/server.HTTPError')\n\n/** Default maximum request body size (bytes) `readBody` accepts before a 413. */\nexport const DEFAULT_BODY_LIMIT = 1_048_576\n\n/**\n * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap\n * the body pipeline's byte-counting `TransformStream` enforces when\n * transparently decompressing a `Content-Encoding` request body.\n *\n * @remarks\n * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)\n * can inflate by many orders of magnitude — a classic decompression bomb.\n * Capping the decompressed byte count makes the pipe ABORT the moment the\n * output would exceed this, BEFORE the full bomb is materialized, so the\n * inflation can never exhaust memory. Defaults to `16 MiB` — a generous\n * ceiling for a legitimate compressed JSON / form body, far below an OOM. A\n * consumer raises it via {@link import('./types.js').BodyOptions}\n * `decompression` for a workload that genuinely ships larger decompressed\n * bodies.\n */\nexport const DEFAULT_DECOMPRESSED_LIMIT = 16_777_216\n\n/**\n * The SSE response headers the `openStream` seam always sets.\n *\n * @remarks\n * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`\n * keeps a proxy from caching the stream; `keep-alive` holds the connection\n * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so\n * events flush promptly rather than batching. Frozen so a consumer can read\n * but never mutate the shared default; `openStream` merges any\n * {@link import('./types.js').StreamOptions.headers} UNDER these.\n */\nexport const SSE_HEADERS: Readonly<Record<string, string>> = Object.freeze({\n\t'Content-Type': 'text/event-stream; charset=utf-8',\n\t'Cache-Control': 'no-cache',\n\tConnection: 'keep-alive',\n\t'X-Accel-Buffering': 'no',\n})\n\n/**\n * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`\n * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized\n * / control-char-bearing incoming id is REJECTED (a fresh id is minted\n * instead) rather than ever riding into a response header or `context.state`\n * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const REQUEST_ID_PATTERN: Readonly<RegExp> = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/)\n\n/**\n * The set of bare `Content-Type`s `isCompressibleType` treats as\n * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /\n * `+xml`) rules that helper also applies.\n *\n * @remarks\n * The text-shaped application types worth compressing (JSON / JavaScript /\n * XML / SVG / WASM / a few document formats) — NOT already-compressed\n * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's\n * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads\n * but never mutates the shared default.\n */\nexport const COMPRESSIBLE_TYPES: ReadonlySet<string> = new Set([\n\t'application/json',\n\t'application/javascript',\n\t'application/xml',\n\t'application/xhtml+xml',\n\t'application/rss+xml',\n\t'application/atom+xml',\n\t'application/ld+json',\n\t'application/manifest+json',\n\t'application/vnd.api+json',\n\t'application/wasm',\n\t'image/svg+xml',\n\t'application/pdf',\n])\n\n/**\n * The default {@link Encoding} content-codings the substrate offers, in\n * PREFERENCE order — `gzip` / `deflate`.\n *\n * @remarks\n * `identity` (no compression) is always implicitly acceptable and is NOT\n * listed here — it is the fall-through when a client accepts none of these.\n * Brotli is omitted per the core's `CompressionStream`-only decision (see\n * {@link Encoding}). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const DEFAULT_ENCODINGS: readonly Encoding[] = Object.freeze(['gzip', 'deflate'])\n","// AGENTS §12: a handler signals a client-facing fault by throwing an\n// `HTTPError` carrying the HTTP `status` to send; the server's error boundary\n// (§5.3 of the proposal) turns it into a response of that status. Any OTHER\n// throw is a programmer/runtime error → a 500 (its message hidden unless\n// `expose`). The machine-readable field here is the numeric `status` (plus an\n// optional `context` bag) — `MultipartError` is NOT ported here: it moves to\n// the future `@orkestrel/middleware` package with its owner (`createMultipart`).\n//\n// Dual-package hazard: `instanceof HTTPError` fails when the thrown value was\n// constructed by a DIFFERENT copy of this package (version skew, a linked\n// workspace) — the two copies' `HTTPError` constructors are distinct objects\n// even though they are structurally identical. `isHTTPError` therefore tries\n// `instanceof` first (the common, cheap case) and falls back to a total\n// structural check keyed by a `Symbol.for`-interned brand (`HTTP_ERROR_BRAND`,\n// shared across every copy via the global symbol registry) plus the exact\n// fields the server's boundary reads off a recognized error (`status`,\n// `message`) — so a foreign-copy instance the guard accepts can never crash\n// the boundary that trusts it.\n\nimport { isNumber, isString } from '@orkestrel/contract'\nimport { HTTP_ERROR_BRAND } from './constants.js'\n\n/**\n * An error a handler (or middleware) throws to produce an HTTP response of a\n * specific status.\n *\n * @remarks\n * Carries the HTTP `status` to send and an optional `context` record (the\n * offending field / value). The server's built-in error boundary catches it\n * and renders a response of `status` with the error's `message` as the body\n * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's\n * deliberate signal), unlike a generic throw whose message is hidden unless\n * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for\n * specific statuses, or throw it directly. Narrow a caught value with\n * {@link isHTTPError}.\n *\n * @example\n * ```ts\n * import { HTTPError } from '@src/server'\n *\n * const handler = async (request: Request): Promise<Response> => {\n * \tconst user = await find(new URL(request.url).searchParams.get('id'))\n * \tif (user === undefined) throw new HTTPError(404, 'user not found')\n * \treturn Response.json(user)\n * }\n * ```\n */\nexport class HTTPError extends Error {\n\treadonly status: number\n\treadonly context?: Readonly<Record<string, unknown>>\n\t// The cross-copy brand (AGENTS §12 / dual-package hazard) — `isHTTPError`\n\t// reads it structurally when `instanceof` fails across package copies.\n\t// Not a public field to set by hand: the constructor is the only writer.\n\treadonly [HTTP_ERROR_BRAND] = true\n\n\tconstructor(status: number, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tthis.name = 'HTTPError'\n\t\tthis.status = status\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * The {@link HTTPError} thrown when a request body exceeds the body\n * pipeline's size limit — a `413 Content Too Large`.\n *\n * @remarks\n * Thrown by `readBody` (and the middleware context's cached `body()`) when\n * the received bytes exceed the configured {@link\n * import('./types.js').BodyOptions.limit}, carrying the `limit` in its\n * `context`. The server's error boundary renders it as a 413.\n *\n * @example\n * ```ts\n * import { ContentTooLargeError, isHTTPError } from '@src/server'\n *\n * try {\n * \tawait readBody(request, { limit: 1024 })\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status) // 413\n * }\n * ```\n */\nexport class ContentTooLargeError extends HTTPError {\n\tconstructor(limit: number) {\n\t\tsuper(413, `request body exceeds the ${limit}-byte limit`, { limit })\n\t\tthis.name = 'ContentTooLargeError'\n\t}\n}\n\n/**\n * Narrow an unknown caught value to an {@link HTTPError} (including its\n * subclasses, e.g. {@link ContentTooLargeError}).\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link HTTPError}\n *\n * @remarks\n * Tries `instanceof` first, then falls back to a total structural check for\n * an instance built by a DIFFERENT copy of this package (the dual-package\n * hazard — version skew, a linked workspace duplicate) whose `HTTPError`\n * constructor is a distinct object from this copy's: the value must carry\n * the cross-copy brand (interned via `Symbol.for`, so every copy resolves the\n * same key) AND expose the exact fields the server's error boundary reads off\n * a recognized `HTTPError` — a numeric `status` and a string `message`. A\n * plain object that merely carries a `status` WITHOUT the brand is rejected.\n *\n * @example\n * ```ts\n * import { isHTTPError } from '@src/server'\n *\n * try {\n * \tawait handle(request)\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status, error.message)\n * }\n * ```\n */\nexport function isHTTPError(value: unknown): value is HTTPError {\n\tif (value instanceof HTTPError) return true\n\tif (typeof value !== 'object' || value === null) return false\n\tif (!(HTTP_ERROR_BRAND in value) || value[HTTP_ERROR_BRAND] !== true) return false\n\tif (!('status' in value) || !('message' in value)) return false\n\treturn isNumber(value.status) && isString(value.message)\n}\n","import type { AddressInfo } from 'node:net'\nimport type {\n\tAcceptEntry,\n\tBodyOptions,\n\tCookieOptions,\n\tEncoding,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tRangeSpec,\n\tSSEMessage,\n\tStreamInterface,\n\tStreamOptions,\n\tTokenOptions,\n\tTokenSecret,\n} from './types.js'\nimport { once } from 'node:events'\nimport { createServer as createNetServer } from 'node:net'\nimport { isNumber, isRecord, isString, parseJSON } from '@orkestrel/contract'\nimport {\n\tCOMPRESSIBLE_TYPES,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DECOMPRESSED_LIMIT,\n\tREQUEST_ID_PATTERN,\n\tSSE_HEADERS,\n} from './constants.js'\nimport { ContentTooLargeError, HTTPError } from './errors.js'\n\n// The middleware seam's composition engine (AGENTS §5 — a pure function, not a\n// class: `compose` has no instance state, so it lives here rather than as an\n// entity). The RETURNING onion (§5.1 of the proposal): each middleware may\n// transform the request (`next(newRequest)`), transform the response (`await\n// next()` then mutate the result), or short-circuit (return without calling\n// `next`) — no mutable framework object anywhere. The double-`next` guard\n// (calling `next` twice within one middleware invocation) rejects, preserving\n// the old spine's crown-jewel invariant that each link runs the chain at most\n// once.\n\n/**\n * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`\n * handler into one request handler — the frozen middleware seam (§5.1).\n *\n * @remarks\n * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`\n * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes\n * `terminal`. Each middleware's `next` may be called with a substituted\n * `Request` (the downstream chain then sees that request instead of the\n * original), called with no argument (the original request continues\n * downstream), or NOT called at all (a short-circuit — the middleware's own\n * returned `Response` is sent, and everything downstream never runs). A\n * SECOND call to the same `next` within one middleware invocation REJECTS —\n * each link runs the chain at most once, so a middleware cannot fork the\n * request into two divergent downstream runs.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param middleware - The ordered chain, outermost first\n * @param terminal - The innermost handler the chain ultimately reaches\n * @returns A single `(request, context) => Promise<Response>` handler running the whole onion\n *\n * @example\n * ```ts\n * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {\n * \tconst response = await next()\n * \tresponse.headers.set('X-Powered-By', 'orkestrel')\n * \treturn response\n * }\n *\n * const handle = compose([withHeader], async () => new Response('ok'))\n * ```\n */\nexport function compose<TState>(\n\tmiddleware: readonly MiddlewareHandler<TState>[],\n\tterminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\treturn middleware.reduceRight<\n\t\t(request: Request, context: MiddlewareContext<TState>) => Promise<Response>\n\t>((next, layer) => wrapMiddleware(layer, next), terminal)\n}\n\n/**\n * Wrap one middleware layer around its downstream handler.\n *\n * @remarks\n * The returned handler enforces the one-call `next` invariant while preserving\n * request substitution and the middleware's synchronous or asynchronous result.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param layer - The middleware layer to invoke\n * @param next - The downstream handler wrapped by `layer`\n * @returns A handler with `layer` composed around `next`\n *\n * @example\n * ```ts\n * const handle = wrapMiddleware(\n * \tasync (_request, _context, next) => next(),\n * \tasync () => new Response('ok'),\n * )\n * ```\n */\nexport function wrapMiddleware<TState>(\n\tlayer: MiddlewareHandler<TState>,\n\tnext: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\treturn async (request: Request, context: MiddlewareContext<TState>): Promise<Response> => {\n\t\tlet called = false\n\t\treturn Promise.resolve(\n\t\t\tlayer(request, context, (nextRequest?: Request): Promise<Response> => {\n\t\t\t\tif (called) return Promise.reject(new Error('next() was already called by this middleware'))\n\t\t\t\tcalled = true\n\t\t\t\treturn next(nextRequest ?? request, context)\n\t\t\t}),\n\t\t)\n\t}\n}\n\n// The cookie machinery (AGENTS §4.3 module-scope helpers) — `parseCookies`\n// decodes a raw `Cookie:` header into a name→value lookup; `serializeCookie`\n// builds a spec-shaped `Set-Cookie` value with its attributes. The SIGNED\n// pair reuses the shipped HMAC token primitives rather than a second HMAC\n// scheme: `writeSignedCookie` is `serializeCookie(name, await signToken(value,\n// { secret }))` appended to a `Headers`, and `readSignedCookie` is `await\n// verifyToken(parseCookies(...)[name], secret)` — so a cookie is just a\n// `signToken` value in a `Set-Cookie`, with the SAME secret rotation + tamper\n// rejection. Every reader narrows untrusted request input with `typeof`,\n// never `as` (§14), and total on hostile input.\n\n/**\n * Parse a raw `Cookie:` request header into a `name → value` lookup.\n *\n * @remarks\n * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine\n * cookie-pair separator never precedes it), while every later segment has its\n * inter-pair separator (ASCII space/tab) stripped before parsing — so a\n * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by\n * {@link isCookieName} rather than silently reconciling into a\n * prefix-protected `__Host-` name. A pair without `=`, or with an invalid\n * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/\n * malformed header yields an empty record, never throws (AGENTS §14).\n *\n * @param header - The raw `Cookie` header value (possibly `undefined`)\n * @returns A record of every parsed cookie, `name → decoded value`\n *\n * @example\n * ```ts\n * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }\n * ```\n */\nexport function parseCookies(header: string | undefined): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tif (header === undefined) return out\n\tconst segments = header.split(';')\n\tfor (let index = 0; index < segments.length; index += 1) {\n\t\tconst raw = segments[index] ?? ''\n\t\tconst segment = index === 0 ? raw : raw.replace(/^[ \\t]+/, '')\n\t\tconst eq = segment.indexOf('=')\n\t\tif (eq < 0) continue\n\t\tconst name = segment.slice(0, eq)\n\t\tif (!isCookieName(name)) continue\n\t\tout[name] = decodeCookieValue(segment.slice(eq + 1).trim())\n\t}\n\treturn out\n}\n\n/**\n * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of\n * cookie-token chars with NO surrounding (or interior) whitespace.\n *\n * @remarks\n * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$` —\n * which excludes every whitespace char (ASCII and Unicode) plus controls,\n * separators, and `=`. The {@link parseCookies} hardening that stops a\n * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.\n *\n * @param value - The candidate cookie name\n * @returns `true` when `value` is a valid, whitespace-free cookie token\n *\n * @example\n * ```ts\n * isCookieName('__Host-session') // true\n * isCookieName(' __Host-session') // false — whitespace-padded\n * ```\n */\nexport function isCookieName(value: string): boolean {\n\treturn /^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$/.test(value)\n}\n\n/**\n * Decode a cookie value with `decodeURIComponent`, falling back to the raw\n * text when the value is not valid percent-encoding.\n *\n * @param raw - The raw (trimmed) cookie value\n * @returns The URL-decoded value, or the raw value when decoding would throw\n *\n * @example\n * ```ts\n * decodeCookieValue('a%20b') // 'a b'\n * decodeCookieValue('%') // '%' — malformed escape stays literal\n * ```\n */\nexport function decodeCookieValue(raw: string): string {\n\ttry {\n\t\treturn decodeURIComponent(raw)\n\t} catch {\n\t\treturn raw\n\t}\n}\n\n/**\n * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE\n * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two\n * attributes with before emitting them.\n *\n * @remarks\n * Rejects a value carrying a `;` (splits attributes), a `,` (can split a\n * folded header), ASCII/Unicode whitespace, or a C0/DEL control char\n * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`\n * directive. Total — never throws (a bad value returns `false`).\n *\n * @param value - The candidate attribute value (a `Domain` or `Path`)\n * @returns `true` when `value` carries no separator / whitespace / control char\n *\n * @example\n * ```ts\n * isCookieAttribute('/app') // true\n * isCookieAttribute('/a\\r\\nSet-Cookie: x=y') // false\n * ```\n */\nexport function isCookieAttribute(value: string): boolean {\n\tfor (const char of value) {\n\t\tif (char === ';' || char === ',' || /\\s/.test(char)) return false\n\t\tconst code = char.codePointAt(0)\n\t\tif (code !== undefined && (code < 0x20 || code === 0x7f)) return false\n\t}\n\treturn true\n}\n\n/**\n * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.\n *\n * @remarks\n * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and\n * appends the present {@link CookieOptions} attributes in canonical order:\n * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`\n * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated\n * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an\n * injection attempt (a programmer misconfiguration, AGENTS §12 — never a\n * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of\n * the `secure` option (the spec requires it); an un-resolved `undefined`\n * `secure` here falls to OFF — request-aware callers resolve it first via\n * {@link resolveSecure}.\n *\n * @param name - The cookie name\n * @param value - The cookie value (URL-encoded into the output)\n * @param options - The {@link CookieOptions} attributes; see its fields for defaults\n * @returns The `Set-Cookie` header value\n * @throws {HTTPError} When `domain` or `path` carries an injection char\n *\n * @example\n * ```ts\n * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'\n * ```\n */\nexport function serializeCookie(name: string, value: string, options?: CookieOptions): string {\n\tconst sameSite = options?.sameSite ?? 'Lax'\n\tconst domain = options?.domain\n\tif (domain !== undefined && !isCookieAttribute(domain))\n\t\tthrow new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`)\n\tconst path = options?.path ?? '/'\n\tif (!isCookieAttribute(path))\n\t\tthrow new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`)\n\tconst secure = sameSite === 'None' || options?.secure === true\n\tconst parts = [`${name}=${encodeURIComponent(value)}`]\n\tif (domain !== undefined) parts.push(`Domain=${domain}`)\n\tparts.push(`Path=${path}`)\n\tif (options?.maxAge !== undefined) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`)\n\tif (options?.httpOnly !== false) parts.push('HttpOnly')\n\tif (secure) parts.push('Secure')\n\tparts.push(`SameSite=${sameSite}`)\n\treturn parts.join('; ')\n}\n\n/**\n * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}\n * `secure` setting and whether the request arrived over TLS.\n *\n * @remarks\n * `true` / `false` are explicit overrides. `undefined` (the secure default —\n * the option omitted) resolves to `encrypted` — `Secure` on a TLS\n * connection, off over plaintext HTTP — so a production HTTPS deployment\n * gets `Secure` automatically while local-dev HTTP still works.\n *\n * @param secure - The {@link CookieOptions} `secure` setting\n * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})\n * @returns The concrete `Secure` flag to emit\n *\n * @example\n * ```ts\n * resolveSecure(undefined, true) // true\n * resolveSecure(undefined, false) // false\n * resolveSecure(false, true) // false — explicit override wins\n * ```\n */\nexport function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean {\n\tif (secure === true || secure === false) return secure\n\treturn encrypted\n}\n\n/**\n * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT\n * clobbering a prior one.\n *\n * @remarks\n * `Headers.append` already accumulates repeated headers (unlike node's\n * `setHeader`), so this is a thin, self-documenting wrapper naming the\n * cookie-append intent — the primitive {@link writeSignedCookie} /\n * {@link clearCookie} use.\n *\n * @param headers - The response `Headers` to write into\n * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * appendCookie(headers, serializeCookie('a', '1'))\n * appendCookie(headers, serializeCookie('b', '2'))\n * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'\n * ```\n */\nexport function appendCookie(headers: Headers, cookie: string): void {\n\theaders.append('set-cookie', cookie)\n}\n\n/**\n * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append\n * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).\n *\n * @remarks\n * The cookie value is `await signToken(value, { secret })`\n * (`<payload>.<signature>`), so a signed cookie is a stateless token in a\n * cookie — the same secret rotation and tamper rejection, no second HMAC\n * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto\n * signing is asynchronous (§3 of the proposal).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name\n * @param value - The opaque value to sign into the cookie\n * @param secret - The {@link TokenSecret} to sign with (the first secret signs)\n * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * await writeSignedCookie(headers, 'session', 'user-1', 'secret')\n * ```\n */\nexport async function writeSignedCookie(\n\theaders: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: TokenSecret,\n\toptions?: CookieOptions,\n): Promise<void> {\n\tappendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options))\n}\n\n/**\n * Read + verify a SIGNED cookie off a request — TOTAL, returning the\n * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).\n *\n * @remarks\n * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,\n * and verifies it with {@link verifyToken} against `secret` (a rotation list\n * accepts a cookie signed by any of its secrets). ANY failure — an absent\n * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.\n *\n * @param request - The `Request` to read the `Cookie` header from\n * @param name - The cookie name to read\n * @param secret - The {@link TokenSecret} (or rotation list) to verify against\n * @returns The embedded value when the cookie is present + valid, else `undefined`\n *\n * @example\n * ```ts\n * const value = await readSignedCookie(request, 'session', 'secret')\n * ```\n */\nexport async function readSignedCookie(\n\trequest: Request,\n\tname: string,\n\tsecret: TokenSecret,\n): Promise<string | undefined> {\n\tconst cookie = parseCookies(request.headers.get('cookie') ?? undefined)[name]\n\treturn cookie === undefined ? undefined : verifyToken(cookie, secret)\n}\n\n/**\n * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).\n *\n * @remarks\n * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the\n * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops\n * a cookie when those MATCH the one it set).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name to clear\n * @param options - The {@link CookieOptions} that must match the original cookie\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * clearCookie(headers, 'session')\n * ```\n */\nexport function clearCookie(headers: Headers, name: string, options?: CookieOptions): void {\n\tappendCookie(headers, serializeCookie(name, '', { ...options, maxAge: 0 }))\n}\n\n// The stateless signed-token primitives over WebCrypto (AGENTS §4.3 module-\n// scope helpers, §3 of the proposal). A token is `<payload>.<signature>`: the\n// payload a base64url JSON `{ value, exp? }`, the signature an HMAC-SHA256 of\n// the payload under the secret. Signing always uses the FIRST secret (a\n// rotation list's current head); verifying accepts ANY secret in the list,\n// via `crypto.subtle.verify` — constant-time internally, so the old\n// `safeCompare` is RETIRED, never ported. `verifyToken` is TOTAL (never\n// throws — adversarial input returns `undefined`, AGENTS §14); only\n// `signToken` throws, and only on a misconfigured (empty) secret.\n\n/**\n * Base64url-encode a byte sequence — the payload encoding {@link signToken} /\n * {@link verifyToken} use, and the signature encoding for the HMAC.\n *\n * @param bytes - The bytes to encode\n * @returns The base64url string (no padding)\n *\n * @example\n * ```ts\n * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'\n * ```\n */\nexport function encodeBase64Url(bytes: Uint8Array): string {\n\tlet binary = ''\n\tfor (const byte of bytes) binary += String.fromCharCode(byte)\n\treturn btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Decode a base64url string back into its bytes — the inverse of\n * {@link encodeBase64Url}.\n *\n * @remarks\n * Restores the standard base64 alphabet + padding before decoding with\n * `atob`. THROWS `DOMException` on a malformed input — callers on the\n * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).\n *\n * @param value - The base64url string to decode\n * @returns The decoded bytes\n * @throws {DOMException} When `value` is not valid base64url\n *\n * @example\n * ```ts\n * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'\n * ```\n */\nexport function decodeBase64Url(value: string): Uint8Array<ArrayBuffer> {\n\tconst restored = value.replace(/-/g, '+').replace(/_/g, '/')\n\tconst padding = restored.length % 4 === 0 ? '' : '='.repeat(4 - (restored.length % 4))\n\tconst binary = atob(restored + padding)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)\n\treturn bytes\n}\n\n/**\n * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.\n *\n * @remarks\n * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the\n * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so\n * the expiry is HMAC-COVERED — a client cannot extend it without invalidating\n * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST\n * {@link TokenSecret} (the current secret, or the head of a rotation list).\n * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a\n * misconfigured secret with no usable entry THROWS an {@link HTTPError}\n * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with\n * {@link verifyToken}. Omitting `ttl` mints a token that never expires.\n *\n * @param value - The opaque value to embed (a session id, a deployment marker)\n * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}\n * @returns The signed `<payload>.<signature>` token string\n * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry\n *\n * @example\n * ```ts\n * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })\n * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined\n * ```\n */\nexport async function signToken(value: string, options: TokenOptions): Promise<string> {\n\tconst secrets = normalizeSecret(options.secret)\n\tconst secret = secrets[0]\n\tif (secret === undefined) throw new HTTPError(500, 'signToken requires at least one secret')\n\tconst exp = options.ttl !== undefined ? Date.now() + options.ttl : undefined\n\tconst encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({ value, exp })))\n\tconst key = await crypto.subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(secret),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign'],\n\t)\n\tconst signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(encoded))\n\treturn `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`\n}\n\n/**\n * Verify a stateless token and return its embedded value — TOTAL, never throws.\n *\n * @remarks\n * The inverse of {@link signToken}: splits the token on its LAST `.` (so a\n * value containing dots survives), and checks the payload's HMAC-SHA256\n * signature against EACH {@link TokenSecret} candidate via\n * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is\n * retired, §3 of the proposal), accepting the token on the first match (the\n * rotation path). It then decodes + narrows the payload (`isRecord` +\n * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,\n * rejects an expired token. ANY failure — a malformed token, a bad signature,\n * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —\n * yields `undefined` rather than throwing.\n *\n * @param token - The candidate token string (from a request header/cookie)\n * @param secret - The {@link TokenSecret} (or rotation list) to verify against\n * @returns The embedded value when the token is valid + unexpired, else `undefined`\n *\n * @example\n * ```ts\n * await verifyToken('bad.token', 'shh') // undefined — never throws\n * ```\n */\nexport async function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined> {\n\tconst secrets = normalizeSecret(secret)\n\tif (secrets.length === 0) return undefined\n\tconst dot = token.lastIndexOf('.')\n\tif (dot < 0) return undefined\n\tconst encoded = token.slice(0, dot)\n\tconst signatureText = token.slice(dot + 1)\n\ttry {\n\t\tconst signature = decodeBase64Url(signatureText)\n\t\tconst data = new TextEncoder().encode(encoded)\n\t\tfor (const candidate of secrets) {\n\t\t\tconst key = await crypto.subtle.importKey(\n\t\t\t\t'raw',\n\t\t\t\tnew TextEncoder().encode(candidate),\n\t\t\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\t\t\tfalse,\n\t\t\t\t['verify'],\n\t\t\t)\n\t\t\tconst matched = await crypto.subtle.verify('HMAC', key, signature, data)\n\t\t\tif (matched) return decodeTokenPayload(encoded)\n\t\t}\n\t\treturn undefined\n\t} catch {\n\t\t// A malformed base64url signature/payload is just an invalid token — stay total.\n\t\treturn undefined\n\t}\n}\n\n/**\n * Decode + narrow a signed token's base64url JSON payload, honoring its\n * expiry — the shared decode step {@link verifyToken} applies after a\n * signature match.\n *\n * @remarks\n * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a\n * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.\n * TOTAL — any decode/shape/expiry failure yields `undefined`.\n *\n * @param encoded - The base64url-encoded payload segment (before the last `.`)\n * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`\n */\nexport function decodeTokenPayload(encoded: string): string | undefined {\n\ttry {\n\t\tconst text = new TextDecoder().decode(decodeBase64Url(encoded))\n\t\tconst payload: unknown = JSON.parse(text)\n\t\tif (!isRecord(payload)) return undefined\n\t\tif (typeof payload.value !== 'string') return undefined\n\t\tif (payload.exp !== undefined && typeof payload.exp !== 'number') return undefined\n\t\tif (payload.exp !== undefined && Date.now() >= payload.exp) return undefined\n\t\treturn payload.value\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —\n * backs both {@link signToken} and {@link verifyToken}.\n *\n * @remarks\n * A single string becomes a one-element list; a rotation list is copied. Any\n * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that\n * emptiness test; each kept secret is stored VERBATIM). The first kept\n * element is the signing secret; all kept are accepted on verify.\n *\n * @param secret - The {@link TokenSecret} (a single string, or a rotation list)\n * @returns The kept (non-blank) secrets, in order — empty when none is usable\n *\n * @example\n * ```ts\n * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']\n * ```\n */\nexport function normalizeSecret(secret: TokenSecret): readonly string[] {\n\tconst list = typeof secret === 'string' ? [secret] : [...secret]\n\treturn list.filter((entry) => entry.trim().length > 0)\n}\n\n// The content-negotiation helpers (AGENTS §4.3 module-scope, §5) — the ONE\n// shared q-value parser behind the `Negotiator` (U3) and any future\n// compression middleware's `Accept-Encoding` pick.\n\n/**\n * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header\n * into its q-sorted entries.\n *\n * @remarks\n * Splits on `,`; for each part takes the token before the first `;`\n * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the\n * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls\n * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must\n * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving\n * the header's own order within a tie — a single pass with no backtracking,\n * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an\n * empty/malformed header yields `[]`/best-effort entries, never throws.\n *\n * @param header - The raw weighted header value\n * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending\n *\n * @example\n * ```ts\n * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')\n * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]\n * ```\n */\nexport function parseAcceptHeader(header: string): readonly AcceptEntry[] {\n\tconst entries: AcceptEntry[] = []\n\tfor (const part of header.split(',')) {\n\t\tconst trimmed = part.trim()\n\t\tif (trimmed.length === 0) continue\n\t\tconst semicolon = trimmed.indexOf(';')\n\t\tconst value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase()\n\t\tif (value.length === 0) continue\n\t\tlet q = 1\n\t\tif (semicolon !== -1) {\n\t\t\tconst match = /;\\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon))\n\t\t\tif (match !== null) {\n\t\t\t\tconst parsed = Number(match[1])\n\t\t\t\tif (Number.isFinite(parsed)) q = Math.min(1, Math.max(0, parsed))\n\t\t\t}\n\t\t}\n\t\tentries.push({ value, q })\n\t}\n\treturn entries\n\t\t.map((entry, index) => ({ entry, index }))\n\t\t.sort((a, b) => b.entry.q - a.entry.q || a.index - b.index)\n\t\t.map((ranked) => ranked.entry)\n}\n\n/**\n * The client's quality (q) for one content-coding from the parsed\n * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s\n * server-preference selection.\n *\n * @remarks\n * Prefers an EXACT named match (including an explicit `;q=0` rejection);\n * failing that, a bare `*` wildcard's q applies. A coding that is neither\n * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins\n * over a `*` (a specific rejection beats the wildcard), so it scores `0`.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param coding - The candidate coding to score\n * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5\n * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1\n * ```\n */\nexport function codingQuality(entries: readonly AcceptEntry[], coding: string): number {\n\tconst named = entries.find((entry) => entry.value === coding)\n\tif (named !== undefined) return named.q\n\tconst wildcard = entries.find((entry) => entry.value === '*')\n\treturn wildcard?.q ?? 0\n}\n\n/**\n * Select the best content-coding for an `Accept-Encoding` header from the\n * codings the server offers.\n *\n * @remarks\n * Parses the header ({@link parseAcceptHeader}) and scores each `available`\n * coding in the SERVER's preference order ({@link codingQuality}), keeping\n * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a\n * client-side tie). Returns `undefined` when the client accepts none of\n * `available` (identity — no compression). TOTAL on hostile input.\n *\n * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)\n * @param header - The raw `Accept-Encoding` header value\n * @param available - The codings the server offers, in preference (tie-break) order\n * @returns The negotiated coding, or `undefined` when none of `available` is acceptable\n *\n * @example\n * ```ts\n * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'\n * ```\n */\nexport function negotiateEncoding<T extends string>(\n\theader: string,\n\tavailable: readonly T[],\n): T | undefined {\n\tif (available.length === 0) return undefined\n\tconst entries = parseAcceptHeader(header)\n\tlet best: T | undefined\n\tlet bestQuality = 0\n\tfor (const coding of available) {\n\t\tconst quality = codingQuality(entries, coding)\n\t\tif (quality > bestQuality) {\n\t\t\tbest = coding\n\t\t\tbestQuality = quality\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * Rank + quality of one `candidate` media type against the parsed `Accept`\n * entries — the generic media-type primitive the `Negotiator`'s `negotiate`\n * uses to score each `available` candidate.\n *\n * @remarks\n * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the\n * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact\n * `;q=0` entry explicitly rejects the candidate outright (returns\n * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own\n * (less specific) coverage, so a later more-specific match can still allow\n * it. Among multiple matching entries, the lowest `rank` wins, and among a\n * rank tie the highest `q` wins.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate media type to score (e.g. `'text/html'`)\n * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches\n *\n * @example\n * ```ts\n * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')\n * // { q: 1, rank: 0 }\n * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }\n * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined\n * ```\n */\nexport function matchMediaType(\n\tentries: readonly AcceptEntry[],\n\tcandidate: string,\n): { readonly q: number; readonly rank: number } | undefined {\n\tconst slash = candidate.indexOf('/')\n\tconst type = slash === -1 ? candidate : candidate.slice(0, slash)\n\tlet best: { readonly q: number; readonly rank: number } | undefined\n\tfor (const entry of entries) {\n\t\tlet rank: number | undefined\n\t\tif (entry.value === candidate) rank = 0\n\t\telse if (entry.value === `${type}/*`) rank = 1\n\t\telse if (entry.value === '*/*') rank = 2\n\t\tif (rank === undefined) continue\n\t\tif (entry.q === 0) {\n\t\t\t// An exact `;q=0` explicitly rejects this candidate outright; a\n\t\t\t// wildcard `;q=0` only rejects the wildcard's own (less specific)\n\t\t\t// coverage, so a later more-specific match can still allow it.\n\t\t\tif (rank === 0) return undefined\n\t\t\tcontinue\n\t\t}\n\t\tif (best === undefined || rank < best.rank || (rank === best.rank && entry.q > best.q)) {\n\t\t\tbest = { q: entry.q, rank }\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * The client's quality for one `candidate` language from the parsed\n * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.\n *\n * @remarks\n * Prefers an exact match, then a primary-tag prefix match (`en` accepts\n * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry\n * is an explicit rejection).\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate language tag to score (e.g. `'en-US'`)\n * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1\n * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix\n * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard\n * ```\n */\nexport function languageQuality(entries: readonly AcceptEntry[], candidate: string): number {\n\tconst lower = candidate.toLowerCase()\n\tconst primary = lower.split('-')[0]\n\tlet named: number | undefined\n\tlet prefixed: number | undefined\n\tlet wildcard: number | undefined\n\tfor (const entry of entries) {\n\t\tconst entryPrimary = entry.value.split('-')[0]\n\t\tif (entry.value === lower) named = entry.q\n\t\telse if (entryPrimary === primary) {\n\t\t\tif (prefixed === undefined) prefixed = entry.q\n\t\t} else if (entry.value === '*') wildcard = entry.q\n\t}\n\tif (named !== undefined) return named\n\tif (prefixed !== undefined) return prefixed\n\treturn wildcard ?? 0\n}\n\n/**\n * Whether a `Content-Type` is worth compressing.\n *\n * @remarks\n * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`\n * type, a `+json`/`+xml` structured suffix, or one of the explicit\n * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed\n * binary (`image/png`, `application/zip`) is NOT compressible. An\n * absent/empty type is not compressible. TOTAL.\n *\n * @param type - The response `Content-Type` header value (with or without parameters)\n * @returns `true` when the type is text-shaped and worth compressing\n *\n * @example\n * ```ts\n * isCompressibleType('application/json; charset=utf-8') // true\n * isCompressibleType('image/png') // false\n * ```\n */\nexport function isCompressibleType(type: string): boolean {\n\tconst semicolon = type.indexOf(';')\n\tconst bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase()\n\tif (bare.length === 0) return false\n\tif (bare.startsWith('text/')) return true\n\tif (bare.endsWith('+json') || bare.endsWith('+xml')) return true\n\treturn COMPRESSIBLE_TYPES.has(bare)\n}\n\n// The conditional-request helpers (AGENTS §4.3 module-scope, §5) — ETag\n// compute/compare (RFC 7232 §2.3.2 WEAK comparison) and the TOTAL `Range`\n// parser.\n\n/**\n * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.\n *\n * @remarks\n * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex\n * digest as a WEAK validator (`W/\"<hash>\"`) when `weak` is `true` — the\n * default, encoding-AGNOSTIC, so the tag survives a downstream content\n * re-encoding (gzip) and still matches on revalidation — or a STRONG one\n * (`\"<hash>\"`, byte-identity) when `weak` is `false`.\n *\n * @param body - The full (uncompressed) response body to hash\n * @param weak - `true` for a weak `W/\"…\"` validator (the default), `false` for a strong `\"…\"` one\n * @returns The `ETag` header value\n *\n * @example\n * ```ts\n * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/\"…sha256-hex…\"'\n * ```\n */\nexport async function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak = true): Promise<string> {\n\tconst digest = await crypto.subtle.digest('SHA-256', body)\n\tconst hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(\n\t\t'',\n\t)\n\treturn weak ? `W/\"${hex}\"` : `\"${hex}\"`\n}\n\n/**\n * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque\n * comparison body — the reduction {@link matchesETag} applies to both sides\n * before the RFC 7232 §2.3.2 weak comparison.\n *\n * @param tag - One entity-tag (`W/\"<body>\"` or `\"<body>\"`)\n * @returns The tag with any leading `W/` removed (the quotes preserved)\n *\n * @example\n * ```ts\n * unwrapETag('W/\"abc\"') // '\"abc\"'\n * ```\n */\nexport function unwrapETag(tag: string): string {\n\tconst trimmed = tag.trim()\n\treturn trimmed.startsWith('W/') ? trimmed.slice(2) : trimmed\n}\n\n/**\n * Whether a request's `If-None-Match` header matches a resource's current\n * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.\n *\n * @remarks\n * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY\n * listed tag matches), or the `*` wildcard (matches ANY current\n * representation — only a list of exactly `*` is the wildcard). Comparison is\n * WEAK: `W/\"abc\"` and `\"abc\"` are equal (both sides' weak prefix is stripped\n * via {@link unwrapETag} before comparing the opaque body). TOTAL — a\n * malformed/empty header matches nothing, never throws.\n *\n * @param header - The raw `If-None-Match` header value\n * @param etag - The resource's current `ETag`\n * @returns `true` when the conditional matches (the caller answers `304`)\n *\n * @example\n * ```ts\n * matchesETag('\"abc\", W/\"def\"', 'W/\"abc\"') // true — weak comparison\n * matchesETag('*', 'W/\"anything\"') // true — wildcard\n * ```\n */\nexport function matchesETag(header: string, etag: string): boolean {\n\tconst trimmed = header.trim()\n\tif (trimmed === '*') return true\n\tconst target = unwrapETag(etag)\n\tfor (const member of trimmed.split(',')) {\n\t\tconst candidate = member.trim()\n\t\tif (candidate.length === 0) continue\n\t\tif (unwrapETag(candidate) === target) return true\n\t}\n\treturn false\n}\n\n/**\n * Parse an HTTP `Range` request header against a known resource `size` —\n * TOTAL, returning a {@link RangeSpec} or `undefined`.\n *\n * @remarks\n * Handles the three single-range `bytes=` forms — closed (`start-end`), open\n * (`start-`), and suffix (`-suffixLength`) — clamping the window to\n * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns\n * `{ satisfiable: true, start, end }` for an overlapping range,\n * `{ satisfiable: false }` for a range wholly past the resource, and\n * `undefined` for the \"serve the whole resource\" case: an ABSENT header, a\n * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not\n * supported), or any malformed/non-finite bound. NEVER throws on a hostile\n * header.\n *\n * @param header - The raw `Range` header value\n * @param size - The resource's total byte length\n * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource\n *\n * @example\n * ```ts\n * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }\n * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused\n * ```\n */\nexport function parseRange(header: string | undefined, size: number): RangeSpec | undefined {\n\tif (header === undefined) return undefined\n\tconst match = /^bytes=(.*)$/.exec(header.trim())\n\tif (match === null) return undefined\n\tconst capture = match[1]\n\tif (capture === undefined) return undefined\n\tconst spec = capture.trim()\n\tif (spec.includes(',')) return undefined\n\tconst dash = spec.indexOf('-')\n\tif (dash < 0) return undefined\n\tconst startText = spec.slice(0, dash).trim()\n\tconst endText = spec.slice(dash + 1).trim()\n\tif (startText === '') {\n\t\tconst suffix = Number(endText)\n\t\tif (endText === '' || !Number.isInteger(suffix) || suffix <= 0) return undefined\n\t\tif (size === 0) return { satisfiable: false }\n\t\tconst start = Math.max(0, size - suffix)\n\t\treturn { satisfiable: true, start, end: size - 1 }\n\t}\n\tconst start = Number(startText)\n\tif (!Number.isInteger(start) || start < 0) return undefined\n\tif (start >= size) return { satisfiable: false }\n\tif (endText === '') return { satisfiable: true, start, end: size - 1 }\n\tconst end = Number(endText)\n\tif (!Number.isInteger(end) || end < start) return undefined\n\treturn { satisfiable: true, start, end: Math.min(end, size - 1) }\n}\n\n// The security primitives (AGENTS §4.3 module-scope, §5) — CORS origin\n// resolution, `Vary` merging, security-header resolution, request-id\n// validation, and the IPv6 `/64` rate-key collapse.\n\n/**\n * Resolve the `Access-Control-Allow-Origin` value for a request.\n *\n * @remarks\n * `'*'` and a single origin string pass straight through. An allow-list\n * echoes the request's `Origin` only when it is present in the list, else\n * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent\n * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is\n * NEVER reflected even if `'null'` were listed, closing the hostile-context\n * cross-origin-access hole.\n *\n * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list\n * @param requestOrigin - The request's `Origin` header value, if present\n * @returns The allow-origin value to send, or `undefined` to set no header\n *\n * @example\n * ```ts\n * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'\n * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected\n * ```\n */\nexport function resolveOrigin(\n\torigin: string | readonly string[],\n\trequestOrigin: string | undefined,\n): string | undefined {\n\tif (isString(origin)) return origin\n\tif (!isString(requestOrigin)) return undefined\n\tif (requestOrigin === 'null') return undefined\n\treturn origin.includes(requestOrigin) ? requestOrigin : undefined\n}\n\n/**\n * Merge a `Vary` value into an existing `Vary` header without duplication.\n *\n * @remarks\n * Splits `existing` on `,`, trims each member, and appends `value` only when\n * no existing member already matches it case-insensitively (`Vary` header\n * names are case-insensitive). Preserves the existing members' order and\n * appends the new one last.\n *\n * @param existing - The current `Vary` header value, if any\n * @param value - The header name to ensure is listed\n * @returns The merged `Vary` value\n *\n * @example\n * ```ts\n * mergeVary(undefined, 'Origin') // 'Origin'\n * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)\n * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'\n * ```\n */\nexport function mergeVary(existing: string | undefined, value: string): string {\n\tconst members =\n\t\texisting === undefined\n\t\t\t? []\n\t\t\t: existing\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((member) => member.trim())\n\t\t\t\t\t.filter((member) => member.length > 0)\n\tconst present = members.some((member) => member.toLowerCase() === value.toLowerCase())\n\treturn present ? members.join(', ') : [...members, value].join(', ')\n}\n\n/**\n * Resolve one opt-out, value-bearing security header.\n *\n * @remarks\n * The shared \"a `string` value, or `false` to omit, or a default when unset\"\n * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):\n * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that\n * override, `undefined` (unset) ⇒ `fallback` (the secure default).\n *\n * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default\n * @param fallback - The secure-default value used when `value` is unset\n * @returns The header value to set, or `undefined` to omit the header\n *\n * @example\n * ```ts\n * resolveSecurityHeader(undefined, 'DENY') // 'DENY'\n * resolveSecurityHeader(false, 'DENY') // undefined — omitted\n * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override\n * ```\n */\nexport function resolveSecurityHeader(\n\tvalue: string | false | undefined,\n\tfallback: string,\n): string | undefined {\n\tif (value === false) return undefined\n\treturn value ?? fallback\n}\n\n/**\n * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response\n * header + `context.state`.\n *\n * @remarks\n * A request id is echoed RAW into a response header and log lines, so an\n * untrusted one is a header-injection + log-injection + DoS vector. This\n * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}\n * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).\n * TOTAL — never throws.\n *\n * @param value - The candidate incoming request id\n * @returns `true` when `value` is a safe, bounded, charset-clean correlation id\n *\n * @example\n * ```ts\n * isValidRequestId('req_abc-123') // true\n * isValidRequestId('bad\\r\\nheader') // false\n * ```\n */\nexport function isValidRequestId(value: string): boolean {\n\treturn REQUEST_ID_PATTERN.test(value)\n}\n\n/**\n * Compute the `/64` network of a full IPv6 address, or `undefined` when the\n * input is not a plain IPv6 address to collapse.\n *\n * @remarks\n * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4\n * is the identity) or any string that does not expand to exactly eight\n * hextets. Expands a single `::` into the missing zero hextets, takes the\n * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading\n * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped\n * first. Total — a malformed address returns `undefined`.\n *\n * @param address - The candidate IPv6 address\n * @returns The `/64` network string, or `undefined` when not a plain IPv6 address\n *\n * @example\n * ```ts\n * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'\n * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed\n * ```\n */\nexport function ipv6Network(address: string): string | undefined {\n\tif (/^::ffff:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/i.test(address)) return undefined\n\tconst percent = address.indexOf('%')\n\tconst bare = percent === -1 ? address : address.slice(0, percent)\n\tconst halves = bare.split('::')\n\tif (halves.length > 2) return undefined\n\tconst first = halves[0]\n\tif (first === undefined) return undefined\n\tconst second = halves[1]\n\tif (halves.length === 2 && second === undefined) return undefined\n\tconst head = first === '' ? [] : first.split(':')\n\tconst tail = second === undefined || second === '' ? [] : second.split(':')\n\tlet groups: string[]\n\tif (halves.length === 2) {\n\t\tconst missing = 8 - head.length - tail.length\n\t\tif (missing < 0) return undefined\n\t\tgroups = [...head, ...Array.from({ length: missing }, () => '0'), ...tail]\n\t} else {\n\t\tgroups = head\n\t}\n\tif (groups.length !== 8) return undefined\n\tconst prefix: string[] = []\n\tfor (const group of groups.slice(0, 4)) {\n\t\tif (!/^[0-9a-fA-F]{1,4}$/.test(group)) return undefined\n\t\tprefix.push(Number.parseInt(group, 16).toString(16))\n\t}\n\treturn `${prefix.join(':')}::/64`\n}\n\n/**\n * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to\n * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.\n *\n * @remarks\n * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a\n * per-`/128` rate limit is trivially bypassed by rotating host bits — the\n * real identity is the `/64` network. Delegates the IPv6 collapse to\n * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,\n * a malformed string) is kept unchanged.\n *\n * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})\n * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged\n *\n * @example\n * ```ts\n * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'\n * clientRateKey('192.0.2.1') // '192.0.2.1'\n * ```\n */\nexport function clientRateKey(address: string): string {\n\treturn ipv6Network(address) ?? address\n}\n\n// The Server-Sent-Events seam (AGENTS §4.3 module-scope, §5.4 of the\n// proposal) — `serializeEvent` is the wire encoder (the exact inverse of a\n// consuming SSE parser); `openStream` is the generic `Response`-returning\n// stream handle any streaming route (SSE today, a future producer tomorrow)\n// opens over a `ReadableStream`.\n\n/**\n * Serialize one {@link SSEMessage} to the SSE wire.\n *\n * @remarks\n * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE\n * `data:` line per CRLF-aware-split (`\\r\\n` / `\\r` / `\\n`) segment of `data`\n * (so a consuming parser's multi-`data` concat reproduces the original\n * `data` exactly, and no raw `\\r` or `\\n` can ever ride onto the wire inside\n * a `data:` line), then the terminating blank line.\n *\n * @param message - The event to serialize\n * @returns The SSE wire text for the event (terminated by a blank line)\n *\n * @example\n * ```ts\n * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\\ndata: hello\\n\\n'\n * serializeEvent({ data: 'multi\\nline' }) // 'data: multi\\ndata: line\\n\\n'\n * ```\n */\nexport function serializeEvent(message: SSEMessage): string {\n\tconst lines: string[] = []\n\tif (message.event !== undefined) lines.push(`event: ${message.event}`)\n\tif (message.id !== undefined) lines.push(`id: ${message.id}`)\n\tif (message.retry !== undefined) lines.push(`retry: ${message.retry}`)\n\tfor (const segment of message.data.split(/\\r\\n|\\r|\\n/)) lines.push(`data: ${segment}`)\n\treturn `${lines.join('\\n')}\\n\\n`\n}\n\n/**\n * Enqueue encoded text into an open byte stream.\n *\n * @param controller - The stream controller, when the stream has started\n * @param encoder - The encoder used for the stream's byte representation\n * @param closed - Whether the stream has already ended or been cancelled\n * @param text - The text to encode and enqueue\n * @returns Nothing\n *\n * @example\n * ```ts\n * const body = new ReadableStream<Uint8Array>({\n * \tstart(controller) {\n * \t\tenqueueStreamText(controller, new TextEncoder(), false, 'hello')\n * \t},\n * })\n * ```\n */\nexport function enqueueStreamText(\n\tcontroller: ReadableStreamDefaultController<Uint8Array> | undefined,\n\tencoder: TextEncoder,\n\tclosed: boolean,\n\ttext: string,\n): void {\n\tif (closed || controller === undefined) return\n\tcontroller.enqueue(encoder.encode(text))\n}\n\n/**\n * Open a generic Server-Sent-Events stream — a fetch-standard `Response`\n * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.\n *\n * @remarks\n * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}\n * merged under any `options.headers` (a seam-owned key is never overridden),\n * at `options.status` (default `200`). The returned {@link StreamInterface}'s\n * `write` serializes one message ({@link serializeEvent}), enqueues it, and\n * returns whether the controller still has positive desired size. A producer\n * receiving `false` can await `drain()`; its event-driven promise resolves on\n * the next consumer pull that restores capacity, or on stream closure.\n * `comment` writes a `: text` keep-alive line a conforming parser ignores;\n * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended\n * by `end()`, or the consumer cancelled the stream), so a late write never\n * throws.\n *\n * This readiness reflects only the process-local `ReadableStream` queue — it\n * is not proof that a remote peer consumed bytes. When the response pump\n * honors its socket sink's drain state, socket pressure stops body pulls and\n * therefore keeps this queue full, allowing a cooperative producer to bound\n * buffering. Ignoring the return value preserves the prior unconditional-\n * enqueue behavior. The default stream strategy counts chunks rather than\n * their byte length, so a byte-bounded producer must also cap each message.\n * Return `response` before awaiting a `false` write, because the consumer\n * cannot pull until it receives the response.\n *\n * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}\n * @returns The {@link StreamInterface} handle\n *\n * @example\n * ```ts\n * const stream = openStream()\n * void Promise.resolve().then(async () => {\n * \tif (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()\n * \tstream.end()\n * })\n * // return stream.response from the route handler\n * ```\n */\nexport function openStream(options?: StreamOptions): StreamInterface {\n\tconst encoder = new TextEncoder()\n\tlet closed = false\n\tlet controller: ReadableStreamDefaultController<Uint8Array> | undefined\n\tlet wakeup: PromiseWithResolvers<void> | undefined\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(streamController) {\n\t\t\tcontroller = streamController\n\t\t},\n\t\tpull(streamController) {\n\t\t\tif (streamController.desiredSize === null || streamController.desiredSize <= 0) return\n\t\t\twakeup?.resolve()\n\t\t\twakeup = undefined\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true\n\t\t\twakeup?.resolve()\n\t\t\twakeup = undefined\n\t\t},\n\t})\n\tconst headers = new Headers({ ...SSE_HEADERS, ...options?.headers })\n\tconst response = new Response(body, { status: options?.status ?? 200, headers })\n\treturn {\n\t\tresponse,\n\t\tget closed(): boolean {\n\t\t\treturn closed\n\t\t},\n\t\twrite(message: SSEMessage): boolean {\n\t\t\tif (closed || controller === undefined) return false\n\t\t\tenqueueStreamText(controller, encoder, closed, serializeEvent(message))\n\t\t\treturn controller.desiredSize !== null && controller.desiredSize > 0\n\t\t},\n\t\tcomment(text: string): void {\n\t\t\tenqueueStreamText(controller, encoder, closed, `: ${text}\\n\\n`)\n\t\t},\n\t\tdrain(): Promise<void> {\n\t\t\tconst desired = controller?.desiredSize\n\t\t\tif (closed || (desired !== undefined && desired !== null && desired > 0)) {\n\t\t\t\treturn Promise.resolve()\n\t\t\t}\n\t\t\twakeup ??= Promise.withResolvers<void>()\n\t\t\treturn wakeup.promise\n\t\t},\n\t\tend(): void {\n\t\t\tif (closed) return\n\t\t\tclosed = true\n\t\t\tcontroller?.close()\n\t\t\twakeup?.resolve()\n\t\t\twakeup = undefined\n\t\t},\n\t}\n}\n\n// The body pipeline (AGENTS §4.3 module-scope, §5.4 of the proposal) —\n// `readBody` collects a request body capped at `limit` bytes (413 over),\n// transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n// through a byte-counting `TransformStream` that ABORTS the instant\n// decompressed output exceeds `decompression` (the zip-bomb defense — fail\n// BEFORE materializing the bomb, since `DecompressionStream` has no\n// `maxOutputLength` knob), then decodes by content type. `scrubPrototype` /\n// `isDangerousKey` are the prototype-pollution scrub `readBody` applies to a\n// parsed JSON body, ported verbatim (pure value-walking logic, unaffected by\n// the fetch-vocabulary migration).\n\n/**\n * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,\n * or `prototype` — the three keys that, assigned onto a normal object, can\n * reach and mutate `Object.prototype`.\n *\n * @param key - The candidate object key\n * @returns `true` when `key` is one of the three prototype-pollution keys\n *\n * @example\n * ```ts\n * isDangerousKey('__proto__') // true\n * isDangerousKey('name') // false\n * ```\n */\nexport function isDangerousKey(key: string): boolean {\n\treturn key === '__proto__' || key === 'constructor' || key === 'prototype'\n}\n\n/**\n * Recursively STRIP the prototype-pollution keys from a parsed value IN\n * PLACE.\n *\n * @remarks\n * `JSON.parse('{\"__proto__\":{…}}')` is benign on its own — it produces an OWN,\n * enumerable `__proto__` DATA property — but that own key becomes a\n * pollution gadget the moment a downstream deep-merge copies it onto a live\n * object. This walks the value and `delete`s any own {@link isDangerousKey}\n * key at every depth, recursing into nested objects + array elements.\n * Primitives/`null` pass through untouched. Total — never throws. Mutates the\n * freshly-parsed value (which nothing else holds yet).\n *\n * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)\n * @returns The same `value`, with every dangerous key removed at every depth\n *\n * @example\n * ```ts\n * scrubPrototype(JSON.parse('{\"__proto__\":{\"polluted\":true},\"name\":\"ok\"}'))\n * // { name: 'ok' } — the __proto__ key is gone\n * ```\n */\nexport function scrubPrototype(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\tfor (const item of value) scrubPrototype(item)\n\t\treturn value\n\t}\n\tif (isRecord(value)) {\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tif (isDangerousKey(key)) {\n\t\t\t\tReflect.deleteProperty(value, key)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tscrubPrototype(value[key])\n\t\t}\n\t\treturn value\n\t}\n\treturn value\n}\n\n/**\n * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.\n *\n * @remarks\n * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,\n * throwing a {@link ContentTooLargeError} (413) the instant the running total\n * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than\n * collecting an unbounded body. A bodyless request (`request.body === null`)\n * resolves an empty array. A non-positive `limit` means unbounded.\n *\n * @param request - The `Request` to drain\n * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded\n * @returns The full request body as one `Uint8Array`\n * @throws {ContentTooLargeError} When the body exceeds `limit`\n *\n * @example\n * ```ts\n * const bytes = await collectRequestBody(request, 1_048_576)\n * ```\n */\nexport async function collectRequestBody(\n\trequest: Request,\n\tlimit: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tif (request.body === null) return new Uint8Array(0)\n\tconst reader = request.body.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet total = 0\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read()\n\t\tif (done) break\n\t\ttotal += value.byteLength\n\t\tif (limit > 0 && total > limit) {\n\t\t\tawait reader.cancel()\n\t\t\tthrow new ContentTooLargeError(limit)\n\t\t}\n\t\tchunks.push(value)\n\t}\n\tconst merged = new Uint8Array(total)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn merged\n}\n\n/**\n * Narrow a raw `Content-Encoding` header value to a decompressible\n * {@link Encoding} — the boundary guard {@link readBody} uses to decide\n * whether a request body needs transparent decompression.\n *\n * @remarks\n * Lower-cases + trims and returns the matching {@link Encoding} ONLY for\n * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of\n * the proposal). An absent header, `identity`, an unknown value, or a\n * comma-joined multi-coding all yield `undefined` (the body is read as-is).\n * TOTAL — never asserts the loose `string | null` header.\n *\n * @param header - The raw `Content-Encoding` header value\n * @returns The single decompressible {@link Encoding}, or `undefined` when none applies\n *\n * @example\n * ```ts\n * requestEncoding('gzip') // 'gzip'\n * requestEncoding('br') // undefined — unsupported by DecompressionStream\n * ```\n */\nexport function requestEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined {\n\tif (!isString(header)) return undefined\n\tconst value = header.trim().toLowerCase()\n\treturn value === 'gzip' || value === 'deflate' ? value : undefined\n}\n\n/**\n * Transparently decompress an already-collected, `gzip`/`deflate`-encoded\n * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —\n * the zip-bomb defense.\n *\n * @remarks\n * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting\n * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed\n * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`\n * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces\n * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated\n * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}\n * (never conflated with the cap). A non-positive `cap` means uncapped.\n *\n * @param bytes - The compressed bytes to decompress\n * @param encoding - The {@link Encoding} the bytes are compressed with\n * @param cap - The maximum decompressed byte count; a non-positive value means uncapped\n * @returns The decompressed bytes\n * @throws {ContentTooLargeError} When decompressed output would exceed `cap`\n * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)\n */\nexport async function decompressRequestBody(\n\tbytes: Uint8Array<ArrayBuffer>,\n\tencoding: Exclude<Encoding, 'identity'>,\n\tcap: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tlet total = 0\n\tconst capStream = new TransformStream<Uint8Array, Uint8Array>({\n\t\ttransform(chunk, controller) {\n\t\t\ttotal += chunk.byteLength\n\t\t\tif (cap > 0 && total > cap) {\n\t\t\t\tcontroller.error(new ContentTooLargeError(cap))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk)\n\t\t},\n\t})\n\tconst source = new ReadableStream<Uint8Array<ArrayBuffer>>({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue(bytes)\n\t\t\tcontroller.close()\n\t\t},\n\t})\n\tconst decompressed = source.pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream)\n\tconst reader = decompressed.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet size = 0\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (done) break\n\t\t\tchunks.push(value)\n\t\t\tsize += value.byteLength\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof ContentTooLargeError) throw error\n\t\tthrow new HTTPError(400, 'malformed compressed request body')\n\t}\n\tconst merged = new Uint8Array(size)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn merged\n}\n\n/**\n * Collect + decode a `Request` body — the shared body-collection pipeline\n * surfaced to middleware and handlers as the middleware context's cached\n * `body()`.\n *\n * @remarks\n * Collects the wire body capped at `options.limit` bytes ({@link\n * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),\n * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at\n * `options.decompression`, default {@link\n * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by\n * content type: `application/json` is parsed via `@orkestrel/contract`'s\n * `parseJSON` and scrubbed of prototype-pollution keys ({@link\n * scrubPrototype}); any other type decodes as UTF-8 text; an empty body\n * decodes to `undefined`.\n *\n * @param request - The `Request` to read the body from\n * @param options - The {@link BodyOptions} `limit` + `decompression` caps\n * @returns The parsed JSON value, the raw text, or `undefined` for an empty body\n * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap\n * @throws {HTTPError} When the compressed body is corrupt (400)\n *\n * @example\n * ```ts\n * const body = await readBody(request, { limit: 1_048_576 })\n * ```\n */\nexport async function readBody(request: Request, options?: BodyOptions): Promise<unknown> {\n\tconst limit = options?.limit ?? DEFAULT_BODY_LIMIT\n\tconst decompression = options?.decompression ?? DEFAULT_DECOMPRESSED_LIMIT\n\tconst wire = await collectRequestBody(request, limit)\n\tconst encoding = requestEncoding(request.headers.get('content-encoding'))\n\tconst bytes =\n\t\tencoding === undefined ? wire : await decompressRequestBody(wire, encoding, decompression)\n\tif (bytes.length === 0) return undefined\n\tconst contentType = request.headers.get('content-type')\n\tconst semicolon = contentType === null ? -1 : contentType.indexOf(';')\n\tconst bareType =\n\t\tcontentType === null\n\t\t\t? ''\n\t\t\t: (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase()\n\tconst text = new TextDecoder().decode(bytes)\n\tif (bareType === 'application/json') return scrubPrototype(parseJSON(text))\n\treturn text\n}\n\n// ============================================================================\n// The node face — pure helpers (AGENTS §5). Every function here is genuinely\n// node-bound (a `node:net` probe, an `AddressInfo` narrow) — everything\n// fetch/string-pure lives above in this same file and is consumed, never\n// duplicated (the socket-encrypted narrow and the `Request`/`Response`\n// conversion are `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` /\n// `sendResponse`).\n// ============================================================================\n\n/**\n * Whether a `node:net` `server.address()` return is the structured\n * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`\n * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`\n * and the `Server`'s own port resolution read the bound port through.\n *\n * @param value - The `server.address()` return (`AddressInfo | string | null`)\n * @returns `true` when `value` is an `AddressInfo` with a numeric `port`\n *\n * @example\n * ```ts\n * import { isAddressInfo } from '@src/server'\n *\n * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true\n * isAddressInfo(null) // false\n * ```\n */\nexport function isAddressInfo(value: unknown): value is AddressInfo {\n\treturn isRecord(value) && isNumber(value.port)\n}\n\n/**\n * Bind and close a throwaway TCP server to resolve one available port.\n *\n * @param port - The requested port, with `0` selecting an ephemeral port\n * @returns The bound port after the probe server has closed\n *\n * @example\n * ```ts\n * const port = await probePort(0)\n * ```\n */\nexport async function probePort(port: number): Promise<number> {\n\tconst probe = createNetServer()\n\tconst listening = once(probe, 'listening')\n\tprobe.listen(port)\n\tawait listening\n\tconst address = probe.address()\n\tconst resolved = isAddressInfo(address) ? address.port : 0\n\tconst closed = once(probe, 'close')\n\tprobe.close()\n\tawait closed\n\treturn resolved\n}\n\n/**\n * Find a FREE TCP port — bind a throwaway `node:net` server, read the\n * OS-assigned port, close it, and resolve that port.\n *\n * @remarks\n * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)\n * and returns it. With a `preferred` port it tries THAT port first and\n * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an\n * ephemeral free port rather than rejecting — a caller always gets a usable\n * port. It binds then immediately closes a probe server, so the returned\n * port is free at the instant of the probe (an inherent TOCTOU race — bind it\n * promptly). Rejects only on an unexpected listen error other than a taken\n * `preferred` port (e.g. a permission fault).\n *\n * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒\n * fall back to an ephemeral port\n * @returns A free TCP port number\n *\n * @example\n * ```ts\n * import { createServer, discoverPort } from '@src/server'\n *\n * const port = await discoverPort() // a guaranteed-free ephemeral port\n * ```\n */\nexport async function discoverPort(preferred?: number): Promise<number> {\n\tif (preferred === undefined) return probePort(0)\n\ttry {\n\t\treturn await probePort(preferred)\n\t} catch (error) {\n\t\tif (error instanceof Error && 'code' in error && error.code === 'EADDRINUSE')\n\t\t\treturn probePort(0)\n\t\tthrow error\n\t}\n}\n","import type { Encoding, FormatHandlerMap, MiddlewareContext, NegotiatorInterface } from './types.js'\nimport { languageQuality, matchMediaType, negotiateEncoding, parseAcceptHeader } from './helpers.js'\n\n/**\n * The content-negotiation machine over the weighted `Accept` family — a\n * reusable, cross-middleware ENTITY (not a middleware). Implements exactly\n * {@link NegotiatorInterface}.\n *\n * @remarks\n * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /\n * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its\n * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the\n * rest of the substrate uses — one parser, never two. `format` reads the\n * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes\n * the winner — or answers `406 Not Acceptable`.\n *\n * @example\n * ```ts\n * const negotiator = new Negotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport class Negotiator implements NegotiatorInterface {\n\tnegotiate(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tlet best: string | undefined\n\t\tlet bestQuality = 0\n\t\tlet bestRank = Number.POSITIVE_INFINITY\n\t\tfor (const candidate of available) {\n\t\t\tconst match = matchMediaType(entries, candidate)\n\t\t\tif (match === undefined) continue\n\t\t\tconst { q, rank } = match\n\t\t\tif (q > bestQuality || (q === bestQuality && rank < bestRank)) {\n\t\t\t\tbest = candidate\n\t\t\t\tbestQuality = q\n\t\t\t\tbestRank = rank\n\t\t\t}\n\t\t}\n\t\treturn best\n\t}\n\n\tencoding(header: string, available: readonly Encoding[]): Encoding | undefined {\n\t\treturn negotiateEncoding(header, available)\n\t}\n\n\tlanguage(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tlet best: string | undefined\n\t\tlet bestQuality = 0\n\t\tfor (const candidate of available) {\n\t\t\tconst quality = languageQuality(entries, candidate)\n\t\t\tif (quality > bestQuality) {\n\t\t\t\tbest = candidate\n\t\t\t\tbestQuality = quality\n\t\t\t}\n\t\t}\n\t\treturn best\n\t}\n\n\t/**\n\t * @remarks\n\t * Errors thrown by the negotiated handler propagate UNMODIFIED — the\n\t * server boundary classifies them, never this negotiator.\n\t */\n\tasync format<TState>(\n\t\trequest: Request,\n\t\tcontext: MiddlewareContext<TState>,\n\t\thandlers: FormatHandlerMap<TState>,\n\t): Promise<Response> {\n\t\tconst keys = Object.keys(handlers)\n\t\tconst header = request.headers.get('accept')\n\t\tconst type = header === null ? keys[0] : this.negotiate(header, keys)\n\t\tif (type === undefined) return new Response('Not Acceptable', { status: 406 })\n\t\tconst handler = handlers[type]\n\t\tif (handler === undefined) return new Response('Not Acceptable', { status: 406 })\n\t\treturn handler(request, context)\n\t}\n}\n","import type { IncomingMessage, Server as NodeHTTPServer, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { AbortInterface } from '@orkestrel/abort'\nimport type { TimeoutInterface } from '@orkestrel/timeout'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnectionStateFunction,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { addAbortListener, once } from 'node:events'\nimport { createServer as createHTTPServer } from 'node:http'\nimport { createAbort, linkSignal } from '@orkestrel/abort'\nimport { createTimeout } from '@orkestrel/timeout'\nimport { buildRequest, isEncryptedSocket, sendResponse } from '@orkestrel/router/server'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isFiniteNumber, isFunction, isInteger } from '@orkestrel/contract'\nimport { compose, isAddressInfo, readBody } from './helpers.js'\nimport { DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_MS } from './constants.js'\nimport { HTTPError, isHTTPError } from './errors.js'\n\n/**\n * The HTTP server facade — an observable `node:http` lifecycle composing this\n * module's own middleware onion around a consumed `@orkestrel/router`\n * dispatcher.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n *\n * @remarks\n * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`\n * server, binds the configured {@link ServerOptions.host} / {@link\n * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the\n * bound address), observes caller cancellation plus the configured\n * `timeouts.start` deadline while the bind is pending, and transitions\n * `idle → starting → listening`. A cancelled or expired bind closes its\n * partial server and resets to `idle` for another start. `stop()` transitions\n * to `stopping`: refuses new connections, fires a fresh-per-run stop signal\n * so in-flight handlers observe cancellation, drains up to the `drain`\n * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`\n * is the idempotent final teardown.\n * - **Per request.** In-flight is tracked (finished on response `finish` or\n * `close`); a `Request` is built via the router's `buildRequest`, its\n * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s\n * `linkSignal` (a fresh `Request` is constructed with the linked signal —\n * `buildRequest`'s own abort, armed by BOTH request-side and response-side\n * teardown, composes with the server's stop signal via `AbortSignal.any`,\n * so a handler awaiting `request.signal` observes BOTH); `context.state` is built via\n * {@link ServerOptions.state} from the connection facts; the composed\n * middleware onion runs, terminating in `dispatcher.handle`; the result is\n * written back via `sendResponse`.\n * - **The built-in boundary** wraps the WHOLE per-request chain, including\n * setup: `buildRequest` runs behind its own inner boundary that maps a\n * throw (e.g. a malformed `Host` header) to a silent `400` with no\n * `error` emit; everything after (`Request` reconstruction, connection\n * facts, `state`, the composed onion, and `dispatcher.handle`) runs\n * behind the outer boundary — a thrown `HTTPError` renders as its status +\n * message; any other throw renders `500` (message hidden unless\n * `expose`), `report` is invoked (its own throw swallowed), and `error` is\n * emitted. A server-owned last resort wraps the final `sendResponse`\n * write itself: if even that fails, the connection is destroyed rather\n * than left to escape as an unhandled error.\n * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a\n * throwing handler is treated as declined and surfaced on `error`, an\n * unclaimed upgrade destroys the socket), bound per-run to this instance.\n * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}\n * exposed as `readonly emitter`; the emitter isolates a listener throw and\n * routes it to the `error` OPTION (not the domain `error` event).\n */\nexport class Server<TState> implements ServerInterface<TState> {\n\treadonly id = crypto.randomUUID()\n\treadonly #dispatcher: DispatcherInterface<TState>\n\treadonly #state: ConnectionStateFunction<TState>\n\treadonly #middleware: MiddlewareHandler<TState>[]\n\treadonly #upgradeHandlers: UpgradeHandler[] = []\n\treadonly #emitter: Emitter<ServerEventMap>\n\treadonly #host: string | undefined\n\treadonly #configuredPort: number | undefined\n\treadonly #drain: number\n\treadonly #limit: number\n\treadonly #expose: boolean\n\treadonly #report: ((error: unknown, request?: { method: string; url: URL }) => void) | undefined\n\treadonly #timeouts: {\n\t\treadonly start?: number\n\t\treadonly request?: number\n\t\treadonly headers?: number\n\t\treadonly keepalive?: number\n\t}\n\treadonly #sockets: {\n\t\treadonly connections?: number\n\t\treadonly headers?: number\n\t\treadonly requests?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#abort: AbortInterface = createAbort()\n\t#wakeup: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#pending = 0\n\n\tconstructor(options: ServerOptions<TState>) {\n\t\tif (!isFunction(options.state)) throw new TypeError('ServerOptions.state must be a function')\n\t\tif (options.report !== undefined && !isFunction(options.report))\n\t\t\tthrow new TypeError('ServerOptions.report must be a function')\n\t\tconst drain = options.drain ?? DEFAULT_DRAIN_MS\n\t\tif (!isFiniteNumber(drain) || drain < 0)\n\t\t\tthrow new TypeError('ServerOptions.drain must be a non-negative finite number')\n\t\tconst limit = options.limit ?? DEFAULT_BODY_LIMIT\n\t\tif (!isFiniteNumber(limit) || limit < 0)\n\t\t\tthrow new TypeError('ServerOptions.limit must be a non-negative finite number')\n\t\tconst timeouts = options.timeouts ?? {}\n\t\tfor (const [name, value] of Object.entries(timeouts)) {\n\t\t\tif (value !== undefined && (!isFiniteNumber(value) || value < 0))\n\t\t\t\tthrow new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`)\n\t\t}\n\t\tif (\n\t\t\ttimeouts.headers !== undefined &&\n\t\t\ttimeouts.keepalive !== undefined &&\n\t\t\ttimeouts.headers > timeouts.keepalive\n\t\t) {\n\t\t\tthrow new TypeError('ServerOptions.timeouts.headers must not exceed timeouts.keepalive')\n\t\t}\n\t\tconst sockets = options.sockets ?? {}\n\t\tfor (const [name, value] of Object.entries(sockets)) {\n\t\t\tif (value !== undefined && (!isInteger(value) || value < 0))\n\t\t\t\tthrow new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`)\n\t\t}\n\t\tthis.#dispatcher = options.dispatcher\n\t\tthis.#state = options.state\n\t\tthis.#middleware = options.middleware === undefined ? [] : [...options.middleware]\n\t\tthis.#host = options.host\n\t\tthis.#configuredPort = options.port\n\t\tthis.#drain = drain\n\t\tthis.#limit = limit\n\t\tthis.#expose = options.expose ?? false\n\t\tthis.#report = options.report\n\t\tthis.#timeouts = timeouts\n\t\tthis.#sockets = sockets\n\t\tthis.#emitter = new Emitter<ServerEventMap>({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t}\n\n\tget status(): ServerStatus {\n\t\treturn this.#status\n\t}\n\n\tget port(): number | undefined {\n\t\treturn this.#port\n\t}\n\n\tget dispatcher(): DispatcherInterface<TState> {\n\t\treturn this.#dispatcher\n\t}\n\n\tget emitter(): EmitterInterface<ServerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tuse(middleware: MiddlewareHandler<TState>): void\n\tuse(middleware: readonly MiddlewareHandler<TState>[]): void\n\tuse(middleware: MiddlewareHandler<TState> | readonly MiddlewareHandler<TState>[]): void {\n\t\tif (typeof middleware === 'function') this.#middleware.push(middleware)\n\t\telse this.#middleware.push(...middleware)\n\t}\n\n\tupgrade(handler: UpgradeHandler): void {\n\t\tthis.#upgradeHandlers.push(handler)\n\t}\n\n\tstart(signal?: AbortSignal): Promise<number> {\n\t\tif (this.#status !== 'idle' && this.#status !== 'stopped') {\n\t\t\treturn Promise.reject(new Error(`server cannot start from '${this.#status}'`))\n\t\t}\n\t\tthis.#status = 'starting'\n\t\t// A fresh stop signal per run, so a restarted server is not born aborted.\n\t\tthis.#abort = createAbort()\n\t\tconst server = createHTTPServer((request, response) => this.#handle(request, response))\n\t\tif (this.#timeouts.request !== undefined) server.requestTimeout = this.#timeouts.request\n\t\tif (this.#timeouts.headers !== undefined) server.headersTimeout = this.#timeouts.headers\n\t\tif (this.#timeouts.keepalive !== undefined) server.keepAliveTimeout = this.#timeouts.keepalive\n\t\tif (this.#sockets.connections !== undefined) server.maxConnections = this.#sockets.connections\n\t\tif (this.#sockets.headers !== undefined) server.maxHeadersCount = this.#sockets.headers\n\t\tif (this.#sockets.requests !== undefined) server.maxRequestsPerSocket = this.#sockets.requests\n\t\t// Bound to THIS run's server instance, discarded with it on stop/restart —\n\t\t// no manual removal needed (the same per-run lifecycle as the handler above).\n\t\tserver.on('upgrade', (request, socket, head) => this.#onUpgrade(request, socket, head))\n\t\tthis.#http = server\n\t\treturn this.#listen(server, signal)\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (this.#status !== 'listening') return\n\t\tthis.#status = 'stopping'\n\t\tthis.#emitter.emit('stop')\n\t\tconst server = this.#http\n\t\t// A pure signal — NOT the drain deadline's parent (a parent abort would\n\t\t// clear the Timeout so it never fires). The drain deadline is an\n\t\t// independent clock; the wake-park below resolves on the last finish OR\n\t\t// the deadline, event-driven, never a busy-loop.\n\t\tthis.#abort.abort()\n\t\tconst deadline: TimeoutInterface = createTimeout({ ms: this.#drain })\n\t\tdeadline.start()\n\t\tawait this.#drainPending(deadline.signal)\n\t\tdeadline.clear()\n\t\tconst pending = this.#pending\n\t\tthis.#emitter.emit('drain', pending)\n\t\tif (server !== undefined) await this.#close(server, pending > 0)\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#status === 'stopped' && this.#http === undefined) {\n\t\t\tthis.#emitter.destroy()\n\t\t\treturn\n\t\t}\n\t\tif (!this.#abort.aborted) this.#abort.abort()\n\t\tconst server = this.#http\n\t\tif (server !== undefined) await this.#close(server, true)\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Track the request for draining FIRST — before anything that can throw —\n\t// so the sync listener itself never throws; the rest of setup (which CAN\n\t// throw on a malformed request) is deferred into the async `#accept`\n\t// entry, kept behind the built-in boundary.\n\t#handle(message: IncomingMessage, response: ServerResponse): void {\n\t\tconst finish = this.#trackStart()\n\t\tresponse.once('finish', finish)\n\t\tresponse.once('close', finish)\n\t\tvoid this.#accept(message, response)\n\t}\n\n\t// Build the fetch `Request` + `MiddlewareContext`, run the composed onion,\n\t// and write the result back — every escaping throw is caught so the\n\t// process can never crash on an unhandled handler (or malformed request)\n\t// error. `buildRequest` runs behind its OWN inner boundary: a throw there\n\t// (e.g. a malformed `Host` header) maps to a silent `400`, never `error`.\n\tasync #accept(message: IncomingMessage, response: ServerResponse): Promise<void> {\n\t\tlet raw: Request\n\t\ttry {\n\t\t\traw = buildRequest(message, { response })\n\t\t} catch {\n\t\t\tawait this.#respond(this.#boundary(new HTTPError(400, 'invalid request')), response)\n\t\t\treturn\n\t\t}\n\t\t// Hoisted above the inner try (not block-scoped inside it) so the catch\n\t\t// below can attach real request context to the `error` emit / `report`\n\t\t// sink — and so `response` can be emitted with the same facts on either\n\t\t// the success or the error path.\n\t\tconst method = raw.method\n\t\tconst url = new URL(raw.url)\n\t\tconst start = performance.now()\n\t\ttry {\n\t\t\tconst linked = linkSignal(raw.signal, this.#abort.signal)\n\t\t\tconst request = new Request(raw, { signal: linked })\n\t\t\tthis.#emitter.emit('request', method, url.pathname)\n\t\t\tconst ip = message.socket.remoteAddress\n\t\t\tconst connection = {\n\t\t\t\t...(ip === undefined ? {} : { ip }),\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tconst context: MiddlewareContext<TState> = {\n\t\t\t\turl,\n\t\t\t\tmethod,\n\t\t\t\tstate: this.#state(connection),\n\t\t\t\tbody: this.#createBody(request),\n\t\t\t}\n\t\t\tconst runner = compose(this.#middleware, (currentRequest, currentContext) =>\n\t\t\t\tthis.#dispatcher.handle(currentRequest, currentContext.state),\n\t\t\t)\n\t\t\tconst result = await runner(request, context)\n\t\t\tawait this.#respond(result, response)\n\t\t\tthis.#emitter.emit('response', {\n\t\t\t\tmethod,\n\t\t\t\tpathname: url.pathname,\n\t\t\t\tstatus: result.status,\n\t\t\t\tms: Math.round(performance.now() - start),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tconst mapped = this.#boundary(error)\n\t\t\tif (!isHTTPError(error)) {\n\t\t\t\tthis.#emitter.emit('error', error, { method, url })\n\t\t\t\tif (this.#report !== undefined) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#report(error, { method, url })\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Swallowed — reporting can never crash the response.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait this.#respond(mapped, response)\n\t\t\tthis.#emitter.emit('response', {\n\t\t\t\tmethod,\n\t\t\t\tpathname: url.pathname,\n\t\t\t\tstatus: mapped.status,\n\t\t\t\tms: Math.round(performance.now() - start),\n\t\t\t})\n\t\t}\n\t}\n\n\t// The server-owned last resort: even a write failure inside\n\t// `sendResponse` cannot escape and crash the process — the underlying\n\t// response (and its socket) is destroyed instead.\n\tasync #respond(result: Response, response: ServerResponse): Promise<void> {\n\t\ttry {\n\t\t\tawait sendResponse(result, response)\n\t\t} catch {\n\t\t\tresponse.destroy()\n\t\t}\n\t}\n\n\t// The built-in boundary — an `HTTPError` renders as its status + message;\n\t// any other throw renders `500` with its message hidden unless `expose`.\n\t#boundary(error: unknown): Response {\n\t\tif (isHTTPError(error)) return new Response(error.message, { status: error.status })\n\t\tconst message = this.#expose && error instanceof Error ? error.message : 'Internal Server Error'\n\t\treturn new Response(message, { status: 500 })\n\t}\n\n\t// Fan a raw protocol-upgrade out to the registered handlers in\n\t// registration order: the FIRST to return `true` CLAIMS the socket. A\n\t// throwing handler is treated as DECLINED — surfaced on `error` — and the\n\t// fan-out continues so a later handler can still claim. Unclaimed ⇒ the\n\t// socket is destroyed so an unhandled upgrade never leaks a connection.\n\t#onUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {\n\t\tlet handled = false\n\t\tfor (const handler of this.#upgradeHandlers) {\n\t\t\ttry {\n\t\t\t\tif (handler(request, socket, head)) {\n\t\t\t\t\thandled = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.#emitter.emit('error', error)\n\t\t\t}\n\t\t}\n\t\tif (!handled) socket.destroy()\n\t\tthis.#emitter.emit('upgrade', request, handled)\n\t}\n\n\t// Resolve the bound port from the server's address, narrowed via a guard\n\t// (an `AddressInfo` carries a numeric `port`; a string / null address has\n\t// none). No assertion — an unresolvable address yields `0`.\n\t#resolvePort(server: NodeHTTPServer): number {\n\t\tconst address = server.address()\n\t\tif (isAddressInfo(address)) return address.port\n\t\treturn 0\n\t}\n\n\tasync #listen(server: NodeHTTPServer, signal?: AbortSignal): Promise<number> {\n\t\tconst deadline =\n\t\t\tthis.#timeouts.start === undefined ? undefined : createTimeout({ ms: this.#timeouts.start })\n\t\tconst startup = deadline === undefined ? signal : linkSignal(deadline.signal, signal)\n\t\tconst binding = createAbort()\n\t\tconst relay =\n\t\t\tstartup === undefined\n\t\t\t\t? undefined\n\t\t\t\t: addAbortListener(startup, () => binding.abort(startup.reason))\n\t\tlet listening: Promise<unknown[]> | undefined\n\t\ttry {\n\t\t\tsignal?.throwIfAborted()\n\t\t\tdeadline?.start()\n\t\t\tif (deadline?.ms === 0 && startup !== undefined) await once(startup, 'abort')\n\t\t\tstartup?.throwIfAborted()\n\t\t\tlistening = once(server, 'listening', { signal: binding.signal })\n\t\t\tif (startup === undefined) server.listen(this.#configuredPort ?? 0, this.#host)\n\t\t\telse {\n\t\t\t\tserver.listen({\n\t\t\t\t\tport: this.#configuredPort ?? 0,\n\t\t\t\t\t...(this.#host === undefined ? {} : { host: this.#host }),\n\t\t\t\t\tsignal: binding.signal,\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait listening\n\t\t} catch (error) {\n\t\t\tconst expired = deadline?.expired === true\n\t\t\tconst cancelled = startup?.aborted === true\n\t\t\t// A cancellation removes `events.once`'s temporary error listener. Keep\n\t\t\t// the discarded server guarded while a simultaneous late bind error\n\t\t\t// settles so it cannot escape as an uncaught process error.\n\t\t\tserver.on('error', () => undefined)\n\t\t\tbinding.abort(error)\n\t\t\tif (listening !== undefined) await listening.catch(() => undefined)\n\t\t\tawait this.#close(server, true)\n\t\t\tthis.#http = undefined\n\t\t\tthis.#port = undefined\n\t\t\tthis.#status = 'idle'\n\t\t\tif (expired && deadline !== undefined) {\n\t\t\t\tthrow new DOMException(\n\t\t\t\t\t`Server startup exceeded ${deadline.ms} milliseconds`,\n\t\t\t\t\t'TimeoutError',\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (cancelled && startup !== undefined) throw startup.reason\n\t\t\tthrow error\n\t\t} finally {\n\t\t\trelay?.[Symbol.dispose]()\n\t\t\tdeadline?.clear()\n\t\t}\n\t\tconst port = this.#resolvePort(server)\n\t\tthis.#port = port\n\t\tthis.#status = 'listening'\n\t\tthis.#emitter.emit('start', port)\n\t\treturn port\n\t}\n\n\t#createBody(request: Request): () => Promise<unknown> {\n\t\tlet cached: Promise<unknown> | undefined\n\t\treturn () => {\n\t\t\tcached ??= readBody(request, { limit: this.#limit })\n\t\t\treturn cached\n\t\t}\n\t}\n\n\t// Close the underlying server, resolving once it stops accepting\n\t// connections. A keep-alive client leaves its socket IDLE after a\n\t// response, which would hang a plain `close()` — so idle sockets are\n\t// always dropped (an in-flight request is untouched); when `force` is set\n\t// (the drain deadline fired with work still in flight, or `destroy`)\n\t// every open socket is destroyed so the callback fires promptly.\n\t#close(server: NodeHTTPServer, force: boolean): Promise<void> {\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tserver.close(() => resolve())\n\t\t\tif (force) server.closeAllConnections()\n\t\t\telse server.closeIdleConnections()\n\t\t})\n\t}\n\n\t// Track one in-flight request; returns an idempotent finish thunk. When\n\t// the last in-flight request finishes, the current drain wakeup fires —\n\t// event-driven, never a busy-loop.\n\t#trackStart(): () => void {\n\t\tif (this.#pending === 0) this.#wakeup = createAbort()\n\t\tthis.#pending += 1\n\t\tlet finished = false\n\t\treturn () => {\n\t\t\tif (finished) return\n\t\t\tfinished = true\n\t\t\tthis.#pending -= 1\n\t\t\tif (this.#pending === 0) this.#wakeup.abort()\n\t\t}\n\t}\n\n\t// Park until the in-flight count reaches zero OR `signal` fires —\n\t// event-driven (wake-park), no polling.\n\tasync #drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#pending === 0 || signal.aborted) return\n\t\tawait once(AbortSignal.any([signal, this.#wakeup.signal]), 'abort')\n\t}\n}\n","import type { NegotiatorInterface, ServerInterface, ServerOptions } from './types.js'\nimport { Negotiator } from './Negotiator.js'\nimport { Server } from './Server.js'\n\n/**\n * Create a {@link NegotiatorInterface} — the reusable content-negotiation\n * machine over the weighted `Accept` family.\n *\n * @remarks\n * Prefer this over `new Negotiator()` at call sites that only need the\n * interface.\n *\n * @returns A {@link NegotiatorInterface}\n *\n * @example\n * ```ts\n * import { createNegotiator } from '@src/server'\n *\n * const negotiator = createNegotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport function createNegotiator(): NegotiatorInterface {\n\treturn new Negotiator()\n}\n\n/**\n * Create a {@link ServerInterface} — the node face's HTTP server facade over\n * a consumed `@orkestrel/router` dispatcher.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param options - {@link ServerOptions}\n * @returns A {@link ServerInterface}, not yet started\n *\n * @example\n * ```ts\n * import { createServer } from '@src/server'\n * import { createDispatcher } from '@orkestrel/router'\n *\n * const dispatcher = createDispatcher<{ readonly ip?: string }>()\n * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })\n *\n * const server = createServer({\n * \tdispatcher,\n * \tstate: (connection) => ({ ip: connection.ip }),\n * })\n * const port = await server.start()\n * await server.stop()\n * ```\n */\nexport function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState> {\n\treturn new Server(options)\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,mBAAmB;;;;;;;;;;;;;;AAehC,IAAa,mBAAmB,OAAO,IAAI,6BAA6B;;AAGxE,IAAa,qBAAqB;;;;;;;;;;;;;;;;;AAkBlC,IAAa,6BAA6B;;;;;;;;;;;;AAa1C,IAAa,cAAgD,OAAO,OAAO;CAC1E,gBAAgB;CAChB,iBAAiB;CACjB,YAAY;CACZ,qBAAqB;AAC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KAAKd,QAAQ;EACb,KAAKD,UAAU;EACf,KAAKT,SAAS,KAAK,SAAS,IAAI;EAChC,OAAO;CACR;CAEA,YAAY,SAA0C;EACrD,IAAI;EACJ,aAAa;GACZ,WAAW,SAAS,SAAS,EAAE,OAAO,KAAKI,OAAO,CAAC;GACnD,OAAO;EACR;CACD;CAQA,OAAO,QAAwB,OAA+B;EAC7D,OAAO,IAAI,SAAe,YAAY;GACrC,OAAO,YAAY,QAAQ,CAAC;GAC5B,IAAI,OAAO,OAAO,oBAAoB;QACjC,OAAO,qBAAqB;EAClC,CAAC;CACF;CAKA,cAA0B;EACzB,IAAI,KAAKa,aAAa,GAAG,KAAKQ,WAAAA,GAAU,iBAAA,YAAA,CAAY;EACpD,KAAKR,YAAY;EACjB,IAAI,WAAW;EACf,aAAa;GACZ,IAAI,UAAU;GACd,WAAW;GACX,KAAKA,YAAY;GACjB,IAAI,KAAKA,aAAa,GAAG,KAAKQ,QAAQ,MAAM;EAC7C;CACD;CAIA,MAAMT,cAAc,QAAoC;EACvD,IAAI,KAAKC,aAAa,KAAK,OAAO,SAAS;EAC3C,OAAA,GAAM,YAAA,KAAA,CAAK,YAAY,IAAI,CAAC,QAAQ,KAAKQ,QAAQ,MAAM,CAAC,GAAG,OAAO;CACnE;AACD;;;;;;;;;;;;;;;;;;;;;;ACtbA,SAAgB,mBAAwC;CACvD,OAAO,IAAI,WAAW;AACvB;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aAAqB,SAAyD;CAC7F,OAAO,IAAI,OAAO,OAAO;AAC1B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["#dispatcher","#state","#middleware","#upgradeHandlers","#emitter","#host","#configuredPort","#drain","#limit","#expose","#report","#timeouts","#sockets","#status","#port","#abort","#handle","#onUpgrade","#http","#listen","#drainPending","#pending","#close","#trackStart","#accept","#respond","#boundary","#createBody","#resolvePort","#wakeup"],"sources":["../../../src/server/constants.ts","../../../src/server/errors.ts","../../../src/server/helpers.ts","../../../src/server/Negotiator.ts","../../../src/server/Server.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { Encoding } from './types.js'\n\n// The substrate's tunable defaults (AGENTS §5 constants file) — only the\n// constants with a real consumer inside THIS package (AGENTS §21: build\n// against a concrete consumer, not speculatively). Frozen so a consumer can\n// read but never mutate the shared default. Middleware-package-only defaults\n// (rate limiting, CSRF, sessions, static serving, multipart — Appendix A of\n// the proposal) stay OUT of this file; they belong to that package's own\n// `constants.ts`.\n\n/** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */\nexport const DEFAULT_DRAIN_MS = 10_000\n\n/**\n * The `Symbol.for`-keyed brand `HTTPError` carries so `isHTTPError` recognizes\n * an instance thrown by ANOTHER copy of this package (the dual-package\n * hazard — a version-skewed or workspace-linked duplicate install), where\n * `instanceof` alone fails because the two copies' `HTTPError` constructors\n * are distinct objects.\n *\n * @remarks\n * `Symbol.for` interns the symbol on the GLOBAL symbol registry, so every\n * copy of this package that evaluates this key resolves the SAME symbol\n * instance — unlike a locally-scoped `Symbol()`, which would mint a fresh,\n * unequal symbol per copy and defeat the whole point of a cross-copy brand.\n */\nexport const HTTP_ERROR_BRAND = Symbol.for('@orkestrel/server.HTTPError')\n\n/** Default maximum request body size (bytes) `readBody` accepts before a 413. */\nexport const DEFAULT_BODY_LIMIT = 1_048_576\n\n/**\n * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap\n * the body pipeline's byte-counting `TransformStream` enforces when\n * transparently decompressing a `Content-Encoding` request body.\n *\n * @remarks\n * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)\n * can inflate by many orders of magnitude — a classic decompression bomb.\n * Capping the decompressed byte count makes the pipe ABORT the moment the\n * output would exceed this, BEFORE the full bomb is materialized, so the\n * inflation can never exhaust memory. Defaults to `16 MiB` — a generous\n * ceiling for a legitimate compressed JSON / form body, far below an OOM. A\n * consumer raises it via {@link import('./types.js').BodyOptions}\n * `decompression` for a workload that genuinely ships larger decompressed\n * bodies.\n */\nexport const DEFAULT_DECOMPRESSED_LIMIT = 16_777_216\n\n/**\n * The SSE response headers the `openStream` seam always sets.\n *\n * @remarks\n * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`\n * keeps a proxy from caching the stream; `keep-alive` holds the connection\n * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so\n * events flush promptly rather than batching. Frozen so a consumer can read\n * but never mutate the shared default; `openStream` merges any\n * {@link import('./types.js').StreamOptions.headers} UNDER these.\n */\nexport const SSE_HEADERS: Readonly<Record<string, string>> = Object.freeze({\n\t'Content-Type': 'text/event-stream; charset=utf-8',\n\t'Cache-Control': 'no-cache',\n\tConnection: 'keep-alive',\n\t'X-Accel-Buffering': 'no',\n})\n\n/**\n * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`\n * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized\n * / control-char-bearing incoming id is REJECTED (a fresh id is minted\n * instead) rather than ever riding into a response header or `context.state`\n * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const REQUEST_ID_PATTERN: Readonly<RegExp> = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/)\n\n/**\n * The set of bare `Content-Type`s `isCompressibleType` treats as\n * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /\n * `+xml`) rules that helper also applies.\n *\n * @remarks\n * The text-shaped application types worth compressing (JSON / JavaScript /\n * XML / SVG / WASM / a few document formats) — NOT already-compressed\n * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's\n * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads\n * but never mutates the shared default.\n */\nexport const COMPRESSIBLE_TYPES: ReadonlySet<string> = new Set([\n\t'application/json',\n\t'application/javascript',\n\t'application/xml',\n\t'application/xhtml+xml',\n\t'application/rss+xml',\n\t'application/atom+xml',\n\t'application/ld+json',\n\t'application/manifest+json',\n\t'application/vnd.api+json',\n\t'application/wasm',\n\t'image/svg+xml',\n\t'application/pdf',\n])\n\n/**\n * The default {@link Encoding} content-codings the substrate offers, in\n * PREFERENCE order — `gzip` / `deflate`.\n *\n * @remarks\n * `identity` (no compression) is always implicitly acceptable and is NOT\n * listed here — it is the fall-through when a client accepts none of these.\n * Brotli is omitted per the core's `CompressionStream`-only decision (see\n * {@link Encoding}). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const DEFAULT_ENCODINGS: readonly Encoding[] = Object.freeze(['gzip', 'deflate'])\n","// AGENTS §12: a handler signals a client-facing fault by throwing an\n// `HTTPError` carrying the HTTP `status` to send; the server's error boundary\n// (§5.3 of the proposal) turns it into a response of that status. Any OTHER\n// throw is a programmer/runtime error → a 500 (its message hidden unless\n// `expose`). The machine-readable field here is the numeric `status` (plus an\n// optional `context` bag) — `MultipartError` is NOT ported here: it moves to\n// the future `@orkestrel/middleware` package with its owner (`createMultipart`).\n//\n// Dual-package hazard: `instanceof HTTPError` fails when the thrown value was\n// constructed by a DIFFERENT copy of this package (version skew, a linked\n// workspace) — the two copies' `HTTPError` constructors are distinct objects\n// even though they are structurally identical. `isHTTPError` therefore tries\n// `instanceof` first (the common, cheap case) and falls back to a total\n// structural check keyed by a `Symbol.for`-interned brand (`HTTP_ERROR_BRAND`,\n// shared across every copy via the global symbol registry) plus the exact\n// fields the server's boundary reads off a recognized error (`status`,\n// `message`) — so a foreign-copy instance the guard accepts can never crash\n// the boundary that trusts it.\n\nimport { isNumber, isString } from '@orkestrel/contract'\nimport { HTTP_ERROR_BRAND } from './constants.js'\n\n/**\n * An error a handler (or middleware) throws to produce an HTTP response of a\n * specific status.\n *\n * @remarks\n * Carries the HTTP `status` to send and an optional `context` record (the\n * offending field / value). The server's built-in error boundary catches it\n * and renders a response of `status` with the error's `message` as the body\n * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's\n * deliberate signal), unlike a generic throw whose message is hidden unless\n * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for\n * specific statuses, or throw it directly. Narrow a caught value with\n * {@link isHTTPError}.\n *\n * @example\n * ```ts\n * import { HTTPError } from '@src/server'\n *\n * const handler = async (request: Request): Promise<Response> => {\n * \tconst user = await find(new URL(request.url).searchParams.get('id'))\n * \tif (user === undefined) throw new HTTPError(404, 'user not found')\n * \treturn Response.json(user)\n * }\n * ```\n */\nexport class HTTPError extends Error {\n\treadonly status: number\n\treadonly context?: Readonly<Record<string, unknown>>\n\t// The cross-copy brand (AGENTS §12 / dual-package hazard) — `isHTTPError`\n\t// reads it structurally when `instanceof` fails across package copies.\n\t// Not a public field to set by hand: the constructor is the only writer.\n\treadonly [HTTP_ERROR_BRAND] = true\n\n\tconstructor(status: number, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tthis.name = 'HTTPError'\n\t\tthis.status = status\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * The {@link HTTPError} thrown when a request body exceeds the body\n * pipeline's size limit — a `413 Content Too Large`.\n *\n * @remarks\n * Thrown by `readBody` (and the middleware context's cached `body()`) when\n * the received bytes exceed the configured {@link\n * import('./types.js').BodyOptions.limit}, carrying the `limit` in its\n * `context`. The server's error boundary renders it as a 413.\n *\n * @example\n * ```ts\n * import { ContentTooLargeError, isHTTPError } from '@src/server'\n *\n * try {\n * \tawait readBody(request, { limit: 1024 })\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status) // 413\n * }\n * ```\n */\nexport class ContentTooLargeError extends HTTPError {\n\tconstructor(limit: number) {\n\t\tsuper(413, `request body exceeds the ${limit}-byte limit`, { limit })\n\t\tthis.name = 'ContentTooLargeError'\n\t}\n}\n\n/**\n * Narrow an unknown caught value to an {@link HTTPError} (including its\n * subclasses, e.g. {@link ContentTooLargeError}).\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link HTTPError}\n *\n * @remarks\n * Tries `instanceof` first, then falls back to a total structural check for\n * an instance built by a DIFFERENT copy of this package (the dual-package\n * hazard — version skew, a linked workspace duplicate) whose `HTTPError`\n * constructor is a distinct object from this copy's: the value must carry\n * the cross-copy brand (interned via `Symbol.for`, so every copy resolves the\n * same key) AND expose the exact fields the server's error boundary reads off\n * a recognized `HTTPError` — a numeric `status` and a string `message`. A\n * plain object that merely carries a `status` WITHOUT the brand is rejected.\n *\n * @example\n * ```ts\n * import { isHTTPError } from '@src/server'\n *\n * try {\n * \tawait handle(request)\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status, error.message)\n * }\n * ```\n */\nexport function isHTTPError(value: unknown): value is HTTPError {\n\tif (value instanceof HTTPError) return true\n\tif (typeof value !== 'object' || value === null) return false\n\tif (!(HTTP_ERROR_BRAND in value) || value[HTTP_ERROR_BRAND] !== true) return false\n\tif (!('status' in value) || !('message' in value)) return false\n\treturn isNumber(value.status) && isString(value.message)\n}\n","import type { AddressInfo } from 'node:net'\nimport type {\n\tAcceptEntry,\n\tBodyOptions,\n\tCookieOptions,\n\tEncoding,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tRangeSpec,\n\tSSEMessage,\n\tStreamInterface,\n\tStreamOptions,\n\tTokenOptions,\n\tTokenSecret,\n} from './types.js'\nimport { once } from 'node:events'\nimport { createServer as createNetServer } from 'node:net'\nimport { isNumber, isRecord, isString, parseJSON } from '@orkestrel/contract'\nimport {\n\tCOMPRESSIBLE_TYPES,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DECOMPRESSED_LIMIT,\n\tREQUEST_ID_PATTERN,\n\tSSE_HEADERS,\n} from './constants.js'\nimport { ContentTooLargeError, HTTPError } from './errors.js'\n\n// The middleware seam's composition engine (AGENTS §5 — a pure function, not a\n// class: `compose` has no instance state, so it lives here rather than as an\n// entity). The RETURNING onion (§5.1 of the proposal): each middleware may\n// transform the request (`next(newRequest)`), transform the response (`await\n// next()` then mutate the result), or short-circuit (return without calling\n// `next`) — no mutable framework object anywhere. The double-`next` guard\n// (calling `next` twice within one middleware invocation) rejects, preserving\n// the old spine's crown-jewel invariant that each link runs the chain at most\n// once.\n\n/**\n * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`\n * handler into one request handler — the frozen middleware seam (§5.1).\n *\n * @remarks\n * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`\n * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes\n * `terminal`. Each middleware's `next` may be called with a substituted\n * `Request` (the downstream chain then sees that request instead of the\n * original), called with no argument (the original request continues\n * downstream), or NOT called at all (a short-circuit — the middleware's own\n * returned `Response` is sent, and everything downstream never runs). A\n * SECOND call to the same `next` within one middleware invocation REJECTS —\n * each link runs the chain at most once, so a middleware cannot fork the\n * request into two divergent downstream runs.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param middleware - The ordered chain, outermost first\n * @param terminal - The innermost handler the chain ultimately reaches\n * @returns A single `(request, context) => Promise<Response>` handler running the whole onion\n *\n * @example\n * ```ts\n * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {\n * \tconst response = await next()\n * \tresponse.headers.set('X-Powered-By', 'orkestrel')\n * \treturn response\n * }\n *\n * const handle = compose([withHeader], async () => new Response('ok'))\n * ```\n */\nexport function compose<TState>(\n\tmiddleware: readonly MiddlewareHandler<TState>[],\n\tterminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\treturn middleware.reduceRight<\n\t\t(request: Request, context: MiddlewareContext<TState>) => Promise<Response>\n\t>((next, layer) => wrapMiddleware(layer, next), terminal)\n}\n\n/**\n * Wrap one middleware layer around its downstream handler.\n *\n * @remarks\n * The returned handler enforces the one-call `next` invariant while preserving\n * request substitution and the middleware's synchronous or asynchronous result.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param layer - The middleware layer to invoke\n * @param next - The downstream handler wrapped by `layer`\n * @returns A handler with `layer` composed around `next`\n *\n * @example\n * ```ts\n * const handle = wrapMiddleware(\n * \tasync (_request, _context, next) => next(),\n * \tasync () => new Response('ok'),\n * )\n * ```\n */\nexport function wrapMiddleware<TState>(\n\tlayer: MiddlewareHandler<TState>,\n\tnext: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\treturn async (request: Request, context: MiddlewareContext<TState>): Promise<Response> => {\n\t\tlet called = false\n\t\treturn Promise.resolve(\n\t\t\tlayer(request, context, (nextRequest?: Request): Promise<Response> => {\n\t\t\t\tif (called) return Promise.reject(new Error('next() was already called by this middleware'))\n\t\t\t\tcalled = true\n\t\t\t\treturn next(nextRequest ?? request, context)\n\t\t\t}),\n\t\t)\n\t}\n}\n\n// The cookie machinery (AGENTS §4.3 module-scope helpers) — `parseCookies`\n// decodes a raw `Cookie:` header into a name→value lookup; `serializeCookie`\n// builds a spec-shaped `Set-Cookie` value with its attributes. The SIGNED\n// pair reuses the shipped HMAC token primitives rather than a second HMAC\n// scheme: `writeSignedCookie` is `serializeCookie(name, await signToken(value,\n// { secret }))` appended to a `Headers`, and `readSignedCookie` is `await\n// verifyToken(parseCookies(...)[name], secret)` — so a cookie is just a\n// `signToken` value in a `Set-Cookie`, with the SAME secret rotation + tamper\n// rejection. Every reader narrows untrusted request input with `typeof`,\n// never `as` (§14), and total on hostile input.\n\n/**\n * Parse a raw `Cookie:` request header into a `name → value` lookup.\n *\n * @remarks\n * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine\n * cookie-pair separator never precedes it), while every later segment has its\n * inter-pair separator (ASCII space/tab) stripped before parsing — so a\n * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by\n * {@link isCookieName} rather than silently reconciling into a\n * prefix-protected `__Host-` name. A pair without `=`, or with an invalid\n * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/\n * malformed header yields an empty record, never throws (AGENTS §14).\n *\n * @param header - The raw `Cookie` header value (possibly `undefined`)\n * @returns A record of every parsed cookie, `name → decoded value`\n *\n * @example\n * ```ts\n * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }\n * ```\n */\nexport function parseCookies(header: string | undefined): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tif (header === undefined) return out\n\tconst segments = header.split(';')\n\tfor (let index = 0; index < segments.length; index += 1) {\n\t\tconst raw = segments[index] ?? ''\n\t\tconst segment = index === 0 ? raw : raw.replace(/^[ \\t]+/, '')\n\t\tconst eq = segment.indexOf('=')\n\t\tif (eq < 0) continue\n\t\tconst name = segment.slice(0, eq)\n\t\tif (!isCookieName(name)) continue\n\t\tout[name] = decodeCookieValue(segment.slice(eq + 1).trim())\n\t}\n\treturn out\n}\n\n/**\n * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of\n * cookie-token chars with NO surrounding (or interior) whitespace.\n *\n * @remarks\n * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$` —\n * which excludes every whitespace char (ASCII and Unicode) plus controls,\n * separators, and `=`. The {@link parseCookies} hardening that stops a\n * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.\n *\n * @param value - The candidate cookie name\n * @returns `true` when `value` is a valid, whitespace-free cookie token\n *\n * @example\n * ```ts\n * isCookieName('__Host-session') // true\n * isCookieName(' __Host-session') // false — whitespace-padded\n * ```\n */\nexport function isCookieName(value: string): boolean {\n\treturn /^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$/.test(value)\n}\n\n/**\n * Decode a cookie value with `decodeURIComponent`, falling back to the raw\n * text when the value is not valid percent-encoding.\n *\n * @param raw - The raw (trimmed) cookie value\n * @returns The URL-decoded value, or the raw value when decoding would throw\n *\n * @example\n * ```ts\n * decodeCookieValue('a%20b') // 'a b'\n * decodeCookieValue('%') // '%' — malformed escape stays literal\n * ```\n */\nexport function decodeCookieValue(raw: string): string {\n\ttry {\n\t\treturn decodeURIComponent(raw)\n\t} catch {\n\t\treturn raw\n\t}\n}\n\n/**\n * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE\n * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two\n * attributes with before emitting them.\n *\n * @remarks\n * Rejects a value carrying a `;` (splits attributes), a `,` (can split a\n * folded header), ASCII/Unicode whitespace, or a C0/DEL control char\n * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`\n * directive. Total — never throws (a bad value returns `false`).\n *\n * @param value - The candidate attribute value (a `Domain` or `Path`)\n * @returns `true` when `value` carries no separator / whitespace / control char\n *\n * @example\n * ```ts\n * isCookieAttribute('/app') // true\n * isCookieAttribute('/a\\r\\nSet-Cookie: x=y') // false\n * ```\n */\nexport function isCookieAttribute(value: string): boolean {\n\tfor (const char of value) {\n\t\tif (char === ';' || char === ',' || /\\s/.test(char)) return false\n\t\tconst code = char.codePointAt(0)\n\t\tif (code !== undefined && (code < 0x20 || code === 0x7f)) return false\n\t}\n\treturn true\n}\n\n/**\n * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.\n *\n * @remarks\n * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and\n * appends the present {@link CookieOptions} attributes in canonical order:\n * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`\n * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated\n * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an\n * injection attempt (a programmer misconfiguration, AGENTS §12 — never a\n * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of\n * the `secure` option (the spec requires it); an un-resolved `undefined`\n * `secure` here falls to OFF — request-aware callers resolve it first via\n * {@link resolveSecure}.\n *\n * @param name - The cookie name\n * @param value - The cookie value (URL-encoded into the output)\n * @param options - The {@link CookieOptions} attributes; see its fields for defaults\n * @returns The `Set-Cookie` header value\n * @throws {HTTPError} When `domain` or `path` carries an injection char\n *\n * @example\n * ```ts\n * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'\n * ```\n */\nexport function serializeCookie(name: string, value: string, options?: CookieOptions): string {\n\tconst sameSite = options?.sameSite ?? 'Lax'\n\tconst domain = options?.domain\n\tif (domain !== undefined && !isCookieAttribute(domain))\n\t\tthrow new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`)\n\tconst path = options?.path ?? '/'\n\tif (!isCookieAttribute(path))\n\t\tthrow new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`)\n\tconst secure = sameSite === 'None' || options?.secure === true\n\tconst parts = [`${name}=${encodeURIComponent(value)}`]\n\tif (domain !== undefined) parts.push(`Domain=${domain}`)\n\tparts.push(`Path=${path}`)\n\tif (options?.maxAge !== undefined) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`)\n\tif (options?.httpOnly !== false) parts.push('HttpOnly')\n\tif (secure) parts.push('Secure')\n\tparts.push(`SameSite=${sameSite}`)\n\treturn parts.join('; ')\n}\n\n/**\n * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}\n * `secure` setting and whether the request arrived over TLS.\n *\n * @remarks\n * `true` / `false` are explicit overrides. `undefined` (the secure default —\n * the option omitted) resolves to `encrypted` — `Secure` on a TLS\n * connection, off over plaintext HTTP — so a production HTTPS deployment\n * gets `Secure` automatically while local-dev HTTP still works.\n *\n * @param secure - The {@link CookieOptions} `secure` setting\n * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})\n * @returns The concrete `Secure` flag to emit\n *\n * @example\n * ```ts\n * resolveSecure(undefined, true) // true\n * resolveSecure(undefined, false) // false\n * resolveSecure(false, true) // false — explicit override wins\n * ```\n */\nexport function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean {\n\tif (secure === true || secure === false) return secure\n\treturn encrypted\n}\n\n/**\n * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT\n * clobbering a prior one.\n *\n * @remarks\n * `Headers.append` already accumulates repeated headers (unlike node's\n * `setHeader`), so this is a thin, self-documenting wrapper naming the\n * cookie-append intent — the primitive {@link writeSignedCookie} /\n * {@link clearCookie} use.\n *\n * @param headers - The response `Headers` to write into\n * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * appendCookie(headers, serializeCookie('a', '1'))\n * appendCookie(headers, serializeCookie('b', '2'))\n * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'\n * ```\n */\nexport function appendCookie(headers: Headers, cookie: string): void {\n\theaders.append('set-cookie', cookie)\n}\n\n/**\n * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append\n * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).\n *\n * @remarks\n * The cookie value is `await signToken(value, { secret })`\n * (`<payload>.<signature>`), so a signed cookie is a stateless token in a\n * cookie — the same secret rotation and tamper rejection, no second HMAC\n * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto\n * signing is asynchronous (§3 of the proposal).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name\n * @param value - The opaque value to sign into the cookie\n * @param secret - The {@link TokenSecret} to sign with (the first secret signs)\n * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * await writeSignedCookie(headers, 'session', 'user-1', 'secret')\n * ```\n */\nexport async function writeSignedCookie(\n\theaders: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: TokenSecret,\n\toptions?: CookieOptions,\n): Promise<void> {\n\tappendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options))\n}\n\n/**\n * Read + verify a SIGNED cookie off a request — TOTAL, returning the\n * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).\n *\n * @remarks\n * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,\n * and verifies it with {@link verifyToken} against `secret` (a rotation list\n * accepts a cookie signed by any of its secrets). ANY failure — an absent\n * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.\n *\n * @param request - The `Request` to read the `Cookie` header from\n * @param name - The cookie name to read\n * @param secret - The {@link TokenSecret} (or rotation list) to verify against\n * @returns The embedded value when the cookie is present + valid, else `undefined`\n *\n * @example\n * ```ts\n * const value = await readSignedCookie(request, 'session', 'secret')\n * ```\n */\nexport async function readSignedCookie(\n\trequest: Request,\n\tname: string,\n\tsecret: TokenSecret,\n): Promise<string | undefined> {\n\tconst cookie = parseCookies(request.headers.get('cookie') ?? undefined)[name]\n\treturn cookie === undefined ? undefined : verifyToken(cookie, secret)\n}\n\n/**\n * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).\n *\n * @remarks\n * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the\n * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops\n * a cookie when those MATCH the one it set).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name to clear\n * @param options - The {@link CookieOptions} that must match the original cookie\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * clearCookie(headers, 'session')\n * ```\n */\nexport function clearCookie(headers: Headers, name: string, options?: CookieOptions): void {\n\tappendCookie(headers, serializeCookie(name, '', { ...options, maxAge: 0 }))\n}\n\n// The stateless signed-token primitives over WebCrypto (AGENTS §4.3 module-\n// scope helpers, §3 of the proposal). A token is `<payload>.<signature>`: the\n// payload a base64url JSON `{ value, exp? }`, the signature an HMAC-SHA256 of\n// the payload under the secret. Signing always uses the FIRST secret (a\n// rotation list's current head); verifying accepts ANY secret in the list,\n// via `crypto.subtle.verify` — constant-time internally, so the old\n// `safeCompare` is RETIRED, never ported. `verifyToken` is TOTAL (never\n// throws — adversarial input returns `undefined`, AGENTS §14); only\n// `signToken` throws, and only on a misconfigured (empty) secret.\n\n/**\n * Base64url-encode a byte sequence — the payload encoding {@link signToken} /\n * {@link verifyToken} use, and the signature encoding for the HMAC.\n *\n * @param bytes - The bytes to encode\n * @returns The base64url string (no padding)\n *\n * @example\n * ```ts\n * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'\n * ```\n */\nexport function encodeBase64Url(bytes: Uint8Array): string {\n\tlet binary = ''\n\tfor (const byte of bytes) binary += String.fromCharCode(byte)\n\treturn btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Decode a base64url string back into its bytes — the inverse of\n * {@link encodeBase64Url}.\n *\n * @remarks\n * Restores the standard base64 alphabet + padding before decoding with\n * `atob`. THROWS `DOMException` on a malformed input — callers on the\n * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).\n *\n * @param value - The base64url string to decode\n * @returns The decoded bytes\n * @throws {DOMException} When `value` is not valid base64url\n *\n * @example\n * ```ts\n * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'\n * ```\n */\nexport function decodeBase64Url(value: string): Uint8Array<ArrayBuffer> {\n\tconst restored = value.replace(/-/g, '+').replace(/_/g, '/')\n\tconst padding = restored.length % 4 === 0 ? '' : '='.repeat(4 - (restored.length % 4))\n\tconst binary = atob(restored + padding)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)\n\treturn bytes\n}\n\n/**\n * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.\n *\n * @remarks\n * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the\n * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so\n * the expiry is HMAC-COVERED — a client cannot extend it without invalidating\n * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST\n * {@link TokenSecret} (the current secret, or the head of a rotation list).\n * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a\n * misconfigured secret with no usable entry THROWS an {@link HTTPError}\n * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with\n * {@link verifyToken}. Omitting `ttl` mints a token that never expires.\n *\n * @param value - The opaque value to embed (a session id, a deployment marker)\n * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}\n * @returns The signed `<payload>.<signature>` token string\n * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry\n *\n * @example\n * ```ts\n * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })\n * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined\n * ```\n */\nexport async function signToken(value: string, options: TokenOptions): Promise<string> {\n\tconst secrets = normalizeSecret(options.secret)\n\tconst secret = secrets[0]\n\tif (secret === undefined) throw new HTTPError(500, 'signToken requires at least one secret')\n\tconst exp = options.ttl !== undefined ? Date.now() + options.ttl : undefined\n\tconst encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({ value, exp })))\n\tconst key = await crypto.subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(secret),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign'],\n\t)\n\tconst signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(encoded))\n\treturn `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`\n}\n\n/**\n * Verify a stateless token and return its embedded value — TOTAL, never throws.\n *\n * @remarks\n * The inverse of {@link signToken}: splits the token on its LAST `.` (so a\n * value containing dots survives), and checks the payload's HMAC-SHA256\n * signature against EACH {@link TokenSecret} candidate via\n * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is\n * retired, §3 of the proposal), accepting the token on the first match (the\n * rotation path). It then decodes + narrows the payload (`isRecord` +\n * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,\n * rejects an expired token. ANY failure — a malformed token, a bad signature,\n * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —\n * yields `undefined` rather than throwing.\n *\n * @param token - The candidate token string (from a request header/cookie)\n * @param secret - The {@link TokenSecret} (or rotation list) to verify against\n * @returns The embedded value when the token is valid + unexpired, else `undefined`\n *\n * @example\n * ```ts\n * await verifyToken('bad.token', 'shh') // undefined — never throws\n * ```\n */\nexport async function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined> {\n\tconst secrets = normalizeSecret(secret)\n\tif (secrets.length === 0) return undefined\n\tconst dot = token.lastIndexOf('.')\n\tif (dot < 0) return undefined\n\tconst encoded = token.slice(0, dot)\n\tconst signatureText = token.slice(dot + 1)\n\ttry {\n\t\tconst signature = decodeBase64Url(signatureText)\n\t\tconst data = new TextEncoder().encode(encoded)\n\t\tfor (const candidate of secrets) {\n\t\t\tconst key = await crypto.subtle.importKey(\n\t\t\t\t'raw',\n\t\t\t\tnew TextEncoder().encode(candidate),\n\t\t\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\t\t\tfalse,\n\t\t\t\t['verify'],\n\t\t\t)\n\t\t\tconst matched = await crypto.subtle.verify('HMAC', key, signature, data)\n\t\t\tif (matched) return decodeTokenPayload(encoded)\n\t\t}\n\t\treturn undefined\n\t} catch {\n\t\t// A malformed base64url signature/payload is just an invalid token — stay total.\n\t\treturn undefined\n\t}\n}\n\n/**\n * Decode + narrow a signed token's base64url JSON payload, honoring its\n * expiry — the shared decode step {@link verifyToken} applies after a\n * signature match.\n *\n * @remarks\n * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a\n * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.\n * TOTAL — any decode/shape/expiry failure yields `undefined`.\n *\n * @param encoded - The base64url-encoded payload segment (before the last `.`)\n * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`\n */\nexport function decodeTokenPayload(encoded: string): string | undefined {\n\ttry {\n\t\tconst text = new TextDecoder().decode(decodeBase64Url(encoded))\n\t\tconst payload: unknown = JSON.parse(text)\n\t\tif (!isRecord(payload)) return undefined\n\t\tif (typeof payload.value !== 'string') return undefined\n\t\tif (payload.exp !== undefined && typeof payload.exp !== 'number') return undefined\n\t\tif (payload.exp !== undefined && Date.now() >= payload.exp) return undefined\n\t\treturn payload.value\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —\n * backs both {@link signToken} and {@link verifyToken}.\n *\n * @remarks\n * A single string becomes a one-element list; a rotation list is copied. Any\n * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that\n * emptiness test; each kept secret is stored VERBATIM). The first kept\n * element is the signing secret; all kept are accepted on verify.\n *\n * @param secret - The {@link TokenSecret} (a single string, or a rotation list)\n * @returns The kept (non-blank) secrets, in order — empty when none is usable\n *\n * @example\n * ```ts\n * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']\n * ```\n */\nexport function normalizeSecret(secret: TokenSecret): readonly string[] {\n\tconst list = typeof secret === 'string' ? [secret] : [...secret]\n\treturn list.filter((entry) => entry.trim().length > 0)\n}\n\n// The content-negotiation helpers (AGENTS §4.3 module-scope, §5) — the ONE\n// shared q-value parser behind the `Negotiator` (U3) and any future\n// compression middleware's `Accept-Encoding` pick.\n\n/**\n * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header\n * into its q-sorted entries.\n *\n * @remarks\n * Splits on `,`; for each part takes the token before the first `;`\n * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the\n * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls\n * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must\n * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving\n * the header's own order within a tie — a single pass with no backtracking,\n * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an\n * empty/malformed header yields `[]`/best-effort entries, never throws.\n *\n * @param header - The raw weighted header value\n * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending\n *\n * @example\n * ```ts\n * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')\n * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]\n * ```\n */\nexport function parseAcceptHeader(header: string): readonly AcceptEntry[] {\n\tconst entries: AcceptEntry[] = []\n\tfor (const part of header.split(',')) {\n\t\tconst trimmed = part.trim()\n\t\tif (trimmed.length === 0) continue\n\t\tconst semicolon = trimmed.indexOf(';')\n\t\tconst value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase()\n\t\tif (value.length === 0) continue\n\t\tlet q = 1\n\t\tif (semicolon !== -1) {\n\t\t\tconst match = /;\\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon))\n\t\t\tif (match !== null) {\n\t\t\t\tconst parsed = Number(match[1])\n\t\t\t\tif (Number.isFinite(parsed)) q = Math.min(1, Math.max(0, parsed))\n\t\t\t}\n\t\t}\n\t\tentries.push({ value, q })\n\t}\n\treturn entries\n\t\t.map((entry, index) => ({ entry, index }))\n\t\t.sort((a, b) => b.entry.q - a.entry.q || a.index - b.index)\n\t\t.map((ranked) => ranked.entry)\n}\n\n/**\n * The client's quality (q) for one content-coding from the parsed\n * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s\n * server-preference selection.\n *\n * @remarks\n * Prefers an EXACT named match (including an explicit `;q=0` rejection);\n * failing that, a bare `*` wildcard's q applies. A coding that is neither\n * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins\n * over a `*` (a specific rejection beats the wildcard), so it scores `0`.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param coding - The candidate coding to score\n * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5\n * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1\n * ```\n */\nexport function codingQuality(entries: readonly AcceptEntry[], coding: string): number {\n\tconst named = entries.find((entry) => entry.value === coding)\n\tif (named !== undefined) return named.q\n\tconst wildcard = entries.find((entry) => entry.value === '*')\n\treturn wildcard?.q ?? 0\n}\n\n/**\n * Select the best content-coding for an `Accept-Encoding` header from the\n * codings the server offers.\n *\n * @remarks\n * Parses the header ({@link parseAcceptHeader}) and scores each `available`\n * coding in the SERVER's preference order ({@link codingQuality}), keeping\n * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a\n * client-side tie). Returns `undefined` when the client accepts none of\n * `available` (identity — no compression). TOTAL on hostile input.\n *\n * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)\n * @param header - The raw `Accept-Encoding` header value\n * @param available - The codings the server offers, in preference (tie-break) order\n * @returns The negotiated coding, or `undefined` when none of `available` is acceptable\n *\n * @example\n * ```ts\n * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'\n * ```\n */\nexport function negotiateEncoding<T extends string>(\n\theader: string,\n\tavailable: readonly T[],\n): T | undefined {\n\tif (available.length === 0) return undefined\n\tconst entries = parseAcceptHeader(header)\n\tlet best: T | undefined\n\tlet bestQuality = 0\n\tfor (const coding of available) {\n\t\tconst quality = codingQuality(entries, coding)\n\t\tif (quality > bestQuality) {\n\t\t\tbest = coding\n\t\t\tbestQuality = quality\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * Rank + quality of one `candidate` media type against the parsed `Accept`\n * entries — the generic media-type primitive the `Negotiator`'s `negotiate`\n * uses to score each `available` candidate.\n *\n * @remarks\n * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the\n * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact\n * `;q=0` entry explicitly rejects the candidate outright (returns\n * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own\n * (less specific) coverage, so a later more-specific match can still allow\n * it. Among multiple matching entries, the lowest `rank` wins, and among a\n * rank tie the highest `q` wins.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate media type to score (e.g. `'text/html'`)\n * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches\n *\n * @example\n * ```ts\n * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')\n * // { q: 1, rank: 0 }\n * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }\n * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined\n * ```\n */\nexport function matchMediaType(\n\tentries: readonly AcceptEntry[],\n\tcandidate: string,\n): { readonly q: number; readonly rank: number } | undefined {\n\tconst slash = candidate.indexOf('/')\n\tconst type = slash === -1 ? candidate : candidate.slice(0, slash)\n\tlet best: { readonly q: number; readonly rank: number } | undefined\n\tfor (const entry of entries) {\n\t\tlet rank: number | undefined\n\t\tif (entry.value === candidate) rank = 0\n\t\telse if (entry.value === `${type}/*`) rank = 1\n\t\telse if (entry.value === '*/*') rank = 2\n\t\tif (rank === undefined) continue\n\t\tif (entry.q === 0) {\n\t\t\t// An exact `;q=0` explicitly rejects this candidate outright; a\n\t\t\t// wildcard `;q=0` only rejects the wildcard's own (less specific)\n\t\t\t// coverage, so a later more-specific match can still allow it.\n\t\t\tif (rank === 0) return undefined\n\t\t\tcontinue\n\t\t}\n\t\tif (best === undefined || rank < best.rank || (rank === best.rank && entry.q > best.q)) {\n\t\t\tbest = { q: entry.q, rank }\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * The client's quality for one `candidate` language from the parsed\n * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.\n *\n * @remarks\n * Prefers an exact match, then a primary-tag prefix match (`en` accepts\n * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry\n * is an explicit rejection).\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate language tag to score (e.g. `'en-US'`)\n * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1\n * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix\n * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard\n * ```\n */\nexport function languageQuality(entries: readonly AcceptEntry[], candidate: string): number {\n\tconst lower = candidate.toLowerCase()\n\tconst primary = lower.split('-')[0]\n\tlet named: number | undefined\n\tlet prefixed: number | undefined\n\tlet wildcard: number | undefined\n\tfor (const entry of entries) {\n\t\tconst entryPrimary = entry.value.split('-')[0]\n\t\tif (entry.value === lower) named = entry.q\n\t\telse if (entryPrimary === primary) {\n\t\t\tif (prefixed === undefined) prefixed = entry.q\n\t\t} else if (entry.value === '*') wildcard = entry.q\n\t}\n\tif (named !== undefined) return named\n\tif (prefixed !== undefined) return prefixed\n\treturn wildcard ?? 0\n}\n\n/**\n * Whether a `Content-Type` is worth compressing.\n *\n * @remarks\n * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`\n * type, a `+json`/`+xml` structured suffix, or one of the explicit\n * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed\n * binary (`image/png`, `application/zip`) is NOT compressible. An\n * absent/empty type is not compressible. TOTAL.\n *\n * @param type - The response `Content-Type` header value (with or without parameters)\n * @returns `true` when the type is text-shaped and worth compressing\n *\n * @example\n * ```ts\n * isCompressibleType('application/json; charset=utf-8') // true\n * isCompressibleType('image/png') // false\n * ```\n */\nexport function isCompressibleType(type: string): boolean {\n\tconst semicolon = type.indexOf(';')\n\tconst bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase()\n\tif (bare.length === 0) return false\n\tif (bare.startsWith('text/')) return true\n\tif (bare.endsWith('+json') || bare.endsWith('+xml')) return true\n\treturn COMPRESSIBLE_TYPES.has(bare)\n}\n\n// The conditional-request helpers (AGENTS §4.3 module-scope, §5) — ETag\n// compute/compare (RFC 7232 §2.3.2 WEAK comparison) and the TOTAL `Range`\n// parser.\n\n/**\n * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.\n *\n * @remarks\n * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex\n * digest as a WEAK validator (`W/\"<hash>\"`) when `weak` is `true` — the\n * default, encoding-AGNOSTIC, so the tag survives a downstream content\n * re-encoding (gzip) and still matches on revalidation — or a STRONG one\n * (`\"<hash>\"`, byte-identity) when `weak` is `false`.\n *\n * @param body - The full (uncompressed) response body to hash\n * @param weak - `true` for a weak `W/\"…\"` validator (the default), `false` for a strong `\"…\"` one\n * @returns The `ETag` header value\n *\n * @example\n * ```ts\n * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/\"…sha256-hex…\"'\n * ```\n */\nexport async function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak = true): Promise<string> {\n\tconst digest = await crypto.subtle.digest('SHA-256', body)\n\tconst hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(\n\t\t'',\n\t)\n\treturn weak ? `W/\"${hex}\"` : `\"${hex}\"`\n}\n\n/**\n * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque\n * comparison body — the reduction {@link matchesETag} applies to both sides\n * before the RFC 7232 §2.3.2 weak comparison.\n *\n * @param tag - One entity-tag (`W/\"<body>\"` or `\"<body>\"`)\n * @returns The tag with any leading `W/` removed (the quotes preserved)\n *\n * @example\n * ```ts\n * unwrapETag('W/\"abc\"') // '\"abc\"'\n * ```\n */\nexport function unwrapETag(tag: string): string {\n\tconst trimmed = tag.trim()\n\treturn trimmed.startsWith('W/') ? trimmed.slice(2) : trimmed\n}\n\n/**\n * Whether a request's `If-None-Match` header matches a resource's current\n * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.\n *\n * @remarks\n * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY\n * listed tag matches), or the `*` wildcard (matches ANY current\n * representation — only a list of exactly `*` is the wildcard). Comparison is\n * WEAK: `W/\"abc\"` and `\"abc\"` are equal (both sides' weak prefix is stripped\n * via {@link unwrapETag} before comparing the opaque body). TOTAL — a\n * malformed/empty header matches nothing, never throws.\n *\n * @param header - The raw `If-None-Match` header value\n * @param etag - The resource's current `ETag`\n * @returns `true` when the conditional matches (the caller answers `304`)\n *\n * @example\n * ```ts\n * matchesETag('\"abc\", W/\"def\"', 'W/\"abc\"') // true — weak comparison\n * matchesETag('*', 'W/\"anything\"') // true — wildcard\n * ```\n */\nexport function matchesETag(header: string, etag: string): boolean {\n\tconst trimmed = header.trim()\n\tif (trimmed === '*') return true\n\tconst target = unwrapETag(etag)\n\tfor (const member of trimmed.split(',')) {\n\t\tconst candidate = member.trim()\n\t\tif (candidate.length === 0) continue\n\t\tif (unwrapETag(candidate) === target) return true\n\t}\n\treturn false\n}\n\n/**\n * Parse an HTTP `Range` request header against a known resource `size` —\n * TOTAL, returning a {@link RangeSpec} or `undefined`.\n *\n * @remarks\n * Handles the three single-range `bytes=` forms — closed (`start-end`), open\n * (`start-`), and suffix (`-suffixLength`) — clamping the window to\n * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns\n * `{ satisfiable: true, start, end }` for an overlapping range,\n * `{ satisfiable: false }` for a range wholly past the resource, and\n * `undefined` for the \"serve the whole resource\" case: an ABSENT header, a\n * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not\n * supported), or any malformed/non-finite bound. NEVER throws on a hostile\n * header.\n *\n * @param header - The raw `Range` header value\n * @param size - The resource's total byte length\n * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource\n *\n * @example\n * ```ts\n * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }\n * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused\n * ```\n */\nexport function parseRange(header: string | undefined, size: number): RangeSpec | undefined {\n\tif (header === undefined) return undefined\n\tconst match = /^bytes=(.*)$/.exec(header.trim())\n\tif (match === null) return undefined\n\tconst capture = match[1]\n\tif (capture === undefined) return undefined\n\tconst spec = capture.trim()\n\tif (spec.includes(',')) return undefined\n\tconst dash = spec.indexOf('-')\n\tif (dash < 0) return undefined\n\tconst startText = spec.slice(0, dash).trim()\n\tconst endText = spec.slice(dash + 1).trim()\n\tif (startText === '') {\n\t\tconst suffix = Number(endText)\n\t\tif (endText === '' || !Number.isInteger(suffix) || suffix <= 0) return undefined\n\t\tif (size === 0) return { satisfiable: false }\n\t\tconst start = Math.max(0, size - suffix)\n\t\treturn { satisfiable: true, start, end: size - 1 }\n\t}\n\tconst start = Number(startText)\n\tif (!Number.isInteger(start) || start < 0) return undefined\n\tif (start >= size) return { satisfiable: false }\n\tif (endText === '') return { satisfiable: true, start, end: size - 1 }\n\tconst end = Number(endText)\n\tif (!Number.isInteger(end) || end < start) return undefined\n\treturn { satisfiable: true, start, end: Math.min(end, size - 1) }\n}\n\n// The security primitives (AGENTS §4.3 module-scope, §5) — CORS origin\n// resolution, `Vary` merging, security-header resolution, request-id\n// validation, and the IPv6 `/64` rate-key collapse.\n\n/**\n * Resolve the `Access-Control-Allow-Origin` value for a request.\n *\n * @remarks\n * `'*'` and a single origin string pass straight through. An allow-list\n * echoes the request's `Origin` only when it is present in the list, else\n * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent\n * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is\n * NEVER reflected even if `'null'` were listed, closing the hostile-context\n * cross-origin-access hole.\n *\n * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list\n * @param requestOrigin - The request's `Origin` header value, if present\n * @returns The allow-origin value to send, or `undefined` to set no header\n *\n * @example\n * ```ts\n * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'\n * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected\n * ```\n */\nexport function resolveOrigin(\n\torigin: string | readonly string[],\n\trequestOrigin: string | undefined,\n): string | undefined {\n\tif (isString(origin)) return origin\n\tif (!isString(requestOrigin)) return undefined\n\tif (requestOrigin === 'null') return undefined\n\treturn origin.includes(requestOrigin) ? requestOrigin : undefined\n}\n\n/**\n * Merge a `Vary` value into an existing `Vary` header without duplication.\n *\n * @remarks\n * Splits `existing` on `,`, trims each member, and appends `value` only when\n * no existing member already matches it case-insensitively (`Vary` header\n * names are case-insensitive). Preserves the existing members' order and\n * appends the new one last.\n *\n * @param existing - The current `Vary` header value, if any\n * @param value - The header name to ensure is listed\n * @returns The merged `Vary` value\n *\n * @example\n * ```ts\n * mergeVary(undefined, 'Origin') // 'Origin'\n * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)\n * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'\n * ```\n */\nexport function mergeVary(existing: string | undefined, value: string): string {\n\tconst members =\n\t\texisting === undefined\n\t\t\t? []\n\t\t\t: existing\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((member) => member.trim())\n\t\t\t\t\t.filter((member) => member.length > 0)\n\tconst present = members.some((member) => member.toLowerCase() === value.toLowerCase())\n\treturn present ? members.join(', ') : [...members, value].join(', ')\n}\n\n/**\n * Resolve one opt-out, value-bearing security header.\n *\n * @remarks\n * The shared \"a `string` value, or `false` to omit, or a default when unset\"\n * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):\n * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that\n * override, `undefined` (unset) ⇒ `fallback` (the secure default).\n *\n * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default\n * @param fallback - The secure-default value used when `value` is unset\n * @returns The header value to set, or `undefined` to omit the header\n *\n * @example\n * ```ts\n * resolveSecurityHeader(undefined, 'DENY') // 'DENY'\n * resolveSecurityHeader(false, 'DENY') // undefined — omitted\n * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override\n * ```\n */\nexport function resolveSecurityHeader(\n\tvalue: string | false | undefined,\n\tfallback: string,\n): string | undefined {\n\tif (value === false) return undefined\n\treturn value ?? fallback\n}\n\n/**\n * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response\n * header + `context.state`.\n *\n * @remarks\n * A request id is echoed RAW into a response header and log lines, so an\n * untrusted one is a header-injection + log-injection + DoS vector. This\n * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}\n * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).\n * TOTAL — never throws.\n *\n * @param value - The candidate incoming request id\n * @returns `true` when `value` is a safe, bounded, charset-clean correlation id\n *\n * @example\n * ```ts\n * isValidRequestId('req_abc-123') // true\n * isValidRequestId('bad\\r\\nheader') // false\n * ```\n */\nexport function isValidRequestId(value: string): boolean {\n\treturn REQUEST_ID_PATTERN.test(value)\n}\n\n/**\n * Compute the `/64` network of a full IPv6 address, or `undefined` when the\n * input is not a plain IPv6 address to collapse.\n *\n * @remarks\n * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4\n * is the identity) or any string that does not expand to exactly eight\n * hextets. Expands a single `::` into the missing zero hextets, takes the\n * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading\n * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped\n * first. Total — a malformed address returns `undefined`.\n *\n * @param address - The candidate IPv6 address\n * @returns The `/64` network string, or `undefined` when not a plain IPv6 address\n *\n * @example\n * ```ts\n * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'\n * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed\n * ```\n */\nexport function ipv6Network(address: string): string | undefined {\n\tif (/^::ffff:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/i.test(address)) return undefined\n\tconst percent = address.indexOf('%')\n\tconst bare = percent === -1 ? address : address.slice(0, percent)\n\tconst halves = bare.split('::')\n\tif (halves.length > 2) return undefined\n\tconst first = halves[0]\n\tif (first === undefined) return undefined\n\tconst second = halves[1]\n\tif (halves.length === 2 && second === undefined) return undefined\n\tconst head = first === '' ? [] : first.split(':')\n\tconst tail = second === undefined || second === '' ? [] : second.split(':')\n\tlet groups: string[]\n\tif (halves.length === 2) {\n\t\tconst missing = 8 - head.length - tail.length\n\t\tif (missing < 0) return undefined\n\t\tgroups = [...head, ...Array.from({ length: missing }, () => '0'), ...tail]\n\t} else {\n\t\tgroups = head\n\t}\n\tif (groups.length !== 8) return undefined\n\tconst prefix: string[] = []\n\tfor (const group of groups.slice(0, 4)) {\n\t\tif (!/^[0-9a-fA-F]{1,4}$/.test(group)) return undefined\n\t\tprefix.push(Number.parseInt(group, 16).toString(16))\n\t}\n\treturn `${prefix.join(':')}::/64`\n}\n\n/**\n * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to\n * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.\n *\n * @remarks\n * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a\n * per-`/128` rate limit is trivially bypassed by rotating host bits — the\n * real identity is the `/64` network. Delegates the IPv6 collapse to\n * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,\n * a malformed string) is kept unchanged.\n *\n * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})\n * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged\n *\n * @example\n * ```ts\n * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'\n * clientRateKey('192.0.2.1') // '192.0.2.1'\n * ```\n */\nexport function clientRateKey(address: string): string {\n\treturn ipv6Network(address) ?? address\n}\n\n// The Server-Sent-Events seam (AGENTS §4.3 module-scope, §5.4 of the\n// proposal) — `serializeEvent` is the wire encoder (the exact inverse of a\n// consuming SSE parser); `openStream` is the generic `Response`-returning\n// stream handle any streaming route (SSE today, a future producer tomorrow)\n// opens over a `ReadableStream`.\n\n/**\n * Serialize one {@link SSEMessage} to the SSE wire.\n *\n * @remarks\n * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE\n * `data:` line per CRLF-aware-split (`\\r\\n` / `\\r` / `\\n`) segment of `data`\n * (so a consuming parser's multi-`data` concat reproduces the original\n * `data` exactly, and no raw `\\r` or `\\n` can ever ride onto the wire inside\n * a `data:` line), then the terminating blank line.\n *\n * @param message - The event to serialize\n * @returns The SSE wire text for the event (terminated by a blank line)\n *\n * @example\n * ```ts\n * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\\ndata: hello\\n\\n'\n * serializeEvent({ data: 'multi\\nline' }) // 'data: multi\\ndata: line\\n\\n'\n * ```\n */\nexport function serializeEvent(message: SSEMessage): string {\n\tconst lines: string[] = []\n\tif (message.event !== undefined) lines.push(`event: ${message.event}`)\n\tif (message.id !== undefined) lines.push(`id: ${message.id}`)\n\tif (message.retry !== undefined) lines.push(`retry: ${message.retry}`)\n\tfor (const segment of message.data.split(/\\r\\n|\\r|\\n/)) lines.push(`data: ${segment}`)\n\treturn `${lines.join('\\n')}\\n\\n`\n}\n\n/**\n * Enqueue encoded text into an open byte stream.\n *\n * @param controller - The stream controller, when the stream has started\n * @param encoder - The encoder used for the stream's byte representation\n * @param closed - Whether the stream has already ended or been cancelled\n * @param text - The text to encode and enqueue\n * @returns Nothing\n *\n * @example\n * ```ts\n * const body = new ReadableStream<Uint8Array>({\n * \tstart(controller) {\n * \t\tenqueueStreamText(controller, new TextEncoder(), false, 'hello')\n * \t},\n * })\n * ```\n */\nexport function enqueueStreamText(\n\tcontroller: ReadableStreamDefaultController<Uint8Array> | undefined,\n\tencoder: TextEncoder,\n\tclosed: boolean,\n\ttext: string,\n): void {\n\tif (closed || controller === undefined) return\n\tcontroller.enqueue(encoder.encode(text))\n}\n\n/**\n * Open a generic Server-Sent-Events stream — a fetch-standard `Response`\n * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.\n *\n * @remarks\n * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}\n * merged under any `options.headers` (a seam-owned key is never overridden),\n * at `options.status` (default `200`). The returned {@link StreamInterface}'s\n * `write` serializes one message ({@link serializeEvent}), enqueues it, and\n * returns whether the controller still has positive desired size. A producer\n * receiving `false` can await `drain()`; its event-driven promise resolves on\n * the next consumer pull that restores capacity, or on stream closure.\n * `comment` writes a `: text` keep-alive line a conforming parser ignores;\n * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended\n * by `end()`, or the consumer cancelled the stream), so a late write never\n * throws.\n *\n * This readiness reflects only the process-local `ReadableStream` queue — it\n * is not proof that a remote peer consumed bytes. When the response pump\n * honors its socket sink's drain state, socket pressure stops body pulls and\n * therefore keeps this queue full, allowing a cooperative producer to bound\n * buffering. Ignoring the return value preserves the prior unconditional-\n * enqueue behavior. The default stream strategy counts chunks rather than\n * their byte length, so a byte-bounded producer must also cap each message.\n * Return `response` before awaiting a `false` write, because the consumer\n * cannot pull until it receives the response.\n *\n * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}\n * @returns The {@link StreamInterface} handle\n *\n * @example\n * ```ts\n * const stream = openStream()\n * void Promise.resolve().then(async () => {\n * \tif (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()\n * \tstream.end()\n * })\n * // return stream.response from the route handler\n * ```\n */\nexport function openStream(options?: StreamOptions): StreamInterface {\n\tconst encoder = new TextEncoder()\n\tlet closed = false\n\tlet controller: ReadableStreamDefaultController<Uint8Array> | undefined\n\tlet wakeup: PromiseWithResolvers<void> | undefined\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(streamController) {\n\t\t\tcontroller = streamController\n\t\t},\n\t\tpull(streamController) {\n\t\t\tif (streamController.desiredSize === null || streamController.desiredSize <= 0) return\n\t\t\twakeup?.resolve()\n\t\t\twakeup = undefined\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true\n\t\t\twakeup?.resolve()\n\t\t\twakeup = undefined\n\t\t},\n\t})\n\tconst headers = new Headers({ ...SSE_HEADERS, ...options?.headers })\n\tconst response = new Response(body, { status: options?.status ?? 200, headers })\n\treturn {\n\t\tresponse,\n\t\tget closed(): boolean {\n\t\t\treturn closed\n\t\t},\n\t\twrite(message: SSEMessage): boolean {\n\t\t\tif (closed || controller === undefined) return false\n\t\t\tenqueueStreamText(controller, encoder, closed, serializeEvent(message))\n\t\t\treturn controller.desiredSize !== null && controller.desiredSize > 0\n\t\t},\n\t\tcomment(text: string): void {\n\t\t\tenqueueStreamText(controller, encoder, closed, `: ${text}\\n\\n`)\n\t\t},\n\t\tdrain(): Promise<void> {\n\t\t\tconst desired = controller?.desiredSize\n\t\t\tif (closed || (desired !== undefined && desired !== null && desired > 0)) {\n\t\t\t\treturn Promise.resolve()\n\t\t\t}\n\t\t\twakeup ??= Promise.withResolvers<void>()\n\t\t\treturn wakeup.promise\n\t\t},\n\t\tend(): void {\n\t\t\tif (closed) return\n\t\t\tclosed = true\n\t\t\tcontroller?.close()\n\t\t\twakeup?.resolve()\n\t\t\twakeup = undefined\n\t\t},\n\t}\n}\n\n// The body pipeline (AGENTS §4.3 module-scope, §5.4 of the proposal) —\n// `readBody` collects a request body capped at `limit` bytes (413 over),\n// transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n// through a byte-counting `TransformStream` that ABORTS the instant\n// decompressed output exceeds `decompression` (the zip-bomb defense — fail\n// BEFORE materializing the bomb, since `DecompressionStream` has no\n// `maxOutputLength` knob), then decodes by content type. `scrubPrototype` /\n// `isDangerousKey` are the prototype-pollution scrub `readBody` applies to a\n// parsed JSON body, ported verbatim (pure value-walking logic, unaffected by\n// the fetch-vocabulary migration).\n\n/**\n * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,\n * or `prototype` — the three keys that, assigned onto a normal object, can\n * reach and mutate `Object.prototype`.\n *\n * @param key - The candidate object key\n * @returns `true` when `key` is one of the three prototype-pollution keys\n *\n * @example\n * ```ts\n * isDangerousKey('__proto__') // true\n * isDangerousKey('name') // false\n * ```\n */\nexport function isDangerousKey(key: string): boolean {\n\treturn key === '__proto__' || key === 'constructor' || key === 'prototype'\n}\n\n/**\n * Recursively STRIP the prototype-pollution keys from a parsed value IN\n * PLACE.\n *\n * @remarks\n * `JSON.parse('{\"__proto__\":{…}}')` is benign on its own — it produces an OWN,\n * enumerable `__proto__` DATA property — but that own key becomes a\n * pollution gadget the moment a downstream deep-merge copies it onto a live\n * object. This walks the value and `delete`s any own {@link isDangerousKey}\n * key at every depth, recursing into nested objects + array elements.\n * Primitives/`null` pass through untouched. Total — never throws. Mutates the\n * freshly-parsed value (which nothing else holds yet).\n *\n * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)\n * @returns The same `value`, with every dangerous key removed at every depth\n *\n * @example\n * ```ts\n * scrubPrototype(JSON.parse('{\"__proto__\":{\"polluted\":true},\"name\":\"ok\"}'))\n * // { name: 'ok' } — the __proto__ key is gone\n * ```\n */\nexport function scrubPrototype(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\tfor (const item of value) scrubPrototype(item)\n\t\treturn value\n\t}\n\tif (isRecord(value)) {\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tif (isDangerousKey(key)) {\n\t\t\t\tReflect.deleteProperty(value, key)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tscrubPrototype(value[key])\n\t\t}\n\t\treturn value\n\t}\n\treturn value\n}\n\n/**\n * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.\n *\n * @remarks\n * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,\n * throwing a {@link ContentTooLargeError} (413) the instant the running total\n * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than\n * collecting an unbounded body. A bodyless request (`request.body === null`)\n * resolves an empty array. A non-positive `limit` means unbounded.\n *\n * @param request - The `Request` to drain\n * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded\n * @returns The full request body as one `Uint8Array`\n * @throws {ContentTooLargeError} When the body exceeds `limit`\n *\n * @example\n * ```ts\n * const bytes = await collectRequestBody(request, 1_048_576)\n * ```\n */\nexport async function collectRequestBody(\n\trequest: Request,\n\tlimit: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tif (request.body === null) return new Uint8Array(0)\n\tconst reader = request.body.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet total = 0\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read()\n\t\tif (done) break\n\t\ttotal += value.byteLength\n\t\tif (limit > 0 && total > limit) {\n\t\t\tawait reader.cancel()\n\t\t\tthrow new ContentTooLargeError(limit)\n\t\t}\n\t\tchunks.push(value)\n\t}\n\tconst merged = new Uint8Array(total)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn merged\n}\n\n/**\n * Narrow a raw `Content-Encoding` header value to a decompressible\n * {@link Encoding} — the boundary guard {@link readBody} uses to decide\n * whether a request body needs transparent decompression.\n *\n * @remarks\n * Lower-cases + trims and returns the matching {@link Encoding} ONLY for\n * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of\n * the proposal). An absent header, `identity`, an unknown value, or a\n * comma-joined multi-coding all yield `undefined` (the body is read as-is).\n * TOTAL — never asserts the loose `string | null` header.\n *\n * @param header - The raw `Content-Encoding` header value\n * @returns The single decompressible {@link Encoding}, or `undefined` when none applies\n *\n * @example\n * ```ts\n * requestEncoding('gzip') // 'gzip'\n * requestEncoding('br') // undefined — unsupported by DecompressionStream\n * ```\n */\nexport function requestEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined {\n\tif (!isString(header)) return undefined\n\tconst value = header.trim().toLowerCase()\n\treturn value === 'gzip' || value === 'deflate' ? value : undefined\n}\n\n/**\n * Transparently decompress an already-collected, `gzip`/`deflate`-encoded\n * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —\n * the zip-bomb defense.\n *\n * @remarks\n * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting\n * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed\n * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`\n * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces\n * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated\n * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}\n * (never conflated with the cap). A non-positive `cap` means uncapped.\n *\n * @param bytes - The compressed bytes to decompress\n * @param encoding - The {@link Encoding} the bytes are compressed with\n * @param cap - The maximum decompressed byte count; a non-positive value means uncapped\n * @returns The decompressed bytes\n * @throws {ContentTooLargeError} When decompressed output would exceed `cap`\n * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)\n */\nexport async function decompressRequestBody(\n\tbytes: Uint8Array<ArrayBuffer>,\n\tencoding: Exclude<Encoding, 'identity'>,\n\tcap: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tlet total = 0\n\tconst capStream = new TransformStream<Uint8Array, Uint8Array>({\n\t\ttransform(chunk, controller) {\n\t\t\ttotal += chunk.byteLength\n\t\t\tif (cap > 0 && total > cap) {\n\t\t\t\tcontroller.error(new ContentTooLargeError(cap))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk)\n\t\t},\n\t})\n\tconst source = new ReadableStream<Uint8Array<ArrayBuffer>>({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue(bytes)\n\t\t\tcontroller.close()\n\t\t},\n\t})\n\tconst decompressed = source.pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream)\n\tconst reader = decompressed.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet size = 0\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (done) break\n\t\t\tchunks.push(value)\n\t\t\tsize += value.byteLength\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof ContentTooLargeError) throw error\n\t\tthrow new HTTPError(400, 'malformed compressed request body')\n\t}\n\tconst merged = new Uint8Array(size)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn merged\n}\n\n/**\n * Collect + decode a `Request` body — the shared body-collection pipeline\n * surfaced to middleware and handlers as the middleware context's cached\n * `body()`.\n *\n * @remarks\n * Collects the wire body capped at `options.limit` bytes ({@link\n * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),\n * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at\n * `options.decompression`, default {@link\n * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by\n * content type: `application/json` is parsed via `@orkestrel/contract`'s\n * `parseJSON` and scrubbed of prototype-pollution keys ({@link\n * scrubPrototype}); any other type decodes as UTF-8 text; an empty body\n * decodes to `undefined`.\n *\n * @param request - The `Request` to read the body from\n * @param options - The {@link BodyOptions} `limit` + `decompression` caps\n * @returns The parsed JSON value, the raw text, or `undefined` for an empty body\n * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap\n * @throws {HTTPError} When the compressed body is corrupt (400)\n *\n * @example\n * ```ts\n * const body = await readBody(request, { limit: 1_048_576 })\n * ```\n */\nexport async function readBody(request: Request, options?: BodyOptions): Promise<unknown> {\n\tconst limit = options?.limit ?? DEFAULT_BODY_LIMIT\n\tconst decompression = options?.decompression ?? DEFAULT_DECOMPRESSED_LIMIT\n\tconst wire = await collectRequestBody(request, limit)\n\tconst encoding = requestEncoding(request.headers.get('content-encoding'))\n\tconst bytes =\n\t\tencoding === undefined ? wire : await decompressRequestBody(wire, encoding, decompression)\n\tif (bytes.length === 0) return undefined\n\tconst contentType = request.headers.get('content-type')\n\tconst semicolon = contentType === null ? -1 : contentType.indexOf(';')\n\tconst bareType =\n\t\tcontentType === null\n\t\t\t? ''\n\t\t\t: (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase()\n\tconst text = new TextDecoder().decode(bytes)\n\tif (bareType === 'application/json') return scrubPrototype(parseJSON(text))\n\treturn text\n}\n\n// ============================================================================\n// The node face — pure helpers (AGENTS §5). Every function here is genuinely\n// node-bound (a `node:net` probe, an `AddressInfo` narrow) — everything\n// fetch/string-pure lives above in this same file and is consumed, never\n// duplicated (the socket-encrypted narrow and the `Request`/`Response`\n// conversion are `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` /\n// `sendResponse`).\n// ============================================================================\n\n/**\n * Whether a `node:net` `server.address()` return is the structured\n * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`\n * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`\n * and the `Server`'s own port resolution read the bound port through.\n *\n * @param value - The `server.address()` return (`AddressInfo | string | null`)\n * @returns `true` when `value` is an `AddressInfo` with a numeric `port`\n *\n * @example\n * ```ts\n * import { isAddressInfo } from '@src/server'\n *\n * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true\n * isAddressInfo(null) // false\n * ```\n */\nexport function isAddressInfo(value: unknown): value is AddressInfo {\n\treturn isRecord(value) && isNumber(value.port)\n}\n\n/**\n * Bind and close a throwaway TCP server to resolve one available port.\n *\n * @param port - The requested port, with `0` selecting an ephemeral port\n * @returns The bound port after the probe server has closed\n *\n * @example\n * ```ts\n * const port = await probePort(0)\n * ```\n */\nexport async function probePort(port: number): Promise<number> {\n\tconst probe = createNetServer()\n\tconst listening = once(probe, 'listening')\n\tprobe.listen(port)\n\tawait listening\n\tconst address = probe.address()\n\tconst resolved = isAddressInfo(address) ? address.port : 0\n\tconst closed = once(probe, 'close')\n\tprobe.close()\n\tawait closed\n\treturn resolved\n}\n\n/**\n * Find a FREE TCP port — bind a throwaway `node:net` server, read the\n * OS-assigned port, close it, and resolve that port.\n *\n * @remarks\n * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)\n * and returns it. With a `preferred` port it tries THAT port first and\n * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an\n * ephemeral free port rather than rejecting — a caller always gets a usable\n * port. It binds then immediately closes a probe server, so the returned\n * port is free at the instant of the probe (an inherent TOCTOU race — bind it\n * promptly). Rejects only on an unexpected listen error other than a taken\n * `preferred` port (e.g. a permission fault).\n *\n * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒\n * fall back to an ephemeral port\n * @returns A free TCP port number\n *\n * @example\n * ```ts\n * import { createServer, discoverPort } from '@src/server'\n *\n * const port = await discoverPort() // a guaranteed-free ephemeral port\n * ```\n */\nexport async function discoverPort(preferred?: number): Promise<number> {\n\tif (preferred === undefined) return probePort(0)\n\ttry {\n\t\treturn await probePort(preferred)\n\t} catch (error) {\n\t\tif (error instanceof Error && 'code' in error && error.code === 'EADDRINUSE')\n\t\t\treturn probePort(0)\n\t\tthrow error\n\t}\n}\n","import type { Encoding, FormatHandlerMap, MiddlewareContext, NegotiatorInterface } from './types.js'\nimport { languageQuality, matchMediaType, negotiateEncoding, parseAcceptHeader } from './helpers.js'\n\n/**\n * The content-negotiation machine over the weighted `Accept` family — a\n * reusable, cross-middleware ENTITY (not a middleware). Implements exactly\n * {@link NegotiatorInterface}.\n *\n * @remarks\n * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /\n * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its\n * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the\n * rest of the substrate uses — one parser, never two. `format` reads the\n * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes\n * the winner — or answers `406 Not Acceptable`.\n *\n * @example\n * ```ts\n * const negotiator = new Negotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport class Negotiator implements NegotiatorInterface {\n\tnegotiate(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tlet best: string | undefined\n\t\tlet bestQuality = 0\n\t\tlet bestRank = Number.POSITIVE_INFINITY\n\t\tfor (const candidate of available) {\n\t\t\tconst match = matchMediaType(entries, candidate)\n\t\t\tif (match === undefined) continue\n\t\t\tconst { q, rank } = match\n\t\t\tif (q > bestQuality || (q === bestQuality && rank < bestRank)) {\n\t\t\t\tbest = candidate\n\t\t\t\tbestQuality = q\n\t\t\t\tbestRank = rank\n\t\t\t}\n\t\t}\n\t\treturn best\n\t}\n\n\tencoding(header: string, available: readonly Encoding[]): Encoding | undefined {\n\t\treturn negotiateEncoding(header, available)\n\t}\n\n\tlanguage(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tlet best: string | undefined\n\t\tlet bestQuality = 0\n\t\tfor (const candidate of available) {\n\t\t\tconst quality = languageQuality(entries, candidate)\n\t\t\tif (quality > bestQuality) {\n\t\t\t\tbest = candidate\n\t\t\t\tbestQuality = quality\n\t\t\t}\n\t\t}\n\t\treturn best\n\t}\n\n\t/**\n\t * @remarks\n\t * Errors thrown by the negotiated handler propagate UNMODIFIED — the\n\t * server boundary classifies them, never this negotiator.\n\t */\n\tasync format<TState>(\n\t\trequest: Request,\n\t\tcontext: MiddlewareContext<TState>,\n\t\thandlers: FormatHandlerMap<TState>,\n\t): Promise<Response> {\n\t\tconst keys = Object.keys(handlers)\n\t\tconst header = request.headers.get('accept')\n\t\tconst type = header === null ? keys[0] : this.negotiate(header, keys)\n\t\tif (type === undefined) return new Response('Not Acceptable', { status: 406 })\n\t\tconst handler = handlers[type]\n\t\tif (handler === undefined) return new Response('Not Acceptable', { status: 406 })\n\t\treturn handler(request, context)\n\t}\n}\n","import type { IncomingMessage, Server as NodeHTTPServer, ServerResponse } from 'node:http'\nimport type { Duplex } from 'node:stream'\nimport type { AbortInterface } from '@orkestrel/abort'\nimport type { TimeoutInterface } from '@orkestrel/timeout'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnectionStateFunction,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { addAbortListener, once } from 'node:events'\nimport { createServer as createHTTPServer } from 'node:http'\nimport { createAbort, linkSignal } from '@orkestrel/abort'\nimport { createTimeout } from '@orkestrel/timeout'\nimport { buildRequest, isEncryptedSocket, sendResponse } from '@orkestrel/router/server'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isFiniteNumber, isFunction, isInteger } from '@orkestrel/contract'\nimport { compose, isAddressInfo, readBody } from './helpers.js'\nimport { DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_MS } from './constants.js'\nimport { HTTPError, isHTTPError } from './errors.js'\n\n/**\n * The HTTP server facade — an observable `node:http` lifecycle composing this\n * module's own middleware onion around a consumed `@orkestrel/router`\n * dispatcher.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n *\n * @remarks\n * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`\n * server, binds the configured {@link ServerOptions.host} / {@link\n * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the\n * bound address), observes caller cancellation plus the configured\n * `timeouts.start` deadline while the bind is pending, and transitions\n * `idle → starting → listening`. A cancelled or expired bind closes its\n * partial server and resets to `idle` for another start. `stop()` transitions\n * to `stopping`: refuses new connections, fires a fresh-per-run stop signal\n * so in-flight handlers observe cancellation, drains up to the `drain`\n * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`\n * is the idempotent final teardown.\n * - **Per request.** In-flight is tracked (finished on response `finish` or\n * `close`); a `Request` is built via the router's `buildRequest`, its\n * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s\n * `linkSignal` (a fresh `Request` is constructed with the linked signal —\n * `buildRequest`'s own abort, armed by BOTH request-side and response-side\n * teardown, composes with the server's stop signal via `AbortSignal.any`,\n * so a handler awaiting `request.signal` observes BOTH); `context.state` is built via\n * {@link ServerOptions.state} from the connection facts; the composed\n * middleware onion runs, terminating in `dispatcher.handle`; the result is\n * written back via `sendResponse`.\n * - **The built-in boundary** wraps the WHOLE per-request chain, including\n * setup: `buildRequest` runs behind its own inner boundary that maps a\n * throw (e.g. a malformed `Host` header) to a silent `400` with no\n * `error` emit; everything after (`Request` reconstruction, connection\n * facts, `state`, the composed onion, and `dispatcher.handle`) runs\n * behind the outer boundary — a thrown `HTTPError` renders as its status +\n * message; any other throw renders `500` (message hidden unless\n * `expose`), `report` is invoked (its own throw swallowed), and `error` is\n * emitted. A server-owned last resort wraps the final `sendResponse`\n * write itself: if even that fails, the connection is destroyed rather\n * than left to escape as an unhandled error.\n * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a\n * throwing handler is treated as declined and surfaced on `error`, an\n * unclaimed upgrade destroys the socket), bound per-run to this instance.\n * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}\n * exposed as `readonly emitter`; the emitter isolates a listener throw and\n * routes it to the `error` OPTION (not the domain `error` event).\n */\nexport class Server<TState> implements ServerInterface<TState> {\n\treadonly id = crypto.randomUUID()\n\treadonly #dispatcher: DispatcherInterface<TState>\n\treadonly #state: ConnectionStateFunction<TState>\n\treadonly #middleware: MiddlewareHandler<TState>[]\n\treadonly #upgradeHandlers: UpgradeHandler[] = []\n\treadonly #emitter: Emitter<ServerEventMap>\n\treadonly #host: string | undefined\n\treadonly #configuredPort: number | undefined\n\treadonly #drain: number\n\treadonly #limit: number\n\treadonly #expose: boolean\n\treadonly #report: ((error: unknown, request?: { method: string; url: URL }) => void) | undefined\n\treadonly #timeouts: {\n\t\treadonly start?: number\n\t\treadonly request?: number\n\t\treadonly headers?: number\n\t\treadonly keepalive?: number\n\t}\n\treadonly #sockets: {\n\t\treadonly connections?: number\n\t\treadonly headers?: number\n\t\treadonly requests?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#abort: AbortInterface = createAbort()\n\t#wakeup: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#pending = 0\n\n\tconstructor(options: ServerOptions<TState>) {\n\t\tif (!isFunction(options.state)) throw new TypeError('ServerOptions.state must be a function')\n\t\tif (options.report !== undefined && !isFunction(options.report))\n\t\t\tthrow new TypeError('ServerOptions.report must be a function')\n\t\tconst drain = options.drain ?? DEFAULT_DRAIN_MS\n\t\tif (!isFiniteNumber(drain) || drain < 0)\n\t\t\tthrow new TypeError('ServerOptions.drain must be a non-negative finite number')\n\t\tconst limit = options.limit ?? DEFAULT_BODY_LIMIT\n\t\tif (!isFiniteNumber(limit) || limit < 0)\n\t\t\tthrow new TypeError('ServerOptions.limit must be a non-negative finite number')\n\t\tconst timeouts = options.timeouts ?? {}\n\t\tfor (const [name, value] of Object.entries(timeouts)) {\n\t\t\tif (value !== undefined && (!isFiniteNumber(value) || value < 0))\n\t\t\t\tthrow new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`)\n\t\t}\n\t\tif (\n\t\t\ttimeouts.headers !== undefined &&\n\t\t\ttimeouts.keepalive !== undefined &&\n\t\t\ttimeouts.headers > timeouts.keepalive\n\t\t) {\n\t\t\tthrow new TypeError('ServerOptions.timeouts.headers must not exceed timeouts.keepalive')\n\t\t}\n\t\tconst sockets = options.sockets ?? {}\n\t\tfor (const [name, value] of Object.entries(sockets)) {\n\t\t\tif (value !== undefined && (!isInteger(value) || value < 0))\n\t\t\t\tthrow new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`)\n\t\t}\n\t\tthis.#dispatcher = options.dispatcher\n\t\tthis.#state = options.state\n\t\tthis.#middleware = options.middleware === undefined ? [] : [...options.middleware]\n\t\tthis.#host = options.host\n\t\tthis.#configuredPort = options.port\n\t\tthis.#drain = drain\n\t\tthis.#limit = limit\n\t\tthis.#expose = options.expose ?? false\n\t\tthis.#report = options.report\n\t\tthis.#timeouts = timeouts\n\t\tthis.#sockets = sockets\n\t\tthis.#emitter = new Emitter<ServerEventMap>({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t}\n\n\tget status(): ServerStatus {\n\t\treturn this.#status\n\t}\n\n\tget port(): number | undefined {\n\t\treturn this.#port\n\t}\n\n\tget dispatcher(): DispatcherInterface<TState> {\n\t\treturn this.#dispatcher\n\t}\n\n\tget emitter(): EmitterInterface<ServerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tuse(middleware: MiddlewareHandler<TState>): void\n\tuse(middleware: readonly MiddlewareHandler<TState>[]): void\n\tuse(middleware: MiddlewareHandler<TState> | readonly MiddlewareHandler<TState>[]): void {\n\t\tif (typeof middleware === 'function') this.#middleware.push(middleware)\n\t\telse this.#middleware.push(...middleware)\n\t}\n\n\tupgrade(handler: UpgradeHandler): void {\n\t\tthis.#upgradeHandlers.push(handler)\n\t}\n\n\tstart(signal?: AbortSignal): Promise<number> {\n\t\tif (this.#status !== 'idle' && this.#status !== 'stopped') {\n\t\t\treturn Promise.reject(new Error(`server cannot start from '${this.#status}'`))\n\t\t}\n\t\tthis.#status = 'starting'\n\t\t// A fresh stop signal per run, so a restarted server is not born aborted.\n\t\tthis.#abort = createAbort()\n\t\tconst server = createHTTPServer((request, response) => this.#handle(request, response))\n\t\tif (this.#timeouts.request !== undefined) server.requestTimeout = this.#timeouts.request\n\t\tif (this.#timeouts.headers !== undefined) server.headersTimeout = this.#timeouts.headers\n\t\tif (this.#timeouts.keepalive !== undefined) server.keepAliveTimeout = this.#timeouts.keepalive\n\t\tif (this.#sockets.connections !== undefined) server.maxConnections = this.#sockets.connections\n\t\tif (this.#sockets.headers !== undefined) server.maxHeadersCount = this.#sockets.headers\n\t\tif (this.#sockets.requests !== undefined) server.maxRequestsPerSocket = this.#sockets.requests\n\t\t// Bound to THIS run's server instance, discarded with it on stop/restart —\n\t\t// no manual removal needed (the same per-run lifecycle as the handler above).\n\t\tserver.on('upgrade', (request, socket, head) => this.#onUpgrade(request, socket, head))\n\t\tthis.#http = server\n\t\treturn this.#listen(server, signal)\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (this.#status !== 'listening') return\n\t\tthis.#status = 'stopping'\n\t\tthis.#emitter.emit('stop')\n\t\tconst server = this.#http\n\t\t// A pure signal — NOT the drain deadline's parent (a parent abort would\n\t\t// clear the Timeout so it never fires). The drain deadline is an\n\t\t// independent clock; the wake-park below resolves on the last finish OR\n\t\t// the deadline, event-driven, never a busy-loop.\n\t\tthis.#abort.abort()\n\t\tconst deadline: TimeoutInterface = createTimeout({ ms: this.#drain })\n\t\tdeadline.start()\n\t\tawait this.#drainPending(deadline.signal)\n\t\tdeadline.clear()\n\t\tconst pending = this.#pending\n\t\tthis.#emitter.emit('drain', pending)\n\t\tif (server !== undefined) await this.#close(server, pending > 0)\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t}\n\n\tasync destroy(): Promise<void> {\n\t\tif (this.#status === 'stopped' && this.#http === undefined) {\n\t\t\tthis.#emitter.destroy()\n\t\t\treturn\n\t\t}\n\t\tif (!this.#abort.aborted) this.#abort.abort()\n\t\tconst server = this.#http\n\t\tif (server !== undefined) await this.#close(server, true)\n\t\tthis.#http = undefined\n\t\tthis.#port = undefined\n\t\tthis.#status = 'stopped'\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Track the request for draining FIRST — before anything that can throw —\n\t// so the sync listener itself never throws; the rest of setup (which CAN\n\t// throw on a malformed request) is deferred into the async `#accept`\n\t// entry, kept behind the built-in boundary.\n\t#handle(message: IncomingMessage, response: ServerResponse): void {\n\t\tconst finish = this.#trackStart()\n\t\tresponse.once('finish', finish)\n\t\tresponse.once('close', finish)\n\t\tvoid this.#accept(message, response)\n\t}\n\n\t// Build the fetch `Request` + `MiddlewareContext`, run the composed onion,\n\t// and write the result back — every escaping throw is caught so the\n\t// process can never crash on an unhandled handler (or malformed request)\n\t// error. `buildRequest` runs behind its OWN inner boundary: a throw there\n\t// (e.g. a malformed `Host` header) maps to a silent `400`, never `error`.\n\tasync #accept(message: IncomingMessage, response: ServerResponse): Promise<void> {\n\t\tlet raw: Request\n\t\ttry {\n\t\t\traw = buildRequest(message, { response })\n\t\t} catch {\n\t\t\tawait this.#respond(this.#boundary(new HTTPError(400, 'invalid request')), response)\n\t\t\treturn\n\t\t}\n\t\t// Hoisted above the inner try (not block-scoped inside it) so the catch\n\t\t// below can attach real request context to the `error` emit / `report`\n\t\t// sink — and so `response` can be emitted with the same facts on either\n\t\t// the success or the error path.\n\t\tconst method = raw.method\n\t\tconst url = new URL(raw.url)\n\t\tconst start = performance.now()\n\t\ttry {\n\t\t\tconst linked = linkSignal(raw.signal, this.#abort.signal)\n\t\t\tconst request = new Request(raw, { signal: linked })\n\t\t\tthis.#emitter.emit('request', method, url.pathname)\n\t\t\tconst ip = message.socket.remoteAddress\n\t\t\tconst connection = {\n\t\t\t\t...(ip === undefined ? {} : { ip }),\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tconst context: MiddlewareContext<TState> = {\n\t\t\t\turl,\n\t\t\t\tmethod,\n\t\t\t\tstate: this.#state(connection),\n\t\t\t\tbody: this.#createBody(request),\n\t\t\t}\n\t\t\tconst runner = compose(this.#middleware, (currentRequest, currentContext) =>\n\t\t\t\tthis.#dispatcher.handle(currentRequest, currentContext.state),\n\t\t\t)\n\t\t\tconst result = await runner(request, context)\n\t\t\tawait this.#respond(result, response)\n\t\t\tthis.#emitter.emit('response', {\n\t\t\t\tmethod,\n\t\t\t\tpathname: url.pathname,\n\t\t\t\tstatus: result.status,\n\t\t\t\tms: Math.round(performance.now() - start),\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tconst mapped = this.#boundary(error)\n\t\t\tif (!isHTTPError(error)) {\n\t\t\t\tthis.#emitter.emit('error', error, { method, url })\n\t\t\t\tif (this.#report !== undefined) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#report(error, { method, url })\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Swallowed — reporting can never crash the response.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait this.#respond(mapped, response)\n\t\t\tthis.#emitter.emit('response', {\n\t\t\t\tmethod,\n\t\t\t\tpathname: url.pathname,\n\t\t\t\tstatus: mapped.status,\n\t\t\t\tms: Math.round(performance.now() - start),\n\t\t\t})\n\t\t}\n\t}\n\n\t// The server-owned last resort: even a write failure inside\n\t// `sendResponse` cannot escape and crash the process — the underlying\n\t// response (and its socket) is destroyed instead.\n\tasync #respond(result: Response, response: ServerResponse): Promise<void> {\n\t\ttry {\n\t\t\tawait sendResponse(result, response)\n\t\t} catch {\n\t\t\tresponse.destroy()\n\t\t}\n\t}\n\n\t// The built-in boundary — an `HTTPError` renders as its status + message;\n\t// any other throw renders `500` with its message hidden unless `expose`.\n\t#boundary(error: unknown): Response {\n\t\tif (isHTTPError(error)) return new Response(error.message, { status: error.status })\n\t\tconst message = this.#expose && error instanceof Error ? error.message : 'Internal Server Error'\n\t\treturn new Response(message, { status: 500 })\n\t}\n\n\t// Fan a raw protocol-upgrade out to the registered handlers in\n\t// registration order: the FIRST to return `true` CLAIMS the socket. A\n\t// throwing handler is treated as DECLINED — surfaced on `error` — and the\n\t// fan-out continues so a later handler can still claim. Unclaimed ⇒ the\n\t// socket is destroyed so an unhandled upgrade never leaks a connection.\n\t#onUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {\n\t\tlet handled = false\n\t\tfor (const handler of this.#upgradeHandlers) {\n\t\t\ttry {\n\t\t\t\tif (handler(request, socket, head)) {\n\t\t\t\t\thandled = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.#emitter.emit('error', error)\n\t\t\t}\n\t\t}\n\t\tif (!handled) socket.destroy()\n\t\tthis.#emitter.emit('upgrade', request, handled)\n\t}\n\n\t// Resolve the bound port from the server's address, narrowed via a guard\n\t// (an `AddressInfo` carries a numeric `port`; a string / null address has\n\t// none). No assertion — an unresolvable address yields `0`.\n\t#resolvePort(server: NodeHTTPServer): number {\n\t\tconst address = server.address()\n\t\tif (isAddressInfo(address)) return address.port\n\t\treturn 0\n\t}\n\n\tasync #listen(server: NodeHTTPServer, signal?: AbortSignal): Promise<number> {\n\t\tconst deadline =\n\t\t\tthis.#timeouts.start === undefined ? undefined : createTimeout({ ms: this.#timeouts.start })\n\t\tconst startup = deadline === undefined ? signal : linkSignal(deadline.signal, signal)\n\t\tconst binding = createAbort()\n\t\tconst relay =\n\t\t\tstartup === undefined\n\t\t\t\t? undefined\n\t\t\t\t: addAbortListener(startup, () => binding.abort(startup.reason))\n\t\tlet listening: Promise<unknown[]> | undefined\n\t\ttry {\n\t\t\tsignal?.throwIfAborted()\n\t\t\tdeadline?.start()\n\t\t\tif (deadline?.ms === 0 && startup !== undefined) await once(startup, 'abort')\n\t\t\tstartup?.throwIfAborted()\n\t\t\tlistening = once(server, 'listening', { signal: binding.signal })\n\t\t\tif (startup === undefined) server.listen(this.#configuredPort ?? 0, this.#host)\n\t\t\telse {\n\t\t\t\tserver.listen({\n\t\t\t\t\tport: this.#configuredPort ?? 0,\n\t\t\t\t\t...(this.#host === undefined ? {} : { host: this.#host }),\n\t\t\t\t\tsignal: binding.signal,\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait listening\n\t\t} catch (error) {\n\t\t\tconst expired = deadline?.expired === true\n\t\t\tconst cancelled = startup?.aborted === true\n\t\t\t// A cancellation removes `events.once`'s temporary error listener. Keep\n\t\t\t// the discarded server guarded while a simultaneous late bind error\n\t\t\t// settles so it cannot escape as an uncaught process error.\n\t\t\tserver.on('error', () => undefined)\n\t\t\tbinding.abort(error)\n\t\t\tif (listening !== undefined) await listening.catch(() => undefined)\n\t\t\tawait this.#close(server, true)\n\t\t\tthis.#http = undefined\n\t\t\tthis.#port = undefined\n\t\t\tthis.#status = 'idle'\n\t\t\tif (expired && deadline !== undefined) {\n\t\t\t\tthrow new DOMException(\n\t\t\t\t\t`Server startup exceeded ${deadline.ms} milliseconds`,\n\t\t\t\t\t'TimeoutError',\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (cancelled && startup !== undefined) throw startup.reason\n\t\t\tthrow error\n\t\t} finally {\n\t\t\trelay?.[Symbol.dispose]()\n\t\t\tdeadline?.clear()\n\t\t}\n\t\tconst port = this.#resolvePort(server)\n\t\tthis.#port = port\n\t\tthis.#status = 'listening'\n\t\tthis.#emitter.emit('start', port)\n\t\treturn port\n\t}\n\n\t#createBody(request: Request): () => Promise<unknown> {\n\t\tlet cached: Promise<unknown> | undefined\n\t\treturn () => {\n\t\t\tcached ??= readBody(request, { limit: this.#limit })\n\t\t\treturn cached\n\t\t}\n\t}\n\n\t// Close the underlying server, resolving once it stops accepting\n\t// connections. A keep-alive client leaves its socket IDLE after a\n\t// response, which would hang a plain `close()` — so idle sockets are\n\t// always dropped (an in-flight request is untouched); when `force` is set\n\t// (the drain deadline fired with work still in flight, or `destroy`)\n\t// every open socket is destroyed so the callback fires promptly.\n\t#close(server: NodeHTTPServer, force: boolean): Promise<void> {\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tserver.close(() => resolve())\n\t\t\tif (force) server.closeAllConnections()\n\t\t\telse server.closeIdleConnections()\n\t\t})\n\t}\n\n\t// Track one in-flight request; returns an idempotent finish thunk. When\n\t// the last in-flight request finishes, the current drain wakeup fires —\n\t// event-driven, never a busy-loop.\n\t#trackStart(): () => void {\n\t\tif (this.#pending === 0) this.#wakeup = createAbort()\n\t\tthis.#pending += 1\n\t\tlet finished = false\n\t\treturn () => {\n\t\t\tif (finished) return\n\t\t\tfinished = true\n\t\t\tthis.#pending -= 1\n\t\t\tif (this.#pending === 0) this.#wakeup.abort()\n\t\t}\n\t}\n\n\t// Park until the in-flight count reaches zero OR `signal` fires —\n\t// event-driven (wake-park), no polling.\n\tasync #drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#pending === 0 || signal.aborted) return\n\t\tawait once(AbortSignal.any([signal, this.#wakeup.signal]), 'abort')\n\t}\n}\n","import type { NegotiatorInterface, ServerInterface, ServerOptions } from './types.js'\nimport { Negotiator } from './Negotiator.js'\nimport { Server } from './Server.js'\n\n/**\n * Create a {@link NegotiatorInterface} — the reusable content-negotiation\n * machine over the weighted `Accept` family.\n *\n * @remarks\n * Prefer this over `new Negotiator()` at call sites that only need the\n * interface.\n *\n * @returns A {@link NegotiatorInterface}\n *\n * @example\n * ```ts\n * import { createNegotiator } from '@src/server'\n *\n * const negotiator = createNegotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport function createNegotiator(): NegotiatorInterface {\n\treturn new Negotiator()\n}\n\n/**\n * Create a {@link ServerInterface} — the node face's HTTP server facade over\n * a consumed `@orkestrel/router` dispatcher.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param options - {@link ServerOptions}\n * @returns A {@link ServerInterface}, not yet started\n *\n * @example\n * ```ts\n * import { createServer } from '@src/server'\n * import { createDispatcher } from '@orkestrel/router'\n *\n * const dispatcher = createDispatcher<{ readonly ip?: string }>()\n * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })\n *\n * const server = createServer({\n * \tdispatcher,\n * \tstate: (connection) => ({ ip: connection.ip }),\n * })\n * const port = await server.start()\n * await server.stop()\n * ```\n */\nexport function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState> {\n\treturn new Server(options)\n}\n"],"mappings":";;;;;;;;;;AAWA,IAAa,mBAAmB;;;;;;;;;;;;;;AAehC,IAAa,mBAAmB,OAAO,IAAI,6BAA6B;;AAGxE,IAAa,qBAAqB;;;;;;;;;;;;;;;;;AAkBlC,IAAa,6BAA6B;;;;;;;;;;;;AAa1C,IAAa,cAAgD,OAAO,OAAO;CAC1E,gBAAgB;CAChB,iBAAiB;CACjB,YAAY;CACZ,qBAAqB;AACtB,CAAC;;;;;;;;;AAUD,IAAa,qBAAuC,OAAO,OAAO,wBAAwB;;;;;;;;;;;;;AAc1F,IAAa,qCAA0C,IAAI,IAAI;CAC9D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;;;;AAaD,IAAa,oBAAyC,OAAO,OAAO,CAAC,QAAQ,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACpEvF,IAAa,YAAb,cAA+B,MAAM;CACpC;CACA;CAIA,CAAU,oBAAoB;CAE9B,YAAY,QAAgB,SAAiB,SAA6C;EACzF,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,uBAAb,cAA0C,UAAU;CACnD,YAAY,OAAe;EAC1B,MAAM,KAAK,4BAA4B,MAAM,cAAc,EAAE,MAAM,CAAC;EACpE,KAAK,OAAO;CACb;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,YAAY,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