@orkestrel/server 0.0.6 → 0.0.8

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.
@@ -514,6 +514,26 @@ export declare function encodeBase64Url(bytes: Uint8Array): string;
514
514
  */
515
515
  export declare type Encoding = 'gzip' | 'deflate' | 'identity';
516
516
 
517
+ /**
518
+ * Enqueue encoded text into an open byte stream.
519
+ *
520
+ * @param controller - The stream controller, when the stream has started
521
+ * @param encoder - The encoder used for the stream's byte representation
522
+ * @param closed - Whether the stream has already ended or been cancelled
523
+ * @param text - The text to encode and enqueue
524
+ * @returns Nothing
525
+ *
526
+ * @example
527
+ * ```ts
528
+ * const body = new ReadableStream<Uint8Array>({
529
+ * start(controller) {
530
+ * enqueueStreamText(controller, new TextEncoder(), false, 'hello')
531
+ * },
532
+ * })
533
+ * ```
534
+ */
535
+ export declare function enqueueStreamText(controller: ReadableStreamDefaultController<Uint8Array> | undefined, encoder: TextEncoder, closed: boolean, text: string): void;
536
+
517
537
  /**
518
538
  * A map of media type → handler for {@link NegotiatorInterface.format} — the
519
539
  * content-negotiation dispatch table.
@@ -1165,6 +1185,19 @@ export declare function parseCookies(header: string | undefined): Record<string,
1165
1185
  */
1166
1186
  export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
1167
1187
 
1188
+ /**
1189
+ * Bind and close a throwaway TCP server to resolve one available port.
1190
+ *
1191
+ * @param port - The requested port, with `0` selecting an ephemeral port
1192
+ * @returns The bound port after the probe server has closed
1193
+ *
1194
+ * @example
1195
+ * ```ts
1196
+ * const port = await probePort(0)
1197
+ * ```
1198
+ */
1199
+ export declare function probePort(port: number): Promise<number>;
1200
+
1168
1201
  /**
1169
1202
  * The parsed outcome of an HTTP `Range` request header.
1170
1203
  *
@@ -1425,14 +1458,17 @@ export declare function serializeEvent(message: SSEMessage): string;
1425
1458
  * @typeParam TState - The consumer's opaque per-request state type
1426
1459
  *
1427
1460
  * @remarks
1428
- * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
1461
+ * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1429
1462
  * server, binds the configured {@link ServerOptions.host} / {@link
1430
1463
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1431
- * bound address), and transitions `idle → starting → listening`. `stop()`
1432
- * transitions to `stopping`: refuses new connections, fires a fresh-per-run
1433
- * stop signal so in-flight handlers observe cancellation, drains up to the
1434
- * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
1435
- * `destroy()` is the idempotent final teardown.
1464
+ * bound address), observes caller cancellation plus the configured
1465
+ * `timeouts.start` deadline while the bind is pending, and transitions
1466
+ * `idle → starting → listening`. A cancelled or expired bind closes its
1467
+ * partial server and resets to `idle` for another start. `stop()` transitions
1468
+ * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1469
+ * so in-flight handlers observe cancellation, drains up to the `drain`
1470
+ * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1471
+ * is the idempotent final teardown.
1436
1472
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1437
1473
  * `close`); a `Request` is built via the router's `buildRequest`, its
1438
1474
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1472,7 +1508,7 @@ export declare class Server<TState> implements ServerInterface<TState> {
1472
1508
  use(middleware: MiddlewareHandler<TState>): void;
1473
1509
  use(middleware: readonly MiddlewareHandler<TState>[]): void;
1474
1510
  upgrade(handler: UpgradeHandler): void;
1475
- start(): Promise<number>;
1511
+ start(signal?: AbortSignal): Promise<number>;
1476
1512
  stop(): Promise<void>;
1477
1513
  destroy(): Promise<void>;
1478
1514
  }
@@ -1533,18 +1569,19 @@ export declare type ServerEventMap = {
1533
1569
  *
1534
1570
  * @remarks
1535
1571
  * `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
1536
- * both configurable before or after `start()`. `start()` binds the configured
1537
- * `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved from the
1538
- * bound address) and resolves the actually-bound port. `stop()` refuses new
1572
+ * both configurable before or after `start()`. `start(signal?)` binds the
1573
+ * configured `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved
1574
+ * from the bound address), observes caller cancellation plus `timeouts.start`
1575
+ * while binding, and resolves the actually-bound port. A cancelled or expired
1576
+ * bind closes its partial server and resets to `idle`. `stop()` refuses new
1539
1577
  * connections, fires the stop signal so in-flight handlers can observe it,
1540
1578
  * drains up to the configured deadline, then closes. `destroy()` is the final
1541
1579
  * idempotent teardown. Per request: a `Request` is built via the router's
1542
- * `buildRequest` (its signal linked to the server's stop signal), the
1543
- * composed middleware onion runs terminating in `dispatcher.handle`, and the
1544
- * result is written back via `sendResponse` — every escaping throw is caught
1545
- * by the built-in boundary (`HTTPError` → its status; anything else → a
1546
- * hidden-unless-`expose` `500`) so a handler error can never crash the
1547
- * process.
1580
+ * `buildRequest` (its signal linked to the server's stop signal), the composed
1581
+ * middleware onion runs terminating in `dispatcher.handle`, and the result is
1582
+ * written back via `sendResponse` — every escaping throw is caught by the
1583
+ * built-in boundary (`HTTPError` → its status; anything else → a
1584
+ * hidden-unless-`expose` `500`) so a handler error can never crash the process.
1548
1585
  */
1549
1586
  export declare interface ServerInterface<TState> {
1550
1587
  readonly id: string;
@@ -1555,7 +1592,14 @@ export declare interface ServerInterface<TState> {
1555
1592
  use(middleware: MiddlewareHandler<TState>): void;
1556
1593
  use(middleware: readonly MiddlewareHandler<TState>[]): void;
1557
1594
  upgrade(handler: UpgradeHandler): void;
1558
- start(): Promise<number>;
1595
+ /**
1596
+ * Bind the configured listener and resolve its actually-bound port.
1597
+ *
1598
+ * @param signal - Optional caller cancellation observed only while startup
1599
+ * is pending; aborting after this method resolves does not stop the server.
1600
+ * @returns The actually-bound TCP port
1601
+ */
1602
+ start(signal?: AbortSignal): Promise<number>;
1559
1603
  stop(): Promise<void>;
1560
1604
  destroy(): Promise<void>;
1561
1605
  }
@@ -1594,11 +1638,20 @@ export declare interface ServerInterface<TState> {
1594
1638
  * request's method + parsed `url` when one is available (absent on an
1595
1639
  * upgrade-path fault); its own throw is swallowed so reporting can never
1596
1640
  * crash the response.
1597
- * @param timeouts - `node:http` tuning knobs: `request` (max time to fully
1598
- * receive + respond, `requestTimeout`), `headers` (max time to receive the
1599
- * request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
1600
- * timeout, `keepAliveTimeout`). `headers` must not exceed `keepalive` (the
1601
- * Slowloris footgun) — construction throws a `TypeError` otherwise.
1641
+ * @param timeouts - Lifecycle and `node:http` tuning knobs: `start` (maximum
1642
+ * time to bind the listener; `0` permits no startup window), `request` (max
1643
+ * time to fully receive + respond, `requestTimeout`), `headers` (max time
1644
+ * to receive the request headers, `headersTimeout`), and `keepalive` (idle
1645
+ * keep-alive socket timeout, `keepAliveTimeout`). `headers` must not exceed
1646
+ * `keepalive` (the Slowloris footgun) — construction throws a `TypeError`
1647
+ * otherwise. Every present value must be a non-negative finite number. A
1648
+ * startup expiry rejects with a `DOMException` named `TimeoutError`; caller
1649
+ * cancellation rejects with the caller signal's `reason`.
1650
+ * @param sockets - `node:http` socket caps: `connections` maps to
1651
+ * `maxConnections` (`0` rejects every incoming connection), `headers` maps
1652
+ * to `maxHeadersCount` (`0` disables the limit), and `requests` maps to
1653
+ * `maxRequestsPerSocket` (`0` disables the limit). Every present value must
1654
+ * be a non-negative integer. Omitted leaves preserve node's defaults.
1602
1655
  * @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
1603
1656
  * (AGENTS §8), wiring initial lifecycle listeners at construction.
1604
1657
  * @param error - The emitter's listener-error handler (AGENTS §13) — a
@@ -1618,10 +1671,16 @@ export declare interface ServerOptions<TState> {
1618
1671
  url: URL;
1619
1672
  }) => void;
1620
1673
  readonly timeouts?: {
1674
+ readonly start?: number;
1621
1675
  readonly request?: number;
1622
1676
  readonly headers?: number;
1623
1677
  readonly keepalive?: number;
1624
1678
  };
1679
+ readonly sockets?: {
1680
+ readonly connections?: number;
1681
+ readonly headers?: number;
1682
+ readonly requests?: number;
1683
+ };
1625
1684
  readonly on?: EmitterHooks<ServerEventMap>;
1626
1685
  readonly error?: EmitterErrorHandler;
1627
1686
  }
@@ -1841,6 +1900,28 @@ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex,
1841
1900
  */
1842
1901
  export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
1843
1902
 
1903
+ /**
1904
+ * Wrap one middleware layer around its downstream handler.
1905
+ *
1906
+ * @remarks
1907
+ * The returned handler enforces the one-call `next` invariant while preserving
1908
+ * request substitution and the middleware's synchronous or asynchronous result.
1909
+ *
1910
+ * @typeParam TState - The consumer's opaque per-request state type
1911
+ * @param layer - The middleware layer to invoke
1912
+ * @param next - The downstream handler wrapped by `layer`
1913
+ * @returns A handler with `layer` composed around `next`
1914
+ *
1915
+ * @example
1916
+ * ```ts
1917
+ * const handle = wrapMiddleware(
1918
+ * async (_request, _context, next) => next(),
1919
+ * async () => new Response('ok'),
1920
+ * )
1921
+ * ```
1922
+ */
1923
+ export declare function wrapMiddleware<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
1924
+
1844
1925
  /**
1845
1926
  * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
1846
1927
  * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
@@ -514,6 +514,26 @@ export declare function encodeBase64Url(bytes: Uint8Array): string;
514
514
  */
515
515
  export declare type Encoding = 'gzip' | 'deflate' | 'identity';
516
516
 
517
+ /**
518
+ * Enqueue encoded text into an open byte stream.
519
+ *
520
+ * @param controller - The stream controller, when the stream has started
521
+ * @param encoder - The encoder used for the stream's byte representation
522
+ * @param closed - Whether the stream has already ended or been cancelled
523
+ * @param text - The text to encode and enqueue
524
+ * @returns Nothing
525
+ *
526
+ * @example
527
+ * ```ts
528
+ * const body = new ReadableStream<Uint8Array>({
529
+ * start(controller) {
530
+ * enqueueStreamText(controller, new TextEncoder(), false, 'hello')
531
+ * },
532
+ * })
533
+ * ```
534
+ */
535
+ export declare function enqueueStreamText(controller: ReadableStreamDefaultController<Uint8Array> | undefined, encoder: TextEncoder, closed: boolean, text: string): void;
536
+
517
537
  /**
518
538
  * A map of media type → handler for {@link NegotiatorInterface.format} — the
519
539
  * content-negotiation dispatch table.
@@ -1165,6 +1185,19 @@ export declare function parseCookies(header: string | undefined): Record<string,
1165
1185
  */
1166
1186
  export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
1167
1187
 
1188
+ /**
1189
+ * Bind and close a throwaway TCP server to resolve one available port.
1190
+ *
1191
+ * @param port - The requested port, with `0` selecting an ephemeral port
1192
+ * @returns The bound port after the probe server has closed
1193
+ *
1194
+ * @example
1195
+ * ```ts
1196
+ * const port = await probePort(0)
1197
+ * ```
1198
+ */
1199
+ export declare function probePort(port: number): Promise<number>;
1200
+
1168
1201
  /**
1169
1202
  * The parsed outcome of an HTTP `Range` request header.
1170
1203
  *
@@ -1425,14 +1458,17 @@ export declare function serializeEvent(message: SSEMessage): string;
1425
1458
  * @typeParam TState - The consumer's opaque per-request state type
1426
1459
  *
1427
1460
  * @remarks
1428
- * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
1461
+ * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1429
1462
  * server, binds the configured {@link ServerOptions.host} / {@link
1430
1463
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1431
- * bound address), and transitions `idle → starting → listening`. `stop()`
1432
- * transitions to `stopping`: refuses new connections, fires a fresh-per-run
1433
- * stop signal so in-flight handlers observe cancellation, drains up to the
1434
- * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
1435
- * `destroy()` is the idempotent final teardown.
1464
+ * bound address), observes caller cancellation plus the configured
1465
+ * `timeouts.start` deadline while the bind is pending, and transitions
1466
+ * `idle → starting → listening`. A cancelled or expired bind closes its
1467
+ * partial server and resets to `idle` for another start. `stop()` transitions
1468
+ * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1469
+ * so in-flight handlers observe cancellation, drains up to the `drain`
1470
+ * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1471
+ * is the idempotent final teardown.
1436
1472
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1437
1473
  * `close`); a `Request` is built via the router's `buildRequest`, its
1438
1474
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1472,7 +1508,7 @@ export declare class Server<TState> implements ServerInterface<TState> {
1472
1508
  use(middleware: MiddlewareHandler<TState>): void;
1473
1509
  use(middleware: readonly MiddlewareHandler<TState>[]): void;
1474
1510
  upgrade(handler: UpgradeHandler): void;
1475
- start(): Promise<number>;
1511
+ start(signal?: AbortSignal): Promise<number>;
1476
1512
  stop(): Promise<void>;
1477
1513
  destroy(): Promise<void>;
1478
1514
  }
@@ -1533,18 +1569,19 @@ export declare type ServerEventMap = {
1533
1569
  *
1534
1570
  * @remarks
1535
1571
  * `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
1536
- * both configurable before or after `start()`. `start()` binds the configured
1537
- * `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved from the
1538
- * bound address) and resolves the actually-bound port. `stop()` refuses new
1572
+ * both configurable before or after `start()`. `start(signal?)` binds the
1573
+ * configured `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved
1574
+ * from the bound address), observes caller cancellation plus `timeouts.start`
1575
+ * while binding, and resolves the actually-bound port. A cancelled or expired
1576
+ * bind closes its partial server and resets to `idle`. `stop()` refuses new
1539
1577
  * connections, fires the stop signal so in-flight handlers can observe it,
1540
1578
  * drains up to the configured deadline, then closes. `destroy()` is the final
1541
1579
  * idempotent teardown. Per request: a `Request` is built via the router's
1542
- * `buildRequest` (its signal linked to the server's stop signal), the
1543
- * composed middleware onion runs terminating in `dispatcher.handle`, and the
1544
- * result is written back via `sendResponse` — every escaping throw is caught
1545
- * by the built-in boundary (`HTTPError` → its status; anything else → a
1546
- * hidden-unless-`expose` `500`) so a handler error can never crash the
1547
- * process.
1580
+ * `buildRequest` (its signal linked to the server's stop signal), the composed
1581
+ * middleware onion runs terminating in `dispatcher.handle`, and the result is
1582
+ * written back via `sendResponse` — every escaping throw is caught by the
1583
+ * built-in boundary (`HTTPError` → its status; anything else → a
1584
+ * hidden-unless-`expose` `500`) so a handler error can never crash the process.
1548
1585
  */
1549
1586
  export declare interface ServerInterface<TState> {
1550
1587
  readonly id: string;
@@ -1555,7 +1592,14 @@ export declare interface ServerInterface<TState> {
1555
1592
  use(middleware: MiddlewareHandler<TState>): void;
1556
1593
  use(middleware: readonly MiddlewareHandler<TState>[]): void;
1557
1594
  upgrade(handler: UpgradeHandler): void;
1558
- start(): Promise<number>;
1595
+ /**
1596
+ * Bind the configured listener and resolve its actually-bound port.
1597
+ *
1598
+ * @param signal - Optional caller cancellation observed only while startup
1599
+ * is pending; aborting after this method resolves does not stop the server.
1600
+ * @returns The actually-bound TCP port
1601
+ */
1602
+ start(signal?: AbortSignal): Promise<number>;
1559
1603
  stop(): Promise<void>;
1560
1604
  destroy(): Promise<void>;
1561
1605
  }
@@ -1594,11 +1638,20 @@ export declare interface ServerInterface<TState> {
1594
1638
  * request's method + parsed `url` when one is available (absent on an
1595
1639
  * upgrade-path fault); its own throw is swallowed so reporting can never
1596
1640
  * crash the response.
1597
- * @param timeouts - `node:http` tuning knobs: `request` (max time to fully
1598
- * receive + respond, `requestTimeout`), `headers` (max time to receive the
1599
- * request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
1600
- * timeout, `keepAliveTimeout`). `headers` must not exceed `keepalive` (the
1601
- * Slowloris footgun) — construction throws a `TypeError` otherwise.
1641
+ * @param timeouts - Lifecycle and `node:http` tuning knobs: `start` (maximum
1642
+ * time to bind the listener; `0` permits no startup window), `request` (max
1643
+ * time to fully receive + respond, `requestTimeout`), `headers` (max time
1644
+ * to receive the request headers, `headersTimeout`), and `keepalive` (idle
1645
+ * keep-alive socket timeout, `keepAliveTimeout`). `headers` must not exceed
1646
+ * `keepalive` (the Slowloris footgun) — construction throws a `TypeError`
1647
+ * otherwise. Every present value must be a non-negative finite number. A
1648
+ * startup expiry rejects with a `DOMException` named `TimeoutError`; caller
1649
+ * cancellation rejects with the caller signal's `reason`.
1650
+ * @param sockets - `node:http` socket caps: `connections` maps to
1651
+ * `maxConnections` (`0` rejects every incoming connection), `headers` maps
1652
+ * to `maxHeadersCount` (`0` disables the limit), and `requests` maps to
1653
+ * `maxRequestsPerSocket` (`0` disables the limit). Every present value must
1654
+ * be a non-negative integer. Omitted leaves preserve node's defaults.
1602
1655
  * @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
1603
1656
  * (AGENTS §8), wiring initial lifecycle listeners at construction.
1604
1657
  * @param error - The emitter's listener-error handler (AGENTS §13) — a
@@ -1618,10 +1671,16 @@ export declare interface ServerOptions<TState> {
1618
1671
  url: URL;
1619
1672
  }) => void;
1620
1673
  readonly timeouts?: {
1674
+ readonly start?: number;
1621
1675
  readonly request?: number;
1622
1676
  readonly headers?: number;
1623
1677
  readonly keepalive?: number;
1624
1678
  };
1679
+ readonly sockets?: {
1680
+ readonly connections?: number;
1681
+ readonly headers?: number;
1682
+ readonly requests?: number;
1683
+ };
1625
1684
  readonly on?: EmitterHooks<ServerEventMap>;
1626
1685
  readonly error?: EmitterErrorHandler;
1627
1686
  }
@@ -1841,6 +1900,28 @@ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex,
1841
1900
  */
1842
1901
  export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
1843
1902
 
1903
+ /**
1904
+ * Wrap one middleware layer around its downstream handler.
1905
+ *
1906
+ * @remarks
1907
+ * The returned handler enforces the one-call `next` invariant while preserving
1908
+ * request substitution and the middleware's synchronous or asynchronous result.
1909
+ *
1910
+ * @typeParam TState - The consumer's opaque per-request state type
1911
+ * @param layer - The middleware layer to invoke
1912
+ * @param next - The downstream handler wrapped by `layer`
1913
+ * @returns A handler with `layer` composed around `next`
1914
+ *
1915
+ * @example
1916
+ * ```ts
1917
+ * const handle = wrapMiddleware(
1918
+ * async (_request, _context, next) => next(),
1919
+ * async () => new Response('ok'),
1920
+ * )
1921
+ * ```
1922
+ */
1923
+ export declare function wrapMiddleware<TState>(layer: MiddlewareHandler<TState>, next: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
1924
+
1844
1925
  /**
1845
1926
  * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
1846
1927
  * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).