@orkestrel/server 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../node_modules/@orkestrel/contract/dist/src/core/index.js","../../../src/core/helpers.ts","../../../src/core/Negotiator.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Encoding } from './types.js'\n\n// The substrate's tunable defaults (AGENTS §5 constants file) — only the\n// constants with a real consumer inside THIS package (AGENTS §21: build\n// against a concrete consumer, not speculatively). Frozen so a consumer can\n// read but never mutate the shared default. Middleware-package-only defaults\n// (rate limiting, CSRF, sessions, static serving, multipart — Appendix A of\n// the proposal) stay OUT of this file; they belong to that package's own\n// `constants.ts`.\n\n/** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */\nexport const DEFAULT_DRAIN_MS = 10_000\n\n/** Default maximum request body size (bytes) `readBody` accepts before a 413. */\nexport const DEFAULT_BODY_LIMIT = 1_048_576\n\n/**\n * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap\n * the body pipeline's byte-counting `TransformStream` enforces when\n * transparently decompressing a `Content-Encoding` request body.\n *\n * @remarks\n * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)\n * can inflate by many orders of magnitude — a classic decompression bomb.\n * Capping the decompressed byte count makes the pipe ABORT the moment the\n * output would exceed this, BEFORE the full bomb is materialized, so the\n * inflation can never exhaust memory. Defaults to `16 MiB` — a generous\n * ceiling for a legitimate compressed JSON / form body, far below an OOM. A\n * consumer raises it via {@link import('./types.js').BodyOptions}\n * `decompression` for a workload that genuinely ships larger decompressed\n * bodies.\n */\nexport const DEFAULT_DECOMPRESSED_LIMIT = 16_777_216\n\n/**\n * The SSE response headers the `openStream` seam always sets.\n *\n * @remarks\n * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`\n * keeps a proxy from caching the stream; `keep-alive` holds the connection\n * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so\n * events flush promptly rather than batching. Frozen so a consumer can read\n * but never mutate the shared default; `openStream` merges any\n * {@link import('./types.js').StreamOptions.headers} UNDER these.\n */\nexport const SSE_HEADERS: Readonly<Record<string, string>> = Object.freeze({\n\t'Content-Type': 'text/event-stream; charset=utf-8',\n\t'Cache-Control': 'no-cache',\n\tConnection: 'keep-alive',\n\t'X-Accel-Buffering': 'no',\n})\n\n/**\n * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`\n * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized\n * / control-char-bearing incoming id is REJECTED (a fresh id is minted\n * instead) rather than ever riding into a response header or `context.state`\n * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const REQUEST_ID_PATTERN: Readonly<RegExp> = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/)\n\n/**\n * The set of bare `Content-Type`s `isCompressibleType` treats as\n * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /\n * `+xml`) rules that helper also applies.\n *\n * @remarks\n * The text-shaped application types worth compressing (JSON / JavaScript /\n * XML / SVG / WASM / a few document formats) — NOT already-compressed\n * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's\n * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads\n * but never mutates the shared default.\n */\nexport const COMPRESSIBLE_TYPES: ReadonlySet<string> = new Set([\n\t'application/json',\n\t'application/javascript',\n\t'application/xml',\n\t'application/xhtml+xml',\n\t'application/rss+xml',\n\t'application/atom+xml',\n\t'application/ld+json',\n\t'application/manifest+json',\n\t'application/vnd.api+json',\n\t'application/wasm',\n\t'image/svg+xml',\n\t'application/pdf',\n])\n\n/**\n * The default {@link Encoding} content-codings the substrate offers, in\n * PREFERENCE order — `gzip` / `deflate`.\n *\n * @remarks\n * `identity` (no compression) is always implicitly acceptable and is NOT\n * listed here — it is the fall-through when a client accepts none of these.\n * Brotli is omitted per the core's `CompressionStream`-only decision (see\n * {@link Encoding}). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const DEFAULT_ENCODINGS: readonly Encoding[] = Object.freeze(['gzip', 'deflate'])\n","// AGENTS §12: a handler signals a client-facing fault by throwing an\n// `HTTPError` carrying the HTTP `status` to send; the server's error boundary\n// (§5.3 of the proposal) turns it into a response of that status. Any OTHER\n// throw is a programmer/runtime error → a 500 (its message hidden unless\n// `expose`). The machine-readable field here is the numeric `status` (plus an\n// optional `context` bag) — `MultipartError` is NOT ported here: it moves to\n// the future `@orkestrel/middleware` package with its owner (`createMultipart`).\n\n/**\n * An error a handler (or middleware) throws to produce an HTTP response of a\n * specific status.\n *\n * @remarks\n * Carries the HTTP `status` to send and an optional `context` record (the\n * offending field / value). The server's built-in error boundary catches it\n * and renders a response of `status` with the error's `message` as the body\n * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's\n * deliberate signal), unlike a generic throw whose message is hidden unless\n * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for\n * specific statuses, or throw it directly. Narrow a caught value with\n * {@link isHTTPError}.\n *\n * @example\n * ```ts\n * import { HTTPError } from '@src/core'\n *\n * const handler = async (request: Request): Promise<Response> => {\n * \tconst user = await find(new URL(request.url).searchParams.get('id'))\n * \tif (user === undefined) throw new HTTPError(404, 'user not found')\n * \treturn Response.json(user)\n * }\n * ```\n */\nexport class HTTPError extends Error {\n\treadonly status: number\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(status: number, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tthis.name = 'HTTPError'\n\t\tthis.status = status\n\t\tthis.context = context\n\t}\n}\n\n/**\n * The {@link HTTPError} thrown when a request body exceeds the body\n * pipeline's size limit — a `413 Content Too Large`.\n *\n * @remarks\n * Thrown by `readBody` (and the middleware context's cached `body()`) when\n * the received bytes exceed the configured {@link\n * import('./types.js').BodyOptions.limit}, carrying the `limit` in its\n * `context`. The server's error boundary renders it as a 413.\n *\n * @example\n * ```ts\n * import { ContentTooLargeError, isHTTPError } from '@src/core'\n *\n * try {\n * \tawait readBody(request, { limit: 1024 })\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status) // 413\n * }\n * ```\n */\nexport class ContentTooLargeError extends HTTPError {\n\tconstructor(limit: number) {\n\t\tsuper(413, `request body exceeds the ${limit}-byte limit`, { limit })\n\t\tthis.name = 'ContentTooLargeError'\n\t}\n}\n\n/**\n * Narrow an unknown caught value to an {@link HTTPError} (including its\n * subclasses, e.g. {@link ContentTooLargeError}).\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link HTTPError}\n *\n * @example\n * ```ts\n * import { isHTTPError } from '@src/core'\n *\n * try {\n * \tawait handle(request)\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status, error.message)\n * }\n * ```\n */\nexport function isHTTPError(value: unknown): value is HTTPError {\n\treturn value instanceof HTTPError\n}\n","//#region src/core/constants.ts\n/**\n* The seven standard JSON Schema `type` names, frozen.\n*\n* @remarks\n* The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose\n* it with the shipped primitives instead of reaching for a bespoke guard:\n* `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and\n* `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)`\n* is the parser.\n*\n* @example\n* ```ts\n* import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'\n*\n* const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>\n* parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined\n* ```\n*/\nvar JSON_SCHEMA_TYPES = Object.freeze([\n\t\"null\",\n\t\"boolean\",\n\t\"object\",\n\t\"array\",\n\t\"number\",\n\t\"integer\",\n\t\"string\"\n]);\n//#endregion\n//#region src/core/validators.ts\n/** Determine whether a value is `null`. */\nfunction isNull(value) {\n\treturn value === null;\n}\n/** Determine whether a value is `undefined`. */\nfunction isUndefined(value) {\n\treturn value === void 0;\n}\n/** Determine whether a value is defined (neither `null` nor `undefined`). */\nfunction isDefined(value) {\n\treturn value !== null && value !== void 0;\n}\n/** Determine whether a value is a string. */\nfunction isString(value) {\n\treturn typeof value === \"string\";\n}\n/**\n* Determine whether a value is a number.\n*\n* @remarks\n* Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.\n*/\nfunction isNumber(value) {\n\treturn typeof value === \"number\";\n}\n/** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`). */\nfunction isFiniteNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value);\n}\n/** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers). */\nfunction isInteger(value) {\n\treturn Number.isInteger(value);\n}\n/** Determine whether a value is a boolean. */\nfunction isBoolean(value) {\n\treturn typeof value === \"boolean\";\n}\n/** Determine whether a value is exactly `true`. */\nfunction isTrue(value) {\n\treturn value === true;\n}\n/** Determine whether a value is exactly `false`. */\nfunction isFalse(value) {\n\treturn value === false;\n}\n/** Determine whether a value is a bigint. */\nfunction isBigInt(value) {\n\treturn typeof value === \"bigint\";\n}\n/** Determine whether a value is a symbol. */\nfunction isSymbol(value) {\n\treturn typeof value === \"symbol\";\n}\n/** Determine whether a value is callable. */\nfunction isFunction(value) {\n\treturn typeof value === \"function\";\n}\n/** Determine whether a value is a string or `null`. */\nfunction isNullableString(value) {\n\treturn value === null || isString(value);\n}\n/** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`). */\nfunction isNullableNumber(value) {\n\treturn value === null || isNumber(value);\n}\n/** Determine whether a value is a boolean or `null`. */\nfunction isNullableBoolean(value) {\n\treturn value === null || isBoolean(value);\n}\n/** Determine whether a value is a `Date`. */\nfunction isDate(value) {\n\treturn value instanceof Date;\n}\n/** Determine whether a value is a `RegExp`. */\nfunction isRegExp(value) {\n\treturn value instanceof RegExp;\n}\n/** Determine whether a value is an `Error`. */\nfunction isError(value) {\n\treturn value instanceof Error;\n}\n/** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable). */\nfunction isPromise(value) {\n\treturn value instanceof Promise;\n}\n/**\n* Determine whether a value is promise-like — an object exposing callable\n* `then`, `catch`, and `finally` methods.\n*\n* @remarks\n* Accepts any object with all three methods, not only native `Promise`\n* instances. Use {@link isPromise} when you specifically need `instanceof Promise`.\n*/\nfunction isPromiseLike(value) {\n\tif (!isObject(value)) return false;\n\tconst outcome = attempt(() => {\n\t\tconst thenValue = Reflect.get(value, \"then\");\n\t\tconst catchValue = Reflect.get(value, \"catch\");\n\t\tconst finallyValue = Reflect.get(value, \"finally\");\n\t\treturn isFunction(thenValue) && isFunction(catchValue) && isFunction(finallyValue);\n\t});\n\treturn outcome.success && outcome.value;\n}\n/** Determine whether a value is an `ArrayBuffer`. */\nfunction isArrayBuffer(value) {\n\treturn value instanceof ArrayBuffer;\n}\n/**\n* Determine whether a value is a `SharedArrayBuffer`.\n*\n* @remarks\n* Guards the global existence of `SharedArrayBuffer` first — safe where it is\n* absent or disabled (e.g. a context that is not cross-origin isolated).\n*/\nfunction isSharedArrayBuffer(value) {\n\treturn typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer;\n}\n/**\n* Determine whether a value implements the iterable protocol (`Symbol.iterator`).\n*\n* @remarks\n* Strings are explicitly included: a string has a callable `Symbol.iterator`\n* but is not an object, so the generic object path alone would miss it.\n*/\nfunction isIterable(value) {\n\tif (isString(value)) return true;\n\tif (!isObject(value)) return false;\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.iterator)));\n\treturn outcome.success && outcome.value;\n}\n/** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`). */\nfunction isAsyncIterable(value) {\n\tif (!isObject(value)) return false;\n\tconst outcome = attempt(() => isFunction(Reflect.get(value, Symbol.asyncIterator)));\n\treturn outcome.success && outcome.value;\n}\n/**\n* Determine whether a value is a non-null object.\n*\n* @remarks\n* `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use\n* {@link isRecord} when you need a plain-record check.\n*/\nfunction isObject(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\n/**\n* Determine whether a value is a plain record (object literal or null-prototype),\n* not an array or class instance.\n*\n* @remarks\n* Use instead of {@link isObject} to distinguish a plain `{}` /\n* `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain\n* test is realm-agnostic: rather than comparing against the current realm's\n* `Object.prototype` (which a plain object from another `vm.Context`, iframe,\n* or worker would fail), it accepts any value whose prototype is `null`, OR\n* whose prototype's own prototype is `null` — the shape every plain object\n* has in every realm, since `Object.prototype` itself always sits one step\n* above `null`. Arrays and class instances are still rejected: an array's\n* prototype chain runs through `Array.prototype` before `null`, and a class\n* instance's runs through the class's own prototype. The whole body runs\n* inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile\n* `getPrototypeOf` trap cannot escape as a thrown error.\n*/\nfunction isRecord(value) {\n\tconst outcome = attempt(() => {\n\t\tif (!isObject(value) || isArray(value)) return false;\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\treturn prototype === null || Object.getPrototypeOf(prototype) === null;\n\t});\n\treturn outcome.success && outcome.value;\n}\n/** Determine whether a value is a `Map`. */\nfunction isMap(value) {\n\treturn value instanceof Map;\n}\n/** Determine whether a value is a `Set`. */\nfunction isSet(value) {\n\treturn value instanceof Set;\n}\n/** Determine whether a value is a `WeakMap`. */\nfunction isWeakMap(value) {\n\treturn value instanceof WeakMap;\n}\n/** Determine whether a value is a `WeakSet`. */\nfunction isWeakSet(value) {\n\treturn value instanceof WeakSet;\n}\n/** Determine whether a value is an array. */\nfunction isArray(value) {\n\treturn Array.isArray(value);\n}\n/** Determine whether a value is a `DataView`. */\nfunction isDataView(value) {\n\treturn value instanceof DataView;\n}\n/** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`). */\nfunction isArrayBufferView(value) {\n\treturn ArrayBuffer.isView(value);\n}\n/** Determine whether a value is an `Int8Array`. */\nfunction isInt8Array(value) {\n\treturn value instanceof Int8Array;\n}\n/** Determine whether a value is a `Uint8Array`. */\nfunction isUint8Array(value) {\n\treturn value instanceof Uint8Array;\n}\n/** Determine whether a value is a `Uint8ClampedArray`. */\nfunction isUint8ClampedArray(value) {\n\treturn value instanceof Uint8ClampedArray;\n}\n/** Determine whether a value is an `Int16Array`. */\nfunction isInt16Array(value) {\n\treturn value instanceof Int16Array;\n}\n/** Determine whether a value is a `Uint16Array`. */\nfunction isUint16Array(value) {\n\treturn value instanceof Uint16Array;\n}\n/** Determine whether a value is an `Int32Array`. */\nfunction isInt32Array(value) {\n\treturn value instanceof Int32Array;\n}\n/** Determine whether a value is a `Uint32Array`. */\nfunction isUint32Array(value) {\n\treturn value instanceof Uint32Array;\n}\n/** Determine whether a value is a `Float32Array`. */\nfunction isFloat32Array(value) {\n\treturn value instanceof Float32Array;\n}\n/** Determine whether a value is a `Float64Array`. */\nfunction isFloat64Array(value) {\n\treturn value instanceof Float64Array;\n}\n/**\n* Determine whether a value is a `BigInt64Array`.\n*\n* @remarks\n* Guards the global existence of `BigInt64Array` first — safe in environments\n* that pre-date the BigInt typed-array additions.\n*/\nfunction isBigInt64Array(value) {\n\treturn typeof BigInt64Array !== \"undefined\" && value instanceof BigInt64Array;\n}\n/**\n* Determine whether a value is a `BigUint64Array`.\n*\n* @remarks\n* Guards the global existence of `BigUint64Array` first — safe in environments\n* that pre-date the BigInt typed-array additions.\n*/\nfunction isBigUint64Array(value) {\n\treturn typeof BigUint64Array !== \"undefined\" && value instanceof BigUint64Array;\n}\n/** Determine whether a value is the empty string `''`. */\nfunction isEmptyString(value) {\n\treturn isString(value) && value.length === 0;\n}\n/** Determine whether a value is an empty array. */\nfunction isEmptyArray(value) {\n\treturn isArray(value) && value.length === 0;\n}\n/** Determine whether a value is an empty plain object (no own string or enumerable symbol keys). */\nfunction isEmptyObject(value) {\n\tif (!isRecord(value)) return false;\n\treturn Object.keys(value).length === 0 && enumerableSymbolCount(value) === 0;\n}\n/** Determine whether a value is an empty `Map`. */\nfunction isEmptyMap(value) {\n\treturn value instanceof Map && value.size === 0;\n}\n/** Determine whether a value is an empty `Set`. */\nfunction isEmptySet(value) {\n\treturn value instanceof Set && value.size === 0;\n}\n/** Determine whether a value is a non-empty string (at least one character). */\nfunction isNonEmptyString(value) {\n\treturn isString(value) && value.length > 0;\n}\n/** Determine whether a value is a non-empty array (at least one element). */\nfunction isNonEmptyArray(value) {\n\treturn isArray(value) && value.length > 0;\n}\n/** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key). */\nfunction isNonEmptyObject(value) {\n\tif (!isRecord(value)) return false;\n\treturn Object.keys(value).length > 0 || enumerableSymbolCount(value) > 0;\n}\n/** Determine whether a value is a non-empty `Map` (at least one entry). */\nfunction isNonEmptyMap(value) {\n\treturn value instanceof Map && value.size > 0;\n}\n/** Determine whether a value is a non-empty `Set` (at least one element). */\nfunction isNonEmptySet(value) {\n\treturn value instanceof Set && value.size > 0;\n}\n/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`). */\nfunction isZeroArg(value) {\n\treturn isFunction(value) && value.length === 0;\n}\n/**\n* Determine whether a value is a native `async function`.\n*\n* @remarks\n* Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is\n* unreliable across realms. The `?.` keeps the guard total (§14): a function\n* whose `constructor` was nulled yields `undefined`, never a thrown `null.name`.\n*/\nfunction isAsyncFunction(value) {\n\treturn isFunction(value) && value.constructor?.name === \"AsyncFunction\";\n}\n/** Determine whether a value is a generator function (`function*`). */\nfunction isGeneratorFunction(value) {\n\treturn isFunction(value) && value.constructor?.name === \"GeneratorFunction\";\n}\n/** Determine whether a value is an async generator function (`async function*`). */\nfunction isAsyncGeneratorFunction(value) {\n\treturn isFunction(value) && value.constructor?.name === \"AsyncGeneratorFunction\";\n}\n/** Determine whether a value is a zero-argument async function. */\nfunction isZeroArgAsync(value) {\n\treturn isZeroArg(value) && isAsyncFunction(value);\n}\n/** Determine whether a value is a zero-argument generator function. */\nfunction isZeroArgGenerator(value) {\n\treturn isZeroArg(value) && isGeneratorFunction(value);\n}\n/** Determine whether a value is a zero-argument async generator function. */\nfunction isZeroArgAsyncGenerator(value) {\n\treturn isZeroArg(value) && isAsyncGeneratorFunction(value);\n}\n/**\n* Determine whether a value can be used as a `new`-target constructor.\n*\n* @remarks\n* Probes with `Reflect.construct(String, [], value)`: a real constructor\n* succeeds, while arrow functions, plain functions, and non-functions throw\n* and yield `false`. Never throws. Backs the `instanceOf` combinator.\n*/\nfunction isConstructor(value) {\n\tif (!isFunction(value)) return false;\n\ttry {\n\t\tReflect.construct(String, [], value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Determine whether a value is a cycle-safe JSON value.\n*\n* @remarks\n* Total guard: never throws, returns `false` for cycles, functions, `Date`\n* instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records\n* are walked with an ancestor set so recursive input fails instead of hanging.\n* The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a\n* record property, or a revoked `Proxy` anywhere in the structure, is caught\n* and yields `false` instead of escaping as a thrown error.\n*\n* @param value - The value to test\n* @returns `true` when the value has a JSON representation\n*\n* @example\n* ```ts\n* isJSONValue({ nested: [1, 'x', null] }) // true\n* isJSONValue(Number.NaN) // false\n* ```\n*/\nfunction isJSONValue(value) {\n\tconst ancestors = /* @__PURE__ */ new WeakSet();\n\tconst check = (entry) => {\n\t\tif (entry === null || isString(entry) || isBoolean(entry) || isFiniteNumber(entry)) return true;\n\t\tif (Array.isArray(entry)) {\n\t\t\tif (ancestors.has(entry)) return false;\n\t\t\tancestors.add(entry);\n\t\t\tconst valid = entry.every(check);\n\t\t\tancestors.delete(entry);\n\t\t\treturn valid;\n\t\t}\n\t\tif (!isRecord(entry)) return false;\n\t\tif (ancestors.has(entry)) return false;\n\t\tancestors.add(entry);\n\t\tconst valid = Object.values(entry).every(check);\n\t\tancestors.delete(entry);\n\t\treturn valid;\n\t};\n\tconst outcome = attempt(() => check(value));\n\treturn outcome.success && outcome.value;\n}\n/**\n* Determine whether a value is a primitive JSON value.\n*\n* @remarks\n* The flat leaf of any JSON document: `null`, a string, a **finite** number, or\n* a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON\n* carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`.\n*\n* The recursive {@link isJSONValue} guard is shipped and stays total with\n* cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and\n* the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with\n* the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`.\n*\n* @param value - The value to test\n* @returns `true` when `value` is `null`, a string, a finite number, or a boolean\n*\n* @example\n* ```ts\n* isJSONPrimitive(null) // true\n* isJSONPrimitive('hi') // true\n* isJSONPrimitive(42) // true\n* isJSONPrimitive(Number.NaN) // false — not representable in JSON\n* isJSONPrimitive({}) // false\n* ```\n*/\nfunction isJSONPrimitive(value) {\n\treturn isNull(value) || isString(value) || isFiniteNumber(value) || isBoolean(value);\n}\n//#endregion\n//#region src/core/helpers.ts\n/**\n* Invoke a callback and capture its outcome as a {@link Result}, never letting\n* a throw escape.\n*\n* @remarks\n* The single sanctioned never-throw boundary for the guards (AGENTS §14). The\n* `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied\n* callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a\n* `boolean`. This converts a throwing callback into a `Failure` so the\n* surrounding guard can treat it as a non-match instead of propagating the\n* exception, written once and shared rather than copy-pasted as ad-hoc\n* `try`/`catch`.\n*\n* @param callback - The callback to invoke with no arguments\n* @returns A `Success` carrying the return value, or a `Failure` carrying the\n* thrown reason normalised to an `Error`\n*\n* @example\n* ```ts\n* const outcome = attempt(() => predicate(value))\n* return outcome.success && outcome.value\n* ```\n*/\nfunction attempt(callback) {\n\ttry {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: callback()\n\t\t};\n\t} catch (reason) {\n\t\tif (reason instanceof Error) return {\n\t\t\tsuccess: false,\n\t\t\terror: reason\n\t\t};\n\t\tlet message = \"Unknown thrown value\";\n\t\ttry {\n\t\t\tmessage = String(reason);\n\t\t} catch {}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: new Error(message)\n\t\t};\n\t}\n}\n/**\n* Resolve a (possibly nested) field value from a record by a key or key path.\n*\n* @remarks\n* A single `string` is ONE key (never split on `.`, so dotted keys are safe); a\n* string array descends left-to-right through nested objects. Intermediates may\n* be any object — records, class instances, or arrays indexed by string. Returns\n* `undefined` the moment a segment is missing or lands on a non-object, so the\n* lookup is total — even against a hostile getter or Proxy trap that throws on\n* read, contained via {@link attempt} so the throw never escapes.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @returns The resolved value, or `undefined`\n*\n* @example\n* ```ts\n* resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada'\n* resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key)\n* resolveField({ a: 1 }, ['a', 'b']) // undefined\n* ```\n*/\nfunction resolveField(record, path) {\n\tconst keys = isString(path) ? [path] : path;\n\tlet current = record;\n\tfor (const key of keys) {\n\t\tif (!isObject(current)) return void 0;\n\t\tconst container = current;\n\t\tconst outcome = attempt(() => Reflect.get(container, key));\n\t\tif (!outcome.success) return void 0;\n\t\tcurrent = outcome.value;\n\t}\n\treturn current;\n}\n/**\n* Build a deterministic pseudo-random source seeded from a single number.\n*\n* @remarks\n* A mulberry32 generator — the same seed always yields the same sequence, so\n* generated seed data is reproducible across runs. Used as the default random\n* source for {@link compileGenerator}, seeded from the wall clock so casual\n* callers still get varied output without passing a source themselves.\n*\n* @param seed - The seed for the sequence\n* @returns A {@link RandomFunction} returning values in `[0, 1)`\n*\n* @example\n* ```ts\n* const random = seededRandom(42)\n* random() // always the same first value for seed 42\n* ```\n*/\nfunction seededRandom(seed) {\n\tlet state = seed >>> 0;\n\treturn () => {\n\t\tstate = state + 1831565813 >>> 0;\n\t\tlet t = state;\n\t\tt = Math.imul(t ^ t >>> 15, t | 1);\n\t\tt ^= t + Math.imul(t ^ t >>> 7, t | 61);\n\t\treturn ((t ^ t >>> 14) >>> 0) / 4294967296;\n\t};\n}\n/**\n* Count the enumerable own-symbol keys on a value.\n*\n* @remarks\n* String keys are ignored — only `Object.getOwnPropertySymbols` entries whose\n* descriptor is `enumerable` are counted. Backs the object-emptiness guards\n* (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an\n* enumerable symbol is not mistaken for empty.\n*\n* @param value - The object to inspect\n* @returns The number of enumerable own-symbol keys\n*\n* @example\n* ```ts\n* const flag = Symbol('flag')\n* enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1\n* enumerableSymbolCount({}) // 0\n* ```\n*/\nfunction enumerableSymbolCount(value) {\n\tlet count = 0;\n\tfor (const symbol of Object.getOwnPropertySymbols(value)) if (Object.getOwnPropertyDescriptor(value, symbol)?.enumerable) count += 1;\n\treturn count;\n}\n/**\n* Narrow a compiled {@link JSONSchema} down to the open `Readonly<Record<string, unknown>>` shape\n* tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never\n* an assertion (AGENTS §14).\n*\n* @remarks\n* A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a\n* tool advertises its `parameters` as an open record. The two are structurally compatible but not\n* assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema\n* is always a record, so the guard passes; the `undefined` fallback only satisfies the type's\n* optionality. This is the single sanctioned narrowing from a compiled contract schema to the open\n* tool-parameters record, so the crossing lives once rather than being copy-pasted per call site.\n*\n* @param schema - The compiled JSON Schema (a contract's `schema`)\n* @returns The schema as the open tool-parameters record, or `undefined` when it is not a record\n*\n* @example\n* ```ts\n* import { createContract, schemaToParameters } from '@src/core'\n*\n* const contract = createContract(shape)\n* const parameters = schemaToParameters(contract.schema) // the open record a tool advertises\n* ```\n*/\nfunction schemaToParameters(schema) {\n\treturn isRecord(schema) ? schema : void 0;\n}\n//#endregion\n//#region src/core/combinators.ts\nfunction arrayOf(elementGuard) {\n\treturn (value) => {\n\t\tif (!isArray(value)) return false;\n\t\tconst outcome = attempt(() => value.every(elementGuard));\n\t\treturn outcome.success && outcome.value;\n\t};\n}\nfunction tupleOf(...guards) {\n\treturn (value) => {\n\t\tif (!isArray(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tif (value.length !== guards.length) return false;\n\t\t\tfor (let index = 0; index < guards.length; index += 1) {\n\t\t\t\tconst guard = guards[index];\n\t\t\t\tif (!guard?.(value[index])) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\n}\n/**\n* Build a guard that accepts values identical (via `Object.is`) to one of the\n* provided literal primitives.\n*\n* @example\n* ```ts\n* const isRole = literalOf('admin', 'member', 'guest')\n* isRole('admin') // true\n* isRole('owner') // false\n* ```\n*/\nfunction literalOf(...literals) {\n\treturn (value) => literals.some((literal) => Object.is(literal, value));\n}\n/**\n* Build a guard that accepts instances of the provided constructor.\n*\n* @remarks\n* Verifies that `ctor` is a real constructor (via {@link isConstructor}) first,\n* so passing an arrow function does not silently produce a broken guard.\n*\n* @example\n* ```ts\n* const isDateValue = instanceOf(Date)\n* isDateValue(new Date()) // true\n* isDateValue({}) // false\n* ```\n*/\nfunction instanceOf(ctor) {\n\treturn (value) => isConstructor(ctor) && isObject(value) && value instanceof ctor;\n}\n/**\n* Build a guard from a native `enum` or any object whose values are strings or\n* numbers.\n*\n* @example\n* ```ts\n* enum Direction { Up = 'up', Down = 'down' }\n* const isDirection = enumOf(Direction)\n* isDirection('up') // true\n* isDirection('left') // false\n* ```\n*/\nfunction enumOf(enumeration) {\n\tconst values = new Set(Object.values(enumeration));\n\treturn (value) => (isString(value) || isNumber(value)) && values.has(value);\n}\nfunction setOf(elementGuard) {\n\treturn (value) => {\n\t\tif (!isSet(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) if (!elementGuard(entry)) return false;\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\n}\nfunction mapOf(keyGuard, valueGuard) {\n\treturn (value) => {\n\t\tif (!isMap(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const [key, entryValue] of value) if (!keyGuard(key) || !valueGuard(entryValue)) return false;\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\n}\n/**\n* Build a guard that accepts plain records matching a guard shape.\n*\n* @remarks\n* Three calling modes depending on the `optional` argument:\n* - **No `optional`** — all shape keys required; extra keys rejected.\n* - **`optional: K[]`** — the listed keys are optional; all others required.\n* - **`optional: true`** — every shape key is optional.\n*\n* Key presence is tested with `Object.hasOwn`, so a shape key satisfied only by\n* an inherited prototype member (`toString`, `constructor`, …) counts as absent.\n* A non-object / `null` / array input returns `false` rather than throwing. The\n* extra-key check only inspects `Object.keys` (string keys), so an extra\n* enumerable SYMBOL key is never rejected — intentional, for JSON fidelity, and\n* matches the compiled guard.\n*\n* @example\n* ```ts\n* const isUser = recordOf({ name: isString, age: isNumber })\n* isUser({ name: 'Ada', age: 36 }) // true\n* isUser({ name: 'Ada' }) // false — age missing\n*\n* const isPartial = recordOf({ name: isString, age: isNumber }, ['age'])\n* isPartial({ name: 'Ada' }) // true\n* ```\n*/\nfunction recordOf(shape, optional) {\n\tconst allowed = /* @__PURE__ */ new Set();\n\tfor (const key in shape) if (Object.prototype.hasOwnProperty.call(shape, key)) allowed.add(key);\n\tconst optionalSet = new Set(optional === true ? [...allowed] : isArray(optional) ? optional.map((key) => String(key)) : []);\n\treturn (value) => {\n\t\tif (!isRecord(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const key of Object.keys(value)) if (!allowed.has(key)) return false;\n\t\t\tfor (const key in shape) {\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) continue;\n\t\t\t\tconst present = Object.hasOwn(value, key);\n\t\t\t\tif (!optionalSet.has(key) && !present) return false;\n\t\t\t\tif (present) {\n\t\t\t\t\tconst guard = shape[key];\n\t\t\t\t\tif (!guard(value[key])) return false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\n}\nfunction iterableOf(elementGuard) {\n\treturn (value) => {\n\t\tif (!isIterable(value)) return false;\n\t\tconst outcome = attempt(() => {\n\t\t\tfor (const entry of value) if (!elementGuard(entry)) return false;\n\t\t\treturn true;\n\t\t});\n\t\treturn outcome.success && outcome.value;\n\t};\n}\n/**\n* Build a guard that accepts values that are own keys of the provided object.\n*\n* @remarks\n* Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys\n* (`toString`, `constructor`, …) are rejected. An own property that shadows a\n* prototype name is accepted.\n*\n* @example\n* ```ts\n* const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const\n* const isColorKey = keyOf(COLORS)\n* isColorKey('red') // true\n* isColorKey('purple') // false\n* isColorKey('toString') // false — inherited, not an own key\n* ```\n*/\nfunction keyOf(value) {\n\treturn (entry) => (isString(entry) || isSymbol(entry) || isNumber(entry)) && Object.hasOwn(value, entry);\n}\n/**\n* Build a new guard shape by keeping only the listed keys — the structural\n* equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n*\n* @example\n* ```ts\n* const full = { name: isString, age: isNumber, role: isString }\n* const isName = recordOf(pickOf(full, ['name']))\n* isName({ name: 'Ada' }) // true\n* ```\n*/\nfunction pickOf(shape, keys) {\n\tconst result = Object.create(null);\n\tfor (const key of keys) if (Object.prototype.hasOwnProperty.call(shape, key)) result[key] = shape[key];\n\treturn result;\n}\n/**\n* Build a new guard shape by removing the listed keys — the structural\n* equivalent of `Omit<T, K>`. Produces a shape for {@link recordOf}, not a guard.\n*\n* @example\n* ```ts\n* const full = { name: isString, age: isNumber, role: isString }\n* const isPublic = recordOf(omitOf(full, ['role']))\n* isPublic({ name: 'Ada', age: 36 }) // true\n* ```\n*/\nfunction omitOf(shape, keys) {\n\tconst skipped = /* @__PURE__ */ new Set();\n\tfor (const key of keys) skipped.add(key);\n\tconst result = Object.create(null);\n\tfor (const key in shape) {\n\t\tif (!Object.prototype.hasOwnProperty.call(shape, key)) continue;\n\t\tif (!skipped.has(key)) result[key] = shape[key];\n\t}\n\treturn result;\n}\nfunction andOf(left, right) {\n\treturn (value) => left(value) && right(value);\n}\nfunction orOf(left, right) {\n\treturn (value) => left(value) || right(value);\n}\n/**\n* Negate a guard or predicate — passes when `guard` returns `false`.\n*\n* @remarks\n* Typed as `Guard<unknown>` because `Exclude<unknown, T>` is not useful; use\n* {@link complementOf} when you need the narrowed `Exclude<TBase, TExcluded>`.\n*\n* @example\n* ```ts\n* const isNotNull = notOf(isNull)\n* ```\n*/\nfunction notOf(guard) {\n\treturn (value) => !guard(value);\n}\n/**\n* Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass\n* `base` but not `excluded`.\n*\n* @example\n* ```ts\n* const isNonEmpty = complementOf(isString, isEmptyString)\n* isNonEmpty('hi') // true\n* isNonEmpty('') // false\n* ```\n*/\nfunction complementOf(base, excluded) {\n\treturn (value) => {\n\t\tif (!base(value)) return false;\n\t\treturn !excluded(value);\n\t};\n}\nfunction unionOf(...guards) {\n\treturn (value) => guards.some((guard) => guard(value));\n}\nfunction intersectionOf(...guards) {\n\treturn (value) => guards.every((guard) => guard(value));\n}\nfunction whereOf(base, predicate) {\n\treturn (value) => {\n\t\tif (!base(value)) return false;\n\t\tconst outcome = attempt(() => predicate(value));\n\t\treturn outcome.success && outcome.value;\n\t};\n}\n/**\n* Defer guard creation until first use by calling `thunk()` on every\n* invocation.\n*\n* @remarks\n* `thunk` is called on every guard call, not cached — this lets it close over a\n* binding assigned *after* `lazyOf` is called, the primary use case for\n* self-referential recursive guards. Per §14 a throw from `thunk` (or the guard\n* it resolves to) is contained and reported as a non-match.\n*\n* A recursive guard built this way has no cycle/depth detection: a cyclic or\n* pathologically deep input is stack-bounded — the overflow is contained and the\n* guard returns `false` rather than throwing, but it is not validated correctly\n* past that bound.\n*\n* @example\n* ```ts\n* type Tree = { value: number; children: Tree[] }\n* let isTree: Guard<Tree>\n* isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) })\n* ```\n*/\nfunction lazyOf(thunk) {\n\treturn (value) => {\n\t\tconst outcome = attempt(() => thunk()(value));\n\t\treturn outcome.success && outcome.value;\n\t};\n}\nfunction transformOf(base, project, target) {\n\treturn (value) => {\n\t\tif (!base(value)) return false;\n\t\tconst outcome = attempt(() => project(value));\n\t\treturn outcome.success && target(outcome.value);\n\t};\n}\n/**\n* Build a guard that accepts finite numbers within an inclusive `[min, max]`\n* range.\n*\n* @remarks\n* Refines {@link isFiniteNumber} with the bound comparison, so `NaN` /\n* `±Infinity` are rejected before any comparison runs. An absent bound never\n* constrains that side. Reused for a number's own value AND, applied to a\n* `.length`, for string and array length refinements — the single source of the\n* bound logic shared by the compiled guard and parser (compilers.ts).\n*\n* @example\n* ```ts\n* const inRange = boundsOf(1, 5)\n* inRange(3) // true\n* inRange(0) // false — below min\n* inRange(6) // false — above max\n*\n* const atLeastTwo = boundsOf(2)\n* atLeastTwo(2) // true — unbounded above\n* ```\n*/\nfunction boundsOf(min, max) {\n\treturn whereOf(isFiniteNumber, (value) => (min === void 0 || value >= min) && (max === void 0 || value <= max));\n}\n/**\n* Build a guard that accepts strings matching a regular expression.\n*\n* @example\n* ```ts\n* const isHex = matchOf(/^[0-9a-f]+$/)\n* isHex('1a2f') // true\n* isHex('xyz') // false\n* ```\n*/\nfunction matchOf(pattern) {\n\treturn whereOf(isString, (value) => pattern.test(value));\n}\n/**\n* Build a guard that accepts strings satisfying optional length and pattern\n* refinements — `min` / `max` length and a `pattern`.\n*\n* @remarks\n* Composes {@link isString} with {@link boundsOf} on the string's `.length` and\n* an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns\n* the bare {@link isString} guard (the unconstrained fast path), so an\n* unrefined string leaf pays no wrapping cost. The single source of the string\n* refinement shared by the compiled guard and parser (compilers.ts).\n*\n* @example\n* ```ts\n* const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ })\n* isSlug('hello-world') // true\n* isSlug('') // false — below min\n* isSlug('Hello') // false — pattern miss\n*\n* stringOf() // identical to isString\n* ```\n*/\nfunction stringOf(options) {\n\tconst min = options?.min;\n\tconst max = options?.max;\n\tconst pattern = options?.pattern;\n\tif (min === void 0 && max === void 0 && pattern === void 0) return isString;\n\tconst withinLength = boundsOf(min, max);\n\treturn whereOf(isString, (value) => withinLength(value.length) && (pattern === void 0 || pattern.test(value)));\n}\n/**\n* Extend a guard to also allow `null`.\n*\n* @example\n* ```ts\n* const isNullableString = nullableOf(isString)\n* isNullableString('hi') // true\n* isNullableString(null) // true\n* isNullableString(42) // false\n* ```\n*/\nfunction nullableOf(guard) {\n\treturn (value) => value === null || guard(value);\n}\n/**\n* Extend a guard to also allow `undefined` — the optional counterpart of\n* {@link nullableOf}.\n*\n* @example\n* ```ts\n* const isOptionalString = optionalOf(isString)\n* isOptionalString('hi') // true\n* isOptionalString(undefined) // true\n* isOptionalString(null) // false\n* ```\n*/\nfunction optionalOf(guard) {\n\treturn (value) => value === void 0 || guard(value);\n}\n//#endregion\n//#region src/core/parsers.ts\n/**\n* Parse an unknown value to a string.\n*\n* @remarks\n* A string is returned unchanged; a finite number is coerced to its decimal\n* string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.\n*\n* @param value - The value to parse\n* @returns A string, or `undefined`\n*/\nfunction parseString(value) {\n\tif (isString(value)) return value;\n\tif (isFiniteNumber(value)) return String(value);\n}\n/**\n* Parse an unknown value to a finite number.\n*\n* @remarks\n* A finite number is returned unchanged; a non-blank numeric string is parsed\n* via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every\n* other type → `undefined`.\n*\n* @param value - The value to parse\n* @returns A finite number, or `undefined`\n*/\nfunction parseNumber(value) {\n\tif (typeof value === \"number\") return Number.isFinite(value) ? value : void 0;\n\tif (isString(value)) {\n\t\tif (value.trim() === \"\") return void 0;\n\t\tconst parsed = Number(value);\n\t\treturn Number.isFinite(parsed) ? parsed : void 0;\n\t}\n}\n/**\n* Parse an unknown value to a finite integer.\n*\n* @remarks\n* Accepts whatever {@link parseNumber} accepts, then requires the result to have\n* no fractional part. `3.14` / `'3.14'` → `undefined`.\n*\n* @param value - The value to parse\n* @returns A finite integer, or `undefined`\n*/\nfunction parseInteger(value) {\n\tconst parsed = parseNumber(value);\n\tif (parsed === void 0) return void 0;\n\treturn Number.isInteger(parsed) ? parsed : void 0;\n}\n/**\n* Parse an unknown value to a boolean.\n*\n* @remarks\n* A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /\n* `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything\n* else → `undefined`.\n*\n* @param value - The value to parse\n* @returns A boolean, or `undefined`\n*/\nfunction parseBoolean(value) {\n\tif (typeof value === \"boolean\") return value;\n\tif (value === \"true\" || value === \"1\" || value === 1) return true;\n\tif (value === \"false\" || value === \"0\" || value === 0) return false;\n}\n/**\n* Parse an unknown value to `null`.\n*\n* @remarks\n* A successful parse returns `null` itself — distinct from the `undefined`\n* failure sentinel every other parser in this file uses. Only `null` passes;\n* every other value (including `undefined`) → `undefined`.\n*\n* @param value - The value to parse\n* @returns `null` on a successful parse, or `undefined`\n*/\nfunction parseNull(value) {\n\treturn isNull(value) ? value : void 0;\n}\n/**\n* Parse an unknown value to a plain record — the input reference, never cloned.\n*\n* @param value - The value to parse\n* @returns The record, or `undefined`\n*/\nfunction parseRecord(value) {\n\treturn isRecord(value) ? value : void 0;\n}\n/**\n* Parse an unknown value to an array — the input reference, never cloned —\n* optionally guarding every element.\n*\n* @remarks\n* Without a `guard`, element types are NOT verified; let `T` default to\n* `unknown` rather than asserting a specific element type.\n*\n* @param value - The value to parse\n* @param guard - Optional element guard\n* @returns The array, or `undefined`\n*/\nfunction parseArray(value, guard) {\n\tif (!isArray(value)) return void 0;\n\tif (guard !== void 0 && !value.every(guard)) return void 0;\n\treturn value;\n}\n/**\n* Parse an unknown value to a cycle-safe JSON value — the input reference,\n* never cloned.\n*\n* @remarks\n* Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it\n* walks the entire tree via {@link isJSONValue} rather than checking only the\n* top-level shape. That walk is cycle-safe and total (never throws) because\n* `isJSONValue` runs its own probe inside a guard, so an adversarial\n* structure (a cycle, a hostile getter) yields `undefined` instead of hanging\n* or throwing.\n*\n* @param value - The value to parse\n* @returns The value, or `undefined` when it is not a valid JSON value\n*/\nfunction parseJSONValue(value) {\n\treturn isJSONValue(value) ? value : void 0;\n}\n/**\n* Parse an unknown value as one of the allowed literal primitives.\n*\n* @remarks\n* Pairs with {@link literalOf} — both match by `Object.is`, so the\n* `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive\n* (string, number, or boolean), not only strings. Matching is identity, never\n* cross-type coercion: `parseEnum('1', [1])` stays `undefined`.\n*\n* @param value - The value to parse\n* @param allowed - The permitted literal values\n* @returns The matched literal (by identity), or `undefined`\n*/\nfunction parseEnum(value, allowed) {\n\tfor (const option of allowed) if (Object.is(value, option)) return option;\n}\n/**\n* Read and parse a string field from a record by key or nested key path.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @returns A string, or `undefined`\n*/\nfunction parseStringField(record, path) {\n\treturn parseString(resolveField(record, path));\n}\n/**\n* Read and parse a finite-number field from a record by key or nested key path.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @returns A finite number, or `undefined`\n*/\nfunction parseNumberField(record, path) {\n\treturn parseNumber(resolveField(record, path));\n}\n/**\n* Read and parse a finite-integer field from a record by key or nested key path.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @returns A finite integer, or `undefined`\n*/\nfunction parseIntegerField(record, path) {\n\treturn parseInteger(resolveField(record, path));\n}\n/**\n* Read and parse a boolean field from a record by key or nested key path.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @returns A boolean, or `undefined`\n*/\nfunction parseBooleanField(record, path) {\n\treturn parseBoolean(resolveField(record, path));\n}\n/**\n* Read and parse a `null` field from a record by key or nested key path.\n*\n* @remarks\n* A successful parse returns `null` itself — distinct from the `undefined`\n* failure sentinel, which also covers a missing field.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @returns `null` on a successful parse, or `undefined`\n*/\nfunction parseNullField(record, path) {\n\treturn parseNull(resolveField(record, path));\n}\n/**\n* Read and parse a nested record field from a record by key or nested key path.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @returns A plain record, or `undefined`\n*/\nfunction parseRecordField(record, path) {\n\treturn parseRecord(resolveField(record, path));\n}\n/**\n* Read and parse an array field from a record by key or nested key path,\n* optionally guarding elements.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @param guard - Optional element guard\n* @returns An array, or `undefined`\n*/\nfunction parseArrayField(record, path, guard) {\n\treturn parseArray(resolveField(record, path), guard);\n}\n/**\n* Read and parse an enum field from a record by key or nested key path.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @param allowed - The permitted literal values\n* @returns The matched literal, or `undefined`\n*/\nfunction parseEnumField(record, path, allowed) {\n\treturn parseEnum(resolveField(record, path), allowed);\n}\n/**\n* Read and parse a JSON-value field from a record by key or nested key path.\n*\n* @remarks\n* Deep-gates the field's whole subtree via {@link parseJSONValue} — see that\n* function's remarks for why this differs from the shallow\n* {@link parseRecordField} / {@link parseArrayField}.\n*\n* @param record - The source record\n* @param path - A property key, or a key path descending into nested objects\n* @returns The value, or `undefined`\n*/\nfunction parseJSONValueField(record, path) {\n\treturn parseJSONValue(resolveField(record, path));\n}\n/**\n* Parse a JSON string, returning `undefined` instead of throwing.\n*\n* @remarks\n* The safe boundary for untrusted JSON text: a malformed string yields\n* `undefined`, never an exception. Returns `unknown` — a successful parse proves\n* nothing about shape, so narrow the result with a guard (or use\n* {@link parseJSONAs}). A large document is not walked here; parsing is shallow\n* and lazy validation is the caller's to compose.\n*\n* @param value - The JSON string to parse\n* @returns The parsed value, or `undefined` when `value` is not valid JSON\n*/\nfunction parseJSON(value) {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn;\n\t}\n}\n/**\n* Parse a JSON string and validate the result against a guard.\n*\n* @remarks\n* The lazy, safe path from an untrusted string to a typed `T`: parse, then check\n* the parsed value with the guard you bring — typically one composed from the\n* combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is\n* validated, so a large document is never walked in full unless the guard does.\n*\n* @param value - The JSON string to parse\n* @param guard - The guard for the expected shape\n* @returns The parsed value when it satisfies `guard`, otherwise `undefined`\n*\n* @example\n* ```ts\n* const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })\n* parseJSONAs('{\"host\":\"localhost\",\"tags\":[\"a\"]}', isConfig) // { host: 'localhost', tags: ['a'] }\n* parseJSONAs('{\"host\":\"localhost\"}', isConfig) // undefined — guard fails\n* parseJSONAs('not json', isConfig) // undefined — never throws\n* ```\n*/\nfunction parseJSONAs(value, guard) {\n\tconst parsed = parseJSON(value);\n\tif (parsed === void 0) return void 0;\n\treturn guard(parsed) ? parsed : void 0;\n}\n//#endregion\n//#region src/core/compilers.ts\n/**\n* Validate that a {@link ContractShape} tree is well-formed — a pure recursive\n* prepass run before compilation.\n*\n* @remarks\n* Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this\n* throws a plain `Error` immediately rather than surfacing as a silently-wrong\n* guard, parser, schema, or generator later. Checks, recursively:\n*\n* - An {@link OptionalShape} is only legal as a direct object-property value —\n* `optionalShape` wrapping an array item, a union variant, another\n* optional/nullable's inner shape, `additionalProperties`, or the top-level\n* shape all throw. An object property IS the one legal placement: its value\n* is unwrapped to `.inner` before recursing, so `.inner` itself is validated\n* as a normal (non-optional-wrapping) shape.\n* - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}\n* needs at least one value and rejects non-finite (`NaN` / `Infinity` /\n* `-Infinity`) number values.\n* - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}\n* needs `min <= max` when both are set.\n* - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer\n* range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.\n* - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion\n* continues into array items, object properties (and `additionalProperties`\n* when it is a shape), union variants, and optional/nullable inner shapes.\n*\n* @param shape - The shape to validate\n* @throws {Error} When the shape is malformed\n*/\nfunction validateShape(shape) {\n\tswitch (shape.type) {\n\t\tcase \"string\":\n\t\t\tif (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error(\"validateShape: a string shape has min greater than max\");\n\t\t\treturn;\n\t\tcase \"number\":\n\t\t\tif (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error(\"validateShape: a number shape has min greater than max\");\n\t\t\tif (shape.integer === true) {\n\t\t\t\tif (Math.ceil(shape.min ?? Number.NEGATIVE_INFINITY) > Math.floor(shape.max ?? Number.POSITIVE_INFINITY)) throw new Error(\"validateShape: an integer number shape has an empty integer range\");\n\t\t\t}\n\t\t\treturn;\n\t\tcase \"boolean\":\n\t\tcase \"null\":\n\t\tcase \"json\":\n\t\tcase \"raw\": return;\n\t\tcase \"literal\":\n\t\t\tif (shape.values.length === 0) throw new Error(\"validateShape: a literal shape needs at least one value\");\n\t\t\tfor (const value of shape.values) if (typeof value === \"number\" && !Number.isFinite(value)) throw new Error(\"validateShape: a literal shape may not contain non-finite number values\");\n\t\t\treturn;\n\t\tcase \"array\":\n\t\t\tif (shape.min !== void 0 && shape.max !== void 0 && shape.min > shape.max) throw new Error(\"validateShape: an array shape has min greater than max\");\n\t\t\tvalidateShape(shape.items);\n\t\t\treturn;\n\t\tcase \"object\": {\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key];\n\t\t\t\tif (child === void 0) continue;\n\t\t\t\tvalidateShape(child.type === \"optional\" ? child.inner : child);\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties;\n\t\t\tif (extra !== void 0 && extra !== true && extra !== false) validateShape(extra);\n\t\t\treturn;\n\t\t}\n\t\tcase \"union\":\n\t\t\tif (shape.variants.length === 0) throw new Error(\"validateShape: a union shape needs at least one variant\");\n\t\t\tfor (const variant of shape.variants) validateShape(variant);\n\t\t\treturn;\n\t\tcase \"optional\": throw new Error(\"validateShape: an optional shape may only appear as a direct object-property value\");\n\t\tcase \"nullable\":\n\t\t\tvalidateShape(shape.inner);\n\t\t\treturn;\n\t}\n}\n/**\n* Compile a {@link ContractShape} into a JSON Schema document.\n*\n* @remarks\n* Object shapes emit `additionalProperties: false` (unless opened) and list only\n* required keys in `required`; nullable shapes emit an `anyOf` with `{ type:\n* 'null' }`. Emission only — it never inspects a runtime value.\n*\n* @param shape - The shape to compile\n* @returns The emitted JSON Schema\n*/\nfunction compileSchema(shape) {\n\tswitch (shape.type) {\n\t\tcase \"string\": return {\n\t\t\ttype: \"string\",\n\t\t\t...shape.min !== void 0 ? { minLength: shape.min } : {},\n\t\t\t...shape.max !== void 0 ? { maxLength: shape.max } : {},\n\t\t\t...shape.pattern !== void 0 ? { pattern: shape.pattern.source } : {},\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"number\": return {\n\t\t\ttype: shape.integer === true ? \"integer\" : \"number\",\n\t\t\t...shape.min !== void 0 ? { minimum: shape.min } : {},\n\t\t\t...shape.max !== void 0 ? { maximum: shape.max } : {},\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"boolean\": return {\n\t\t\ttype: \"boolean\",\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"null\": return {\n\t\t\ttype: \"null\",\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"json\": return { ...shape.description !== void 0 ? { description: shape.description } : {} };\n\t\tcase \"literal\": return {\n\t\t\tenum: [...shape.values],\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"array\": return {\n\t\t\ttype: \"array\",\n\t\t\titems: compileSchema(shape.items),\n\t\t\t...shape.min !== void 0 ? { minItems: shape.min } : {},\n\t\t\t...shape.max !== void 0 ? { maxItems: shape.max } : {},\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"object\": {\n\t\t\tconst properties = {};\n\t\t\tconst required = [];\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key];\n\t\t\t\tif (child === void 0) continue;\n\t\t\t\tproperties[key] = compileSchema(child);\n\t\t\t\tif (child.type !== \"optional\") required.push(key);\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties;\n\t\t\tconst additionalProperties = extra === true ? true : extra !== void 0 && extra !== false ? compileSchema(extra) : false;\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\t...Object.keys(properties).length > 0 ? { properties } : {},\n\t\t\t\t...required.length > 0 ? { required } : {},\n\t\t\t\tadditionalProperties,\n\t\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t\t};\n\t\t}\n\t\tcase \"union\": return {\n\t\t\t...shape.mode === \"oneOf\" ? { oneOf: shape.variants.map((variant) => compileSchema(variant)) } : { anyOf: shape.variants.map((variant) => compileSchema(variant)) },\n\t\t\t...shape.description !== void 0 ? { description: shape.description } : {}\n\t\t};\n\t\tcase \"optional\": return compileSchema(shape.inner);\n\t\tcase \"nullable\": return { anyOf: [compileSchema(shape.inner), { type: \"null\" }] };\n\t\tcase \"raw\": return shape.schema;\n\t}\n}\n/**\n* Compile a {@link ContractShape} into a runtime type guard.\n*\n* @remarks\n* Reuses the combinators: `literalOf` for literals, `arrayOf` for arrays,\n* `recordOf` for closed objects, `unionOf` for unions, `nullableOf` for nullable,\n* and `whereOf` for constraint refinement. Like every guard it is total — it\n* never throws (AGENTS §14).\n*\n* @param shape - The shape to compile\n* @returns A guard narrowing to the shape's inferred type\n*/\nfunction compileGuard(shape) {\n\tswitch (shape.type) {\n\t\tcase \"string\": return stringOf({\n\t\t\tmin: shape.min,\n\t\t\tmax: shape.max,\n\t\t\tpattern: shape.pattern\n\t\t});\n\t\tcase \"number\": {\n\t\t\tconst base = shape.integer === true ? isInteger : isFiniteNumber;\n\t\t\tif (shape.min === void 0 && shape.max === void 0) return base;\n\t\t\treturn shape.integer === true ? intersectionOf(isInteger, boundsOf(shape.min, shape.max)) : boundsOf(shape.min, shape.max);\n\t\t}\n\t\tcase \"boolean\": return isBoolean;\n\t\tcase \"null\": return isNull;\n\t\tcase \"json\": return isJSONValue;\n\t\tcase \"literal\": return literalOf(...shape.values);\n\t\tcase \"array\": {\n\t\t\tconst base = arrayOf(compileGuard(shape.items));\n\t\t\tif (shape.min === void 0 && shape.max === void 0) return base;\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max);\n\t\t\treturn whereOf(base, (value) => withinLength(value.length));\n\t\t}\n\t\tcase \"object\": {\n\t\t\tconst map = Object.create(null);\n\t\t\tconst optionalKeys = [];\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key];\n\t\t\t\tif (child === void 0) continue;\n\t\t\t\tif (child.type === \"optional\") {\n\t\t\t\t\tmap[key] = compileGuard(child.inner);\n\t\t\t\t\toptionalKeys.push(key);\n\t\t\t\t} else map[key] = compileGuard(child);\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties;\n\t\t\tif (extra === void 0 || extra === false) return optionalKeys.length > 0 ? recordOf(map, optionalKeys) : recordOf(map);\n\t\t\tconst additional = extra === true ? void 0 : compileGuard(extra);\n\t\t\tconst required = Object.keys(map).filter((key) => !optionalKeys.includes(key));\n\t\t\treturn (value) => {\n\t\t\t\tif (!isRecord(value)) return false;\n\t\t\t\tfor (const key of required) if (!Object.hasOwn(value, key)) return false;\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\tfor (const key of Object.keys(value)) {\n\t\t\t\t\t\tconst guard = Object.hasOwn(map, key) ? map[key] : void 0;\n\t\t\t\t\t\tif (guard !== void 0) {\n\t\t\t\t\t\t\tif (!guard(value[key])) return false;\n\t\t\t\t\t\t} else if (additional !== void 0 && !additional(value[key])) return false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t\treturn outcome.success && outcome.value;\n\t\t\t};\n\t\t}\n\t\tcase \"union\": return unionOf(...shape.variants.map((variant) => compileGuard(variant)));\n\t\tcase \"optional\": return orOf(isUndefined, compileGuard(shape.inner));\n\t\tcase \"nullable\": return nullableOf(compileGuard(shape.inner));\n\t\tcase \"raw\": return (_value) => true;\n\t}\n}\n/**\n* Compile a {@link ContractShape} into an input parser.\n*\n* @remarks\n* Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /\n* `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a\n* whole on any required-field failure; a union returns a guard-valid value\n* unchanged, otherwise the first variant that both parses and guards wins.\n*\n* After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same\n* combinators `compileGuard` uses — `stringOf` for a string's length/pattern and\n* `boundsOf` for a number's value and an array's length — so a value that coerces\n* but violates a bound parses to `undefined`. The result is full parse↔guard\n* soundness (AGENTS §14): a non-`undefined` parse always satisfies the contract's\n* `is`, refinements included.\n*\n* @param shape - The shape to compile\n* @returns A parser yielding the shape's inferred type or `undefined`\n*/\nfunction compileParser(shape) {\n\tswitch (shape.type) {\n\t\tcase \"string\": {\n\t\t\tif (shape.min === void 0 && shape.max === void 0 && shape.pattern === void 0) return parseString;\n\t\t\tconst guard = stringOf({\n\t\t\t\tmin: shape.min,\n\t\t\t\tmax: shape.max,\n\t\t\t\tpattern: shape.pattern\n\t\t\t});\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = parseString(value);\n\t\t\t\treturn parsed !== void 0 && guard(parsed) ? parsed : void 0;\n\t\t\t};\n\t\t}\n\t\tcase \"number\": {\n\t\t\tconst base = shape.integer === true ? parseInteger : parseNumber;\n\t\t\tif (shape.min === void 0 && shape.max === void 0) return base;\n\t\t\tconst within = boundsOf(shape.min, shape.max);\n\t\t\treturn (value) => {\n\t\t\t\tconst parsed = base(value);\n\t\t\t\treturn parsed !== void 0 && within(parsed) ? parsed : void 0;\n\t\t\t};\n\t\t}\n\t\tcase \"boolean\": return parseBoolean;\n\t\tcase \"null\": return (value) => value === null ? null : void 0;\n\t\tcase \"json\": return (value) => isJSONValue(value) ? value : void 0;\n\t\tcase \"literal\": {\n\t\t\tconst allowed = new Set(shape.values);\n\t\t\treturn (value) => {\n\t\t\t\tif (allowed.has(value)) return value;\n\t\t\t\tif (isString(value)) {\n\t\t\t\t\tconst trimmed = value.trim();\n\t\t\t\t\tif (allowed.has(trimmed)) return trimmed;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tcase \"array\": {\n\t\t\tconst item = compileParser(shape.items);\n\t\t\tconst unbounded = shape.min === void 0 && shape.max === void 0;\n\t\t\tconst withinLength = boundsOf(shape.min, shape.max);\n\t\t\treturn (value) => {\n\t\t\t\tif (!isArray(value)) return void 0;\n\t\t\t\tconst result = [];\n\t\t\t\tfor (const entry of value) {\n\t\t\t\t\tconst parsed = item(entry);\n\t\t\t\t\tif (parsed === void 0) return void 0;\n\t\t\t\t\tresult.push(parsed);\n\t\t\t\t}\n\t\t\t\treturn unbounded || withinLength(result.length) ? result : void 0;\n\t\t\t};\n\t\t}\n\t\tcase \"object\": {\n\t\t\tconst entries = [];\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key];\n\t\t\t\tif (child === void 0) continue;\n\t\t\t\tconst optional = child.type === \"optional\";\n\t\t\t\tentries.push({\n\t\t\t\t\tkey,\n\t\t\t\t\tparse: compileParser(optional ? child.inner : child),\n\t\t\t\t\toptional\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst known = new Set(entries.map((entry) => entry.key));\n\t\t\tconst extra = shape.additionalProperties;\n\t\t\tconst additional = extra === void 0 || extra === false || extra === true ? void 0 : compileParser(extra);\n\t\t\tconst open = extra === true || additional !== void 0;\n\t\t\treturn (value) => {\n\t\t\t\tconst record = parseRecord(value);\n\t\t\t\tif (record === void 0) return void 0;\n\t\t\t\tconst outcome = attempt(() => {\n\t\t\t\t\tconst result = Object.create(null);\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tconst raw = record[entry.key];\n\t\t\t\t\t\tif (raw === void 0) {\n\t\t\t\t\t\t\tif (entry.optional) continue;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst parsed = entry.parse(raw);\n\t\t\t\t\t\tif (parsed === void 0) return void 0;\n\t\t\t\t\t\tresult[entry.key] = parsed;\n\t\t\t\t\t}\n\t\t\t\t\tif (open) for (const key of Object.keys(record)) {\n\t\t\t\t\t\tif (known.has(key)) continue;\n\t\t\t\t\t\tif (additional === void 0) result[key] = record[key];\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst parsed = additional(record[key]);\n\t\t\t\t\t\t\tif (parsed === void 0) return void 0;\n\t\t\t\t\t\t\tresult[key] = parsed;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t});\n\t\t\t\treturn outcome.success ? outcome.value : void 0;\n\t\t\t};\n\t\t}\n\t\tcase \"union\": {\n\t\t\tconst variants = shape.variants.map((variant) => ({\n\t\t\t\tparse: compileParser(variant),\n\t\t\t\tguard: compileGuard(variant)\n\t\t\t}));\n\t\t\treturn (value) => {\n\t\t\t\tfor (const variant of variants) if (variant.guard(value)) return value;\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tconst parsed = variant.parse(value);\n\t\t\t\t\tif (parsed !== void 0 && variant.guard(parsed)) return parsed;\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tcase \"optional\": {\n\t\t\tconst inner = compileParser(shape.inner);\n\t\t\treturn (value) => value === void 0 ? void 0 : inner(value);\n\t\t}\n\t\tcase \"nullable\": {\n\t\t\tconst inner = compileParser(shape.inner);\n\t\t\treturn (value) => value === null ? null : inner(value);\n\t\t}\n\t\tcase \"raw\": return (value) => value;\n\t}\n}\n/**\n* Compile a {@link ContractShape} into a deterministic seed value.\n*\n* @remarks\n* The same shape and the same `random` source always produce the same value, so\n* seed data is reproducible. Defaults to a {@link seededRandom} source seeded\n* from the wall clock when none is supplied. Throws on a degenerate empty\n* `literalShape` / `unionShape`, on a pattern-constrained `stringShape` whose\n* generated sample cannot satisfy the pattern, or on a `rawShape` (its embedded\n* schema is arbitrary and cannot be auto-generated) — a programmer error that\n* cannot generate a value (AGENTS §12). `createContract` runs\n* {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /\n* bounded shape is normally caught there; these throws remain here as defense\n* for standalone `compileGenerator` use.\n*\n* @param shape - The shape to generate from\n* @param random - A seeded random source (defaults to `seededRandom(Date.now())`)\n* @returns A value matching the shape\n*/\nfunction compileGenerator(shape, random = seededRandom(Date.now())) {\n\tswitch (shape.type) {\n\t\tcase \"string\": {\n\t\t\tconst min = shape.min ?? 0;\n\t\t\tconst max = shape.max ?? Math.max(min, 12);\n\t\t\tconst length = Math.max(min, Math.min(max, 8));\n\t\t\tconst alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789\";\n\t\t\tlet value = \"\";\n\t\t\tfor (let index = 0; index < length; index += 1) value += alphabet[Math.floor(random() * 36)];\n\t\t\tif (shape.pattern !== void 0 && !shape.pattern.test(value)) throw new Error(\"compileGenerator: a pattern-constrained string shape cannot be auto-generated — supply or verify values another way\");\n\t\t\treturn value;\n\t\t}\n\t\tcase \"number\": {\n\t\t\tconst min = shape.min ?? 0;\n\t\t\tconst max = shape.max ?? 100;\n\t\t\tif (shape.integer === true) {\n\t\t\t\tconst lo = Math.ceil(min);\n\t\t\t\tconst hi = Math.floor(max);\n\t\t\t\treturn Math.floor(random() * (hi - lo + 1)) + lo;\n\t\t\t}\n\t\t\treturn random() * (max - min) + min;\n\t\t}\n\t\tcase \"boolean\": return random() >= .5;\n\t\tcase \"null\": return null;\n\t\tcase \"json\": {\n\t\t\tconst pick = Math.floor(random() * 5);\n\t\t\tif (pick === 0) return null;\n\t\t\tif (pick === 1) return random() >= .5;\n\t\t\tif (pick === 2) return Math.floor(random() * 1e3);\n\t\t\tif (pick === 3) {\n\t\t\t\tconst alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n\t\t\t\tlet value = \"\";\n\t\t\t\tfor (let index = 0; index < 6; index += 1) value += alphabet[Math.floor(random() * 26)];\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\treturn { value: Math.floor(random() * 1e3) };\n\t\t}\n\t\tcase \"literal\":\n\t\t\tif (shape.values.length === 0) throw new Error(\"compileGenerator: a literal shape needs at least one value\");\n\t\t\treturn shape.values[Math.floor(random() * shape.values.length)];\n\t\tcase \"array\": {\n\t\t\tconst lo = shape.min ?? Math.min(1, shape.max ?? 1);\n\t\t\tconst hi = shape.max ?? Math.max(lo, 3);\n\t\t\tconst length = Math.floor(random() * (hi - lo + 1)) + lo;\n\t\t\tconst result = [];\n\t\t\tfor (let index = 0; index < length; index += 1) result.push(compileGenerator(shape.items, random));\n\t\t\treturn result;\n\t\t}\n\t\tcase \"object\": {\n\t\t\tconst result = {};\n\t\t\tfor (const key of Object.keys(shape.properties)) {\n\t\t\t\tconst child = shape.properties[key];\n\t\t\t\tif (child === void 0) continue;\n\t\t\t\tif (child.type === \"optional\" && random() < .3) continue;\n\t\t\t\tresult[key] = compileGenerator(child, random);\n\t\t\t}\n\t\t\tconst extra = shape.additionalProperties;\n\t\t\tif (extra !== void 0 && extra !== true && extra !== false) {\n\t\t\t\tconst count = 1 + Math.floor(random() * 2);\n\t\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\t\tconst key = `key${index}`;\n\t\t\t\t\tif (Object.hasOwn(result, key)) continue;\n\t\t\t\t\tresult[key] = compileGenerator(extra, random);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tcase \"union\":\n\t\t\tif (shape.variants.length === 0) throw new Error(\"compileGenerator: a union shape needs at least one variant\");\n\t\t\treturn compileGenerator(shape.variants[Math.floor(random() * shape.variants.length)], random);\n\t\tcase \"optional\": return compileGenerator(shape.inner, random);\n\t\tcase \"nullable\": return random() < .2 ? null : compileGenerator(shape.inner, random);\n\t\tcase \"raw\": throw new Error(\"compileGenerator: a raw shape embeds an arbitrary JSON Schema and cannot be auto-generated — supply values another way\");\n\t}\n}\nfunction createContract(shape) {\n\tvalidateShape(shape);\n\tconst schema = compileSchema(shape);\n\tconst guard = compileGuard(shape);\n\tconst parser = compileParser(shape);\n\treturn {\n\t\tschema,\n\t\tis: guard,\n\t\tparse(value) {\n\t\t\treturn parser(value);\n\t\t},\n\t\tgenerate(random) {\n\t\t\treturn compileGenerator(shape, random);\n\t\t}\n\t};\n}\n//#endregion\n//#region src/core/shapers.ts\n/**\n* Build a string {@link StringShape}.\n*\n* @param options - Optional length (`min` / `max`), `pattern`, and `description`\n* @returns A string shape\n*\n* @example\n* ```ts\n* const name = stringShape({ min: 1, max: 80, description: 'Display name' })\n* ```\n*/\nfunction stringShape(options) {\n\treturn {\n\t\ttype: \"string\",\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tpattern: options?.pattern,\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build a numeric {@link NumberShape}.\n*\n* @param options - Optional bounds (`min` / `max`), `integer`, and `description`\n* @returns A number shape\n*/\nfunction numberShape(options) {\n\treturn {\n\t\ttype: \"number\",\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tinteger: options?.integer,\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build an integer {@link NumberShape} — forces `integer: true`.\n*\n* @remarks\n* The emitted JSON Schema uses `\"type\": \"integer\"` and the guard rejects\n* fractional numbers.\n*\n* @param options - Optional bounds and `description` (no `integer` key)\n* @returns An integer number shape\n*/\nfunction integerShape(options) {\n\treturn {\n\t\ttype: \"number\",\n\t\tinteger: true,\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build a {@link BooleanShape}.\n*\n* @param options - Optional `description`\n* @returns A boolean shape\n*/\nfunction booleanShape(options) {\n\treturn {\n\t\ttype: \"boolean\",\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build a {@link NullShape}.\n*\n* @param options - Optional `description`\n* @returns A null shape\n*/\nfunction nullShape(options) {\n\treturn {\n\t\ttype: \"null\",\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build a literal shape from a fixed set of primitive values.\n*\n* @param values - The permitted literals\n* @param options - Optional `description`\n* @returns A literal shape whose `Infer` is the union of `values`\n*\n* @example\n* ```ts\n* const role = literalShape(['admin', 'member', 'guest'])\n* // Infer<typeof role> = 'admin' | 'member' | 'guest'\n*\n* const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })\n* ```\n*/\nfunction literalShape(values, options) {\n\treturn {\n\t\ttype: \"literal\",\n\t\tvalues,\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build an {@link ArrayShape} from an element shape.\n*\n* @param items - The element shape\n* @param options - Optional length bounds and `description`\n* @returns An array shape\n*\n* @example\n* ```ts\n* const tags = arrayShape(stringShape(), { max: 10 })\n* ```\n*/\nfunction arrayShape(items, options) {\n\treturn {\n\t\ttype: \"array\",\n\t\titems,\n\t\tmin: options?.min,\n\t\tmax: options?.max,\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build an {@link ObjectShape} from a property map.\n*\n* @remarks\n* Wrap any property in {@link optionalShape} to allow its absence. By default\n* the compiled guard rejects unknown keys; pass `additionalProperties` to open\n* the object.\n*\n* @param properties - Map of property names to child shapes\n* @param options - Optional `additionalProperties` and `description`\n* @returns An object shape\n*\n* @example\n* ```ts\n* const user = objectShape({\n* \tname: stringShape({ min: 1 }),\n* \tage: integerShape({ min: 0, max: 120 }),\n* \tbio: optionalShape(stringShape()),\n* })\n* ```\n*/\nfunction objectShape(properties, options) {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties,\n\t\tadditionalProperties: options?.additionalProperties,\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build an open {@link ObjectShape} with no fixed properties — a dictionary.\n*\n* @remarks\n* Every value is validated against `values`; keys are unconstrained. Equivalent\n* to `objectShape({}, { additionalProperties: values })`.\n*\n* @param values - The shape every value must match\n* @param options - Optional `description`\n* @returns An open object shape\n*\n* @example\n* ```ts\n* const bindings = recordShape(numberShape()) // ~ Record<string, number>\n* ```\n*/\nfunction recordShape(values, options) {\n\treturn {\n\t\ttype: \"object\",\n\t\tproperties: {},\n\t\tadditionalProperties: values,\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).\n*\n* @param variants - The candidate shapes; the first match wins at runtime\n* @returns A union shape whose `Infer` is the union of the variants\n*\n* @example\n* ```ts\n* const id = unionShape(stringShape(), integerShape())\n* // Infer<typeof id> = string | number\n* ```\n*/\nfunction unionShape(...variants) {\n\treturn {\n\t\ttype: \"union\",\n\t\tvariants\n\t};\n}\n/**\n* Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.\n*\n* @remarks\n* Runtime behavior is identical to {@link unionShape} — only the emitted schema\n* keyword differs (`oneOf` vs `anyOf`).\n*\n* @param variants - The candidate shapes\n* @returns A union shape with `mode: 'oneOf'`\n*/\nfunction oneOfShape(...variants) {\n\treturn {\n\t\ttype: \"union\",\n\t\tvariants,\n\t\tmode: \"oneOf\"\n\t};\n}\n/**\n* Wrap a shape so it may be absent (`undefined`).\n*\n* @remarks\n* As an {@link objectShape} property, the field becomes a true optional property\n* in the inferred type.\n*\n* @param inner - The wrapped shape\n* @returns An optional shape\n*/\nfunction optionalShape(inner) {\n\treturn {\n\t\ttype: \"optional\",\n\t\tinner\n\t};\n}\n/**\n* Wrap a shape so it may be `null`.\n*\n* @param inner - The wrapped shape\n* @returns A nullable shape\n*/\nfunction nullableShape(inner) {\n\treturn {\n\t\ttype: \"nullable\",\n\t\tinner\n\t};\n}\n/**\n* Build a {@link JSONShape}.\n*\n* @remarks\n* The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary\n* schema fragment and accepts anything at runtime, while `jsonShape` validates\n* that a value is real JSON (via {@link isJSONValue}).\n*\n* @param options - Optional `description`\n* @returns A JSON passthrough shape\n*/\nfunction jsonShape(options) {\n\treturn {\n\t\ttype: \"json\",\n\t\tdescription: options?.description\n\t};\n}\n/**\n* Build a {@link RawShape} from a JSON Schema fragment.\n*\n* @remarks\n* For values the shape DSL can't express. The compiled guard accepts any value;\n* the parser passes it through; the schema is emitted verbatim.\n*\n* @param schema - The JSON Schema fragment to embed\n* @returns A raw shape\n*/\nfunction rawShape(schema) {\n\treturn {\n\t\ttype: \"raw\",\n\t\tschema\n\t};\n}\n//#endregion\nexport { JSON_SCHEMA_TYPES, andOf, arrayOf, arrayShape, attempt, booleanShape, boundsOf, compileGenerator, compileGuard, compileParser, compileSchema, complementOf, createContract, enumOf, enumerableSymbolCount, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isConstructor, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFalse, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterableOf, jsonShape, keyOf, lazyOf, literalOf, literalShape, mapOf, matchOf, notOf, nullShape, nullableOf, nullableShape, numberShape, objectShape, omitOf, oneOfShape, optionalOf, optionalShape, orOf, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pickOf, rawShape, recordOf, recordShape, resolveField, schemaToParameters, seededRandom, setOf, stringOf, stringShape, transformOf, tupleOf, unionOf, unionShape, validateShape, whereOf };\n\n//# sourceMappingURL=index.js.map","import type {\n\tAcceptEntry,\n\tBodyOptions,\n\tCookieOptions,\n\tEncoding,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tNextFunction,\n\tRangeSpec,\n\tSSEMessage,\n\tStreamInterface,\n\tStreamOptions,\n\tTokenOptions,\n\tTokenSecret,\n} from './types.js'\nimport { isRecord, isString, parseJSON } from '@orkestrel/contract'\nimport {\n\tCOMPRESSIBLE_TYPES,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DECOMPRESSED_LIMIT,\n\tREQUEST_ID_PATTERN,\n\tSSE_HEADERS,\n} from './constants.js'\nimport { ContentTooLargeError, HTTPError } from './errors.js'\n\n// The middleware seam's composition engine (AGENTS §5 — a pure function, not a\n// class: `compose` has no instance state, so it lives here rather than as an\n// entity). The RETURNING onion (§5.1 of the proposal): each middleware may\n// transform the request (`next(newRequest)`), transform the response (`await\n// next()` then mutate the result), or short-circuit (return without calling\n// `next`) — no mutable framework object anywhere. The double-`next` guard\n// (calling `next` twice within one middleware invocation) rejects, preserving\n// the old spine's crown-jewel invariant that each link runs the chain at most\n// once.\n\n/**\n * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`\n * handler into one request handler — the frozen middleware seam (§5.1).\n *\n * @remarks\n * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`\n * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes\n * `terminal`. Each middleware's `next` may be called with a substituted\n * `Request` (the downstream chain then sees that request instead of the\n * original), called with no argument (the original request continues\n * downstream), or NOT called at all (a short-circuit — the middleware's own\n * returned `Response` is sent, and everything downstream never runs). A\n * SECOND call to the same `next` within one middleware invocation REJECTS —\n * each link runs the chain at most once, so a middleware cannot fork the\n * request into two divergent downstream runs.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param middleware - The ordered chain, outermost first\n * @param terminal - The innermost handler the chain ultimately reaches\n * @returns A single `(request, context) => Promise<Response>` handler running the whole onion\n *\n * @example\n * ```ts\n * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {\n * \tconst response = await next()\n * \tresponse.headers.set('X-Powered-By', 'orkestrel')\n * \treturn response\n * }\n *\n * const handle = compose([withHeader], async () => new Response('ok'))\n * ```\n */\nexport function compose<TState>(\n\tmiddleware: readonly MiddlewareHandler<TState>[],\n\tterminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\treturn async (request: Request, context: MiddlewareContext<TState>): Promise<Response> => {\n\t\tconst dispatch = (index: number, currentRequest: Request): Promise<Response> => {\n\t\t\tconst layer = middleware[index]\n\t\t\tif (layer === undefined) return terminal(currentRequest, context)\n\t\t\tlet called = false\n\t\t\tconst next: NextFunction = (nextRequest?: Request): Promise<Response> => {\n\t\t\t\tif (called) return Promise.reject(new Error('next() was already called by this middleware'))\n\t\t\t\tcalled = true\n\t\t\t\treturn dispatch(index + 1, nextRequest ?? currentRequest)\n\t\t\t}\n\t\t\treturn Promise.resolve(layer(currentRequest, context, next))\n\t\t}\n\t\treturn dispatch(0, request)\n\t}\n}\n\n// The cookie machinery (AGENTS §4.3 module-scope helpers) — `parseCookies`\n// decodes a raw `Cookie:` header into a name→value lookup; `serializeCookie`\n// builds a spec-shaped `Set-Cookie` value with its attributes. The SIGNED\n// pair reuses the shipped HMAC token primitives rather than a second HMAC\n// scheme: `writeSignedCookie` is `serializeCookie(name, await signToken(value,\n// { secret }))` appended to a `Headers`, and `readSignedCookie` is `await\n// verifyToken(parseCookies(...)[name], secret)` — so a cookie is just a\n// `signToken` value in a `Set-Cookie`, with the SAME secret rotation + tamper\n// rejection. Every reader narrows untrusted request input with `typeof`,\n// never `as` (§14), and total on hostile input.\n\n/**\n * Parse a raw `Cookie:` request header into a `name → value` lookup.\n *\n * @remarks\n * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine\n * cookie-pair separator never precedes it), while every later segment has its\n * inter-pair separator (ASCII space/tab) stripped before parsing — so a\n * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by\n * {@link isCookieName} rather than silently reconciling into a\n * prefix-protected `__Host-` name. A pair without `=`, or with an invalid\n * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/\n * malformed header yields an empty record, never throws (AGENTS §14).\n *\n * @param header - The raw `Cookie` header value (possibly `undefined`)\n * @returns A record of every parsed cookie, `name → decoded value`\n *\n * @example\n * ```ts\n * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }\n * ```\n */\nexport function parseCookies(header: string | undefined): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tif (header === undefined) return out\n\tconst segments = header.split(';')\n\tfor (let index = 0; index < segments.length; index += 1) {\n\t\tconst raw = segments[index] ?? ''\n\t\tconst segment = index === 0 ? raw : raw.replace(/^[ \\t]+/, '')\n\t\tconst eq = segment.indexOf('=')\n\t\tif (eq < 0) continue\n\t\tconst name = segment.slice(0, eq)\n\t\tif (!isCookieName(name)) continue\n\t\tout[name] = decodeCookieValue(segment.slice(eq + 1).trim())\n\t}\n\treturn out\n}\n\n/**\n * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of\n * cookie-token chars with NO surrounding (or interior) whitespace.\n *\n * @remarks\n * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$` —\n * which excludes every whitespace char (ASCII and Unicode) plus controls,\n * separators, and `=`. The {@link parseCookies} hardening that stops a\n * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.\n *\n * @param value - The candidate cookie name\n * @returns `true` when `value` is a valid, whitespace-free cookie token\n *\n * @example\n * ```ts\n * isCookieName('__Host-session') // true\n * isCookieName(' __Host-session') // false — whitespace-padded\n * ```\n */\nexport function isCookieName(value: string): boolean {\n\treturn /^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$/.test(value)\n}\n\n/**\n * Decode a cookie value with `decodeURIComponent`, falling back to the raw\n * text when the value is not valid percent-encoding.\n *\n * @param raw - The raw (trimmed) cookie value\n * @returns The URL-decoded value, or the raw value when decoding would throw\n *\n * @example\n * ```ts\n * decodeCookieValue('a%20b') // 'a b'\n * decodeCookieValue('%') // '%' — malformed escape stays literal\n * ```\n */\nexport function decodeCookieValue(raw: string): string {\n\ttry {\n\t\treturn decodeURIComponent(raw)\n\t} catch {\n\t\treturn raw\n\t}\n}\n\n/**\n * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE\n * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two\n * attributes with before emitting them.\n *\n * @remarks\n * Rejects a value carrying a `;` (splits attributes), a `,` (can split a\n * folded header), ASCII/Unicode whitespace, or a C0/DEL control char\n * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`\n * directive. Total — never throws (a bad value returns `false`).\n *\n * @param value - The candidate attribute value (a `Domain` or `Path`)\n * @returns `true` when `value` carries no separator / whitespace / control char\n *\n * @example\n * ```ts\n * isCookieAttribute('/app') // true\n * isCookieAttribute('/a\\r\\nSet-Cookie: x=y') // false\n * ```\n */\nexport function isCookieAttribute(value: string): boolean {\n\tfor (const char of value) {\n\t\tif (char === ';' || char === ',' || /\\s/.test(char)) return false\n\t\tconst code = char.codePointAt(0)\n\t\tif (code !== undefined && (code < 0x20 || code === 0x7f)) return false\n\t}\n\treturn true\n}\n\n/**\n * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.\n *\n * @remarks\n * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and\n * appends the present {@link CookieOptions} attributes in canonical order:\n * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`\n * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated\n * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an\n * injection attempt (a programmer misconfiguration, AGENTS §12 — never a\n * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of\n * the `secure` option (the spec requires it); an un-resolved `undefined`\n * `secure` here falls to OFF — request-aware callers resolve it first via\n * {@link resolveSecure}.\n *\n * @param name - The cookie name\n * @param value - The cookie value (URL-encoded into the output)\n * @param options - The {@link CookieOptions} attributes; see its fields for defaults\n * @returns The `Set-Cookie` header value\n * @throws {HTTPError} When `domain` or `path` carries an injection char\n *\n * @example\n * ```ts\n * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'\n * ```\n */\nexport function serializeCookie(name: string, value: string, options?: CookieOptions): string {\n\tconst sameSite = options?.sameSite ?? 'Lax'\n\tconst domain = options?.domain\n\tif (domain !== undefined && !isCookieAttribute(domain))\n\t\tthrow new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`)\n\tconst path = options?.path ?? '/'\n\tif (!isCookieAttribute(path))\n\t\tthrow new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`)\n\tconst secure = sameSite === 'None' || options?.secure === true\n\tconst parts = [`${name}=${encodeURIComponent(value)}`]\n\tif (domain !== undefined) parts.push(`Domain=${domain}`)\n\tparts.push(`Path=${path}`)\n\tif (options?.maxAge !== undefined) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`)\n\tif (options?.httpOnly !== false) parts.push('HttpOnly')\n\tif (secure) parts.push('Secure')\n\tparts.push(`SameSite=${sameSite}`)\n\treturn parts.join('; ')\n}\n\n/**\n * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}\n * `secure` setting and whether the request arrived over TLS.\n *\n * @remarks\n * `true` / `false` are explicit overrides. `undefined` (the secure default —\n * the option omitted) resolves to `encrypted` — `Secure` on a TLS\n * connection, off over plaintext HTTP — so a production HTTPS deployment\n * gets `Secure` automatically while local-dev HTTP still works.\n *\n * @param secure - The {@link CookieOptions} `secure` setting\n * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})\n * @returns The concrete `Secure` flag to emit\n *\n * @example\n * ```ts\n * resolveSecure(undefined, true) // true\n * resolveSecure(undefined, false) // false\n * resolveSecure(false, true) // false — explicit override wins\n * ```\n */\nexport function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean {\n\tif (secure === true || secure === false) return secure\n\treturn encrypted\n}\n\n/**\n * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT\n * clobbering a prior one.\n *\n * @remarks\n * `Headers.append` already accumulates repeated headers (unlike node's\n * `setHeader`), so this is a thin, self-documenting wrapper naming the\n * cookie-append intent — the primitive {@link writeSignedCookie} /\n * {@link clearCookie} use.\n *\n * @param headers - The response `Headers` to write into\n * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * appendCookie(headers, serializeCookie('a', '1'))\n * appendCookie(headers, serializeCookie('b', '2'))\n * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'\n * ```\n */\nexport function appendCookie(headers: Headers, cookie: string): void {\n\theaders.append('set-cookie', cookie)\n}\n\n/**\n * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append\n * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).\n *\n * @remarks\n * The cookie value is `await signToken(value, { secret })`\n * (`<payload>.<signature>`), so a signed cookie is a stateless token in a\n * cookie — the same secret rotation and tamper rejection, no second HMAC\n * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto\n * signing is asynchronous (§3 of the proposal).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name\n * @param value - The opaque value to sign into the cookie\n * @param secret - The {@link TokenSecret} to sign with (the first secret signs)\n * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * await writeSignedCookie(headers, 'session', 'user-1', 'secret')\n * ```\n */\nexport async function writeSignedCookie(\n\theaders: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: TokenSecret,\n\toptions?: CookieOptions,\n): Promise<void> {\n\tappendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options))\n}\n\n/**\n * Read + verify a SIGNED cookie off a request — TOTAL, returning the\n * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).\n *\n * @remarks\n * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,\n * and verifies it with {@link verifyToken} against `secret` (a rotation list\n * accepts a cookie signed by any of its secrets). ANY failure — an absent\n * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.\n *\n * @param request - The `Request` to read the `Cookie` header from\n * @param name - The cookie name to read\n * @param secret - The {@link TokenSecret} (or rotation list) to verify against\n * @returns The embedded value when the cookie is present + valid, else `undefined`\n *\n * @example\n * ```ts\n * const value = await readSignedCookie(request, 'session', 'secret')\n * ```\n */\nexport async function readSignedCookie(\n\trequest: Request,\n\tname: string,\n\tsecret: TokenSecret,\n): Promise<string | undefined> {\n\tconst cookie = parseCookies(request.headers.get('cookie') ?? undefined)[name]\n\treturn cookie === undefined ? undefined : verifyToken(cookie, secret)\n}\n\n/**\n * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).\n *\n * @remarks\n * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the\n * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops\n * a cookie when those MATCH the one it set).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name to clear\n * @param options - The {@link CookieOptions} that must match the original cookie\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * clearCookie(headers, 'session')\n * ```\n */\nexport function clearCookie(headers: Headers, name: string, options?: CookieOptions): void {\n\tappendCookie(headers, serializeCookie(name, '', { ...options, maxAge: 0 }))\n}\n\n// The stateless signed-token primitives over WebCrypto (AGENTS §4.3 module-\n// scope helpers, §3 of the proposal). A token is `<payload>.<signature>`: the\n// payload a base64url JSON `{ value, exp? }`, the signature an HMAC-SHA256 of\n// the payload under the secret. Signing always uses the FIRST secret (a\n// rotation list's current head); verifying accepts ANY secret in the list,\n// via `crypto.subtle.verify` — constant-time internally, so the old\n// `safeCompare` is RETIRED, never ported. `verifyToken` is TOTAL (never\n// throws — adversarial input returns `undefined`, AGENTS §14); only\n// `signToken` throws, and only on a misconfigured (empty) secret.\n\n/**\n * Base64url-encode a byte sequence — the payload encoding {@link signToken} /\n * {@link verifyToken} use, and the signature encoding for the HMAC.\n *\n * @param bytes - The bytes to encode\n * @returns The base64url string (no padding)\n *\n * @example\n * ```ts\n * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'\n * ```\n */\nexport function encodeBase64Url(bytes: Uint8Array): string {\n\tlet binary = ''\n\tfor (const byte of bytes) binary += String.fromCharCode(byte)\n\treturn btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Decode a base64url string back into its bytes — the inverse of\n * {@link encodeBase64Url}.\n *\n * @remarks\n * Restores the standard base64 alphabet + padding before decoding with\n * `atob`. THROWS `DOMException` on a malformed input — callers on the\n * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).\n *\n * @param value - The base64url string to decode\n * @returns The decoded bytes\n * @throws {DOMException} When `value` is not valid base64url\n *\n * @example\n * ```ts\n * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'\n * ```\n */\nexport function decodeBase64Url(value: string): Uint8Array<ArrayBuffer> {\n\tconst restored = value.replace(/-/g, '+').replace(/_/g, '/')\n\tconst padding = restored.length % 4 === 0 ? '' : '='.repeat(4 - (restored.length % 4))\n\tconst binary = atob(restored + padding)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)\n\treturn bytes\n}\n\n/**\n * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.\n *\n * @remarks\n * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the\n * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so\n * the expiry is HMAC-COVERED — a client cannot extend it without invalidating\n * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST\n * {@link TokenSecret} (the current secret, or the head of a rotation list).\n * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a\n * misconfigured secret with no usable entry THROWS an {@link HTTPError}\n * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with\n * {@link verifyToken}. Omitting `ttl` mints a token that never expires.\n *\n * @param value - The opaque value to embed (a session id, a deployment marker)\n * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}\n * @returns The signed `<payload>.<signature>` token string\n * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry\n *\n * @example\n * ```ts\n * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })\n * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined\n * ```\n */\nexport async function signToken(value: string, options: TokenOptions): Promise<string> {\n\tconst secrets = normalizeSecret(options.secret)\n\tconst secret = secrets[0]\n\tif (secret === undefined) throw new HTTPError(500, 'signToken requires at least one secret')\n\tconst exp = options.ttl !== undefined ? Date.now() + options.ttl : undefined\n\tconst encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({ value, exp })))\n\tconst key = await crypto.subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(secret),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign'],\n\t)\n\tconst signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(encoded))\n\treturn `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`\n}\n\n/**\n * Verify a stateless token and return its embedded value — TOTAL, never throws.\n *\n * @remarks\n * The inverse of {@link signToken}: splits the token on its LAST `.` (so a\n * value containing dots survives), and checks the payload's HMAC-SHA256\n * signature against EACH {@link TokenSecret} candidate via\n * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is\n * retired, §3 of the proposal), accepting the token on the first match (the\n * rotation path). It then decodes + narrows the payload (`isRecord` +\n * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,\n * rejects an expired token. ANY failure — a malformed token, a bad signature,\n * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —\n * yields `undefined` rather than throwing.\n *\n * @param token - The candidate token string (from a request header/cookie)\n * @param secret - The {@link TokenSecret} (or rotation list) to verify against\n * @returns The embedded value when the token is valid + unexpired, else `undefined`\n *\n * @example\n * ```ts\n * await verifyToken('bad.token', 'shh') // undefined — never throws\n * ```\n */\nexport async function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined> {\n\tconst secrets = normalizeSecret(secret)\n\tif (secrets.length === 0) return undefined\n\tconst dot = token.lastIndexOf('.')\n\tif (dot < 0) return undefined\n\tconst encoded = token.slice(0, dot)\n\tconst signatureText = token.slice(dot + 1)\n\ttry {\n\t\tconst signature = decodeBase64Url(signatureText)\n\t\tconst data = new TextEncoder().encode(encoded)\n\t\tfor (const candidate of secrets) {\n\t\t\tconst key = await crypto.subtle.importKey(\n\t\t\t\t'raw',\n\t\t\t\tnew TextEncoder().encode(candidate),\n\t\t\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\t\t\tfalse,\n\t\t\t\t['verify'],\n\t\t\t)\n\t\t\tconst matched = await crypto.subtle.verify('HMAC', key, signature, data)\n\t\t\tif (matched) return decodeTokenPayload(encoded)\n\t\t}\n\t\treturn undefined\n\t} catch {\n\t\t// A malformed base64url signature/payload is just an invalid token — stay total.\n\t\treturn undefined\n\t}\n}\n\n/**\n * Decode + narrow a signed token's base64url JSON payload, honoring its\n * expiry — the shared decode step {@link verifyToken} applies after a\n * signature match.\n *\n * @remarks\n * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a\n * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.\n * TOTAL — any decode/shape/expiry failure yields `undefined`.\n *\n * @param encoded - The base64url-encoded payload segment (before the last `.`)\n * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`\n */\nexport function decodeTokenPayload(encoded: string): string | undefined {\n\ttry {\n\t\tconst text = new TextDecoder().decode(decodeBase64Url(encoded))\n\t\tconst payload: unknown = JSON.parse(text)\n\t\tif (!isRecord(payload)) return undefined\n\t\tif (typeof payload.value !== 'string') return undefined\n\t\tif (payload.exp !== undefined && typeof payload.exp !== 'number') return undefined\n\t\tif (payload.exp !== undefined && Date.now() >= payload.exp) return undefined\n\t\treturn payload.value\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —\n * backs both {@link signToken} and {@link verifyToken}.\n *\n * @remarks\n * A single string becomes a one-element list; a rotation list is copied. Any\n * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that\n * emptiness test; each kept secret is stored VERBATIM). The first kept\n * element is the signing secret; all kept are accepted on verify.\n *\n * @param secret - The {@link TokenSecret} (a single string, or a rotation list)\n * @returns The kept (non-blank) secrets, in order — empty when none is usable\n *\n * @example\n * ```ts\n * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']\n * ```\n */\nexport function normalizeSecret(secret: TokenSecret): readonly string[] {\n\tconst list = typeof secret === 'string' ? [secret] : [...secret]\n\treturn list.filter((entry) => entry.trim().length > 0)\n}\n\n// The content-negotiation helpers (AGENTS §4.3 module-scope, §5) — the ONE\n// shared q-value parser behind the `Negotiator` (U3) and any future\n// compression middleware's `Accept-Encoding` pick.\n\n/**\n * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header\n * into its q-sorted entries.\n *\n * @remarks\n * Splits on `,`; for each part takes the token before the first `;`\n * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the\n * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls\n * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must\n * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving\n * the header's own order within a tie — a single pass with no backtracking,\n * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an\n * empty/malformed header yields `[]`/best-effort entries, never throws.\n *\n * @param header - The raw weighted header value\n * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending\n *\n * @example\n * ```ts\n * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')\n * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]\n * ```\n */\nexport function parseAcceptHeader(header: string): readonly AcceptEntry[] {\n\tconst entries: AcceptEntry[] = []\n\tfor (const part of header.split(',')) {\n\t\tconst trimmed = part.trim()\n\t\tif (trimmed.length === 0) continue\n\t\tconst semicolon = trimmed.indexOf(';')\n\t\tconst value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase()\n\t\tif (value.length === 0) continue\n\t\tlet q = 1\n\t\tif (semicolon !== -1) {\n\t\t\tconst match = /;\\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon))\n\t\t\tif (match !== null) {\n\t\t\t\tconst parsed = Number(match[1])\n\t\t\t\tif (Number.isFinite(parsed)) q = Math.min(1, Math.max(0, parsed))\n\t\t\t}\n\t\t}\n\t\tentries.push({ value, q })\n\t}\n\treturn entries\n\t\t.map((entry, index) => ({ entry, index }))\n\t\t.sort((a, b) => b.entry.q - a.entry.q || a.index - b.index)\n\t\t.map((ranked) => ranked.entry)\n}\n\n/**\n * The client's quality (q) for one content-coding from the parsed\n * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s\n * server-preference selection.\n *\n * @remarks\n * Prefers an EXACT named match (including an explicit `;q=0` rejection);\n * failing that, a bare `*` wildcard's q applies. A coding that is neither\n * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins\n * over a `*` (a specific rejection beats the wildcard), so it scores `0`.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param coding - The candidate coding to score\n * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5\n * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1\n * ```\n */\nexport function codingQuality(entries: readonly AcceptEntry[], coding: string): number {\n\tconst named = entries.find((entry) => entry.value === coding)\n\tif (named !== undefined) return named.q\n\tconst wildcard = entries.find((entry) => entry.value === '*')\n\treturn wildcard?.q ?? 0\n}\n\n/**\n * Select the best content-coding for an `Accept-Encoding` header from the\n * codings the server offers.\n *\n * @remarks\n * Parses the header ({@link parseAcceptHeader}) and scores each `available`\n * coding in the SERVER's preference order ({@link codingQuality}), keeping\n * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a\n * client-side tie). Returns `undefined` when the client accepts none of\n * `available` (identity — no compression). TOTAL on hostile input.\n *\n * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)\n * @param header - The raw `Accept-Encoding` header value\n * @param available - The codings the server offers, in preference (tie-break) order\n * @returns The negotiated coding, or `undefined` when none of `available` is acceptable\n *\n * @example\n * ```ts\n * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'\n * ```\n */\nexport function negotiateEncoding<T extends string>(\n\theader: string,\n\tavailable: readonly T[],\n): T | undefined {\n\tif (available.length === 0) return undefined\n\tconst entries = parseAcceptHeader(header)\n\tlet best: T | undefined\n\tlet bestQuality = 0\n\tfor (const coding of available) {\n\t\tconst quality = codingQuality(entries, coding)\n\t\tif (quality > bestQuality) {\n\t\t\tbest = coding\n\t\t\tbestQuality = quality\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * Rank + quality of one `candidate` media type against the parsed `Accept`\n * entries — the generic media-type primitive the `Negotiator`'s `negotiate`\n * uses to score each `available` candidate.\n *\n * @remarks\n * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the\n * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact\n * `;q=0` entry explicitly rejects the candidate outright (returns\n * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own\n * (less specific) coverage, so a later more-specific match can still allow\n * it. Among multiple matching entries, the lowest `rank` wins, and among a\n * rank tie the highest `q` wins.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate media type to score (e.g. `'text/html'`)\n * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches\n *\n * @example\n * ```ts\n * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')\n * // { q: 1, rank: 0 }\n * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }\n * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined\n * ```\n */\nexport function matchMediaType(\n\tentries: readonly AcceptEntry[],\n\tcandidate: string,\n): { readonly q: number; readonly rank: number } | undefined {\n\tconst slash = candidate.indexOf('/')\n\tconst type = slash === -1 ? candidate : candidate.slice(0, slash)\n\tlet best: { readonly q: number; readonly rank: number } | undefined\n\tfor (const entry of entries) {\n\t\tlet rank: number | undefined\n\t\tif (entry.value === candidate) rank = 0\n\t\telse if (entry.value === `${type}/*`) rank = 1\n\t\telse if (entry.value === '*/*') rank = 2\n\t\tif (rank === undefined) continue\n\t\tif (entry.q === 0) {\n\t\t\t// An exact `;q=0` explicitly rejects this candidate outright; a\n\t\t\t// wildcard `;q=0` only rejects the wildcard's own (less specific)\n\t\t\t// coverage, so a later more-specific match can still allow it.\n\t\t\tif (rank === 0) return undefined\n\t\t\tcontinue\n\t\t}\n\t\tif (best === undefined || rank < best.rank || (rank === best.rank && entry.q > best.q)) {\n\t\t\tbest = { q: entry.q, rank }\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * The client's quality for one `candidate` language from the parsed\n * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.\n *\n * @remarks\n * Prefers an exact match, then a primary-tag prefix match (`en` accepts\n * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry\n * is an explicit rejection).\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate language tag to score (e.g. `'en-US'`)\n * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1\n * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix\n * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard\n * ```\n */\nexport function languageQuality(entries: readonly AcceptEntry[], candidate: string): number {\n\tconst lower = candidate.toLowerCase()\n\tconst primary = lower.split('-')[0]\n\tlet named: number | undefined\n\tlet prefixed: number | undefined\n\tlet wildcard: number | undefined\n\tfor (const entry of entries) {\n\t\tconst entryPrimary = entry.value.split('-')[0]\n\t\tif (entry.value === lower) named = entry.q\n\t\telse if (entryPrimary === primary) {\n\t\t\tif (prefixed === undefined) prefixed = entry.q\n\t\t} else if (entry.value === '*') wildcard = entry.q\n\t}\n\tif (named !== undefined) return named\n\tif (prefixed !== undefined) return prefixed\n\treturn wildcard ?? 0\n}\n\n/**\n * Whether a `Content-Type` is worth compressing.\n *\n * @remarks\n * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`\n * type, a `+json`/`+xml` structured suffix, or one of the explicit\n * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed\n * binary (`image/png`, `application/zip`) is NOT compressible. An\n * absent/empty type is not compressible. TOTAL.\n *\n * @param type - The response `Content-Type` header value (with or without parameters)\n * @returns `true` when the type is text-shaped and worth compressing\n *\n * @example\n * ```ts\n * isCompressibleType('application/json; charset=utf-8') // true\n * isCompressibleType('image/png') // false\n * ```\n */\nexport function isCompressibleType(type: string): boolean {\n\tconst semicolon = type.indexOf(';')\n\tconst bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase()\n\tif (bare.length === 0) return false\n\tif (bare.startsWith('text/')) return true\n\tif (bare.endsWith('+json') || bare.endsWith('+xml')) return true\n\treturn COMPRESSIBLE_TYPES.has(bare)\n}\n\n// The conditional-request helpers (AGENTS §4.3 module-scope, §5) — ETag\n// compute/compare (RFC 7232 §2.3.2 WEAK comparison) and the TOTAL `Range`\n// parser.\n\n/**\n * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.\n *\n * @remarks\n * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex\n * digest as a WEAK validator (`W/\"<hash>\"`) when `weak` is `true` — the\n * default, encoding-AGNOSTIC, so the tag survives a downstream content\n * re-encoding (gzip) and still matches on revalidation — or a STRONG one\n * (`\"<hash>\"`, byte-identity) when `weak` is `false`.\n *\n * @param body - The full (uncompressed) response body to hash\n * @param weak - `true` for a weak `W/\"…\"` validator (the default), `false` for a strong `\"…\"` one\n * @returns The `ETag` header value\n *\n * @example\n * ```ts\n * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/\"…sha256-hex…\"'\n * ```\n */\nexport async function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak = true): Promise<string> {\n\tconst digest = await crypto.subtle.digest('SHA-256', body)\n\tconst hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(\n\t\t'',\n\t)\n\treturn weak ? `W/\"${hex}\"` : `\"${hex}\"`\n}\n\n/**\n * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque\n * comparison body — the reduction {@link matchesETag} applies to both sides\n * before the RFC 7232 §2.3.2 weak comparison.\n *\n * @param tag - One entity-tag (`W/\"<body>\"` or `\"<body>\"`)\n * @returns The tag with any leading `W/` removed (the quotes preserved)\n *\n * @example\n * ```ts\n * unwrapETag('W/\"abc\"') // '\"abc\"'\n * ```\n */\nexport function unwrapETag(tag: string): string {\n\tconst trimmed = tag.trim()\n\treturn trimmed.startsWith('W/') ? trimmed.slice(2) : trimmed\n}\n\n/**\n * Whether a request's `If-None-Match` header matches a resource's current\n * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.\n *\n * @remarks\n * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY\n * listed tag matches), or the `*` wildcard (matches ANY current\n * representation — only a list of exactly `*` is the wildcard). Comparison is\n * WEAK: `W/\"abc\"` and `\"abc\"` are equal (both sides' weak prefix is stripped\n * via {@link unwrapETag} before comparing the opaque body). TOTAL — a\n * malformed/empty header matches nothing, never throws.\n *\n * @param header - The raw `If-None-Match` header value\n * @param etag - The resource's current `ETag`\n * @returns `true` when the conditional matches (the caller answers `304`)\n *\n * @example\n * ```ts\n * matchesETag('\"abc\", W/\"def\"', 'W/\"abc\"') // true — weak comparison\n * matchesETag('*', 'W/\"anything\"') // true — wildcard\n * ```\n */\nexport function matchesETag(header: string, etag: string): boolean {\n\tconst trimmed = header.trim()\n\tif (trimmed === '*') return true\n\tconst target = unwrapETag(etag)\n\tfor (const member of trimmed.split(',')) {\n\t\tconst candidate = member.trim()\n\t\tif (candidate.length === 0) continue\n\t\tif (unwrapETag(candidate) === target) return true\n\t}\n\treturn false\n}\n\n/**\n * Parse an HTTP `Range` request header against a known resource `size` —\n * TOTAL, returning a {@link RangeSpec} or `undefined`.\n *\n * @remarks\n * Handles the three single-range `bytes=` forms — closed (`start-end`), open\n * (`start-`), and suffix (`-suffixLength`) — clamping the window to\n * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns\n * `{ satisfiable: true, start, end }` for an overlapping range,\n * `{ satisfiable: false }` for a range wholly past the resource, and\n * `undefined` for the \"serve the whole resource\" case: an ABSENT header, a\n * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not\n * supported), or any malformed/non-finite bound. NEVER throws on a hostile\n * header.\n *\n * @param header - The raw `Range` header value\n * @param size - The resource's total byte length\n * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource\n *\n * @example\n * ```ts\n * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }\n * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused\n * ```\n */\nexport function parseRange(header: string | undefined, size: number): RangeSpec | undefined {\n\tif (header === undefined) return undefined\n\tconst match = /^bytes=(.*)$/.exec(header.trim())\n\tif (match === null) return undefined\n\tconst spec = match[1].trim()\n\tif (spec.includes(',')) return undefined\n\tconst dash = spec.indexOf('-')\n\tif (dash < 0) return undefined\n\tconst startText = spec.slice(0, dash).trim()\n\tconst endText = spec.slice(dash + 1).trim()\n\tif (startText === '') {\n\t\tconst suffix = Number(endText)\n\t\tif (endText === '' || !Number.isInteger(suffix) || suffix <= 0) return undefined\n\t\tif (size === 0) return { satisfiable: false }\n\t\tconst start = Math.max(0, size - suffix)\n\t\treturn { satisfiable: true, start, end: size - 1 }\n\t}\n\tconst start = Number(startText)\n\tif (!Number.isInteger(start) || start < 0) return undefined\n\tif (start >= size) return { satisfiable: false }\n\tif (endText === '') return { satisfiable: true, start, end: size - 1 }\n\tconst end = Number(endText)\n\tif (!Number.isInteger(end) || end < start) return undefined\n\treturn { satisfiable: true, start, end: Math.min(end, size - 1) }\n}\n\n// The security primitives (AGENTS §4.3 module-scope, §5) — CORS origin\n// resolution, `Vary` merging, security-header resolution, request-id\n// validation, and the IPv6 `/64` rate-key collapse.\n\n/**\n * Resolve the `Access-Control-Allow-Origin` value for a request.\n *\n * @remarks\n * `'*'` and a single origin string pass straight through. An allow-list\n * echoes the request's `Origin` only when it is present in the list, else\n * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent\n * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is\n * NEVER reflected even if `'null'` were listed, closing the hostile-context\n * cross-origin-access hole.\n *\n * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list\n * @param requestOrigin - The request's `Origin` header value, if present\n * @returns The allow-origin value to send, or `undefined` to set no header\n *\n * @example\n * ```ts\n * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'\n * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected\n * ```\n */\nexport function resolveOrigin(\n\torigin: string | readonly string[],\n\trequestOrigin: string | undefined,\n): string | undefined {\n\tif (isString(origin)) return origin\n\tif (!isString(requestOrigin)) return undefined\n\tif (requestOrigin === 'null') return undefined\n\treturn origin.includes(requestOrigin) ? requestOrigin : undefined\n}\n\n/**\n * Merge a `Vary` value into an existing `Vary` header without duplication.\n *\n * @remarks\n * Splits `existing` on `,`, trims each member, and appends `value` only when\n * no existing member already matches it case-insensitively (`Vary` header\n * names are case-insensitive). Preserves the existing members' order and\n * appends the new one last.\n *\n * @param existing - The current `Vary` header value, if any\n * @param value - The header name to ensure is listed\n * @returns The merged `Vary` value\n *\n * @example\n * ```ts\n * mergeVary(undefined, 'Origin') // 'Origin'\n * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)\n * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'\n * ```\n */\nexport function mergeVary(existing: string | undefined, value: string): string {\n\tconst members =\n\t\texisting === undefined\n\t\t\t? []\n\t\t\t: existing\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((member) => member.trim())\n\t\t\t\t\t.filter((member) => member.length > 0)\n\tconst present = members.some((member) => member.toLowerCase() === value.toLowerCase())\n\treturn present ? members.join(', ') : [...members, value].join(', ')\n}\n\n/**\n * Resolve one opt-out, value-bearing security header.\n *\n * @remarks\n * The shared \"a `string` value, or `false` to omit, or a default when unset\"\n * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):\n * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that\n * override, `undefined` (unset) ⇒ `fallback` (the secure default).\n *\n * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default\n * @param fallback - The secure-default value used when `value` is unset\n * @returns The header value to set, or `undefined` to omit the header\n *\n * @example\n * ```ts\n * resolveSecurityHeader(undefined, 'DENY') // 'DENY'\n * resolveSecurityHeader(false, 'DENY') // undefined — omitted\n * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override\n * ```\n */\nexport function resolveSecurityHeader(\n\tvalue: string | false | undefined,\n\tfallback: string,\n): string | undefined {\n\tif (value === false) return undefined\n\treturn value ?? fallback\n}\n\n/**\n * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response\n * header + `context.state`.\n *\n * @remarks\n * A request id is echoed RAW into a response header and log lines, so an\n * untrusted one is a header-injection + log-injection + DoS vector. This\n * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}\n * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).\n * TOTAL — never throws.\n *\n * @param value - The candidate incoming request id\n * @returns `true` when `value` is a safe, bounded, charset-clean correlation id\n *\n * @example\n * ```ts\n * isValidRequestId('req_abc-123') // true\n * isValidRequestId('bad\\r\\nheader') // false\n * ```\n */\nexport function isValidRequestId(value: string): boolean {\n\treturn REQUEST_ID_PATTERN.test(value)\n}\n\n/**\n * Compute the `/64` network of a full IPv6 address, or `undefined` when the\n * input is not a plain IPv6 address to collapse.\n *\n * @remarks\n * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4\n * is the identity) or any string that does not expand to exactly eight\n * hextets. Expands a single `::` into the missing zero hextets, takes the\n * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading\n * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped\n * first. Total — a malformed address returns `undefined`.\n *\n * @param address - The candidate IPv6 address\n * @returns The `/64` network string, or `undefined` when not a plain IPv6 address\n *\n * @example\n * ```ts\n * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'\n * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed\n * ```\n */\nexport function ipv6Network(address: string): string | undefined {\n\tif (/^::ffff:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/i.test(address)) return undefined\n\tconst percent = address.indexOf('%')\n\tconst bare = percent === -1 ? address : address.slice(0, percent)\n\tconst halves = bare.split('::')\n\tif (halves.length > 2) return undefined\n\tconst head = halves[0] === '' ? [] : halves[0].split(':')\n\tconst tail = halves.length === 2 ? (halves[1] === '' ? [] : halves[1].split(':')) : []\n\tlet groups: string[]\n\tif (halves.length === 2) {\n\t\tconst missing = 8 - head.length - tail.length\n\t\tif (missing < 0) return undefined\n\t\tgroups = [...head, ...Array.from({ length: missing }, () => '0'), ...tail]\n\t} else {\n\t\tgroups = head\n\t}\n\tif (groups.length !== 8) return undefined\n\tconst prefix: string[] = []\n\tfor (const group of groups.slice(0, 4)) {\n\t\tif (!/^[0-9a-fA-F]{1,4}$/.test(group)) return undefined\n\t\tprefix.push(Number.parseInt(group, 16).toString(16))\n\t}\n\treturn `${prefix.join(':')}::/64`\n}\n\n/**\n * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to\n * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.\n *\n * @remarks\n * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a\n * per-`/128` rate limit is trivially bypassed by rotating host bits — the\n * real identity is the `/64` network. Delegates the IPv6 collapse to\n * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,\n * a malformed string) is kept unchanged.\n *\n * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})\n * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged\n *\n * @example\n * ```ts\n * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'\n * clientRateKey('192.0.2.1') // '192.0.2.1'\n * ```\n */\nexport function clientRateKey(address: string): string {\n\treturn ipv6Network(address) ?? address\n}\n\n// The Server-Sent-Events seam (AGENTS §4.3 module-scope, §5.4 of the\n// proposal) — `serializeEvent` is the wire encoder (the exact inverse of a\n// consuming SSE parser); `openStream` is the generic `Response`-returning\n// stream handle any streaming route (SSE today, a future producer tomorrow)\n// opens over a `ReadableStream`.\n\n/**\n * Serialize one {@link SSEMessage} to the SSE wire.\n *\n * @remarks\n * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE\n * `data:` line per CRLF-aware-split (`\\r\\n` / `\\r` / `\\n`) segment of `data`\n * (so a consuming parser's multi-`data` concat reproduces the original\n * `data` exactly, and no raw `\\r` or `\\n` can ever ride onto the wire inside\n * a `data:` line), then the terminating blank line.\n *\n * @param message - The event to serialize\n * @returns The SSE wire text for the event (terminated by a blank line)\n *\n * @example\n * ```ts\n * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\\ndata: hello\\n\\n'\n * serializeEvent({ data: 'multi\\nline' }) // 'data: multi\\ndata: line\\n\\n'\n * ```\n */\nexport function serializeEvent(message: SSEMessage): string {\n\tconst lines: string[] = []\n\tif (message.event !== undefined) lines.push(`event: ${message.event}`)\n\tif (message.id !== undefined) lines.push(`id: ${message.id}`)\n\tif (message.retry !== undefined) lines.push(`retry: ${message.retry}`)\n\tfor (const segment of message.data.split(/\\r\\n|\\r|\\n/)) lines.push(`data: ${segment}`)\n\treturn `${lines.join('\\n')}\\n\\n`\n}\n\n/**\n * Open a generic Server-Sent-Events stream — a fetch-standard `Response`\n * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.\n *\n * @remarks\n * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}\n * merged under any `options.headers` (a seam-owned key is never overridden),\n * at `options.status` (default `200`). The returned {@link StreamInterface}'s\n * `write` serializes one message ({@link serializeEvent}) and enqueues it;\n * `comment` writes a `: text` keep-alive line a conforming parser ignores;\n * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended\n * by `end()`, or the consumer cancelled the stream), so a late write never\n * throws.\n *\n * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}\n * @returns The {@link StreamInterface} handle\n *\n * @example\n * ```ts\n * const stream = openStream()\n * stream.write({ event: 'token', data: 'hello' })\n * stream.end()\n * // return stream.response from the route handler\n * ```\n */\nexport function openStream(options?: StreamOptions): StreamInterface {\n\tconst encoder = new TextEncoder()\n\tlet closed = false\n\tlet controller: ReadableStreamDefaultController<Uint8Array> | undefined\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(streamController) {\n\t\t\tcontroller = streamController\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true\n\t\t},\n\t})\n\tconst headers = new Headers({ ...SSE_HEADERS, ...options?.headers })\n\tconst response = new Response(body, { status: options?.status ?? 200, headers })\n\tconst enqueue = (text: string): void => {\n\t\tif (closed || controller === undefined) return\n\t\tcontroller.enqueue(encoder.encode(text))\n\t}\n\treturn {\n\t\tresponse,\n\t\tget closed(): boolean {\n\t\t\treturn closed\n\t\t},\n\t\twrite(message: SSEMessage): void {\n\t\t\tenqueue(serializeEvent(message))\n\t\t},\n\t\tcomment(text: string): void {\n\t\t\tenqueue(`: ${text}\\n\\n`)\n\t\t},\n\t\tend(): void {\n\t\t\tif (closed) return\n\t\t\tclosed = true\n\t\t\tcontroller?.close()\n\t\t},\n\t}\n}\n\n// The body pipeline (AGENTS §4.3 module-scope, §5.4 of the proposal) —\n// `readBody` collects a request body capped at `limit` bytes (413 over),\n// transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n// through a byte-counting `TransformStream` that ABORTS the instant\n// decompressed output exceeds `decompression` (the zip-bomb defense — fail\n// BEFORE materializing the bomb, since `DecompressionStream` has no\n// `maxOutputLength` knob), then decodes by content type. `scrubPrototype` /\n// `isDangerousKey` are the prototype-pollution scrub `readBody` applies to a\n// parsed JSON body, ported verbatim (pure value-walking logic, unaffected by\n// the fetch-vocabulary migration).\n\n/**\n * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,\n * or `prototype` — the three keys that, assigned onto a normal object, can\n * reach and mutate `Object.prototype`.\n *\n * @param key - The candidate object key\n * @returns `true` when `key` is one of the three prototype-pollution keys\n *\n * @example\n * ```ts\n * isDangerousKey('__proto__') // true\n * isDangerousKey('name') // false\n * ```\n */\nexport function isDangerousKey(key: string): boolean {\n\treturn key === '__proto__' || key === 'constructor' || key === 'prototype'\n}\n\n/**\n * Recursively STRIP the prototype-pollution keys from a parsed value IN\n * PLACE.\n *\n * @remarks\n * `JSON.parse('{\"__proto__\":{…}}')` is benign on its own — it produces an OWN,\n * enumerable `__proto__` DATA property — but that own key becomes a\n * pollution gadget the moment a downstream deep-merge copies it onto a live\n * object. This walks the value and `delete`s any own {@link isDangerousKey}\n * key at every depth, recursing into nested objects + array elements.\n * Primitives/`null` pass through untouched. Total — never throws. Mutates the\n * freshly-parsed value (which nothing else holds yet).\n *\n * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)\n * @returns The same `value`, with every dangerous key removed at every depth\n *\n * @example\n * ```ts\n * scrubPrototype(JSON.parse('{\"__proto__\":{\"polluted\":true},\"name\":\"ok\"}'))\n * // { name: 'ok' } — the __proto__ key is gone\n * ```\n */\nexport function scrubPrototype(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\tfor (const item of value) scrubPrototype(item)\n\t\treturn value\n\t}\n\tif (isRecord(value)) {\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tif (isDangerousKey(key)) {\n\t\t\t\tReflect.deleteProperty(value, key)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tscrubPrototype(value[key])\n\t\t}\n\t\treturn value\n\t}\n\treturn value\n}\n\n/**\n * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.\n *\n * @remarks\n * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,\n * throwing a {@link ContentTooLargeError} (413) the instant the running total\n * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than\n * collecting an unbounded body. A bodyless request (`request.body === null`)\n * resolves an empty array. A non-positive `limit` means unbounded.\n *\n * @param request - The `Request` to drain\n * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded\n * @returns The full request body as one `Uint8Array`\n * @throws {ContentTooLargeError} When the body exceeds `limit`\n *\n * @example\n * ```ts\n * const bytes = await collectRequestBody(request, 1_048_576)\n * ```\n */\nexport async function collectRequestBody(\n\trequest: Request,\n\tlimit: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tif (request.body === null) return new Uint8Array(0)\n\tconst reader = request.body.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet total = 0\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read()\n\t\tif (done) break\n\t\ttotal += value.byteLength\n\t\tif (limit > 0 && total > limit) {\n\t\t\tawait reader.cancel()\n\t\t\tthrow new ContentTooLargeError(limit)\n\t\t}\n\t\tchunks.push(value)\n\t}\n\tconst merged = new Uint8Array(total)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn merged\n}\n\n/**\n * Narrow a raw `Content-Encoding` header value to a decompressible\n * {@link Encoding} — the boundary guard {@link readBody} uses to decide\n * whether a request body needs transparent decompression.\n *\n * @remarks\n * Lower-cases + trims and returns the matching {@link Encoding} ONLY for\n * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of\n * the proposal). An absent header, `identity`, an unknown value, or a\n * comma-joined multi-coding all yield `undefined` (the body is read as-is).\n * TOTAL — never asserts the loose `string | null` header.\n *\n * @param header - The raw `Content-Encoding` header value\n * @returns The single decompressible {@link Encoding}, or `undefined` when none applies\n *\n * @example\n * ```ts\n * requestEncoding('gzip') // 'gzip'\n * requestEncoding('br') // undefined — unsupported by DecompressionStream\n * ```\n */\nexport function requestEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined {\n\tif (!isString(header)) return undefined\n\tconst value = header.trim().toLowerCase()\n\treturn value === 'gzip' || value === 'deflate' ? value : undefined\n}\n\n/**\n * Transparently decompress an already-collected, `gzip`/`deflate`-encoded\n * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —\n * the zip-bomb defense.\n *\n * @remarks\n * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting\n * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed\n * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`\n * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces\n * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated\n * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}\n * (never conflated with the cap). A non-positive `cap` means uncapped.\n *\n * @param bytes - The compressed bytes to decompress\n * @param encoding - The {@link Encoding} the bytes are compressed with\n * @param cap - The maximum decompressed byte count; a non-positive value means uncapped\n * @returns The decompressed bytes\n * @throws {ContentTooLargeError} When decompressed output would exceed `cap`\n * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)\n */\nexport async function decompressRequestBody(\n\tbytes: Uint8Array<ArrayBuffer>,\n\tencoding: Exclude<Encoding, 'identity'>,\n\tcap: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tlet total = 0\n\tconst capStream = new TransformStream<Uint8Array, Uint8Array>({\n\t\ttransform(chunk, controller) {\n\t\t\ttotal += chunk.byteLength\n\t\t\tif (cap > 0 && total > cap) {\n\t\t\t\tcontroller.error(new ContentTooLargeError(cap))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk)\n\t\t},\n\t})\n\tconst source = new ReadableStream<Uint8Array<ArrayBuffer>>({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue(bytes)\n\t\t\tcontroller.close()\n\t\t},\n\t})\n\tconst decompressed = source.pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream)\n\tconst reader = decompressed.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet size = 0\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (done) break\n\t\t\tchunks.push(value)\n\t\t\tsize += value.byteLength\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof ContentTooLargeError) throw error\n\t\tthrow new HTTPError(400, 'malformed compressed request body')\n\t}\n\tconst merged = new Uint8Array(size)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn merged\n}\n\n/**\n * Collect + decode a `Request` body — the shared body-collection pipeline\n * surfaced to middleware and handlers as the middleware context's cached\n * `body()`.\n *\n * @remarks\n * Collects the wire body capped at `options.limit` bytes ({@link\n * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),\n * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at\n * `options.decompression`, default {@link\n * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by\n * content type: `application/json` is parsed via `@orkestrel/contract`'s\n * `parseJSON` and scrubbed of prototype-pollution keys ({@link\n * scrubPrototype}); any other type decodes as UTF-8 text; an empty body\n * decodes to `undefined`.\n *\n * @param request - The `Request` to read the body from\n * @param options - The {@link BodyOptions} `limit` + `decompression` caps\n * @returns The parsed JSON value, the raw text, or `undefined` for an empty body\n * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap\n * @throws {HTTPError} When the compressed body is corrupt (400)\n *\n * @example\n * ```ts\n * const body = await readBody(request, { limit: 1_048_576 })\n * ```\n */\nexport async function readBody(request: Request, options?: BodyOptions): Promise<unknown> {\n\tconst limit = options?.limit ?? DEFAULT_BODY_LIMIT\n\tconst decompression = options?.decompression ?? DEFAULT_DECOMPRESSED_LIMIT\n\tconst wire = await collectRequestBody(request, limit)\n\tconst encoding = requestEncoding(request.headers.get('content-encoding'))\n\tconst bytes =\n\t\tencoding === undefined ? wire : await decompressRequestBody(wire, encoding, decompression)\n\tif (bytes.length === 0) return undefined\n\tconst contentType = request.headers.get('content-type')\n\tconst semicolon = contentType === null ? -1 : contentType.indexOf(';')\n\tconst bareType =\n\t\tcontentType === null\n\t\t\t? ''\n\t\t\t: (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase()\n\tconst text = new TextDecoder().decode(bytes)\n\tif (bareType === 'application/json') return scrubPrototype(parseJSON(text))\n\treturn text\n}\n","import type { Encoding, FormatHandlerMap, MiddlewareContext, NegotiatorInterface } from './types.js'\nimport { languageQuality, matchMediaType, negotiateEncoding, parseAcceptHeader } from './helpers.js'\n\n/**\n * The content-negotiation machine over the weighted `Accept` family — a\n * reusable, cross-middleware ENTITY (not a middleware). Implements exactly\n * {@link NegotiatorInterface}.\n *\n * @remarks\n * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /\n * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its\n * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the\n * rest of the substrate uses — one parser, never two. `format` reads the\n * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes\n * the winner — or answers `406 Not Acceptable`.\n *\n * @example\n * ```ts\n * const negotiator = new Negotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport class Negotiator implements NegotiatorInterface {\n\tnegotiate(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tlet best: string | undefined\n\t\tlet bestQuality = 0\n\t\tlet bestRank = Number.POSITIVE_INFINITY\n\t\tfor (const candidate of available) {\n\t\t\tconst match = matchMediaType(entries, candidate)\n\t\t\tif (match === undefined) continue\n\t\t\tconst { q, rank } = match\n\t\t\tif (q > bestQuality || (q === bestQuality && rank < bestRank)) {\n\t\t\t\tbest = candidate\n\t\t\t\tbestQuality = q\n\t\t\t\tbestRank = rank\n\t\t\t}\n\t\t}\n\t\treturn best\n\t}\n\n\tencoding(header: string, available: readonly Encoding[]): Encoding | undefined {\n\t\treturn negotiateEncoding(header, available)\n\t}\n\n\tlanguage(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tlet best: string | undefined\n\t\tlet bestQuality = 0\n\t\tfor (const candidate of available) {\n\t\t\tconst quality = languageQuality(entries, candidate)\n\t\t\tif (quality > bestQuality) {\n\t\t\t\tbest = candidate\n\t\t\t\tbestQuality = quality\n\t\t\t}\n\t\t}\n\t\treturn best\n\t}\n\n\t/**\n\t * @remarks\n\t * Errors thrown by the negotiated handler propagate UNMODIFIED — the\n\t * server boundary classifies them, never this negotiator.\n\t */\n\tasync format<TState>(\n\t\trequest: Request,\n\t\tcontext: MiddlewareContext<TState>,\n\t\thandlers: FormatHandlerMap<TState>,\n\t): Promise<Response> {\n\t\tconst keys = Object.keys(handlers)\n\t\tconst header = request.headers.get('accept')\n\t\tconst type = header === null ? keys[0] : this.negotiate(header, keys)\n\t\tif (type === undefined) return new Response('Not Acceptable', { status: 406 })\n\t\tconst handler = handlers[type]\n\t\tif (handler === undefined) return new Response('Not Acceptable', { status: 406 })\n\t\treturn handler(request, context)\n\t}\n}\n","import type { NegotiatorInterface } from './types.js'\nimport { Negotiator } from './Negotiator.js'\n\n/**\n * Create a {@link NegotiatorInterface} — the reusable content-negotiation\n * machine over the weighted `Accept` family.\n *\n * @remarks\n * Prefer this over `new Negotiator()` at call sites that only need the\n * interface.\n *\n * @returns A {@link NegotiatorInterface}\n *\n * @example\n * ```ts\n * import { createNegotiator } from '@src/core'\n *\n * const negotiator = createNegotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport function createNegotiator(): NegotiatorInterface {\n\treturn new Negotiator()\n}\n"],"x_google_ignoreList":[2],"mappings":";;AAWA,IAAa,mBAAmB;;AAGhC,IAAa,qBAAqB;;;;;;;;;;;;;;;;;AAkBlC,IAAa,6BAA6B;;;;;;;;;;;;AAa1C,IAAa,cAAgD,OAAO,OAAO;CAC1E,gBAAgB;CAChB,iBAAiB;CACjB,YAAY;CACZ,qBAAqB;AACtB,CAAC;;;;;;;;;AAUD,IAAa,qBAAuC,OAAO,OAAO,wBA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W;GACzB,MAAM,EAAE,GAAG,SAAS;GACpB,IAAI,IAAI,eAAgB,MAAM,eAAe,OAAO,UAAW;IAC9D,OAAO;IACP,cAAc;IACd,WAAW;GACZ;EACD;EACA,OAAO;CACR;CAEA,SAAS,QAAgB,WAAsD;EAC9E,OAAO,kBAAkB,QAAQ,SAAS;CAC3C;CAEA,SAAS,QAAgB,WAAkD;EAC1E,IAAI,UAAU,WAAW,GAAG,OAAO,KAAA;EACnC,MAAM,UAAU,kBAAkB,MAAM;EACxC,IAAI,QAAQ,WAAW,GAAG,OAAO,UAAU;EAC3C,IAAI;EACJ,IAAI,cAAc;EAClB,KAAK,MAAM,aAAa,WAAW;GAClC,MAAM,UAAU,gBAAgB,SAAS,SAAS;GAClD,IAAI,UAAU,aAAa;IAC1B,OAAO;IACP,cAAc;GACf;EACD;EACA,OAAO;CACR;;;;;;CAOA,MAAM,OACL,SACA,SACA,UACoB;EACpB,MAAM,OAAO,OAAO,KAAK,QAAQ;EACjC,MAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ;EAC3C,MAAM,OAAO,WAAW,OAAO,KAAK,KAAK,KAAK,UAAU,QAAQ,IAAI;EACpE,IAAI,SAAS,KAAA,GAAW,OAAO,IAAI,SAAS,kBAAkB,EAAE,QAAQ,IAAI,CAAC;EAC7E,MAAM,UAAU,SAAS;EACzB,IAAI,YAAY,KAAA,GAAW,OAAO,IAAI,SAAS,kBAAkB,EAAE,QAAQ,IAAI,CAAC;EAChF,OAAO,QAAQ,SAAS,OAAO;CAChC;AACD;;;;;;;;;;;;;;;;;;;;;;AC5DA,SAAgB,mBAAwC;CACvD,OAAO,IAAI,WAAW;AACvB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/errors.ts","../../../src/core/helpers.ts","../../../src/core/Negotiator.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { Encoding } from './types.js'\n\n// The substrate's tunable defaults (AGENTS §5 constants file) — only the\n// constants with a real consumer inside THIS package (AGENTS §21: build\n// against a concrete consumer, not speculatively). Frozen so a consumer can\n// read but never mutate the shared default. Middleware-package-only defaults\n// (rate limiting, CSRF, sessions, static serving, multipart — Appendix A of\n// the proposal) stay OUT of this file; they belong to that package's own\n// `constants.ts`.\n\n/** Default graceful-stop deadline (ms) the server gives in-flight requests on `stop()`. */\nexport const DEFAULT_DRAIN_MS = 10_000\n\n/** Default maximum request body size (bytes) `readBody` accepts before a 413. */\nexport const DEFAULT_BODY_LIMIT = 1_048_576\n\n/**\n * Default maximum DECOMPRESSED request body size (bytes) — the zip-bomb cap\n * the body pipeline's byte-counting `TransformStream` enforces when\n * transparently decompressing a `Content-Encoding` request body.\n *\n * @remarks\n * A small compressed payload (under {@link DEFAULT_BODY_LIMIT} on the wire)\n * can inflate by many orders of magnitude — a classic decompression bomb.\n * Capping the decompressed byte count makes the pipe ABORT the moment the\n * output would exceed this, BEFORE the full bomb is materialized, so the\n * inflation can never exhaust memory. Defaults to `16 MiB` — a generous\n * ceiling for a legitimate compressed JSON / form body, far below an OOM. A\n * consumer raises it via {@link import('./types.js').BodyOptions}\n * `decompression` for a workload that genuinely ships larger decompressed\n * bodies.\n */\nexport const DEFAULT_DECOMPRESSED_LIMIT = 16_777_216\n\n/**\n * The SSE response headers the `openStream` seam always sets.\n *\n * @remarks\n * `text/event-stream` is the media type browsers dispatch as SSE; `no-cache`\n * keeps a proxy from caching the stream; `keep-alive` holds the connection\n * open; `X-Accel-Buffering: no` opts a buffering reverse proxy (nginx) out so\n * events flush promptly rather than batching. Frozen so a consumer can read\n * but never mutate the shared default; `openStream` merges any\n * {@link import('./types.js').StreamOptions.headers} UNDER these.\n */\nexport const SSE_HEADERS: Readonly<Record<string, string>> = Object.freeze({\n\t'Content-Type': 'text/event-stream; charset=utf-8',\n\t'Cache-Control': 'no-cache',\n\tConnection: 'keep-alive',\n\t'X-Accel-Buffering': 'no',\n})\n\n/**\n * The strict charset `isValidRequestId` requires an incoming `X-Request-ID`\n * to match — `^[A-Za-z0-9_-]{1,200}$` — so a CRLF / log-injection / oversized\n * / control-char-bearing incoming id is REJECTED (a fresh id is minted\n * instead) rather than ever riding into a response header or `context.state`\n * (AGENTS §14 totality). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const REQUEST_ID_PATTERN: Readonly<RegExp> = Object.freeze(/^[A-Za-z0-9_-]{1,200}$/)\n\n/**\n * The set of bare `Content-Type`s `isCompressibleType` treats as\n * COMPRESSIBLE, beyond the `text/*` prefix + structured-suffix (`+json` /\n * `+xml`) rules that helper also applies.\n *\n * @remarks\n * The text-shaped application types worth compressing (JSON / JavaScript /\n * XML / SVG / WASM / a few document formats) — NOT already-compressed\n * binaries (`image/png`, `image/jpeg`, `video/*`, `application/zip`, a font's\n * `woff2`), which gzip/deflate would only bloat. Frozen so a consumer reads\n * but never mutates the shared default.\n */\nexport const COMPRESSIBLE_TYPES: ReadonlySet<string> = new Set([\n\t'application/json',\n\t'application/javascript',\n\t'application/xml',\n\t'application/xhtml+xml',\n\t'application/rss+xml',\n\t'application/atom+xml',\n\t'application/ld+json',\n\t'application/manifest+json',\n\t'application/vnd.api+json',\n\t'application/wasm',\n\t'image/svg+xml',\n\t'application/pdf',\n])\n\n/**\n * The default {@link Encoding} content-codings the substrate offers, in\n * PREFERENCE order — `gzip` / `deflate`.\n *\n * @remarks\n * `identity` (no compression) is always implicitly acceptable and is NOT\n * listed here — it is the fall-through when a client accepts none of these.\n * Brotli is omitted per the core's `CompressionStream`-only decision (see\n * {@link Encoding}). Frozen so a consumer can read but never mutate the\n * shared default.\n */\nexport const DEFAULT_ENCODINGS: readonly Encoding[] = Object.freeze(['gzip', 'deflate'])\n","// AGENTS §12: a handler signals a client-facing fault by throwing an\n// `HTTPError` carrying the HTTP `status` to send; the server's error boundary\n// (§5.3 of the proposal) turns it into a response of that status. Any OTHER\n// throw is a programmer/runtime error → a 500 (its message hidden unless\n// `expose`). The machine-readable field here is the numeric `status` (plus an\n// optional `context` bag) — `MultipartError` is NOT ported here: it moves to\n// the future `@orkestrel/middleware` package with its owner (`createMultipart`).\n\n/**\n * An error a handler (or middleware) throws to produce an HTTP response of a\n * specific status.\n *\n * @remarks\n * Carries the HTTP `status` to send and an optional `context` record (the\n * offending field / value). The server's built-in error boundary catches it\n * and renders a response of `status` with the error's `message` as the body\n * — so an `HTTPError`'s message is ALWAYS client-facing (it is the handler's\n * deliberate signal), unlike a generic throw whose message is hidden unless\n * `expose` is set. Subclass it (as {@link ContentTooLargeError} does) for\n * specific statuses, or throw it directly. Narrow a caught value with\n * {@link isHTTPError}.\n *\n * @example\n * ```ts\n * import { HTTPError } from '@src/core'\n *\n * const handler = async (request: Request): Promise<Response> => {\n * \tconst user = await find(new URL(request.url).searchParams.get('id'))\n * \tif (user === undefined) throw new HTTPError(404, 'user not found')\n * \treturn Response.json(user)\n * }\n * ```\n */\nexport class HTTPError extends Error {\n\treadonly status: number\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(status: number, message: string, context?: Readonly<Record<string, unknown>>) {\n\t\tsuper(message)\n\t\tthis.name = 'HTTPError'\n\t\tthis.status = status\n\t\tthis.context = context\n\t}\n}\n\n/**\n * The {@link HTTPError} thrown when a request body exceeds the body\n * pipeline's size limit — a `413 Content Too Large`.\n *\n * @remarks\n * Thrown by `readBody` (and the middleware context's cached `body()`) when\n * the received bytes exceed the configured {@link\n * import('./types.js').BodyOptions.limit}, carrying the `limit` in its\n * `context`. The server's error boundary renders it as a 413.\n *\n * @example\n * ```ts\n * import { ContentTooLargeError, isHTTPError } from '@src/core'\n *\n * try {\n * \tawait readBody(request, { limit: 1024 })\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status) // 413\n * }\n * ```\n */\nexport class ContentTooLargeError extends HTTPError {\n\tconstructor(limit: number) {\n\t\tsuper(413, `request body exceeds the ${limit}-byte limit`, { limit })\n\t\tthis.name = 'ContentTooLargeError'\n\t}\n}\n\n/**\n * Narrow an unknown caught value to an {@link HTTPError} (including its\n * subclasses, e.g. {@link ContentTooLargeError}).\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns `true` when `value` is an {@link HTTPError}\n *\n * @example\n * ```ts\n * import { isHTTPError } from '@src/core'\n *\n * try {\n * \tawait handle(request)\n * } catch (error) {\n * \tif (isHTTPError(error)) console.log(error.status, error.message)\n * }\n * ```\n */\nexport function isHTTPError(value: unknown): value is HTTPError {\n\treturn value instanceof HTTPError\n}\n","import type {\n\tAcceptEntry,\n\tBodyOptions,\n\tCookieOptions,\n\tEncoding,\n\tMiddlewareContext,\n\tMiddlewareHandler,\n\tNextFunction,\n\tRangeSpec,\n\tSSEMessage,\n\tStreamInterface,\n\tStreamOptions,\n\tTokenOptions,\n\tTokenSecret,\n} from './types.js'\nimport { isRecord, isString, parseJSON } from '@orkestrel/contract'\nimport {\n\tCOMPRESSIBLE_TYPES,\n\tDEFAULT_BODY_LIMIT,\n\tDEFAULT_DECOMPRESSED_LIMIT,\n\tREQUEST_ID_PATTERN,\n\tSSE_HEADERS,\n} from './constants.js'\nimport { ContentTooLargeError, HTTPError } from './errors.js'\n\n// The middleware seam's composition engine (AGENTS §5 — a pure function, not a\n// class: `compose` has no instance state, so it lives here rather than as an\n// entity). The RETURNING onion (§5.1 of the proposal): each middleware may\n// transform the request (`next(newRequest)`), transform the response (`await\n// next()` then mutate the result), or short-circuit (return without calling\n// `next`) — no mutable framework object anywhere. The double-`next` guard\n// (calling `next` twice within one middleware invocation) rejects, preserving\n// the old spine's crown-jewel invariant that each link runs the chain at most\n// once.\n\n/**\n * Compose an ordered chain of {@link MiddlewareHandler}s around a `terminal`\n * handler into one request handler — the frozen middleware seam (§5.1).\n *\n * @remarks\n * `middleware[0]` runs OUTERMOST: it is invoked first, and its call to `next`\n * runs `middleware[1]`, and so on until the LAST middleware's `next` invokes\n * `terminal`. Each middleware's `next` may be called with a substituted\n * `Request` (the downstream chain then sees that request instead of the\n * original), called with no argument (the original request continues\n * downstream), or NOT called at all (a short-circuit — the middleware's own\n * returned `Response` is sent, and everything downstream never runs). A\n * SECOND call to the same `next` within one middleware invocation REJECTS —\n * each link runs the chain at most once, so a middleware cannot fork the\n * request into two divergent downstream runs.\n *\n * @typeParam TState - The consumer's opaque per-request state type\n * @param middleware - The ordered chain, outermost first\n * @param terminal - The innermost handler the chain ultimately reaches\n * @returns A single `(request, context) => Promise<Response>` handler running the whole onion\n *\n * @example\n * ```ts\n * const withHeader: MiddlewareHandler<{}> = async (request, context, next) => {\n * \tconst response = await next()\n * \tresponse.headers.set('X-Powered-By', 'orkestrel')\n * \treturn response\n * }\n *\n * const handle = compose([withHeader], async () => new Response('ok'))\n * ```\n */\nexport function compose<TState>(\n\tmiddleware: readonly MiddlewareHandler<TState>[],\n\tterminal: (request: Request, context: MiddlewareContext<TState>) => Promise<Response>,\n): (request: Request, context: MiddlewareContext<TState>) => Promise<Response> {\n\treturn async (request: Request, context: MiddlewareContext<TState>): Promise<Response> => {\n\t\tconst dispatch = (index: number, currentRequest: Request): Promise<Response> => {\n\t\t\tconst layer = middleware[index]\n\t\t\tif (layer === undefined) return terminal(currentRequest, context)\n\t\t\tlet called = false\n\t\t\tconst next: NextFunction = (nextRequest?: Request): Promise<Response> => {\n\t\t\t\tif (called) return Promise.reject(new Error('next() was already called by this middleware'))\n\t\t\t\tcalled = true\n\t\t\t\treturn dispatch(index + 1, nextRequest ?? currentRequest)\n\t\t\t}\n\t\t\treturn Promise.resolve(layer(currentRequest, context, next))\n\t\t}\n\t\treturn dispatch(0, request)\n\t}\n}\n\n// The cookie machinery (AGENTS §4.3 module-scope helpers) — `parseCookies`\n// decodes a raw `Cookie:` header into a name→value lookup; `serializeCookie`\n// builds a spec-shaped `Set-Cookie` value with its attributes. The SIGNED\n// pair reuses the shipped HMAC token primitives rather than a second HMAC\n// scheme: `writeSignedCookie` is `serializeCookie(name, await signToken(value,\n// { secret }))` appended to a `Headers`, and `readSignedCookie` is `await\n// verifyToken(parseCookies(...)[name], secret)` — so a cookie is just a\n// `signToken` value in a `Set-Cookie`, with the SAME secret rotation + tamper\n// rejection. Every reader narrows untrusted request input with `typeof`,\n// never `as` (§14), and total on hostile input.\n\n/**\n * Parse a raw `Cookie:` request header into a `name → value` lookup.\n *\n * @remarks\n * Splits on `;`; the FIRST segment keeps any leading whitespace (a genuine\n * cookie-pair separator never precedes it), while every later segment has its\n * inter-pair separator (ASCII space/tab) stripped before parsing — so a\n * whitespace-PADDED name (`' __Host-x=evil'`) is rejected by\n * {@link isCookieName} rather than silently reconciling into a\n * prefix-protected `__Host-` name. A pair without `=`, or with an invalid\n * name, is skipped; a later duplicate name wins. TOTAL — an absent/empty/\n * malformed header yields an empty record, never throws (AGENTS §14).\n *\n * @param header - The raw `Cookie` header value (possibly `undefined`)\n * @returns A record of every parsed cookie, `name → decoded value`\n *\n * @example\n * ```ts\n * parseCookies('session=abc; theme=dark') // { session: 'abc', theme: 'dark' }\n * ```\n */\nexport function parseCookies(header: string | undefined): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tif (header === undefined) return out\n\tconst segments = header.split(';')\n\tfor (let index = 0; index < segments.length; index += 1) {\n\t\tconst raw = segments[index] ?? ''\n\t\tconst segment = index === 0 ? raw : raw.replace(/^[ \\t]+/, '')\n\t\tconst eq = segment.indexOf('=')\n\t\tif (eq < 0) continue\n\t\tconst name = segment.slice(0, eq)\n\t\tif (!isCookieName(name)) continue\n\t\tout[name] = decodeCookieValue(segment.slice(eq + 1).trim())\n\t}\n\treturn out\n}\n\n/**\n * Whether a string is a valid RFC 6265 cookie NAME — a non-empty run of\n * cookie-token chars with NO surrounding (or interior) whitespace.\n *\n * @remarks\n * A cookie name is an RFC 7230 `token`: `^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$` —\n * which excludes every whitespace char (ASCII and Unicode) plus controls,\n * separators, and `=`. The {@link parseCookies} hardening that stops a\n * `' __Host-x'` from reconciling into `__Host-x`. Total — never throws.\n *\n * @param value - The candidate cookie name\n * @returns `true` when `value` is a valid, whitespace-free cookie token\n *\n * @example\n * ```ts\n * isCookieName('__Host-session') // true\n * isCookieName(' __Host-session') // false — whitespace-padded\n * ```\n */\nexport function isCookieName(value: string): boolean {\n\treturn /^[!#$%&'*+\\-.0-9A-Z^_`a-z|~]+$/.test(value)\n}\n\n/**\n * Decode a cookie value with `decodeURIComponent`, falling back to the raw\n * text when the value is not valid percent-encoding.\n *\n * @param raw - The raw (trimmed) cookie value\n * @returns The URL-decoded value, or the raw value when decoding would throw\n *\n * @example\n * ```ts\n * decodeCookieValue('a%20b') // 'a b'\n * decodeCookieValue('%') // '%' — malformed escape stays literal\n * ```\n */\nexport function decodeCookieValue(raw: string): string {\n\ttry {\n\t\treturn decodeURIComponent(raw)\n\t} catch {\n\t\treturn raw\n\t}\n}\n\n/**\n * Whether a string is safe to interpolate as a `Set-Cookie` attribute VALUE\n * (a `Domain` / `Path`) — the guard {@link serializeCookie} screens those two\n * attributes with before emitting them.\n *\n * @remarks\n * Rejects a value carrying a `;` (splits attributes), a `,` (can split a\n * folded header), ASCII/Unicode whitespace, or a C0/DEL control char\n * (`< 0x20` or `0x7f`) — the chars that could inject another `Set-Cookie`\n * directive. Total — never throws (a bad value returns `false`).\n *\n * @param value - The candidate attribute value (a `Domain` or `Path`)\n * @returns `true` when `value` carries no separator / whitespace / control char\n *\n * @example\n * ```ts\n * isCookieAttribute('/app') // true\n * isCookieAttribute('/a\\r\\nSet-Cookie: x=y') // false\n * ```\n */\nexport function isCookieAttribute(value: string): boolean {\n\tfor (const char of value) {\n\t\tif (char === ';' || char === ',' || /\\s/.test(char)) return false\n\t\tconst code = char.codePointAt(0)\n\t\tif (code !== undefined && (code < 0x20 || code === 0x7f)) return false\n\t}\n\treturn true\n}\n\n/**\n * Serialize a cookie into a `Set-Cookie` header value — `name=value` plus its attributes.\n *\n * @remarks\n * URL-encodes the value (the inverse of {@link parseCookies}'s decode) and\n * appends the present {@link CookieOptions} attributes in canonical order:\n * `Domain`, `Path` (default `/`), `Max-Age`, `HttpOnly` (default ON), `Secure`\n * (default OFF), `SameSite` (default `Lax`). `Domain` / `Path` are validated\n * with {@link isCookieAttribute} and THROW an {@link HTTPError} on an\n * injection attempt (a programmer misconfiguration, AGENTS §12 — never a\n * silent drop). A `sameSite: 'None'` cookie is ALWAYS `Secure` regardless of\n * the `secure` option (the spec requires it); an un-resolved `undefined`\n * `secure` here falls to OFF — request-aware callers resolve it first via\n * {@link resolveSecure}.\n *\n * @param name - The cookie name\n * @param value - The cookie value (URL-encoded into the output)\n * @param options - The {@link CookieOptions} attributes; see its fields for defaults\n * @returns The `Set-Cookie` header value\n * @throws {HTTPError} When `domain` or `path` carries an injection char\n *\n * @example\n * ```ts\n * serializeCookie('session', 'abc') // 'session=abc; Path=/; HttpOnly; SameSite=Lax'\n * ```\n */\nexport function serializeCookie(name: string, value: string, options?: CookieOptions): string {\n\tconst sameSite = options?.sameSite ?? 'Lax'\n\tconst domain = options?.domain\n\tif (domain !== undefined && !isCookieAttribute(domain))\n\t\tthrow new HTTPError(500, `invalid cookie Domain: ${JSON.stringify(domain)}`)\n\tconst path = options?.path ?? '/'\n\tif (!isCookieAttribute(path))\n\t\tthrow new HTTPError(500, `invalid cookie Path: ${JSON.stringify(path)}`)\n\tconst secure = sameSite === 'None' || options?.secure === true\n\tconst parts = [`${name}=${encodeURIComponent(value)}`]\n\tif (domain !== undefined) parts.push(`Domain=${domain}`)\n\tparts.push(`Path=${path}`)\n\tif (options?.maxAge !== undefined) parts.push(`Max-Age=${Math.trunc(options.maxAge)}`)\n\tif (options?.httpOnly !== false) parts.push('HttpOnly')\n\tif (secure) parts.push('Secure')\n\tparts.push(`SameSite=${sameSite}`)\n\treturn parts.join('; ')\n}\n\n/**\n * Resolve a cookie's effective `Secure` flag from its {@link CookieOptions}\n * `secure` setting and whether the request arrived over TLS.\n *\n * @remarks\n * `true` / `false` are explicit overrides. `undefined` (the secure default —\n * the option omitted) resolves to `encrypted` — `Secure` on a TLS\n * connection, off over plaintext HTTP — so a production HTTPS deployment\n * gets `Secure` automatically while local-dev HTTP still works.\n *\n * @param secure - The {@link CookieOptions} `secure` setting\n * @param encrypted - The connection's TLS flag ({@link import('./types.js').ConnectionInfo.encrypted})\n * @returns The concrete `Secure` flag to emit\n *\n * @example\n * ```ts\n * resolveSecure(undefined, true) // true\n * resolveSecure(undefined, false) // false\n * resolveSecure(false, true) // false — explicit override wins\n * ```\n */\nexport function resolveSecure(secure: boolean | undefined, encrypted: boolean): boolean {\n\tif (secure === true || secure === false) return secure\n\treturn encrypted\n}\n\n/**\n * Append a `Set-Cookie` header onto a fetch-standard `Headers` WITHOUT\n * clobbering a prior one.\n *\n * @remarks\n * `Headers.append` already accumulates repeated headers (unlike node's\n * `setHeader`), so this is a thin, self-documenting wrapper naming the\n * cookie-append intent — the primitive {@link writeSignedCookie} /\n * {@link clearCookie} use.\n *\n * @param headers - The response `Headers` to write into\n * @param cookie - The fully-serialized `Set-Cookie` value (from {@link serializeCookie})\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * appendCookie(headers, serializeCookie('a', '1'))\n * appendCookie(headers, serializeCookie('b', '2'))\n * headers.get('set-cookie') // 'a=1; Path=/; HttpOnly; SameSite=Lax, b=2; …'\n * ```\n */\nexport function appendCookie(headers: Headers, cookie: string): void {\n\theaders.append('set-cookie', cookie)\n}\n\n/**\n * Write a SIGNED cookie — HMAC-sign `value` with {@link signToken} and append\n * it as a `Set-Cookie` (the inverse of {@link readSignedCookie}).\n *\n * @remarks\n * The cookie value is `await signToken(value, { secret })`\n * (`<payload>.<signature>`), so a signed cookie is a stateless token in a\n * cookie — the same secret rotation and tamper rejection, no second HMAC\n * scheme. Appends (never clobbers) via {@link appendCookie}. Async — WebCrypto\n * signing is asynchronous (§3 of the proposal).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name\n * @param value - The opaque value to sign into the cookie\n * @param secret - The {@link TokenSecret} to sign with (the first secret signs)\n * @param options - The {@link CookieOptions} attributes for the `Set-Cookie`\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * await writeSignedCookie(headers, 'session', 'user-1', 'secret')\n * ```\n */\nexport async function writeSignedCookie(\n\theaders: Headers,\n\tname: string,\n\tvalue: string,\n\tsecret: TokenSecret,\n\toptions?: CookieOptions,\n): Promise<void> {\n\tappendCookie(headers, serializeCookie(name, await signToken(value, { secret }), options))\n}\n\n/**\n * Read + verify a SIGNED cookie off a request — TOTAL, returning the\n * embedded value or `undefined` (the inverse of {@link writeSignedCookie}).\n *\n * @remarks\n * Parses the `Cookie` header ({@link parseCookies}), takes the named cookie,\n * and verifies it with {@link verifyToken} against `secret` (a rotation list\n * accepts a cookie signed by any of its secrets). ANY failure — an absent\n * cookie, a tampered value, a wrong secret — yields `undefined`, never throws.\n *\n * @param request - The `Request` to read the `Cookie` header from\n * @param name - The cookie name to read\n * @param secret - The {@link TokenSecret} (or rotation list) to verify against\n * @returns The embedded value when the cookie is present + valid, else `undefined`\n *\n * @example\n * ```ts\n * const value = await readSignedCookie(request, 'session', 'secret')\n * ```\n */\nexport async function readSignedCookie(\n\trequest: Request,\n\tname: string,\n\tsecret: TokenSecret,\n): Promise<string | undefined> {\n\tconst cookie = parseCookies(request.headers.get('cookie') ?? undefined)[name]\n\treturn cookie === undefined ? undefined : verifyToken(cookie, secret)\n}\n\n/**\n * Clear a cookie — append a `Set-Cookie` that expires it immediately (`Max-Age=0`).\n *\n * @remarks\n * Writes an empty-valued cookie of the same `name` with `Max-Age=0` plus the\n * same `path`/`domain`/`sameSite`/`secure` attributes (the browser only drops\n * a cookie when those MATCH the one it set).\n *\n * @param headers - The response `Headers` to write into\n * @param name - The cookie name to clear\n * @param options - The {@link CookieOptions} that must match the original cookie\n *\n * @example\n * ```ts\n * const headers = new Headers()\n * clearCookie(headers, 'session')\n * ```\n */\nexport function clearCookie(headers: Headers, name: string, options?: CookieOptions): void {\n\tappendCookie(headers, serializeCookie(name, '', { ...options, maxAge: 0 }))\n}\n\n// The stateless signed-token primitives over WebCrypto (AGENTS §4.3 module-\n// scope helpers, §3 of the proposal). A token is `<payload>.<signature>`: the\n// payload a base64url JSON `{ value, exp? }`, the signature an HMAC-SHA256 of\n// the payload under the secret. Signing always uses the FIRST secret (a\n// rotation list's current head); verifying accepts ANY secret in the list,\n// via `crypto.subtle.verify` — constant-time internally, so the old\n// `safeCompare` is RETIRED, never ported. `verifyToken` is TOTAL (never\n// throws — adversarial input returns `undefined`, AGENTS §14); only\n// `signToken` throws, and only on a misconfigured (empty) secret.\n\n/**\n * Base64url-encode a byte sequence — the payload encoding {@link signToken} /\n * {@link verifyToken} use, and the signature encoding for the HMAC.\n *\n * @param bytes - The bytes to encode\n * @returns The base64url string (no padding)\n *\n * @example\n * ```ts\n * encodeBase64Url(new TextEncoder().encode('hi')) // 'aGk'\n * ```\n */\nexport function encodeBase64Url(bytes: Uint8Array): string {\n\tlet binary = ''\n\tfor (const byte of bytes) binary += String.fromCharCode(byte)\n\treturn btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/**\n * Decode a base64url string back into its bytes — the inverse of\n * {@link encodeBase64Url}.\n *\n * @remarks\n * Restores the standard base64 alphabet + padding before decoding with\n * `atob`. THROWS `DOMException` on a malformed input — callers on the\n * untrusted-token path (`verifyToken`) catch it to stay total (AGENTS §14).\n *\n * @param value - The base64url string to decode\n * @returns The decoded bytes\n * @throws {DOMException} When `value` is not valid base64url\n *\n * @example\n * ```ts\n * new TextDecoder().decode(decodeBase64Url('aGk')) // 'hi'\n * ```\n */\nexport function decodeBase64Url(value: string): Uint8Array<ArrayBuffer> {\n\tconst restored = value.replace(/-/g, '+').replace(/_/g, '/')\n\tconst padding = restored.length % 4 === 0 ? '' : '='.repeat(4 - (restored.length % 4))\n\tconst binary = atob(restored + padding)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)\n\treturn bytes\n}\n\n/**\n * Sign a value into a stateless, HMAC-SHA256 token — `<payload>.<signature>`.\n *\n * @remarks\n * The payload is a base64url-encoded JSON `{ value, exp }` (`exp` is the\n * absolute expiry instant `Date.now() + ttl` when `options.ttl` is set, so\n * the expiry is HMAC-COVERED — a client cannot extend it without invalidating\n * the signature), signed via `crypto.subtle.sign('HMAC', …)` under the FIRST\n * {@link TokenSecret} (the current secret, or the head of a rotation list).\n * Blank/whitespace-only secrets are IGNORED ({@link normalizeSecret}); a\n * misconfigured secret with no usable entry THROWS an {@link HTTPError}\n * (`500`) — fail-closed, a programmer error (AGENTS §12). Verify with\n * {@link verifyToken}. Omitting `ttl` mints a token that never expires.\n *\n * @param value - The opaque value to embed (a session id, a deployment marker)\n * @param options - The signing `secret` and optional `ttl` (ms); see {@link TokenOptions}\n * @returns The signed `<payload>.<signature>` token string\n * @throws {HTTPError} When `options.secret` has no usable (non-blank) entry\n *\n * @example\n * ```ts\n * const token = await signToken('client', { secret: 'shh', ttl: 60_000 })\n * await verifyToken(token, 'shh') // 'client' (within 60s), else undefined\n * ```\n */\nexport async function signToken(value: string, options: TokenOptions): Promise<string> {\n\tconst secrets = normalizeSecret(options.secret)\n\tconst secret = secrets[0]\n\tif (secret === undefined) throw new HTTPError(500, 'signToken requires at least one secret')\n\tconst exp = options.ttl !== undefined ? Date.now() + options.ttl : undefined\n\tconst encoded = encodeBase64Url(new TextEncoder().encode(JSON.stringify({ value, exp })))\n\tconst key = await crypto.subtle.importKey(\n\t\t'raw',\n\t\tnew TextEncoder().encode(secret),\n\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\tfalse,\n\t\t['sign'],\n\t)\n\tconst signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(encoded))\n\treturn `${encoded}.${encodeBase64Url(new Uint8Array(signature))}`\n}\n\n/**\n * Verify a stateless token and return its embedded value — TOTAL, never throws.\n *\n * @remarks\n * The inverse of {@link signToken}: splits the token on its LAST `.` (so a\n * value containing dots survives), and checks the payload's HMAC-SHA256\n * signature against EACH {@link TokenSecret} candidate via\n * `crypto.subtle.verify` (constant-time internally — the old `safeCompare` is\n * retired, §3 of the proposal), accepting the token on the first match (the\n * rotation path). It then decodes + narrows the payload (`isRecord` +\n * `typeof`, never `as` — AGENTS §14) and, when an expiry was bound in,\n * rejects an expired token. ANY failure — a malformed token, a bad signature,\n * a hostile/non-JSON payload, an empty secret list, or an elapsed expiry —\n * yields `undefined` rather than throwing.\n *\n * @param token - The candidate token string (from a request header/cookie)\n * @param secret - The {@link TokenSecret} (or rotation list) to verify against\n * @returns The embedded value when the token is valid + unexpired, else `undefined`\n *\n * @example\n * ```ts\n * await verifyToken('bad.token', 'shh') // undefined — never throws\n * ```\n */\nexport async function verifyToken(token: string, secret: TokenSecret): Promise<string | undefined> {\n\tconst secrets = normalizeSecret(secret)\n\tif (secrets.length === 0) return undefined\n\tconst dot = token.lastIndexOf('.')\n\tif (dot < 0) return undefined\n\tconst encoded = token.slice(0, dot)\n\tconst signatureText = token.slice(dot + 1)\n\ttry {\n\t\tconst signature = decodeBase64Url(signatureText)\n\t\tconst data = new TextEncoder().encode(encoded)\n\t\tfor (const candidate of secrets) {\n\t\t\tconst key = await crypto.subtle.importKey(\n\t\t\t\t'raw',\n\t\t\t\tnew TextEncoder().encode(candidate),\n\t\t\t\t{ name: 'HMAC', hash: 'SHA-256' },\n\t\t\t\tfalse,\n\t\t\t\t['verify'],\n\t\t\t)\n\t\t\tconst matched = await crypto.subtle.verify('HMAC', key, signature, data)\n\t\t\tif (matched) return decodeTokenPayload(encoded)\n\t\t}\n\t\treturn undefined\n\t} catch {\n\t\t// A malformed base64url signature/payload is just an invalid token — stay total.\n\t\treturn undefined\n\t}\n}\n\n/**\n * Decode + narrow a signed token's base64url JSON payload, honoring its\n * expiry — the shared decode step {@link verifyToken} applies after a\n * signature match.\n *\n * @remarks\n * Decodes the base64url payload to UTF-8 JSON, narrows it to a record with a\n * string `value` (AGENTS §14 — never `as`), and rejects an expired `exp`.\n * TOTAL — any decode/shape/expiry failure yields `undefined`.\n *\n * @param encoded - The base64url-encoded payload segment (before the last `.`)\n * @returns The embedded value when the payload is well-shaped + unexpired, else `undefined`\n */\nexport function decodeTokenPayload(encoded: string): string | undefined {\n\ttry {\n\t\tconst text = new TextDecoder().decode(decodeBase64Url(encoded))\n\t\tconst payload: unknown = JSON.parse(text)\n\t\tif (!isRecord(payload)) return undefined\n\t\tif (typeof payload.value !== 'string') return undefined\n\t\tif (payload.exp !== undefined && typeof payload.exp !== 'number') return undefined\n\t\tif (payload.exp !== undefined && Date.now() >= payload.exp) return undefined\n\t\treturn payload.value\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Normalize a {@link TokenSecret} to a concrete list of USABLE secrets —\n * backs both {@link signToken} and {@link verifyToken}.\n *\n * @remarks\n * A single string becomes a one-element list; a rotation list is copied. Any\n * blank/whitespace-only entry is DROPPED (`.trim()` is used only for that\n * emptiness test; each kept secret is stored VERBATIM). The first kept\n * element is the signing secret; all kept are accepted on verify.\n *\n * @param secret - The {@link TokenSecret} (a single string, or a rotation list)\n * @returns The kept (non-blank) secrets, in order — empty when none is usable\n *\n * @example\n * ```ts\n * normalizeSecret(['new', '', ' ', 'old']) // ['new', 'old']\n * ```\n */\nexport function normalizeSecret(secret: TokenSecret): readonly string[] {\n\tconst list = typeof secret === 'string' ? [secret] : [...secret]\n\treturn list.filter((entry) => entry.trim().length > 0)\n}\n\n// The content-negotiation helpers (AGENTS §4.3 module-scope, §5) — the ONE\n// shared q-value parser behind the `Negotiator` (U3) and any future\n// compression middleware's `Accept-Encoding` pick.\n\n/**\n * Parse a weighted `Accept` / `Accept-Encoding` / `Accept-Language` header\n * into its q-sorted entries.\n *\n * @remarks\n * Splits on `,`; for each part takes the token before the first `;`\n * (lower-cased + trimmed) as `value`, and reads a `;q=<n>` parameter as the\n * quality (default `1`, clamped to `[0, 1]`; a non-finite/malformed `q` falls\n * back to `1`). A `;q=0` entry is KEPT (an explicit rejection a caller must\n * honor). The result is sorted by `q` DESCENDING, a STABLE sort preserving\n * the header's own order within a tie — a single pass with no backtracking,\n * so parsing stays linear in the header length (ReDoS-safe). TOTAL — an\n * empty/malformed header yields `[]`/best-effort entries, never throws.\n *\n * @param header - The raw weighted header value\n * @returns The parsed {@link AcceptEntry} list, sorted by `q` descending\n *\n * @example\n * ```ts\n * parseAcceptHeader('br;q=1.0, gzip;q=0.8, identity;q=0')\n * // [{ value: 'br', q: 1 }, { value: 'gzip', q: 0.8 }, { value: 'identity', q: 0 }]\n * ```\n */\nexport function parseAcceptHeader(header: string): readonly AcceptEntry[] {\n\tconst entries: AcceptEntry[] = []\n\tfor (const part of header.split(',')) {\n\t\tconst trimmed = part.trim()\n\t\tif (trimmed.length === 0) continue\n\t\tconst semicolon = trimmed.indexOf(';')\n\t\tconst value = (semicolon === -1 ? trimmed : trimmed.slice(0, semicolon)).trim().toLowerCase()\n\t\tif (value.length === 0) continue\n\t\tlet q = 1\n\t\tif (semicolon !== -1) {\n\t\t\tconst match = /;\\s*q=(-?[0-9.]+)/i.exec(trimmed.slice(semicolon))\n\t\t\tif (match !== null) {\n\t\t\t\tconst parsed = Number(match[1])\n\t\t\t\tif (Number.isFinite(parsed)) q = Math.min(1, Math.max(0, parsed))\n\t\t\t}\n\t\t}\n\t\tentries.push({ value, q })\n\t}\n\treturn entries\n\t\t.map((entry, index) => ({ entry, index }))\n\t\t.sort((a, b) => b.entry.q - a.entry.q || a.index - b.index)\n\t\t.map((ranked) => ranked.entry)\n}\n\n/**\n * The client's quality (q) for one content-coding from the parsed\n * `Accept-Encoding` entries — backs {@link negotiateEncoding}'s\n * server-preference selection.\n *\n * @remarks\n * Prefers an EXACT named match (including an explicit `;q=0` rejection);\n * failing that, a bare `*` wildcard's q applies. A coding that is neither\n * named nor covered by `*` scores `0` (not acceptable). A named `;q=0` wins\n * over a `*` (a specific rejection beats the wildcard), so it scores `0`.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param coding - The candidate coding to score\n * @returns The client's quality for `coding` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'gzip') // 0.5\n * codingQuality(parseAcceptHeader('gzip;q=0.5, *;q=0.1'), 'br') // 0.1\n * ```\n */\nexport function codingQuality(entries: readonly AcceptEntry[], coding: string): number {\n\tconst named = entries.find((entry) => entry.value === coding)\n\tif (named !== undefined) return named.q\n\tconst wildcard = entries.find((entry) => entry.value === '*')\n\treturn wildcard?.q ?? 0\n}\n\n/**\n * Select the best content-coding for an `Accept-Encoding` header from the\n * codings the server offers.\n *\n * @remarks\n * Parses the header ({@link parseAcceptHeader}) and scores each `available`\n * coding in the SERVER's preference order ({@link codingQuality}), keeping\n * the highest-scoring one (a strict `>` keeps the earlier-offered coding on a\n * client-side tie). Returns `undefined` when the client accepts none of\n * `available` (identity — no compression). TOTAL on hostile input.\n *\n * @typeParam T - The coding string type (so a `readonly Encoding[]` returns an `Encoding`)\n * @param header - The raw `Accept-Encoding` header value\n * @param available - The codings the server offers, in preference (tie-break) order\n * @returns The negotiated coding, or `undefined` when none of `available` is acceptable\n *\n * @example\n * ```ts\n * negotiateEncoding('gzip;q=1.0, deflate;q=0.8', ['gzip', 'deflate']) // 'gzip'\n * ```\n */\nexport function negotiateEncoding<T extends string>(\n\theader: string,\n\tavailable: readonly T[],\n): T | undefined {\n\tif (available.length === 0) return undefined\n\tconst entries = parseAcceptHeader(header)\n\tlet best: T | undefined\n\tlet bestQuality = 0\n\tfor (const coding of available) {\n\t\tconst quality = codingQuality(entries, coding)\n\t\tif (quality > bestQuality) {\n\t\t\tbest = coding\n\t\t\tbestQuality = quality\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * Rank + quality of one `candidate` media type against the parsed `Accept`\n * entries — the generic media-type primitive the `Negotiator`'s `negotiate`\n * uses to score each `available` candidate.\n *\n * @remarks\n * An exact match ranks `0`, a subtype wildcard (`type/*`) ranks `1`, the\n * any-range (`* / *`) ranks `2`; `undefined` when nothing matches. An exact\n * `;q=0` entry explicitly rejects the candidate outright (returns\n * `undefined` immediately); a wildcard `;q=0` only rejects the wildcard's own\n * (less specific) coverage, so a later more-specific match can still allow\n * it. Among multiple matching entries, the lowest `rank` wins, and among a\n * rank tie the highest `q` wins.\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate media type to score (e.g. `'text/html'`)\n * @returns The `{ q, rank }` of the best matching entry, or `undefined` when nothing matches\n *\n * @example\n * ```ts\n * matchMediaType(parseAcceptHeader('text/html, application/json;q=0.9'), 'text/html')\n * // { q: 1, rank: 0 }\n * matchMediaType(parseAcceptHeader('text/*;q=0.8'), 'text/plain') // { q: 0.8, rank: 1 }\n * matchMediaType(parseAcceptHeader('text/html;q=0'), 'text/html') // undefined\n * ```\n */\nexport function matchMediaType(\n\tentries: readonly AcceptEntry[],\n\tcandidate: string,\n): { readonly q: number; readonly rank: number } | undefined {\n\tconst slash = candidate.indexOf('/')\n\tconst type = slash === -1 ? candidate : candidate.slice(0, slash)\n\tlet best: { readonly q: number; readonly rank: number } | undefined\n\tfor (const entry of entries) {\n\t\tlet rank: number | undefined\n\t\tif (entry.value === candidate) rank = 0\n\t\telse if (entry.value === `${type}/*`) rank = 1\n\t\telse if (entry.value === '*/*') rank = 2\n\t\tif (rank === undefined) continue\n\t\tif (entry.q === 0) {\n\t\t\t// An exact `;q=0` explicitly rejects this candidate outright; a\n\t\t\t// wildcard `;q=0` only rejects the wildcard's own (less specific)\n\t\t\t// coverage, so a later more-specific match can still allow it.\n\t\t\tif (rank === 0) return undefined\n\t\t\tcontinue\n\t\t}\n\t\tif (best === undefined || rank < best.rank || (rank === best.rank && entry.q > best.q)) {\n\t\t\tbest = { q: entry.q, rank }\n\t\t}\n\t}\n\treturn best\n}\n\n/**\n * The client's quality for one `candidate` language from the parsed\n * `Accept-Language` entries — backs the `Negotiator`'s `language` axis.\n *\n * @remarks\n * Prefers an exact match, then a primary-tag prefix match (`en` accepts\n * `en-US`), then the `*` wildcard; `0` when nothing matches (a `;q=0` entry\n * is an explicit rejection).\n *\n * @param entries - The parsed {@link AcceptEntry} list\n * @param candidate - The candidate language tag to score (e.g. `'en-US'`)\n * @returns The client's quality for `candidate` in `[0, 1]` (`0` ⇒ not acceptable)\n *\n * @example\n * ```ts\n * languageQuality(parseAcceptHeader('en-US, en;q=0.8'), 'en-US') // 1\n * languageQuality(parseAcceptHeader('en;q=0.8'), 'en-US') // 0.8 — primary-tag prefix\n * languageQuality(parseAcceptHeader('*;q=0.5'), 'fr') // 0.5 — wildcard\n * ```\n */\nexport function languageQuality(entries: readonly AcceptEntry[], candidate: string): number {\n\tconst lower = candidate.toLowerCase()\n\tconst primary = lower.split('-')[0]\n\tlet named: number | undefined\n\tlet prefixed: number | undefined\n\tlet wildcard: number | undefined\n\tfor (const entry of entries) {\n\t\tconst entryPrimary = entry.value.split('-')[0]\n\t\tif (entry.value === lower) named = entry.q\n\t\telse if (entryPrimary === primary) {\n\t\t\tif (prefixed === undefined) prefixed = entry.q\n\t\t} else if (entry.value === '*') wildcard = entry.q\n\t}\n\tif (named !== undefined) return named\n\tif (prefixed !== undefined) return prefixed\n\treturn wildcard ?? 0\n}\n\n/**\n * Whether a `Content-Type` is worth compressing.\n *\n * @remarks\n * Strips any `; charset=…` parameter (lower-cased), then accepts a `text/*`\n * type, a `+json`/`+xml` structured suffix, or one of the explicit\n * {@link import('./constants.js').COMPRESSIBLE_TYPES}. An already-compressed\n * binary (`image/png`, `application/zip`) is NOT compressible. An\n * absent/empty type is not compressible. TOTAL.\n *\n * @param type - The response `Content-Type` header value (with or without parameters)\n * @returns `true` when the type is text-shaped and worth compressing\n *\n * @example\n * ```ts\n * isCompressibleType('application/json; charset=utf-8') // true\n * isCompressibleType('image/png') // false\n * ```\n */\nexport function isCompressibleType(type: string): boolean {\n\tconst semicolon = type.indexOf(';')\n\tconst bare = (semicolon === -1 ? type : type.slice(0, semicolon)).trim().toLowerCase()\n\tif (bare.length === 0) return false\n\tif (bare.startsWith('text/')) return true\n\tif (bare.endsWith('+json') || bare.endsWith('+xml')) return true\n\treturn COMPRESSIBLE_TYPES.has(bare)\n}\n\n// The conditional-request helpers (AGENTS §4.3 module-scope, §5) — ETag\n// compute/compare (RFC 7232 §2.3.2 WEAK comparison) and the TOTAL `Range`\n// parser.\n\n/**\n * Compute a CONTENT `ETag` over a fully-buffered response body via WebCrypto.\n *\n * @remarks\n * Hashes `body` with SHA-256 (`crypto.subtle.digest`) and wraps the hex\n * digest as a WEAK validator (`W/\"<hash>\"`) when `weak` is `true` — the\n * default, encoding-AGNOSTIC, so the tag survives a downstream content\n * re-encoding (gzip) and still matches on revalidation — or a STRONG one\n * (`\"<hash>\"`, byte-identity) when `weak` is `false`.\n *\n * @param body - The full (uncompressed) response body to hash\n * @param weak - `true` for a weak `W/\"…\"` validator (the default), `false` for a strong `\"…\"` one\n * @returns The `ETag` header value\n *\n * @example\n * ```ts\n * await computeBodyETag(new TextEncoder().encode('hello')) // 'W/\"…sha256-hex…\"'\n * ```\n */\nexport async function computeBodyETag(body: Uint8Array<ArrayBuffer>, weak = true): Promise<string> {\n\tconst digest = await crypto.subtle.digest('SHA-256', body)\n\tconst hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join(\n\t\t'',\n\t)\n\treturn weak ? `W/\"${hex}\"` : `\"${hex}\"`\n}\n\n/**\n * Strip the WEAK indicator (`W/`) from an entity-tag, returning its opaque\n * comparison body — the reduction {@link matchesETag} applies to both sides\n * before the RFC 7232 §2.3.2 weak comparison.\n *\n * @param tag - One entity-tag (`W/\"<body>\"` or `\"<body>\"`)\n * @returns The tag with any leading `W/` removed (the quotes preserved)\n *\n * @example\n * ```ts\n * unwrapETag('W/\"abc\"') // '\"abc\"'\n * ```\n */\nexport function unwrapETag(tag: string): string {\n\tconst trimmed = tag.trim()\n\treturn trimmed.startsWith('W/') ? trimmed.slice(2) : trimmed\n}\n\n/**\n * Whether a request's `If-None-Match` header matches a resource's current\n * `ETag` — the RFC 7232 §2.3.2 WEAK comparison.\n *\n * @remarks\n * `If-None-Match` is a COMMA-separated LIST of entity-tags (matches if ANY\n * listed tag matches), or the `*` wildcard (matches ANY current\n * representation — only a list of exactly `*` is the wildcard). Comparison is\n * WEAK: `W/\"abc\"` and `\"abc\"` are equal (both sides' weak prefix is stripped\n * via {@link unwrapETag} before comparing the opaque body). TOTAL — a\n * malformed/empty header matches nothing, never throws.\n *\n * @param header - The raw `If-None-Match` header value\n * @param etag - The resource's current `ETag`\n * @returns `true` when the conditional matches (the caller answers `304`)\n *\n * @example\n * ```ts\n * matchesETag('\"abc\", W/\"def\"', 'W/\"abc\"') // true — weak comparison\n * matchesETag('*', 'W/\"anything\"') // true — wildcard\n * ```\n */\nexport function matchesETag(header: string, etag: string): boolean {\n\tconst trimmed = header.trim()\n\tif (trimmed === '*') return true\n\tconst target = unwrapETag(etag)\n\tfor (const member of trimmed.split(',')) {\n\t\tconst candidate = member.trim()\n\t\tif (candidate.length === 0) continue\n\t\tif (unwrapETag(candidate) === target) return true\n\t}\n\treturn false\n}\n\n/**\n * Parse an HTTP `Range` request header against a known resource `size` —\n * TOTAL, returning a {@link RangeSpec} or `undefined`.\n *\n * @remarks\n * Handles the three single-range `bytes=` forms — closed (`start-end`), open\n * (`start-`), and suffix (`-suffixLength`) — clamping the window to\n * `[0, size - 1]` (the HTTP INCLUSIVE-end convention). Returns\n * `{ satisfiable: true, start, end }` for an overlapping range,\n * `{ satisfiable: false }` for a range wholly past the resource, and\n * `undefined` for the \"serve the whole resource\" case: an ABSENT header, a\n * non-`bytes` unit, a MULTI-range header (`a-b, c-d` — refused outright, not\n * supported), or any malformed/non-finite bound. NEVER throws on a hostile\n * header.\n *\n * @param header - The raw `Range` header value\n * @param size - The resource's total byte length\n * @returns The {@link RangeSpec}, or `undefined` to serve the whole resource\n *\n * @example\n * ```ts\n * parseRange('bytes=0-99', 1000) // { satisfiable: true, start: 0, end: 99 }\n * parseRange('bytes=0-1, 2-3', 1000) // undefined — multi-range refused\n * ```\n */\nexport function parseRange(header: string | undefined, size: number): RangeSpec | undefined {\n\tif (header === undefined) return undefined\n\tconst match = /^bytes=(.*)$/.exec(header.trim())\n\tif (match === null) return undefined\n\tconst spec = match[1].trim()\n\tif (spec.includes(',')) return undefined\n\tconst dash = spec.indexOf('-')\n\tif (dash < 0) return undefined\n\tconst startText = spec.slice(0, dash).trim()\n\tconst endText = spec.slice(dash + 1).trim()\n\tif (startText === '') {\n\t\tconst suffix = Number(endText)\n\t\tif (endText === '' || !Number.isInteger(suffix) || suffix <= 0) return undefined\n\t\tif (size === 0) return { satisfiable: false }\n\t\tconst start = Math.max(0, size - suffix)\n\t\treturn { satisfiable: true, start, end: size - 1 }\n\t}\n\tconst start = Number(startText)\n\tif (!Number.isInteger(start) || start < 0) return undefined\n\tif (start >= size) return { satisfiable: false }\n\tif (endText === '') return { satisfiable: true, start, end: size - 1 }\n\tconst end = Number(endText)\n\tif (!Number.isInteger(end) || end < start) return undefined\n\treturn { satisfiable: true, start, end: Math.min(end, size - 1) }\n}\n\n// The security primitives (AGENTS §4.3 module-scope, §5) — CORS origin\n// resolution, `Vary` merging, security-header resolution, request-id\n// validation, and the IPv6 `/64` rate-key collapse.\n\n/**\n * Resolve the `Access-Control-Allow-Origin` value for a request.\n *\n * @remarks\n * `'*'` and a single origin string pass straight through. An allow-list\n * echoes the request's `Origin` only when it is present in the list, else\n * `undefined` (no header set). SECURITY: the literal `'null'` origin — sent\n * by a sandboxed iframe, a `file://` document, an opaque-origin redirect — is\n * NEVER reflected even if `'null'` were listed, closing the hostile-context\n * cross-origin-access hole.\n *\n * @param origin - The configured origin policy — `'*'`, a single origin, or an allow-list\n * @param requestOrigin - The request's `Origin` header value, if present\n * @returns The allow-origin value to send, or `undefined` to set no header\n *\n * @example\n * ```ts\n * resolveOrigin(['https://app.example'], 'https://app.example') // 'https://app.example'\n * resolveOrigin(['https://app.example'], 'null') // undefined — never reflected\n * ```\n */\nexport function resolveOrigin(\n\torigin: string | readonly string[],\n\trequestOrigin: string | undefined,\n): string | undefined {\n\tif (isString(origin)) return origin\n\tif (!isString(requestOrigin)) return undefined\n\tif (requestOrigin === 'null') return undefined\n\treturn origin.includes(requestOrigin) ? requestOrigin : undefined\n}\n\n/**\n * Merge a `Vary` value into an existing `Vary` header without duplication.\n *\n * @remarks\n * Splits `existing` on `,`, trims each member, and appends `value` only when\n * no existing member already matches it case-insensitively (`Vary` header\n * names are case-insensitive). Preserves the existing members' order and\n * appends the new one last.\n *\n * @param existing - The current `Vary` header value, if any\n * @param value - The header name to ensure is listed\n * @returns The merged `Vary` value\n *\n * @example\n * ```ts\n * mergeVary(undefined, 'Origin') // 'Origin'\n * mergeVary('Origin', 'origin') // 'Origin' — no duplicate (case-insensitive)\n * mergeVary('Accept-Encoding', 'Origin') // 'Accept-Encoding, Origin'\n * ```\n */\nexport function mergeVary(existing: string | undefined, value: string): string {\n\tconst members =\n\t\texisting === undefined\n\t\t\t? []\n\t\t\t: existing\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((member) => member.trim())\n\t\t\t\t\t.filter((member) => member.length > 0)\n\tconst present = members.some((member) => member.toLowerCase() === value.toLowerCase())\n\treturn present ? members.join(', ') : [...members, value].join(', ')\n}\n\n/**\n * Resolve one opt-out, value-bearing security header.\n *\n * @remarks\n * The shared \"a `string` value, or `false` to omit, or a default when unset\"\n * resolution (AGENTS §4.4 — a value-or-off union, not a behavioral toggle):\n * `false` ⇒ `undefined` (omit the header), an explicit `string` ⇒ that\n * override, `undefined` (unset) ⇒ `fallback` (the secure default).\n *\n * @param value - The option value — a `string` override, `false` to omit, or `undefined` for the default\n * @param fallback - The secure-default value used when `value` is unset\n * @returns The header value to set, or `undefined` to omit the header\n *\n * @example\n * ```ts\n * resolveSecurityHeader(undefined, 'DENY') // 'DENY'\n * resolveSecurityHeader(false, 'DENY') // undefined — omitted\n * resolveSecurityHeader('SAMEORIGIN', 'DENY') // 'SAMEORIGIN' — override\n * ```\n */\nexport function resolveSecurityHeader(\n\tvalue: string | false | undefined,\n\tfallback: string,\n): string | undefined {\n\tif (value === false) return undefined\n\treturn value ?? fallback\n}\n\n/**\n * Whether a client-supplied `X-Request-ID` is SAFE to echo into a response\n * header + `context.state`.\n *\n * @remarks\n * A request id is echoed RAW into a response header and log lines, so an\n * untrusted one is a header-injection + log-injection + DoS vector. This\n * refuses anything off {@link import('./constants.js').REQUEST_ID_PATTERN}\n * (`^[A-Za-z0-9_-]{1,200}$` — no whitespace, no control chars, no CR/LF).\n * TOTAL — never throws.\n *\n * @param value - The candidate incoming request id\n * @returns `true` when `value` is a safe, bounded, charset-clean correlation id\n *\n * @example\n * ```ts\n * isValidRequestId('req_abc-123') // true\n * isValidRequestId('bad\\r\\nheader') // false\n * ```\n */\nexport function isValidRequestId(value: string): boolean {\n\treturn REQUEST_ID_PATTERN.test(value)\n}\n\n/**\n * Compute the `/64` network of a full IPv6 address, or `undefined` when the\n * input is not a plain IPv6 address to collapse.\n *\n * @remarks\n * Returns `undefined` for an IPv4-mapped `::ffff:a.b.c.d` (the embedded IPv4\n * is the identity) or any string that does not expand to exactly eight\n * hextets. Expands a single `::` into the missing zero hextets, takes the\n * first FOUR (the `/64` prefix), normalizes each (lower-case, no leading\n * zeros), and joins with a trailing `::/64`. A zone id (`%eth0`) is stripped\n * first. Total — a malformed address returns `undefined`.\n *\n * @param address - The candidate IPv6 address\n * @returns The `/64` network string, or `undefined` when not a plain IPv6 address\n *\n * @example\n * ```ts\n * ipv6Network('2001:db8:1:2::1') // '2001:db8:1:2::/64'\n * ipv6Network('192.0.2.1') // undefined — IPv4, not collapsed\n * ```\n */\nexport function ipv6Network(address: string): string | undefined {\n\tif (/^::ffff:\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/i.test(address)) return undefined\n\tconst percent = address.indexOf('%')\n\tconst bare = percent === -1 ? address : address.slice(0, percent)\n\tconst halves = bare.split('::')\n\tif (halves.length > 2) return undefined\n\tconst head = halves[0] === '' ? [] : halves[0].split(':')\n\tconst tail = halves.length === 2 ? (halves[1] === '' ? [] : halves[1].split(':')) : []\n\tlet groups: string[]\n\tif (halves.length === 2) {\n\t\tconst missing = 8 - head.length - tail.length\n\t\tif (missing < 0) return undefined\n\t\tgroups = [...head, ...Array.from({ length: missing }, () => '0'), ...tail]\n\t} else {\n\t\tgroups = head\n\t}\n\tif (groups.length !== 8) return undefined\n\tconst prefix: string[] = []\n\tfor (const group of groups.slice(0, 4)) {\n\t\tif (!/^[0-9a-fA-F]{1,4}$/.test(group)) return undefined\n\t\tprefix.push(Number.parseInt(group, 16).toString(16))\n\t}\n\treturn `${prefix.join(':')}::/64`\n}\n\n/**\n * Collapse a client IP into its rate-limit BUCKET key — an IPv6 address to\n * its `/64` network, an IPv4 (or IPv4-mapped) address unchanged.\n *\n * @remarks\n * A residential/mobile IPv6 user is routinely handed a WHOLE `/64`, so a\n * per-`/128` rate limit is trivially bypassed by rotating host bits — the\n * real identity is the `/64` network. Delegates the IPv6 collapse to\n * {@link ipv6Network}; anything it returns `undefined` for (an IPv4 address,\n * a malformed string) is kept unchanged.\n *\n * @param address - The raw connection peer address ({@link import('./types.js').ConnectionInfo.ip})\n * @returns The bucket key — the `/64` network for an IPv6 address, else the address unchanged\n *\n * @example\n * ```ts\n * clientRateKey('2001:db8:1:2:dead:beef:0:9') // '2001:db8:1:2::/64'\n * clientRateKey('192.0.2.1') // '192.0.2.1'\n * ```\n */\nexport function clientRateKey(address: string): string {\n\treturn ipv6Network(address) ?? address\n}\n\n// The Server-Sent-Events seam (AGENTS §4.3 module-scope, §5.4 of the\n// proposal) — `serializeEvent` is the wire encoder (the exact inverse of a\n// consuming SSE parser); `openStream` is the generic `Response`-returning\n// stream handle any streaming route (SSE today, a future producer tomorrow)\n// opens over a `ReadableStream`.\n\n/**\n * Serialize one {@link SSEMessage} to the SSE wire.\n *\n * @remarks\n * Emits an `event:`/`id:`/`retry:` line for each present field, then ONE\n * `data:` line per CRLF-aware-split (`\\r\\n` / `\\r` / `\\n`) segment of `data`\n * (so a consuming parser's multi-`data` concat reproduces the original\n * `data` exactly, and no raw `\\r` or `\\n` can ever ride onto the wire inside\n * a `data:` line), then the terminating blank line.\n *\n * @param message - The event to serialize\n * @returns The SSE wire text for the event (terminated by a blank line)\n *\n * @example\n * ```ts\n * serializeEvent({ event: 'token', data: 'hello' }) // 'event: token\\ndata: hello\\n\\n'\n * serializeEvent({ data: 'multi\\nline' }) // 'data: multi\\ndata: line\\n\\n'\n * ```\n */\nexport function serializeEvent(message: SSEMessage): string {\n\tconst lines: string[] = []\n\tif (message.event !== undefined) lines.push(`event: ${message.event}`)\n\tif (message.id !== undefined) lines.push(`id: ${message.id}`)\n\tif (message.retry !== undefined) lines.push(`retry: ${message.retry}`)\n\tfor (const segment of message.data.split(/\\r\\n|\\r|\\n/)) lines.push(`data: ${segment}`)\n\treturn `${lines.join('\\n')}\\n\\n`\n}\n\n/**\n * Open a generic Server-Sent-Events stream — a fetch-standard `Response`\n * whose body is a `ReadableStream` a caller writes {@link SSEMessage}s into.\n *\n * @remarks\n * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}\n * merged under any `options.headers` (a seam-owned key is never overridden),\n * at `options.status` (default `200`). The returned {@link StreamInterface}'s\n * `write` serializes one message ({@link serializeEvent}) and enqueues it;\n * `comment` writes a `: text` keep-alive line a conforming parser ignores;\n * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended\n * by `end()`, or the consumer cancelled the stream), so a late write never\n * throws.\n *\n * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}\n * @returns The {@link StreamInterface} handle\n *\n * @example\n * ```ts\n * const stream = openStream()\n * stream.write({ event: 'token', data: 'hello' })\n * stream.end()\n * // return stream.response from the route handler\n * ```\n */\nexport function openStream(options?: StreamOptions): StreamInterface {\n\tconst encoder = new TextEncoder()\n\tlet closed = false\n\tlet controller: ReadableStreamDefaultController<Uint8Array> | undefined\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(streamController) {\n\t\t\tcontroller = streamController\n\t\t},\n\t\tcancel() {\n\t\t\tclosed = true\n\t\t},\n\t})\n\tconst headers = new Headers({ ...SSE_HEADERS, ...options?.headers })\n\tconst response = new Response(body, { status: options?.status ?? 200, headers })\n\tconst enqueue = (text: string): void => {\n\t\tif (closed || controller === undefined) return\n\t\tcontroller.enqueue(encoder.encode(text))\n\t}\n\treturn {\n\t\tresponse,\n\t\tget closed(): boolean {\n\t\t\treturn closed\n\t\t},\n\t\twrite(message: SSEMessage): void {\n\t\t\tenqueue(serializeEvent(message))\n\t\t},\n\t\tcomment(text: string): void {\n\t\t\tenqueue(`: ${text}\\n\\n`)\n\t\t},\n\t\tend(): void {\n\t\t\tif (closed) return\n\t\t\tclosed = true\n\t\t\tcontroller?.close()\n\t\t},\n\t}\n}\n\n// The body pipeline (AGENTS §4.3 module-scope, §5.4 of the proposal) —\n// `readBody` collects a request body capped at `limit` bytes (413 over),\n// transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n// through a byte-counting `TransformStream` that ABORTS the instant\n// decompressed output exceeds `decompression` (the zip-bomb defense — fail\n// BEFORE materializing the bomb, since `DecompressionStream` has no\n// `maxOutputLength` knob), then decodes by content type. `scrubPrototype` /\n// `isDangerousKey` are the prototype-pollution scrub `readBody` applies to a\n// parsed JSON body, ported verbatim (pure value-walking logic, unaffected by\n// the fetch-vocabulary migration).\n\n/**\n * Whether a key is a PROTOTYPE-POLLUTION vector — `__proto__`, `constructor`,\n * or `prototype` — the three keys that, assigned onto a normal object, can\n * reach and mutate `Object.prototype`.\n *\n * @param key - The candidate object key\n * @returns `true` when `key` is one of the three prototype-pollution keys\n *\n * @example\n * ```ts\n * isDangerousKey('__proto__') // true\n * isDangerousKey('name') // false\n * ```\n */\nexport function isDangerousKey(key: string): boolean {\n\treturn key === '__proto__' || key === 'constructor' || key === 'prototype'\n}\n\n/**\n * Recursively STRIP the prototype-pollution keys from a parsed value IN\n * PLACE.\n *\n * @remarks\n * `JSON.parse('{\"__proto__\":{…}}')` is benign on its own — it produces an OWN,\n * enumerable `__proto__` DATA property — but that own key becomes a\n * pollution gadget the moment a downstream deep-merge copies it onto a live\n * object. This walks the value and `delete`s any own {@link isDangerousKey}\n * key at every depth, recursing into nested objects + array elements.\n * Primitives/`null` pass through untouched. Total — never throws. Mutates the\n * freshly-parsed value (which nothing else holds yet).\n *\n * @param value - The freshly `JSON.parse`d value to scrub (mutated in place)\n * @returns The same `value`, with every dangerous key removed at every depth\n *\n * @example\n * ```ts\n * scrubPrototype(JSON.parse('{\"__proto__\":{\"polluted\":true},\"name\":\"ok\"}'))\n * // { name: 'ok' } — the __proto__ key is gone\n * ```\n */\nexport function scrubPrototype(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\tfor (const item of value) scrubPrototype(item)\n\t\treturn value\n\t}\n\tif (isRecord(value)) {\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tif (isDangerousKey(key)) {\n\t\t\t\tReflect.deleteProperty(value, key)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tscrubPrototype(value[key])\n\t\t}\n\t\treturn value\n\t}\n\treturn value\n}\n\n/**\n * Collect a `Request` body into a single `Uint8Array`, enforcing a size limit.\n *\n * @remarks\n * Reads `request.body` (a `ReadableStream<Uint8Array>`) chunk by chunk,\n * throwing a {@link ContentTooLargeError} (413) the instant the running total\n * exceeds `limit` — BEFORE the rest of the stream is buffered — rather than\n * collecting an unbounded body. A bodyless request (`request.body === null`)\n * resolves an empty array. A non-positive `limit` means unbounded.\n *\n * @param request - The `Request` to drain\n * @param limit - The maximum total bytes before a 413; a non-positive value means unbounded\n * @returns The full request body as one `Uint8Array`\n * @throws {ContentTooLargeError} When the body exceeds `limit`\n *\n * @example\n * ```ts\n * const bytes = await collectRequestBody(request, 1_048_576)\n * ```\n */\nexport async function collectRequestBody(\n\trequest: Request,\n\tlimit: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tif (request.body === null) return new Uint8Array(0)\n\tconst reader = request.body.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet total = 0\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read()\n\t\tif (done) break\n\t\ttotal += value.byteLength\n\t\tif (limit > 0 && total > limit) {\n\t\t\tawait reader.cancel()\n\t\t\tthrow new ContentTooLargeError(limit)\n\t\t}\n\t\tchunks.push(value)\n\t}\n\tconst merged = new Uint8Array(total)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn merged\n}\n\n/**\n * Narrow a raw `Content-Encoding` header value to a decompressible\n * {@link Encoding} — the boundary guard {@link readBody} uses to decide\n * whether a request body needs transparent decompression.\n *\n * @remarks\n * Lower-cases + trims and returns the matching {@link Encoding} ONLY for\n * `gzip` / `deflate` (the two `DecompressionStream`-supported codings, §3 of\n * the proposal). An absent header, `identity`, an unknown value, or a\n * comma-joined multi-coding all yield `undefined` (the body is read as-is).\n * TOTAL — never asserts the loose `string | null` header.\n *\n * @param header - The raw `Content-Encoding` header value\n * @returns The single decompressible {@link Encoding}, or `undefined` when none applies\n *\n * @example\n * ```ts\n * requestEncoding('gzip') // 'gzip'\n * requestEncoding('br') // undefined — unsupported by DecompressionStream\n * ```\n */\nexport function requestEncoding(header: string | null): Exclude<Encoding, 'identity'> | undefined {\n\tif (!isString(header)) return undefined\n\tconst value = header.trim().toLowerCase()\n\treturn value === 'gzip' || value === 'deflate' ? value : undefined\n}\n\n/**\n * Transparently decompress an already-collected, `gzip`/`deflate`-encoded\n * byte sequence via `DecompressionStream`, capping the DECOMPRESSED output —\n * the zip-bomb defense.\n *\n * @remarks\n * Pipes `bytes` through `DecompressionStream(encoding)` and a byte-counting\n * `TransformStream` that ABORTS the pipe the INSTANT the running decompressed\n * total exceeds `cap` — fail-before-materialize, since `DecompressionStream`\n * has no `maxOutputLength` knob (§3 of the proposal). A cap breach surfaces\n * as a {@link ContentTooLargeError} (413); a genuinely corrupt/truncated\n * compressed stream surfaces as a distinct `400`-mappable {@link HTTPError}\n * (never conflated with the cap). A non-positive `cap` means uncapped.\n *\n * @param bytes - The compressed bytes to decompress\n * @param encoding - The {@link Encoding} the bytes are compressed with\n * @param cap - The maximum decompressed byte count; a non-positive value means uncapped\n * @returns The decompressed bytes\n * @throws {ContentTooLargeError} When decompressed output would exceed `cap`\n * @throws {HTTPError} When the compressed stream is corrupt/truncated (400)\n */\nexport async function decompressRequestBody(\n\tbytes: Uint8Array<ArrayBuffer>,\n\tencoding: Exclude<Encoding, 'identity'>,\n\tcap: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n\tlet total = 0\n\tconst capStream = new TransformStream<Uint8Array, Uint8Array>({\n\t\ttransform(chunk, controller) {\n\t\t\ttotal += chunk.byteLength\n\t\t\tif (cap > 0 && total > cap) {\n\t\t\t\tcontroller.error(new ContentTooLargeError(cap))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk)\n\t\t},\n\t})\n\tconst source = new ReadableStream<Uint8Array<ArrayBuffer>>({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue(bytes)\n\t\t\tcontroller.close()\n\t\t},\n\t})\n\tconst decompressed = source.pipeThrough(new DecompressionStream(encoding)).pipeThrough(capStream)\n\tconst reader = decompressed.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet size = 0\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (done) break\n\t\t\tchunks.push(value)\n\t\t\tsize += value.byteLength\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof ContentTooLargeError) throw error\n\t\tthrow new HTTPError(400, 'malformed compressed request body')\n\t}\n\tconst merged = new Uint8Array(size)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn merged\n}\n\n/**\n * Collect + decode a `Request` body — the shared body-collection pipeline\n * surfaced to middleware and handlers as the middleware context's cached\n * `body()`.\n *\n * @remarks\n * Collects the wire body capped at `options.limit` bytes ({@link\n * import('./constants.js').DEFAULT_BODY_LIMIT} by default — a 413 over),\n * transparently decompresses a `gzip`/`deflate` `Content-Encoding` body\n * through the zip-bomb-capped pipe ({@link decompressRequestBody}, capped at\n * `options.decompression`, default {@link\n * import('./constants.js').DEFAULT_DECOMPRESSED_LIMIT}), then decodes by\n * content type: `application/json` is parsed via `@orkestrel/contract`'s\n * `parseJSON` and scrubbed of prototype-pollution keys ({@link\n * scrubPrototype}); any other type decodes as UTF-8 text; an empty body\n * decodes to `undefined`.\n *\n * @param request - The `Request` to read the body from\n * @param options - The {@link BodyOptions} `limit` + `decompression` caps\n * @returns The parsed JSON value, the raw text, or `undefined` for an empty body\n * @throws {ContentTooLargeError} When the wire body or decompressed output exceeds its cap\n * @throws {HTTPError} When the compressed body is corrupt (400)\n *\n * @example\n * ```ts\n * const body = await readBody(request, { limit: 1_048_576 })\n * ```\n */\nexport async function readBody(request: Request, options?: BodyOptions): Promise<unknown> {\n\tconst limit = options?.limit ?? DEFAULT_BODY_LIMIT\n\tconst decompression = options?.decompression ?? DEFAULT_DECOMPRESSED_LIMIT\n\tconst wire = await collectRequestBody(request, limit)\n\tconst encoding = requestEncoding(request.headers.get('content-encoding'))\n\tconst bytes =\n\t\tencoding === undefined ? wire : await decompressRequestBody(wire, encoding, decompression)\n\tif (bytes.length === 0) return undefined\n\tconst contentType = request.headers.get('content-type')\n\tconst semicolon = contentType === null ? -1 : contentType.indexOf(';')\n\tconst bareType =\n\t\tcontentType === null\n\t\t\t? ''\n\t\t\t: (semicolon === -1 ? contentType : contentType.slice(0, semicolon)).trim().toLowerCase()\n\tconst text = new TextDecoder().decode(bytes)\n\tif (bareType === 'application/json') return scrubPrototype(parseJSON(text))\n\treturn text\n}\n","import type { Encoding, FormatHandlerMap, MiddlewareContext, NegotiatorInterface } from './types.js'\nimport { languageQuality, matchMediaType, negotiateEncoding, parseAcceptHeader } from './helpers.js'\n\n/**\n * The content-negotiation machine over the weighted `Accept` family — a\n * reusable, cross-middleware ENTITY (not a middleware). Implements exactly\n * {@link NegotiatorInterface}.\n *\n * @remarks\n * `negotiate` is the generic media-type primitive (exact / subtype-wildcard /\n * any-range, q-sorted, `;q=0` rejected); `encoding` / `language` are its\n * sibling axes and REUSE the same {@link parseAcceptHeader} q-value parser the\n * rest of the substrate uses — one parser, never two. `format` reads the\n * request `Accept`, negotiates a {@link FormatHandlerMap}'s keys, and invokes\n * the winner — or answers `406 Not Acceptable`.\n *\n * @example\n * ```ts\n * const negotiator = new Negotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport class Negotiator implements NegotiatorInterface {\n\tnegotiate(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tlet best: string | undefined\n\t\tlet bestQuality = 0\n\t\tlet bestRank = Number.POSITIVE_INFINITY\n\t\tfor (const candidate of available) {\n\t\t\tconst match = matchMediaType(entries, candidate)\n\t\t\tif (match === undefined) continue\n\t\t\tconst { q, rank } = match\n\t\t\tif (q > bestQuality || (q === bestQuality && rank < bestRank)) {\n\t\t\t\tbest = candidate\n\t\t\t\tbestQuality = q\n\t\t\t\tbestRank = rank\n\t\t\t}\n\t\t}\n\t\treturn best\n\t}\n\n\tencoding(header: string, available: readonly Encoding[]): Encoding | undefined {\n\t\treturn negotiateEncoding(header, available)\n\t}\n\n\tlanguage(header: string, available: readonly string[]): string | undefined {\n\t\tif (available.length === 0) return undefined\n\t\tconst entries = parseAcceptHeader(header)\n\t\tif (entries.length === 0) return available[0]\n\t\tlet best: string | undefined\n\t\tlet bestQuality = 0\n\t\tfor (const candidate of available) {\n\t\t\tconst quality = languageQuality(entries, candidate)\n\t\t\tif (quality > bestQuality) {\n\t\t\t\tbest = candidate\n\t\t\t\tbestQuality = quality\n\t\t\t}\n\t\t}\n\t\treturn best\n\t}\n\n\t/**\n\t * @remarks\n\t * Errors thrown by the negotiated handler propagate UNMODIFIED — the\n\t * server boundary classifies them, never this negotiator.\n\t */\n\tasync format<TState>(\n\t\trequest: Request,\n\t\tcontext: MiddlewareContext<TState>,\n\t\thandlers: FormatHandlerMap<TState>,\n\t): Promise<Response> {\n\t\tconst keys = Object.keys(handlers)\n\t\tconst header = request.headers.get('accept')\n\t\tconst type = header === null ? keys[0] : this.negotiate(header, keys)\n\t\tif (type === undefined) return new Response('Not Acceptable', { status: 406 })\n\t\tconst handler = handlers[type]\n\t\tif (handler === undefined) return new Response('Not Acceptable', { status: 406 })\n\t\treturn handler(request, context)\n\t}\n}\n","import type { NegotiatorInterface } from './types.js'\nimport { Negotiator } from './Negotiator.js'\n\n/**\n * Create a {@link NegotiatorInterface} — the reusable content-negotiation\n * machine over the weighted `Accept` family.\n *\n * @remarks\n * Prefer this over `new Negotiator()` at call sites that only need the\n * interface.\n *\n * @returns A {@link NegotiatorInterface}\n *\n * @example\n * ```ts\n * import { createNegotiator } from '@src/core'\n *\n * const negotiator = createNegotiator()\n * negotiator.negotiate('text/html, application/json;q=0.9', ['application/json', 'text/html'])\n * // 'text/html'\n * ```\n */\nexport function createNegotiator(): NegotiatorInterface {\n\treturn new Negotiator()\n}\n"],"mappings":";;;AAWA,IAAa,mBAAmB;;AAGhC,IAAa,qBAAqB;;;;;;;;;;;;;;;;;AAkBlC,IAAa,6BAA6B;;;;;;;;;;;;AAa1C,IAAa,cAAgD,OAAO,OAAO;CAC1E,gBAAgB;CAChB,iBAAiB;CACjB,YAAY;CACZ,qBAAqB;AACtB,CAAC;;;;;;;;;AAUD,IAAa,qBAAuC,OAAO,OAAO,wBAAwB;;;;;;;;;;;;;AAc1F,IAAa,qCAA0C,IAAI,IAAI;CAC9D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;;;;AAaD,IAAa,oBAAyC,OAAO,OAAO,CAAC,QAAQ,SAAS,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnEv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