@orkestrel/server 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,307 @@
1
- export type * from './types.js';
2
- export * from './helpers.js';
3
- export * from './factories.js';
4
- export * from './Server.js';
1
+ import { AddressInfo } from 'node:net';
2
+ import { ConnectionInfo } from '../core/index.ts';
3
+ import { DispatcherInterface } from '@orkestrel/router';
4
+ import { Duplex } from 'node:stream';
5
+ import { EmitterErrorHandler } from '@orkestrel/emitter';
6
+ import { EmitterHooks } from '@orkestrel/emitter';
7
+ import { EmitterInterface } from '@orkestrel/emitter';
8
+ import { IncomingMessage } from 'node:http';
9
+ import { MiddlewareHandler } from '../core/index.ts';
10
+
11
+ /**
12
+ * Derives a consumer's per-request `TState` from the adapter-injected
13
+ * {@link ConnectionInfo} — `ServerOptions.state`, invoked once per request
14
+ * before the middleware onion runs.
15
+ *
16
+ * @typeParam TState - The consumer's opaque per-request state type
17
+ */
18
+ export declare type ConnectionStateFunction<TState> = (connection: ConnectionInfo) => TState;
19
+
20
+ /**
21
+ * Create a {@link ServerInterface} — the node face's HTTP server facade over
22
+ * a consumed `@orkestrel/router` dispatcher.
23
+ *
24
+ * @typeParam TState - The consumer's opaque per-request state type
25
+ * @param options - {@link ServerOptions}
26
+ * @returns A {@link ServerInterface}, not yet started
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { createServer } from '@src/server'
31
+ * import { createDispatcher } from '@orkestrel/router'
32
+ *
33
+ * const dispatcher = createDispatcher<{ readonly ip?: string }>()
34
+ * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
35
+ *
36
+ * const server = createServer({
37
+ * dispatcher,
38
+ * state: (connection) => ({ ip: connection.ip }),
39
+ * })
40
+ * const port = await server.start()
41
+ * await server.stop()
42
+ * ```
43
+ */
44
+ export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
45
+
46
+ /**
47
+ * Find a FREE TCP port — bind a throwaway `node:net` server, read the
48
+ * OS-assigned port, close it, and resolve that port.
49
+ *
50
+ * @remarks
51
+ * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
52
+ * and returns it. With a `preferred` port it tries THAT port first and
53
+ * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
54
+ * ephemeral free port rather than rejecting — a caller always gets a usable
55
+ * port. It binds then immediately closes a probe server, so the returned
56
+ * port is free at the instant of the probe (an inherent TOCTOU race — bind it
57
+ * promptly). Rejects only on an unexpected listen error other than a taken
58
+ * `preferred` port (e.g. a permission fault).
59
+ *
60
+ * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
61
+ * fall back to an ephemeral port
62
+ * @returns A free TCP port number
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { createServer, discoverPort } from '@src/server'
67
+ *
68
+ * const port = await discoverPort() // a guaranteed-free ephemeral port
69
+ * ```
70
+ */
71
+ export declare function discoverPort(preferred?: number): Promise<number>;
72
+
73
+ /**
74
+ * Whether a `node:net` `server.address()` return is the structured
75
+ * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
76
+ * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
77
+ * and the `Server`'s own port resolution read the bound port through.
78
+ *
79
+ * @param value - The `server.address()` return (`AddressInfo | string | null`)
80
+ * @returns `true` when `value` is an `AddressInfo` with a numeric `port`
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * import { isAddressInfo } from '@src/server'
85
+ *
86
+ * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
87
+ * isAddressInfo(null) // false
88
+ * ```
89
+ */
90
+ export declare function isAddressInfo(value: unknown): value is AddressInfo;
91
+
92
+ /**
93
+ * The HTTP server facade — an observable `node:http` lifecycle composing the
94
+ * `@src/core` middleware onion around a consumed `@orkestrel/router`
95
+ * dispatcher.
96
+ *
97
+ * @typeParam TState - The consumer's opaque per-request state type
98
+ *
99
+ * @remarks
100
+ * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
101
+ * server, binds the configured {@link ServerOptions.host} / {@link
102
+ * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
103
+ * bound address), and transitions `idle → starting → listening`. `stop()`
104
+ * transitions to `stopping`: refuses new connections, fires a fresh-per-run
105
+ * stop signal so in-flight handlers observe cancellation, drains up to the
106
+ * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
107
+ * `destroy()` is the idempotent final teardown.
108
+ * - **Per request.** In-flight is tracked (finished on response `finish` or
109
+ * `close`); a `Request` is built via the router's `buildRequest`, its
110
+ * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
111
+ * `linkSignal` (a fresh `Request` is constructed with the linked signal —
112
+ * `buildRequest`'s own abort, tied to client disconnect, composes with the
113
+ * server's stop signal via `AbortSignal.any`, so a handler awaiting
114
+ * `request.signal` observes BOTH); `context.state` is built via
115
+ * {@link ServerOptions.state} from the connection facts; the composed
116
+ * middleware onion runs, terminating in `dispatcher.handle`; the result is
117
+ * written back via `sendResponse`.
118
+ * - **The built-in boundary** wraps the WHOLE per-request chain, including
119
+ * setup: `buildRequest` runs behind its own inner boundary that maps a
120
+ * throw (e.g. a malformed `Host` header) to a silent `400` with no
121
+ * `error` emit; everything after (`Request` reconstruction, connection
122
+ * facts, `state`, the composed onion, and `dispatcher.handle`) runs
123
+ * behind the outer boundary — a thrown `HTTPError` renders as its status +
124
+ * message; any other throw renders `500` (message hidden unless
125
+ * `expose`), `report` is invoked (its own throw swallowed), and `error` is
126
+ * emitted. A server-owned last resort wraps the final `sendResponse`
127
+ * write itself: if even that fails, the connection is destroyed rather
128
+ * than left to escape as an unhandled error.
129
+ * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
130
+ * throwing handler is treated as declined and surfaced on `error`, an
131
+ * unclaimed upgrade destroys the socket), bound per-run to this instance.
132
+ * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
133
+ * exposed as `readonly emitter`; the emitter isolates a listener throw and
134
+ * routes it to the `error` OPTION (not the domain `error` event).
135
+ */
136
+ export declare class Server<TState> implements ServerInterface<TState> {
137
+ #private;
138
+ readonly id: `${string}-${string}-${string}-${string}-${string}`;
139
+ constructor(options: ServerOptions<TState>);
140
+ get status(): ServerStatus;
141
+ get port(): number | undefined;
142
+ get dispatcher(): DispatcherInterface<TState>;
143
+ get emitter(): EmitterInterface<ServerEventMap>;
144
+ use(middleware: MiddlewareHandler<TState>): void;
145
+ use(middleware: readonly MiddlewareHandler<TState>[]): void;
146
+ upgrade(handler: UpgradeHandler): void;
147
+ start(): Promise<number>;
148
+ stop(): Promise<void>;
149
+ destroy(): Promise<void>;
150
+ }
151
+
152
+ /**
153
+ * The `Server`'s observable lifecycle events (AGENTS §13).
154
+ *
155
+ * @remarks
156
+ * - `start` — `listen()` resolved; carries the actually-bound port (an
157
+ * ephemeral `0` resolves to the OS-assigned one).
158
+ * - `request` — fired once per incoming request, before the middleware onion
159
+ * runs, carrying the raw method + the parsed pathname.
160
+ * - `upgrade` — a raw protocol-upgrade fan-out settled; carries the original
161
+ * `IncomingMessage` and whether a registered {@link UpgradeHandler} claimed it.
162
+ * - `error` — a server-level fault: an escaping throw past the built-in
163
+ * boundary, an upgrade handler's throw, or a listen failure.
164
+ * - `stop` — `stop()` began (status just moved to `'stopping'`).
165
+ * - `drain` — the graceful drain settled (deadline hit or all finished);
166
+ * carries the still-pending request count (`0` on a clean drain).
167
+ */
168
+ export declare type ServerEventMap = {
169
+ readonly start: readonly [port: number];
170
+ readonly request: readonly [method: string, pathname: string];
171
+ readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
172
+ readonly error: readonly [error: unknown];
173
+ readonly stop: readonly [];
174
+ readonly drain: readonly [pending: number];
175
+ };
176
+
177
+ /**
178
+ * The HTTP server facade — an observable `node:http` lifecycle that composes
179
+ * a middleware onion (the `@src/core` seam) around a consumed
180
+ * `@orkestrel/router` {@link DispatcherInterface}.
181
+ *
182
+ * @typeParam TState - The consumer's opaque per-request state type
183
+ *
184
+ * @remarks
185
+ * `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
186
+ * both configurable before or after `start()`. `start()` binds the configured
187
+ * `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved from the
188
+ * bound address) and resolves the actually-bound port. `stop()` refuses new
189
+ * connections, fires the stop signal so in-flight handlers can observe it,
190
+ * drains up to the configured deadline, then closes. `destroy()` is the final
191
+ * idempotent teardown. Per request: a `Request` is built via the router's
192
+ * `buildRequest` (its signal linked to the server's stop signal), the
193
+ * composed middleware onion runs terminating in `dispatcher.handle`, and the
194
+ * result is written back via `sendResponse` — every escaping throw is caught
195
+ * by the built-in boundary (`HTTPError` → its status; anything else → a
196
+ * hidden-unless-`expose` `500`) so a handler error can never crash the
197
+ * process.
198
+ */
199
+ export declare interface ServerInterface<TState> {
200
+ readonly id: string;
201
+ readonly status: ServerStatus;
202
+ readonly port: number | undefined;
203
+ readonly dispatcher: DispatcherInterface<TState>;
204
+ readonly emitter: EmitterInterface<ServerEventMap>;
205
+ use(middleware: MiddlewareHandler<TState>): void;
206
+ use(middleware: readonly MiddlewareHandler<TState>[]): void;
207
+ upgrade(handler: UpgradeHandler): void;
208
+ start(): Promise<number>;
209
+ stop(): Promise<void>;
210
+ destroy(): Promise<void>;
211
+ }
212
+
213
+ /**
214
+ * Options for `createServer`.
215
+ *
216
+ * @param dispatcher - The `@orkestrel/router` {@link DispatcherInterface} the
217
+ * composed middleware onion terminates into — bring-your-own router (the
218
+ * composition seam stays explicit and independently testable).
219
+ * @param state - {@link ConnectionStateFunction} — builds each request's
220
+ * `TState` from the connection facts (peer IP, TLS flag). `X-Forwarded-For`
221
+ * is never implicitly trusted here; a deployment behind a trusted proxy
222
+ * derives its own client key in this function or in middleware.
223
+ * @param middleware - Initial middleware, run in array order (outer-first);
224
+ * more may be added later via `use`.
225
+ * @param host - The network interface `start()` binds to (`node:http`
226
+ * `server.listen`'s host). Omitted ⇒ node's default (all interfaces).
227
+ * @param port - The TCP port `start()` binds to. Omitted or `0` ⇒ an
228
+ * EPHEMERAL, OS-assigned free port (the default); `start()` always resolves
229
+ * the actually-bound port. A port already in use rejects `start()` with
230
+ * `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
231
+ * guaranteed-free port up front).
232
+ * @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
233
+ * server stops accepting new connections and gives in-flight requests this
234
+ * long to finish before forcing sockets closed. Defaults to
235
+ * `DEFAULT_DRAIN_MS`. Must be a non-negative finite number.
236
+ * @param limit - The default request-body byte cap the context's `body()`
237
+ * reads through. Defaults to `DEFAULT_BODY_LIMIT`. Must be a non-negative
238
+ * finite number.
239
+ * @param expose - Whether a non-`HTTPError` throw's message is sent in the
240
+ * 500 response body (an `HTTPError`'s own message is always client-facing).
241
+ * Defaults to `false`.
242
+ * @param report - A fire-and-forget sink the built-in boundary hands every
243
+ * caught error to (logging / metrics); its own throw is swallowed so
244
+ * reporting can never crash the response.
245
+ * @param timeouts - `node:http` tuning knobs: `request` (max time to fully
246
+ * receive + respond, `requestTimeout`), `headers` (max time to receive the
247
+ * request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
248
+ * timeout, `keepAliveTimeout`). `headers` must not exceed `keepalive` (the
249
+ * Slowloris footgun) — construction throws a `TypeError` otherwise.
250
+ * @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
251
+ * (AGENTS §8), wiring initial lifecycle listeners at construction.
252
+ * @param error - The emitter's listener-error handler (AGENTS §13) — a
253
+ * listener throw routes here, never to the domain `error` event.
254
+ */
255
+ export declare interface ServerOptions<TState> {
256
+ readonly dispatcher: DispatcherInterface<TState>;
257
+ readonly state: ConnectionStateFunction<TState>;
258
+ readonly middleware?: readonly MiddlewareHandler<TState>[];
259
+ readonly host?: string;
260
+ readonly port?: number;
261
+ readonly drain?: number;
262
+ readonly limit?: number;
263
+ readonly expose?: boolean;
264
+ readonly report?: (error: unknown) => void;
265
+ readonly timeouts?: {
266
+ readonly request?: number;
267
+ readonly headers?: number;
268
+ readonly keepalive?: number;
269
+ };
270
+ readonly on?: EmitterHooks<ServerEventMap>;
271
+ readonly error?: EmitterErrorHandler;
272
+ }
273
+
274
+ /**
275
+ * The `Server`'s lifecycle state (AGENTS §10 vocabulary).
276
+ *
277
+ * @remarks
278
+ * `idle` (never started, or a fresh instance) → `starting` (binding the
279
+ * listener) → `listening` (accepting requests) → `stopping` (draining
280
+ * in-flight requests) → `stopped` (closed; `start()` may run again, minting a
281
+ * fresh stop signal). `destroy()` is a terminal teardown reachable from any
282
+ * state, idempotent once `stopped`.
283
+ */
284
+ export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
285
+
286
+ /**
287
+ * A raw `node:http` protocol-upgrade claimant — registered via
288
+ * {@link ServerInterface.upgrade}.
289
+ *
290
+ * @remarks
291
+ * Fan-out semantics (verbatim, PROPOSAL §4): handlers run in registration
292
+ * order, the FIRST to return `true` CLAIMS (owns) the socket and stops the
293
+ * fan-out; a handler that THROWS is treated as declined (the throw surfaces
294
+ * on the `error` event) and the fan-out continues; if NONE claim it, the
295
+ * socket is destroyed so an unhandled upgrade never leaks a dangling
296
+ * connection. `request` / `socket` / `head` are node's own raw values, handed
297
+ * over verbatim — no assertion at this boundary (AGENTS §14).
298
+ *
299
+ * @param request - The raw `node:http` upgrade request
300
+ * @param socket - The raw, now-detached `Duplex` connection
301
+ * @param head - The first packet of the upgraded stream, if any
302
+ * @returns `true` to CLAIM the socket (this handler now owns it), `false` to
303
+ * decline and let a later handler try
304
+ */
305
+ export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
306
+
307
+ export { }
@@ -0,0 +1,386 @@
1
+ import { createServer as createServer$1 } from "node:net";
2
+ import { isFiniteNumber, isFunction, isNumber, isRecord } from "@orkestrel/contract";
3
+ import { createServer as createServer$2 } from "node:http";
4
+ import { DEFAULT_BODY_LIMIT, DEFAULT_DRAIN_MS, HTTPError, compose, isHTTPError, readBody } from "../core/index.js";
5
+ import { createAbort, linkSignal } from "@orkestrel/abort";
6
+ import { createTimeout } from "@orkestrel/timeout";
7
+ import { buildRequest, isEncryptedSocket, sendResponse } from "@orkestrel/router/server";
8
+ import { Emitter } from "@orkestrel/emitter";
9
+ //#region src/server/helpers.ts
10
+ /**
11
+ * Whether a `node:net` `server.address()` return is the structured
12
+ * {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
13
+ * or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
14
+ * and the `Server`'s own port resolution read the bound port through.
15
+ *
16
+ * @param value - The `server.address()` return (`AddressInfo | string | null`)
17
+ * @returns `true` when `value` is an `AddressInfo` with a numeric `port`
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { isAddressInfo } from '@src/server'
22
+ *
23
+ * isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
24
+ * isAddressInfo(null) // false
25
+ * ```
26
+ */
27
+ function isAddressInfo(value) {
28
+ return isRecord(value) && isNumber(value.port);
29
+ }
30
+ /**
31
+ * Find a FREE TCP port — bind a throwaway `node:net` server, read the
32
+ * OS-assigned port, close it, and resolve that port.
33
+ *
34
+ * @remarks
35
+ * With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
36
+ * and returns it. With a `preferred` port it tries THAT port first and
37
+ * returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
38
+ * ephemeral free port rather than rejecting — a caller always gets a usable
39
+ * port. It binds then immediately closes a probe server, so the returned
40
+ * port is free at the instant of the probe (an inherent TOCTOU race — bind it
41
+ * promptly). Rejects only on an unexpected listen error other than a taken
42
+ * `preferred` port (e.g. a permission fault).
43
+ *
44
+ * @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
45
+ * fall back to an ephemeral port
46
+ * @returns A free TCP port number
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * import { createServer, discoverPort } from '@src/server'
51
+ *
52
+ * const port = await discoverPort() // a guaranteed-free ephemeral port
53
+ * ```
54
+ */
55
+ function discoverPort(preferred) {
56
+ return new Promise((resolve, reject) => {
57
+ const bind = (port, fallback) => {
58
+ const probe = createServer$1();
59
+ const onError = (error) => {
60
+ probe.close();
61
+ const taken = "code" in error && error.code === "EADDRINUSE";
62
+ if (fallback && taken) bind(0, false);
63
+ else reject(error);
64
+ };
65
+ probe.once("error", onError);
66
+ probe.listen(port, () => {
67
+ const address = probe.address();
68
+ const resolved = isAddressInfo(address) ? address.port : 0;
69
+ probe.close(() => resolve(resolved));
70
+ });
71
+ };
72
+ bind(preferred ?? 0, preferred !== void 0);
73
+ });
74
+ }
75
+ //#endregion
76
+ //#region src/server/Server.ts
77
+ /**
78
+ * The HTTP server facade — an observable `node:http` lifecycle composing the
79
+ * `@src/core` middleware onion around a consumed `@orkestrel/router`
80
+ * dispatcher.
81
+ *
82
+ * @typeParam TState - The consumer's opaque per-request state type
83
+ *
84
+ * @remarks
85
+ * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
86
+ * server, binds the configured {@link ServerOptions.host} / {@link
87
+ * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
88
+ * bound address), and transitions `idle → starting → listening`. `stop()`
89
+ * transitions to `stopping`: refuses new connections, fires a fresh-per-run
90
+ * stop signal so in-flight handlers observe cancellation, drains up to the
91
+ * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
92
+ * `destroy()` is the idempotent final teardown.
93
+ * - **Per request.** In-flight is tracked (finished on response `finish` or
94
+ * `close`); a `Request` is built via the router's `buildRequest`, its
95
+ * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
96
+ * `linkSignal` (a fresh `Request` is constructed with the linked signal —
97
+ * `buildRequest`'s own abort, tied to client disconnect, composes with the
98
+ * server's stop signal via `AbortSignal.any`, so a handler awaiting
99
+ * `request.signal` observes BOTH); `context.state` is built via
100
+ * {@link ServerOptions.state} from the connection facts; the composed
101
+ * middleware onion runs, terminating in `dispatcher.handle`; the result is
102
+ * written back via `sendResponse`.
103
+ * - **The built-in boundary** wraps the WHOLE per-request chain, including
104
+ * setup: `buildRequest` runs behind its own inner boundary that maps a
105
+ * throw (e.g. a malformed `Host` header) to a silent `400` with no
106
+ * `error` emit; everything after (`Request` reconstruction, connection
107
+ * facts, `state`, the composed onion, and `dispatcher.handle`) runs
108
+ * behind the outer boundary — a thrown `HTTPError` renders as its status +
109
+ * message; any other throw renders `500` (message hidden unless
110
+ * `expose`), `report` is invoked (its own throw swallowed), and `error` is
111
+ * emitted. A server-owned last resort wraps the final `sendResponse`
112
+ * write itself: if even that fails, the connection is destroyed rather
113
+ * than left to escape as an unhandled error.
114
+ * - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
115
+ * throwing handler is treated as declined and surfaced on `error`, an
116
+ * unclaimed upgrade destroys the socket), bound per-run to this instance.
117
+ * - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
118
+ * exposed as `readonly emitter`; the emitter isolates a listener throw and
119
+ * routes it to the `error` OPTION (not the domain `error` event).
120
+ */
121
+ var Server = class {
122
+ id = crypto.randomUUID();
123
+ #dispatcher;
124
+ #state;
125
+ #middleware;
126
+ #upgradeHandlers = [];
127
+ #emitter;
128
+ #host;
129
+ #configuredPort;
130
+ #drain;
131
+ #limit;
132
+ #expose;
133
+ #report;
134
+ #timeouts;
135
+ #http;
136
+ #abort = createAbort();
137
+ #status = "idle";
138
+ #port;
139
+ #pending = 0;
140
+ #waiters = [];
141
+ constructor(options) {
142
+ if (!isFunction(options.state)) throw new TypeError("ServerOptions.state must be a function");
143
+ if (options.report !== void 0 && !isFunction(options.report)) throw new TypeError("ServerOptions.report must be a function");
144
+ const drain = options.drain ?? DEFAULT_DRAIN_MS;
145
+ if (!isFiniteNumber(drain) || drain < 0) throw new TypeError("ServerOptions.drain must be a non-negative finite number");
146
+ const limit = options.limit ?? DEFAULT_BODY_LIMIT;
147
+ if (!isFiniteNumber(limit) || limit < 0) throw new TypeError("ServerOptions.limit must be a non-negative finite number");
148
+ const timeouts = options.timeouts ?? {};
149
+ for (const [name, value] of Object.entries(timeouts)) if (value !== void 0 && (!isFiniteNumber(value) || value < 0)) throw new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`);
150
+ if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
151
+ this.#dispatcher = options.dispatcher;
152
+ this.#state = options.state;
153
+ this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
154
+ this.#host = options.host;
155
+ this.#configuredPort = options.port;
156
+ this.#drain = drain;
157
+ this.#limit = limit;
158
+ this.#expose = options.expose ?? false;
159
+ this.#report = options.report;
160
+ this.#timeouts = timeouts;
161
+ this.#emitter = new Emitter({
162
+ on: options.on,
163
+ error: options.error
164
+ });
165
+ }
166
+ get status() {
167
+ return this.#status;
168
+ }
169
+ get port() {
170
+ return this.#port;
171
+ }
172
+ get dispatcher() {
173
+ return this.#dispatcher;
174
+ }
175
+ get emitter() {
176
+ return this.#emitter;
177
+ }
178
+ use(middleware) {
179
+ if (typeof middleware === "function") this.#middleware.push(middleware);
180
+ else this.#middleware.push(...middleware);
181
+ }
182
+ upgrade(handler) {
183
+ this.#upgradeHandlers.push(handler);
184
+ }
185
+ start() {
186
+ if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
187
+ this.#status = "starting";
188
+ this.#abort = createAbort();
189
+ const server = createServer$2((request, response) => this.#handle(request, response));
190
+ if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
191
+ if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
192
+ if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
193
+ server.on("upgrade", (request, socket, head) => this.#onUpgrade(request, socket, head));
194
+ this.#http = server;
195
+ return new Promise((resolve, reject) => {
196
+ const onError = (error) => {
197
+ server.off("listening", onListening);
198
+ this.#http = void 0;
199
+ this.#status = "idle";
200
+ reject(error);
201
+ };
202
+ const onListening = () => {
203
+ server.off("error", onError);
204
+ const port = this.#resolvePort(server);
205
+ this.#port = port;
206
+ this.#status = "listening";
207
+ this.#emitter.emit("start", port);
208
+ resolve(port);
209
+ };
210
+ server.once("error", onError);
211
+ server.once("listening", onListening);
212
+ server.listen(this.#configuredPort ?? 0, this.#host);
213
+ });
214
+ }
215
+ async stop() {
216
+ if (this.#status !== "listening") return;
217
+ this.#status = "stopping";
218
+ this.#emitter.emit("stop");
219
+ const server = this.#http;
220
+ this.#abort.abort();
221
+ const deadline = createTimeout({ ms: this.#drain });
222
+ deadline.start();
223
+ await this.#drainPending(deadline.signal);
224
+ deadline.clear();
225
+ const pending = this.#pending;
226
+ this.#emitter.emit("drain", pending);
227
+ if (server !== void 0) await this.#close(server, pending > 0);
228
+ this.#http = void 0;
229
+ this.#port = void 0;
230
+ this.#status = "stopped";
231
+ }
232
+ async destroy() {
233
+ if (this.#status === "stopped" && this.#http === void 0) {
234
+ this.#emitter.destroy();
235
+ return;
236
+ }
237
+ if (!this.#abort.aborted) this.#abort.abort();
238
+ const server = this.#http;
239
+ if (server !== void 0) await this.#close(server, true);
240
+ this.#http = void 0;
241
+ this.#port = void 0;
242
+ this.#status = "stopped";
243
+ this.#emitter.destroy();
244
+ }
245
+ #handle(message, response) {
246
+ const finish = this.#trackStart();
247
+ response.once("finish", finish);
248
+ response.once("close", finish);
249
+ this.#accept(message, response);
250
+ }
251
+ async #accept(message, response) {
252
+ let raw;
253
+ try {
254
+ raw = buildRequest(message);
255
+ } catch {
256
+ await this.#respond(this.#boundary(new HTTPError(400, "invalid request")), response);
257
+ return;
258
+ }
259
+ try {
260
+ const linked = linkSignal(raw.signal, this.#abort.signal);
261
+ const request = new Request(raw, { signal: linked });
262
+ const url = new URL(request.url);
263
+ this.#emitter.emit("request", request.method, url.pathname);
264
+ const connection = {
265
+ ip: message.socket.remoteAddress,
266
+ encrypted: isEncryptedSocket(message.socket)
267
+ };
268
+ let cached;
269
+ const context = {
270
+ url,
271
+ method: request.method,
272
+ state: this.#state(connection),
273
+ body: () => {
274
+ cached ??= readBody(request, { limit: this.#limit });
275
+ return cached;
276
+ }
277
+ };
278
+ const result = await compose(this.#middleware, (currentRequest, currentContext) => this.#dispatcher.handle(currentRequest, currentContext.state))(request, context);
279
+ await this.#respond(result, response);
280
+ } catch (error) {
281
+ const mapped = this.#boundary(error);
282
+ if (!isHTTPError(error)) {
283
+ this.#emitter.emit("error", error);
284
+ if (this.#report !== void 0) try {
285
+ this.#report(error);
286
+ } catch {}
287
+ }
288
+ await this.#respond(mapped, response);
289
+ }
290
+ }
291
+ async #respond(result, response) {
292
+ try {
293
+ await sendResponse(result, response);
294
+ } catch {
295
+ response.destroy();
296
+ }
297
+ }
298
+ #boundary(error) {
299
+ if (isHTTPError(error)) return new Response(error.message, { status: error.status });
300
+ const message = this.#expose && error instanceof Error ? error.message : "Internal Server Error";
301
+ return new Response(message, { status: 500 });
302
+ }
303
+ #onUpgrade(request, socket, head) {
304
+ let handled = false;
305
+ for (const handler of this.#upgradeHandlers) try {
306
+ if (handler(request, socket, head)) {
307
+ handled = true;
308
+ break;
309
+ }
310
+ } catch (error) {
311
+ this.#emitter.emit("error", error);
312
+ }
313
+ if (!handled) socket.destroy();
314
+ this.#emitter.emit("upgrade", request, handled);
315
+ }
316
+ #resolvePort(server) {
317
+ const address = server.address();
318
+ if (isAddressInfo(address)) return address.port;
319
+ return 0;
320
+ }
321
+ #close(server, force) {
322
+ return new Promise((resolve) => {
323
+ server.close(() => resolve());
324
+ if (force) server.closeAllConnections();
325
+ else server.closeIdleConnections();
326
+ });
327
+ }
328
+ #trackStart() {
329
+ this.#pending += 1;
330
+ let finished = false;
331
+ return () => {
332
+ if (finished) return;
333
+ finished = true;
334
+ this.#pending -= 1;
335
+ if (this.#pending === 0) {
336
+ const waiters = this.#waiters;
337
+ this.#waiters = [];
338
+ for (const wake of waiters) wake();
339
+ }
340
+ };
341
+ }
342
+ #drainPending(signal) {
343
+ if (this.#pending === 0 || signal.aborted) return Promise.resolve();
344
+ return new Promise((resolve) => {
345
+ const onDone = () => {
346
+ signal.removeEventListener("abort", onDone);
347
+ resolve();
348
+ };
349
+ this.#waiters.push(onDone);
350
+ signal.addEventListener("abort", onDone, { once: true });
351
+ });
352
+ }
353
+ };
354
+ //#endregion
355
+ //#region src/server/factories.ts
356
+ /**
357
+ * Create a {@link ServerInterface} — the node face's HTTP server facade over
358
+ * a consumed `@orkestrel/router` dispatcher.
359
+ *
360
+ * @typeParam TState - The consumer's opaque per-request state type
361
+ * @param options - {@link ServerOptions}
362
+ * @returns A {@link ServerInterface}, not yet started
363
+ *
364
+ * @example
365
+ * ```ts
366
+ * import { createServer } from '@src/server'
367
+ * import { createDispatcher } from '@orkestrel/router'
368
+ *
369
+ * const dispatcher = createDispatcher<{ readonly ip?: string }>()
370
+ * dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
371
+ *
372
+ * const server = createServer({
373
+ * dispatcher,
374
+ * state: (connection) => ({ ip: connection.ip }),
375
+ * })
376
+ * const port = await server.start()
377
+ * await server.stop()
378
+ * ```
379
+ */
380
+ function createServer(options) {
381
+ return new Server(options);
382
+ }
383
+ //#endregion
384
+ export { Server, createServer, discoverPort, isAddressInfo };
385
+
386
+ //# sourceMappingURL=index.js.map