@orkestrel/server 0.0.1
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.
- package/LICENSE +21 -0
- package/README.md +34 -0
- package/dist/src/core/Negotiator.d.ts +32 -0
- package/dist/src/core/constants.d.ts +68 -0
- package/dist/src/core/errors.d.ts +73 -0
- package/dist/src/core/factories.d.ts +21 -0
- package/dist/src/core/helpers.d.ts +890 -0
- package/dist/src/core/index.d.ts +6 -0
- package/dist/src/core/index.js +1728 -0
- package/dist/src/core/index.js.map +1 -0
- package/dist/src/core/types.d.ts +362 -0
- package/dist/src/server/Server.d.ts +63 -0
- package/dist/src/server/factories.d.ts +26 -0
- package/dist/src/server/helpers.d.ts +45 -0
- package/dist/src/server/index.cjs +1330 -0
- package/dist/src/server/index.cjs.map +1 -0
- package/dist/src/server/index.d.ts +4 -0
- package/dist/src/server/types.d.ts +163 -0
- package/package.json +87 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The composition context — plain data, one per request, shared by every
|
|
3
|
+
* middleware AND (as `state`) by the route handlers behind the dispatcher.
|
|
4
|
+
*
|
|
5
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* - `url` — the parsed request {@link URL} (mirrors the router's own parse, so
|
|
9
|
+
* a middleware never re-parses it).
|
|
10
|
+
* - `method` — the raw request verb; the dispatcher (not this seam) narrows it
|
|
11
|
+
* to a known {@link import('@orkestrel/router').Method}.
|
|
12
|
+
* - `state` — THE shared bag threaded from the adapter's `state` factory,
|
|
13
|
+
* through every middleware, into `dispatcher.handle`'s `state` — the same
|
|
14
|
+
* object a route handler reads as `context.state`.
|
|
15
|
+
* - `body()` — lazily collect the request body (byte-limited, transparently
|
|
16
|
+
* decompressed, prototype-scrubbed for JSON), cached so repeated calls (a
|
|
17
|
+
* body-parsing middleware, then the handler) read the underlying stream
|
|
18
|
+
* exactly once.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* const middleware: MiddlewareHandler<{ readonly userId?: string }> = async (request, context, next) => {
|
|
23
|
+
* const body = await context.body()
|
|
24
|
+
* return next(request)
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export interface MiddlewareContext<TState> {
|
|
29
|
+
readonly url: URL;
|
|
30
|
+
readonly method: string;
|
|
31
|
+
readonly state: TState;
|
|
32
|
+
body(): Promise<unknown>;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The downstream continuation a {@link MiddlewareHandler} invokes to run the
|
|
36
|
+
* rest of the onion.
|
|
37
|
+
*
|
|
38
|
+
* @remarks
|
|
39
|
+
* Call it (optionally with a substituted `Request`) to run the downstream
|
|
40
|
+
* chain and receive its `Response`; omit the call entirely to short-circuit
|
|
41
|
+
* with a `Response` built by this middleware instead. A SECOND call rejects
|
|
42
|
+
* (the double-`next` guard) — each middleware runs the chain at most once.
|
|
43
|
+
*
|
|
44
|
+
* @param request - An optional replacement `Request` to hand downstream
|
|
45
|
+
* (omitted ⇒ the original request continues)
|
|
46
|
+
* @returns The downstream chain's resolved `Response`
|
|
47
|
+
*/
|
|
48
|
+
export type NextFunction = (request?: Request) => Promise<Response>;
|
|
49
|
+
/**
|
|
50
|
+
* One link in the middleware onion — runs around the rest of the chain.
|
|
51
|
+
*
|
|
52
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
53
|
+
*
|
|
54
|
+
* @remarks
|
|
55
|
+
* Transform the request (call `next(newRequest)`), transform the response
|
|
56
|
+
* (`await next()` then modify the result), short-circuit (return a `Response`
|
|
57
|
+
* without calling `next`), or thread data via `context.state` — no mutable
|
|
58
|
+
* framework object anywhere, only fetch-standard `Request`/`Response`.
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```ts
|
|
62
|
+
* const withRequestId: MiddlewareHandler<{ readonly requestId: string }> = async (request, context, next) => {
|
|
63
|
+
* const response = await next()
|
|
64
|
+
* response.headers.set('X-Request-ID', context.state.requestId)
|
|
65
|
+
* return response
|
|
66
|
+
* }
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export type MiddlewareHandler<TState> = (request: Request, context: MiddlewareContext<TState>, next: NextFunction) => Response | Promise<Response>;
|
|
70
|
+
/**
|
|
71
|
+
* The per-request connection facts the server face injects — the ONLY data
|
|
72
|
+
* that genuinely exists solely on the socket, surfaced so middleware and a
|
|
73
|
+
* consumer's `state` factory stay core-pure.
|
|
74
|
+
*
|
|
75
|
+
* @remarks
|
|
76
|
+
* - `ip` — the socket peer address, for a spoof-proof rate-limit key. Never
|
|
77
|
+
* derived from `X-Forwarded-For` (a client-controlled header) — a
|
|
78
|
+
* deployment behind a trusted proxy derives its own client key explicitly.
|
|
79
|
+
* - `encrypted` — whether the connection is TLS, for an auto-`Secure` cookie
|
|
80
|
+
* decision ({@link CookieOptions.secure} left `undefined`).
|
|
81
|
+
*/
|
|
82
|
+
export interface ConnectionInfo {
|
|
83
|
+
readonly ip?: string;
|
|
84
|
+
readonly encrypted: boolean;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A secret (or rotation list) for signing + verifying a stateless, HMAC-signed
|
|
88
|
+
* token.
|
|
89
|
+
*
|
|
90
|
+
* @remarks
|
|
91
|
+
* A single `string` is the lone secret. A `readonly string[]` is a rotation
|
|
92
|
+
* list in `[current, ...older]` order: `signToken` always signs with the
|
|
93
|
+
* FIRST (current) secret, while `verifyToken` accepts a token signed by ANY
|
|
94
|
+
* secret in the list — so a key rotates by prepending the new one and keeping
|
|
95
|
+
* the old until every outstanding token has expired, with zero downtime.
|
|
96
|
+
*/
|
|
97
|
+
export type TokenSecret = string | readonly string[];
|
|
98
|
+
/**
|
|
99
|
+
* Options for `signToken` — how a stateless, HMAC-signed token is minted.
|
|
100
|
+
*
|
|
101
|
+
* @param secret - The {@link TokenSecret} to sign with; `signToken` always
|
|
102
|
+
* uses the FIRST secret (a single string, or the current head of a
|
|
103
|
+
* rotation list). An empty rotation list is a misconfiguration and throws.
|
|
104
|
+
* @param ttl - An optional lifetime in milliseconds. When set, the expiry
|
|
105
|
+
* timestamp is bound INTO the signed payload (HMAC-covered, tamper-proof);
|
|
106
|
+
* `verifyToken` rejects the token once that instant has passed. Omitted ⇒
|
|
107
|
+
* the token never expires.
|
|
108
|
+
*/
|
|
109
|
+
export interface TokenOptions {
|
|
110
|
+
readonly secret: TokenSecret;
|
|
111
|
+
readonly ttl?: number;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The `Set-Cookie` attributes for `serializeCookie` (and any signed-cookie
|
|
115
|
+
* transport built over it).
|
|
116
|
+
*
|
|
117
|
+
* @param path - The `Path` directive; defaults to `'/'`.
|
|
118
|
+
* @param domain - The `Domain` directive; omitted ⇒ a host-only cookie.
|
|
119
|
+
* @param maxAge - The `Max-Age` directive in SECONDS (the wire unit, not a
|
|
120
|
+
* millisecond `ttl`); `0` expires the cookie immediately.
|
|
121
|
+
* @param httpOnly - The `HttpOnly` directive; defaults to `true`.
|
|
122
|
+
* @param secure - The `Secure` directive: `true` forces it, `false`
|
|
123
|
+
* suppresses it, and omitted/`undefined` (the default) derives it from the
|
|
124
|
+
* connection via {@link import('./helpers.js').resolveSecure} — `Secure` on
|
|
125
|
+
* a TLS connection, off over plaintext HTTP ({@link
|
|
126
|
+
* ConnectionInfo.encrypted}). A `sameSite: 'None'` cookie is ALWAYS
|
|
127
|
+
* `Secure` regardless (the spec requires it).
|
|
128
|
+
* @param sameSite - The `SameSite` directive; defaults to `'Lax'`.
|
|
129
|
+
*/
|
|
130
|
+
export interface CookieOptions {
|
|
131
|
+
readonly path?: string;
|
|
132
|
+
readonly domain?: string;
|
|
133
|
+
readonly maxAge?: number;
|
|
134
|
+
readonly httpOnly?: boolean;
|
|
135
|
+
readonly secure?: boolean;
|
|
136
|
+
readonly sameSite?: 'Strict' | 'Lax' | 'None';
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* One parsed entry of a weighted `Accept` / `Accept-Encoding` / `Accept-Language`
|
|
140
|
+
* header — a value and its quality weight, the element type `parseAcceptHeader`
|
|
141
|
+
* returns (sorted by `q` descending).
|
|
142
|
+
*
|
|
143
|
+
* @remarks
|
|
144
|
+
* `value` is the lower-cased token (`text/html`, `gzip`, `en-us`, or a
|
|
145
|
+
* wildcard). `q` is the quality weight in `[0, 1]` (the `;q=` parameter,
|
|
146
|
+
* default `1` when absent); a `;q=0` entry explicitly REJECTS that token — a
|
|
147
|
+
* parser keeps it (so a caller can honor the rejection) rather than
|
|
148
|
+
* dropping it.
|
|
149
|
+
*/
|
|
150
|
+
export interface AcceptEntry {
|
|
151
|
+
readonly value: string;
|
|
152
|
+
readonly q: number;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* A content-coding the substrate compresses / decompresses with — the
|
|
156
|
+
* `Content-Encoding` / `Accept-Encoding` token vocabulary it understands.
|
|
157
|
+
*
|
|
158
|
+
* @remarks
|
|
159
|
+
* `gzip` / `deflate` map to `CompressionStream` / `DecompressionStream`
|
|
160
|
+
* (web-standard, no external codec); `identity` is the no-op "uncompressed"
|
|
161
|
+
* coding. Brotli (`br`) has no `CompressionStream` implementation yet, so it
|
|
162
|
+
* is deliberately OMITTED here — Brotli parity is the future middleware
|
|
163
|
+
* package's node-entry decision (§3 of the proposal), not this core's. A
|
|
164
|
+
* constrained set of external-spec literals, so it stays a union, not a
|
|
165
|
+
* behavioral toggle (AGENTS §4.4).
|
|
166
|
+
*/
|
|
167
|
+
export type Encoding = 'gzip' | 'deflate' | 'identity';
|
|
168
|
+
/**
|
|
169
|
+
* A map of media type → handler for {@link NegotiatorInterface.format} — the
|
|
170
|
+
* content-negotiation dispatch table.
|
|
171
|
+
*
|
|
172
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
173
|
+
*
|
|
174
|
+
* @remarks
|
|
175
|
+
* Each key is a media type the route can PRODUCE (`application/json`,
|
|
176
|
+
* `text/html`, …) and each value the responder that returns that
|
|
177
|
+
* representation as a `Response`. `format` negotiates the client's preferred
|
|
178
|
+
* key from the request `Accept` header and invokes the matching handler, or
|
|
179
|
+
* answers `406 Not Acceptable` when none of the offered types is acceptable.
|
|
180
|
+
* The keys are the `available` set negotiation chooses from, so their order
|
|
181
|
+
* is the server's tie-break preference (a client accepting the any-media-
|
|
182
|
+
* range gets the first key).
|
|
183
|
+
*/
|
|
184
|
+
export type FormatHandlerMap<TState> = Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response | Promise<Response>>>;
|
|
185
|
+
/**
|
|
186
|
+
* Content negotiation over the weighted `Accept` family — a reusable,
|
|
187
|
+
* cross-middleware machine (not itself a middleware).
|
|
188
|
+
*
|
|
189
|
+
* @remarks
|
|
190
|
+
* Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
|
|
191
|
+
* (q-values honored, `*` wildcards honored, a `;q=0` rejection respected) and
|
|
192
|
+
* picks the client's most-preferred value the server also offers. `negotiate`
|
|
193
|
+
* is the generic primitive (media types); `encoding` / `language` are its
|
|
194
|
+
* sibling axes. `format` is the dispatcher — it reads the request `Accept`,
|
|
195
|
+
* negotiates against a {@link FormatHandlerMap}'s keys, and invokes the
|
|
196
|
+
* winning handler, resolving `406 Not Acceptable` when none is acceptable.
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```ts
|
|
200
|
+
* const response = await negotiator.format(request, context, {
|
|
201
|
+
* 'application/json': (request, context) => Response.json({ ok: true }),
|
|
202
|
+
* 'text/html': (request, context) => new Response('<p>ok</p>', { headers: { 'Content-Type': 'text/html' } }),
|
|
203
|
+
* })
|
|
204
|
+
* ```
|
|
205
|
+
*/
|
|
206
|
+
export interface NegotiatorInterface {
|
|
207
|
+
/**
|
|
208
|
+
* Pick the best `available` value for a weighted `Accept`-style `header` —
|
|
209
|
+
* the generic media-type primitive (`encoding` / `language` build on it).
|
|
210
|
+
*
|
|
211
|
+
* @param header - The raw weighted header value (e.g. `text/html, application/json;q=0.9`)
|
|
212
|
+
* @param available - The values the server can produce, in preference (tie-break) order
|
|
213
|
+
* @returns The best acceptable value, or `undefined` when none is
|
|
214
|
+
*/
|
|
215
|
+
negotiate(header: string, available: readonly string[]): string | undefined;
|
|
216
|
+
/**
|
|
217
|
+
* Pick the best `available` content-coding for an `Accept-Encoding` header
|
|
218
|
+
* — `negotiate` scoped to codings (a bare `*` wildcard ⇒ the first `available`).
|
|
219
|
+
*
|
|
220
|
+
* @param header - The raw `Accept-Encoding` header value (e.g. `gzip;q=1.0, deflate;q=0.8`)
|
|
221
|
+
* @param available - The codings the server offers, in preference order
|
|
222
|
+
* @returns The best acceptable coding, or `undefined` when none is
|
|
223
|
+
*/
|
|
224
|
+
encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
|
|
225
|
+
/**
|
|
226
|
+
* Pick the best `available` language for an `Accept-Language` header —
|
|
227
|
+
* `negotiate` with a language-prefix match (`en` accepts `en-US`) and a
|
|
228
|
+
* bare `*` wildcard.
|
|
229
|
+
*
|
|
230
|
+
* @param header - The raw `Accept-Language` header value (e.g. `en-US, en;q=0.8, fr;q=0.5`)
|
|
231
|
+
* @param available - The languages the server offers, in preference order
|
|
232
|
+
* @returns The best acceptable language, or `undefined` when none is
|
|
233
|
+
*/
|
|
234
|
+
language(header: string, available: readonly string[]): string | undefined;
|
|
235
|
+
/**
|
|
236
|
+
* Dispatch to the handler whose media type the client most prefers — read
|
|
237
|
+
* the request `Accept`, negotiate against `handlers`' keys, and invoke the
|
|
238
|
+
* winner; `406` when none is acceptable.
|
|
239
|
+
*
|
|
240
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
241
|
+
* @param request - The in-flight `Request`
|
|
242
|
+
* @param context - The request's {@link MiddlewareContext}
|
|
243
|
+
* @param handlers - The media type → responder {@link FormatHandlerMap} the route offers
|
|
244
|
+
* @returns The winning handler's `Response`, or a `406 Not Acceptable` `Response`
|
|
245
|
+
*/
|
|
246
|
+
format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* One Server-Sent Event to serialize to the wire.
|
|
250
|
+
*
|
|
251
|
+
* @remarks
|
|
252
|
+
* - `data` — the event payload (required). Serialized as one or more `data:`
|
|
253
|
+
* lines: the value is split on `\n` into a `data:` line PER segment, so it
|
|
254
|
+
* round-trips through a consumer's multi-`data` concat.
|
|
255
|
+
* - `event` — the optional event TYPE, emitted as an `event:` line; omitted
|
|
256
|
+
* ⇒ the consumer's default (`message`).
|
|
257
|
+
* - `id` — the optional last-event-id, emitted as an `id:` line.
|
|
258
|
+
* - `retry` — the optional reconnection time in milliseconds, emitted as a
|
|
259
|
+
* `retry:` line.
|
|
260
|
+
*/
|
|
261
|
+
export interface SSEMessage {
|
|
262
|
+
readonly data: string;
|
|
263
|
+
/** Must be a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
|
|
264
|
+
readonly event?: string;
|
|
265
|
+
/** Must be a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
|
|
266
|
+
readonly id?: string;
|
|
267
|
+
readonly retry?: number;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Options for the `openStream` seam.
|
|
271
|
+
*
|
|
272
|
+
* @param status - The HTTP status the streaming response is opened with;
|
|
273
|
+
* defaults to `200`.
|
|
274
|
+
* @param headers - Extra response headers merged with the SSE headers the
|
|
275
|
+
* seam always sets ({@link SSE_HEADERS}) — a key the seam owns is never
|
|
276
|
+
* overridden.
|
|
277
|
+
*/
|
|
278
|
+
export interface StreamOptions {
|
|
279
|
+
readonly status?: number;
|
|
280
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* A handle to write Server-Sent Events to an open, fetch-standard streaming
|
|
284
|
+
* `Response` — the generic streaming surface `openStream` returns over a
|
|
285
|
+
* `ReadableStream`.
|
|
286
|
+
*
|
|
287
|
+
* @remarks
|
|
288
|
+
* Agent-agnostic by design: it speaks only the SSE wire vocabulary ({@link
|
|
289
|
+
* SSEMessage}), so any streaming consumer maps its own events onto `write`.
|
|
290
|
+
* `response` is the `Response` to return from the route handler (its body is
|
|
291
|
+
* the `ReadableStream` this handle writes into). Each `write` serializes the
|
|
292
|
+
* message to the wire and enqueues it; `comment` writes a `: text` keep-alive
|
|
293
|
+
* line (ignored by a conforming SSE parser — no spurious event); `end` closes
|
|
294
|
+
* the stream. Every method is a SAFE NO-OP once `closed` is `true`, so a late
|
|
295
|
+
* `write` never throws.
|
|
296
|
+
*/
|
|
297
|
+
export interface StreamInterface {
|
|
298
|
+
/** The streaming `Response` to return from the route handler. */
|
|
299
|
+
readonly response: Response;
|
|
300
|
+
/** Whether the underlying stream is done (ended, or the consumer disconnected). */
|
|
301
|
+
readonly closed: boolean;
|
|
302
|
+
/**
|
|
303
|
+
* Serialize + enqueue one {@link SSEMessage} to the wire (a no-op once `closed`).
|
|
304
|
+
*
|
|
305
|
+
* @param message - The event to send (its `data` split on `\n` into `data:` lines)
|
|
306
|
+
*/
|
|
307
|
+
write(message: SSEMessage): void;
|
|
308
|
+
/**
|
|
309
|
+
* Write a `: text` SSE comment line — a keep-alive a conforming parser ignores.
|
|
310
|
+
*
|
|
311
|
+
* @param text - The comment text (sent after the `: ` prefix)
|
|
312
|
+
*/
|
|
313
|
+
comment(text: string): void;
|
|
314
|
+
/** End the stream, completing the response (a no-op once already `closed`). */
|
|
315
|
+
end(): void;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* The parsed outcome of an HTTP `Range` request header.
|
|
319
|
+
*
|
|
320
|
+
* @remarks
|
|
321
|
+
* A `Range: bytes=start-end` against a known resource `size` resolves to ONE
|
|
322
|
+
* of two shapes, discriminated by `satisfiable` (the axis is whether the
|
|
323
|
+
* requested span overlaps the resource):
|
|
324
|
+
*
|
|
325
|
+
* - **`satisfiable: true`** — a concrete, clamped byte window `[start, end]`
|
|
326
|
+
* (INCLUSIVE, the HTTP wire convention), normalized from the header's
|
|
327
|
+
* open / suffix / closed forms against `size`.
|
|
328
|
+
* - **`satisfiable: false`** — the range lies wholly outside the resource.
|
|
329
|
+
*
|
|
330
|
+
* `parseRange` returns `undefined` for an ABSENT / unparseable / multi-range
|
|
331
|
+
* / non-`bytes` header — the "no range, serve the whole resource" case — so
|
|
332
|
+
* the three outcomes (full / partial / unsatisfiable) are distinguished
|
|
333
|
+
* without a separate flag. It is TOTAL — a hostile header never throws.
|
|
334
|
+
*/
|
|
335
|
+
export type RangeSpec = {
|
|
336
|
+
readonly satisfiable: true;
|
|
337
|
+
readonly start: number;
|
|
338
|
+
readonly end: number;
|
|
339
|
+
} | {
|
|
340
|
+
readonly satisfiable: false;
|
|
341
|
+
};
|
|
342
|
+
/**
|
|
343
|
+
* Options for `readBody` — how the shared body-collection pipeline caps and
|
|
344
|
+
* decompresses a request body.
|
|
345
|
+
*
|
|
346
|
+
* @param limit - The maximum request body size in bytes; a larger body
|
|
347
|
+
* throws a {@link import('./errors.js').ContentTooLargeError} (413).
|
|
348
|
+
* Defaults to {@link DEFAULT_BODY_LIMIT}.
|
|
349
|
+
* @param decompression - The maximum DECOMPRESSED body size in bytes (the
|
|
350
|
+
* zip-bomb cap) for a `Content-Encoding: gzip` / `deflate` request body. A
|
|
351
|
+
* highly-compressible payload small ON THE WIRE (under `limit`) can inflate
|
|
352
|
+
* enormously, so a byte-counting `TransformStream` aborts the pipe the
|
|
353
|
+
* instant decompressed output would exceed this. Defaults to {@link
|
|
354
|
+
* import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT} (16 MiB) —
|
|
355
|
+
* INDEPENDENT of `limit`, not aligned with it; a non-positive value means
|
|
356
|
+
* UNCAPPED decompressed output — use only when `limit` already bounds the
|
|
357
|
+
* compressed input.
|
|
358
|
+
*/
|
|
359
|
+
export interface BodyOptions {
|
|
360
|
+
readonly limit?: number;
|
|
361
|
+
readonly decompression?: number;
|
|
362
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { EmitterInterface } from '@orkestrel/emitter';
|
|
2
|
+
import type { MiddlewareHandler } from '@src/core';
|
|
3
|
+
import type { DispatcherInterface } from '@orkestrel/router';
|
|
4
|
+
import type { ServerEventMap, ServerInterface, ServerOptions, ServerStatus, UpgradeHandler } from './types.js';
|
|
5
|
+
/**
|
|
6
|
+
* The HTTP server facade — an observable `node:http` lifecycle composing the
|
|
7
|
+
* `@src/core` middleware onion around a consumed `@orkestrel/router`
|
|
8
|
+
* dispatcher.
|
|
9
|
+
*
|
|
10
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
11
|
+
*
|
|
12
|
+
* @remarks
|
|
13
|
+
* - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
|
|
14
|
+
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
15
|
+
* ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
|
|
16
|
+
* bound address), and transitions `idle → starting → listening`. `stop()`
|
|
17
|
+
* transitions to `stopping`: refuses new connections, fires a fresh-per-run
|
|
18
|
+
* stop signal so in-flight handlers observe cancellation, drains up to the
|
|
19
|
+
* `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
|
|
20
|
+
* `destroy()` is the idempotent final teardown.
|
|
21
|
+
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
22
|
+
* `close`); a `Request` is built via the router's `buildRequest`, its
|
|
23
|
+
* `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
|
|
24
|
+
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
25
|
+
* `buildRequest`'s own abort, tied to client disconnect, composes with the
|
|
26
|
+
* server's stop signal via `AbortSignal.any`, so a handler awaiting
|
|
27
|
+
* `request.signal` observes BOTH); `context.state` is built via
|
|
28
|
+
* {@link ServerOptions.state} from the connection facts; the composed
|
|
29
|
+
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
30
|
+
* written back via `sendResponse`.
|
|
31
|
+
* - **The built-in boundary** wraps the WHOLE per-request chain, including
|
|
32
|
+
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
33
|
+
* throw (e.g. a malformed `Host` header) to a silent `400` with no
|
|
34
|
+
* `error` emit; everything after (`Request` reconstruction, connection
|
|
35
|
+
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
36
|
+
* behind the outer boundary — a thrown `HTTPError` renders as its status +
|
|
37
|
+
* message; any other throw renders `500` (message hidden unless
|
|
38
|
+
* `expose`), `report` is invoked (its own throw swallowed), and `error` is
|
|
39
|
+
* emitted. A server-owned last resort wraps the final `sendResponse`
|
|
40
|
+
* write itself: if even that fails, the connection is destroyed rather
|
|
41
|
+
* than left to escape as an unhandled error.
|
|
42
|
+
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
43
|
+
* throwing handler is treated as declined and surfaced on `error`, an
|
|
44
|
+
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
45
|
+
* - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
46
|
+
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
47
|
+
* routes it to the `error` OPTION (not the domain `error` event).
|
|
48
|
+
*/
|
|
49
|
+
export declare class Server<TState> implements ServerInterface<TState> {
|
|
50
|
+
#private;
|
|
51
|
+
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
52
|
+
constructor(options: ServerOptions<TState>);
|
|
53
|
+
get status(): ServerStatus;
|
|
54
|
+
get port(): number | undefined;
|
|
55
|
+
get dispatcher(): DispatcherInterface<TState>;
|
|
56
|
+
get emitter(): EmitterInterface<ServerEventMap>;
|
|
57
|
+
use(middleware: MiddlewareHandler<TState>): void;
|
|
58
|
+
use(middleware: readonly MiddlewareHandler<TState>[]): void;
|
|
59
|
+
upgrade(handler: UpgradeHandler): void;
|
|
60
|
+
start(): Promise<number>;
|
|
61
|
+
stop(): Promise<void>;
|
|
62
|
+
destroy(): Promise<void>;
|
|
63
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ServerInterface, ServerOptions } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Create a {@link ServerInterface} — the node face's HTTP server facade over
|
|
4
|
+
* a consumed `@orkestrel/router` dispatcher.
|
|
5
|
+
*
|
|
6
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
7
|
+
* @param options - {@link ServerOptions}
|
|
8
|
+
* @returns A {@link ServerInterface}, not yet started
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { createServer } from '@src/server'
|
|
13
|
+
* import { createDispatcher } from '@orkestrel/router'
|
|
14
|
+
*
|
|
15
|
+
* const dispatcher = createDispatcher<{ readonly ip?: string }>()
|
|
16
|
+
* dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
|
|
17
|
+
*
|
|
18
|
+
* const server = createServer({
|
|
19
|
+
* dispatcher,
|
|
20
|
+
* state: (connection) => ({ ip: connection.ip }),
|
|
21
|
+
* })
|
|
22
|
+
* const port = await server.start()
|
|
23
|
+
* await server.stop()
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { AddressInfo } from 'node:net';
|
|
2
|
+
/**
|
|
3
|
+
* Whether a `node:net` `server.address()` return is the structured
|
|
4
|
+
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
5
|
+
* or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
|
|
6
|
+
* and the `Server`'s own port resolution read the bound port through.
|
|
7
|
+
*
|
|
8
|
+
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
9
|
+
* @returns `true` when `value` is an `AddressInfo` with a numeric `port`
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { isAddressInfo } from '@src/server'
|
|
14
|
+
*
|
|
15
|
+
* isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
|
|
16
|
+
* isAddressInfo(null) // false
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
20
|
+
/**
|
|
21
|
+
* Find a FREE TCP port — bind a throwaway `node:net` server, read the
|
|
22
|
+
* OS-assigned port, close it, and resolve that port.
|
|
23
|
+
*
|
|
24
|
+
* @remarks
|
|
25
|
+
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
26
|
+
* and returns it. With a `preferred` port it tries THAT port first and
|
|
27
|
+
* returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
|
|
28
|
+
* ephemeral free port rather than rejecting — a caller always gets a usable
|
|
29
|
+
* port. It binds then immediately closes a probe server, so the returned
|
|
30
|
+
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
31
|
+
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
32
|
+
* `preferred` port (e.g. a permission fault).
|
|
33
|
+
*
|
|
34
|
+
* @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
|
|
35
|
+
* fall back to an ephemeral port
|
|
36
|
+
* @returns A free TCP port number
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* import { createServer, discoverPort } from '@src/server'
|
|
41
|
+
*
|
|
42
|
+
* const port = await discoverPort() // a guaranteed-free ephemeral port
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export declare function discoverPort(preferred?: number): Promise<number>;
|