@orkestrel/server 0.0.2 → 0.0.4

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,1512 +0,0 @@
1
- /**
2
- * One parsed entry of a weighted `Accept` / `Accept-Encoding` / `Accept-Language`
3
- * header — a value and its quality weight, the element type `parseAcceptHeader`
4
- * returns (sorted by `q` descending).
5
- *
6
- * @remarks
7
- * `value` is the lower-cased token (`text/html`, `gzip`, `en-us`, or a
8
- * wildcard). `q` is the quality weight in `[0, 1]` (the `;q=` parameter,
9
- * default `1` when absent); a `;q=0` entry explicitly REJECTS that token — a
10
- * parser keeps it (so a caller can honor the rejection) rather than
11
- * dropping it.
12
- */
13
- export declare interface AcceptEntry {
14
- readonly value: string;
15
- readonly q: number;
16
- }
17
-
18
- /**
19
- * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT
20
- * clobbering a prior one.
21
- *
22
- * @remarks
23
- * `Headers.append` already accumulates repeated headers (unlike node's
24
- * `setHeader`), so this is a thin, self-documenting wrapper naming the
25
- * cookie-append intent — the primitive {@link writeSignedCookie} /
26
- * {@link clearCookie} use.
27
- *
28
- * @param headers - The response `Headers` to write into
29
- * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})
30
- *
31
- * @example
32
- * ```ts
33
- * const headers = new Headers()
34
- * appendCookie(headers, serializeCookie('a', '1'))
35
- * appendCookie(headers, serializeCookie('b', '2'))
36
- * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'
37
- * ```
38
- */
39
- export declare function appendCookie(headers: Headers, cookie: string): void;
40
-
41
- /**
42
- * Options for `readBody` — how the shared body-collection pipeline caps and
43
- * decompresses a request body.
44
- *
45
- * @param limit - The maximum request body size in bytes; a larger body
46
- * throws a {@link import('./errors.js').ContentTooLargeError} (413).
47
- * Defaults to {@link DEFAULT_BODY_LIMIT}.
48
- * @param decompression - The maximum DECOMPRESSED body size in bytes (the
49
- * zip-bomb cap) for a `Content-Encoding: gzip` / `deflate` request body. A
50
- * highly-compressible payload small ON THE WIRE (under `limit`) can inflate
51
- * enormously, so a byte-counting `TransformStream` aborts the pipe the
52
- * instant decompressed output would exceed this. Defaults to {@link
53
- * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT} (16 MiB) —
54
- * INDEPENDENT of `limit`, not aligned with it; a non-positive value means
55
- * UNCAPPED decompressed output — use only when `limit` already bounds the
56
- * compressed input.
57
- */
58
- export declare interface BodyOptions {
59
- readonly limit?: number;
60
- readonly decompression?: number;
61
- }
62
-
63
- /**
64
- * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).
65
- *
66
- * @remarks
67
- * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the
68
- * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops
69
- * a cookie when those MATCH the one it set).
70
- *
71
- * @param headers - The response `Headers` to write into
72
- * @param name - The cookie name to clear
73
- * @param options - The {@link CookieOptions} that must match the original cookie
74
- *
75
- * @example
76
- * ```ts
77
- * const headers = new Headers()
78
- * clearCookie(headers, 'session')
79
- * ```
80
- */
81
- export declare function clearCookie(headers: Headers, name: string, options?: CookieOptions): void;
82
-
83
- /**
84
- * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to
85
- * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.
86
- *
87
- * @remarks
88
- * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a
89
- * per-`/128` rate limit is trivially bypassed by rotating host bits — the
90
- * real identity is the `/64` network. Delegates the IPv6 collapse to
91
- * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,
92
- * a malformed string) is kept unchanged.
93
- *
94
- * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})
95
- * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged
96
- *
97
- * @example
98
- * ```ts
99
- * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'
100
- * clientRateKey('192.0.2.1') // '192.0.2.1'
101
- * ```
102
- */
103
- export declare function clientRateKey(address: string): string;
104
-
105
- /**
106
- * The client's quality (q) for one content-coding from the parsed
107
- * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s
108
- * server-preference selection.
109
- *
110
- * @remarks
111
- * Prefers an EXACT named match (including an explicit `;q=0` rejection);
112
- * failing that, a bare `*` wildcard's q applies. A coding that is neither
113
- * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins
114
- * over a `*` (a specific rejection beats the wildcard), so it scores `0`.
115
- *
116
- * @param entries - The parsed {@link AcceptEntry} list
117
- * @param coding - The candidate coding to score
118
- * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)
119
- *
120
- * @example
121
- * ```ts
122
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5
123
- * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1
124
- * ```
125
- */
126
- export declare function codingQuality(entries: readonly AcceptEntry[], coding: string): number;
127
-
128
- /**
129
- * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.
130
- *
131
- * @remarks
132
- * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,
133
- * throwing a {@link ContentTooLargeError} (413) the instant the running total
134
- * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than
135
- * collecting an unbounded body. A bodyless request (`request.body === null`)
136
- * resolves an empty array. A non-positive `limit` means unbounded.
137
- *
138
- * @param request - The `Request` to drain
139
- * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded
140
- * @returns The full request body as one `Uint8Array`
141
- * @throws {ContentTooLargeError} When the body exceeds `limit`
142
- *
143
- * @example
144
- * ```ts
145
- * const bytes = await collectRequestBody(request, 1_048_576)
146
- * ```
147
- */
148
- export declare function collectRequestBody(request: Request, limit: number): Promise<Uint8Array<ArrayBuffer>>;
149
-
150
- /**
151
- * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`
152
- * handler into one request handler — the frozen middleware seam (§5.1).
153
- *
154
- * @remarks
155
- * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`
156
- * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes
157
- * `terminal`. Each middleware's `next` may be called with a substituted
158
- * `Request` (the downstream chain then sees that request instead of the
159
- * original), called with no argument (the original request continues
160
- * downstream), or NOT called at all (a short-circuit — the middleware's own
161
- * returned `Response` is sent, and everything downstream never runs). A
162
- * SECOND call to the same `next` within one middleware invocation REJECTS —
163
- * each link runs the chain at most once, so a middleware cannot fork the
164
- * request into two divergent downstream runs.
165
- *
166
- * @typeParam TState - The consumer's opaque per-request state type
167
- * @param middleware - The ordered chain, outermost first
168
- * @param terminal - The innermost handler the chain ultimately reaches
169
- * @returns A single `(request, context) => Promise<Response>` handler running the whole onion
170
- *
171
- * @example
172
- * ```ts
173
- * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {
174
- * const response = await next()
175
- * response.headers.set('X-Powered-By', 'orkestrel')
176
- * return response
177
- * }
178
- *
179
- * const handle = compose([withHeader], async () => new Response('ok'))
180
- * ```
181
- */
182
- export declare function compose<TState>(middleware: readonly MiddlewareHandler<TState>[], terminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>): (request: Request, context: MiddlewareContext<TState>) => Promise<Response>;
183
-
184
- /**
185
- * The set of bare `Content-Type`s `isCompressibleType` treats as
186
- * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /
187
- * `+xml`) rules that helper also applies.
188
- *
189
- * @remarks
190
- * The text-shaped application types worth compressing (JSON / JavaScript /
191
- * XML / SVG / WASM / a few document formats) — NOT already-compressed
192
- * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's
193
- * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads
194
- * but never mutates the shared default.
195
- */
196
- export declare const COMPRESSIBLE_TYPES: ReadonlySet<string>;
197
-
198
- /**
199
- * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.
200
- *
201
- * @remarks
202
- * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex
203
- * digest as a WEAK validator (`W/"<hash>"`) when `weak` is `true` — the
204
- * default, encoding-AGNOSTIC, so the tag survives a downstream content
205
- * re-encoding (gzip) and still matches on revalidation — or a STRONG one
206
- * (`"<hash>"`, byte-identity) when `weak` is `false`.
207
- *
208
- * @param body - The full (uncompressed) response body to hash
209
- * @param weak - `true` for a weak `W/"…"` validator (the default), `false` for a strong `"…"` one
210
- * @returns The `ETag` header value
211
- *
212
- * @example
213
- * ```ts
214
- * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/"…sha256-hex…"'
215
- * ```
216
- */
217
- export declare function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak?: boolean): Promise<string>;
218
-
219
- /**
220
- * The per-request connection facts the server face injects — the ONLY data
221
- * that genuinely exists solely on the socket, surfaced so middleware and a
222
- * consumer's `state` factory stay core-pure.
223
- *
224
- * @remarks
225
- * - `ip` — the socket peer address, for a spoof-proof rate-limit key. Never
226
- * derived from `X-Forwarded-For` (a client-controlled header) — a
227
- * deployment behind a trusted proxy derives its own client key explicitly.
228
- * - `encrypted` — whether the connection is TLS, for an auto-`Secure` cookie
229
- * decision ({@link CookieOptions.secure} left `undefined`).
230
- */
231
- export declare interface ConnectionInfo {
232
- readonly ip?: string;
233
- readonly encrypted: boolean;
234
- }
235
-
236
- /**
237
- * The {@link HTTPError} thrown when a request body exceeds the body
238
- * pipeline's size limit — a `413 Content Too Large`.
239
- *
240
- * @remarks
241
- * Thrown by `readBody` (and the middleware context's cached `body()`) when
242
- * the received bytes exceed the configured {@link
243
- * import('./types.js').BodyOptions.limit}, carrying the `limit` in its
244
- * `context`. The server's error boundary renders it as a 413.
245
- *
246
- * @example
247
- * ```ts
248
- * import { ContentTooLargeError, isHTTPError } from '@src/core'
249
- *
250
- * try {
251
- * await readBody(request, { limit: 1024 })
252
- * } catch (error) {
253
- * if (isHTTPError(error)) console.log(error.status) // 413
254
- * }
255
- * ```
256
- */
257
- export declare class ContentTooLargeError extends HTTPError {
258
- constructor(limit: number);
259
- }
260
-
261
- /**
262
- * The `Set-Cookie` attributes for `serializeCookie` (and any signed-cookie
263
- * transport built over it).
264
- *
265
- * @param path - The `Path` directive; defaults to `'/'`.
266
- * @param domain - The `Domain` directive; omitted ⇒ a host-only cookie.
267
- * @param maxAge - The `Max-Age` directive in SECONDS (the wire unit, not a
268
- * millisecond `ttl`); `0` expires the cookie immediately.
269
- * @param httpOnly - The `HttpOnly` directive; defaults to `true`.
270
- * @param secure - The `Secure` directive: `true` forces it, `false`
271
- * suppresses it, and omitted/`undefined` (the default) derives it from the
272
- * connection via {@link import('./helpers.js').resolveSecure} — `Secure` on
273
- * a TLS connection, off over plaintext HTTP ({@link
274
- * ConnectionInfo.encrypted}). A `sameSite: 'None'` cookie is ALWAYS
275
- * `Secure` regardless (the spec requires it).
276
- * @param sameSite - The `SameSite` directive; defaults to `'Lax'`.
277
- */
278
- export declare interface CookieOptions {
279
- readonly path?: string;
280
- readonly domain?: string;
281
- readonly maxAge?: number;
282
- readonly httpOnly?: boolean;
283
- readonly secure?: boolean;
284
- readonly sameSite?: 'Strict' | 'Lax' | 'None';
285
- }
286
-
287
- /**
288
- * Create a {@link NegotiatorInterface} — the reusable content-negotiation
289
- * machine over the weighted `Accept` family.
290
- *
291
- * @remarks
292
- * Prefer this over `new Negotiator()` at call sites that only need the
293
- * interface.
294
- *
295
- * @returns A {@link NegotiatorInterface}
296
- *
297
- * @example
298
- * ```ts
299
- * import { createNegotiator } from '@src/core'
300
- *
301
- * const negotiator = createNegotiator()
302
- * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
303
- * // 'text/html'
304
- * ```
305
- */
306
- export declare function createNegotiator(): NegotiatorInterface;
307
-
308
- /**
309
- * Decode a base64url string back into its bytes — the inverse of
310
- * {@link encodeBase64Url}.
311
- *
312
- * @remarks
313
- * Restores the standard base64 alphabet + padding before decoding with
314
- * `atob`. THROWS `DOMException` on a malformed input — callers on the
315
- * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).
316
- *
317
- * @param value - The base64url string to decode
318
- * @returns The decoded bytes
319
- * @throws {DOMException} When `value` is not valid base64url
320
- *
321
- * @example
322
- * ```ts
323
- * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'
324
- * ```
325
- */
326
- export declare function decodeBase64Url(value: string): Uint8Array<ArrayBuffer>;
327
-
328
- /**
329
- * Decode a cookie value with `decodeURIComponent`, falling back to the raw
330
- * text when the value is not valid percent-encoding.
331
- *
332
- * @param raw - The raw (trimmed) cookie value
333
- * @returns The URL-decoded value, or the raw value when decoding would throw
334
- *
335
- * @example
336
- * ```ts
337
- * decodeCookieValue('a%20b') // 'a b'
338
- * decodeCookieValue('%') // '%' — malformed escape stays literal
339
- * ```
340
- */
341
- export declare function decodeCookieValue(raw: string): string;
342
-
343
- /**
344
- * Decode + narrow a signed token's base64url JSON payload, honoring its
345
- * expiry — the shared decode step {@link verifyToken} applies after a
346
- * signature match.
347
- *
348
- * @remarks
349
- * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a
350
- * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.
351
- * TOTAL — any decode/shape/expiry failure yields `undefined`.
352
- *
353
- * @param encoded - The base64url-encoded payload segment (before the last `.`)
354
- * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`
355
- */
356
- export declare function decodeTokenPayload(encoded: string): string | undefined;
357
-
358
- /**
359
- * Transparently decompress an already-collected, `gzip`/`deflate`-encoded
360
- * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —
361
- * the zip-bomb defense.
362
- *
363
- * @remarks
364
- * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting
365
- * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed
366
- * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`
367
- * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces
368
- * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated
369
- * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}
370
- * (never conflated with the cap). A non-positive `cap` means uncapped.
371
- *
372
- * @param bytes - The compressed bytes to decompress
373
- * @param encoding - The {@link Encoding} the bytes are compressed with
374
- * @param cap - The maximum decompressed byte count; a non-positive value means uncapped
375
- * @returns The decompressed bytes
376
- * @throws {ContentTooLargeError} When decompressed output would exceed `cap`
377
- * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)
378
- */
379
- export declare function decompressRequestBody(bytes: Uint8Array<ArrayBuffer>, encoding: Exclude<Encoding, 'identity'>, cap: number): Promise<Uint8Array<ArrayBuffer>>;
380
-
381
- /** Default maximum request body size (bytes) `readBody` accepts before a 413. */
382
- export declare const DEFAULT_BODY_LIMIT = 1048576;
383
-
384
- /**
385
- * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap
386
- * the body pipeline's byte-counting `TransformStream` enforces when
387
- * transparently decompressing a `Content-Encoding` request body.
388
- *
389
- * @remarks
390
- * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)
391
- * can inflate by many orders of magnitude — a classic decompression bomb.
392
- * Capping the decompressed byte count makes the pipe ABORT the moment the
393
- * output would exceed this, BEFORE the full bomb is materialized, so the
394
- * inflation can never exhaust memory. Defaults to `16 MiB` — a generous
395
- * ceiling for a legitimate compressed JSON / form body, far below an OOM. A
396
- * consumer raises it via {@link import('./types.js').BodyOptions}
397
- * `decompression` for a workload that genuinely ships larger decompressed
398
- * bodies.
399
- */
400
- export declare const DEFAULT_DECOMPRESSED_LIMIT = 16777216;
401
-
402
- /** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */
403
- export declare const DEFAULT_DRAIN_MS = 10000;
404
-
405
- /**
406
- * The default {@link Encoding} content-codings the substrate offers, in
407
- * PREFERENCE order — `gzip` / `deflate`.
408
- *
409
- * @remarks
410
- * `identity` (no compression) is always implicitly acceptable and is NOT
411
- * listed here — it is the fall-through when a client accepts none of these.
412
- * Brotli is omitted per the core's `CompressionStream`-only decision (see
413
- * {@link Encoding}). Frozen so a consumer can read but never mutate the
414
- * shared default.
415
- */
416
- export declare const DEFAULT_ENCODINGS: readonly Encoding[];
417
-
418
- /**
419
- * Base64url-encode a byte sequence — the payload encoding {@link signToken} /
420
- * {@link verifyToken} use, and the signature encoding for the HMAC.
421
- *
422
- * @param bytes - The bytes to encode
423
- * @returns The base64url string (no padding)
424
- *
425
- * @example
426
- * ```ts
427
- * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'
428
- * ```
429
- */
430
- export declare function encodeBase64Url(bytes: Uint8Array): string;
431
-
432
- /**
433
- * A content-coding the substrate compresses / decompresses with — the
434
- * `Content-Encoding` / `Accept-Encoding` token vocabulary it understands.
435
- *
436
- * @remarks
437
- * `gzip` / `deflate` map to `CompressionStream` / `DecompressionStream`
438
- * (web-standard, no external codec); `identity` is the no-op "uncompressed"
439
- * coding. Brotli (`br`) has no `CompressionStream` implementation yet, so it
440
- * is deliberately OMITTED here — Brotli parity is the future middleware
441
- * package's node-entry decision (§3 of the proposal), not this core's. A
442
- * constrained set of external-spec literals, so it stays a union, not a
443
- * behavioral toggle (AGENTS §4.4).
444
- */
445
- export declare type Encoding = 'gzip' | 'deflate' | 'identity';
446
-
447
- /**
448
- * A map of media type → handler for {@link NegotiatorInterface.format} — the
449
- * content-negotiation dispatch table.
450
- *
451
- * @typeParam TState - The consumer's opaque per-request state type
452
- *
453
- * @remarks
454
- * Each key is a media type the route can PRODUCE (`application/json`,
455
- * `text/html`, …) and each value the responder that returns that
456
- * representation as a `Response`. `format` negotiates the client's preferred
457
- * key from the request `Accept` header and invokes the matching handler, or
458
- * answers `406 Not Acceptable` when none of the offered types is acceptable.
459
- * The keys are the `available` set negotiation chooses from, so their order
460
- * is the server's tie-break preference (a client accepting the any-media-
461
- * range gets the first key).
462
- */
463
- export declare type FormatHandlerMap<TState> = Readonly<Record<string, (request: Request, context: MiddlewareContext<TState>) => Response | Promise<Response>>>;
464
-
465
- /**
466
- * An error a handler (or middleware) throws to produce an HTTP response of a
467
- * specific status.
468
- *
469
- * @remarks
470
- * Carries the HTTP `status` to send and an optional `context` record (the
471
- * offending field / value). The server's built-in error boundary catches it
472
- * and renders a response of `status` with the error's `message` as the body
473
- * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's
474
- * deliberate signal), unlike a generic throw whose message is hidden unless
475
- * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for
476
- * specific statuses, or throw it directly. Narrow a caught value with
477
- * {@link isHTTPError}.
478
- *
479
- * @example
480
- * ```ts
481
- * import { HTTPError } from '@src/core'
482
- *
483
- * const handler = async (request: Request): Promise<Response> => {
484
- * const user = await find(new URL(request.url).searchParams.get('id'))
485
- * if (user === undefined) throw new HTTPError(404, 'user not found')
486
- * return Response.json(user)
487
- * }
488
- * ```
489
- */
490
- export declare class HTTPError extends Error {
491
- readonly status: number;
492
- readonly context?: Readonly<Record<string, unknown>>;
493
- constructor(status: number, message: string, context?: Readonly<Record<string, unknown>>);
494
- }
495
-
496
- /**
497
- * Compute the `/64` network of a full IPv6 address, or `undefined` when the
498
- * input is not a plain IPv6 address to collapse.
499
- *
500
- * @remarks
501
- * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4
502
- * is the identity) or any string that does not expand to exactly eight
503
- * hextets. Expands a single `::` into the missing zero hextets, takes the
504
- * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading
505
- * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped
506
- * first. Total — a malformed address returns `undefined`.
507
- *
508
- * @param address - The candidate IPv6 address
509
- * @returns The `/64` network string, or `undefined` when not a plain IPv6 address
510
- *
511
- * @example
512
- * ```ts
513
- * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'
514
- * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed
515
- * ```
516
- */
517
- export declare function ipv6Network(address: string): string | undefined;
518
-
519
- /**
520
- * Whether a `Content-Type` is worth compressing.
521
- *
522
- * @remarks
523
- * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`
524
- * type, a `+json`/`+xml` structured suffix, or one of the explicit
525
- * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed
526
- * binary (`image/png`, `application/zip`) is NOT compressible. An
527
- * absent/empty type is not compressible. TOTAL.
528
- *
529
- * @param type - The response `Content-Type` header value (with or without parameters)
530
- * @returns `true` when the type is text-shaped and worth compressing
531
- *
532
- * @example
533
- * ```ts
534
- * isCompressibleType('application/json; charset=utf-8') // true
535
- * isCompressibleType('image/png') // false
536
- * ```
537
- */
538
- export declare function isCompressibleType(type: string): boolean;
539
-
540
- /**
541
- * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE
542
- * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two
543
- * attributes with before emitting them.
544
- *
545
- * @remarks
546
- * Rejects a value carrying a `;` (splits attributes), a `,` (can split a
547
- * folded header), ASCII/Unicode whitespace, or a C0/DEL control char
548
- * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`
549
- * directive. Total — never throws (a bad value returns `false`).
550
- *
551
- * @param value - The candidate attribute value (a `Domain` or `Path`)
552
- * @returns `true` when `value` carries no separator / whitespace / control char
553
- *
554
- * @example
555
- * ```ts
556
- * isCookieAttribute('/app') // true
557
- * isCookieAttribute('/a\r\nSet-Cookie: x=y') // false
558
- * ```
559
- */
560
- export declare function isCookieAttribute(value: string): boolean;
561
-
562
- /**
563
- * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of
564
- * cookie-token chars with NO surrounding (or interior) whitespace.
565
- *
566
- * @remarks
567
- * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$` —
568
- * which excludes every whitespace char (ASCII and Unicode) plus controls,
569
- * separators, and `=`. The {@link parseCookies} hardening that stops a
570
- * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.
571
- *
572
- * @param value - The candidate cookie name
573
- * @returns `true` when `value` is a valid, whitespace-free cookie token
574
- *
575
- * @example
576
- * ```ts
577
- * isCookieName('__Host-session') // true
578
- * isCookieName(' __Host-session') // false — whitespace-padded
579
- * ```
580
- */
581
- export declare function isCookieName(value: string): boolean;
582
-
583
- /**
584
- * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,
585
- * or `prototype` — the three keys that, assigned onto a normal object, can
586
- * reach and mutate `Object.prototype`.
587
- *
588
- * @param key - The candidate object key
589
- * @returns `true` when `key` is one of the three prototype-pollution keys
590
- *
591
- * @example
592
- * ```ts
593
- * isDangerousKey('__proto__') // true
594
- * isDangerousKey('name') // false
595
- * ```
596
- */
597
- export declare function isDangerousKey(key: string): boolean;
598
-
599
- /**
600
- * Narrow an unknown caught value to an {@link HTTPError} (including its
601
- * subclasses, e.g. {@link ContentTooLargeError}).
602
- *
603
- * @param value - The value to test (typically a `catch` binding)
604
- * @returns `true` when `value` is an {@link HTTPError}
605
- *
606
- * @example
607
- * ```ts
608
- * import { isHTTPError } from '@src/core'
609
- *
610
- * try {
611
- * await handle(request)
612
- * } catch (error) {
613
- * if (isHTTPError(error)) console.log(error.status, error.message)
614
- * }
615
- * ```
616
- */
617
- export declare function isHTTPError(value: unknown): value is HTTPError;
618
-
619
- /**
620
- * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response
621
- * header + `context.state`.
622
- *
623
- * @remarks
624
- * A request id is echoed RAW into a response header and log lines, so an
625
- * untrusted one is a header-injection + log-injection + DoS vector. This
626
- * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}
627
- * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).
628
- * TOTAL — never throws.
629
- *
630
- * @param value - The candidate incoming request id
631
- * @returns `true` when `value` is a safe, bounded, charset-clean correlation id
632
- *
633
- * @example
634
- * ```ts
635
- * isValidRequestId('req_abc-123') // true
636
- * isValidRequestId('bad\r\nheader') // false
637
- * ```
638
- */
639
- export declare function isValidRequestId(value: string): boolean;
640
-
641
- /**
642
- * The client's quality for one `candidate` language from the parsed
643
- * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.
644
- *
645
- * @remarks
646
- * Prefers an exact match, then a primary-tag prefix match (`en` accepts
647
- * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry
648
- * is an explicit rejection).
649
- *
650
- * @param entries - The parsed {@link AcceptEntry} list
651
- * @param candidate - The candidate language tag to score (e.g. `'en-US'`)
652
- * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)
653
- *
654
- * @example
655
- * ```ts
656
- * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1
657
- * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix
658
- * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard
659
- * ```
660
- */
661
- export declare function languageQuality(entries: readonly AcceptEntry[], candidate: string): number;
662
-
663
- /**
664
- * Whether a request's `If-None-Match` header matches a resource's current
665
- * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.
666
- *
667
- * @remarks
668
- * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY
669
- * listed tag matches), or the `*` wildcard (matches ANY current
670
- * representation — only a list of exactly `*` is the wildcard). Comparison is
671
- * WEAK: `W/"abc"` and `"abc"` are equal (both sides' weak prefix is stripped
672
- * via {@link unwrapETag} before comparing the opaque body). TOTAL — a
673
- * malformed/empty header matches nothing, never throws.
674
- *
675
- * @param header - The raw `If-None-Match` header value
676
- * @param etag - The resource's current `ETag`
677
- * @returns `true` when the conditional matches (the caller answers `304`)
678
- *
679
- * @example
680
- * ```ts
681
- * matchesETag('"abc", W/"def"', 'W/"abc"') // true — weak comparison
682
- * matchesETag('*', 'W/"anything"') // true — wildcard
683
- * ```
684
- */
685
- export declare function matchesETag(header: string, etag: string): boolean;
686
-
687
- /**
688
- * Rank + quality of one `candidate` media type against the parsed `Accept`
689
- * entries — the generic media-type primitive the `Negotiator`'s `negotiate`
690
- * uses to score each `available` candidate.
691
- *
692
- * @remarks
693
- * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the
694
- * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact
695
- * `;q=0` entry explicitly rejects the candidate outright (returns
696
- * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own
697
- * (less specific) coverage, so a later more-specific match can still allow
698
- * it. Among multiple matching entries, the lowest `rank` wins, and among a
699
- * rank tie the highest `q` wins.
700
- *
701
- * @param entries - The parsed {@link AcceptEntry} list
702
- * @param candidate - The candidate media type to score (e.g. `'text/html'`)
703
- * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches
704
- *
705
- * @example
706
- * ```ts
707
- * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')
708
- * // { q: 1, rank: 0 }
709
- * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }
710
- * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined
711
- * ```
712
- */
713
- export declare function matchMediaType(entries: readonly AcceptEntry[], candidate: string): {
714
- readonly q: number;
715
- readonly rank: number;
716
- } | undefined;
717
-
718
- /**
719
- * Merge a `Vary` value into an existing `Vary` header without duplication.
720
- *
721
- * @remarks
722
- * Splits `existing` on `,`, trims each member, and appends `value` only when
723
- * no existing member already matches it case-insensitively (`Vary` header
724
- * names are case-insensitive). Preserves the existing members' order and
725
- * appends the new one last.
726
- *
727
- * @param existing - The current `Vary` header value, if any
728
- * @param value - The header name to ensure is listed
729
- * @returns The merged `Vary` value
730
- *
731
- * @example
732
- * ```ts
733
- * mergeVary(undefined, 'Origin') // 'Origin'
734
- * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)
735
- * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'
736
- * ```
737
- */
738
- export declare function mergeVary(existing: string | undefined, value: string): string;
739
-
740
- /**
741
- * The composition context — plain data, one per request, shared by every
742
- * middleware AND (as `state`) by the route handlers behind the dispatcher.
743
- *
744
- * @typeParam TState - The consumer's opaque per-request state type
745
- *
746
- * @remarks
747
- * - `url` — the parsed request {@link URL} (mirrors the router's own parse, so
748
- * a middleware never re-parses it).
749
- * - `method` — the raw request verb; the dispatcher (not this seam) narrows it
750
- * to a known {@link import('@orkestrel/router').Method}.
751
- * - `state` — THE shared bag threaded from the adapter's `state` factory,
752
- * through every middleware, into `dispatcher.handle`'s `state` — the same
753
- * object a route handler reads as `context.state`.
754
- * - `body()` — lazily collect the request body (byte-limited, transparently
755
- * decompressed, prototype-scrubbed for JSON), cached so repeated calls (a
756
- * body-parsing middleware, then the handler) read the underlying stream
757
- * exactly once.
758
- *
759
- * @example
760
- * ```ts
761
- * const middleware: MiddlewareHandler<{ readonly userId?: string }> = async (request, context, next) => {
762
- * const body = await context.body()
763
- * return next(request)
764
- * }
765
- * ```
766
- */
767
- export declare interface MiddlewareContext<TState> {
768
- readonly url: URL;
769
- readonly method: string;
770
- readonly state: TState;
771
- body(): Promise<unknown>;
772
- }
773
-
774
- /**
775
- * One link in the middleware onion — runs around the rest of the chain.
776
- *
777
- * @typeParam TState - The consumer's opaque per-request state type
778
- *
779
- * @remarks
780
- * Transform the request (call `next(newRequest)`), transform the response
781
- * (`await next()` then modify the result), short-circuit (return a `Response`
782
- * without calling `next`), or thread data via `context.state` — no mutable
783
- * framework object anywhere, only fetch-standard `Request`/`Response`.
784
- *
785
- * @example
786
- * ```ts
787
- * const withRequestId: MiddlewareHandler<{ readonly requestId: string }> = async (request, context, next) => {
788
- * const response = await next()
789
- * response.headers.set('X-Request-ID', context.state.requestId)
790
- * return response
791
- * }
792
- * ```
793
- */
794
- export declare type MiddlewareHandler<TState> = (request: Request, context: MiddlewareContext<TState>, next: NextFunction) => Response | Promise<Response>;
795
-
796
- /**
797
- * Select the best content-coding for an `Accept-Encoding` header from the
798
- * codings the server offers.
799
- *
800
- * @remarks
801
- * Parses the header ({@link parseAcceptHeader}) and scores each `available`
802
- * coding in the SERVER's preference order ({@link codingQuality}), keeping
803
- * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a
804
- * client-side tie). Returns `undefined` when the client accepts none of
805
- * `available` (identity — no compression). TOTAL on hostile input.
806
- *
807
- * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)
808
- * @param header - The raw `Accept-Encoding` header value
809
- * @param available - The codings the server offers, in preference (tie-break) order
810
- * @returns The negotiated coding, or `undefined` when none of `available` is acceptable
811
- *
812
- * @example
813
- * ```ts
814
- * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'
815
- * ```
816
- */
817
- export declare function negotiateEncoding<T extends string>(header: string, available: readonly T[]): T | undefined;
818
-
819
- /**
820
- * The content-negotiation machine over the weighted `Accept` family — a
821
- * reusable, cross-middleware ENTITY (not a middleware). Implements exactly
822
- * {@link NegotiatorInterface}.
823
- *
824
- * @remarks
825
- * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /
826
- * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its
827
- * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the
828
- * rest of the substrate uses — one parser, never two. `format` reads the
829
- * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes
830
- * the winner — or answers `406 Not Acceptable`.
831
- *
832
- * @example
833
- * ```ts
834
- * const negotiator = new Negotiator()
835
- * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])
836
- * // 'text/html'
837
- * ```
838
- */
839
- export declare class Negotiator implements NegotiatorInterface {
840
- negotiate(header: string, available: readonly string[]): string | undefined;
841
- encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
842
- language(header: string, available: readonly string[]): string | undefined;
843
- /**
844
- * @remarks
845
- * Errors thrown by the negotiated handler propagate UNMODIFIED — the
846
- * server boundary classifies them, never this negotiator.
847
- */
848
- format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
849
- }
850
-
851
- /**
852
- * Content negotiation over the weighted `Accept` family — a reusable,
853
- * cross-middleware machine (not itself a middleware).
854
- *
855
- * @remarks
856
- * Parses a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
857
- * (q-values honored, `*` wildcards honored, a `;q=0` rejection respected) and
858
- * picks the client's most-preferred value the server also offers. `negotiate`
859
- * is the generic primitive (media types); `encoding` / `language` are its
860
- * sibling axes. `format` is the dispatcher — it reads the request `Accept`,
861
- * negotiates against a {@link FormatHandlerMap}'s keys, and invokes the
862
- * winning handler, resolving `406 Not Acceptable` when none is acceptable.
863
- *
864
- * @example
865
- * ```ts
866
- * const response = await negotiator.format(request, context, {
867
- * 'application/json': (request, context) => Response.json({ ok: true }),
868
- * 'text/html': (request, context) => new Response('<p>ok</p>', { headers: { 'Content-Type': 'text/html' } }),
869
- * })
870
- * ```
871
- */
872
- export declare interface NegotiatorInterface {
873
- /**
874
- * Pick the best `available` value for a weighted `Accept`-style `header` —
875
- * the generic media-type primitive (`encoding` / `language` build on it).
876
- *
877
- * @param header - The raw weighted header value (e.g. `text/html, application/json;q=0.9`)
878
- * @param available - The values the server can produce, in preference (tie-break) order
879
- * @returns The best acceptable value, or `undefined` when none is
880
- */
881
- negotiate(header: string, available: readonly string[]): string | undefined;
882
- /**
883
- * Pick the best `available` content-coding for an `Accept-Encoding` header
884
- * — `negotiate` scoped to codings (a bare `*` wildcard ⇒ the first `available`).
885
- *
886
- * @param header - The raw `Accept-Encoding` header value (e.g. `gzip;q=1.0, deflate;q=0.8`)
887
- * @param available - The codings the server offers, in preference order
888
- * @returns The best acceptable coding, or `undefined` when none is
889
- */
890
- encoding(header: string, available: readonly Encoding[]): Encoding | undefined;
891
- /**
892
- * Pick the best `available` language for an `Accept-Language` header —
893
- * `negotiate` with a language-prefix match (`en` accepts `en-US`) and a
894
- * bare `*` wildcard.
895
- *
896
- * @param header - The raw `Accept-Language` header value (e.g. `en-US, en;q=0.8, fr;q=0.5`)
897
- * @param available - The languages the server offers, in preference order
898
- * @returns The best acceptable language, or `undefined` when none is
899
- */
900
- language(header: string, available: readonly string[]): string | undefined;
901
- /**
902
- * Dispatch to the handler whose media type the client most prefers — read
903
- * the request `Accept`, negotiate against `handlers`' keys, and invoke the
904
- * winner; `406` when none is acceptable.
905
- *
906
- * @typeParam TState - The consumer's opaque per-request state type
907
- * @param request - The in-flight `Request`
908
- * @param context - The request's {@link MiddlewareContext}
909
- * @param handlers - The media type → responder {@link FormatHandlerMap} the route offers
910
- * @returns The winning handler's `Response`, or a `406 Not Acceptable` `Response`
911
- */
912
- format<TState>(request: Request, context: MiddlewareContext<TState>, handlers: FormatHandlerMap<TState>): Promise<Response>;
913
- }
914
-
915
- /**
916
- * The downstream continuation a {@link MiddlewareHandler} invokes to run the
917
- * rest of the onion.
918
- *
919
- * @remarks
920
- * Call it (optionally with a substituted `Request`) to run the downstream
921
- * chain and receive its `Response`; omit the call entirely to short-circuit
922
- * with a `Response` built by this middleware instead. A SECOND call rejects
923
- * (the double-`next` guard) — each middleware runs the chain at most once.
924
- *
925
- * @param request - An optional replacement `Request` to hand downstream
926
- * (omitted ⇒ the original request continues)
927
- * @returns The downstream chain's resolved `Response`
928
- */
929
- export declare type NextFunction = (request?: Request) => Promise<Response>;
930
-
931
- /**
932
- * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —
933
- * backs both {@link signToken} and {@link verifyToken}.
934
- *
935
- * @remarks
936
- * A single string becomes a one-element list; a rotation list is copied. Any
937
- * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that
938
- * emptiness test; each kept secret is stored VERBATIM). The first kept
939
- * element is the signing secret; all kept are accepted on verify.
940
- *
941
- * @param secret - The {@link TokenSecret} (a single string, or a rotation list)
942
- * @returns The kept (non-blank) secrets, in order — empty when none is usable
943
- *
944
- * @example
945
- * ```ts
946
- * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']
947
- * ```
948
- */
949
- export declare function normalizeSecret(secret: TokenSecret): readonly string[];
950
-
951
- /**
952
- * Open a generic Server-Sent-Events stream — a fetch-standard `Response`
953
- * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.
954
- *
955
- * @remarks
956
- * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
957
- * merged under any `options.headers` (a seam-owned key is never overridden),
958
- * at `options.status` (default `200`). The returned {@link StreamInterface}'s
959
- * `write` serializes one message ({@link serializeEvent}) and enqueues it;
960
- * `comment` writes a `: text` keep-alive line a conforming parser ignores;
961
- * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
962
- * by `end()`, or the consumer cancelled the stream), so a late write never
963
- * throws.
964
- *
965
- * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
966
- * @returns The {@link StreamInterface} handle
967
- *
968
- * @example
969
- * ```ts
970
- * const stream = openStream()
971
- * stream.write({ event: 'token', data: 'hello' })
972
- * stream.end()
973
- * // return stream.response from the route handler
974
- * ```
975
- */
976
- export declare function openStream(options?: StreamOptions): StreamInterface;
977
-
978
- /**
979
- * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header
980
- * into its q-sorted entries.
981
- *
982
- * @remarks
983
- * Splits on `,`; for each part takes the token before the first `;`
984
- * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the
985
- * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls
986
- * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must
987
- * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving
988
- * the header's own order within a tie — a single pass with no backtracking,
989
- * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an
990
- * empty/malformed header yields `[]`/best-effort entries, never throws.
991
- *
992
- * @param header - The raw weighted header value
993
- * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending
994
- *
995
- * @example
996
- * ```ts
997
- * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')
998
- * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]
999
- * ```
1000
- */
1001
- export declare function parseAcceptHeader(header: string): readonly AcceptEntry[];
1002
-
1003
- /**
1004
- * Parse a raw `Cookie:` request header into a `name → value` lookup.
1005
- *
1006
- * @remarks
1007
- * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine
1008
- * cookie-pair separator never precedes it), while every later segment has its
1009
- * inter-pair separator (ASCII space/tab) stripped before parsing — so a
1010
- * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by
1011
- * {@link isCookieName} rather than silently reconciling into a
1012
- * prefix-protected `__Host-` name. A pair without `=`, or with an invalid
1013
- * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/
1014
- * malformed header yields an empty record, never throws (AGENTS §14).
1015
- *
1016
- * @param header - The raw `Cookie` header value (possibly `undefined`)
1017
- * @returns A record of every parsed cookie, `name → decoded value`
1018
- *
1019
- * @example
1020
- * ```ts
1021
- * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }
1022
- * ```
1023
- */
1024
- export declare function parseCookies(header: string | undefined): Record<string, string>;
1025
-
1026
- /**
1027
- * Parse an HTTP `Range` request header against a known resource `size` —
1028
- * TOTAL, returning a {@link RangeSpec} or `undefined`.
1029
- *
1030
- * @remarks
1031
- * Handles the three single-range `bytes=` forms — closed (`start-end`), open
1032
- * (`start-`), and suffix (`-suffixLength`) — clamping the window to
1033
- * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns
1034
- * `{ satisfiable: true, start, end }` for an overlapping range,
1035
- * `{ satisfiable: false }` for a range wholly past the resource, and
1036
- * `undefined` for the "serve the whole resource" case: an ABSENT header, a
1037
- * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not
1038
- * supported), or any malformed/non-finite bound. NEVER throws on a hostile
1039
- * header.
1040
- *
1041
- * @param header - The raw `Range` header value
1042
- * @param size - The resource's total byte length
1043
- * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource
1044
- *
1045
- * @example
1046
- * ```ts
1047
- * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }
1048
- * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused
1049
- * ```
1050
- */
1051
- export declare function parseRange(header: string | undefined, size: number): RangeSpec | undefined;
1052
-
1053
- /**
1054
- * The parsed outcome of an HTTP `Range` request header.
1055
- *
1056
- * @remarks
1057
- * A `Range: bytes=start-end` against a known resource `size` resolves to ONE
1058
- * of two shapes, discriminated by `satisfiable` (the axis is whether the
1059
- * requested span overlaps the resource):
1060
- *
1061
- * - **`satisfiable: true`** — a concrete, clamped byte window `[start, end]`
1062
- * (INCLUSIVE, the HTTP wire convention), normalized from the header's
1063
- * open / suffix / closed forms against `size`.
1064
- * - **`satisfiable: false`** — the range lies wholly outside the resource.
1065
- *
1066
- * `parseRange` returns `undefined` for an ABSENT / unparseable / multi-range
1067
- * / non-`bytes` header — the "no range, serve the whole resource" case — so
1068
- * the three outcomes (full / partial / unsatisfiable) are distinguished
1069
- * without a separate flag. It is TOTAL — a hostile header never throws.
1070
- */
1071
- export declare type RangeSpec = {
1072
- readonly satisfiable: true;
1073
- readonly start: number;
1074
- readonly end: number;
1075
- } | {
1076
- readonly satisfiable: false;
1077
- };
1078
-
1079
- /**
1080
- * Collect + decode a `Request` body — the shared body-collection pipeline
1081
- * surfaced to middleware and handlers as the middleware context's cached
1082
- * `body()`.
1083
- *
1084
- * @remarks
1085
- * Collects the wire body capped at `options.limit` bytes ({@link
1086
- * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),
1087
- * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body
1088
- * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at
1089
- * `options.decompression`, default {@link
1090
- * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by
1091
- * content type: `application/json` is parsed via `@orkestrel/contract`'s
1092
- * `parseJSON` and scrubbed of prototype-pollution keys ({@link
1093
- * scrubPrototype}); any other type decodes as UTF-8 text; an empty body
1094
- * decodes to `undefined`.
1095
- *
1096
- * @param request - The `Request` to read the body from
1097
- * @param options - The {@link BodyOptions} `limit` + `decompression` caps
1098
- * @returns The parsed JSON value, the raw text, or `undefined` for an empty body
1099
- * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap
1100
- * @throws {HTTPError} When the compressed body is corrupt (400)
1101
- *
1102
- * @example
1103
- * ```ts
1104
- * const body = await readBody(request, { limit: 1_048_576 })
1105
- * ```
1106
- */
1107
- export declare function readBody(request: Request, options?: BodyOptions): Promise<unknown>;
1108
-
1109
- /**
1110
- * Read + verify a SIGNED cookie off a request — TOTAL, returning the
1111
- * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).
1112
- *
1113
- * @remarks
1114
- * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,
1115
- * and verifies it with {@link verifyToken} against `secret` (a rotation list
1116
- * accepts a cookie signed by any of its secrets). ANY failure — an absent
1117
- * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.
1118
- *
1119
- * @param request - The `Request` to read the `Cookie` header from
1120
- * @param name - The cookie name to read
1121
- * @param secret - The {@link TokenSecret} (or rotation list) to verify against
1122
- * @returns The embedded value when the cookie is present + valid, else `undefined`
1123
- *
1124
- * @example
1125
- * ```ts
1126
- * const value = await readSignedCookie(request, 'session', 'secret')
1127
- * ```
1128
- */
1129
- export declare function readSignedCookie(request: Request, name: string, secret: TokenSecret): Promise<string | undefined>;
1130
-
1131
- /**
1132
- * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`
1133
- * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized
1134
- * / control-char-bearing incoming id is REJECTED (a fresh id is minted
1135
- * instead) rather than ever riding into a response header or `context.state`
1136
- * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the
1137
- * shared default.
1138
- */
1139
- export declare const REQUEST_ID_PATTERN: Readonly<RegExp>;
1140
-
1141
- /**
1142
- * Narrow a raw `Content-Encoding` header value to a decompressible
1143
- * {@link Encoding} — the boundary guard {@link readBody} uses to decide
1144
- * whether a request body needs transparent decompression.
1145
- *
1146
- * @remarks
1147
- * Lower-cases + trims and returns the matching {@link Encoding} ONLY for
1148
- * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of
1149
- * the proposal). An absent header, `identity`, an unknown value, or a
1150
- * comma-joined multi-coding all yield `undefined` (the body is read as-is).
1151
- * TOTAL — never asserts the loose `string | null` header.
1152
- *
1153
- * @param header - The raw `Content-Encoding` header value
1154
- * @returns The single decompressible {@link Encoding}, or `undefined` when none applies
1155
- *
1156
- * @example
1157
- * ```ts
1158
- * requestEncoding('gzip') // 'gzip'
1159
- * requestEncoding('br') // undefined — unsupported by DecompressionStream
1160
- * ```
1161
- */
1162
- export declare function requestEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined;
1163
-
1164
- /**
1165
- * Resolve the `Access-Control-Allow-Origin` value for a request.
1166
- *
1167
- * @remarks
1168
- * `'*'` and a single origin string pass straight through. An allow-list
1169
- * echoes the request's `Origin` only when it is present in the list, else
1170
- * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent
1171
- * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is
1172
- * NEVER reflected even if `'null'` were listed, closing the hostile-context
1173
- * cross-origin-access hole.
1174
- *
1175
- * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list
1176
- * @param requestOrigin - The request's `Origin` header value, if present
1177
- * @returns The allow-origin value to send, or `undefined` to set no header
1178
- *
1179
- * @example
1180
- * ```ts
1181
- * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'
1182
- * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected
1183
- * ```
1184
- */
1185
- export declare function resolveOrigin(origin: string | readonly string[], requestOrigin: string | undefined): string | undefined;
1186
-
1187
- /**
1188
- * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}
1189
- * `secure` setting and whether the request arrived over TLS.
1190
- *
1191
- * @remarks
1192
- * `true` / `false` are explicit overrides. `undefined` (the secure default —
1193
- * the option omitted) resolves to `encrypted` — `Secure` on a TLS
1194
- * connection, off over plaintext HTTP — so a production HTTPS deployment
1195
- * gets `Secure` automatically while local-dev HTTP still works.
1196
- *
1197
- * @param secure - The {@link CookieOptions} `secure` setting
1198
- * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})
1199
- * @returns The concrete `Secure` flag to emit
1200
- *
1201
- * @example
1202
- * ```ts
1203
- * resolveSecure(undefined, true) // true
1204
- * resolveSecure(undefined, false) // false
1205
- * resolveSecure(false, true) // false — explicit override wins
1206
- * ```
1207
- */
1208
- export declare function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean;
1209
-
1210
- /**
1211
- * Resolve one opt-out, value-bearing security header.
1212
- *
1213
- * @remarks
1214
- * The shared "a `string` value, or `false` to omit, or a default when unset"
1215
- * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):
1216
- * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that
1217
- * override, `undefined` (unset) ⇒ `fallback` (the secure default).
1218
- *
1219
- * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default
1220
- * @param fallback - The secure-default value used when `value` is unset
1221
- * @returns The header value to set, or `undefined` to omit the header
1222
- *
1223
- * @example
1224
- * ```ts
1225
- * resolveSecurityHeader(undefined, 'DENY') // 'DENY'
1226
- * resolveSecurityHeader(false, 'DENY') // undefined — omitted
1227
- * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override
1228
- * ```
1229
- */
1230
- export declare function resolveSecurityHeader(value: string | false | undefined, fallback: string): string | undefined;
1231
-
1232
- /**
1233
- * Recursively STRIP the prototype-pollution keys from a parsed value IN
1234
- * PLACE.
1235
- *
1236
- * @remarks
1237
- * `JSON.parse('{"__proto__":{…}}')` is benign on its own — it produces an OWN,
1238
- * enumerable `__proto__` DATA property — but that own key becomes a
1239
- * pollution gadget the moment a downstream deep-merge copies it onto a live
1240
- * object. This walks the value and `delete`s any own {@link isDangerousKey}
1241
- * key at every depth, recursing into nested objects + array elements.
1242
- * Primitives/`null` pass through untouched. Total — never throws. Mutates the
1243
- * freshly-parsed value (which nothing else holds yet).
1244
- *
1245
- * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)
1246
- * @returns The same `value`, with every dangerous key removed at every depth
1247
- *
1248
- * @example
1249
- * ```ts
1250
- * scrubPrototype(JSON.parse('{"__proto__":{"polluted":true},"name":"ok"}'))
1251
- * // { name: 'ok' } — the __proto__ key is gone
1252
- * ```
1253
- */
1254
- export declare function scrubPrototype(value: unknown): unknown;
1255
-
1256
- /**
1257
- * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.
1258
- *
1259
- * @remarks
1260
- * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and
1261
- * appends the present {@link CookieOptions} attributes in canonical order:
1262
- * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`
1263
- * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated
1264
- * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an
1265
- * injection attempt (a programmer misconfiguration, AGENTS §12 — never a
1266
- * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of
1267
- * the `secure` option (the spec requires it); an un-resolved `undefined`
1268
- * `secure` here falls to OFF — request-aware callers resolve it first via
1269
- * {@link resolveSecure}.
1270
- *
1271
- * @param name - The cookie name
1272
- * @param value - The cookie value (URL-encoded into the output)
1273
- * @param options - The {@link CookieOptions} attributes; see its fields for defaults
1274
- * @returns The `Set-Cookie` header value
1275
- * @throws {HTTPError} When `domain` or `path` carries an injection char
1276
- *
1277
- * @example
1278
- * ```ts
1279
- * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'
1280
- * ```
1281
- */
1282
- export declare function serializeCookie(name: string, value: string, options?: CookieOptions): string;
1283
-
1284
- /**
1285
- * Serialize one {@link SSEMessage} to the SSE wire.
1286
- *
1287
- * @remarks
1288
- * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE
1289
- * `data:` line per CRLF-aware-split (`\r\n` / `\r` / `\n`) segment of `data`
1290
- * (so a consuming parser's multi-`data` concat reproduces the original
1291
- * `data` exactly, and no raw `\r` or `\n` can ever ride onto the wire inside
1292
- * a `data:` line), then the terminating blank line.
1293
- *
1294
- * @param message - The event to serialize
1295
- * @returns The SSE wire text for the event (terminated by a blank line)
1296
- *
1297
- * @example
1298
- * ```ts
1299
- * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\ndata: hello\n\n'
1300
- * serializeEvent({ data: 'multi\nline' }) // 'data: multi\ndata: line\n\n'
1301
- * ```
1302
- */
1303
- export declare function serializeEvent(message: SSEMessage): string;
1304
-
1305
- /**
1306
- * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.
1307
- *
1308
- * @remarks
1309
- * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the
1310
- * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so
1311
- * the expiry is HMAC-COVERED — a client cannot extend it without invalidating
1312
- * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST
1313
- * {@link TokenSecret} (the current secret, or the head of a rotation list).
1314
- * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a
1315
- * misconfigured secret with no usable entry THROWS an {@link HTTPError}
1316
- * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with
1317
- * {@link verifyToken}. Omitting `ttl` mints a token that never expires.
1318
- *
1319
- * @param value - The opaque value to embed (a session id, a deployment marker)
1320
- * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}
1321
- * @returns The signed `<payload>.<signature>` token string
1322
- * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry
1323
- *
1324
- * @example
1325
- * ```ts
1326
- * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })
1327
- * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined
1328
- * ```
1329
- */
1330
- export declare function signToken(value: string, options: TokenOptions): Promise<string>;
1331
-
1332
- /**
1333
- * The SSE response headers the `openStream` seam always sets.
1334
- *
1335
- * @remarks
1336
- * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`
1337
- * keeps a proxy from caching the stream; `keep-alive` holds the connection
1338
- * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so
1339
- * events flush promptly rather than batching. Frozen so a consumer can read
1340
- * but never mutate the shared default; `openStream` merges any
1341
- * {@link import('./types.js').StreamOptions.headers} UNDER these.
1342
- */
1343
- export declare const SSE_HEADERS: Readonly<Record<string, string>>;
1344
-
1345
- /**
1346
- * One Server-Sent Event to serialize to the wire.
1347
- *
1348
- * @remarks
1349
- * - `data` — the event payload (required). Serialized as one or more `data:`
1350
- * lines: the value is split on `\n` into a `data:` line PER segment, so it
1351
- * round-trips through a consumer's multi-`data` concat.
1352
- * - `event` — the optional event TYPE, emitted as an `event:` line; omitted
1353
- * ⇒ the consumer's default (`message`).
1354
- * - `id` — the optional last-event-id, emitted as an `id:` line.
1355
- * - `retry` — the optional reconnection time in milliseconds, emitted as a
1356
- * `retry:` line.
1357
- */
1358
- export declare interface SSEMessage {
1359
- readonly data: string;
1360
- /** Must be a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
1361
- readonly event?: string;
1362
- /** Must be a SINGLE-LINE value — an embedded newline would corrupt the SSE wire format. */
1363
- readonly id?: string;
1364
- readonly retry?: number;
1365
- }
1366
-
1367
- /**
1368
- * A handle to write Server-Sent Events to an open, fetch-standard streaming
1369
- * `Response` — the generic streaming surface `openStream` returns over a
1370
- * `ReadableStream`.
1371
- *
1372
- * @remarks
1373
- * Agent-agnostic by design: it speaks only the SSE wire vocabulary ({@link
1374
- * SSEMessage}), so any streaming consumer maps its own events onto `write`.
1375
- * `response` is the `Response` to return from the route handler (its body is
1376
- * the `ReadableStream` this handle writes into). Each `write` serializes the
1377
- * message to the wire and enqueues it; `comment` writes a `: text` keep-alive
1378
- * line (ignored by a conforming SSE parser — no spurious event); `end` closes
1379
- * the stream. Every method is a SAFE NO-OP once `closed` is `true`, so a late
1380
- * `write` never throws.
1381
- */
1382
- export declare interface StreamInterface {
1383
- /** The streaming `Response` to return from the route handler. */
1384
- readonly response: Response;
1385
- /** Whether the underlying stream is done (ended, or the consumer disconnected). */
1386
- readonly closed: boolean;
1387
- /**
1388
- * Serialize + enqueue one {@link SSEMessage} to the wire (a no-op once `closed`).
1389
- *
1390
- * @param message - The event to send (its `data` split on `\n` into `data:` lines)
1391
- */
1392
- write(message: SSEMessage): void;
1393
- /**
1394
- * Write a `: text` SSE comment line — a keep-alive a conforming parser ignores.
1395
- *
1396
- * @param text - The comment text (sent after the `: ` prefix)
1397
- */
1398
- comment(text: string): void;
1399
- /** End the stream, completing the response (a no-op once already `closed`). */
1400
- end(): void;
1401
- }
1402
-
1403
- /**
1404
- * Options for the `openStream` seam.
1405
- *
1406
- * @param status - The HTTP status the streaming response is opened with;
1407
- * defaults to `200`.
1408
- * @param headers - Extra response headers merged with the SSE headers the
1409
- * seam always sets ({@link SSE_HEADERS}) — a key the seam owns is never
1410
- * overridden.
1411
- */
1412
- export declare interface StreamOptions {
1413
- readonly status?: number;
1414
- readonly headers?: Readonly<Record<string, string>>;
1415
- }
1416
-
1417
- /**
1418
- * Options for `signToken` — how a stateless, HMAC-signed token is minted.
1419
- *
1420
- * @param secret - The {@link TokenSecret} to sign with; `signToken` always
1421
- * uses the FIRST secret (a single string, or the current head of a
1422
- * rotation list). An empty rotation list is a misconfiguration and throws.
1423
- * @param ttl - An optional lifetime in milliseconds. When set, the expiry
1424
- * timestamp is bound INTO the signed payload (HMAC-covered, tamper-proof);
1425
- * `verifyToken` rejects the token once that instant has passed. Omitted ⇒
1426
- * the token never expires.
1427
- */
1428
- export declare interface TokenOptions {
1429
- readonly secret: TokenSecret;
1430
- readonly ttl?: number;
1431
- }
1432
-
1433
- /**
1434
- * A secret (or rotation list) for signing + verifying a stateless, HMAC-signed
1435
- * token.
1436
- *
1437
- * @remarks
1438
- * A single `string` is the lone secret. A `readonly string[]` is a rotation
1439
- * list in `[current, ...older]` order: `signToken` always signs with the
1440
- * FIRST (current) secret, while `verifyToken` accepts a token signed by ANY
1441
- * secret in the list — so a key rotates by prepending the new one and keeping
1442
- * the old until every outstanding token has expired, with zero downtime.
1443
- */
1444
- export declare type TokenSecret = string | readonly string[];
1445
-
1446
- /**
1447
- * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque
1448
- * comparison body — the reduction {@link matchesETag} applies to both sides
1449
- * before the RFC 7232 §2.3.2 weak comparison.
1450
- *
1451
- * @param tag - One entity-tag (`W/"<body>"` or `"<body>"`)
1452
- * @returns The tag with any leading `W/` removed (the quotes preserved)
1453
- *
1454
- * @example
1455
- * ```ts
1456
- * unwrapETag('W/"abc"') // '"abc"'
1457
- * ```
1458
- */
1459
- export declare function unwrapETag(tag: string): string;
1460
-
1461
- /**
1462
- * Verify a stateless token and return its embedded value — TOTAL, never throws.
1463
- *
1464
- * @remarks
1465
- * The inverse of {@link signToken}: splits the token on its LAST `.` (so a
1466
- * value containing dots survives), and checks the payload's HMAC-SHA256
1467
- * signature against EACH {@link TokenSecret} candidate via
1468
- * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is
1469
- * retired, §3 of the proposal), accepting the token on the first match (the
1470
- * rotation path). It then decodes + narrows the payload (`isRecord` +
1471
- * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,
1472
- * rejects an expired token. ANY failure — a malformed token, a bad signature,
1473
- * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —
1474
- * yields `undefined` rather than throwing.
1475
- *
1476
- * @param token - The candidate token string (from a request header/cookie)
1477
- * @param secret - The {@link TokenSecret} (or rotation list) to verify against
1478
- * @returns The embedded value when the token is valid + unexpired, else `undefined`
1479
- *
1480
- * @example
1481
- * ```ts
1482
- * await verifyToken('bad.token', 'shh') // undefined — never throws
1483
- * ```
1484
- */
1485
- export declare function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined>;
1486
-
1487
- /**
1488
- * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append
1489
- * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).
1490
- *
1491
- * @remarks
1492
- * The cookie value is `await signToken(value, { secret })`
1493
- * (`<payload>.<signature>`), so a signed cookie is a stateless token in a
1494
- * cookie — the same secret rotation and tamper rejection, no second HMAC
1495
- * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto
1496
- * signing is asynchronous (§3 of the proposal).
1497
- *
1498
- * @param headers - The response `Headers` to write into
1499
- * @param name - The cookie name
1500
- * @param value - The opaque value to sign into the cookie
1501
- * @param secret - The {@link TokenSecret} to sign with (the first secret signs)
1502
- * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`
1503
- *
1504
- * @example
1505
- * ```ts
1506
- * const headers = new Headers()
1507
- * await writeSignedCookie(headers, 'session', 'user-1', 'secret')
1508
- * ```
1509
- */
1510
- export declare function writeSignedCookie(headers: Headers, name: string, value: string, secret: TokenSecret, options?: CookieOptions): Promise<void>;
1511
-
1512
- export { }