@orkestrel/server 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _orkestrel_contract = require("@orkestrel/contract");
3
+ let node_events = require("node:events");
3
4
  let node_net = require("node:net");
4
5
  let node_http = require("node:http");
5
6
  let _orkestrel_abort = require("@orkestrel/abort");
@@ -141,7 +142,7 @@ var HTTPError = class extends Error {
141
142
  super(message);
142
143
  this.name = "HTTPError";
143
144
  this.status = status;
144
- this.context = context;
145
+ if (context !== void 0) this.context = context;
145
146
  }
146
147
  };
147
148
  /**
@@ -241,19 +242,36 @@ function isHTTPError(value) {
241
242
  * ```
242
243
  */
243
244
  function compose(middleware, terminal) {
245
+ return middleware.reduceRight((next, layer) => wrapMiddleware(layer, next), terminal);
246
+ }
247
+ /**
248
+ * Wrap one middleware layer around its downstream handler.
249
+ *
250
+ * @remarks
251
+ * The returned handler enforces the one-call `next` invariant while preserving
252
+ * request substitution and the middleware's synchronous or asynchronous result.
253
+ *
254
+ * @typeParam TState - The consumer's opaque per-request state type
255
+ * @param layer - The middleware layer to invoke
256
+ * @param next - The downstream handler wrapped by `layer`
257
+ * @returns A handler with `layer` composed around `next`
258
+ *
259
+ * @example
260
+ * ```ts
261
+ * const handle = wrapMiddleware(
262
+ * async (_request, _context, next) => next(),
263
+ * async () => new Response('ok'),
264
+ * )
265
+ * ```
266
+ */
267
+ function wrapMiddleware(layer, next) {
244
268
  return async (request, context) => {
245
- const dispatch = (index, currentRequest) => {
246
- const layer = middleware[index];
247
- if (layer === void 0) return terminal(currentRequest, context);
248
- let called = false;
249
- const next = (nextRequest) => {
250
- if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
251
- called = true;
252
- return dispatch(index + 1, nextRequest ?? currentRequest);
253
- };
254
- return Promise.resolve(layer(currentRequest, context, next));
255
- };
256
- return dispatch(0, request);
269
+ let called = false;
270
+ return Promise.resolve(layer(request, context, (nextRequest) => {
271
+ if (called) return Promise.reject(/* @__PURE__ */ new Error("next() was already called by this middleware"));
272
+ called = true;
273
+ return next(nextRequest ?? request, context);
274
+ }));
257
275
  };
258
276
  }
259
277
  /**
@@ -1027,7 +1045,9 @@ function parseRange(header, size) {
1027
1045
  if (header === void 0) return void 0;
1028
1046
  const match = /^bytes=(.*)$/.exec(header.trim());
1029
1047
  if (match === null) return void 0;
1030
- const spec = match[1].trim();
1048
+ const capture = match[1];
1049
+ if (capture === void 0) return void 0;
1050
+ const spec = capture.trim();
1031
1051
  if (spec.includes(",")) return void 0;
1032
1052
  const dash = spec.indexOf("-");
1033
1053
  if (dash < 0) return void 0;
@@ -1183,8 +1203,12 @@ function ipv6Network(address) {
1183
1203
  const percent = address.indexOf("%");
1184
1204
  const halves = (percent === -1 ? address : address.slice(0, percent)).split("::");
1185
1205
  if (halves.length > 2) return void 0;
1186
- const head = halves[0] === "" ? [] : halves[0].split(":");
1187
- const tail = halves.length === 2 ? halves[1] === "" ? [] : halves[1].split(":") : [];
1206
+ const first = halves[0];
1207
+ if (first === void 0) return void 0;
1208
+ const second = halves[1];
1209
+ if (halves.length === 2 && second === void 0) return void 0;
1210
+ const head = first === "" ? [] : first.split(":");
1211
+ const tail = second === void 0 || second === "" ? [] : second.split(":");
1188
1212
  let groups;
1189
1213
  if (halves.length === 2) {
1190
1214
  const missing = 8 - head.length - tail.length;
@@ -1254,6 +1278,28 @@ function serializeEvent(message) {
1254
1278
  return `${lines.join("\n")}\n\n`;
1255
1279
  }
1256
1280
  /**
1281
+ * Enqueue encoded text into an open byte stream.
1282
+ *
1283
+ * @param controller - The stream controller, when the stream has started
1284
+ * @param encoder - The encoder used for the stream's byte representation
1285
+ * @param closed - Whether the stream has already ended or been cancelled
1286
+ * @param text - The text to encode and enqueue
1287
+ * @returns Nothing
1288
+ *
1289
+ * @example
1290
+ * ```ts
1291
+ * const body = new ReadableStream<Uint8Array>({
1292
+ * start(controller) {
1293
+ * enqueueStreamText(controller, new TextEncoder(), false, 'hello')
1294
+ * },
1295
+ * })
1296
+ * ```
1297
+ */
1298
+ function enqueueStreamText(controller, encoder, closed, text) {
1299
+ if (closed || controller === void 0) return;
1300
+ controller.enqueue(encoder.encode(text));
1301
+ }
1302
+ /**
1257
1303
  * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
1258
1304
  * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
1259
1305
  *
@@ -1294,24 +1340,19 @@ function openStream(options) {
1294
1340
  ...SSE_HEADERS,
1295
1341
  ...options?.headers
1296
1342
  });
1297
- const response = new Response(body, {
1298
- status: options?.status ?? 200,
1299
- headers
1300
- });
1301
- const enqueue = (text) => {
1302
- if (closed || controller === void 0) return;
1303
- controller.enqueue(encoder.encode(text));
1304
- };
1305
1343
  return {
1306
- response,
1344
+ response: new Response(body, {
1345
+ status: options?.status ?? 200,
1346
+ headers
1347
+ }),
1307
1348
  get closed() {
1308
1349
  return closed;
1309
1350
  },
1310
1351
  write(message) {
1311
- enqueue(serializeEvent(message));
1352
+ enqueueStreamText(controller, encoder, closed, serializeEvent(message));
1312
1353
  },
1313
1354
  comment(text) {
1314
- enqueue(`: ${text}\n\n`);
1355
+ enqueueStreamText(controller, encoder, closed, `: ${text}\n\n`);
1315
1356
  },
1316
1357
  end() {
1317
1358
  if (closed) return;
@@ -1564,6 +1605,29 @@ function isAddressInfo(value) {
1564
1605
  return (0, _orkestrel_contract.isRecord)(value) && (0, _orkestrel_contract.isNumber)(value.port);
1565
1606
  }
1566
1607
  /**
1608
+ * Bind and close a throwaway TCP server to resolve one available port.
1609
+ *
1610
+ * @param port - The requested port, with `0` selecting an ephemeral port
1611
+ * @returns The bound port after the probe server has closed
1612
+ *
1613
+ * @example
1614
+ * ```ts
1615
+ * const port = await probePort(0)
1616
+ * ```
1617
+ */
1618
+ async function probePort(port) {
1619
+ const probe = (0, node_net.createServer)();
1620
+ const listening = (0, node_events.once)(probe, "listening");
1621
+ probe.listen(port);
1622
+ await listening;
1623
+ const address = probe.address();
1624
+ const resolved = isAddressInfo(address) ? address.port : 0;
1625
+ const closed = (0, node_events.once)(probe, "close");
1626
+ probe.close();
1627
+ await closed;
1628
+ return resolved;
1629
+ }
1630
+ /**
1567
1631
  * Find a FREE TCP port — bind a throwaway `node:net` server, read the
1568
1632
  * OS-assigned port, close it, and resolve that port.
1569
1633
  *
@@ -1588,25 +1652,14 @@ function isAddressInfo(value) {
1588
1652
  * const port = await discoverPort() // a guaranteed-free ephemeral port
1589
1653
  * ```
1590
1654
  */
1591
- function discoverPort(preferred) {
1592
- return new Promise((resolve, reject) => {
1593
- const bind = (port, fallback) => {
1594
- const probe = (0, node_net.createServer)();
1595
- const onError = (error) => {
1596
- probe.close();
1597
- const taken = "code" in error && error.code === "EADDRINUSE";
1598
- if (fallback && taken) bind(0, false);
1599
- else reject(error);
1600
- };
1601
- probe.once("error", onError);
1602
- probe.listen(port, () => {
1603
- const address = probe.address();
1604
- const resolved = isAddressInfo(address) ? address.port : 0;
1605
- probe.close(() => resolve(resolved));
1606
- });
1607
- };
1608
- bind(preferred ?? 0, preferred !== void 0);
1609
- });
1655
+ async function discoverPort(preferred) {
1656
+ if (preferred === void 0) return probePort(0);
1657
+ try {
1658
+ return await probePort(preferred);
1659
+ } catch (error) {
1660
+ if (error instanceof Error && "code" in error && error.code === "EADDRINUSE") return probePort(0);
1661
+ throw error;
1662
+ }
1610
1663
  }
1611
1664
  //#endregion
1612
1665
  //#region src/server/Negotiator.ts
@@ -1693,14 +1746,17 @@ var Negotiator = class {
1693
1746
  * @typeParam TState - The consumer's opaque per-request state type
1694
1747
  *
1695
1748
  * @remarks
1696
- * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
1749
+ * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1697
1750
  * server, binds the configured {@link ServerOptions.host} / {@link
1698
1751
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1699
- * bound address), and transitions `idle → starting → listening`. `stop()`
1700
- * transitions to `stopping`: refuses new connections, fires a fresh-per-run
1701
- * stop signal so in-flight handlers observe cancellation, drains up to the
1702
- * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
1703
- * `destroy()` is the idempotent final teardown.
1752
+ * bound address), observes caller cancellation plus the configured
1753
+ * `timeouts.start` deadline while the bind is pending, and transitions
1754
+ * `idle → starting → listening`. A cancelled or expired bind closes its
1755
+ * partial server and resets to `idle` for another start. `stop()` transitions
1756
+ * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1757
+ * so in-flight handlers observe cancellation, drains up to the `drain`
1758
+ * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1759
+ * is the idempotent final teardown.
1704
1760
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1705
1761
  * `close`); a `Request` is built via the router's `buildRequest`, its
1706
1762
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1743,12 +1799,13 @@ var Server = class {
1743
1799
  #expose;
1744
1800
  #report;
1745
1801
  #timeouts;
1802
+ #sockets;
1746
1803
  #http;
1747
1804
  #abort = (0, _orkestrel_abort.createAbort)();
1805
+ #wakeup = (0, _orkestrel_abort.createAbort)();
1748
1806
  #status = "idle";
1749
1807
  #port;
1750
1808
  #pending = 0;
1751
- #waiters = [];
1752
1809
  constructor(options) {
1753
1810
  if (!(0, _orkestrel_contract.isFunction)(options.state)) throw new TypeError("ServerOptions.state must be a function");
1754
1811
  if (options.report !== void 0 && !(0, _orkestrel_contract.isFunction)(options.report)) throw new TypeError("ServerOptions.report must be a function");
@@ -1759,6 +1816,8 @@ var Server = class {
1759
1816
  const timeouts = options.timeouts ?? {};
1760
1817
  for (const [name, value] of Object.entries(timeouts)) if (value !== void 0 && (!(0, _orkestrel_contract.isFiniteNumber)(value) || value < 0)) throw new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`);
1761
1818
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1819
+ const sockets = options.sockets ?? {};
1820
+ for (const [name, value] of Object.entries(sockets)) if (value !== void 0 && (!(0, _orkestrel_contract.isInteger)(value) || value < 0)) throw new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`);
1762
1821
  this.#dispatcher = options.dispatcher;
1763
1822
  this.#state = options.state;
1764
1823
  this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
@@ -1769,9 +1828,10 @@ var Server = class {
1769
1828
  this.#expose = options.expose ?? false;
1770
1829
  this.#report = options.report;
1771
1830
  this.#timeouts = timeouts;
1831
+ this.#sockets = sockets;
1772
1832
  this.#emitter = new _orkestrel_emitter.Emitter({
1773
- on: options.on,
1774
- error: options.error
1833
+ ...options.on === void 0 ? {} : { on: options.on },
1834
+ ...options.error === void 0 ? {} : { error: options.error }
1775
1835
  });
1776
1836
  }
1777
1837
  get status() {
@@ -1793,7 +1853,7 @@ var Server = class {
1793
1853
  upgrade(handler) {
1794
1854
  this.#upgradeHandlers.push(handler);
1795
1855
  }
1796
- start() {
1856
+ start(signal) {
1797
1857
  if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
1798
1858
  this.#status = "starting";
1799
1859
  this.#abort = (0, _orkestrel_abort.createAbort)();
@@ -1801,27 +1861,12 @@ var Server = class {
1801
1861
  if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
1802
1862
  if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
1803
1863
  if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
1864
+ if (this.#sockets.connections !== void 0) server.maxConnections = this.#sockets.connections;
1865
+ if (this.#sockets.headers !== void 0) server.maxHeadersCount = this.#sockets.headers;
1866
+ if (this.#sockets.requests !== void 0) server.maxRequestsPerSocket = this.#sockets.requests;
1804
1867
  server.on("upgrade", (request, socket, head) => this.#onUpgrade(request, socket, head));
1805
1868
  this.#http = server;
1806
- return new Promise((resolve, reject) => {
1807
- const onError = (error) => {
1808
- server.off("listening", onListening);
1809
- this.#http = void 0;
1810
- this.#status = "idle";
1811
- reject(error);
1812
- };
1813
- const onListening = () => {
1814
- server.off("error", onError);
1815
- const port = this.#resolvePort(server);
1816
- this.#port = port;
1817
- this.#status = "listening";
1818
- this.#emitter.emit("start", port);
1819
- resolve(port);
1820
- };
1821
- server.once("error", onError);
1822
- server.once("listening", onListening);
1823
- server.listen(this.#configuredPort ?? 0, this.#host);
1824
- });
1869
+ return this.#listen(server, signal);
1825
1870
  }
1826
1871
  async stop() {
1827
1872
  if (this.#status !== "listening") return;
@@ -1874,19 +1919,16 @@ var Server = class {
1874
1919
  const linked = (0, _orkestrel_abort.linkSignal)(raw.signal, this.#abort.signal);
1875
1920
  const request = new Request(raw, { signal: linked });
1876
1921
  this.#emitter.emit("request", method, url.pathname);
1922
+ const ip = message.socket.remoteAddress;
1877
1923
  const connection = {
1878
- ip: message.socket.remoteAddress,
1924
+ ...ip === void 0 ? {} : { ip },
1879
1925
  encrypted: (0, _orkestrel_router_server.isEncryptedSocket)(message.socket)
1880
1926
  };
1881
- let cached;
1882
1927
  const context = {
1883
1928
  url,
1884
1929
  method,
1885
1930
  state: this.#state(connection),
1886
- body: () => {
1887
- cached ??= readBody(request, { limit: this.#limit });
1888
- return cached;
1889
- }
1931
+ body: this.#createBody(request)
1890
1932
  };
1891
1933
  const result = await compose(this.#middleware, (currentRequest, currentContext) => this.#dispatcher.handle(currentRequest, currentContext.state))(request, context);
1892
1934
  await this.#respond(result, response);
@@ -1949,6 +1991,55 @@ var Server = class {
1949
1991
  if (isAddressInfo(address)) return address.port;
1950
1992
  return 0;
1951
1993
  }
1994
+ async #listen(server, signal) {
1995
+ const deadline = this.#timeouts.start === void 0 ? void 0 : (0, _orkestrel_timeout.createTimeout)({ ms: this.#timeouts.start });
1996
+ const startup = deadline === void 0 ? signal : (0, _orkestrel_abort.linkSignal)(deadline.signal, signal);
1997
+ const binding = (0, _orkestrel_abort.createAbort)();
1998
+ const relay = startup === void 0 ? void 0 : (0, node_events.addAbortListener)(startup, () => binding.abort(startup.reason));
1999
+ let listening;
2000
+ try {
2001
+ signal?.throwIfAborted();
2002
+ deadline?.start();
2003
+ if (deadline?.ms === 0 && startup !== void 0) await (0, node_events.once)(startup, "abort");
2004
+ startup?.throwIfAborted();
2005
+ listening = (0, node_events.once)(server, "listening", { signal: binding.signal });
2006
+ if (startup === void 0) server.listen(this.#configuredPort ?? 0, this.#host);
2007
+ else server.listen({
2008
+ port: this.#configuredPort ?? 0,
2009
+ ...this.#host === void 0 ? {} : { host: this.#host },
2010
+ signal: binding.signal
2011
+ });
2012
+ await listening;
2013
+ } catch (error) {
2014
+ const expired = deadline?.expired === true;
2015
+ const cancelled = startup?.aborted === true;
2016
+ server.on("error", () => void 0);
2017
+ binding.abort(error);
2018
+ if (listening !== void 0) await listening.catch(() => void 0);
2019
+ await this.#close(server, true);
2020
+ this.#http = void 0;
2021
+ this.#port = void 0;
2022
+ this.#status = "idle";
2023
+ if (expired && deadline !== void 0) throw new DOMException(`Server startup exceeded ${deadline.ms} milliseconds`, "TimeoutError");
2024
+ if (cancelled && startup !== void 0) throw startup.reason;
2025
+ throw error;
2026
+ } finally {
2027
+ relay?.[Symbol.dispose]();
2028
+ deadline?.clear();
2029
+ }
2030
+ const port = this.#resolvePort(server);
2031
+ this.#port = port;
2032
+ this.#status = "listening";
2033
+ this.#emitter.emit("start", port);
2034
+ return port;
2035
+ }
2036
+ #createBody(request) {
2037
+ let cached;
2038
+ return () => {
2039
+ cached ??= readBody(request, { limit: this.#limit });
2040
+ return cached;
2041
+ };
2042
+ }
1952
2043
  #close(server, force) {
1953
2044
  return new Promise((resolve) => {
1954
2045
  server.close(() => resolve());
@@ -1957,29 +2048,19 @@ var Server = class {
1957
2048
  });
1958
2049
  }
1959
2050
  #trackStart() {
2051
+ if (this.#pending === 0) this.#wakeup = (0, _orkestrel_abort.createAbort)();
1960
2052
  this.#pending += 1;
1961
2053
  let finished = false;
1962
2054
  return () => {
1963
2055
  if (finished) return;
1964
2056
  finished = true;
1965
2057
  this.#pending -= 1;
1966
- if (this.#pending === 0) {
1967
- const waiters = this.#waiters;
1968
- this.#waiters = [];
1969
- for (const wake of waiters) wake();
1970
- }
2058
+ if (this.#pending === 0) this.#wakeup.abort();
1971
2059
  };
1972
2060
  }
1973
- #drainPending(signal) {
1974
- if (this.#pending === 0 || signal.aborted) return Promise.resolve();
1975
- return new Promise((resolve) => {
1976
- const onDone = () => {
1977
- signal.removeEventListener("abort", onDone);
1978
- resolve();
1979
- };
1980
- this.#waiters.push(onDone);
1981
- signal.addEventListener("abort", onDone, { once: true });
1982
- });
2061
+ async #drainPending(signal) {
2062
+ if (this.#pending === 0 || signal.aborted) return;
2063
+ await (0, node_events.once)(AbortSignal.any([signal, this.#wakeup.signal]), "abort");
1983
2064
  }
1984
2065
  };
1985
2066
  //#endregion
@@ -2061,6 +2142,7 @@ exports.decodeTokenPayload = decodeTokenPayload;
2061
2142
  exports.decompressRequestBody = decompressRequestBody;
2062
2143
  exports.discoverPort = discoverPort;
2063
2144
  exports.encodeBase64Url = encodeBase64Url;
2145
+ exports.enqueueStreamText = enqueueStreamText;
2064
2146
  exports.ipv6Network = ipv6Network;
2065
2147
  exports.isAddressInfo = isAddressInfo;
2066
2148
  exports.isCompressibleType = isCompressibleType;
@@ -2079,6 +2161,7 @@ exports.openStream = openStream;
2079
2161
  exports.parseAcceptHeader = parseAcceptHeader;
2080
2162
  exports.parseCookies = parseCookies;
2081
2163
  exports.parseRange = parseRange;
2164
+ exports.probePort = probePort;
2082
2165
  exports.readBody = readBody;
2083
2166
  exports.readSignedCookie = readSignedCookie;
2084
2167
  exports.requestEncoding = requestEncoding;
@@ -2091,6 +2174,7 @@ exports.serializeEvent = serializeEvent;
2091
2174
  exports.signToken = signToken;
2092
2175
  exports.unwrapETag = unwrapETag;
2093
2176
  exports.verifyToken = verifyToken;
2177
+ exports.wrapMiddleware = wrapMiddleware;
2094
2178
  exports.writeSignedCookie = writeSignedCookie;
2095
2179
 
2096
2180
  //# sourceMappingURL=index.cjs.map