@orkestrel/server 0.0.2 → 0.0.3

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 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#dispatcher","#state","#middleware","#upgradeHandlers","#emitter","#host","#configuredPort","#drain","#limit","#expose","#report","#timeouts","#status","#port","#abort","#handle","#onUpgrade","#http","#resolvePort","#drainPending","#pending","#close","#trackStart","#accept","#respond","#boundary","#waiters"],"sources":["../../../src/server/helpers.ts","../../../src/server/Server.ts","../../../src/server/factories.ts"],"sourcesContent":["// ============================================================================\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 in `@src/core` and is consumed, never duplicated\n// (the socket-encrypted narrow and the `Request`/`Response` conversion are\n// `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` / `sendResponse`).\n// ============================================================================\n\nimport type { AddressInfo } from 'node:net'\nimport { createServer as createNetServer } from 'node:net'\nimport { isNumber, isRecord } from '@orkestrel/contract'\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 * 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 function discoverPort(preferred?: number): Promise<number> {\n\treturn new Promise<number>((resolve, reject) => {\n\t\tconst bind = (port: number, fallback: boolean): void => {\n\t\t\tconst probe = createNetServer()\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tprobe.close()\n\t\t\t\tconst taken = 'code' in error && error.code === 'EADDRINUSE'\n\t\t\t\tif (fallback && taken) bind(0, false)\n\t\t\t\telse reject(error)\n\t\t\t}\n\t\t\tprobe.once('error', onError)\n\t\t\tprobe.listen(port, () => {\n\t\t\t\tconst address = probe.address()\n\t\t\t\tconst resolved = isAddressInfo(address) ? address.port : 0\n\t\t\t\tprobe.close(() => resolve(resolved))\n\t\t\t})\n\t\t}\n\t\tbind(preferred ?? 0, preferred !== undefined)\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 { MiddlewareContext, MiddlewareHandler } from '@src/core'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnectionStateFunction,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { createServer as createHTTPServer } from 'node:http'\nimport {\n\tcompose,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DRAIN_MS,\n\tHTTPError,\n\tisHTTPError,\n\treadBody,\n} from '@src/core'\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 } from '@orkestrel/contract'\nimport { isAddressInfo } from './helpers.js'\n\n/**\n * The HTTP server facade — an observable `node:http` lifecycle composing the\n * `@src/core` 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()` 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), and transitions `idle → starting → listening`. `stop()`\n * transitions to `stopping`: refuses new connections, fires a fresh-per-run\n * stop signal so in-flight handlers observe cancellation, drains up to the\n * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.\n * `destroy()` 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, tied to client disconnect, composes with the\n * server's stop signal via `AbortSignal.any`, so a handler awaiting\n * `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) => void) | undefined\n\treadonly #timeouts: {\n\t\treadonly request?: number\n\t\treadonly headers?: number\n\t\treadonly keepalive?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#abort: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#pending = 0\n\t#waiters: (() => void)[] = []\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\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.#emitter = new Emitter<ServerEventMap>({ on: options.on, error: options.error })\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(): 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\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 new Promise<number>((resolve, reject) => {\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tserver.off('listening', onListening)\n\t\t\t\tthis.#http = undefined\n\t\t\t\tthis.#status = 'idle'\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst onListening = (): void => {\n\t\t\t\tserver.off('error', onError)\n\t\t\t\tconst port = this.#resolvePort(server)\n\t\t\t\tthis.#port = port\n\t\t\t\tthis.#status = 'listening'\n\t\t\t\tthis.#emitter.emit('start', port)\n\t\t\t\tresolve(port)\n\t\t\t}\n\t\t\tserver.once('error', onError)\n\t\t\tserver.once('listening', onListening)\n\t\t\tserver.listen(this.#configuredPort ?? 0, this.#host)\n\t\t})\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)\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\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\tconst url = new URL(request.url)\n\t\t\tthis.#emitter.emit('request', request.method, url.pathname)\n\t\t\tconst connection = {\n\t\t\t\tip: message.socket.remoteAddress,\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tlet cached: Promise<unknown> | undefined\n\t\t\tconst context: MiddlewareContext<TState> = {\n\t\t\t\turl,\n\t\t\t\tmethod: request.method,\n\t\t\t\tstate: this.#state(connection),\n\t\t\t\tbody: () => {\n\t\t\t\t\tcached ??= readBody(request, { limit: this.#limit })\n\t\t\t\t\treturn cached\n\t\t\t\t},\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} 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)\n\t\t\t\tif (this.#report !== undefined) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#report(error)\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}\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\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, every parked drain waiter is woken\n\t// — event-driven, never a busy-loop.\n\t#trackStart(): () => void {\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) {\n\t\t\t\tconst waiters = this.#waiters\n\t\t\t\tthis.#waiters = []\n\t\t\t\tfor (const wake of waiters) wake()\n\t\t\t}\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\t#drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#pending === 0 || signal.aborted) return Promise.resolve()\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tconst onDone = (): void => {\n\t\t\t\tsignal.removeEventListener('abort', onDone)\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.#waiters.push(onDone)\n\t\t\tsignal.addEventListener('abort', onDone, { once: true })\n\t\t})\n\t}\n}\n","import type { ServerInterface, ServerOptions } from './types.js'\nimport { Server } from './Server.js'\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,cAAc,OAAsC;CACnE,QAAA,GAAA,oBAAA,SAAA,CAAgB,KAAK,MAAA,GAAA,oBAAA,SAAA,CAAc,MAAM,IAAI;AAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,aAAa,WAAqC;CACjE,OAAO,IAAI,SAAiB,SAAS,WAAW;EAC/C,MAAM,QAAQ,MAAc,aAA4B;GACvD,MAAM,SAAA,GAAA,SAAA,aAAA,CAAwB;GAC9B,MAAM,WAAW,UA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G;IACnC,UAAU;IACV;GACD;EACD,SAAS,OAAO;GACf,KAAKC,SAAS,KAAK,SAAS,KAAK;EAClC;EAED,IAAI,CAAC,SAAS,OAAO,QAAQ;EAC7B,KAAKA,SAAS,KAAK,WAAW,SAAS,OAAO;CAC/C;CAKA,aAAa,QAAgC;EAC5C,MAAM,UAAU,OAAO,QAAQ;EAC/B,IAAI,cAAc,OAAO,GAAG,OAAO,QAAQ;EAC3C,OAAO;CACR;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,KAAKgB,YAAY;EACjB,IAAI,WAAW;EACf,aAAa;GACZ,IAAI,UAAU;GACd,WAAW;GACX,KAAKA,YAAY;GACjB,IAAI,KAAKA,aAAa,GAAG;IACxB,MAAM,UAAU,KAAKM;IACrB,KAAKA,WAAW,CAAC;IACjB,KAAK,MAAM,QAAQ,SAAS,KAAK;GAClC;EACD;CACD;CAIA,cAAc,QAAoC;EACjD,IAAI,KAAKN,aAAa,KAAK,OAAO,SAAS,OAAO,QAAQ,QAAQ;EAClE,OAAO,IAAI,SAAe,YAAY;GACrC,MAAM,eAAqB;IAC1B,OAAO,oBAAoB,SAAS,MAAM;IAC1C,QAAQ;GACT;GACA,KAAKM,SAAS,KAAK,MAAM;GACzB,OAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;EACxD,CAAC;CACF;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7WA,SAAgB,aAAqB,SAAyD;CAC7F,OAAO,IAAI,OAAO,OAAO;AAC1B"}
1
+ {"version":3,"file":"index.cjs","names":["#dispatcher","#state","#middleware","#upgradeHandlers","#emitter","#host","#configuredPort","#drain","#limit","#expose","#report","#timeouts","#status","#port","#abort","#handle","#onUpgrade","#http","#resolvePort","#drainPending","#pending","#close","#trackStart","#accept","#respond","#boundary","#waiters"],"sources":["../../../src/server/helpers.ts","../../../src/server/Server.ts","../../../src/server/factories.ts"],"sourcesContent":["// ============================================================================\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 in `@src/core` and is consumed, never duplicated\n// (the socket-encrypted narrow and the `Request`/`Response` conversion are\n// `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` / `sendResponse`).\n// ============================================================================\n\nimport type { AddressInfo } from 'node:net'\nimport { createServer as createNetServer } from 'node:net'\nimport { isNumber, isRecord } from '@orkestrel/contract'\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 * 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 function discoverPort(preferred?: number): Promise<number> {\n\treturn new Promise<number>((resolve, reject) => {\n\t\tconst bind = (port: number, fallback: boolean): void => {\n\t\t\tconst probe = createNetServer()\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tprobe.close()\n\t\t\t\tconst taken = 'code' in error && error.code === 'EADDRINUSE'\n\t\t\t\tif (fallback && taken) bind(0, false)\n\t\t\t\telse reject(error)\n\t\t\t}\n\t\t\tprobe.once('error', onError)\n\t\t\tprobe.listen(port, () => {\n\t\t\t\tconst address = probe.address()\n\t\t\t\tconst resolved = isAddressInfo(address) ? address.port : 0\n\t\t\t\tprobe.close(() => resolve(resolved))\n\t\t\t})\n\t\t}\n\t\tbind(preferred ?? 0, preferred !== undefined)\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 { MiddlewareContext, MiddlewareHandler } from '@src/core'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnectionStateFunction,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { createServer as createHTTPServer } from 'node:http'\nimport {\n\tcompose,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DRAIN_MS,\n\tHTTPError,\n\tisHTTPError,\n\treadBody,\n} from '@src/core'\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 } from '@orkestrel/contract'\nimport { isAddressInfo } from './helpers.js'\n\n/**\n * The HTTP server facade — an observable `node:http` lifecycle composing the\n * `@src/core` 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()` 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), and transitions `idle → starting → listening`. `stop()`\n * transitions to `stopping`: refuses new connections, fires a fresh-per-run\n * stop signal so in-flight handlers observe cancellation, drains up to the\n * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.\n * `destroy()` 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, tied to client disconnect, composes with the\n * server's stop signal via `AbortSignal.any`, so a handler awaiting\n * `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 request?: number\n\t\treadonly headers?: number\n\t\treadonly keepalive?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#abort: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#pending = 0\n\t#waiters: (() => void)[] = []\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\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.#emitter = new Emitter<ServerEventMap>({ on: options.on, error: options.error })\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(): 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\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 new Promise<number>((resolve, reject) => {\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tserver.off('listening', onListening)\n\t\t\t\tthis.#http = undefined\n\t\t\t\tthis.#status = 'idle'\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst onListening = (): void => {\n\t\t\t\tserver.off('error', onError)\n\t\t\t\tconst port = this.#resolvePort(server)\n\t\t\t\tthis.#port = port\n\t\t\t\tthis.#status = 'listening'\n\t\t\t\tthis.#emitter.emit('start', port)\n\t\t\t\tresolve(port)\n\t\t\t}\n\t\t\tserver.once('error', onError)\n\t\t\tserver.once('listening', onListening)\n\t\t\tserver.listen(this.#configuredPort ?? 0, this.#host)\n\t\t})\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)\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 connection = {\n\t\t\t\tip: message.socket.remoteAddress,\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tlet cached: Promise<unknown> | undefined\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: () => {\n\t\t\t\t\tcached ??= readBody(request, { limit: this.#limit })\n\t\t\t\t\treturn cached\n\t\t\t\t},\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\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, every parked drain waiter is woken\n\t// — event-driven, never a busy-loop.\n\t#trackStart(): () => void {\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) {\n\t\t\t\tconst waiters = this.#waiters\n\t\t\t\tthis.#waiters = []\n\t\t\t\tfor (const wake of waiters) wake()\n\t\t\t}\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\t#drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#pending === 0 || signal.aborted) return Promise.resolve()\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tconst onDone = (): void => {\n\t\t\t\tsignal.removeEventListener('abort', onDone)\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.#waiters.push(onDone)\n\t\t\tsignal.addEventListener('abort', onDone, { once: true })\n\t\t})\n\t}\n}\n","import type { ServerInterface, ServerOptions } from './types.js'\nimport { Server } from './Server.js'\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,cAAc,OAAsC;CACnE,QAAA,GAAA,oBAAA,SAAA,CAAgB,KAAK,MAAA,GAAA,oBAAA,SAAA,CAAc,MAAM,IAAI;AAC9C;;;;;;;;;;;;;;;;;;;;;;;;;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AI,KAAKN,aAAa,KAAK,OAAO,SAAS,OAAO,QAAQ,QAAQ;EAClE,OAAO,IAAI,SAAe,YAAY;GACrC,MAAM,eAAqB;IAC1B,OAAO,oBAAoB,SAAS,MAAM;IAC1C,QAAQ;GACT;GACA,KAAKM,SAAS,KAAK,MAAM;GACzB,OAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;EACxD,CAAC;CACF;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/XA,SAAgB,aAAqB,SAAyD;CAC7F,OAAO,IAAI,OAAO,OAAO;AAC1B"}
@@ -160,18 +160,40 @@ export declare class Server<TState> implements ServerInterface<TState> {
160
160
  * - `upgrade` — a raw protocol-upgrade fan-out settled; carries the original
161
161
  * `IncomingMessage` and whether a registered {@link UpgradeHandler} claimed it.
162
162
  * - `error` — a server-level fault: an escaping throw past the built-in
163
- * boundary, an upgrade handler's throw, or a listen failure.
163
+ * boundary, an upgrade handler's throw, or a listen failure. Carries the
164
+ * originating request's method + parsed `url` when the fault happened on
165
+ * the per-request path; `undefined` for an upgrade-handler throw (no fetch
166
+ * `Request` exists on that path — only a raw `IncomingMessage`) or a listen
167
+ * failure.
164
168
  * - `stop` — `stop()` began (status just moved to `'stopping'`).
165
169
  * - `drain` — the graceful drain settled (deadline hit or all finished);
166
170
  * carries the still-pending request count (`0` on a clean drain).
171
+ * - `response` — fired after the response has been sent, for every request
172
+ * that reaches the middleware pipeline (the success path and the
173
+ * outer-boundary error path); carries the method, parsed pathname, final
174
+ * status, and elapsed time in milliseconds. A request rejected at the
175
+ * `buildRequest` INNER boundary (a plain `400`, e.g. a malformed `Host`
176
+ * header) emits no `response` — no parsed `Request` exists yet to derive
177
+ * its facts from.
167
178
  */
168
179
  export declare type ServerEventMap = {
169
180
  readonly start: readonly [port: number];
170
181
  readonly request: readonly [method: string, pathname: string];
171
182
  readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
172
- readonly error: readonly [error: unknown];
183
+ readonly error: readonly [error: unknown, request?: {
184
+ method: string;
185
+ url: URL;
186
+ }];
173
187
  readonly stop: readonly [];
174
188
  readonly drain: readonly [pending: number];
189
+ readonly response: readonly [
190
+ event: {
191
+ method: string;
192
+ pathname: string;
193
+ status: number;
194
+ ms: number;
195
+ }
196
+ ];
175
197
  };
176
198
 
177
199
  /**
@@ -240,8 +262,10 @@ export declare interface ServerInterface<TState> {
240
262
  * 500 response body (an `HTTPError`'s own message is always client-facing).
241
263
  * Defaults to `false`.
242
264
  * @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.
265
+ * caught error to (logging / metrics), along with the originating
266
+ * request's method + parsed `url` when one is available (absent on an
267
+ * upgrade-path fault); its own throw is swallowed so reporting can never
268
+ * crash the response.
245
269
  * @param timeouts - `node:http` tuning knobs: `request` (max time to fully
246
270
  * receive + respond, `requestTimeout`), `headers` (max time to receive the
247
271
  * request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
@@ -261,7 +285,10 @@ export declare interface ServerOptions<TState> {
261
285
  readonly drain?: number;
262
286
  readonly limit?: number;
263
287
  readonly expose?: boolean;
264
- readonly report?: (error: unknown) => void;
288
+ readonly report?: (error: unknown, request?: {
289
+ method: string;
290
+ url: URL;
291
+ }) => void;
265
292
  readonly timeouts?: {
266
293
  readonly request?: number;
267
294
  readonly headers?: number;
@@ -160,18 +160,40 @@ export declare class Server<TState> implements ServerInterface<TState> {
160
160
  * - `upgrade` — a raw protocol-upgrade fan-out settled; carries the original
161
161
  * `IncomingMessage` and whether a registered {@link UpgradeHandler} claimed it.
162
162
  * - `error` — a server-level fault: an escaping throw past the built-in
163
- * boundary, an upgrade handler's throw, or a listen failure.
163
+ * boundary, an upgrade handler's throw, or a listen failure. Carries the
164
+ * originating request's method + parsed `url` when the fault happened on
165
+ * the per-request path; `undefined` for an upgrade-handler throw (no fetch
166
+ * `Request` exists on that path — only a raw `IncomingMessage`) or a listen
167
+ * failure.
164
168
  * - `stop` — `stop()` began (status just moved to `'stopping'`).
165
169
  * - `drain` — the graceful drain settled (deadline hit or all finished);
166
170
  * carries the still-pending request count (`0` on a clean drain).
171
+ * - `response` — fired after the response has been sent, for every request
172
+ * that reaches the middleware pipeline (the success path and the
173
+ * outer-boundary error path); carries the method, parsed pathname, final
174
+ * status, and elapsed time in milliseconds. A request rejected at the
175
+ * `buildRequest` INNER boundary (a plain `400`, e.g. a malformed `Host`
176
+ * header) emits no `response` — no parsed `Request` exists yet to derive
177
+ * its facts from.
167
178
  */
168
179
  export declare type ServerEventMap = {
169
180
  readonly start: readonly [port: number];
170
181
  readonly request: readonly [method: string, pathname: string];
171
182
  readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
172
- readonly error: readonly [error: unknown];
183
+ readonly error: readonly [error: unknown, request?: {
184
+ method: string;
185
+ url: URL;
186
+ }];
173
187
  readonly stop: readonly [];
174
188
  readonly drain: readonly [pending: number];
189
+ readonly response: readonly [
190
+ event: {
191
+ method: string;
192
+ pathname: string;
193
+ status: number;
194
+ ms: number;
195
+ }
196
+ ];
175
197
  };
176
198
 
177
199
  /**
@@ -240,8 +262,10 @@ export declare interface ServerInterface<TState> {
240
262
  * 500 response body (an `HTTPError`'s own message is always client-facing).
241
263
  * Defaults to `false`.
242
264
  * @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.
265
+ * caught error to (logging / metrics), along with the originating
266
+ * request's method + parsed `url` when one is available (absent on an
267
+ * upgrade-path fault); its own throw is swallowed so reporting can never
268
+ * crash the response.
245
269
  * @param timeouts - `node:http` tuning knobs: `request` (max time to fully
246
270
  * receive + respond, `requestTimeout`), `headers` (max time to receive the
247
271
  * request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
@@ -261,7 +285,10 @@ export declare interface ServerOptions<TState> {
261
285
  readonly drain?: number;
262
286
  readonly limit?: number;
263
287
  readonly expose?: boolean;
264
- readonly report?: (error: unknown) => void;
288
+ readonly report?: (error: unknown, request?: {
289
+ method: string;
290
+ url: URL;
291
+ }) => void;
265
292
  readonly timeouts?: {
266
293
  readonly request?: number;
267
294
  readonly headers?: number;
@@ -256,11 +256,13 @@ var Server = class {
256
256
  await this.#respond(this.#boundary(new HTTPError(400, "invalid request")), response);
257
257
  return;
258
258
  }
259
+ const method = raw.method;
260
+ const url = new URL(raw.url);
261
+ const start = performance.now();
259
262
  try {
260
263
  const linked = linkSignal(raw.signal, this.#abort.signal);
261
264
  const request = new Request(raw, { signal: linked });
262
- const url = new URL(request.url);
263
- this.#emitter.emit("request", request.method, url.pathname);
265
+ this.#emitter.emit("request", method, url.pathname);
264
266
  const connection = {
265
267
  ip: message.socket.remoteAddress,
266
268
  encrypted: isEncryptedSocket(message.socket)
@@ -268,7 +270,7 @@ var Server = class {
268
270
  let cached;
269
271
  const context = {
270
272
  url,
271
- method: request.method,
273
+ method,
272
274
  state: this.#state(connection),
273
275
  body: () => {
274
276
  cached ??= readBody(request, { limit: this.#limit });
@@ -277,15 +279,33 @@ var Server = class {
277
279
  };
278
280
  const result = await compose(this.#middleware, (currentRequest, currentContext) => this.#dispatcher.handle(currentRequest, currentContext.state))(request, context);
279
281
  await this.#respond(result, response);
282
+ this.#emitter.emit("response", {
283
+ method,
284
+ pathname: url.pathname,
285
+ status: result.status,
286
+ ms: Math.round(performance.now() - start)
287
+ });
280
288
  } catch (error) {
281
289
  const mapped = this.#boundary(error);
282
290
  if (!isHTTPError(error)) {
283
- this.#emitter.emit("error", error);
291
+ this.#emitter.emit("error", error, {
292
+ method,
293
+ url
294
+ });
284
295
  if (this.#report !== void 0) try {
285
- this.#report(error);
296
+ this.#report(error, {
297
+ method,
298
+ url
299
+ });
286
300
  } catch {}
287
301
  }
288
302
  await this.#respond(mapped, response);
303
+ this.#emitter.emit("response", {
304
+ method,
305
+ pathname: url.pathname,
306
+ status: mapped.status,
307
+ ms: Math.round(performance.now() - start)
308
+ });
289
309
  }
290
310
  }
291
311
  async #respond(result, response) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#dispatcher","#state","#middleware","#upgradeHandlers","#emitter","#host","#configuredPort","#drain","#limit","#expose","#report","#timeouts","#status","#port","#abort","#handle","#onUpgrade","#http","#resolvePort","#drainPending","#pending","#close","#trackStart","#accept","#respond","#boundary","#waiters"],"sources":["../../../src/server/helpers.ts","../../../src/server/Server.ts","../../../src/server/factories.ts"],"sourcesContent":["// ============================================================================\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 in `@src/core` and is consumed, never duplicated\n// (the socket-encrypted narrow and the `Request`/`Response` conversion are\n// `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` / `sendResponse`).\n// ============================================================================\n\nimport type { AddressInfo } from 'node:net'\nimport { createServer as createNetServer } from 'node:net'\nimport { isNumber, isRecord } from '@orkestrel/contract'\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 * 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 function discoverPort(preferred?: number): Promise<number> {\n\treturn new Promise<number>((resolve, reject) => {\n\t\tconst bind = (port: number, fallback: boolean): void => {\n\t\t\tconst probe = createNetServer()\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tprobe.close()\n\t\t\t\tconst taken = 'code' in error && error.code === 'EADDRINUSE'\n\t\t\t\tif (fallback && taken) bind(0, false)\n\t\t\t\telse reject(error)\n\t\t\t}\n\t\t\tprobe.once('error', onError)\n\t\t\tprobe.listen(port, () => {\n\t\t\t\tconst address = probe.address()\n\t\t\t\tconst resolved = isAddressInfo(address) ? address.port : 0\n\t\t\t\tprobe.close(() => resolve(resolved))\n\t\t\t})\n\t\t}\n\t\tbind(preferred ?? 0, preferred !== undefined)\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 { MiddlewareContext, MiddlewareHandler } from '@src/core'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnectionStateFunction,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { createServer as createHTTPServer } from 'node:http'\nimport {\n\tcompose,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DRAIN_MS,\n\tHTTPError,\n\tisHTTPError,\n\treadBody,\n} from '@src/core'\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 } from '@orkestrel/contract'\nimport { isAddressInfo } from './helpers.js'\n\n/**\n * The HTTP server facade — an observable `node:http` lifecycle composing the\n * `@src/core` 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()` 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), and transitions `idle → starting → listening`. `stop()`\n * transitions to `stopping`: refuses new connections, fires a fresh-per-run\n * stop signal so in-flight handlers observe cancellation, drains up to the\n * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.\n * `destroy()` 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, tied to client disconnect, composes with the\n * server's stop signal via `AbortSignal.any`, so a handler awaiting\n * `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) => void) | undefined\n\treadonly #timeouts: {\n\t\treadonly request?: number\n\t\treadonly headers?: number\n\t\treadonly keepalive?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#abort: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#pending = 0\n\t#waiters: (() => void)[] = []\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\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.#emitter = new Emitter<ServerEventMap>({ on: options.on, error: options.error })\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(): 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\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 new Promise<number>((resolve, reject) => {\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tserver.off('listening', onListening)\n\t\t\t\tthis.#http = undefined\n\t\t\t\tthis.#status = 'idle'\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst onListening = (): void => {\n\t\t\t\tserver.off('error', onError)\n\t\t\t\tconst port = this.#resolvePort(server)\n\t\t\t\tthis.#port = port\n\t\t\t\tthis.#status = 'listening'\n\t\t\t\tthis.#emitter.emit('start', port)\n\t\t\t\tresolve(port)\n\t\t\t}\n\t\t\tserver.once('error', onError)\n\t\t\tserver.once('listening', onListening)\n\t\t\tserver.listen(this.#configuredPort ?? 0, this.#host)\n\t\t})\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)\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\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\tconst url = new URL(request.url)\n\t\t\tthis.#emitter.emit('request', request.method, url.pathname)\n\t\t\tconst connection = {\n\t\t\t\tip: message.socket.remoteAddress,\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tlet cached: Promise<unknown> | undefined\n\t\t\tconst context: MiddlewareContext<TState> = {\n\t\t\t\turl,\n\t\t\t\tmethod: request.method,\n\t\t\t\tstate: this.#state(connection),\n\t\t\t\tbody: () => {\n\t\t\t\t\tcached ??= readBody(request, { limit: this.#limit })\n\t\t\t\t\treturn cached\n\t\t\t\t},\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} 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)\n\t\t\t\tif (this.#report !== undefined) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.#report(error)\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}\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\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, every parked drain waiter is woken\n\t// — event-driven, never a busy-loop.\n\t#trackStart(): () => void {\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) {\n\t\t\t\tconst waiters = this.#waiters\n\t\t\t\tthis.#waiters = []\n\t\t\t\tfor (const wake of waiters) wake()\n\t\t\t}\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\t#drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#pending === 0 || signal.aborted) return Promise.resolve()\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tconst onDone = (): void => {\n\t\t\t\tsignal.removeEventListener('abort', onDone)\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.#waiters.push(onDone)\n\t\t\tsignal.addEventListener('abort', onDone, { once: true })\n\t\t})\n\t}\n}\n","import type { ServerInterface, ServerOptions } from './types.js'\nimport { Server } from './Server.js'\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":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,cAAc,OAAsC;CACnE,OAAO,SAAS,KAAK,KAAK,SAAS,MAAM,IAAI;AAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,aAAa,WAAqC;CACjE,OAAO,IAAI,SAAiB,SAAS,WAAW;EAC/C,MAAM,QAAQ,MAAc,aAA4B;GACvD,MAAM,QAAQ,eAAgB;GAC9B,MAAM,WAAW,UAAuB;IACvC,MAAM,MAAM;IACZ,MAAM,QAAQ,UAAU,SAAS,MAAM,SAAS;IAChD,IAAI,YAAY,OAAO,KAAK,GAAG,KAAK;SAC/B,OAAO,KAAK;GAClB;GACA,MAAM,KAAK,SAAS,OAA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AAU;GACd,WAAW;GACX,KAAKA,YAAY;GACjB,IAAI,KAAKA,aAAa,GAAG;IACxB,MAAM,UAAU,KAAKM;IACrB,KAAKA,WAAW,CAAC;IACjB,KAAK,MAAM,QAAQ,SAAS,KAAK;GAClC;EACD;CACD;CAIA,cAAc,QAAoC;EACjD,IAAI,KAAKN,aAAa,KAAK,OAAO,SAAS,OAAO,QAAQ,QAAQ;EAClE,OAAO,IAAI,SAAe,YAAY;GACrC,MAAM,eAAqB;IAC1B,OAAO,oBAAoB,SAAS,MAAM;IAC1C,QAAQ;GACT;GACA,KAAKM,SAAS,KAAK,MAAM;GACzB,OAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;EACxD,CAAC;CACF;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7WA,SAAgB,aAAqB,SAAyD;CAC7F,OAAO,IAAI,OAAO,OAAO;AAC1B"}
1
+ {"version":3,"file":"index.js","names":["#dispatcher","#state","#middleware","#upgradeHandlers","#emitter","#host","#configuredPort","#drain","#limit","#expose","#report","#timeouts","#status","#port","#abort","#handle","#onUpgrade","#http","#resolvePort","#drainPending","#pending","#close","#trackStart","#accept","#respond","#boundary","#waiters"],"sources":["../../../src/server/helpers.ts","../../../src/server/Server.ts","../../../src/server/factories.ts"],"sourcesContent":["// ============================================================================\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 in `@src/core` and is consumed, never duplicated\n// (the socket-encrypted narrow and the `Request`/`Response` conversion are\n// `@orkestrel/router`'s `isEncryptedSocket` / `buildRequest` / `sendResponse`).\n// ============================================================================\n\nimport type { AddressInfo } from 'node:net'\nimport { createServer as createNetServer } from 'node:net'\nimport { isNumber, isRecord } from '@orkestrel/contract'\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 * 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 function discoverPort(preferred?: number): Promise<number> {\n\treturn new Promise<number>((resolve, reject) => {\n\t\tconst bind = (port: number, fallback: boolean): void => {\n\t\t\tconst probe = createNetServer()\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tprobe.close()\n\t\t\t\tconst taken = 'code' in error && error.code === 'EADDRINUSE'\n\t\t\t\tif (fallback && taken) bind(0, false)\n\t\t\t\telse reject(error)\n\t\t\t}\n\t\t\tprobe.once('error', onError)\n\t\t\tprobe.listen(port, () => {\n\t\t\t\tconst address = probe.address()\n\t\t\t\tconst resolved = isAddressInfo(address) ? address.port : 0\n\t\t\t\tprobe.close(() => resolve(resolved))\n\t\t\t})\n\t\t}\n\t\tbind(preferred ?? 0, preferred !== undefined)\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 { MiddlewareContext, MiddlewareHandler } from '@src/core'\nimport type { DispatcherInterface } from '@orkestrel/router'\nimport type {\n\tConnectionStateFunction,\n\tServerEventMap,\n\tServerInterface,\n\tServerOptions,\n\tServerStatus,\n\tUpgradeHandler,\n} from './types.js'\nimport { createServer as createHTTPServer } from 'node:http'\nimport {\n\tcompose,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DRAIN_MS,\n\tHTTPError,\n\tisHTTPError,\n\treadBody,\n} from '@src/core'\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 } from '@orkestrel/contract'\nimport { isAddressInfo } from './helpers.js'\n\n/**\n * The HTTP server facade — an observable `node:http` lifecycle composing the\n * `@src/core` 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()` 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), and transitions `idle → starting → listening`. `stop()`\n * transitions to `stopping`: refuses new connections, fires a fresh-per-run\n * stop signal so in-flight handlers observe cancellation, drains up to the\n * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.\n * `destroy()` 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, tied to client disconnect, composes with the\n * server's stop signal via `AbortSignal.any`, so a handler awaiting\n * `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 request?: number\n\t\treadonly headers?: number\n\t\treadonly keepalive?: number\n\t}\n\t#http: NodeHTTPServer | undefined\n\t#abort: AbortInterface = createAbort()\n\t#status: ServerStatus = 'idle'\n\t#port: number | undefined\n\t#pending = 0\n\t#waiters: (() => void)[] = []\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\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.#emitter = new Emitter<ServerEventMap>({ on: options.on, error: options.error })\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(): 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\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 new Promise<number>((resolve, reject) => {\n\t\t\tconst onError = (error: Error): void => {\n\t\t\t\tserver.off('listening', onListening)\n\t\t\t\tthis.#http = undefined\n\t\t\t\tthis.#status = 'idle'\n\t\t\t\treject(error)\n\t\t\t}\n\t\t\tconst onListening = (): void => {\n\t\t\t\tserver.off('error', onError)\n\t\t\t\tconst port = this.#resolvePort(server)\n\t\t\t\tthis.#port = port\n\t\t\t\tthis.#status = 'listening'\n\t\t\t\tthis.#emitter.emit('start', port)\n\t\t\t\tresolve(port)\n\t\t\t}\n\t\t\tserver.once('error', onError)\n\t\t\tserver.once('listening', onListening)\n\t\t\tserver.listen(this.#configuredPort ?? 0, this.#host)\n\t\t})\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)\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 connection = {\n\t\t\t\tip: message.socket.remoteAddress,\n\t\t\t\tencrypted: isEncryptedSocket(message.socket),\n\t\t\t}\n\t\t\tlet cached: Promise<unknown> | undefined\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: () => {\n\t\t\t\t\tcached ??= readBody(request, { limit: this.#limit })\n\t\t\t\t\treturn cached\n\t\t\t\t},\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\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, every parked drain waiter is woken\n\t// — event-driven, never a busy-loop.\n\t#trackStart(): () => void {\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) {\n\t\t\t\tconst waiters = this.#waiters\n\t\t\t\tthis.#waiters = []\n\t\t\t\tfor (const wake of waiters) wake()\n\t\t\t}\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\t#drainPending(signal: AbortSignal): Promise<void> {\n\t\tif (this.#pending === 0 || signal.aborted) return Promise.resolve()\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tconst onDone = (): void => {\n\t\t\t\tsignal.removeEventListener('abort', onDone)\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.#waiters.push(onDone)\n\t\t\tsignal.addEventListener('abort', onDone, { once: true })\n\t\t})\n\t}\n}\n","import type { ServerInterface, ServerOptions } from './types.js'\nimport { Server } from './Server.js'\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":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,cAAc,OAAsC;CACnE,OAAO,SAAS,KAAK,KAAK,SAAS,MAAM,IAAI;AAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,aAAa,WAAqC;CACjE,OAAO,IAAI,SAAiB,SAAS,WAAW;EAC/C,MAAM,QAAQ,MAAc,aAA4B;GACvD,MAAM,QAAQ,eAAgB;GAC9B,MAAM,WAAW,UAAuB;IACvC,MAAM,MAAM;IACZ,MAAM,QAAQ,UAAU,SAAS,MAAM,SAAS;IAChD,IAAI,YAAY,OAAO,KAAK,GAAG,KAAK;SAC/B,OAAO,KAAK;GAClB;GACA,MAAM,KAAK,SAAS,OAAO;GAC3B,MAAM,OAAO,YAAY;IACxB,MAAM,UAAU,MAAM,QAAQ;IAC9B,MAAM,WAAW,cAAc,OAAO,IAAI,QAAQ,OAAO;IACzD,MAAM,YAAY,QAAQ,QAAQ,CAAC;GACpC,CAAC;EACF;EACA,KAAK,aAAa,GAAG,cAAc,KAAA,CAAS;CAC7C,CAAC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;EAClC,CAAC;CACF;CAKA,cAA0B;EACzB,KAAKgB,YAAY;EACjB,IAAI,WAAW;EACf,aAAa;GACZ,IAAI,UAAU;GACd,WAAW;GACX,KAAKA,YAAY;GACjB,IAAI,KAAKA,aAAa,GAAG;IACxB,MAAM,UAAU,KAAKM;IACrB,KAAKA,WAAW,CAAC;IACjB,KAAK,MAAM,QAAQ,SAAS,KAAK;GAClC;EACD;CACD;CAIA,cAAc,QAAoC;EACjD,IAAI,KAAKN,aAAa,KAAK,OAAO,SAAS,OAAO,QAAQ,QAAQ;EAClE,OAAO,IAAI,SAAe,YAAY;GACrC,MAAM,eAAqB;IAC1B,OAAO,oBAAoB,SAAS,MAAM;IAC1C,QAAQ;GACT;GACA,KAAKM,SAAS,KAAK,MAAM;GACzB,OAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,KAAK,CAAC;EACxD,CAAC;CACF;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC/XA,SAAgB,aAAqB,SAAyD;CAC7F,OAAO,IAAI,OAAO,OAAO;AAC1B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orkestrel/server",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
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",
@@ -78,18 +78,18 @@
78
78
  "@orkestrel/abort": "^0.0.1",
79
79
  "@orkestrel/contract": "^0.0.1",
80
80
  "@orkestrel/emitter": "^0.0.1",
81
- "@orkestrel/router": "^0.0.1",
81
+ "@orkestrel/router": "^0.0.2",
82
82
  "@orkestrel/timeout": "^0.0.1"
83
83
  },
84
84
  "devDependencies": {
85
- "@microsoft/api-extractor": "^7.58.9",
85
+ "@microsoft/api-extractor": "^7.58.10",
86
86
  "@orkestrel/guide": "^0.0.1",
87
87
  "@types/node": "^26.1.1",
88
88
  "@vitest/browser-playwright": "^4.1.10",
89
- "oxfmt": "^0.58.0",
90
- "oxlint": "^1.73.0",
89
+ "oxfmt": "^0.59.0",
90
+ "oxlint": "^1.74.0",
91
91
  "typescript": "^6.0.3",
92
- "vite": "^8.1.4",
92
+ "vite": "^8.1.5",
93
93
  "vite-plugin-dts": "^5.0.3",
94
94
  "vitest": "^4.1.10"
95
95
  },