@nifrajs/cli 5.4.0 → 5.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -0
- package/README.md +2 -1
- package/dist/check-scan.d.ts +6 -0
- package/dist/check-scan.d.ts.map +1 -1
- package/dist/check-scan.js +10 -10
- package/dist/check-scan.js.map +1 -1
- package/dist/check.d.ts.map +1 -1
- package/dist/check.js +1 -0
- package/dist/check.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +6 -5
- package/dist/cli.js.map +1 -1
- package/dist/docs-search.d.ts +10 -1
- package/dist/docs-search.d.ts.map +1 -1
- package/dist/docs-search.js +86 -9
- package/dist/docs-search.js.map +1 -1
- package/dist/doctor.d.ts.map +1 -1
- package/dist/doctor.js +49 -4
- package/dist/doctor.js.map +1 -1
- package/dist/internal/source-facts.d.ts +2 -1
- package/dist/internal/source-facts.d.ts.map +1 -1
- package/dist/internal/source-facts.js +17 -11
- package/dist/internal/source-facts.js.map +1 -1
- package/dist/load.d.ts +4 -1
- package/dist/load.d.ts.map +1 -1
- package/dist/load.js +8 -0
- package/dist/load.js.map +1 -1
- package/dist/lock-links.d.ts.map +1 -1
- package/dist/lock-links.js +3 -1
- package/dist/lock-links.js.map +1 -1
- package/dist/mcp-http.js +1 -1
- package/dist/recipes/5.4.0.d.ts.map +1 -1
- package/dist/recipes/5.4.0.js +2 -0
- package/dist/recipes/5.4.0.js.map +1 -1
- package/dist/recipes/5.5.0.d.ts +9 -0
- package/dist/recipes/5.5.0.d.ts.map +1 -0
- package/dist/recipes/5.5.0.js +31 -0
- package/dist/recipes/5.5.0.js.map +1 -0
- package/dist/recipes/index.d.ts +7 -0
- package/dist/recipes/index.d.ts.map +1 -1
- package/dist/recipes/index.js +2 -0
- package/dist/recipes/index.js.map +1 -1
- package/dist/release-verification.d.ts +20 -0
- package/dist/release-verification.d.ts.map +1 -1
- package/dist/release-verification.js +62 -13
- package/dist/release-verification.js.map +1 -1
- package/dist/review.d.ts.map +1 -1
- package/dist/review.js +2 -0
- package/dist/review.js.map +1 -1
- package/dist/rules/codes.d.ts +2 -0
- package/dist/rules/codes.d.ts.map +1 -1
- package/dist/rules/codes.js +2 -0
- package/dist/rules/codes.js.map +1 -1
- package/dist/rules/explanations.d.ts.map +1 -1
- package/dist/rules/explanations.js +12 -2
- package/dist/rules/explanations.js.map +1 -1
- package/dist/rules/legacy.d.ts.map +1 -1
- package/dist/rules/legacy.js +63 -19
- package/dist/rules/legacy.js.map +1 -1
- package/dist/rules/security.d.ts +6 -0
- package/dist/rules/security.d.ts.map +1 -1
- package/dist/rules/security.js +152 -2
- package/dist/rules/security.js.map +1 -1
- package/dist/rules/zones.d.ts.map +1 -1
- package/dist/rules/zones.js +43 -1
- package/dist/rules/zones.js.map +1 -1
- package/dist/smoke.d.ts +17 -1
- package/dist/smoke.d.ts.map +1 -1
- package/dist/smoke.js +49 -0
- package/dist/smoke.js.map +1 -1
- package/dist/upgrade.d.ts +40 -12
- package/dist/upgrade.d.ts.map +1 -1
- package/dist/upgrade.js +182 -17
- package/dist/upgrade.js.map +1 -1
- package/dist/verification-plan.d.ts +4 -0
- package/dist/verification-plan.d.ts.map +1 -1
- package/dist/verification-plan.js +48 -0
- package/dist/verification-plan.js.map +1 -1
- package/dist/version-drift.d.ts +2 -1
- package/dist/version-drift.d.ts.map +1 -1
- package/dist/version-drift.js +11 -26
- package/dist/version-drift.js.map +1 -1
- package/dist/web-app-options.d.ts +1 -1
- package/dist/web-app-options.d.ts.map +1 -1
- package/dist/web-app-options.js.map +1 -1
- package/docs/examples.json +14 -2
- package/docs/llms-full.txt +371 -43
- package/docs/types.json +173 -49
- package/package.json +11 -11
- package/src/check-scan.ts +10 -12
- package/src/check.ts +1 -0
- package/src/cli.ts +6 -5
- package/src/docs-search.ts +90 -10
- package/src/doctor.ts +60 -4
- package/src/internal/source-facts.ts +27 -13
- package/src/load.ts +13 -0
- package/src/lock-links.ts +3 -1
- package/src/mcp-http.ts +1 -1
- package/src/recipes/5.4.0.ts +2 -0
- package/src/recipes/5.5.0.ts +32 -0
- package/src/recipes/index.ts +9 -0
- package/src/release-verification.ts +88 -12
- package/src/review.ts +2 -0
- package/src/rules/codes.ts +2 -0
- package/src/rules/explanations.ts +12 -2
- package/src/rules/legacy.ts +75 -20
- package/src/rules/security.ts +171 -2
- package/src/rules/zones.ts +44 -1
- package/src/smoke.ts +70 -0
- package/src/upgrade.ts +199 -21
- package/src/verification-plan.ts +51 -0
- package/src/version-drift.ts +18 -26
- package/src/web-app-options.ts +1 -0
package/docs/types.json
CHANGED
|
@@ -564,7 +564,7 @@
|
|
|
564
564
|
"name": "AgentEvidenceLog",
|
|
565
565
|
"kind": "interface",
|
|
566
566
|
"package": "@nifrajs/agent",
|
|
567
|
-
"signature": "export interface AgentEvidenceLog {\n /**\n * Telemetry port recording one turn's evidence - combine it into `ports.telemetry` with\n * `combineAgentTelemetry`. Opening a finished turn reopens it (a resume of a suspended run):\n * evidence keeps appending and late replays await the new result.\n */\n open(turnId: string): AgentTelemetryPort;\n /** Mark the turn finished: live replays complete and `result` is stored for late reconnects. */\n finish(turnId: string, result: unknown): void | Promise<void>;\n
|
|
567
|
+
"signature": "export interface AgentEvidenceLog {\n /**\n * Telemetry port recording one turn's evidence - combine it into `ports.telemetry` with\n * `combineAgentTelemetry`. Opening a finished turn reopens it (a resume of a suspended run):\n * evidence keeps appending and late replays await the new result.\n */\n open(turnId: string): AgentTelemetryPort;\n /** Mark the turn finished: live replays complete and `result` is stored for late reconnects. */\n finish(turnId: string, result: unknown): void | Promise<void>;\n /**\n * The turn's evidence after `afterSeq`, or `undefined` for an unknown turn and for a cursor older\n * than the evidence the log still holds (replaying from it would skip items silently).\n */\n replay(turnId: string, afterSeq: number): AgentEvidenceReplay | undefined | Promise<AgentEvidenceReplay | undefined>;\n}",
|
|
568
568
|
"doc": "/**\n * Seam for resumable evidence streams. An HTTP seam records one turn's step evidence through\n * `open`, stores the terminal wire frame through `finish`, and serves SSE reconnects through\n * `replay` (`Last-Event-ID` maps to evidence `seq`). The stored result value is opaque to the log -\n * each seam stores whatever it needs to re-emit its own terminal frames.\n *\n * {@link createMemoryAgentEvidenceLog} is the single-process dev/test reference; a durable,\n * multi-process log is an adapter concern behind the same interface.\n */"
|
|
569
569
|
},
|
|
570
570
|
{
|
|
@@ -1044,6 +1044,13 @@
|
|
|
1044
1044
|
"package": "@nifrajs/agent",
|
|
1045
1045
|
"signature": "export interface AgentTurnError {\n readonly code: \"input_invalid\" | \"output_invalid\" | \"model_failed\";\n readonly issues?: readonly StandardIssue[];\n}"
|
|
1046
1046
|
},
|
|
1047
|
+
{
|
|
1048
|
+
"name": "AgentTurnError",
|
|
1049
|
+
"kind": "class",
|
|
1050
|
+
"package": "@nifrajs/agent-app",
|
|
1051
|
+
"signature": "export declare class AgentTurnError extends Error {\n readonly method: string;\n readonly code: string;\n constructor(method: string, code: string);\n}",
|
|
1052
|
+
"doc": "/**\n * The host ended a streamed turn with its terminal `event: error` frame. The work failed; the\n * connection did not, so it is never retried by attaching again. Carries the host's short failure\n * `code` (`turn_failed` when the frame names none it can trust), never the host's diagnostic text.\n */"
|
|
1053
|
+
},
|
|
1047
1054
|
{
|
|
1048
1055
|
"name": "AgentTurnInput",
|
|
1049
1056
|
"kind": "interface",
|
|
@@ -2252,6 +2259,13 @@
|
|
|
2252
2259
|
"signature": "export interface BudgetClock {\n /** Monotonic milliseconds; must never move backwards during the process lifetime. */\n monotonic(): number;\n /** Unix epoch milliseconds; used only to translate an absolute wire deadline on admission. */\n wall(): number;\n}",
|
|
2253
2260
|
"doc": "/** The only clocks deadline mechanics need. Inject both for deterministic tests. */"
|
|
2254
2261
|
},
|
|
2262
|
+
{
|
|
2263
|
+
"name": "BuildAssetSet",
|
|
2264
|
+
"kind": "interface",
|
|
2265
|
+
"package": "@nifrajs/web",
|
|
2266
|
+
"signature": "export interface BuildAssetSet {\n has(pathname: string): boolean;\n}",
|
|
2267
|
+
"doc": "/** The files a build emitted, by request path: the generated server manifest's `buildAssets`. */"
|
|
2268
|
+
},
|
|
2255
2269
|
{
|
|
2256
2270
|
"name": "BuildClientOptions",
|
|
2257
2271
|
"kind": "interface",
|
|
@@ -2293,13 +2307,13 @@
|
|
|
2293
2307
|
"name": "BuildServerOptions",
|
|
2294
2308
|
"kind": "interface",
|
|
2295
2309
|
"package": "@nifrajs/web",
|
|
2296
|
-
"signature": "export interface BuildServerOptions {\n /** The `routes/` directory to discover (absolute path). */\n readonly routesDir: string;\n /** The worker entry module (absolute path) - your `worker.ts`. It imports `{ manifest, clientEntry }`\n * from the generated `./server-manifest`, builds `createWebApp`, and `export default toFetchHandler(app)`. */\n readonly serverEntry: string;\n /** Output directory for the bundled worker (absolute path). */\n readonly outDir: string;\n /** The content-hashed client entry URL (from `buildClient`'s manifest) - **baked** into the generated\n * server manifest, since a disk-less worker can't read `manifest.json` at runtime. */\n readonly clientEntry
|
|
2310
|
+
"signature": "export interface BuildServerOptions {\n /** The `routes/` directory to discover (absolute path). */\n readonly routesDir: string;\n /** The worker entry module (absolute path) - your `worker.ts`. It imports `{ manifest, clientEntry }`\n * from the generated `./server-manifest`, builds `createWebApp`, and `export default toFetchHandler(app)`. */\n readonly serverEntry: string;\n /** Output directory for the bundled worker (absolute path). */\n readonly outDir: string;\n /**\n * The manifest `buildClient` returned. Supplies {@link clientEntry}, {@link styles},\n * {@link routeStyles}, {@link copyChunks} and {@link buildAssets} at once, so none can be forgotten\n * (a forgotten `styles` ships unstyled pages); an option given explicitly still wins.\n */\n readonly client?: BuildManifest;\n /** The content-hashed client entry URL (from `buildClient`'s manifest) - **baked** into the generated\n * server manifest, since a disk-less worker can't read `manifest.json` at runtime. Required unless\n * {@link client} is given. */\n readonly clientEntry?: string;\n /** The app's aggregate stylesheet URLs (`buildClient`'s `BuildManifest.css`) - baked into the generated\n * manifest so the server entry hands them to `createWebApp` (→ `<link rel=\"stylesheet\">`). Omit ⇒ no CSS\n * link (the built SSR page would otherwise render unstyled). */\n readonly styles?: readonly string[] | undefined;\n /** Per-route stylesheet URLs (`buildClient`'s `BuildManifest.routeStyles`) - baked alongside `styles`. */\n readonly routeStyles?: Readonly<Record<string, readonly string[]>> | undefined;\n /** Copy chunk URLs by locale (`buildClient`'s `BuildManifest.copyChunks`) - baked as `copyChunks`. */\n readonly copyChunks?: Readonly<Record<string, string>> | undefined;\n /**\n * Every file the build emitted, by request path (`buildClient`'s `assets` plus its `publicFiles`):\n * baked as `buildAssets` and `isBuildAsset(pathname)` for a host policy or a hand-written static\n * handler. Defaults from {@link client}; without either, the manifest exports neither name.\n */\n readonly buildAssets?: readonly string[] | undefined;\n /** How framework-owned stylesheet links should activate before hydration (default `\"blocking\"`). */\n readonly cssLoading?: CssLoadingMode;\n /** Route/layout file → import specifier in the generated manifest (default: a relative path from the\n * manifest's location - written next to `serverEntry` - to `routesDir`). */\n readonly resolve?: (file: string) => string;\n /** Filename for the generated server-manifest module, written next to `serverEntry` (default\n * `\"server-manifest.ts\"`); your `serverEntry` imports it as `./server-manifest`. */\n readonly manifestFile?: string;\n /** Adapter build plugins (e.g. `solidBunPlugin(\"ssr\")` - Solid routes need their SSR transform at\n * build time; React's JSX is Bun-native and needs none). */\n readonly plugins?: readonly BunPlugin[];\n /** `Bun.build` resolution conditions (default `[\"workerd\", \"edge-light\", \"browser\"]`) - selects each\n * dependency's edge build. */\n readonly conditions?: readonly string[];\n /** Compile-time replacements (default `{ \"process.env.NODE_ENV\": '\"production\"' }` → production\n * React/Solid on the edge). Pass an explicit object to override (e.g. `{}` to opt out). */\n readonly define?: Readonly<Record<string, string>>;\n /** Minify the output (default `true`). */\n readonly minify?: boolean;\n /** `Bun.build` target (default `\"browser\"` - the right shape for edge runtimes: Cloudflare Workers,\n * Vercel Edge, Deno, Deno Deploy). Use `\"node\"` for a `@nifrajs/node` server (so `node:*` built-ins\n * stay external), or `\"bun\"` for a Bun server. The default `conditions` + the edge resolve shims\n * only apply to the `\"browser\"` target; `\"node\"`/`\"bun\"` resolve their own renderer builds via the\n * matching condition. */\n readonly target?: \"browser\" | \"node\" | \"bun\";\n /** **Lazy/code-split routes** (default `false`): emit `() => import(route)` loaders + bundle with\n * `splitting`, so each route is its own chunk loaded on first request (smaller cold-start parse)\n * instead of all parsed at boot. The output becomes the worker entry **+ chunk files** in `outDir`\n * - on Cloudflare, ship them with wrangler's `no_bundle` + `find_additional_modules` + an ESModule\n * `rule` (Node/Deno import the chunks natively). Eager (one self-contained file) stays the default. */\n readonly lazy?: boolean;\n /** The app root the zone rules classify against (default: the directory holding `routesDir`). */\n readonly root?: string;\n /** Modules a build tool wrote or names as an entry (the adapter module a generated entry imports).\n * Like `serverEntry` and the generated manifest, they may import both halves of a route. */\n readonly generatedFiles?: readonly string[];\n /** The public-env prefix the app's browser code may read (default `\"PUBLIC_\"`). Shared code in\n * the server bundle is held to it too. */\n readonly publicEnvPrefix?: string;\n}"
|
|
2297
2311
|
},
|
|
2298
2312
|
{
|
|
2299
2313
|
"name": "BuildServerViteOptions",
|
|
2300
2314
|
"kind": "interface",
|
|
2301
2315
|
"package": "@nifrajs/web",
|
|
2302
|
-
"signature": "export interface BuildServerViteOptions {\n readonly routesDir: string;\n readonly serverEntry: string;\n readonly outDir: string;\n readonly clientEntry: string;\n readonly styles?: readonly string[] | undefined;\n readonly routeStyles?: Readonly<Record<string, readonly string[]>> | undefined;\n readonly copyChunks?: Readonly<Record<string, string>> | undefined;\n /** How framework-owned stylesheet links should activate before hydration (default `\"blocking\"`). */\n readonly cssLoading?: CssLoadingMode;\n readonly resolve?: (file: string) => string;\n readonly manifestFile?: string;\n readonly vitePlugins?: readonly unknown[];\n readonly conditions?: readonly string[];\n readonly define?: Readonly<Record<string, string>>;\n readonly minify?: boolean;\n /** The runtime the worker targets - mirrors `buildServer`. `browser` = the edge (workerd/edge-light). */\n readonly target?: \"browser\" | \"node\" | \"bun\";\n /** Vite project root (default: the parent of `routesDir`). */\n readonly root?: string;\n /** Modules the build generated besides the entry and manifest (a target's adapter import). */\n readonly generatedFiles?: readonly string[];\n /** The public-env prefix browser code may read (default `\"PUBLIC_\"`). */\n readonly publicEnvPrefix?: string;\n}",
|
|
2316
|
+
"signature": "export interface BuildServerViteOptions {\n readonly routesDir: string;\n readonly serverEntry: string;\n readonly outDir: string;\n readonly clientEntry: string;\n readonly styles?: readonly string[] | undefined;\n readonly routeStyles?: Readonly<Record<string, readonly string[]>> | undefined;\n readonly copyChunks?: Readonly<Record<string, string>> | undefined;\n /** Every file the build emitted, by request path - baked as `buildAssets` (see `buildServer`). */\n readonly buildAssets?: readonly string[] | undefined;\n /** How framework-owned stylesheet links should activate before hydration (default `\"blocking\"`). */\n readonly cssLoading?: CssLoadingMode;\n readonly resolve?: (file: string) => string;\n readonly manifestFile?: string;\n readonly vitePlugins?: readonly unknown[];\n readonly conditions?: readonly string[];\n readonly define?: Readonly<Record<string, string>>;\n readonly minify?: boolean;\n /** The runtime the worker targets - mirrors `buildServer`. `browser` = the edge (workerd/edge-light). */\n readonly target?: \"browser\" | \"node\" | \"bun\";\n /** Vite project root (default: the parent of `routesDir`). */\n readonly root?: string;\n /** Modules the build generated besides the entry and manifest (a target's adapter import). */\n readonly generatedFiles?: readonly string[];\n /** The public-env prefix browser code may read (default `\"PUBLIC_\"`). */\n readonly publicEnvPrefix?: string;\n}",
|
|
2303
2317
|
"doc": "/** Options for {@link buildServerVite} - the same surface as `buildServer` minus Bun-plugin specifics. */"
|
|
2304
2318
|
},
|
|
2305
2319
|
{
|
|
@@ -2331,7 +2345,7 @@
|
|
|
2331
2345
|
"name": "Bundler",
|
|
2332
2346
|
"kind": "interface",
|
|
2333
2347
|
"package": "@nifrajs/web",
|
|
2334
|
-
"signature": "export interface Bundler {\n /** Build the client bundle → the shared {@link BuildManifest}. */\n buildClient(input: {\n readonly routesDir: string;\n readonly outDir: string;\n readonly clientModule: string;\n readonly plugins?: readonly unknown[];\n readonly conditions?: readonly string[];\n readonly define?: Readonly<Record<string, string>>;\n readonly publicDir?: string | false;\n readonly publicEnvPrefix?: string;\n /** Vite CSS splitting policy; the Bun strategy rejects `false` and otherwise preserves its native behavior. */\n readonly cssCodeSplit?: boolean;\n /** Framework-owned stylesheet activation policy; supported by both server strategies. */\n readonly cssLoading?: CssLoadingMode;\n /** Project root (Vite needs it; the Bun strategy ignores it). */\n readonly root?: string;\n /** Reviewed false positives of the secret scan. */\n readonly secretExemptions?: readonly SecretExemption[];\n }): Promise<BuildManifest>;\n /** Build the server worker → the shared {@link ServerBuild}. */\n buildServer(input: {\n readonly routesDir: string;\n readonly serverEntry: string;\n readonly outDir: string;\n readonly clientEntry: string;\n readonly target: \"browser\" | \"node\" | \"bun\";\n /** The client build's aggregate stylesheet URLs to bake into the server manifest. */\n readonly styles?: readonly string[];\n /** The client build's per-route stylesheet map to bake into the server manifest. */\n readonly routeStyles?: Readonly<Record<string, readonly string[]>>;\n /** The client build's copy chunk URLs by locale to bake into the server manifest. */\n readonly copyChunks?: Readonly<Record<string, string>>;\n readonly plugins?: readonly unknown[];\n readonly define?: Readonly<Record<string, string>>;\n /** CSS activation policy to bake into the generated server manifest. */\n readonly cssLoading?: CssLoadingMode;\n readonly root?: string;\n /** Modules the zone rules treat as generated: the adapter module the generated entry imports. */\n readonly generatedFiles?: readonly string[];\n /** The public-env prefix browser code may read (default `\"PUBLIC_\"`). */\n readonly publicEnvPrefix?: string;\n }): Promise<ServerBuild>;\n}",
|
|
2348
|
+
"signature": "export interface Bundler {\n /** Build the client bundle → the shared {@link BuildManifest}. */\n buildClient(input: {\n readonly routesDir: string;\n readonly outDir: string;\n readonly clientModule: string;\n readonly plugins?: readonly unknown[];\n readonly conditions?: readonly string[];\n readonly define?: Readonly<Record<string, string>>;\n readonly publicDir?: string | false;\n readonly publicEnvPrefix?: string;\n /** Vite CSS splitting policy; the Bun strategy rejects `false` and otherwise preserves its native behavior. */\n readonly cssCodeSplit?: boolean;\n /** Framework-owned stylesheet activation policy; supported by both server strategies. */\n readonly cssLoading?: CssLoadingMode;\n /** Project root (Vite needs it; the Bun strategy ignores it). */\n readonly root?: string;\n /** Reviewed false positives of the secret scan. */\n readonly secretExemptions?: readonly SecretExemption[];\n }): Promise<BuildManifest>;\n /** Build the server worker → the shared {@link ServerBuild}. */\n buildServer(input: {\n readonly routesDir: string;\n readonly serverEntry: string;\n readonly outDir: string;\n readonly clientEntry: string;\n readonly target: \"browser\" | \"node\" | \"bun\";\n /** The client build's aggregate stylesheet URLs to bake into the server manifest. */\n readonly styles?: readonly string[];\n /** The client build's per-route stylesheet map to bake into the server manifest. */\n readonly routeStyles?: Readonly<Record<string, readonly string[]>>;\n /** The client build's copy chunk URLs by locale to bake into the server manifest. */\n readonly copyChunks?: Readonly<Record<string, string>>;\n /** Every file the build emitted, by request path, to bake into the server manifest. */\n readonly buildAssets?: readonly string[];\n readonly plugins?: readonly unknown[];\n readonly define?: Readonly<Record<string, string>>;\n /** CSS activation policy to bake into the generated server manifest. */\n readonly cssLoading?: CssLoadingMode;\n readonly root?: string;\n /** Modules the zone rules treat as generated: the adapter module the generated entry imports. */\n readonly generatedFiles?: readonly string[];\n /** The public-env prefix browser code may read (default `\"PUBLIC_\"`). */\n readonly publicEnvPrefix?: string;\n }): Promise<ServerBuild>;\n}",
|
|
2335
2349
|
"doc": "/**\n * A build-tool STRATEGY for {@link buildTargetWith} - the two bundling steps, and nothing else. Everything\n * around them (server-entry codegen, deploy assembly, prerender, size report) is bundler-agnostic and\n * lives in `buildTargetWith`, so a second bundler (Vite) is this interface, not a second orchestrator.\n *\n * Plugin lists are `readonly unknown[]` because a Bun plugin and a Vite plugin are different types; each\n * strategy casts to its own. `buildTargetWith` only forwards them.\n */"
|
|
2336
2350
|
},
|
|
2337
2351
|
{
|
|
@@ -2416,12 +2430,19 @@
|
|
|
2416
2430
|
"signature": "export declare const CLIENT_ENTRY_PATH = \"/__nifra/client.js\";",
|
|
2417
2431
|
"doc": "/**\n * The stable URL every SSR'd page points its client entry at.\n *\n * It has to be stable, and Bun's own URL is not: that one is a content hash over the entire client graph,\n * so it changes whenever anything the entry imports changes. This path redirects to whichever hashed\n * chunk Bun is serving at the moment the browser asks, which is the only formulation that stays correct\n * across a rebuild.\n */"
|
|
2418
2432
|
},
|
|
2433
|
+
{
|
|
2434
|
+
"name": "CONTENT_SNAPSHOT_MAX",
|
|
2435
|
+
"kind": "const",
|
|
2436
|
+
"package": "@nifrajs/core",
|
|
2437
|
+
"signature": "export declare const CONTENT_SNAPSHOT_MAX: number;",
|
|
2438
|
+
"doc": "/** Static HTTP readers tag only a whole, bounded snapshot; streamed inodes can change after hashing. */"
|
|
2439
|
+
},
|
|
2419
2440
|
{
|
|
2420
2441
|
"name": "CONTENT_TAG_MAX",
|
|
2421
2442
|
"kind": "const",
|
|
2422
2443
|
"package": "@nifrajs/core",
|
|
2423
2444
|
"signature": "export declare const CONTENT_TAG_MAX: number;",
|
|
2424
|
-
"doc": "/**\n * Largest file tagged by its content. Its first request waits for one read of the whole file, ~0.1 s\n * per 256 MiB with hardware SHA-256 and several times that on a slow disk or CPU, so a larger file -\n * a long video that is only ever fetched by ranges, say - is tagged by its device, inode, size and\n * times.
|
|
2445
|
+
"doc": "/**\n * Largest file tagged by its content. Its first request waits for one read of the whole file, ~0.1 s\n * per 256 MiB with hardware SHA-256 and several times that on a slow disk or CPU, so a larger file -\n * a long video that is only ever fetched by ranges, say - is tagged by its device, inode, size and\n * times plus a random instance salt. Identity tags require immutable file versions and intentionally\n * differ between tagger instances so local stat identities cannot collide across hosts.\n */"
|
|
2425
2446
|
},
|
|
2426
2447
|
{
|
|
2427
2448
|
"name": "CONTENT_TYPE",
|
|
@@ -3360,7 +3381,7 @@
|
|
|
3360
3381
|
"name": "ClientRetryOptions",
|
|
3361
3382
|
"kind": "interface",
|
|
3362
3383
|
"package": "@nifrajs/client",
|
|
3363
|
-
"signature": "export interface ClientRetryOptions {\n /** Max RETRIES after the first attempt. Default 2. */\n readonly attempts?: number;\n /** Response statuses to retry. Default `[502, 503, 504]`. 4xx/429 are never added by default. */\n readonly on?: readonly number[];\n /** Methods eligible for retry. Default the idempotent set `GET/HEAD/OPTIONS/PUT/DELETE`. */\n readonly methods?: readonly string[];\n /** Delay (ms) before retry `n` (1-based). Default exponential backoff with jitter, capped at 3s. */\n readonly backoff?: (attempt: number) => number;\n}",
|
|
3384
|
+
"signature": "export interface ClientRetryOptions {\n /** Max RETRIES after the first attempt. Default 2. */\n readonly attempts?: number;\n /** Response statuses to retry. Default `[502, 503, 504]`. 4xx/429 are never added by default. */\n readonly on?: readonly number[];\n /** Methods eligible for retry. Default the idempotent set `GET/HEAD/OPTIONS/PUT/DELETE/QUERY`. */\n readonly methods?: readonly string[];\n /** Delay (ms) before retry `n` (1-based). Default exponential backoff with jitter, capped at 3s. */\n readonly backoff?: (attempt: number) => number;\n}",
|
|
3364
3385
|
"doc": "/** Safe retry policy. Off unless `retry` is set; retries ONLY idempotent methods and transient 5xx -\n * never a 4xx/429 and never a non-idempotent method, so a retry can't double a side effect. */"
|
|
3365
3386
|
},
|
|
3366
3387
|
{
|
|
@@ -3724,7 +3745,7 @@
|
|
|
3724
3745
|
"name": "ContentProps",
|
|
3725
3746
|
"kind": "interface",
|
|
3726
3747
|
"package": "@nifrajs/web-preact",
|
|
3727
|
-
"signature": "export interface ContentProps extends Omit<JSX.
|
|
3748
|
+
"signature": "export interface ContentProps extends Omit<JSX.IntrinsicElements[\"div\"], \"dangerouslySetInnerHTML\"> {\n /** Trusted, pre-rendered HTML (e.g. `entry.html`). */\n readonly html: TrustedHtml;\n /** Wrapper element (default `\"div\"`). */\n readonly as?: string;\n}"
|
|
3728
3749
|
},
|
|
3729
3750
|
{
|
|
3730
3751
|
"name": "ContentProps",
|
|
@@ -3749,14 +3770,14 @@
|
|
|
3749
3770
|
"name": "ContentTagOptions",
|
|
3750
3771
|
"kind": "interface",
|
|
3751
3772
|
"package": "@nifrajs/core",
|
|
3752
|
-
"signature": "export interface ContentTagOptions {\n /** Most tags remembered at once (default 8192); past it the earliest is forgotten. */\n readonly limit?: number;\n /** The clock compared with a file's ctime (default `Date.now`). */\n readonly now?: () => number;\n}"
|
|
3773
|
+
"signature": "export interface ContentTagOptions {\n /** Most tags remembered at once (default 8192); past it the earliest is forgotten. */\n readonly limit?: number;\n /** The clock compared with a file's ctime (default `Date.now`). */\n readonly now?: () => number;\n /**\n * Largest snapshot {@link ContentTags.ofSnapshot} hashes on every request (default 4 KiB). A larger\n * one takes the tag remembered for its version once a restat shows that version. Raise it where a\n * stat costs more than hashing, as on Deno.\n */\n readonly rehashMax?: number;\n}"
|
|
3753
3774
|
},
|
|
3754
3775
|
{
|
|
3755
3776
|
"name": "ContentTags",
|
|
3756
3777
|
"kind": "interface",
|
|
3757
3778
|
"package": "@nifrajs/core",
|
|
3758
|
-
"signature": "export interface ContentTags {\n /** The tag remembered for this version of the file at `path`, if any. */\n cached(path: string, version: FileVersion): string | undefined;\n /** The tag of `bytes`, read whole from this version of the file at `path`. */\n ofBytes(path: string, version: FileVersion, bytes: Uint8Array): string;\n /**\n * The tag of this version of the file at `path`, read whole through `read`; requests for a version\n * already being read wait for that read. A file over {@link CONTENT_TAG_MAX} is not read: its tag\n * names its identity
|
|
3759
|
-
"doc": "/**\n *
|
|
3779
|
+
"signature": "export interface ContentTags {\n /** The tag remembered for this version of the file at `path`, if any. */\n cached(path: string, version: FileVersion): string | undefined;\n /** The tag of `bytes`, read whole from this version of the file at `path`. */\n ofBytes(path: string, version: FileVersion, bytes: Uint8Array): string;\n /**\n * The tag of `bytes`, the whole file at `path` read after a stat that gave `version`. A small\n * snapshot is hashed; a larger one takes the tag remembered for `version` when `restat`, called\n * after the read, still reports that version, since no write reached the file in between.\n */\n ofSnapshot(path: string, version: FileVersion, bytes: Uint8Array, restat: () => Promise<FileVersion>): Promise<string>;\n /**\n * The tag of this version of the file at `path`, read whole through `read`; requests for a version\n * already being read wait for that read. A file over {@link CONTENT_TAG_MAX} is not read: its tag\n * names its identity within this tagger instance instead, or is `undefined` without a stable identity.\n * Reading a mutable inode and later streaming it does not preserve this tag's byte identity.\n */\n ofFile(path: string, version: FileVersion, read: ReadAt): Promise<string | undefined>;\n}",
|
|
3780
|
+
"doc": "/**\n * Entity tags from file bytes, consistent across instances and runtimes. Files beyond the content\n * hash limit instead use a per-instance identity tag. Callers must serve the same immutable bytes\n * they hash; static HTTP readers use bounded snapshots for that guarantee. A tag is remembered per\n * real path for the version it was computed from.\n */"
|
|
3760
3781
|
},
|
|
3761
3782
|
{
|
|
3762
3783
|
"name": "Context",
|
|
@@ -4221,7 +4242,7 @@
|
|
|
4221
4242
|
"name": "CreateWebAppOptions",
|
|
4222
4243
|
"kind": "interface",
|
|
4223
4244
|
"package": "@nifrajs/web",
|
|
4224
|
-
"signature": "export interface CreateWebAppOptions<Env = unknown> {\n readonly serverComponents?: import(\"../server-components/types.js\").ServerComponentRuntime;\n readonly adapter: RenderAdapter;\n readonly manifest: Manifest;\n /** Cache production module imports and layout preparation, never request data. Defaults to NODE_ENV === \"production\"; disable for a mutable manifest. */\n readonly cacheRouteModules?: boolean;\n /** URL of the built client entry (module script) injected into every page. */\n readonly clientEntry: string;\n /** Default document title for all pages. */\n readonly title?: string;\n /**\n * Resolve a fresh CSP nonce for each document request. The value is applied to every\n * framework-owned executable script; return `undefined` to keep the default nonce-free output.\n * Nonce-bearing documents are marked `private, no-store` so the request-specific value is not\n * replayed by browser, CDN, or ISR caches. The resolver does not declare a CSP header because the\n * policy's allowed sources are app-specific.\n */\n readonly nonce?: NonceResolver<Env>;\n /**\n * A hash-based Content-Security-Policy from `createCspPolicy`, instead of `nonce`. A document then\n * carries a nonce only when it needs one (it `defer()`s a value, or `meta` names the nonce in\n * `unsafeInlineScript`); every other page is nonce-free, gets the same CSP header on every request,\n * and stays cacheable by `withISR` or a CDN. `meta` still receives a nonce to name.\n */\n readonly csp?: CspPolicy;\n /**\n * Options for the underlying `server()` - `requestTimeoutMs`, `admission`, `gracefulSignals`, and\n * the rest of {@link ServerOptions}.\n *\n * Needed because the `Server` is constructed in here, so a caller has no other way to reach its\n * constructor: a page app could set no request timeout and no capacity gate, which are exactly the\n * two knobs a production readiness check looks for. An SSR app wants them MORE than a backend does -\n * a render is slow and allocation-heavy, so a burst that a JSON API would absorb is the one that\n * exhausts the pod.\n *\n * Applies to the whole app, {@link mounts} and the {@link api} auto-mount included: the capacity gate\n * sits at the fetch entry, ahead of the request hooks those are dispatched from.\n */\n readonly server?: ServerOptions;\n /**\n * Runs against the app BEFORE any page route is registered - the seam for `securityHeaders()`,\n * `requestId()`, `logger()`, a rate limit, or anything else applied with `use`.\n *\n * ```ts\n * createWebApp({\n * …,\n * use: (app) => {\n * app.use(securityHeaders())\n * app.use(requestId())\n * },\n * })\n * ```\n *\n * A callback rather than an array because `use` is overloaded - `Middleware`, `IdentityPlugin`,\n * `ContextPlugin` - and only the real call site instantiates the right overload. The return value\n * is ignored: this is for cross-cutting concerns, not for declaring routes (declare those on the\n * returned app, where they get their types).\n *\n * **Why the timing matters.** `beforeHandle`, `afterHandle`, `around`, `derive`/`decorate`, and\n * `onError` are snapshotted into each route AS IT IS DECLARED, and `createWebApp` declares every\n * page (plus the `/*` catch-all) before it returns - so a caller's `app.use(…)` afterwards would\n * bind them to no page, and outside production it throws (`HOOK_AFTER_PAGES`). `requestId()` is\n * exactly that case: it is a `derive`, so applied late it would leave every page without\n * `c.requestId`. A `group()` is its own scope and stays allowed. Route assurance evidence is order-scoped the same\n * way, so a late `securityHeaders()` leaves the pages unable to PROVE the header to `nifra assure`\n * even though it does still set it.\n *\n * `onRequest`/`onResponse` (and the response header/body hooks) are app-global arrays read at\n * request time, so those alone DO work when added late. Using this seam for everything avoids\n * having to remember which is which.\n *\n * Runs ahead of the {@link mounts} / {@link api} request hooks, so an `onRequest` middleware guards\n * a mounted auth handler too.\n *\n * A `ContextPlugin` applied here takes runtime effect but cannot widen the declared return type of\n * this function, so `c.requestId` is not typed on routes you declare afterwards. Named plugins are\n * idempotent, so `app.use(requestId())` on the returned app recovers the TYPE without applying the\n * plugin a second time.\n */\n readonly use?: (app: ReturnType<typeof server<Env>>) => void;\n /** Injected into each loader's `ctx.api` - typically an `inProcessClient(app)` (typed\n * per-route via `@nifrajs/client`'s `createRoutes`). Opaque to the core.\n *\n * **Auto-mount.** Every `inProcessClient(backend)` exposes the symbol-keyed platform-aware backend\n * mount interface from `@nifrajs/core/mount`; given an {@link apiPrefix}, `createWebApp` also serves\n * that backend over HTTP there: a request whose pathname starts with the prefix is dispatched before\n * page routing with the same `env`/`waitUntil` platform context, and the backend's `Response` is\n * returned untouched. The mount runs in `nifra dev` too. Without `apiPrefix` the backend is\n * loader-only.\n *\n * **Request-scoped loader calls.** While a page renders, its loaders, actions and boundaries get a\n * `ctx.api` bound to that request's platform identity: a backend handler reached through it sees the\n * visitor's `c.clientIp` (derived under this app's `server.clientIp` trust declaration), `c.env` and\n * `c.waitUntil`, so a per-caller rate limit or audit field keys on the real visitor. `c.clientIp` is\n * the supported way to read the caller - identity travels in the platform, so rebuilding a `Request`\n * does not lose it. Headers do NOT travel: the page request's `cookie` and `authorization` are never\n * copied, so a loader call is anonymous unless the loader passes headers on the call itself. */\n readonly api?: unknown;\n /** HTTP path prefix the {@link api} backend is mounted at, such as `\"/api\"`. A request whose\n * pathname is exactly the prefix or starts with `prefix + \"/\"` is dispatched to the backend before\n * page routing; the backend therefore defines its routes at the **full** path (`server().post(\"/api/\n * sync\", …)`), matching the in-process `inProcessClient` call sites. Unset or `\"\"`, nothing is\n * mounted: the app serves pages only and `api` stays a loader-only `ctx.api`. Mounting is also a\n * no-op when `api` does not expose the symbol mount.\n *\n * A page file under the prefix (`routes/api/report.tsx`) could never render - the backend answers\n * first and its 404 is final - so `createWebApp` throws, naming the file. The same holds for every\n * other pre-route mount. */\n readonly apiPrefix?: string;\n /**\n * Strip {@link apiPrefix} from the pathname before dispatching to `api` (default `false`).\n *\n * The default suits a backend that declares FULL paths (`server().post(\"/api/sync\", …)`), which is\n * right when it is only ever mounted here. Set this when the backend declares its routes WITHOUT the\n * prefix because it also runs standalone behind its own shell, so its paths cannot carry a prefix that\n * only exists when it is mounted. Without it every request 404s inside the backend, and the workaround\n * is a `Proxy` that rewrites each URL.\n */\n readonly apiStrip?: boolean;\n /**\n * Sub-apps mounted ahead of page routing - an auth handler, a webhook receiver, a stack's routes.\n *\n * Structural on purpose: anything with `{ path, app: { fetch } }` fits, so a library that exposes its\n * routes as such a list mounts as `mounts: theirRoutes` without `@nifrajs/web` taking a dependency on\n * it. `better-auth` is the motivating case - it is not a `backend` route, so `/api/auth/*` used to 404\n * silently.\n *\n * Tried longest-path-first and BEFORE the `api` mount, so a mount at `/api/auth` wins over a backend\n * at `/api` no matter which was declared first. `stripPrefix` is the per-mount form of {@link apiStrip}:\n * leave it off to pass the full path through. `opaque` states why a mount whose routes nifra cannot\n * read (better-auth's handler) is outside assurance; it is then listed as a known gap, with any\n * routes it declares reported as declared.\n */\n readonly mounts?: ReadonlyArray<{\n readonly path: string;\n readonly app: MountableApp<Env>;\n readonly stripPrefix?: boolean;\n readonly priority?: number;\n readonly fallbackOn?: 404;\n readonly opaque?: MountOptions<Env>[\"opaque\"];\n }>;\n /** Secret for **draft / preview mode** (see `enableDraft`). When set, a request carrying a valid\n * signed `__nifra_draft` cookie gets `ctx.draft === true` in loaders/actions (else always `false`).\n * Pair with `withISR({ draftSecret })` so editors bypass the cache. Omit to disable draft mode. */\n readonly draftSecret?: string;\n /** Per-route chunk URLs (`buildClient`'s `BuildManifest.routes`) - `routeId → [layout chunks…, own\n * chunk]`. When present, each page `modulepreload`s its matched route's chunks alongside the entry,\n * so the route code downloads in parallel (no entry→route-chunk waterfall). Omit ⇒ entry-only. */\n readonly routePreload?: Readonly<Record<string, readonly string[]>>;\n /** The app's bundled stylesheet URLs (`buildClient`'s `BuildManifest.css`) - the aggregate, injected\n * as `<link rel=\"stylesheet\">` in a page's `<head>`. Used as the fallback for any route absent from\n * {@link routeStyles}. Omit ⇒ no links (dev, where Vite injects CSS, or a CSS-free app). */\n readonly styles?: readonly string[];\n /** Per-route stylesheet URLs (`buildClient`'s `BuildManifest.routeStyles`) - `routeId → [chain CSS]`.\n * When a matched route has an entry here, only those (its layout chain + own CSS) are linked instead\n * of the aggregate `styles`, so a page ships only the CSS it uses. An empty array ⇒ no `<link>` (the\n * page imports no CSS). Routes absent here fall back to `styles`. Omit ⇒ always use `styles`. */\n readonly routeStyles?: Readonly<Record<string, readonly string[]>>;\n /** Locale key -> copy chunk URL (`buildClient`'s `BuildManifest.copyChunks`, the server manifest's\n * `copyChunks`). A production client build moves copy tables (`@nifrajs/i18n/copy`) into one chunk per\n * locale; each page lists them for the browser and preloads its own. Omit ⇒ tables keep their values. */\n readonly copyChunks?: Readonly<Record<string, string>>;\n /**\n * The app's locale routing, `defineI18nRouting()` from `@nifrajs/i18n/routing`, registered once:\n * export it as `i18n` from `backend/framework.ts`. Every document then takes its locale from the\n * URL: `<html lang dir>` from the registry unless the route's meta sets `lang`, a `Content-Language`\n * header, and the locale each adapter's `useLocale()` and `<I18nProvider>` read. A route under a\n * `[lang]` or `[[lang]]` directory is checked with its `matchSegment()` before any middleware: an\n * unserved locale, or a page missing from it, is a 404, and a non-canonical prefix (`/en/x` when the\n * default is unprefixed) redirects with a 308.\n */\n readonly i18n?: WebAppI18n;\n /**\n * Activation policy for framework-owned stylesheet links (default `\"blocking\"`). `\"deferred\"`\n * emits `media=\"print\"` links; the generated client waits for them and switches them to `all` before\n * mounting. Pair with an aggregate Vite stylesheet (`cssCodeSplit: false`) to prevent lazy-prefetch\n * CSS insertion. Non-hydrated pages always keep their stylesheet links blocking.\n */\n readonly cssLoading?: CssLoadingMode;\n /** SSG: the prerendered-path set (e.g. `enumerateStaticRoutes(routes).paths` or the build's\n * `prerendered.json`). Handed over as `window.__NIFRA_PRERENDERED__` on every page so a client soft-nav\n * into a prerendered route fetches its static `_data.json` instead of hitting the worker. A set over\n * 4 KB of JSON is served once from `/__nifra/prerendered.json?v=<version>`, cacheable for good, and\n * pages hand over only that URL; `prerenderRoutes` writes the file into a static output. */\n readonly prerenderedPaths?: readonly string[];\n /**\n * Pages a self-hosted build prerendered, answered from their file instead of rendered. `nifra build\n * --target bun|node` wires this from its prerender pass. The page is served from the page route,\n * so `use` middleware and every request hook run first; a request with a query string, a navigation\n * data or component request, or a draft-mode visitor renders on demand as before. Ignored with\n * {@link nonce}, whose documents need a nonce minted for their request.\n */\n readonly prerenderedPages?: PrerenderedPages;\n /** Publish the project's `AGENTS.md` inside `/llms.txt` and `/llms-full.txt`. **Off by default**:\n * those endpoints are public and unauthenticated, while `AGENTS.md` is a repo file written for the\n * team - unreleased feature names, internal hostnames, and \"don't touch X yet\" notes live there\n * routinely. Turn it on only for a repo whose guidelines you would publish as a page. */\n readonly publishLocalGuidelines?: boolean;\n /** Serve `/llms.txt` and `/llms-full.txt`: the page routes, and the backend routes when the backend\n * is mounted over HTTP at {@link apiPrefix}, with their request and response schemas in the full\n * text. **Off by default**: both are public and unauthenticated, and they list every route, admin\n * and internal ones included. Turn it on for an app whose whole surface you would publish. */\n readonly llmsTxt?: boolean;\n /** SSG: per dynamic route pattern, its `getStaticPaths` `fallback` (from `enumerateStaticRoutes` or\n * the build's `prerendered.json`). A route mapped to `\"404\"` rejects any path NOT in\n * `prerenderedPaths` with the 404 page - the unlisted path simply doesn't exist. `\"ssr\"` (the\n * default for unmapped routes) renders unlisted paths on-demand. */\n readonly staticFallbacks?: Readonly<Record<string, \"ssr\" | \"404\">>;\n /** In-memory reference cache for explicitly `static` boundary values. It never persists payloads\n * across processes; operated/durable cache implementations stay outside the public framework. */\n readonly staticBoundaryCache?: import(\"../boundary.js\").StaticBoundaryCache;\n /** Observe every loader/action failure - for error-reporting plugins (Sentry-style). Called for\n * real throws (not control-flow `Response`s like `redirect`), **before** the nearest `_error`\n * boundary renders / a soft-nav 500 / a rethrow. A failure a boundary answers is also written to the\n * server's `logger` (under its `errorLogDetail`) whether or not this is set, exactly as an unhandled\n * error is. Observation only; its own throws are swallowed so a faulty reporter can't break\n * rendering. (`beforeLoader` is intentionally omitted - the core HTTP hooks already cover\n * pre-request work.) */\n readonly onLoaderError?: (error: unknown, ctx: {\n readonly request: Request;\n readonly params: Readonly<Record<string, string>>;\n readonly route: string;\n }) => void;\n}"
|
|
4245
|
+
"signature": "export interface CreateWebAppOptions<Env = unknown> {\n readonly serverComponents?: import(\"../server-components/types.js\").ServerComponentRuntime;\n readonly adapter: RenderAdapter;\n readonly manifest: Manifest;\n /** Cache production module imports and layout preparation, never request data. Defaults to NODE_ENV === \"production\"; disable for a mutable manifest. */\n readonly cacheRouteModules?: boolean;\n /** URL of the built client entry (module script) injected into every page. */\n readonly clientEntry: string;\n /** Default document title for all pages. */\n readonly title?: string;\n /**\n * Resolve a fresh CSP nonce for each document request. The value is applied to every\n * framework-owned executable script; return `undefined` to keep the default nonce-free output.\n * Nonce-bearing documents are marked `private, no-store` so the request-specific value is not\n * replayed by browser, CDN, or ISR caches. The resolver does not declare a CSP header because the\n * policy's allowed sources are app-specific.\n */\n readonly nonce?: NonceResolver<Env>;\n /**\n * A hash-based Content-Security-Policy from `createCspPolicy`, instead of `nonce`. A document then\n * carries a nonce only when it needs one (it `defer()`s a value, or `meta` names the nonce in\n * `unsafeInlineScript`); every other page is nonce-free, gets the same CSP header on every request,\n * and stays cacheable by `withISR` or a CDN. `meta` still receives a nonce to name.\n */\n readonly csp?: CspPolicy;\n /**\n * Options for the underlying `server()` - `requestTimeoutMs`, `admission`, `gracefulSignals`, and\n * the rest of {@link ServerOptions}.\n *\n * Needed because the `Server` is constructed in here, so a caller has no other way to reach its\n * constructor: a page app could set no request timeout and no capacity gate, which are exactly the\n * two knobs a production readiness check looks for. An SSR app wants them MORE than a backend does -\n * a render is slow and allocation-heavy, so a burst that a JSON API would absorb is the one that\n * exhausts the pod.\n *\n * Applies to the whole app, {@link mounts} and the {@link api} auto-mount included: the capacity gate\n * sits at the fetch entry, ahead of the request hooks those are dispatched from.\n */\n readonly server?: ServerOptions;\n /**\n * Runs against the app BEFORE any page route is registered - the seam for `securityHeaders()`,\n * `requestId()`, `logger()`, a rate limit, or anything else applied with `use`.\n *\n * ```ts\n * createWebApp({\n * …,\n * use: (app) => {\n * app.use(securityHeaders())\n * app.use(requestId())\n * },\n * })\n * ```\n *\n * A callback rather than an array because `use` is overloaded - `Middleware`, `IdentityPlugin`,\n * `ContextPlugin` - and only the real call site instantiates the right overload. The return value\n * is ignored: this is for cross-cutting concerns, not for declaring routes (declare those on the\n * returned app, where they get their types).\n *\n * **Why the timing matters.** `beforeHandle`, `afterHandle`, `around`, `derive`/`decorate`, and\n * `onError` are snapshotted into each route AS IT IS DECLARED, and `createWebApp` declares every\n * page (plus the `/*` catch-all) before it returns - so a caller's `app.use(…)` afterwards would\n * bind them to no page, and outside production it throws (`HOOK_AFTER_PAGES`). `requestId()` is\n * exactly that case: it is a `derive`, so applied late it would leave every page without\n * `c.requestId`. A `group()` is its own scope and stays allowed. Route assurance evidence is order-scoped the same\n * way, so a late `securityHeaders()` leaves the pages unable to PROVE the header to `nifra assure`\n * even though it does still set it.\n *\n * `onRequest`/`onResponse` (and the response header/body hooks) are app-global arrays read at\n * request time, so those alone DO work when added late. Using this seam for everything avoids\n * having to remember which is which.\n *\n * Runs ahead of the {@link mounts} / {@link api} request hooks, so an `onRequest` middleware guards\n * a mounted auth handler too.\n *\n * A `ContextPlugin` applied here takes runtime effect but cannot widen the declared return type of\n * this function, so `c.requestId` is not typed on routes you declare afterwards. Named plugins are\n * idempotent, so `app.use(requestId())` on the returned app recovers the TYPE without applying the\n * plugin a second time.\n */\n readonly use?: (app: ReturnType<typeof server<Env>>) => void;\n /** Injected into each loader's `ctx.api` - typically an `inProcessClient(app)` (typed\n * per-route via `@nifrajs/client`'s `createRoutes`). Opaque to the core.\n *\n * **Auto-mount.** Every `inProcessClient(backend)` exposes the symbol-keyed platform-aware backend\n * mount interface from `@nifrajs/core/mount`; given an {@link apiPrefix}, `createWebApp` also serves\n * that backend over HTTP there: a request whose pathname starts with the prefix is dispatched before\n * page routing with the same `env`/`waitUntil` platform context, and the backend's `Response` is\n * returned untouched. The mount runs in `nifra dev` too. Without `apiPrefix` the backend is\n * loader-only.\n *\n * **Request-scoped loader calls.** While a page renders, its loaders, actions and boundaries get a\n * `ctx.api` bound to that request's platform identity: a backend handler reached through it sees the\n * visitor's `c.clientIp` (derived under this app's `server.clientIp` trust declaration), `c.env` and\n * `c.waitUntil`, so a per-caller rate limit or audit field keys on the real visitor. `c.clientIp` is\n * the supported way to read the caller - identity travels in the platform, so rebuilding a `Request`\n * does not lose it. Headers do NOT travel: the page request's `cookie` and `authorization` are never\n * copied, so a loader call is anonymous unless the loader passes headers on the call itself. */\n readonly api?: unknown;\n /** HTTP path prefix the {@link api} backend is mounted at, such as `\"/api\"`. A request whose\n * pathname is exactly the prefix or starts with `prefix + \"/\"` is dispatched to the backend before\n * page routing; the backend therefore defines its routes at the **full** path (`server().post(\"/api/\n * sync\", …)`), matching the in-process `inProcessClient` call sites. Unset or `\"\"`, nothing is\n * mounted: the app serves pages only and `api` stays a loader-only `ctx.api`. Mounting is also a\n * no-op when `api` does not expose the symbol mount.\n *\n * A page file under the prefix (`routes/api/report.tsx`) could never render - the backend answers\n * first and its 404 is final - so `createWebApp` throws, naming the file. The same holds for every\n * other pre-route mount. */\n readonly apiPrefix?: string;\n /**\n * Strip {@link apiPrefix} from the pathname before dispatching to `api` (default `false`).\n *\n * The default suits a backend that declares FULL paths (`server().post(\"/api/sync\", …)`), which is\n * right when it is only ever mounted here. Set this when the backend declares its routes WITHOUT the\n * prefix because it also runs standalone behind its own shell, so its paths cannot carry a prefix that\n * only exists when it is mounted. Without it every request 404s inside the backend, and the workaround\n * is a `Proxy` that rewrites each URL.\n */\n readonly apiStrip?: boolean;\n /**\n * Sub-apps mounted ahead of page routing - an auth handler, a webhook receiver, a stack's routes.\n *\n * Structural on purpose: anything with `{ path, app: { fetch } }` fits, so a library that exposes its\n * routes as such a list mounts as `mounts: theirRoutes` without `@nifrajs/web` taking a dependency on\n * it. `better-auth` is the motivating case - it is not a `backend` route, so `/api/auth/*` used to 404\n * silently.\n *\n * Tried longest-path-first and BEFORE the `api` mount, so a mount at `/api/auth` wins over a backend\n * at `/api` no matter which was declared first. `stripPrefix` is the per-mount form of {@link apiStrip}:\n * leave it off to pass the full path through. `opaque` states why a mount whose routes nifra cannot\n * read (better-auth's handler) is outside assurance; it is then listed as a known gap, with any\n * routes it declares reported as declared.\n */\n readonly mounts?: ReadonlyArray<{\n readonly path: string;\n readonly app: MountableApp<Env>;\n readonly stripPrefix?: boolean;\n readonly priority?: number;\n readonly fallbackOn?: 404;\n readonly opaque?: MountOptions<Env>[\"opaque\"];\n }>;\n /** Secret for **draft / preview mode** (see `enableDraft`). When set, a request carrying a valid\n * signed `__nifra_draft` cookie gets `ctx.draft === true` in loaders/actions (else always `false`).\n * Pair with `withISR({ draftSecret })` so editors bypass the cache. Omit to disable draft mode. */\n readonly draftSecret?: string;\n /** Per-route chunk URLs (`buildClient`'s `BuildManifest.routes`) - `routeId → [layout chunks…, own\n * chunk]`. When present, each page `modulepreload`s its matched route's chunks alongside the entry,\n * so the route code downloads in parallel (no entry→route-chunk waterfall). Omit ⇒ entry-only. */\n readonly routePreload?: Readonly<Record<string, readonly string[]>>;\n /** The app's bundled stylesheet URLs (`buildClient`'s `BuildManifest.css`) - the aggregate, injected\n * as `<link rel=\"stylesheet\">` in a page's `<head>`. Used as the fallback for any route absent from\n * {@link routeStyles}. Omit ⇒ no links (dev, where Vite injects CSS, or a CSS-free app). */\n readonly styles?: readonly string[];\n /** Per-route stylesheet URLs (`buildClient`'s `BuildManifest.routeStyles`) - `routeId → [chain CSS]`.\n * When a matched route has an entry here, only those (its layout chain + own CSS) are linked instead\n * of the aggregate `styles`, so a page ships only the CSS it uses. An empty array ⇒ no `<link>` (the\n * page imports no CSS). Routes absent here fall back to `styles`. Omit ⇒ always use `styles`. */\n readonly routeStyles?: Readonly<Record<string, readonly string[]>>;\n /** Locale key -> copy chunk URL (`buildClient`'s `BuildManifest.copyChunks`, the server manifest's\n * `copyChunks`). A production client build moves copy tables (`@nifrajs/i18n/copy`) into one chunk per\n * locale; each page lists them for the browser and preloads its own. Omit ⇒ tables keep their values. */\n readonly copyChunks?: Readonly<Record<string, string>>;\n /**\n * The app's locale routing, `defineI18nRouting()` from `@nifrajs/i18n/routing`, registered once:\n * export it as `i18n` from `backend/framework.ts`. Every document then takes its locale from the\n * URL: `<html lang dir>` from the registry unless the route's meta sets `lang`, a `Content-Language`\n * header, and the locale each adapter's `useLocale()` and `<I18nProvider>` read. A route under a\n * `[lang]` or `[[lang]]` directory is checked with its `matchSegment()` before any middleware: an\n * unserved locale, or a page missing from it, is a 404, and a non-canonical prefix (`/en/x` when the\n * default is unprefixed) redirects with a 308.\n */\n readonly i18n?: WebAppI18n;\n /**\n * Activation policy for framework-owned stylesheet links (default `\"blocking\"`). `\"deferred\"`\n * emits `media=\"print\"` links; the generated client waits for them and switches them to `all` before\n * mounting. Pair with an aggregate Vite stylesheet (`cssCodeSplit: false`) to prevent lazy-prefetch\n * CSS insertion. Non-hydrated pages always keep their stylesheet links blocking.\n */\n readonly cssLoading?: CssLoadingMode;\n /** SSG: the prerendered-path set (e.g. `enumerateStaticRoutes(routes).paths` or the build's\n * `prerendered.json`). Handed over as `window.__NIFRA_PRERENDERED__` on every page so a client soft-nav\n * into a prerendered route fetches its static `_data.json` instead of hitting the worker, unless the\n * target carries a query string, which renders on demand as a hard request does. A set over\n * 4 KB of JSON is served once from `/__nifra/prerendered.json?v=<version>`, cacheable for good, and\n * pages hand over only that URL; `prerenderRoutes` writes the file into a static output. */\n readonly prerenderedPaths?: readonly string[];\n /**\n * Pages a self-hosted build prerendered, answered from their file instead of rendered. `nifra build\n * --target bun|node` wires this from its prerender pass. The page is served from the page route,\n * so `use` middleware and every request hook run first; a request with a query string, a navigation\n * data or component request, or a draft-mode visitor renders on demand as before. Ignored with\n * {@link nonce}, whose documents need a nonce minted for their request.\n */\n readonly prerenderedPages?: PrerenderedPages;\n /**\n * Which pages and files each host serves, from `createHostPolicy()`. Evaluated before everything\n * else the app answers (prerendered pages, mounts, the API, every page) and, in a `nifra build`\n * server entry, before its static files too. A refused path answers the policy's refusal.\n */\n readonly hostPolicy?: HostPolicy;\n /**\n * The files the build emitted, by request path: `buildAssets` from the generated server manifest.\n * A {@link hostPolicy} rule's `buildAssets` token matches exactly these. `nifra dev` serves the\n * client bundle and `public/` ahead of the app, so the app's own check never sees them there.\n */\n readonly buildAssets?: BuildAssetSet;\n /** Publish the project's `AGENTS.md` inside `/llms.txt` and `/llms-full.txt`. **Off by default**:\n * those endpoints are public and unauthenticated, while `AGENTS.md` is a repo file written for the\n * team - unreleased feature names, internal hostnames, and \"don't touch X yet\" notes live there\n * routinely. Turn it on only for a repo whose guidelines you would publish as a page. */\n readonly publishLocalGuidelines?: boolean;\n /** Serve `/llms.txt` and `/llms-full.txt`: the page routes, and the backend routes when the backend\n * is mounted over HTTP at {@link apiPrefix}, with their request and response schemas in the full\n * text. **Off by default**: both are public and unauthenticated, and they list every route, admin\n * and internal ones included. Turn it on for an app whose whole surface you would publish. */\n readonly llmsTxt?: boolean;\n /** SSG: per dynamic route pattern, its `getStaticPaths` `fallback` (from `enumerateStaticRoutes` or\n * the build's `prerendered.json`). A route mapped to `\"404\"` rejects any path NOT in\n * `prerenderedPaths` with the 404 page - the unlisted path simply doesn't exist. `\"ssr\"` (the\n * default for unmapped routes) renders unlisted paths on-demand. */\n readonly staticFallbacks?: Readonly<Record<string, \"ssr\" | \"404\">>;\n /** In-memory reference cache for explicitly `static` boundary values. It never persists payloads\n * across processes; operated/durable cache implementations stay outside the public framework. */\n readonly staticBoundaryCache?: import(\"../boundary.js\").StaticBoundaryCache;\n /** Observe every loader/action failure - for error-reporting plugins (Sentry-style). Called for\n * real throws (not control-flow `Response`s like `redirect`), **before** the nearest `_error`\n * boundary renders / a soft-nav 500 / a rethrow. A failure a boundary answers is also written to the\n * server's `logger` (under its `errorLogDetail`) whether or not this is set, exactly as an unhandled\n * error is. Observation only; its own throws are swallowed so a faulty reporter can't break\n * rendering. (`beforeLoader` is intentionally omitted - the core HTTP hooks already cover\n * pre-request work.) */\n readonly onLoaderError?: (error: unknown, ctx: {\n readonly request: Request;\n readonly params: Readonly<Record<string, string>>;\n readonly route: string;\n }) => void;\n}"
|
|
4225
4246
|
},
|
|
4226
4247
|
{
|
|
4227
4248
|
"name": "CronError",
|
|
@@ -4268,7 +4289,7 @@
|
|
|
4268
4289
|
"name": "CsrfOptions",
|
|
4269
4290
|
"kind": "interface",
|
|
4270
4291
|
"package": "@nifrajs/middleware",
|
|
4271
|
-
"signature": "export interface CsrfOptions {\n /** HMAC secret (≥ 32 bytes), or a rotation list - see {@link CsrfSecret}. */\n readonly secret: CsrfSecret;\n /** Cookie carrying the signed token. Default `\"csrf-token\"`. */\n readonly cookie?: string;\n /** Header carrying the same signed token. Default `\"x-csrf-token\"`. */\n readonly header?: string;\n /**\n * Form field that may carry the token when the header is absent, so a plain HTML `<form>` (no\n * script to set a header) can submit - e.g. `field: \"_csrf\"` with\n * `<input type=\"hidden\" name=\"_csrf\" value=\"...\">`. Read from `application/x-www-form-urlencoded`\n * and `multipart/form-data` bodies only, through a clone, so the handler still reads the body.\n * Unset (default), only the header is accepted.\n *\n * A cross-site form can set any field but never a custom header, so keep `checkOrigin` on with a\n * field: the Origin check is what stops a site that can plant a cookie on your domain (a sibling\n * subdomain) from pairing it with a matching field.\n */\n readonly field?: string;\n /**\n * Largest body scanned for {@link field}, in bytes. Default 64 KiB. A bigger form (a file upload)\n * fails closed - send the header, or raise this for that app.\n */\n readonly fieldMaxBytes?: number;\n /** Unsafe methods to protect. Default: every method except GET/HEAD/OPTIONS/TRACE. */\n readonly methods?: readonly string[];\n /** Allowed request origins. Default: same host as the request URL, where an `https:` Origin may\n * reach an `http:` URL (what a TLS-terminating proxy looks like from the server). */\n readonly origins?: readonly string[];\n /** Check Origin/Referer on protected requests. Default true. */\n readonly checkOrigin?: boolean;\n}"
|
|
4292
|
+
"signature": "export interface CsrfOptions {\n /** HMAC secret (≥ 32 bytes), or a rotation list - see {@link CsrfSecret}. */\n readonly secret: CsrfSecret;\n /** Cookie carrying the signed token. Default `\"csrf-token\"`. */\n readonly cookie?: string;\n /** Header carrying the same signed token. Default `\"x-csrf-token\"`. */\n readonly header?: string;\n /**\n * Form field that may carry the token when the header is absent, so a plain HTML `<form>` (no\n * script to set a header) can submit - e.g. `field: \"_csrf\"` with\n * `<input type=\"hidden\" name=\"_csrf\" value=\"...\">`. Read from `application/x-www-form-urlencoded`\n * and `multipart/form-data` bodies only, through a clone, so the handler still reads the body.\n * Unset (default), only the header is accepted.\n *\n * A cross-site form can set any field but never a custom header, so keep `checkOrigin` on with a\n * field: the Origin check is what stops a site that can plant a cookie on your domain (a sibling\n * subdomain) from pairing it with a matching field.\n */\n readonly field?: string;\n /**\n * Largest body scanned for {@link field}, in bytes. Default 64 KiB. A bigger form (a file upload)\n * fails closed - send the header, or raise this for that app.\n */\n readonly fieldMaxBytes?: number;\n /** Unsafe methods to protect. Default: every method except GET/HEAD/OPTIONS/TRACE/QUERY. */\n readonly methods?: readonly string[];\n /** Allowed request origins. Default: same host as the request URL, where an `https:` Origin may\n * reach an `http:` URL (what a TLS-terminating proxy looks like from the server). */\n readonly origins?: readonly string[];\n /** Check Origin/Referer on protected requests. Default true. */\n readonly checkOrigin?: boolean;\n}"
|
|
4272
4293
|
},
|
|
4273
4294
|
{
|
|
4274
4295
|
"name": "CssLoadingMode",
|
|
@@ -6299,7 +6320,7 @@
|
|
|
6299
6320
|
"name": "FileStorage",
|
|
6300
6321
|
"kind": "class",
|
|
6301
6322
|
"package": "@nifrajs/storage",
|
|
6302
|
-
"signature": "export declare class FileStorage implements StorageAdapter {\n private root;\n private metadataRoot;\n private legacyMetadataRoot;\n private stagingRoot;\n /** Each key's latest write, so this instance publishes a key's body and sidecar one put at a time. */\n private readonly writes;\n /** The directory holding the root and its bookkeeping, by real path and identity, once resolved. */\n private anchor;\n constructor(root: string);\n private placeRoot;\n /**\n * Resolve the directory holding the root (or its nearest existing ancestor) once, then work beneath\n * that real path and prove before every operation that it is still the same directory. Swapping an\n * ancestor, for a symbolic link or by a rename from whoever can write above the root, then cannot\n * redirect a later read, write or delete into another tree: the operation fails closed instead.\n */\n private pinRoot;\n private movedError;\n /**\n * Move the pin down to the directory holding the root once it exists. Pinned at first use, the\n * anchor is the nearest existing ancestor; a directory a first write creates below it was never\n * checked again, so swapping it for a link redirected every later operation. Called right after\n * such a write creates directories, and before every operation.\n */\n private pinHolder;\n private resolveAnchor;\n private metadataPathFor;\n /** `<key>.json`, where earlier versions kept a sidecar: `a.json` there is also key `a.json`'s parent. */\n private legacyMetadataPathFor;\n private containedPath;\n /** Resolve `key` to an absolute path, asserting it stays inside `root` (defense-in-depth on top of `assertSafeKey`). */\n private pathFor;\n private symlinkError;\n private assertTrustedDirectory;\n /**\n * Prove that another local principal cannot rename any directory leading to `base` after validation.\n * A sticky shared parent (the ordinary `/tmp` case) is safe only while its child belongs to this uid.\n * Root-owned system directories are trusted; a directory owned by any other uid is not.\n */\n private assertTrustedAncestorChain;\n /** Reject existing symbolic links below `base`; missing suffixes are safe for later creation. */\n private assertNoSymlinkPath;\n /** {@link openContained} for an object: a directory under the root is a key prefix, not an object. */\n private openObject;\n /**\n * Open an existing file without following its final component, then prove the descriptor is the file\n * still reachable through a symlink-free path below the same root inode. Reads use the descriptor,\n * not the pathname checked earlier, closing their check/open race.\n */\n private openContained;\n private assertOpenedContained;\n /**\n * Write `data` whole or not at all: staged in a sibling directory, then renamed over `path`, so a\n * reader never sees a half-written object and a failed write leaves the previous one. The renamed\n * inode is then proven to be the staged one, reachable beneath the same root.\n */\n private writeContained;\n /** A new, exclusively created file in the staging directory holding `data`. */\n private stage;\n /**\n * Create parents and open without truncating. The opened inode is validated against the current,\n * fully resolved path before any caller data is written, closing the check/open symlink race.\n */\n private writeInPlace;\n /** Run `write` after this instance's earlier write of `key` settles. */\n private serialized;\n put(key: string, data: StorageData, options?: PutOptions): Promise<void>;\n get(key: string): Promise<StorageObject | null>;\n delete(key: string): Promise<void>;\n private readMetadata;\n private removeLegacyMetadata;\n exists(key: string): Promise<boolean>;\n /** Revalidate an opened inode immediately before unlinking its pathname. */\n private removeContained;\n list(options?: ListOptions): Promise<string[]>;\n /** The directory for key prefix `dirKey`, or `undefined` when no plain directory chain leads there. */\n private listingDirectory;\n private walk;\n}"
|
|
6323
|
+
"signature": "export declare class FileStorage implements StorageAdapter {\n private root;\n private metadataRoot;\n private legacyMetadataRoot;\n private stagingRoot;\n /** Each key's latest write, so this instance publishes a key's body and sidecar one put at a time. */\n private readonly writes;\n /** The directory holding the root and its bookkeeping, by real path and identity, once resolved. */\n private anchor;\n constructor(root: string);\n private placeRoot;\n /**\n * Resolve the directory holding the root (or its nearest existing ancestor) once, then work beneath\n * that real path and prove before every operation that it is still the same directory. Swapping an\n * ancestor, for a symbolic link or by a rename from whoever can write above the root, then cannot\n * redirect a later read, write or delete into another tree: the operation fails closed instead.\n */\n private pinRoot;\n private movedError;\n /**\n * Move the pin down to the directory holding the root once it exists. Pinned at first use, the\n * anchor is the nearest existing ancestor; a directory a first write creates below it was never\n * checked again, so swapping it for a link redirected every later operation. Called right after\n * such a write creates directories, and before every operation.\n */\n private pinHolder;\n private resolveAnchor;\n private metadataPathFor;\n /** `<key>.json`, where earlier versions kept a sidecar: `a.json` there is also key `a.json`'s parent. */\n private legacyMetadataPathFor;\n private containedPath;\n /** Resolve `key` to an absolute path, asserting it stays inside `root` (defense-in-depth on top of `assertSafeKey`). */\n private pathFor;\n private symlinkError;\n private assertTrustedDirectory;\n /**\n * Prove that another local principal cannot rename any directory leading to `base` after validation.\n * A sticky shared parent (the ordinary `/tmp` case) is safe only while its child belongs to this uid.\n * Root-owned system directories are trusted; a directory owned by any other uid is not.\n */\n private assertTrustedAncestorChain;\n /** Reject existing symbolic links below `base`; missing suffixes are safe for later creation. */\n private assertNoSymlinkPath;\n /** {@link openContained} for an object: a directory under the root is a key prefix, not an object. */\n private openObject;\n /**\n * Open an existing file without following its final component, then prove the descriptor is the file\n * still reachable through a symlink-free path below the same root inode. Reads use the descriptor,\n * not the pathname checked earlier, closing their check/open race.\n */\n private openContained;\n private assertOpenedContained;\n /**\n * Write `data` whole or not at all: staged in a sibling directory, then renamed over `path`, so a\n * reader never sees a half-written object and a failed write leaves the previous one. The renamed\n * inode is then proven to be the staged one, reachable beneath the same root.\n */\n private writeContained;\n /** A new, exclusively created file in the staging directory holding `data`. */\n private stage;\n /**\n * Create parents and open without truncating. The opened inode is validated against the current,\n * fully resolved path before any caller data is written, closing the check/open symlink race.\n */\n private writeInPlace;\n /** Run `write` after this instance's earlier write of `key` settles. */\n private serialized;\n put(key: string, data: StorageData, options?: PutOptions): Promise<void>;\n get(key: string): Promise<StorageObject | null>;\n delete(key: string): Promise<void>;\n private readMetadata;\n private removeLegacyMetadata;\n exists(key: string): Promise<boolean>;\n /** Revalidate an opened inode immediately before unlinking its pathname. */\n private removeContained;\n list(options?: ListOptions): Promise<string[]>;\n /** The directory for key prefix `dirKey`, or `undefined` when no plain directory chain leads there. */\n private listingDirectory;\n private walk;\n private directoryEntries;\n}"
|
|
6303
6324
|
},
|
|
6304
6325
|
{
|
|
6305
6326
|
"name": "FileType",
|
|
@@ -6496,7 +6517,7 @@
|
|
|
6496
6517
|
"name": "GenerateServerManifestOptions",
|
|
6497
6518
|
"kind": "interface",
|
|
6498
6519
|
"package": "@nifrajs/web",
|
|
6499
|
-
"signature": "export interface GenerateServerManifestOptions {\n /** Turn a route/layout source file (relative to the routes dir) into an import specifier -\n * same contract as `generateClientEntry`'s `resolve`. */\n readonly resolve: (file: string) => string;\n /** The content-hashed client entry URL (from `buildClient`'s manifest), **baked** into the emitted\n * module - a disk-less worker can't read `manifest.json` at runtime. */\n readonly clientEntry: string;\n /** The app's aggregate stylesheet URLs (`buildClient`'s `BuildManifest.css`) - baked as\n * `export const styles` so the server entry can hand them to `createWebApp` (→ `<link rel=\"stylesheet\">`\n * in `<head>`). Without this the built SSR page ships no CSS link and renders unstyled. */\n readonly styles?: readonly string[] | undefined;\n /** Per-route stylesheet URLs (`buildClient`'s `BuildManifest.routeStyles`) - baked as\n * `export const routeStyles` so a page links only the CSS its route chain uses. */\n readonly routeStyles?: Readonly<Record<string, readonly string[]>> | undefined;\n /** How framework-owned stylesheet links should activate before the generated client mounts. */\n readonly cssLoading?: CssLoadingMode;\n /** Locale key -> copy chunk URL (`buildClient`'s `BuildManifest.copyChunks`) - baked as\n * `export const copyChunks` when the client build split copy tables, for `createWebApp`. */\n readonly copyChunks?: Readonly<Record<string, string>> | undefined;\n /** Emit **lazy** per-route loaders (`() => import(\"./routes/x\")`, a static specifier) instead of\n * eager `import * as`, so a bundler with code-splitting emits one chunk per route - loaded on the\n * first request to it, not all at boot (smaller cold-start parse). Default `false` (eager). Both\n * modes are fs-free with statically-analyzable specifiers; only the *when* differs. */\n readonly lazy?: boolean;\n}"
|
|
6520
|
+
"signature": "export interface GenerateServerManifestOptions {\n /** Turn a route/layout source file (relative to the routes dir) into an import specifier -\n * same contract as `generateClientEntry`'s `resolve`. */\n readonly resolve: (file: string) => string;\n /** The content-hashed client entry URL (from `buildClient`'s manifest), **baked** into the emitted\n * module - a disk-less worker can't read `manifest.json` at runtime. */\n readonly clientEntry: string;\n /** The app's aggregate stylesheet URLs (`buildClient`'s `BuildManifest.css`) - baked as\n * `export const styles` so the server entry can hand them to `createWebApp` (→ `<link rel=\"stylesheet\">`\n * in `<head>`). Without this the built SSR page ships no CSS link and renders unstyled. */\n readonly styles?: readonly string[] | undefined;\n /** Per-route stylesheet URLs (`buildClient`'s `BuildManifest.routeStyles`) - baked as\n * `export const routeStyles` so a page links only the CSS its route chain uses. */\n readonly routeStyles?: Readonly<Record<string, readonly string[]>> | undefined;\n /** How framework-owned stylesheet links should activate before the generated client mounts. */\n readonly cssLoading?: CssLoadingMode;\n /** Locale key -> copy chunk URL (`buildClient`'s `BuildManifest.copyChunks`) - baked as\n * `export const copyChunks` when the client build split copy tables, for `createWebApp`. */\n readonly copyChunks?: Readonly<Record<string, string>> | undefined;\n /**\n * The request path of every file the build emitted: the client build's `assets` and the `public/`\n * files it copied. Baked as `export const buildAssets` (a `Set`) and `isBuildAsset(pathname)`, so a\n * server entry or a host policy can allow exactly the files that exist. Omitted ⇒ neither export.\n */\n readonly buildAssets?: readonly string[] | undefined;\n /** Emit **lazy** per-route loaders (`() => import(\"./routes/x\")`, a static specifier) instead of\n * eager `import * as`, so a bundler with code-splitting emits one chunk per route - loaded on the\n * first request to it, not all at boot (smaller cold-start parse). Default `false` (eager). Both\n * modes are fs-free with statically-analyzable specifiers; only the *when* differs. */\n readonly lazy?: boolean;\n}"
|
|
6500
6521
|
},
|
|
6501
6522
|
{
|
|
6502
6523
|
"name": "GetStaticPaths",
|
|
@@ -6705,6 +6726,44 @@
|
|
|
6705
6726
|
"signature": "export interface HostPolicy {\n /** Capability kinds the host will admit. A descriptor of any other kind is refused. */\n readonly allowedKinds: readonly CapabilityKind[];\n /** Required-capability allowlist. Every `requiredCapabilities` entry must be present. */\n readonly allowedCapabilities: readonly string[];\n /** Isolation floor. A descriptor offering weaker isolation than this is refused. */\n readonly minIsolation: IsolationClass;\n /** When true, a descriptor whose approval class is `none` is refused as a downgrade. */\n readonly requireApproval: boolean;\n}",
|
|
6706
6727
|
"doc": "/** The authoritative admission policy. Empty allowlists deny everything of that kind. */"
|
|
6707
6728
|
},
|
|
6729
|
+
{
|
|
6730
|
+
"name": "HostPolicy",
|
|
6731
|
+
"kind": "interface",
|
|
6732
|
+
"package": "@nifrajs/web",
|
|
6733
|
+
"signature": "export interface HostPolicy {\n readonly rules: readonly HostPolicyRule[];\n /**\n * Whether `pathname` (as requested, percent-encoded, without the query) may be served on `host` (a\n * Host header value; its port and case are ignored). `buildAssets` is the build's file set; without\n * it a rule's `buildAssets` matches nothing.\n */\n allows(host: string, pathname: string, buildAssets?: BuildAssetSet): boolean;\n /** The refusal for `pathname` on `host`, or `undefined` to serve it. */\n refusal(host: string, pathname: string, buildAssets?: BuildAssetSet): Response | undefined;\n /** {@link HostPolicy.refusal} for a request: its Host header (else its URL's host) and path. */\n check(request: Request, buildAssets?: BuildAssetSet): Response | undefined;\n}"
|
|
6734
|
+
},
|
|
6735
|
+
{
|
|
6736
|
+
"name": "HostPolicyOptions",
|
|
6737
|
+
"kind": "interface",
|
|
6738
|
+
"package": "@nifrajs/web",
|
|
6739
|
+
"signature": "export interface HostPolicyOptions {\n readonly rules: readonly HostPolicyRule[];\n /**\n * The answer to a path a rule refuses. Default: a bare `404` with `cache-control: no-store`, so a\n * restricted host does not even confirm the refused page exists.\n */\n readonly refuse?: (refused: {\n readonly host: string;\n readonly pathname: string;\n }) => Response;\n}"
|
|
6740
|
+
},
|
|
6741
|
+
{
|
|
6742
|
+
"name": "HostPolicyRule",
|
|
6743
|
+
"kind": "interface",
|
|
6744
|
+
"package": "@nifrajs/web",
|
|
6745
|
+
"signature": "export interface HostPolicyRule {\n /**\n * The hosts this rule restricts: names compared without case, port or trailing dot, or a predicate\n * given that lowercase name (`(host) => !ownHosts.has(host)` for \"every host that is not ours\").\n */\n readonly hosts: readonly string[] | ((hostname: string) => boolean);\n /** Page routes these hosts render, as route patterns (`/`, `/p/:id`, `/share/*`). */\n readonly pages: readonly string[];\n /**\n * Serve the build's own files on these hosts (default `true`): the client bundle and the files the\n * build copied from `public/`, exactly as the build emitted them.\n */\n readonly buildAssets?: boolean;\n /** Other paths these hosts serve, as route patterns: an API the pages call, a server function. */\n readonly paths?: readonly string[];\n}",
|
|
6746
|
+
"doc": "/** One host's surface. A request on a host no rule names is not restricted. */"
|
|
6747
|
+
},
|
|
6748
|
+
{
|
|
6749
|
+
"name": "HostReachOptions",
|
|
6750
|
+
"kind": "interface",
|
|
6751
|
+
"package": "@nifrajs/web",
|
|
6752
|
+
"signature": "export interface HostReachOptions {\n /** Sends one GET. Given the path and the Host header to send. */\n readonly fetch: (path: string, host: string) => Promise<Response>;\n /** The host to address (the Host header every request carries). */\n readonly host: string;\n /** Page paths that must render on `host` (concrete paths, not patterns). */\n readonly pages: readonly string[];\n /** Paths `host` must refuse with `refusedStatus`. */\n readonly refused?: readonly string[];\n /** The status a refused path answers (default `404`). */\n readonly refusedStatus?: number;\n /** At most this many files are fetched, pages included (default 500). */\n readonly limit?: number;\n}"
|
|
6753
|
+
},
|
|
6754
|
+
{
|
|
6755
|
+
"name": "HostReachReport",
|
|
6756
|
+
"kind": "interface",
|
|
6757
|
+
"package": "@nifrajs/web",
|
|
6758
|
+
"signature": "export interface HostReachReport {\n readonly host: string;\n readonly ok: boolean;\n readonly results: readonly HostReachResult[];\n /** The results that broke the expectation: a page or asset not answered 200, a refused path answered. */\n readonly failures: readonly HostReachResult[];\n /** `limit` stopped the walk with declared pages or references left unfetched; `ok` is then `false`. */\n readonly truncated: boolean;\n}"
|
|
6759
|
+
},
|
|
6760
|
+
{
|
|
6761
|
+
"name": "HostReachResult",
|
|
6762
|
+
"kind": "interface",
|
|
6763
|
+
"package": "@nifrajs/web",
|
|
6764
|
+
"signature": "export interface HostReachResult {\n /** The request path, as sent. */\n readonly path: string;\n /** `page` for a page the check was given, `asset` for a file a page or another file references. */\n readonly kind: \"page\" | \"asset\" | \"refused\";\n readonly status: number;\n /** What referenced it: the page or file path. Absent for a page. */\n readonly from?: string;\n}",
|
|
6765
|
+
"doc": "/** One request the check made. */"
|
|
6766
|
+
},
|
|
6708
6767
|
{
|
|
6709
6768
|
"name": "HostileCodeIsolation",
|
|
6710
6769
|
"kind": "type",
|
|
@@ -7135,6 +7194,13 @@
|
|
|
7135
7194
|
"signature": "export type ImageLoader = (args: {\n src: string;\n width: number;\n quality?: number;\n}) => string;",
|
|
7136
7195
|
"doc": "/** Builds a variant URL for `src` at a target pixel `width` (and optional `quality`). */"
|
|
7137
7196
|
},
|
|
7197
|
+
{
|
|
7198
|
+
"name": "ImagePixelLimitError",
|
|
7199
|
+
"kind": "class",
|
|
7200
|
+
"package": "@nifrajs/uploads",
|
|
7201
|
+
"signature": "export declare class ImagePixelLimitError extends Error {\n readonly width: number;\n readonly height: number;\n readonly maxPixels: number;\n constructor(width: number, height: number, maxPixels: number);\n}",
|
|
7202
|
+
"doc": "/** Thrown before decoding a source larger than `maxPixels`; answer it with a `413`. */"
|
|
7203
|
+
},
|
|
7138
7204
|
{
|
|
7139
7205
|
"name": "ImageProbe",
|
|
7140
7206
|
"kind": "interface",
|
|
@@ -7552,7 +7618,7 @@
|
|
|
7552
7618
|
"name": "IsolatedExtensionWorkerOptions",
|
|
7553
7619
|
"kind": "interface",
|
|
7554
7620
|
"package": "@nifrajs/coding-agent",
|
|
7555
|
-
"signature": "export interface IsolatedExtensionWorkerOptions {\n readonly modulePath: string;\n readonly cwd: string;\n readonly timeoutMs?: number;\n readonly maxMessageBytes?: number;\n /** Include bounded worker exception stacks for trusted local debugging. */\n readonly exposeErrorStacks?: boolean;\n readonly trustedCapabilities?: readonly string[];\n}"
|
|
7621
|
+
"signature": "export interface IsolatedExtensionWorkerOptions {\n readonly modulePath: string;\n readonly cwd: string;\n /** How long one tool call may run. Default 30 s. */\n readonly timeoutMs?: number;\n /** How long `start()` waits for the module to load and register. Default 30 s. */\n readonly startTimeoutMs?: number;\n readonly maxMessageBytes?: number;\n /** Include bounded worker exception stacks for trusted local debugging. */\n readonly exposeErrorStacks?: boolean;\n readonly trustedCapabilities?: readonly string[];\n}"
|
|
7556
7622
|
},
|
|
7557
7623
|
{
|
|
7558
7624
|
"name": "IsolationClass",
|
|
@@ -7834,8 +7900,8 @@
|
|
|
7834
7900
|
"name": "KVSessionStore",
|
|
7835
7901
|
"kind": "class",
|
|
7836
7902
|
"package": "@nifrajs/auth",
|
|
7837
|
-
"signature": "export declare class KVSessionStore implements SessionStore {\n private readonly kv;\n private readonly now;\n constructor(kv: KVNamespaceLike, options?: {\n readonly now?: () => number;\n });\n get(id: string): Promise<SessionRecord | undefined>;\n set(id: string, record: SessionRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}",
|
|
7838
|
-
"doc": "/**\n *
|
|
7903
|
+
"signature": "export declare class KVSessionStore implements SessionStore {\n readonly consistency = \"eventual\";\n private readonly kv;\n private readonly now;\n constructor(kv: KVNamespaceLike, options?: {\n readonly now?: () => number;\n });\n get(id: string): Promise<SessionRecord | undefined>;\n set(id: string, record: SessionRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}",
|
|
7904
|
+
"doc": "/**\n * Legacy Cloudflare Workers KV persistence, retained for reading and migrating existing records.\n * `createSessions` rejects this adapter: cached records and missing revocation markers can resurrect\n * a logged-out session. Use a strongly consistent {@link SessionStore} for authenticated sessions.\n * Records serialize to JSON; the entry's KV `expiration` is set from the record's `expiresAt` so KV\n * auto-evicts the session (a GC backstop - the manager still authoritatively checks expiry on read).\n * Every read is validated, so a corrupt/skewed entry reads as no session.\n * @deprecated Workers KV is eventually consistent and cannot enforce session revocation.\n */"
|
|
7839
7905
|
},
|
|
7840
7906
|
{
|
|
7841
7907
|
"name": "LAST_ERROR_PATH",
|
|
@@ -8400,15 +8466,15 @@
|
|
|
8400
8466
|
"name": "METHODS",
|
|
8401
8467
|
"kind": "const",
|
|
8402
8468
|
"package": "@nifrajs/core",
|
|
8403
|
-
"signature": "export declare const METHODS: readonly [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\"];",
|
|
8404
|
-
"doc": "/** The standard HTTP methods: the ones
|
|
8469
|
+
"signature": "export declare const METHODS: readonly [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\", \"QUERY\"];",
|
|
8470
|
+
"doc": "/** The standard HTTP methods: the ones the typed registry and the typed client know. Each has a server\n * builder except `QUERY` (RFC 9110's safe, idempotent read with a body), which `method()` registers. */"
|
|
8405
8471
|
},
|
|
8406
8472
|
{
|
|
8407
8473
|
"name": "METHODS",
|
|
8408
8474
|
"kind": "const",
|
|
8409
8475
|
"package": "nifra",
|
|
8410
|
-
"signature": "export declare const METHODS: readonly [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\"];",
|
|
8411
|
-
"doc": "/** The standard HTTP methods: the ones
|
|
8476
|
+
"signature": "export declare const METHODS: readonly [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\", \"QUERY\"];",
|
|
8477
|
+
"doc": "/** The standard HTTP methods: the ones the typed registry and the typed client know. Each has a server\n * builder except `QUERY` (RFC 9110's safe, idempotent read with a body), which `method()` registers. */"
|
|
8412
8478
|
},
|
|
8413
8479
|
{
|
|
8414
8480
|
"name": "MIN_DIGEST_KEY_BYTES",
|
|
@@ -8686,7 +8752,7 @@
|
|
|
8686
8752
|
"name": "MemoryAgentEvidenceLogOptions",
|
|
8687
8753
|
"kind": "interface",
|
|
8688
8754
|
"package": "@nifrajs/agent",
|
|
8689
|
-
"signature": "export interface MemoryAgentEvidenceLogOptions {\n /**\n * Maximum retained turns. Opening one more evicts the oldest finished turn, or the oldest turn when\n * none has finished; an evicted running turn ends its rejoined replays with no result. Default 256.\n */\n readonly maxTurns?: number;\n /**\n * Maximum live replays attached to one running turn. One more ends the oldest live view, which then\n * waits for the result without further steps. Default 64.\n */\n readonly maxSubscribers?: number;\n}"
|
|
8755
|
+
"signature": "export interface MemoryAgentEvidenceLogOptions {\n /**\n * Maximum retained turns. Opening one more evicts the oldest finished turn, or the oldest turn when\n * none has finished; an evicted running turn ends its rejoined replays with no result. Default 256.\n */\n readonly maxTurns?: number;\n /**\n * Maximum live replays attached to one running turn. One more ends the oldest live view, which then\n * waits for the result without further steps. Default 64.\n */\n readonly maxSubscribers?: number;\n /**\n * Maximum evidence items retained per turn, across every resume of it. One more drops the oldest,\n * and a replay from a cursor before the retained items reports replay-unavailable. Default 1024.\n */\n readonly maxEvidencePerTurn?: number;\n}"
|
|
8690
8756
|
},
|
|
8691
8757
|
{
|
|
8692
8758
|
"name": "MemoryAgentStateStore",
|
|
@@ -8862,8 +8928,8 @@
|
|
|
8862
8928
|
"name": "MemorySessionStore",
|
|
8863
8929
|
"kind": "class",
|
|
8864
8930
|
"package": "@nifrajs/auth",
|
|
8865
|
-
"signature": "export declare class MemorySessionStore implements SessionStore {\n private readonly sessions;\n private readonly markers;\n private readonly max;\n constructor(options?: MemorySessionStoreOptions);\n private mapFor;\n get(id: string): Promise<SessionRecord | undefined>;\n set(id: string, record: SessionRecord): Promise<void>;\n delete(id: string): Promise<void>;\n}",
|
|
8866
|
-
"doc": "/**\n * In-process session store. Refuses to run in production unless explicitly allowed (mirrors the ISR\n * `MemoryCacheStore` + the rate-limit `MemoryStore` - a per-instance store is unsafe across instances).\n * Bounded: oldest-inserted entries evict past `max`, sessions and revocation markers each on their own.\n */"
|
|
8931
|
+
"signature": "export declare class MemorySessionStore implements SessionStore {\n readonly consistency = \"strong\";\n private readonly sessions;\n private readonly families;\n private readonly markers;\n private readonly max;\n constructor(options?: MemorySessionStoreOptions);\n private mapFor;\n get(id: string): Promise<SessionRecord | undefined>;\n set(id: string, record: SessionRecord): Promise<void>;\n delete(id: string): Promise<void>;\n replace(id: string, record: SessionRecord): Promise<boolean>;\n rotate(previousId: string, nextId: string, record: SessionRecord, marker: SessionRecord): Promise<boolean>;\n private write;\n private removeSession;\n}",
|
|
8932
|
+
"doc": "/**\n * In-process session store. Refuses to run in production unless explicitly allowed (mirrors the ISR\n * `MemoryCacheStore` + the rate-limit `MemoryStore` - a per-instance store is unsafe across instances).\n * Bounded: oldest-inserted entries evict past `max`, sessions and revocation markers each on their own.\n * Because a marker can be evicted, it implements `replace`, so a request that loaded the session before\n * a logout cannot restore it once the marker is gone.\n */"
|
|
8867
8933
|
},
|
|
8868
8934
|
{
|
|
8869
8935
|
"name": "MemorySessionStoreOptions",
|
|
@@ -9357,6 +9423,13 @@
|
|
|
9357
9423
|
"signature": "export type MutationStatus = \"idle\" | \"pending\" | \"success\" | \"error\";",
|
|
9358
9424
|
"doc": "/** A mutation's lifecycle status. */"
|
|
9359
9425
|
},
|
|
9426
|
+
{
|
|
9427
|
+
"name": "NAMESPACED_KEYS",
|
|
9428
|
+
"kind": "const",
|
|
9429
|
+
"package": "@nifrajs/client",
|
|
9430
|
+
"signature": "export declare const NAMESPACED_KEYS: readonly [\"$query\"];",
|
|
9431
|
+
"doc": "/** Capabilities added after the lists above froze, intercepted by exact match. Only ever `$`-prefixed:\n * `$query` calls a route under the QUERY method, which has no plain verb key because `query` is a\n * common route segment. */"
|
|
9432
|
+
},
|
|
9360
9433
|
{
|
|
9361
9434
|
"name": "NAV_FROM_HEADER",
|
|
9362
9435
|
"kind": "const",
|
|
@@ -12396,7 +12469,7 @@
|
|
|
12396
12469
|
"name": "ResponseStream",
|
|
12397
12470
|
"kind": "interface",
|
|
12398
12471
|
"package": "@nifrajs/aws-lambda",
|
|
12399
|
-
"signature": "export interface ResponseStream {\n write(chunk: Uint8Array | string): unknown;\n end(): unknown;\n once?(event: string, listener: () => void): unknown;\n}",
|
|
12472
|
+
"signature": "export interface ResponseStream {\n write(chunk: Uint8Array | string): unknown;\n end(): unknown;\n once?(event: string, listener: () => void): unknown;\n off?(event: string, listener: () => void): unknown;\n readonly destroyed?: boolean;\n}",
|
|
12400
12473
|
"doc": "/** The Node `Writable`-shaped stream Lambda hands a streaming handler. Declared structurally. */"
|
|
12401
12474
|
},
|
|
12402
12475
|
{
|
|
@@ -13504,7 +13577,7 @@
|
|
|
13504
13577
|
"name": "SERVER_ENTRY_OPTIONS",
|
|
13505
13578
|
"kind": "const",
|
|
13506
13579
|
"package": "@nifrajs/web",
|
|
13507
|
-
"signature": "export declare const SERVER_ENTRY_OPTIONS: readonly [\"apiPrefix\", \"apiStrip\", \"mounts\", \"csp\", \"nonce\", \"i18n\"];",
|
|
13580
|
+
"signature": "export declare const SERVER_ENTRY_OPTIONS: readonly [\"apiPrefix\", \"apiStrip\", \"mounts\", \"csp\", \"nonce\", \"i18n\", \"hostPolicy\"];",
|
|
13508
13581
|
"doc": "/** The `createWebApp` options a generated server entry can import from the app's framework module. */"
|
|
13509
13582
|
},
|
|
13510
13583
|
{
|
|
@@ -14068,7 +14141,7 @@
|
|
|
14068
14141
|
"name": "ServeStaticOptions",
|
|
14069
14142
|
"kind": "interface",
|
|
14070
14143
|
"package": "@nifrajs/node",
|
|
14071
|
-
"signature": "export interface ServeStaticOptions {\n /** Directory to read files from - an absolute path or a `file://` URL (`new URL(\"./assets/\", import.meta.url)`). */\n readonly dir: string | URL;\n /** URL prefix these files are served under. Default `\"/assets\"`. Use `\"/\"` to serve the whole dir. */\n readonly prefix?: string;\n /** Emit `cache-control: public, max-age=31536000, immutable` - correct for content-hashed files. Default `true`. */\n readonly immutable?: boolean;\n /**\n * URL paths of the content-hashed files, such as a client build manifest's `assets`. When set,\n * `immutable` applies only to these; any other file is sent with its validators and no\n * `cache-control`, so a file that keeps its name across deploys still revalidates.\n */\n readonly hashedFiles?: Iterable<string>;\n /**\n * `cache-control` for a file that is not served immutable (`immutable: false`, or a file outside\n * `hashedFiles`). Unset, such a file carries only its validators.\n */\n readonly cacheControl?: string;\n /**\n * URL paths (as sent, percent-encoded) of the only files this mount serves. Any other path under\n * `prefix` passes to the next mount, then the app, without this mount touching the filesystem - so\n * a mount over a directory that also holds the server bundle can expose just the build's listed\n * files. A later mount over the same paths can still serve the rest.\n */\n readonly files?: Iterable<string>;\n /** Extra headers merged onto every served file. */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * Whether a path with a dot-leading segment (`/.env`, `/.git/config`, `/.hidden/app.js`) is\n * served. Default `\"deny\"`: answered `404` - the same response as a missing file, so probing\n * can't distinguish \"hidden\" from \"absent\". Dotfiles land in build output by accident, not by\n * design (`.env` next to the bundle, a `.git` dir in a copied tree), so serving them is opt-in.\n * `/.well-known` is public by definition (RFC 8615) and always served, as `servePublicDir` does.\n * The rule applies to the requested path and again to the file it resolves to, so a visible name\n * linking to `.env` is denied too. Set `\"allow\"` if the directory deliberately holds dotfiles.\n */\n readonly dotfiles?: \"deny\" | \"allow\";\n}",
|
|
14144
|
+
"signature": "export interface ServeStaticOptions {\n /** Directory to read files from - an absolute path or a `file://` URL (`new URL(\"./assets/\", import.meta.url)`). */\n readonly dir: string | URL;\n /** URL prefix these files are served under. Default `\"/assets\"`. Use `\"/\"` to serve the whole dir. */\n readonly prefix?: string;\n /** Emit `cache-control: public, max-age=31536000, immutable` - correct for content-hashed files. Default `true`. */\n readonly immutable?: boolean;\n /**\n * URL paths of the content-hashed files, such as a client build manifest's `assets`. When set,\n * `immutable` applies only to these; any other file is sent with its validators and no\n * `cache-control`, so a file that keeps its name across deploys still revalidates.\n */\n readonly hashedFiles?: Iterable<string>;\n /**\n * `cache-control` for a file that is not served immutable (`immutable: false`, or a file outside\n * `hashedFiles`). Unset, such a file carries only its validators.\n */\n readonly cacheControl?: string;\n /**\n * URL paths (as sent, percent-encoded) of the only files this mount serves. Any other path under\n * `prefix` passes to the next mount, then the app, without this mount touching the filesystem - so\n * a mount over a directory that also holds the server bundle can expose just the build's listed\n * files. A later mount over the same paths can still serve the rest.\n */\n readonly files?: Iterable<string>;\n /**\n * Whether this mount may answer `pathname` (as sent, without the query) for a request addressed to\n * `host` (its Host header). `false` passes the request on, without touching the filesystem, to the\n * next mount and then the app - the seam a host policy uses so a host's refused file meets the\n * app's own refusal instead of being served.\n */\n readonly allow?: (host: string, pathname: string) => boolean;\n /** Extra headers merged onto every served file. */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * Whether a path with a dot-leading segment (`/.env`, `/.git/config`, `/.hidden/app.js`) is\n * served. Default `\"deny\"`: answered `404` - the same response as a missing file, so probing\n * can't distinguish \"hidden\" from \"absent\". Dotfiles land in build output by accident, not by\n * design (`.env` next to the bundle, a `.git` dir in a copied tree), so serving them is opt-in.\n * `/.well-known` is public by definition (RFC 8615) and always served, as `servePublicDir` does.\n * The rule applies to the requested path and again to the file it resolves to, so a visible name\n * linking to `.env` is denied too. Set `\"allow\"` if the directory deliberately holds dotfiles.\n */\n readonly dotfiles?: \"deny\" | \"allow\";\n}",
|
|
14072
14145
|
"doc": "/**\n * Serve static files from a directory (e.g. the client build) under a URL prefix - so a self-hosted\n * Node deploy doesn't need a CDN or a hand-rolled `/assets/*` handler. (On Cloudflare/Vercel the\n * platform serves assets; this is for `node server.js`.)\n */"
|
|
14073
14146
|
},
|
|
14074
14147
|
{
|
|
@@ -14087,14 +14160,14 @@
|
|
|
14087
14160
|
"name": "Server",
|
|
14088
14161
|
"kind": "class",
|
|
14089
14162
|
"package": "@nifrajs/core",
|
|
14090
|
-
"signature": "export declare class Server<R extends Registry = EmptyRegistry, Ctx = EmptyContext, HookOutput = never> {\n /**\n * Which copy of `@nifrajs/core` declared this type. Two copies in one build (a linked sibling repo,\n * a hoisting split) produce two unrelated `Server` types whose assignment error is a wall of\n * missing internals; the brand puts the feature version in the type itself, so `typeof app` on\n * hover - and `NifraFeatureVersion` in an assertion - says which core an app is talking to.\n * `nifra doctor` is the diagnosis that names both install paths.\n *\n * `declare` = type-only: no field is emitted, nothing is allocated per server.\n */\n readonly __nifraCoreVersion: NifraFeatureVersion;\n private readonly catalog;\n /** WebSocket routes, matched separately at upgrade time (a GET + `Upgrade: websocket`). */\n private readonly wsRouter;\n /** Each socket path, its declared capabilities, the evidence declarations its handshake captured\n * and the chain it runs; reflection reads it. */\n private readonly wsRoutes;\n /** `wsChanges` when `wsMountsLive` was last worked out; -1 until then. */\n private wsMountsCheckedAt;\n /** Whether an app mounted here takes WebSocket upgrades, as of `wsMountsCheckedAt`. */\n private wsMountsLive;\n /** In-process pub/sub backing `ws.subscribe(topic)` + `app.publish(topic, data)` (single-instance).\n * Created by the first `app.ws()` via the `@nifrajs/core/ws` runtime - `undefined` until then, so a\n * no-WebSocket app never constructs (or bundles) it. */\n private topics;\n /** True once any `app.ws()` route sets `validateSend: true` - the one case where a broadcast frame\n * is validated (and possibly dropped) per socket, so `app.publish` must stay on the JS registry loop\n * rather than delegate to Bun's native `server.publish`. */\n private wsHasValidatedSend;\n /** Bun's native topic broadcast, bound by `listen()` in native-pubsub mode; `app.publish` uses it\n * instead of the JS registry. `undefined` off Bun, before `listen()`, with a validated-send route,\n * or when a mounted app takes upgrades. */\n private nativePublish;\n private readonly maxBodyBytes;\n private readonly protoPoisoning;\n private readonly formOrigins;\n /** `trustBodyFraming`: mark every `app.fetch` request as runtime-framed (see ServerOptions). */\n private readonly trustBodyFraming;\n private readonly wsMaxPayloadBytes;\n private readonly requestTimeoutMs;\n private readonly wsUpgradeTimeoutMs;\n /** Installed by the `responseContract()` plugin; `undefined` = not installed, which is the default\n * and the state in which a declared `response` schema stays a compile-time contract only. */\n private responseContractRuntime;\n /** Opt-in caller-IP trust declaration; `undefined` = socket peer only, no forwarded header believed. */\n private readonly clientIpTrust;\n private readonly acceptInboundDeadlines;\n private readonly maxInboundDeadlineMs;\n private readonly deadlineAdmissionOptions;\n private readonly gracefulSignals;\n private readonly stopHooks;\n private readonly fetchMounts;\n private mountOrder;\n /** Number of composed mounts that must run before the parent route table. Keeps legacy mounts off the hot path. */\n private preRouteMountCount;\n /** Capacity-admission gate; `undefined` = off (the request path pays nothing). */\n private readonly capacityGate;\n private readonly onCapabilityUse;\n private readonly capabilityInterceptors;\n private readonly capabilityObservers;\n /** The installed effect-ledger runtime (owns the sink + per-route resolution + settle), or\n * `undefined` when the effect-ledger plugin is not installed. */\n private effectLedgerRuntime;\n /** The installed idempotency runtime (owns the app-wide default store + the dedupe lane), or\n * `undefined` when the idempotency plugin is not installed. */\n private idempotencyRuntime;\n /** Installed opt-in runtime for `.tool()`/`.resource()`/`.prompt()`; `undefined` until `.use(mcp())`. */\n private mcpRuntime;\n /** Installed answer for a request no route matched; `undefined` (the plain 404) until `.use(notFound())`. */\n private notFoundLane;\n /** Installed Node-direct renderer for direct `resolveNode()` callers; `undefined` until `.use(nodeDirect())`. */\n private nodeOutcomeRuntime;\n /** Installed streaming runtime for `.sse()` routes; `undefined` until `.use(streaming())`. */\n private sseRuntime;\n /** Installed WebSocket runtime for `.ws()` routes; `undefined` until `.use(websocket())`. */\n private wsRuntime;\n private readonly logger;\n /** How much of an unhandled error {@link logRequestError} records. See `ServerOptions.errorLogDetail`. */\n private readonly errorLogDetail;\n /** App-wide validation-error fallback; a route's own `schema.onValidationError` takes precedence. */\n private readonly defaultOnValidationError?;\n private bunServer;\n private sealed;\n private readonly derives;\n /** Dedicated authentication stages captured by subsequent routes. */\n private readonly authStages;\n private readonly decorations;\n private readonly beforeHandleHooks;\n private readonly afterHandleHooks;\n private readonly onErrorHooks;\n private readonly aroundHooks;\n private readonly onRequestHooks;\n private readonly onNodeRequestHooks;\n /** Registration-time eligibility for the Node request twin lane. */\n private nodeRequestHooksComplete;\n /** True when every request hook is safe to skip on a Bun native route. */\n private bunNativeRequestHooksSafe;\n private readonly onResponseHooks;\n private readonly onNodeResponseHooks;\n /** Registration-time eligibility for the Node response twin lane. */\n private nodeResponseHooksComplete;\n /** True when every response hook only mutates headers and can run after a Bun fused response. */\n private bunNativeResponseHeadersOnly;\n /**\n * True once a bundle registers a RAW `onNodeResponse` twin - one handed the outcome's header\n * record itself rather than the case-normalizing view. Their names are contractually the wire\n * spelling, but registration cannot PROVE it, so such an app forgoes the all-lowercase mark and\n * every reader re-derives the answer, exactly as before the mark existed.\n */\n private hasRawNodeResponseHook;\n private readonly onResponseFinalizedHooks;\n /**\n * Statically declared response headers, merged and prebuilt at registration; `undefined` (the\n * default) leaves every render path in its original shape. These are NOT response hooks - they are\n * folded into response construction - so declaring them keeps the fused native lanes an\n * `onResponse` hook would have disabled.\n */\n private staticResponseHeaders;\n /** A group's view of the static headers its enclosing scopes declared before it was created. */\n private inheritedStatics;\n /** A group's view of the plugins its enclosing scopes applied before it was created; unset while\n * a plugin applies, so its own dependency `use()` shares the parent's copy. */\n private inheritedPlugins;\n /** `wrapResponse` for the Web lanes: identity until static headers exist to fold into the\n * framework's own error/404/timeout renders, which are built outside the header init. */\n private wrapWebResponse;\n private webResponseTimeout;\n /** Body/raw response hooks need a framework-payload marker; keep that decision per app. */\n private responseBodyTag;\n private readonly responseBodyOwners;\n private readonly finalizeResponse;\n private readonly responseRequests;\n /** A request the WebSocket handshake check ran the onRequest hooks on and then passed to HTTP →\n * what the hooks returned, so `fetch` routes that instead of running the hooks a second time. */\n private wsHookedPasses;\n /** Original source → request observed by generic request hooks, including in-place mutations. */\n private readonly responseSources;\n /** Memoized NodeRequestContext per plain-`Request` source - see {@link nodeRequestContextOf}. */\n private readonly nodeContexts;\n /** Plugins/middleware already applied via `use`, by name - for idempotent dedupe. */\n private readonly appliedPlugins;\n /** Order-scoped evidence captured by routes registered after an assured plugin. */\n private readonly activeAssurance;\n /** App-wide evidence from global hooks; applies retroactively to every route. */\n private readonly globalAssurance;\n /** App-declared MCP resources / prompts (via {@link resource} / {@link prompt}), read by `nifra mcp`. */\n private readonly mcpResourceList;\n private readonly mcpPromptList;\n /** Kept so a {@link group} scope is built with exactly this server's settings: fused lanes read\n * several of them at request time, so a group route must never run under different ones. */\n private readonly options;\n /** Static prefix joined onto every route this server registers; non-empty only on a group scope. */\n private routePrefix;\n constructor(options?: ServerOptions);\n private assertConfigurable;\n /** Register a callback awaited after graceful drain and server stop. Hung callbacks are bounded. */\n onStop(fn: StopHook): this;\n /**\n * Mount a legacy fetch handler under a literal path prefix. Mounted handlers sit behind typed\n * routes, so routes can move one at a time while the remaining legacy surface stays live.\n * Mounted responses are outside Nifra's typed route and response-contract checks.\n *\n * It carries HTTP only: a WebSocket upgrade under the prefix reaches the handler as an ordinary\n * request and never becomes a socket. Serve that path's sockets with `app.ws()` routes or a\n * mounted child app, or keep the legacy server running beside this one for them.\n */\n mountFetch(path: string, handler: FetchHandler<EnvOf<Ctx>>, options?: MountFetchOptions): this;\n /**\n * Compose a child fetch app under a literal path prefix.\n *\n * Composed mounts run after the app-global request phase and before the parent's route table. This\n * makes them safe to use in an SSR shell whose `/*` page route would otherwise swallow an API mount.\n * If the child exposes `resolveWebSocketUpgrade`, the same mount also participates in adapter-owned\n * WebSocket upgrades; the serving adapter still upgrades its original socket, while the child sees\n * the mounted request path (stripped when requested).\n *\n * `fallbackOn: 404` is deliberately limited to GET/HEAD/OPTIONS at dispatch time. Those methods are\n * replayable without buffering an untrusted request body; POST/PUT/PATCH and streaming requests\n * never get retried after a child has had a chance to consume them.\n */\n mount(options: MountOptions<EnvOf<Ctx>>): this;\n /**\n * Add a per-request, computed context extension. Order-scoped: it is snapshotted into every route\n * declared *after* this call, and reaches none declared before. One added after the last route\n * (e.g. on the app returned by a route-registering factory) covers nothing - see\n * {@link ServerOptions.unusedScopedHooks}.\n *\n * Returning a `status(...)` (or a `Response`) instead of an extension ends the request there - the\n * guard shape, and the cheap one: it renders as plain data on the same lane a handler's return\n * takes, where `throw new Response(...)` pays ~40% of the rejection lane to build the object. That\n * branch is control flow, so it does not widen the derived context type.\n */\n derive<H extends (context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx & ContextExtensionOf<ReturnType<H>>, HookOutput | StatusResponseOf<Awaited<ReturnType<H>>>>;\n /**\n * Add a static context value. Order-scoped: captured by every route declared *after* this call, and\n * by none before; one added after the last route reaches nothing\n * (see {@link ServerOptions.unusedScopedHooks}).\n */\n /**\n * Register a dedicated authentication stage for subsequent routes.\n *\n * Unlike `derive`, this stage receives a body-blind authentication capsule and is compiled before\n * route validation. Keeping it separate prevents an unrelated derive from accidentally becoming a\n * security gate and lets the route compiler retain a protected fast lane.\n *\n * A stage that throws, or returns anything but `authenticated(principal)` or `rejected(...)`, fails\n * closed with 503 `{ ok: false, error: \"auth_unavailable\" }`. The cause goes where a handler's error\n * goes: to `onError`, whose response replaces the 503, and when no hook answers, to the logger. A\n * thrown `Response` or `status(...)` is sent as thrown, as it is from a handler.\n */\n authenticate<Principal>(stage: AuthenticationStage<Principal, EnvOf<Ctx>>): Server<R, Ctx & {\n readonly principal: Principal;\n }, HookOutput>;\n decorate<const K extends string, V>(key: K, value: V): Server<R, Ctx & Record<K, V>, HookOutput>;\n /**\n * Run before routing on the raw request. Return a `Response` or a `status()` result to\n * short-circuit, or a replacement `Request` to continue routing with a rewritten method/URL/headers.\n * Global.\n */\n onRequest(fn: (req: Request, platform?: Platform<EnvOf<Ctx>>) => MaybePromise<OnRequestResult>): this;\n /**\n * Run after validation, before the handler; a non-`undefined` return short-circuits. Order-scoped:\n * it is snapshotted into every route declared *after* this call and covers none declared before, so\n * one added after the last route reaches nothing (see {@link ServerOptions.unusedScopedHooks}).\n */\n beforeHandle<H extends (context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /**\n * Wrap the matched route lifecycle for subsequent routes. This is intentionally generic over the\n * route output, so wrappers like async context storage do not force Node's direct JSON path through\n * a Web `Response`. The first registered wrapper is outermost.\n *\n * Order-scoped: captured by every route declared *after* this call, none before; one added after the\n * last route reaches nothing (see {@link ServerOptions.unusedScopedHooks}).\n */\n around<H extends (context: Context & Ctx, next: () => MaybePromise<unknown>) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /**\n * Asynchronously admit each subsequent `executeCapability()` call before its owned effect runs.\n * Interceptors receive token-only metadata plus an abort signal and must call `next()` exactly once\n * to admit. Returning without `next()`, timing out, aborting, or throwing fails the effect closed.\n */\n aroundCapability(interceptor: CapabilityInterceptor, options?: AroundCapabilityOptions): this;\n /** Observe token-only admission/execution lifecycle events for subsequent capability routes. */\n observeCapability(observer: EffectLifecycleObserver): this;\n /** Transform the handler's result before it is serialized. Order-scoped: captured by routes declared\n * *after* this call, none before; one added after the last route reaches nothing (see\n * {@link ServerOptions.unusedScopedHooks}). */\n afterHandle<H extends (result: unknown, context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /** Handle a thrown error; a non-`undefined` return becomes the response (else the default 500, or 503\n * `auth_unavailable` for a failed {@link authenticate} stage). Order-scoped: captured by routes\n * declared *after* this call, none before; one added after the last route reaches nothing (see\n * {@link ServerOptions.unusedScopedHooks}). */\n onError<H extends (error: unknown, context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /** Transform every outgoing response - success, error, 404, 405, short-circuit. Global. */\n onResponse(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /**\n * Declare response headers with NO per-request decision behind them - and pay nothing for them on\n * the request path.\n *\n * These are not a hook. Because the values are known at wire-up, they are folded into response\n * construction (one prebuilt init for JSON renders, one record merge where the request set its own\n * headers), so an app whose only response middleware is static keeps every fused and native lane -\n * `onResponse`/`onResponseHeaders` disable Bun's fused native routes and, for a full `onResponse`,\n * the Node direct writer. They apply to EVERY response, exactly as a response hook would: success,\n * error, 404/405, timeout, and short-circuit alike.\n *\n * app.responseHeaders({ \"x-frame-options\": \"DENY\", \"referrer-policy\": \"no-referrer\" })\n *\n * They are DEFAULTS: a value the request itself produced (`c.set.headers`, or a response hook)\n * wins, whatever casing it used. In a group, a name the group declares replaces the value its\n * enclosing scopes declared before the group, on the group's routes. Names are lowercased once here; a non-string value, an invalid\n * name, `__proto__`, or a name the render owns (`content-type`, `content-length`,\n * `transfer-encoding`, `set-cookie`) throws a `TypeError` at wire-up.\n *\n * ORDERING: declarations made before any response hook fold into one static record. One made AFTER\n * a response hook cannot - the hook may already have written that name and must keep winning - so\n * it registers as an ordinary `onResponseHeaders` hook instead, preserving registration order at\n * the cost of the static tier's speed. Declare static headers first.\n */\n responseHeaders(record: Readonly<Record<string, string>>): this;\n /** Wire an already-validated lowercase record into the static tier, or - once a dynamic response\n * hook owns part of the header state - into a hook that runs in the right order. */\n private addStaticResponseHeaders;\n private enableResponseBodyTagging;\n private responseObserverMethods;\n /** Observe the terminal response after all transformations. Observers are ordered and fail-open. */\n onResponseFinalized(fn: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>): this;\n /**\n * Apply `all()` or `method()` from `@nifrajs/core/methods`: one handler registered under several\n * methods, or under a method outside the standard seven. The standard methods join the registry.\n *\n * Declared first on purpose. The plugin's handler is typed against this app's context, which\n * TypeScript reads from the first overload it tries.\n */\n use<M extends string, Path extends string, S extends RouteSchema, Output>(plugin: MethodRoutesPlugin<M, Path, S, Output, Ctx>): Server<WithMethodRoutes<R, M, Path, S, Output, HookOutput>, Ctx, HookOutput>;\n /** Enable the opt-in portable response observer methods. */\n use(plugin: ResponseObserverPlugin): this & ResponseObserverMethods;\n /**\n * Apply a **context** plugin ({@link ContextPlugin}, from {@link defineContextPlugin}) - it adds `D`\n * to the handler context and changes nothing else, so the route registry `R` and the existing context\n * `Ctx` thread through untouched. Like the identity overload above, this exists because the generic\n * `(app: this) => Out` overload below cannot infer through a *generic* plugin signature: it erases the\n * plugin's own type parameters to their constraints, which silently widens `R` to `Registry`.\n */\n use<D extends object>(plugin: ContextPlugin<D>): Server<R, Ctx & D, HookOutput>;\n /**\n * Apply a type-**identity** plugin ({@link IdentityPlugin}, from {@link defineIdentityPlugin}) - it\n * registers routes/hooks but doesn't change the types, so this returns `this` with the route registry\n * and context fully intact. This overload exists specifically so a named identity plugin (e.g.\n * `@nifrajs/better-auth`) threads the registry: its `& { pluginName }` intersection would otherwise\n * defeat the generic inference of the transforming overload below and collapse the result to `any`.\n */\n use<AddedHookOutput = never>(plugin: IdentityPlugin<AddedHookOutput>): Server<R, Ctx, HookOutput | AddedHookOutput>;\n /**\n * Apply a **plugin function** - `(app) => app`, typically built with {@link definePlugin}. It's\n * called with `this` and its result is returned, so an inline plugin's `derive`/`decorate` thread\n * the added context to handlers defined after `use` (the overload is generic over the concrete\n * `this`). A named plugin already applied is skipped (idempotent dedupe), however it was configured,\n * so a plugin meant to stack - a second, stricter guard - needs a name of its own per instance.\n *\n * If the plugin's return type is unpinned - `Server<any, any>`, as a hand-rolled `(app) => app` or a\n * `NifraPlugin<AnyServer, AnyServer>` infers (e.g. an auth plugin whose own types collapsed) - this\n * returns the non-callable {@link PluginTypeCollapsed} instead of silently widening the whole typed\n * client to `any`. `.get()`/`.post()` then fail right here rather than surfacing as `any` hundreds of\n * lines away. Fix at the plugin: build it with {@link defineIdentityPlugin}/{@link defineContextPlugin},\n * or pin its input server type. This mirrors the guard {@link definePlugin} already applies.\n */\n use<Out extends AnyServer>(plugin: (app: this) => Out): [ServerTypeUnpinned<Out>] extends [true] ? PluginTypeCollapsed : Out;\n /**\n * Apply a {@link Middleware} bundle - wire each hook it provides to its lifecycle point. Returns\n * `this` (no context-type merging); call it before the routes its `beforeHandle`/`afterHandle`\n * should cover (those are order-scoped; `onRequest`/`onResponse` are global). A bundle applied after\n * the last route reaches nothing - {@link ServerOptions.unusedScopedHooks} logs that at seal. A named\n * bundle already applied is skipped (idempotent).\n */\n use<M extends Middleware>(mw: M): Server<R, Ctx, HookOutput | MiddlewareOutputOf<M>>;\n use(mw: Middleware): this;\n get<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n get<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Register a **typed SSE route** - an endpoint streaming `text/event-stream` whose event\n * payloads are contracted by `schema.sse`. It is a GET route, or a POST route when the schema\n * declares a `body` (a GET carries none): the body validates as on any POST, and the client sends\n * it with `.subscribe(onEvent, { body })` - the shape of a chat stream that posts its prompt. The handler receives the validated context plus a\n * {@link TypedSSEStream}: `stream.send(event)` is compile-time-checked against the schema and\n * JSON-serialized into the SSE `data:` field. The typed client sees the marker and grows a\n * `.subscribe(onEvent)` for the route with the same payload type - end-to-end typed streaming.\n *\n * import { streaming } from \"@nifrajs/core/sse\" // .use(streaming()) enables .sse()\n * const app = server().use(streaming()).sse(\"/feed\", { sse: t.object({ id: t.integer(), title: t.string() }) },\n * async (c, stream) => {\n * stream.send({ id: 1, title: \"hello\" }) // typed\n * await waitForDisconnect(stream.signal)\n * },\n * { keepAlive: 15_000 })\n *\n * // client: const off = api.feed.subscribe((post) => console.log(post.title))\n *\n * `init` passes through to the underlying {@link sse} helper (`keepAlive`, `maxBufferedBytes`,\n * extra headers). The connection closes when the handler resolves, `stream.close()` runs, or the\n * client disconnects (`stream.signal`). Query/body schemas validate exactly as on any other route.\n */\n sse<Path extends string, S extends RouteSchema & {\n sse: StandardSchemaV1;\n }>(path: Path, schema: S, run: (context: Context<Path, S> & Ctx, stream: TypedSSEStream<InferOutput<S[\"sse\"]>>) => void | Promise<void>, init?: SSEInit): Server<AddRoute<R, SseMethodOf<S>, Path, RouteInfoFor<Path, S, Response, HookOutput>>, Ctx, HookOutput>;\n post<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n post<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n put<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n put<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n patch<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n patch<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n delete<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n delete<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Declare an **MCP tool** an agent can call (via `nifra mcp`, or a mounted MCP endpoint): a typed\n * `POST /_nifra/tool/<name>` route whose `input`/`output` schemas contract the call and surface in\n * `tools/list`. Requires `.use(mcp())` - without it, `.tool()` is a registration error, so an\n * ordinary HTTP app never bundles the MCP wiring. Siblings: {@link resource}, {@link prompt}.\n *\n * import { mcp } from \"@nifrajs/core/mcp\"\n * const app = server().use(mcp()).tool(\n * \"search\",\n * { description: \"Search posts\", input: t.object({ q: t.string() }) },\n * ({ q }) => findPosts(q),\n * )\n */\n tool<Name extends string, S extends {\n description: string;\n input: StandardSchemaV1;\n output?: StandardSchemaV1;\n annotations?: ToolAnnotations;\n }, H extends (input: InferOutput<S[\"input\"]>, ctx: Context & Ctx) => MaybePromise<S[\"output\"] extends StandardSchemaV1 ? InferOutput<S[\"output\"]> : unknown>>(name: Name, config: S, handler: H): Server<AddRoute<R, \"POST\", `/_nifra/tool/${Name}`, RouteInfoFor<`/_nifra/tool/${Name}`, S[\"output\"] extends StandardSchemaV1 ? {\n body: S[\"input\"];\n response: S[\"output\"];\n } : {\n body: S[\"input\"];\n }, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Declare an MCP **resource** - read-only data an agent can fetch through `nifra mcp` (app config, a\n * generated document, …). `read` runs in the app process, so capture whatever app state it needs in the\n * closure. `uri` is the MCP resource identifier (e.g. `\"myapp://config\"`). The sibling of {@link tool}\n * for the resource half of MCP.\n */\n resource(uri: string, config: {\n readonly name: string;\n readonly description?: string;\n readonly mimeType?: string;\n }, read: McpResourceDescriptor[\"read\"]): Server<R, Ctx, HookOutput>;\n /**\n * Declare an MCP **prompt** - a reusable prompt template an agent can fetch through `nifra mcp`.\n * `handler` receives the caller's arguments and returns the rendered messages.\n */\n prompt(name: string, config: {\n readonly description: string;\n readonly arguments?: readonly PromptArgument[];\n }, handler: McpPromptDescriptor[\"handler\"]): Server<R, Ctx, HookOutput>;\n /** The MCP resources declared via {@link resource} - enumerated by `nifra mcp`. */\n mcpResources(): readonly McpResourceDescriptor[];\n /** The MCP prompts declared via {@link prompt} - enumerated by `nifra mcp`. */\n mcpPrompts(): readonly McpPromptDescriptor[];\n /**\n * Register a **WebSocket** route. The connection upgrades on a `GET` to `path` carrying\n * `Upgrade: websocket`. The handshake runs the chain an HTTP `GET` registered here would: the\n * `authenticate()` stages, `derive`s and `beforeHandle`s added before this call, then the optional\n * `handler.upgrade(c)`. Any of them may reject (a `Response`, a `status(...)`, a failed auth stage);\n * `upgrade()` may seed per-connection `ws.data`. To keep a socket public, register it before the\n * guard. WebSockets are served by the\n * adapter (`listen()`, `@nifrajs/node`, `@nifrajs/deno`, `toFetchHandler`) - not by bare `app.fetch`, which\n * has no socket (a WS path through `app.fetch` is a normal HTTP response).\n *\n * The route also enters the type-level registry (under the pseudo-method `\"WS\"`), so the typed\n * client grows a `.ws()` handle for it: `messageSchema` types what the client may `send`,\n * `sendSchema` types the frames it receives. Passing explicit type arguments (`ws<MyData>(…)`)\n * defeats path-literal inference and skips the registry entry - the route still serves, it is just\n * invisible to `client<App>`; prefer typing `data` via `upgrade()`'s return.\n *\n * app.ws(\"/chat\", { open: (ws) => ws.send(\"hi\"), message: (ws, data) => ws.send(data) })\n */\n ws<Data = unknown, Schema extends StandardSchemaV1 | undefined = undefined, Send extends StandardSchemaV1 | undefined = undefined, Path extends string = string>(path: Path, handler: WebSocketHandler<Data, EnvOf<Ctx>, Schema, Send, Ctx>): string extends Path ? Server<R, Ctx, HookOutput> : Server<AddRoute<R, \"WS\", Path, WsRouteInfoFor<Path, Schema, Send>>, Ctx, HookOutput>;\n /**\n * Broadcast `data` to every WebSocket connection subscribed to `topic` (via `ws.subscribe(topic)`).\n * In-process and **single-instance** (see {@link TopicRegistry}) - a multi-instance deploy must bridge\n * an external fan-out (Redis, a Durable Object) to this. A no-op when nobody is subscribed.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void;\n private route;\n /**\n * Low-level route registration shared by the inline builder and `implement()`.\n * Captures the server's current `derive`/`decorate` chain into the route - this\n * is the \"compiled\", order-scoped per-route chain.\n */\n register(method: string, path: string, schema: RouteSchema | undefined, handler: (context: never) => unknown): void;\n /** Register a contract/group route batch atomically. Every route captures the same current chain it\n * would capture through {@link register}; no route becomes visible unless the full batch validates.\n *\n * A path ending in optional parameters (`/users/:id?`) is one catalog route per concrete pattern,\n * so reflection, OpenAPI, evidence and the typed client all see ordinary routes. */\n registerBatch(routes: readonly {\n readonly method: string;\n readonly path: string;\n readonly schema: RouteSchema | undefined;\n readonly handler: (context: never) => unknown;\n }[]): void;\n /** Join a group scope's prefix BEFORE compilation, so the pattern, the reflected descriptor, the\n * capability guard, the ledger record, and assurance path matching all see the one served path. */\n private prefixed;\n private prepareRoute;\n /** @internal Symbol-keyed install seam for the `responseContract()` plugin. Off the public typed surface. */\n [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void;\n /** @internal Symbol-keyed install seam for the response observer plugin. */\n [INSTALL_RESPONSE_OBSERVER](runtime: ResponseObserverRuntime): ResponseObserverMethods;\n /** @internal Symbol-keyed install seam for the `idempotency()` plugin. Off the public typed surface. */\n [INSTALL_IDEMPOTENCY](runtime: IdempotencyRuntime): void;\n /** @internal Symbol-keyed install seam for the `mcp()` plugin. Off the public typed surface. */\n [INSTALL_MCP](runtime: McpRuntime): void;\n /** @internal Symbol-keyed install seam for the `notFound()` plugin. Off the public typed surface. */\n [INSTALL_NOT_FOUND](lane: NotFoundLane): void;\n /** @internal Symbol-keyed install seam for the `nodeDirect()` plugin. Off the public typed surface. */\n [INSTALL_NODE_DIRECT](runtime: NodeOutcomeRuntime): void;\n /** @internal An adapter reports a failure no response hook saw (a hook that threw past `fetch`, a\n * response the runtime refused to write), logged as Bun's `listen()` logs one. */\n [REPORT_ERROR](error: unknown): void;\n /** @internal Symbol-keyed install seam for the `streaming()` plugin. Off the public typed surface. */\n [INSTALL_SSE](runtime: SseRuntime): void;\n /** @internal Symbol-keyed install seam for the `websocket()` plugin. Off the public typed surface. */\n [INSTALL_WS](runtime: WsRuntime): void;\n /**\n * @internal The runtime Bun serves this app's WebSocket upgrades with, asked by `listen()` and by a\n * parent that mounts this app: `undefined` while nothing here can take one, `null` when something\n * can but no runtime is at hand. A mounted Nifra app answers through this same seam, so mounting an\n * app without a WebSocket route needs no runtime; a resolver without the seam cannot say, so it\n * counts. `seen` ends a mount cycle (an app mounted under itself to alias a prefix).\n */\n [GET_WS_RUNTIME](seen?: Set<unknown>): WsRuntime | null | undefined;\n /** The `[GET_WS_RUNTIME]` answer for the apps mounted here alone, whatever this app's own routes. */\n private mountedWsRuntime;\n /** Whether an app mounted here takes WebSocket upgrades. Worked out again only after a `ws()` or a\n * `mount()` somewhere, so the upgrade check on a plain request costs one comparison. */\n private mountsTakeUpgrades;\n /**\n * Merge another server's routes into this one - the composition escape hatch for large apps.\n *\n * WHY: the fluent chain accumulates one type-alias level per route, and TypeScript resolves\n * that stack in one recursion - a single chain hits TS2589 at ~95 routes. Groups keep every\n * chain short: build each domain (`listings`, `agents`, …) as its own `server()` (its registry\n * resolves independently), then `app.merge(listings).merge(agents)` - each merge adds ONE level\n * regardless of group size. 300+ routes stay fully typed (see many-routes.test-d.ts). The\n * other escape hatch is contract-first `implement()`, whose registry is a single object type.\n *\n * Semantics: merged routes keep the chains captured where they were DEFINED - the group's\n * `derive`/`decorate`/`beforeHandle`/`afterHandle`/`onError`/`around` apply to its routes\n * exactly as they did standalone, so a group wires its own plugins. The same locality rule\n * covers the group's `onRequest` hooks: they run only for requests that route to the GROUP's\n * routes, and for an `OPTIONS` preflight to a path they serve (a `bodyLimit()` mounted on an uploads group must not start gating the whole app\n * because the app composed it in), and the group's global assurance follows its hooks onto\n * exactly those routes. A group with hooks but NO routes is a middleware bundle - its hooks\n * can only mean app-wide intent, so they are appended globally, unchanged. Response-side hooks\n * (`onResponse`/`onResponseFinalized`) are appended to this server's. This server's\n * route-scoped chains do NOT retroactively wrap merged routes (order-scoped, like routes\n * registered before a `derive`). Fail closed: a path+method collision throws\n * `RouteConfigError` at merge time, and a group with WebSocket routes or mounts is refused\n * (register those on the parent).\n *\n * What this server's `.use()`, made BEFORE the merge, covers on a merged route versus a\n * `group()` route:\n *\n * | installed on this server | group() route | merge()d route |\n * | ------------------------------------------ | ------------- | ------------------------------ |\n * | derive/decorate/beforeHandle/afterHandle, | yes | no - wire it on the merged |\n * | onError/around, authenticate, route-scoped | | server |\n * | assurance | | |\n * | onRequest/onResponse/responseHeaders hooks | yes | yes (app-wide) |\n * | responseContract() | yes | yes, when the route declares a |\n * | | | response and its own server |\n * | | | installed no contract |\n * | effectLedger() | yes | yes, when the route declares |\n * | | | capabilities and has no ledger |\n * | idempotency() | yes | the merged server's own; a |\n * | | | route declaring it without one |\n * | | | is refused at registration |\n *\n * The response contract and the ledger can only add a check or a record, so a merged route is\n * recompiled under them. A runtime installed AFTER the merge covers neither kind of route.\n *\n * In development, {@link ServerOptions.unusedScopedHooks} reports a hook followed only by merges and\n * a contract or ledger installed after the routes it would cover; `nifra check` reports a merge whose\n * server authenticates none of its routes under this server's `authenticate()` (NF-C043).\n */\n merge<R2 extends Registry, Ctx2, HookOutput2>(other: Server<R2, Ctx2, HookOutput2>): Server<R & R2, Ctx, HookOutput>;\n /**\n * Declare routes under a static path prefix, with the prefix in the typed client, `routes()`,\n * OpenAPI, capability events, and the effect ledger - the counterpart of Hono's `route()`,\n * Elysia's `group()`, and Fastify's `register({ prefix })`.\n *\n * app\n * .derive(session)\n * .group(\"/admin\", (admin) =>\n * admin.beforeHandle(requireAdmin).get(\"/users\", listUsers).get(\"/users/:id\", getUser),\n * )\n * .get(\"/\", home) // not covered by requireAdmin\n *\n * The builder receives a scope that INHERITS this server's route chain as it stands at the call\n * (`derive`/`decorate`/`authenticate`/`beforeHandle`/`afterHandle`/`onError`/`around`, assurance,\n * capability interceptors, installed runtimes, applied plugins), exactly as a route declared here\n * would. {@link merge} documents how that differs for a merged server. A plugin this server already applied is in effect for the group: the group's `use()` of\n * that same instance does nothing, and its `use()` of another instance under the same name throws a\n * `RouteConfigError` (`PLUGIN_RECONFIGURED`), because that instance could never replace the parent's.\n * A plugin the group applies still shares the parent's copy of a dependency it `use()`s itself.\n * What it adds stays in the group: its chain additions apply only to its own routes, and its\n * request/response hooks (`onRequest`, `onResponse`, `responseHeaders`, `onResponseFinalized`, and\n * middleware bundles that use them) run only for requests whose path is the prefix or below it.\n * Per-route authorization belongs in `authenticate`/`beforeHandle`, which are compiled into each\n * route; request hooks are path prefilters.\n *\n * The prefix is static text - `\"/api\"`, `\"/api/v1\"` - validated when declared: no params,\n * wildcards, empty or dot segments, percent-escapes, or trailing slash. A group's `\"/\"` route\n * serves the prefix itself. Groups nest (`\"/api\"` then `\"/v1\"` serves `/api/v1/...`).\n *\n * Fail closed: the builder must synchronously return the scope it was given; a collision with an\n * existing route throws `RouteConfigError` and adds none of the group's routes; `.ws()`, mounts,\n * MCP `.tool()`s, and `merge()` inside a group are refused (register them on the parent). Once the\n * builder returns, the scope is closed - a leaked reference cannot add routes later.\n */\n group<const P extends string, R2 extends Registry, Ctx2, HookOutput2>(prefix: P, build: (group: Server<EmptyRegistry, Ctx, HookOutput>) => Server<R2, Ctx2, HookOutput2>): Server<R & PrefixRegistry<P, R2>, Ctx, HookOutput>;\n /**\n * Take over another server's routes and hooks - the shared core of {@link merge} and {@link group}.\n * `prefix` selects group semantics: hooks are scoped to requests under the prefix (response hooks\n * included), and the source's global assurance past `inheritedGlobal` (what it copied from this\n * server) is folded into its routes. Without a prefix, merge semantics: request hooks are scoped to\n * the source's routes when it has any, response hooks are appended app-wide.\n */\n private adopt;\n /** A fused renderer closes over runtime services to keep its seven-argument JSC fast path. Merging\n * rebinds that closure once to the executing server; generic plans already receive the runtime. */\n private bindFusedRuntime;\n /**\n * Enumerate the registered routes (method, path, input schemas), in registration\n * order. Powers `toOpenAPI` and other introspection; the router trie itself no\n * longer holds the original patterns.\n */\n routes(): ReadonlyArray<RouteDescriptor>;\n /**\n * Resolve a `Request` to a `Response` - the whole lifecycle, testable without a port. The\n * optional `platform` carries edge inputs (`env`, `waitUntil`); edge adapters pass it, and\n * Bun/Node/Deno omit it (then `c.env` is `undefined` and `c.waitUntil` runs fire-and-forget).\n */\n fetch(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<Response>;\n private fetchSource;\n private fetchSourceInner;\n /** Web response path when Bun already matched the route. The lifecycle and response hooks remain\n * exactly the same as {@link fetchSource}; only portable URL scanning + trie lookup are skipped. */\n private fetchMatched;\n private fetchMatchedInner;\n /**\n * Run `produce` under the capacity gate: admit → run → release exactly once when the response is\n * produced (or the run throws). Only reached when {@link capacityGate} is set, so the off path pays\n * nothing. The slot is held for the duration of handler execution, not the streaming of the body -\n * capacity here bounds concurrent *work*, matching how in-flight is counted.\n */\n private admitGated;\n private runAdmitted;\n /**\n * Select a mounted handler's native Node lane without materializing a Web Request. This is an\n * adapter seam, not a second lifecycle: any app-wide behavior that the ordinary mount path would\n * run makes the capability ineligible and the caller falls back to `resolveNodeSource`. Typed\n * routes keep precedence exactly as `routeAndRun` does, including the existing mount behavior for\n * a path whose registered route rejects this method.\n */\n [RESOLVE_NODE_MOUNT](source: RequestSource): NativeMountSelection | undefined;\n private firstMountUnder;\n /**\n * Like {@link fetch}, but renders a plain-data result **without** building a Web `Response` - the\n * `@nifrajs/node` adapter serializes the returned primitives straight to the socket, skipping the undici\n * `Response` build + body drain (the bulk of the Node bridge cost, measured ≈4µs/req). A handler that\n * returns a `Response`, an error/short-circuit, or a response hook that replaces/consumes the buffered\n * body stays on the full Web path; an in-place response hook can still use the direct writer. Same\n * lifecycle as {@link fetch} (body cap, validation, hooks all run); only the final render differs.\n */\n resolveNode(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<NodeServeOutcome>;\n resolveNodeSource(source: RequestSource, platform?: Platform<EnvOf<Ctx>>, suppliedRuntime?: NodeOutcomeRuntime): MaybePromise<NodeServeOutcome>;\n /** Run generic Web response middleware while retaining direct writes for untouched buffered bodies. */\n private finishNodeWebResponse;\n /** True only when every transforming Web response hook has a header-only Node equivalent. */\n private canUseNodeResponseHooks;\n /** Apply paired native hooks to data outcomes; preserve the complete Web hook pipeline for Response outcomes. */\n private finishNodeResponse;\n private withNodeResponseHeaders;\n /** Synchronous until a native response hook actually returns a Promise. */\n private applyNodeResponseHooks;\n private continueNodeResponseHooks;\n /**\n * Resolve a WebSocket upgrade - the seam every serving adapter uses. Returns `pass` (not a WS\n * upgrade for a registered route → handle as normal HTTP), `reject` (a WS route matched but\n * `upgrade()` rejected, or the path was malformed → return `response`), or `upgrade` (perform the\n * runtime upgrade, then dispatch the native socket's events to `handler`, seeding `ws.data` with\n * `data`). Runs the route's `upgrade(c)` guard in a real request context. Synchronous unless\n * `upgrade()` is async; a throw rejects with a flat 500 (no detail leaked).\n */\n private runWebSocketRequestHooks;\n private continueWebSocketRequestHooks;\n resolveWebSocketUpgrade(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<WebSocketUpgradeOutcome>;\n /** Bun `fetch` when WS routes exist: try a WS upgrade first, else run the normal HTTP lifecycle.\n * `undefined` ⇒ Bun owns the upgraded socket; a `Response` ⇒ a normal reply or a rejected upgrade.\n * (The socket dispatch itself lives in `ws-bun.ts`, loaded via `@nifrajs/core/ws`.) */\n private bunFetchWithWebSocket;\n /**\n * The shared lifecycle, generic over how the final value is rendered: `finalize` turns a handler's\n * result + `set` into the output `T` (`toResponse` → a Web `Response`; `toNodeOutcome` → node-direct\n * primitives), `wrapResponse` lifts an early/error `Response` into that same `T`, and `onTimeout`\n * produces the 503. The Web `fetch` and `resolveNode` are thin callers over this one routing +\n * context + lifecycle implementation - no duplication across the trust boundary.\n */\n /** Apply the `clientIp` trust declaration to the adapter's raw socket peer, returning a platform\n * whose `clientIp` is the derived caller. Only called when a trust declaration is configured. */\n private deriveClientIp;\n private trustedPlatform;\n private dispatch;\n /** Node-native request hook walk. A header-only hook can inspect the lazy source without forcing a\n * Web `Request`; arbitrary request rewrites and full Web hooks use {@link runWithOnRequest}. */\n private runWithNodeRequest;\n private continueNodeRequest;\n private canUseNodeRequestHooks;\n /**\n * onRequest short-circuit path. Synchronous as long as every hook returns synchronously (the\n * common case - e.g. CORS returning `undefined` for a non-preflight request): an `async` version\n * here put EVERY request of any app with one onRequest hook onto the promise machinery, profiled\n * at ~13% of a realistic request. The first hook that returns a Promise hands the REMAINING\n * hooks to the async continuation; behavior is identical.\n */\n private runWithOnRequest;\n /** Async tail of {@link runWithOnRequest}: applies the first awaited hook's outcome, then runs\n * the remaining hooks (awaiting freely - we're already async here). */\n private continueOnRequest;\n private takeResponseRequest;\n /**\n * The NodeRequestContext for a source, MEMOIZED per source so the request twins and the response\n * twins receive the exact same object within one request - that identity is the documented\n * contract stateful twins key their WeakMaps on. An adapter source (which already speaks the\n * interface) is returned as-is; a plain `Request` source (a direct `resolveNode` caller) gets one\n * cached wrapper.\n */\n private nodeRequestContextOf;\n /** Preserve the request visible to generic onRequest hooks for paired native response hooks. */\n private takeNodeResponseRequest;\n /**\n * Route → build context → run. Synchronous through to the handler for a **bare** route\n * (selected by its compiled plan), so a sync handler produces its result with zero promise allocations;\n * routes with validation/hooks keep the full compiled route program, unchanged.\n */\n private routeAndRun;\n private fetchMount;\n /** Run a route that has already been matched by the runtime or Nifra's portable router. */\n private runMatched;\n /** Supply request-specific deadline state to the route's precompiled execution plan. */\n private runMatchedLanes;\n /** @internal Symbol-keyed install seam for the `effectLedger()` plugin. Off the public typed surface. */\n [INSTALL_EFFECT_LEDGER](runtime: EffectLedgerRuntime): void;\n /** The narrowest bare route: a syntactic `() => ...` handler cannot observe the context argument, so\n * successful requests can skip allocating `RequestContext`. Errors still allocate one for logging. */\n private runContextlessBare;\n private contextlessBareError;\n /**\n * The synchronous fast path selected by a route's execution plan: apply static decorations, call the\n * handler, render the result - **no `await`** unless the handler itself returns a promise. It mirrors\n * the same error boundary as the compiled route program (which a bare route would otherwise no-op through) and shares\n * {@link logRequestError}; a bare route has no `onError` hooks, so error handling is fully synchronous\n * (a thrown `Response` is control flow; anything else is a logged flat 500). This is where nifra skips\n * the per-request async-frame tax - the same win codegen routers get, but without `eval`.\n */\n private runBare;\n /** Bare-route error rendering - identical to the compiled route program's catch minus the (absent) onError\n * loop: a thrown `Response` is returned as deliberate control flow; anything else is logged + 500. */\n /**\n * Build a route's fused Web renderer. Composition happens once at\n * registration; the returned closure is what every request to the route runs. Behavior is\n * byte-identical to the generic `runBare`/`runContextlessBare` + `toResponse` pair - same\n * decoration order, same error routing (thrown `Response` = control flow; anything else logs and\n * 500s), same respond semantics (the lifecycle parity suite pins it).\n */\n private buildFusedWeb;\n /** A fused Web lane's render in an async continuation, where a result that cannot be rendered\n * must fail like a handler throw; a synchronous render throw reaches {@link runMatchedLanes}. */\n private respondFused;\n /** Compile the eligible body-only route's parser → validator → handler continuation once. The\n * bounded parser remains shared with the generic lane; only the route-invariant entry lookups and\n * lifecycle dispatch disappear from the common synchronous-validator/synchronous-handler case. */\n private buildFusedBodyRunner;\n /** Web adapter wrapper for the shared body runner. Node passes its native finalizer directly through\n * the execution plan, while Web needs the live context to preserve lazy `c.set` controls. */\n private buildFusedBodyWeb;\n /** The fused Web lane for a route whose only lifecycle step is a query schema: parse + validate +\n * handler + respond in one closure, no lifecycle promise when the validator and handler are sync.\n * Eligibility is decided at registration (see `fusedQuery` in {@link register}); the semantics here\n * are exactly `runQueryOnly`'s for that eligible shape - invalid input returns\n * `validationError(issues)` (recovery hooks disqualify the route from this lane), a thrown\n * `Response` passes through, anything else logs and returns a flat 500, and an async validator\n * falls to a then-chain with the same steps. */\n private buildFusedQueryWeb;\n /**\n * Compile a route's `derive + before` lifecycle to a single closure: the per-request walk through\n * `runSync` → `runHooksSync` is a stack of 3 frames and 2 `Object.assign`s for what is by far the\n * most common middleware shape (auth/trace/id derivation, an auth/policy `beforeHandle`). Folding\n * the same steps into one closure hits the same monomorphic inline-cache site as `buildFusedWeb`,\n * and `Object.assign(ctx, deriveResult)` becomes one extra property write on the context's already\n * hot hidden class. Behavior is byte-identical to the compiled route program: the same thrown-value\n * contract (`Response` is control flow, anything else logs + 500), the same `c.set` semantics, the\n * same `fusedRespond` for the rendered body. The `LifecycleExecutionLane` guarantee\n * (`schema.params === undefined && schema.headers === undefined && derives === 1 &&\n * beforeHandle === 1 && afterHandle === 0 && onError === 0 && !hasResponseContract &&\n * !hasDecorations`) is enforced by `selectRouteLanes`; this lane is selected ONLY when all of those\n * hold. A `query` schema (the route declares `{ query }` alongside the hooks) is validated FIRST,\n * mirroring the compiled route program's stage order; the fused builder runs validate → derive →\n * before → handler in one frame.\n */\n private buildFusedDeriveBefore;\n private buildFusedDeriveBeforeAfter;\n /**\n * Body + lifecycle hooks fused: parse → validate → derive → before → handler → (after) in one\n * closure, the same win `buildFusedBodyRunner` gives for the no-hooks body shape. The shape is\n * `lifecycleHookLane` PLUS a body schema with no other validation conflicts; the lane is selected\n * ONLY when `schema.body !== undefined && schema.query/params/headers === undefined &&\n * schema.onValidationError === undefined && !defaultOnValidationError && !hasIdempotency &&\n * !hasLedger && derives === 1 && beforeHandle === 1 && afterHandle <= 1 && onError === 0 &&\n * !hasResponseContract && !hasDecorations && around === 0`. The same single `querySchema === undefined`\n * trick used in the no-body lane lets the build path stay simple: a query + body route falls back\n * to the generic program (this is rare in practice - validated query + validated body is usually a\n * \"search results\" route with a middleware chain on top, and the generic lane is fine there).\n */\n private buildFusedBodyDeriveBeforeAfter;\n /**\n * Generic (finalize/wrapResponse-parameterized) fused runner for the derive-before(-after) lane:\n * the Node-direct counterpart of `buildFusedDeriveBefore` / `buildFusedDeriveBeforeAfter`.\n *\n * The Web fused builders above return a `Response`, so the Node dispatcher (`webFast === false`)\n * cannot use them and a derive+before route falls back to the generic route program there - two\n * staged loops, per-stage dispatch, and the async-continuation machinery - while Bun rides the\n * single closure. That asymmetry is the realistic-route Node deficit against Fastify: this runner\n * closes it by running validate → derive → before → handler → (after) in one frame and finalizing\n * through the caller's own `finalize` (the Node outcome on the direct lane, `toResponse` on Web),\n * so the same registration feeds both runtimes with no per-lane copy of the lifecycle to drift.\n *\n * Semantics mirror the generic program stage-for-stage for the shapes this lane admits (exactly\n * one derive, one beforeHandle, zero-or-one afterHandle, no onError/around/decorations/contracts/\n * recovery hooks - enforced by `selectRouteLanes`): thrown `Response`/`status(...)` are control\n * flow through `wrapResponse`/`finalize`, anything else logs + 500s via the shared `bareError`\n * lane (identical to `handleLifecycleError` with no `onError` hooks), and a terminal `finalize`\n * throw (e.g. an unstringifiable handler return on the Node lane) is caught exactly as\n * `finishLifecycleContract` catches it. Step functions close over registration state only and take\n * the request state as arguments, so the hot path allocates no per-request closures.\n */\n private buildFusedDeriveBeforeRunner;\n /**\n * Generic fused runner for the body+derive-before(-after) lane: the Node-direct counterpart of\n * `buildFusedBodyDeriveBeforeAfter`. Same contract as `buildFusedDeriveBeforeRunner` above - one\n * frame running parse → validate → derive → before → handler → (after) through the caller's own\n * `finalize` - with the body read ahead of validation, exactly as the generic program orders its\n * body stage before the derive/before stages. `readBodyFramed` keeps the shared bounded-read,\n * content-type, and prototype-poisoning contracts; the 415/400 renders take `wrapResponse`\n * directly, which is what the generic lane's wrap-after-identity amounts to.\n */\n private buildFusedBodyDeriveBeforeAfterRunner;\n private bareError;\n /**\n * Keep the ordinary thrown-error response independent from the caught value. Deliberate Response\n * control flow is handled by `renderBareError`; every other throw gets this fixed public envelope.\n */\n private internalErrorResponse;\n private runWithAround;\n /** Execute the registration-compiled general stage program. */\n private runProgram;\n /** Bind a compiled validation stage to its stable schema and the existing recovery contract. */\n private validateProgramStage;\n /** Preserve the existing bounded body reader and its fail-closed framing/prototype checks. */\n private readProgramBody;\n /** Keep thrown Response/status and redacted 500 semantics in one existing error boundary. */\n private handleProgramError;\n /** Finish a successful program result through response-contract enforcement and finalization. */\n private finishProgramResult;\n private runAround;\n private runBodyOnly;\n /** Validate + run the handler for the bodyOnly path - shared by the inline fast path and the\n * streaming fallback. A method (not per-request closures) so the hot path allocates nothing\n * beyond the one `.then` continuation. */\n private finishBodyOnly;\n private executeHandler;\n private handleValidationErrorRecovery;\n private applyBodyValidation;\n private runQueryOnly;\n /** Validate-result → set `ctx.query` → run handler. A method (not a per-request closure), the\n * query analogue of {@link applyBodyValidation}. */\n private applyQueryValidation;\n /**\n * Thread the response through each global `onResponse` hook. Stays SYNCHRONOUS until a hook\n * actually returns a Promise - an `async` version forced a promise + microtask on EVERY response\n * of any app with an onResponse hook (cors/securityHeaders/etag/timing all use onResponse), the\n * same ~13%/req tax the onRequest walk was de-async'd to avoid. The first async hook hands the\n * rest to {@link continueOnResponse}.\n */\n private applyOnResponse;\n private applyOnResponseAndFinalize;\n private completeResponseFinalization;\n private failResponseFinalization;\n /** Notify terminal observers in order while isolating both sync and async failures. */\n private notifyResponseFinalized;\n /** Async tail of {@link applyOnResponse}: runs the remaining hooks once one has gone async. */\n private continueOnResponse;\n /**\n * Bound the response time. On timeout we abort `ctx.signal` (so cancellation-aware\n * handlers can bail) and return 503; the in-flight work keeps running but its\n * result is discarded - JS can't forcibly cancel a promise.\n */\n private withTimeout;\n private finishLifecycleContract;\n private finishContractOutcome;\n /** Synchronous by design, and `MaybePromise` rather than `Promise` for the same reason: control flow\n * out of a lifecycle stage must not cost a promise. An `async` method allocates one and defers the\n * result a microtask even when every branch it takes returns immediately, which is the common case\n * here - a thrown `status(...)`/`Response`, or a route with no `onError` hook at all. Only the hook\n * loop, which may await, drops into {@link runErrorHooks}. */\n private handleLifecycleError;\n /** The `onError` chain, split off {@link handleLifecycleError} so its `await` costs only the routes\n * that registered a hook. A hook may return a custom response; otherwise the default 500 stands. */\n private runErrorHooks;\n /** Log an unhandled request error to the (redacting) logger - shared by the compiled route program and the\n * bare fast path ({@link bareError}) so both record the same fields. Never throws; never leaks. */\n private logRequestError;\n private readAndValidateBody;\n /** Apply validation and its recovery hook on the generic lifecycle lane. Recovery is completed\n * before derives/beforeHandle run, matching the body-only and query-only execution lanes. */\n private applyLifecycleValidation;\n private finishLifecycleValidationRecovery;\n /** Adapt one route's compiled execution plan to Bun's already-matched request shape. Route\n * semantics remain in the plan; this closure only supplies native params and deadline fallback. */\n private compileBunNativeHandler;\n /** Compile portable route registrations into Bun's native route table. Apps with request-rewrite\n * hooks or WebSockets retain the single portable dispatcher because those features must run before\n * route selection/upgrade.\n *\n * Bun and the portable router agree on which of two static-and-`:param` paths wins a request, so\n * the table is kept to those paths. Where Bun would otherwise pass a request on to a less specific\n * path, the more specific one carries `fallback`, the portable dispatcher, under that method.\n * `peer` is the platform every request served from the table shares. */\n private buildBunNativeRoutes;\n /**\n * Start a `Bun.serve` instance bound to `port` (use `0` for an ephemeral port).\n *\n * `reusePort` sets `SO_REUSEPORT` so **multiple processes can bind the same port** and the kernel\n * load-balances connections across them - the standard way to use every core (Bun is\n * single-threaded per process). Spawn one process per core, each calling\n * `app.listen(PORT, { reusePort: true })`; see `examples/cluster.ts`. Every process must opt in,\n * and all of them must be the same app. Linux balances ~evenly; macOS accepts the flag but may\n * favor one socket (fine for dev, measure on Linux for production numbers).\n *\n * `hostname` is the bind address, defaulting to Bun's `0.0.0.0` (every interface). Pass\n * `\"127.0.0.1\"` to bind loopback only - an admin surface, a sidecar, or anything that must not be\n * reachable off the box. Omitting it when you meant to restrict is a real exposure, so it is a\n * first-class option rather than something a caller has to drop down to `Bun.serve` for.\n *\n * `idleTimeoutSec` is how long Bun tolerates a connection with no bytes moving before it closes\n * the socket. Bun's default is **10 seconds**, and a request whose handler is still working sends\n * nothing - so any endpoint slower than 10s (a render, an export, a long upstream call) has its\n * connection cut mid-flight regardless of `requestTimeoutMs`. Apps with such endpoints must raise\n * this above their slowest expected response, which is why it is a first-class option and not a\n * reason to drop down to `Bun.serve`. `0` disables the timeout entirely; max 255.\n *\n * `tls` serves HTTPS directly: `app.listen(443, { tls: { cert, key } })` with PEM text or bytes.\n * Requests then arrive with `https:` URLs. Behind a proxy or a platform that terminates TLS, leave\n * it unset.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n readonly idleTimeoutSec?: number;\n readonly tls?: ListenTlsOptions;\n }): RunningServer;\n /**\n * Gracefully stop: wait for in-flight requests to finish (up to `drainMs`), then\n * issue a single terminal stop - graceful if everything drained, forced if\n * stragglers remain. Safe to call when not listening.\n *\n * The Bun semantics: poll `pendingRequests` (awaiting\n * `stop()`'s promise drops in-flight requests), and decide graceful-vs-forced in\n * ONE call (Bun can't escalate an already-graceful `stop()` to a forced close).\n * New connections may be accepted during the drain window; in a real deploy the\n * load balancer has already stopped routing here, and `drainMs` bounds it.\n */\n stop({ drainMs }?: {\n drainMs?: number;\n }): Promise<void>;\n private installSignalHandlers;\n}",
|
|
14163
|
+
"signature": "export declare class Server<R extends Registry = EmptyRegistry, Ctx = EmptyContext, HookOutput = never> {\n /**\n * Which copy of `@nifrajs/core` declared this type. Two copies in one build (a linked sibling repo,\n * a hoisting split) produce two unrelated `Server` types whose assignment error is a wall of\n * missing internals; the brand puts the feature version in the type itself, so `typeof app` on\n * hover - and `NifraFeatureVersion` in an assertion - says which core an app is talking to.\n * `nifra doctor` is the diagnosis that names both install paths.\n *\n * `declare` = type-only: no field is emitted, nothing is allocated per server.\n */\n readonly __nifraCoreVersion: NifraFeatureVersion;\n private readonly catalog;\n /** WebSocket routes, matched separately at upgrade time (a GET + `Upgrade: websocket`). */\n private readonly wsRouter;\n /** Each socket path, its declared capabilities, the evidence declarations its handshake captured\n * and the chain it runs; reflection reads it. */\n private readonly wsRoutes;\n /** `wsChanges` when `wsMountsLive` was last worked out; -1 until then. */\n private wsMountsCheckedAt;\n /** Whether an app mounted here takes WebSocket upgrades, as of `wsMountsCheckedAt`. */\n private wsMountsLive;\n /** In-process pub/sub backing `ws.subscribe(topic)` + `app.publish(topic, data)` (single-instance).\n * Created by the first `app.ws()` via the `@nifrajs/core/ws` runtime - `undefined` until then, so a\n * no-WebSocket app never constructs (or bundles) it. */\n private topics;\n /** True once any `app.ws()` route sets `validateSend: true` - the one case where a broadcast frame\n * is validated (and possibly dropped) per socket, so `app.publish` must stay on the JS registry loop\n * rather than delegate to Bun's native `server.publish`. */\n private wsHasValidatedSend;\n /** Bun's native topic broadcast, bound by `listen()` in native-pubsub mode; `app.publish` uses it\n * instead of the JS registry. `undefined` off Bun, before `listen()`, with a validated-send route,\n * or when a mounted app takes upgrades. */\n private nativePublish;\n private readonly maxBodyBytes;\n private readonly protoPoisoning;\n private readonly formOrigins;\n /** `trustBodyFraming`: mark every `app.fetch` request as runtime-framed (see ServerOptions). */\n private readonly trustBodyFraming;\n private readonly wsMaxPayloadBytes;\n private readonly requestTimeoutMs;\n private readonly wsUpgradeTimeoutMs;\n /** Installed by the `responseContract()` plugin; `undefined` = not installed, which is the default\n * and the state in which a declared `response` schema stays a compile-time contract only. */\n private responseContractRuntime;\n /** Opt-in caller-IP trust declaration; `undefined` = socket peer only, no forwarded header believed. */\n private readonly clientIpTrust;\n private readonly acceptInboundDeadlines;\n private readonly maxInboundDeadlineMs;\n private readonly deadlineAdmissionOptions;\n private readonly gracefulSignals;\n private readonly stopHooks;\n private readonly fetchMounts;\n private mountOrder;\n /** Number of composed mounts that must run before the parent route table. Keeps legacy mounts off the hot path. */\n private preRouteMountCount;\n /** Capacity-admission gate; `undefined` = off (the request path pays nothing). */\n private readonly capacityGate;\n private readonly onCapabilityUse;\n private readonly capabilityInterceptors;\n private readonly capabilityObservers;\n /** The installed effect-ledger runtime (owns the sink + per-route resolution + settle), or\n * `undefined` when the effect-ledger plugin is not installed. */\n private effectLedgerRuntime;\n /** The installed idempotency runtime (owns the app-wide default store + the dedupe lane), or\n * `undefined` when the idempotency plugin is not installed. */\n private idempotencyRuntime;\n /** Installed opt-in runtime for `.tool()`/`.resource()`/`.prompt()`; `undefined` until `.use(mcp())`. */\n private mcpRuntime;\n /** Installed answer for a request no route matched; `undefined` (the plain 404) until `.use(notFound())`. */\n private notFoundLane;\n /** Installed Node-direct renderer for direct `resolveNode()` callers; `undefined` until `.use(nodeDirect())`. */\n private nodeOutcomeRuntime;\n /** Installed streaming runtime for `.sse()` routes; `undefined` until `.use(streaming())`. */\n private sseRuntime;\n /** Installed WebSocket runtime for `.ws()` routes; `undefined` until `.use(websocket())`. */\n private wsRuntime;\n private readonly logger;\n /** How much of an unhandled error {@link logRequestError} records. See `ServerOptions.errorLogDetail`. */\n private readonly errorLogDetail;\n /** App-wide validation-error fallback; a route's own `schema.onValidationError` takes precedence. */\n private readonly defaultOnValidationError?;\n private bunServer;\n private bunSockets;\n private signalHandler;\n private sealed;\n private readonly derives;\n /** Dedicated authentication stages captured by subsequent routes. */\n private readonly authStages;\n private readonly decorations;\n private readonly beforeHandleHooks;\n private readonly afterHandleHooks;\n private readonly onErrorHooks;\n private readonly aroundHooks;\n private readonly onRequestHooks;\n private readonly onNodeRequestHooks;\n /** Registration-time eligibility for the Node request twin lane. */\n private nodeRequestHooksComplete;\n /** True when every request hook is safe to skip on a Bun native route. */\n private bunNativeRequestHooksSafe;\n private readonly onResponseHooks;\n private readonly onNodeResponseHooks;\n /** Registration-time eligibility for the Node response twin lane. */\n private nodeResponseHooksComplete;\n /** True when every response hook only mutates headers and can run after a Bun fused response. */\n private bunNativeResponseHeadersOnly;\n /**\n * True once a bundle registers a RAW `onNodeResponse` twin - one handed the outcome's header\n * record itself rather than the case-normalizing view. Their names are contractually the wire\n * spelling, but registration cannot PROVE it, so such an app forgoes the all-lowercase mark and\n * every reader re-derives the answer, exactly as before the mark existed.\n */\n private hasRawNodeResponseHook;\n private readonly onResponseFinalizedHooks;\n /**\n * Statically declared response headers, merged and prebuilt at registration; `undefined` (the\n * default) leaves every render path in its original shape. These are NOT response hooks - they are\n * folded into response construction - so declaring them keeps the fused native lanes an\n * `onResponse` hook would have disabled.\n */\n private staticResponseHeaders;\n /** A group's view of the static headers its enclosing scopes declared before it was created. */\n private inheritedStatics;\n /** A group's view of the plugins its enclosing scopes applied before it was created; unset while\n * a plugin applies, so its own dependency `use()` shares the parent's copy. */\n private inheritedPlugins;\n /** `wrapResponse` for the Web lanes: identity until static headers exist to fold into the\n * framework's own error/404/timeout renders, which are built outside the header init. */\n private wrapWebResponse;\n private webResponseTimeout;\n /** Body/raw response hooks need a framework-payload marker; keep that decision per app. */\n private responseBodyTag;\n private readonly responseBodyOwners;\n private readonly finalizeResponse;\n private readonly responseRequests;\n /** A request the WebSocket handshake check ran the onRequest hooks on and then passed to HTTP →\n * what the hooks returned, so `fetch` routes that instead of running the hooks a second time. */\n private wsHookedPasses;\n /** Original source → request observed by generic request hooks, including in-place mutations. */\n private readonly responseSources;\n /** Memoized NodeRequestContext per plain-`Request` source - see {@link nodeRequestContextOf}. */\n private readonly nodeContexts;\n /** Plugins/middleware already applied via `use`, by name - for idempotent dedupe. */\n private readonly appliedPlugins;\n /** Order-scoped evidence captured by routes registered after an assured plugin. */\n private readonly activeAssurance;\n /** App-wide evidence from global hooks; applies retroactively to every route. */\n private readonly globalAssurance;\n /** App-declared MCP resources / prompts (via {@link resource} / {@link prompt}), read by `nifra mcp`. */\n private readonly mcpResourceList;\n private readonly mcpPromptList;\n /** Kept so a {@link group} scope is built with exactly this server's settings: fused lanes read\n * several of them at request time, so a group route must never run under different ones. */\n private readonly options;\n /** Static prefix joined onto every route this server registers; non-empty only on a group scope. */\n private routePrefix;\n constructor(options?: ServerOptions);\n private assertConfigurable;\n /** Register a callback awaited after graceful drain and server stop. Hung callbacks are bounded. */\n onStop(fn: StopHook): this;\n /**\n * Mount a legacy fetch handler under a literal path prefix. Mounted handlers sit behind typed\n * routes, so routes can move one at a time while the remaining legacy surface stays live.\n * Mounted responses are outside Nifra's typed route and response-contract checks.\n *\n * It carries HTTP only: a WebSocket upgrade under the prefix reaches the handler as an ordinary\n * request and never becomes a socket. Serve that path's sockets with `app.ws()` routes or a\n * mounted child app, or keep the legacy server running beside this one for them.\n */\n mountFetch(path: string, handler: FetchHandler<EnvOf<Ctx>>, options?: MountFetchOptions): this;\n /**\n * Compose a child fetch app under a literal path prefix.\n *\n * Composed mounts run after the app-global request phase and before the parent's route table. This\n * makes them safe to use in an SSR shell whose `/*` page route would otherwise swallow an API mount.\n * If the child exposes `resolveWebSocketUpgrade`, the same mount also participates in adapter-owned\n * WebSocket upgrades; the serving adapter still upgrades its original socket, while the child sees\n * the mounted request path (stripped when requested).\n *\n * `fallbackOn: 404` is deliberately limited to GET/HEAD/OPTIONS at dispatch time. Those methods are\n * replayable without buffering an untrusted request body; POST/PUT/PATCH and streaming requests\n * never get retried after a child has had a chance to consume them.\n */\n mount(options: MountOptions<EnvOf<Ctx>>): this;\n /**\n * Add a per-request, computed context extension. Order-scoped: it is snapshotted into every route\n * declared *after* this call, and reaches none declared before. One added after the last route\n * (e.g. on the app returned by a route-registering factory) covers nothing - see\n * {@link ServerOptions.unusedScopedHooks}.\n *\n * Returning a `status(...)` (or a `Response`) instead of an extension ends the request there - the\n * guard shape, and the cheap one: it renders as plain data on the same lane a handler's return\n * takes, where `throw new Response(...)` pays ~40% of the rejection lane to build the object. That\n * branch is control flow, so it does not widen the derived context type.\n */\n derive<H extends (context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx & ContextExtensionOf<ReturnType<H>>, HookOutput | StatusResponseOf<Awaited<ReturnType<H>>>>;\n /**\n * Add a static context value. Order-scoped: captured by every route declared *after* this call, and\n * by none before; one added after the last route reaches nothing\n * (see {@link ServerOptions.unusedScopedHooks}).\n */\n /**\n * Register a dedicated authentication stage for subsequent routes.\n *\n * Unlike `derive`, this stage receives a body-blind authentication capsule and is compiled before\n * route validation. Keeping it separate prevents an unrelated derive from accidentally becoming a\n * security gate and lets the route compiler retain a protected fast lane.\n *\n * A stage that throws, or returns anything but `authenticated(principal)` or `rejected(...)`, fails\n * closed with 503 `{ ok: false, error: \"auth_unavailable\" }`. The cause goes where a handler's error\n * goes: to `onError`, whose response replaces the 503, and when no hook answers, to the logger. A\n * thrown `Response` or `status(...)` is sent as thrown, as it is from a handler.\n */\n authenticate<Principal>(stage: AuthenticationStage<Principal, EnvOf<Ctx>>): Server<R, Ctx & {\n readonly principal: Principal;\n }, HookOutput>;\n decorate<const K extends string, V>(key: K, value: V): Server<R, Ctx & Record<K, V>, HookOutput>;\n /**\n * Run before routing on the raw request. Return a `Response` or a `status()` result to\n * short-circuit, or a replacement `Request` to continue routing with a rewritten method/URL/headers.\n * Global. A throw or rejection goes to every registered {@link onError} (route-less context), then\n * the logged default 500.\n */\n onRequest(fn: (req: Request, platform?: Platform<EnvOf<Ctx>>) => MaybePromise<OnRequestResult>): this;\n /**\n * Run after validation, before the handler; a non-`undefined` return short-circuits. Order-scoped:\n * it is snapshotted into every route declared *after* this call and covers none declared before, so\n * one added after the last route reaches nothing (see {@link ServerOptions.unusedScopedHooks}).\n */\n beforeHandle<H extends (context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /**\n * Wrap the matched route lifecycle for subsequent routes. This is intentionally generic over the\n * route output, so wrappers like async context storage do not force Node's direct JSON path through\n * a Web `Response`. The first registered wrapper is outermost.\n *\n * Order-scoped: captured by every route declared *after* this call, none before; one added after the\n * last route reaches nothing (see {@link ServerOptions.unusedScopedHooks}).\n */\n around<H extends (context: Context & Ctx, next: () => MaybePromise<unknown>) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /**\n * Asynchronously admit each subsequent `executeCapability()` call before its owned effect runs.\n * Interceptors receive token-only metadata plus an abort signal and must call `next()` exactly once\n * to admit. Returning without `next()`, timing out, aborting, or throwing fails the effect closed.\n */\n aroundCapability(interceptor: CapabilityInterceptor, options?: AroundCapabilityOptions): this;\n /** Observe token-only admission/execution lifecycle events for subsequent capability routes. */\n observeCapability(observer: EffectLifecycleObserver): this;\n /** Transform the handler's result before it is serialized. Order-scoped: captured by routes declared\n * *after* this call, none before; one added after the last route reaches nothing (see\n * {@link ServerOptions.unusedScopedHooks}). */\n afterHandle<H extends (result: unknown, context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /** Handle a thrown error; a non-`undefined` return becomes the response (else the default 500, or 503\n * `auth_unavailable` for a failed {@link authenticate} stage). Order-scoped: captured by routes\n * declared *after* this call, none before; one added after the last route reaches no route (see\n * {@link ServerOptions.unusedScopedHooks}). Every one answers an {@link onRequest} failure. */\n onError<H extends (error: unknown, context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /** Transform every outgoing response - success, error, 404, 405, short-circuit. Global. */\n onResponse(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /**\n * Declare response headers with NO per-request decision behind them - and pay nothing for them on\n * the request path.\n *\n * These are not a hook. Because the values are known at wire-up, they are folded into response\n * construction (one prebuilt init for JSON renders, one record merge where the request set its own\n * headers), so an app whose only response middleware is static keeps every fused and native lane -\n * `onResponse`/`onResponseHeaders` disable Bun's fused native routes and, for a full `onResponse`,\n * the Node direct writer. They apply to EVERY response, exactly as a response hook would: success,\n * error, 404/405, timeout, and short-circuit alike.\n *\n * app.responseHeaders({ \"x-frame-options\": \"DENY\", \"referrer-policy\": \"no-referrer\" })\n *\n * They are DEFAULTS: a value the request itself produced (`c.set.headers`, or a response hook)\n * wins, whatever casing it used. In a group, a name the group declares replaces the value its\n * enclosing scopes declared before the group, on the group's routes. Names are lowercased once here; a non-string value, an invalid\n * name, `__proto__`, or a name the render owns (`content-type`, `content-length`,\n * `transfer-encoding`, `set-cookie`) throws a `TypeError` at wire-up.\n *\n * ORDERING: declarations made before any response hook fold into one static record. One made AFTER\n * a response hook cannot - the hook may already have written that name and must keep winning - so\n * it registers as an ordinary `onResponseHeaders` hook instead, preserving registration order at\n * the cost of the static tier's speed. Declare static headers first.\n */\n responseHeaders(record: Readonly<Record<string, string>>): this;\n /** Wire an already-validated lowercase record into the static tier, or - once a dynamic response\n * hook owns part of the header state - into a hook that runs in the right order. */\n private addStaticResponseHeaders;\n private enableResponseBodyTagging;\n private responseObserverMethods;\n /** Observe the terminal response after all transformations. Observers are ordered and fail-open. */\n onResponseFinalized(fn: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>): this;\n /**\n * Apply `all()` or `method()` from `@nifrajs/core/methods`: one handler registered under several\n * methods, or under a method outside the standard seven. The standard methods join the registry.\n *\n * Declared first on purpose. The plugin's handler is typed against this app's context, which\n * TypeScript reads from the first overload it tries.\n */\n use<M extends string, Path extends string, S extends RouteSchema, Output>(plugin: MethodRoutesPlugin<M, Path, S, Output, Ctx>): Server<WithMethodRoutes<R, M, Path, S, Output, HookOutput>, Ctx, HookOutput>;\n /** Enable the opt-in portable response observer methods. */\n use(plugin: ResponseObserverPlugin): this & ResponseObserverMethods;\n /**\n * Apply a **context** plugin ({@link ContextPlugin}, from {@link defineContextPlugin}) - it adds `D`\n * to the handler context and changes nothing else, so the route registry `R` and the existing context\n * `Ctx` thread through untouched. Like the identity overload above, this exists because the generic\n * `(app: this) => Out` overload below cannot infer through a *generic* plugin signature: it erases the\n * plugin's own type parameters to their constraints, which silently widens `R` to `Registry`.\n */\n use<D extends object>(plugin: ContextPlugin<D>): Server<R, Ctx & D, HookOutput>;\n /**\n * Apply a type-**identity** plugin ({@link IdentityPlugin}, from {@link defineIdentityPlugin}) - it\n * registers routes/hooks but doesn't change the types, so this returns `this` with the route registry\n * and context fully intact. This overload exists specifically so a named identity plugin (e.g.\n * `@nifrajs/better-auth`) threads the registry: its `& { pluginName }` intersection would otherwise\n * defeat the generic inference of the transforming overload below and collapse the result to `any`.\n */\n use<AddedHookOutput = never>(plugin: IdentityPlugin<AddedHookOutput>): Server<R, Ctx, HookOutput | AddedHookOutput>;\n /**\n * Apply a **plugin function** - `(app) => app`, typically built with {@link definePlugin}. It's\n * called with `this` and its result is returned, so an inline plugin's `derive`/`decorate` thread\n * the added context to handlers defined after `use` (the overload is generic over the concrete\n * `this`). A named plugin already applied is skipped (idempotent dedupe), however it was configured,\n * so a plugin meant to stack - a second, stricter guard - needs a name of its own per instance.\n *\n * If the plugin's return type is unpinned - `Server<any, any>`, as a hand-rolled `(app) => app` or a\n * `NifraPlugin<AnyServer, AnyServer>` infers (e.g. an auth plugin whose own types collapsed) - this\n * returns the non-callable {@link PluginTypeCollapsed} instead of silently widening the whole typed\n * client to `any`. `.get()`/`.post()` then fail right here rather than surfacing as `any` hundreds of\n * lines away. Fix at the plugin: build it with {@link defineIdentityPlugin}/{@link defineContextPlugin},\n * or pin its input server type. This mirrors the guard {@link definePlugin} already applies.\n */\n use<Out extends AnyServer>(plugin: (app: this) => Out): [ServerTypeUnpinned<Out>] extends [true] ? PluginTypeCollapsed : Out;\n /**\n * Apply a {@link Middleware} bundle - wire each hook it provides to its lifecycle point. Returns\n * `this` (no context-type merging); call it before the routes its `beforeHandle`/`afterHandle`\n * should cover (those are order-scoped; `onRequest`/`onResponse` are global). A bundle applied after\n * the last route reaches nothing - {@link ServerOptions.unusedScopedHooks} logs that at seal. A named\n * bundle already applied is skipped (idempotent).\n */\n use<M extends Middleware>(mw: M): Server<R, Ctx, HookOutput | MiddlewareOutputOf<M>>;\n use(mw: Middleware): this;\n get<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n get<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Register a **typed SSE route** - an endpoint streaming `text/event-stream` whose event\n * payloads are contracted by `schema.sse`. It is a GET route, or a POST route when the schema\n * declares a `body` (a GET carries none): the body validates as on any POST, and the client sends\n * it with `.subscribe(onEvent, { body })` - the shape of a chat stream that posts its prompt. The handler receives the validated context plus a\n * {@link TypedSSEStream}: `stream.send(event)` is compile-time-checked against the schema and\n * JSON-serialized into the SSE `data:` field. The typed client sees the marker and grows a\n * `.subscribe(onEvent)` for the route with the same payload type - end-to-end typed streaming.\n *\n * import { streaming } from \"@nifrajs/core/sse\" // .use(streaming()) enables .sse()\n * const app = server().use(streaming()).sse(\"/feed\", { sse: t.object({ id: t.integer(), title: t.string() }) },\n * async (c, stream) => {\n * stream.send({ id: 1, title: \"hello\" }) // typed\n * await waitForDisconnect(stream.signal)\n * },\n * { keepAlive: 15_000 })\n *\n * // client: const off = api.feed.subscribe((post) => console.log(post.title))\n *\n * `init` passes through to the underlying {@link sse} helper (`keepAlive`, `maxBufferedBytes`,\n * extra headers). The connection closes when the handler resolves, `stream.close()` runs, or the\n * client disconnects (`stream.signal`). Query/body schemas validate exactly as on any other route.\n */\n sse<Path extends string, S extends RouteSchema & {\n sse: StandardSchemaV1;\n }>(path: Path, schema: S, run: (context: Context<Path, S> & Ctx, stream: TypedSSEStream<InferOutput<S[\"sse\"]>>) => void | Promise<void>, init?: SSEInit): Server<AddRoute<R, SseMethodOf<S>, Path, RouteInfoFor<Path, S, Response, HookOutput>>, Ctx, HookOutput>;\n post<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n post<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n put<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n put<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n patch<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n patch<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n delete<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n delete<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Declare an **MCP tool** an agent can call (via `nifra mcp`, or a mounted MCP endpoint): a typed\n * `POST /_nifra/tool/<name>` route whose `input`/`output` schemas contract the call and surface in\n * `tools/list`. Requires `.use(mcp())` - without it, `.tool()` is a registration error, so an\n * ordinary HTTP app never bundles the MCP wiring. Siblings: {@link resource}, {@link prompt}.\n *\n * import { mcp } from \"@nifrajs/core/mcp\"\n * const app = server().use(mcp()).tool(\n * \"search\",\n * { description: \"Search posts\", input: t.object({ q: t.string() }) },\n * ({ q }) => findPosts(q),\n * )\n */\n tool<Name extends string, S extends {\n description: string;\n input: StandardSchemaV1;\n output?: StandardSchemaV1;\n annotations?: ToolAnnotations;\n }, H extends (input: InferOutput<S[\"input\"]>, ctx: Context & Ctx) => MaybePromise<S[\"output\"] extends StandardSchemaV1 ? InferOutput<S[\"output\"]> : unknown>>(name: Name, config: S, handler: H): Server<AddRoute<R, \"POST\", `/_nifra/tool/${Name}`, RouteInfoFor<`/_nifra/tool/${Name}`, S[\"output\"] extends StandardSchemaV1 ? {\n body: S[\"input\"];\n response: S[\"output\"];\n } : {\n body: S[\"input\"];\n }, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Declare an MCP **resource** - read-only data an agent can fetch through `nifra mcp` (app config, a\n * generated document, …). `read` runs in the app process, so capture whatever app state it needs in the\n * closure. `uri` is the MCP resource identifier (e.g. `\"myapp://config\"`). The sibling of {@link tool}\n * for the resource half of MCP.\n */\n resource(uri: string, config: {\n readonly name: string;\n readonly description?: string;\n readonly mimeType?: string;\n }, read: McpResourceDescriptor[\"read\"]): Server<R, Ctx, HookOutput>;\n /**\n * Declare an MCP **prompt** - a reusable prompt template an agent can fetch through `nifra mcp`.\n * `handler` receives the caller's arguments and returns the rendered messages.\n */\n prompt(name: string, config: {\n readonly description: string;\n readonly arguments?: readonly PromptArgument[];\n }, handler: McpPromptDescriptor[\"handler\"]): Server<R, Ctx, HookOutput>;\n /** The MCP resources declared via {@link resource} - enumerated by `nifra mcp`. */\n mcpResources(): readonly McpResourceDescriptor[];\n /** The MCP prompts declared via {@link prompt} - enumerated by `nifra mcp`. */\n mcpPrompts(): readonly McpPromptDescriptor[];\n /**\n * Register a **WebSocket** route. The connection upgrades on a `GET` to `path` carrying\n * `Upgrade: websocket`. The handshake runs the chain an HTTP `GET` registered here would: the\n * `authenticate()` stages, `derive`s and `beforeHandle`s added before this call, then the optional\n * `handler.upgrade(c)`. Any of them may reject (a `Response`, a `status(...)`, a failed auth stage);\n * `upgrade()` may seed per-connection `ws.data`. To keep a socket public, register it before the\n * guard. WebSockets are served by the\n * adapter (`listen()`, `@nifrajs/node`, `@nifrajs/deno`, `toFetchHandler`) - not by bare `app.fetch`, which\n * has no socket (a WS path through `app.fetch` is a normal HTTP response).\n *\n * The route also enters the type-level registry (under the pseudo-method `\"WS\"`), so the typed\n * client grows a `.ws()` handle for it: `messageSchema` types what the client may `send`,\n * `sendSchema` types the frames it receives. Passing explicit type arguments (`ws<MyData>(…)`)\n * defeats path-literal inference and skips the registry entry - the route still serves, it is just\n * invisible to `client<App>`; prefer typing `data` via `upgrade()`'s return.\n *\n * app.ws(\"/chat\", { open: (ws) => ws.send(\"hi\"), message: (ws, data) => ws.send(data) })\n */\n ws<Data = unknown, Schema extends StandardSchemaV1 | undefined = undefined, Send extends StandardSchemaV1 | undefined = undefined, Path extends string = string>(path: Path, handler: WebSocketHandler<Data, EnvOf<Ctx>, Schema, Send, Ctx>): string extends Path ? Server<R, Ctx, HookOutput> : Server<AddRoute<R, \"WS\", Path, WsRouteInfoFor<Path, Schema, Send>>, Ctx, HookOutput>;\n /**\n * Broadcast `data` to every WebSocket connection subscribed to `topic` (via `ws.subscribe(topic)`).\n * In-process and **single-instance** (see {@link TopicRegistry}) - a multi-instance deploy must bridge\n * an external fan-out (Redis, a Durable Object) to this. A no-op when nobody is subscribed.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void;\n private route;\n /**\n * Low-level route registration shared by the inline builder and `implement()`.\n * Captures the server's current `derive`/`decorate` chain into the route - this\n * is the \"compiled\", order-scoped per-route chain.\n */\n register(method: string, path: string, schema: RouteSchema | undefined, handler: (context: never) => unknown): void;\n /** Register a contract/group route batch atomically. Every route captures the same current chain it\n * would capture through {@link register}; no route becomes visible unless the full batch validates.\n *\n * A path ending in optional parameters (`/users/:id?`) is one catalog route per concrete pattern,\n * so reflection, OpenAPI, evidence and the typed client all see ordinary routes. */\n registerBatch(routes: readonly {\n readonly method: string;\n readonly path: string;\n readonly schema: RouteSchema | undefined;\n readonly handler: (context: never) => unknown;\n }[]): void;\n /** Join a group scope's prefix BEFORE compilation, so the pattern, the reflected descriptor, the\n * capability guard, the ledger record, and assurance path matching all see the one served path. */\n private prefixed;\n private prepareRoute;\n /** @internal Symbol-keyed install seam for the `responseContract()` plugin. Off the public typed surface. */\n [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void;\n /** @internal Symbol-keyed install seam for the response observer plugin. */\n [INSTALL_RESPONSE_OBSERVER](runtime: ResponseObserverRuntime): ResponseObserverMethods;\n /** @internal Symbol-keyed install seam for the `idempotency()` plugin. Off the public typed surface. */\n [INSTALL_IDEMPOTENCY](runtime: IdempotencyRuntime): void;\n /** @internal Symbol-keyed install seam for the `mcp()` plugin. Off the public typed surface. */\n [INSTALL_MCP](runtime: McpRuntime): void;\n /** @internal Symbol-keyed install seam for the `notFound()` plugin. Off the public typed surface. */\n [INSTALL_NOT_FOUND](lane: NotFoundLane): void;\n /** @internal Symbol-keyed install seam for the `nodeDirect()` plugin. Off the public typed surface. */\n [INSTALL_NODE_DIRECT](runtime: NodeOutcomeRuntime): void;\n /** @internal An adapter reports a failure no response hook saw (a hook that threw past `fetch`, a\n * response the runtime refused to write), logged as Bun's `listen()` logs one. */\n [REPORT_ERROR](error: unknown): void;\n /** @internal Symbol-keyed install seam for the `streaming()` plugin. Off the public typed surface. */\n [INSTALL_SSE](runtime: SseRuntime): void;\n /** @internal Symbol-keyed install seam for the `websocket()` plugin. Off the public typed surface. */\n [INSTALL_WS](runtime: WsRuntime): void;\n /**\n * @internal The runtime Bun serves this app's WebSocket upgrades with, asked by `listen()` and by a\n * parent that mounts this app: `undefined` while nothing here can take one, `null` when something\n * can but no runtime is at hand. A mounted Nifra app answers through this same seam, so mounting an\n * app without a WebSocket route needs no runtime; a resolver without the seam cannot say, so it\n * counts. `seen` ends a mount cycle (an app mounted under itself to alias a prefix).\n */\n [GET_WS_RUNTIME](seen?: Set<unknown>): WsRuntime | null | undefined;\n /** The `[GET_WS_RUNTIME]` answer for the apps mounted here alone, whatever this app's own routes. */\n private mountedWsRuntime;\n /** Whether an app mounted here takes WebSocket upgrades. Worked out again only after a `ws()` or a\n * `mount()` somewhere, so the upgrade check on a plain request costs one comparison. */\n private mountsTakeUpgrades;\n /**\n * Merge another server's routes into this one - the composition escape hatch for large apps.\n *\n * WHY: the fluent chain accumulates one type-alias level per route, and TypeScript resolves\n * that stack in one recursion - a single chain hits TS2589 at ~95 routes. Groups keep every\n * chain short: build each domain (`listings`, `agents`, …) as its own `server()` (its registry\n * resolves independently), then `app.merge(listings).merge(agents)` - each merge adds ONE level\n * regardless of group size. 300+ routes stay fully typed (see many-routes.test-d.ts). The\n * other escape hatch is contract-first `implement()`, whose registry is a single object type.\n *\n * Semantics: merged routes keep the chains captured where they were DEFINED - the group's\n * `derive`/`decorate`/`beforeHandle`/`afterHandle`/`onError`/`around` apply to its routes\n * exactly as they did standalone, so a group wires its own plugins. The same locality rule\n * covers the group's `onRequest` hooks: they run only for requests that route to the GROUP's\n * routes, and for an `OPTIONS` preflight to a path they serve (a `bodyLimit()` mounted on an uploads group must not start gating the whole app\n * because the app composed it in), and the group's global assurance follows its hooks onto\n * exactly those routes. A group with hooks but NO routes is a middleware bundle - its hooks\n * can only mean app-wide intent, so they are appended globally, unchanged. Response-side hooks\n * (`onResponse`/`onResponseFinalized`) are appended to this server's. This server's\n * route-scoped chains do NOT retroactively wrap merged routes (order-scoped, like routes\n * registered before a `derive`). Fail closed: a path+method collision throws\n * `RouteConfigError` at merge time, and a group with WebSocket routes or mounts is refused\n * (register those on the parent).\n *\n * What this server's `.use()`, made BEFORE the merge, covers on a merged route versus a\n * `group()` route:\n *\n * | installed on this server | group() route | merge()d route |\n * | ------------------------------------------ | ------------- | ------------------------------ |\n * | derive/decorate/beforeHandle/afterHandle, | yes | no - wire it on the merged |\n * | onError/around, authenticate, route-scoped | | server |\n * | assurance | | |\n * | onRequest/onResponse/responseHeaders hooks | yes | yes (app-wide) |\n * | responseContract() | yes | yes, when the route declares a |\n * | | | response and its own server |\n * | | | installed no contract |\n * | effectLedger() | yes | yes, when the route declares |\n * | | | capabilities and has no ledger |\n * | idempotency() | yes | the merged server's own; a |\n * | | | route declaring it without one |\n * | | | is refused at registration |\n *\n * The response contract and the ledger can only add a check or a record, so a merged route is\n * recompiled under them. A runtime installed AFTER the merge covers neither kind of route.\n *\n * In development, {@link ServerOptions.unusedScopedHooks} reports a hook followed only by merges and\n * a contract or ledger installed after the routes it would cover; `nifra check` reports a merge whose\n * server authenticates none of its routes under this server's `authenticate()` (NF-C043).\n */\n merge<R2 extends Registry, Ctx2, HookOutput2>(other: Server<R2, Ctx2, HookOutput2>): Server<R & R2, Ctx, HookOutput>;\n /**\n * Declare routes under a static path prefix, with the prefix in the typed client, `routes()`,\n * OpenAPI, capability events, and the effect ledger - the counterpart of Hono's `route()`,\n * Elysia's `group()`, and Fastify's `register({ prefix })`.\n *\n * app\n * .derive(session)\n * .group(\"/admin\", (admin) =>\n * admin.beforeHandle(requireAdmin).get(\"/users\", listUsers).get(\"/users/:id\", getUser),\n * )\n * .get(\"/\", home) // not covered by requireAdmin\n *\n * The builder receives a scope that INHERITS this server's route chain as it stands at the call\n * (`derive`/`decorate`/`authenticate`/`beforeHandle`/`afterHandle`/`onError`/`around`, assurance,\n * capability interceptors, installed runtimes, applied plugins), exactly as a route declared here\n * would. {@link merge} documents how that differs for a merged server. A plugin this server already applied is in effect for the group: the group's `use()` of\n * that same instance does nothing, and its `use()` of another instance under the same name throws a\n * `RouteConfigError` (`PLUGIN_RECONFIGURED`), because that instance could never replace the parent's.\n * A plugin the group applies still shares the parent's copy of a dependency it `use()`s itself.\n * What it adds stays in the group: its chain additions apply only to its own routes, and its\n * request/response hooks (`onRequest`, `onResponse`, `responseHeaders`, `onResponseFinalized`, and\n * middleware bundles that use them) run only for requests whose path is the prefix or below it.\n * Per-route authorization belongs in `authenticate`/`beforeHandle`, which are compiled into each\n * route; request hooks are path prefilters.\n *\n * The prefix is static text - `\"/api\"`, `\"/api/v1\"` - validated when declared: no params,\n * wildcards, empty or dot segments, percent-escapes, or trailing slash. A group's `\"/\"` route\n * serves the prefix itself. Groups nest (`\"/api\"` then `\"/v1\"` serves `/api/v1/...`).\n *\n * Fail closed: the builder must synchronously return the scope it was given; a collision with an\n * existing route throws `RouteConfigError` and adds none of the group's routes; `.ws()`, mounts,\n * MCP `.tool()`s, and `merge()` inside a group are refused (register them on the parent). Once the\n * builder returns, the scope is closed - a leaked reference cannot add routes later.\n */\n group<const P extends string, R2 extends Registry, Ctx2, HookOutput2>(prefix: P, build: (group: Server<EmptyRegistry, Ctx, HookOutput>) => Server<R2, Ctx2, HookOutput2>): Server<R & PrefixRegistry<P, R2>, Ctx, HookOutput>;\n /**\n * Take over another server's routes and hooks - the shared core of {@link merge} and {@link group}.\n * `prefix` selects group semantics: hooks are scoped to requests under the prefix (response hooks\n * included), and the source's global assurance past `inheritedGlobal` (what it copied from this\n * server) is folded into its routes. Without a prefix, merge semantics: request hooks are scoped to\n * the source's routes when it has any, response hooks are appended app-wide.\n */\n private adopt;\n /** A fused renderer closes over runtime services to keep its seven-argument JSC fast path. Merging\n * rebinds that closure once to the executing server; generic plans already receive the runtime. */\n private bindFusedRuntime;\n /**\n * Enumerate the registered routes (method, path, input schemas), in registration\n * order. Powers `toOpenAPI` and other introspection; the router trie itself no\n * longer holds the original patterns.\n */\n routes(): ReadonlyArray<RouteDescriptor>;\n /**\n * Resolve a `Request` to a `Response` - the whole lifecycle, testable without a port. The\n * optional `platform` carries edge inputs (`env`, `waitUntil`); edge adapters pass it, and\n * Bun/Node/Deno omit it (then `c.env` is `undefined` and `c.waitUntil` runs fire-and-forget).\n */\n fetch(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<Response>;\n private fetchSource;\n private fetchSourceInner;\n /** Web response path when Bun already matched the route. The lifecycle and response hooks remain\n * exactly the same as {@link fetchSource}; only portable URL scanning + trie lookup are skipped. */\n private fetchMatched;\n private fetchMatchedInner;\n /**\n * Run `produce` under the capacity gate: admit → run → release exactly once when the response is\n * produced (or the run throws). Only reached when {@link capacityGate} is set, so the off path pays\n * nothing. The slot is held for the duration of handler execution, not the streaming of the body -\n * capacity here bounds concurrent *work*, matching how in-flight is counted.\n */\n private admitGated;\n private runAdmitted;\n /**\n * Select a mounted handler's native Node lane without materializing a Web Request. This is an\n * adapter seam, not a second lifecycle: any app-wide behavior that the ordinary mount path would\n * run makes the capability ineligible and the caller falls back to `resolveNodeSource`. Typed\n * routes keep precedence exactly as `routeAndRun` does, including the existing mount behavior for\n * a path whose registered route rejects this method.\n */\n [RESOLVE_NODE_MOUNT](source: RequestSource): NativeMountSelection | undefined;\n private firstMountUnder;\n /**\n * Like {@link fetch}, but renders a plain-data result **without** building a Web `Response` - the\n * `@nifrajs/node` adapter serializes the returned primitives straight to the socket, skipping the undici\n * `Response` build + body drain (the bulk of the Node bridge cost, measured ≈4µs/req). A handler that\n * returns a `Response`, an error/short-circuit, or a response hook that replaces/consumes the buffered\n * body stays on the full Web path; an in-place response hook can still use the direct writer. Same\n * lifecycle as {@link fetch} (body cap, validation, hooks all run); only the final render differs.\n */\n resolveNode(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<NodeServeOutcome>;\n resolveNodeSource(source: RequestSource, platform?: Platform<EnvOf<Ctx>>, suppliedRuntime?: NodeOutcomeRuntime): MaybePromise<NodeServeOutcome>;\n /** Run generic Web response middleware while retaining direct writes for untouched buffered bodies. */\n private finishNodeWebResponse;\n /** True only when every transforming Web response hook has a header-only Node equivalent. */\n private canUseNodeResponseHooks;\n /** Apply paired native hooks to data outcomes; preserve the complete Web hook pipeline for Response outcomes. */\n private finishNodeResponse;\n private withNodeResponseHeaders;\n /** Synchronous until a native response hook actually returns a Promise. */\n private applyNodeResponseHooks;\n private continueNodeResponseHooks;\n /**\n * Resolve a WebSocket upgrade - the seam every serving adapter uses. Returns `pass` (not a WS\n * upgrade for a registered route → handle as normal HTTP), `reject` (a WS route matched but\n * `upgrade()` rejected, or the path was malformed → return `response`), or `upgrade` (perform the\n * runtime upgrade, then dispatch the native socket's events to `handler`, seeding `ws.data` with\n * `data`). Runs the route's `upgrade(c)` guard in a real request context. Synchronous unless\n * `upgrade()` is async; a throw rejects with a flat 500 (no detail leaked).\n */\n private runWebSocketRequestHooks;\n private continueWebSocketRequestHooks;\n resolveWebSocketUpgrade(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<WebSocketUpgradeOutcome>;\n /** Bun `fetch` when WS routes exist: try a WS upgrade first, else run the normal HTTP lifecycle.\n * `undefined` ⇒ Bun owns the upgraded socket; a `Response` ⇒ a normal reply or a rejected upgrade.\n * (The socket dispatch itself lives in `ws-bun.ts`, loaded via `@nifrajs/core/ws`.) */\n private bunFetchWithWebSocket;\n /**\n * The shared lifecycle, generic over how the final value is rendered: `finalize` turns a handler's\n * result + `set` into the output `T` (`toResponse` → a Web `Response`; `toNodeOutcome` → node-direct\n * primitives), `wrapResponse` lifts an early/error `Response` into that same `T`, and `onTimeout`\n * produces the 503. The Web `fetch` and `resolveNode` are thin callers over this one routing +\n * context + lifecycle implementation - no duplication across the trust boundary.\n */\n /** Apply the `clientIp` trust declaration to the adapter's raw socket peer, returning a platform\n * whose `clientIp` is the derived caller. Only called when a trust declaration is configured. */\n private deriveClientIp;\n private trustedPlatform;\n private dispatch;\n /** Node-native request hook walk. A header-only hook can inspect the lazy source without forcing a\n * Web `Request`; arbitrary request rewrites and full Web hooks use {@link runWithOnRequest}. */\n private runWithNodeRequest;\n private continueNodeRequest;\n private canUseNodeRequestHooks;\n /**\n * onRequest short-circuit path. Synchronous as long as every hook returns synchronously (the\n * common case - e.g. CORS returning `undefined` for a non-preflight request): an `async` version\n * here put EVERY request of any app with one onRequest hook onto the promise machinery, profiled\n * at ~13% of a realistic request. The first hook that returns a Promise hands the REMAINING\n * hooks to the async continuation; behavior is identical.\n */\n private runWithOnRequest;\n /** Async tail of {@link runWithOnRequest}: applies the first awaited hook's outcome, then runs\n * the remaining hooks (awaiting freely - we're already async here). */\n private continueOnRequest;\n private takeResponseRequest;\n /**\n * The NodeRequestContext for a source, MEMOIZED per source so the request twins and the response\n * twins receive the exact same object within one request - that identity is the documented\n * contract stateful twins key their WeakMaps on. An adapter source (which already speaks the\n * interface) is returned as-is; a plain `Request` source (a direct `resolveNode` caller) gets one\n * cached wrapper.\n */\n private nodeRequestContextOf;\n /** Preserve the request visible to generic onRequest hooks for paired native response hooks. */\n private takeNodeResponseRequest;\n /**\n * Route → build context → run. Synchronous through to the handler for a **bare** route\n * (selected by its compiled plan), so a sync handler produces its result with zero promise allocations;\n * routes with validation/hooks keep the full compiled route program, unchanged.\n */\n private routeAndRun;\n private fetchMount;\n /** Run a route that has already been matched by the runtime or Nifra's portable router. */\n private runMatched;\n /** Supply request-specific deadline state to the route's precompiled execution plan. */\n private runMatchedLanes;\n /** @internal Symbol-keyed install seam for the `effectLedger()` plugin. Off the public typed surface. */\n [INSTALL_EFFECT_LEDGER](runtime: EffectLedgerRuntime): void;\n /** The narrowest bare route: a syntactic `() => ...` handler cannot observe the context argument, so\n * successful requests can skip allocating `RequestContext`. Errors still allocate one for logging. */\n private runContextlessBare;\n private contextlessBareError;\n /**\n * The synchronous fast path selected by a route's execution plan: apply static decorations, call the\n * handler, render the result - **no `await`** unless the handler itself returns a promise. It mirrors\n * the same error boundary as the compiled route program (which a bare route would otherwise no-op through) and shares\n * {@link logRequestError}; a bare route has no `onError` hooks, so error handling is fully synchronous\n * (a thrown `Response` is control flow; anything else is a logged flat 500). This is where nifra skips\n * the per-request async-frame tax - the same win codegen routers get, but without `eval`.\n */\n private runBare;\n /** Bare-route error rendering - identical to the compiled route program's catch minus the (absent) onError\n * loop: a thrown `Response` is returned as deliberate control flow; anything else is logged + 500. */\n /**\n * Build a route's fused Web renderer. Composition happens once at\n * registration; the returned closure is what every request to the route runs. Behavior is\n * byte-identical to the generic `runBare`/`runContextlessBare` + `toResponse` pair - same\n * decoration order, same error routing (thrown `Response` = control flow; anything else logs and\n * 500s), same respond semantics (the lifecycle parity suite pins it).\n */\n private buildFusedWeb;\n /** A fused Web lane's render in an async continuation, where a result that cannot be rendered\n * must fail like a handler throw; a synchronous render throw reaches {@link runMatchedLanes}. */\n private respondFused;\n /** Compile the eligible body-only route's parser → validator → handler continuation once. The\n * bounded parser remains shared with the generic lane; only the route-invariant entry lookups and\n * lifecycle dispatch disappear from the common synchronous-validator/synchronous-handler case. */\n private buildFusedBodyRunner;\n /** Web adapter wrapper for the shared body runner. Node passes its native finalizer directly through\n * the execution plan, while Web needs the live context to preserve lazy `c.set` controls. */\n private buildFusedBodyWeb;\n /** The fused Web lane for a route whose only lifecycle step is a query schema: parse + validate +\n * handler + respond in one closure, no lifecycle promise when the validator and handler are sync.\n * Eligibility is decided at registration (see `fusedQuery` in {@link register}); the semantics here\n * are exactly `runQueryOnly`'s for that eligible shape - invalid input returns\n * `validationError(issues)` (recovery hooks disqualify the route from this lane), a thrown\n * `Response` passes through, anything else logs and returns a flat 500, and an async validator\n * falls to a then-chain with the same steps. */\n private buildFusedQueryWeb;\n /**\n * Compile a route's `derive + before` lifecycle to a single closure: the per-request walk through\n * `runSync` → `runHooksSync` is a stack of 3 frames and 2 `Object.assign`s for what is by far the\n * most common middleware shape (auth/trace/id derivation, an auth/policy `beforeHandle`). Folding\n * the same steps into one closure hits the same monomorphic inline-cache site as `buildFusedWeb`,\n * and `Object.assign(ctx, deriveResult)` becomes one extra property write on the context's already\n * hot hidden class. Behavior is byte-identical to the compiled route program: the same thrown-value\n * contract (`Response` is control flow, anything else logs + 500), the same `c.set` semantics, the\n * same `fusedRespond` for the rendered body. The `LifecycleExecutionLane` guarantee\n * (`schema.params === undefined && schema.headers === undefined && derives === 1 &&\n * beforeHandle === 1 && afterHandle === 0 && onError === 0 && !hasResponseContract &&\n * !hasDecorations`) is enforced by `selectRouteLanes`; this lane is selected ONLY when all of those\n * hold. A `query` schema (the route declares `{ query }` alongside the hooks) is validated FIRST,\n * mirroring the compiled route program's stage order; the fused builder runs validate → derive →\n * before → handler in one frame.\n */\n private buildFusedDeriveBefore;\n private buildFusedDeriveBeforeAfter;\n /**\n * Body + lifecycle hooks fused: parse → validate → derive → before → handler → (after) in one\n * closure, the same win `buildFusedBodyRunner` gives for the no-hooks body shape. The shape is\n * `lifecycleHookLane` PLUS a body schema with no other validation conflicts; the lane is selected\n * ONLY when `schema.body !== undefined && schema.query/params/headers === undefined &&\n * schema.onValidationError === undefined && !defaultOnValidationError && !hasIdempotency &&\n * !hasLedger && derives === 1 && beforeHandle === 1 && afterHandle <= 1 && onError === 0 &&\n * !hasResponseContract && !hasDecorations && around === 0`. The same single `querySchema === undefined`\n * trick used in the no-body lane lets the build path stay simple: a query + body route falls back\n * to the generic program (this is rare in practice - validated query + validated body is usually a\n * \"search results\" route with a middleware chain on top, and the generic lane is fine there).\n */\n private buildFusedBodyDeriveBeforeAfter;\n /**\n * Generic (finalize/wrapResponse-parameterized) fused runner for the derive-before(-after) lane:\n * the Node-direct counterpart of `buildFusedDeriveBefore` / `buildFusedDeriveBeforeAfter`.\n *\n * The Web fused builders above return a `Response`, so the Node dispatcher (`webFast === false`)\n * cannot use them and a derive+before route falls back to the generic route program there - two\n * staged loops, per-stage dispatch, and the async-continuation machinery - while Bun rides the\n * single closure. That asymmetry is the realistic-route Node deficit against Fastify: this runner\n * closes it by running validate → derive → before → handler → (after) in one frame and finalizing\n * through the caller's own `finalize` (the Node outcome on the direct lane, `toResponse` on Web),\n * so the same registration feeds both runtimes with no per-lane copy of the lifecycle to drift.\n *\n * Semantics mirror the generic program stage-for-stage for the shapes this lane admits (exactly\n * one derive, one beforeHandle, zero-or-one afterHandle, no onError/around/decorations/contracts/\n * recovery hooks - enforced by `selectRouteLanes`): thrown `Response`/`status(...)` are control\n * flow through `wrapResponse`/`finalize`, anything else logs + 500s via the shared `bareError`\n * lane (identical to `handleLifecycleError` with no `onError` hooks), and a terminal `finalize`\n * throw (e.g. an unstringifiable handler return on the Node lane) is caught exactly as\n * `finishLifecycleContract` catches it. Step functions close over registration state only and take\n * the request state as arguments, so the hot path allocates no per-request closures.\n */\n private buildFusedDeriveBeforeRunner;\n /**\n * Generic fused runner for the body+derive-before(-after) lane: the Node-direct counterpart of\n * `buildFusedBodyDeriveBeforeAfter`. Same contract as `buildFusedDeriveBeforeRunner` above - one\n * frame running parse → validate → derive → before → handler → (after) through the caller's own\n * `finalize` - with the body read ahead of validation, exactly as the generic program orders its\n * body stage before the derive/before stages. `readBodyFramed` keeps the shared bounded-read,\n * content-type, and prototype-poisoning contracts; the 415/400 renders take `wrapResponse`\n * directly, which is what the generic lane's wrap-after-identity amounts to.\n */\n private buildFusedBodyDeriveBeforeAfterRunner;\n private bareError;\n /**\n * Keep the ordinary thrown-error response independent from the caught value. Deliberate Response\n * control flow is handled by `renderBareError`; every other throw gets this fixed public envelope.\n */\n private internalErrorResponse;\n private runWithAround;\n /** Execute the registration-compiled general stage program. */\n private runProgram;\n /** Bind a compiled validation stage to its stable schema and the existing recovery contract. */\n private validateProgramStage;\n /** Preserve the existing bounded body reader and its fail-closed framing/prototype checks. */\n private readProgramBody;\n /** Keep thrown Response/status and redacted 500 semantics in one existing error boundary. */\n private handleProgramError;\n /** Finish a successful program result through response-contract enforcement and finalization. */\n private finishProgramResult;\n private runAround;\n private runBodyOnly;\n /** Validate + run the handler for the bodyOnly path - shared by the inline fast path and the\n * streaming fallback. A method (not per-request closures) so the hot path allocates nothing\n * beyond the one `.then` continuation. */\n private finishBodyOnly;\n private executeHandler;\n private handleValidationErrorRecovery;\n private applyBodyValidation;\n private runQueryOnly;\n /** Validate-result → set `ctx.query` → run handler. A method (not a per-request closure), the\n * query analogue of {@link applyBodyValidation}. */\n private applyQueryValidation;\n /**\n * Thread the response through each global `onResponse` hook. Stays SYNCHRONOUS until a hook\n * actually returns a Promise - an `async` version forced a promise + microtask on EVERY response\n * of any app with an onResponse hook (cors/securityHeaders/etag/timing all use onResponse), the\n * same ~13%/req tax the onRequest walk was de-async'd to avoid. The first async hook hands the\n * rest to {@link continueOnResponse}.\n */\n private applyOnResponse;\n private applyOnResponseAndFinalize;\n private completeResponseFinalization;\n private failResponseFinalization;\n /** Notify terminal observers in order while isolating both sync and async failures. */\n private notifyResponseFinalized;\n /** Async tail of {@link applyOnResponse}: runs the remaining hooks once one has gone async. */\n private continueOnResponse;\n /**\n * Bound the response time. On timeout we abort `ctx.signal` (so cancellation-aware\n * handlers can bail) and return 503; the in-flight work keeps running but its\n * result is discarded - JS can't forcibly cancel a promise.\n */\n private withTimeout;\n private finishLifecycleContract;\n private finishContractOutcome;\n /** Synchronous by design, and `MaybePromise` rather than `Promise` for the same reason: control flow\n * out of a lifecycle stage must not cost a promise. An `async` method allocates one and defers the\n * result a microtask even when every branch it takes returns immediately, which is the common case\n * here - a thrown `status(...)`/`Response`, or a route with no `onError` hook at all. Only the hook\n * loop, which may await, drops into {@link runErrorHooks}. */\n private handleLifecycleError;\n /** An `onRequest` hook threw or rejected. No route has matched, so every `onError` the app holds\n * answers it, with a route-less context; otherwise the logged default 500, as for a handler. */\n private onRequestFailure;\n /** The `onError` chain, split off {@link handleLifecycleError} so its `await` costs only the routes\n * that registered a hook. A hook may return a custom response; otherwise the default 500 stands.\n * Never rejects: nothing outside it re-enters `onError`, so a hook that throws, or an answer that\n * cannot be rendered, is logged and answered here. */\n private runErrorHooks;\n /** Log an unhandled request error to the (redacting) logger - shared by the compiled route program and the\n * bare fast path ({@link bareError}) so both record the same fields. Never throws; never leaks. */\n private logRequestError;\n private readAndValidateBody;\n /** Apply validation and its recovery hook on the generic lifecycle lane. Recovery is completed\n * before derives/beforeHandle run, matching the body-only and query-only execution lanes. */\n private applyLifecycleValidation;\n private finishLifecycleValidationRecovery;\n /** Adapt one route's compiled execution plan to Bun's already-matched request shape. Route\n * semantics remain in the plan; this closure only supplies native params and deadline fallback. */\n private compileBunNativeHandler;\n /** Compile portable route registrations into Bun's native route table. Apps with request-rewrite\n * hooks or WebSockets retain the single portable dispatcher because those features must run before\n * route selection/upgrade.\n *\n * Bun and the portable router agree on which of two static-and-`:param` paths wins a request, so\n * the table is kept to those paths. Where Bun would otherwise pass a request on to a less specific\n * path, the more specific one carries `fallback`, the portable dispatcher, under that method.\n * `peer` is the platform every request served from the table shares. */\n private buildBunNativeRoutes;\n /**\n * Start a `Bun.serve` instance bound to `port` (use `0` for an ephemeral port).\n *\n * `reusePort` sets `SO_REUSEPORT` so **multiple processes can bind the same port** and the kernel\n * load-balances connections across them - the standard way to use every core (Bun is\n * single-threaded per process). Spawn one process per core, each calling\n * `app.listen(PORT, { reusePort: true })`; see `examples/cluster.ts`. Every process must opt in,\n * and all of them must be the same app. Linux balances ~evenly; macOS accepts the flag but may\n * favor one socket (fine for dev, measure on Linux for production numbers).\n *\n * `hostname` is the bind address, defaulting to Bun's `0.0.0.0` (every interface). Pass\n * `\"127.0.0.1\"` to bind loopback only - an admin surface, a sidecar, or anything that must not be\n * reachable off the box. Omitting it when you meant to restrict is a real exposure, so it is a\n * first-class option rather than something a caller has to drop down to `Bun.serve` for.\n *\n * `idleTimeoutSec` is how long Bun tolerates a connection with no bytes moving before it closes\n * the socket. Bun's default is **10 seconds**, and a request whose handler is still working sends\n * nothing - so any endpoint slower than 10s (a render, an export, a long upstream call) has its\n * connection cut mid-flight regardless of `requestTimeoutMs`. Apps with such endpoints must raise\n * this above their slowest expected response, which is why it is a first-class option and not a\n * reason to drop down to `Bun.serve`. `0` disables the timeout entirely; max 255.\n *\n * `tls` serves HTTPS directly: `app.listen(443, { tls: { cert, key } })` with PEM text or bytes.\n * Requests then arrive with `https:` URLs. Behind a proxy or a platform that terminates TLS, leave\n * it unset.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n readonly idleTimeoutSec?: number;\n readonly tls?: ListenTlsOptions;\n }): RunningServer;\n /**\n * Gracefully stop: wait for in-flight requests to finish (up to `drainMs`), then\n * issue a single terminal stop - graceful if everything drained, forced if\n * stragglers remain. Safe to call when not listening.\n *\n * The Bun semantics: poll `pendingRequests` (awaiting\n * `stop()`'s promise drops in-flight requests), and decide graceful-vs-forced in\n * ONE call (Bun can't escalate an already-graceful `stop()` to a forced close).\n * New connections may be accepted during the drain window; in a real deploy the\n * load balancer has already stopped routing here, and `drainMs` bounds it. Open WebSockets\n * get a 1001 close at once and the same window to finish it, before any `onStop` hook runs.\n */\n stop({ drainMs }?: {\n drainMs?: number;\n }): Promise<void>;\n private installSignalHandlers;\n}",
|
|
14091
14164
|
"doc": "/**\n * The inline server. Routes are chainable and fully type-inferred. `derive`/\n * `decorate` extend the handler context (`Ctx`) for routes defined *after* them,\n * with full types; `Ctx` is server-only and never touches the client registry.\n *\n * app.decorate(\"db\", db).derive((c) => ({ user: auth(c) }))\n * .get(\"/me\", (c) => c.user) // c.user + c.db are typed\n */"
|
|
14092
14165
|
},
|
|
14093
14166
|
{
|
|
14094
14167
|
"name": "Server",
|
|
14095
14168
|
"kind": "class",
|
|
14096
14169
|
"package": "nifra",
|
|
14097
|
-
"signature": "export declare class Server<R extends Registry = EmptyRegistry, Ctx = EmptyContext, HookOutput = never> {\n /**\n * Which copy of `@nifrajs/core` declared this type. Two copies in one build (a linked sibling repo,\n * a hoisting split) produce two unrelated `Server` types whose assignment error is a wall of\n * missing internals; the brand puts the feature version in the type itself, so `typeof app` on\n * hover - and `NifraFeatureVersion` in an assertion - says which core an app is talking to.\n * `nifra doctor` is the diagnosis that names both install paths.\n *\n * `declare` = type-only: no field is emitted, nothing is allocated per server.\n */\n readonly __nifraCoreVersion: NifraFeatureVersion;\n private readonly catalog;\n /** WebSocket routes, matched separately at upgrade time (a GET + `Upgrade: websocket`). */\n private readonly wsRouter;\n /** Each socket path, its declared capabilities, the evidence declarations its handshake captured\n * and the chain it runs; reflection reads it. */\n private readonly wsRoutes;\n /** `wsChanges` when `wsMountsLive` was last worked out; -1 until then. */\n private wsMountsCheckedAt;\n /** Whether an app mounted here takes WebSocket upgrades, as of `wsMountsCheckedAt`. */\n private wsMountsLive;\n /** In-process pub/sub backing `ws.subscribe(topic)` + `app.publish(topic, data)` (single-instance).\n * Created by the first `app.ws()` via the `@nifrajs/core/ws` runtime - `undefined` until then, so a\n * no-WebSocket app never constructs (or bundles) it. */\n private topics;\n /** True once any `app.ws()` route sets `validateSend: true` - the one case where a broadcast frame\n * is validated (and possibly dropped) per socket, so `app.publish` must stay on the JS registry loop\n * rather than delegate to Bun's native `server.publish`. */\n private wsHasValidatedSend;\n /** Bun's native topic broadcast, bound by `listen()` in native-pubsub mode; `app.publish` uses it\n * instead of the JS registry. `undefined` off Bun, before `listen()`, with a validated-send route,\n * or when a mounted app takes upgrades. */\n private nativePublish;\n private readonly maxBodyBytes;\n private readonly protoPoisoning;\n private readonly formOrigins;\n /** `trustBodyFraming`: mark every `app.fetch` request as runtime-framed (see ServerOptions). */\n private readonly trustBodyFraming;\n private readonly wsMaxPayloadBytes;\n private readonly requestTimeoutMs;\n private readonly wsUpgradeTimeoutMs;\n /** Installed by the `responseContract()` plugin; `undefined` = not installed, which is the default\n * and the state in which a declared `response` schema stays a compile-time contract only. */\n private responseContractRuntime;\n /** Opt-in caller-IP trust declaration; `undefined` = socket peer only, no forwarded header believed. */\n private readonly clientIpTrust;\n private readonly acceptInboundDeadlines;\n private readonly maxInboundDeadlineMs;\n private readonly deadlineAdmissionOptions;\n private readonly gracefulSignals;\n private readonly stopHooks;\n private readonly fetchMounts;\n private mountOrder;\n /** Number of composed mounts that must run before the parent route table. Keeps legacy mounts off the hot path. */\n private preRouteMountCount;\n /** Capacity-admission gate; `undefined` = off (the request path pays nothing). */\n private readonly capacityGate;\n private readonly onCapabilityUse;\n private readonly capabilityInterceptors;\n private readonly capabilityObservers;\n /** The installed effect-ledger runtime (owns the sink + per-route resolution + settle), or\n * `undefined` when the effect-ledger plugin is not installed. */\n private effectLedgerRuntime;\n /** The installed idempotency runtime (owns the app-wide default store + the dedupe lane), or\n * `undefined` when the idempotency plugin is not installed. */\n private idempotencyRuntime;\n /** Installed opt-in runtime for `.tool()`/`.resource()`/`.prompt()`; `undefined` until `.use(mcp())`. */\n private mcpRuntime;\n /** Installed answer for a request no route matched; `undefined` (the plain 404) until `.use(notFound())`. */\n private notFoundLane;\n /** Installed Node-direct renderer for direct `resolveNode()` callers; `undefined` until `.use(nodeDirect())`. */\n private nodeOutcomeRuntime;\n /** Installed streaming runtime for `.sse()` routes; `undefined` until `.use(streaming())`. */\n private sseRuntime;\n /** Installed WebSocket runtime for `.ws()` routes; `undefined` until `.use(websocket())`. */\n private wsRuntime;\n private readonly logger;\n /** How much of an unhandled error {@link logRequestError} records. See `ServerOptions.errorLogDetail`. */\n private readonly errorLogDetail;\n /** App-wide validation-error fallback; a route's own `schema.onValidationError` takes precedence. */\n private readonly defaultOnValidationError?;\n private bunServer;\n private sealed;\n private readonly derives;\n /** Dedicated authentication stages captured by subsequent routes. */\n private readonly authStages;\n private readonly decorations;\n private readonly beforeHandleHooks;\n private readonly afterHandleHooks;\n private readonly onErrorHooks;\n private readonly aroundHooks;\n private readonly onRequestHooks;\n private readonly onNodeRequestHooks;\n /** Registration-time eligibility for the Node request twin lane. */\n private nodeRequestHooksComplete;\n /** True when every request hook is safe to skip on a Bun native route. */\n private bunNativeRequestHooksSafe;\n private readonly onResponseHooks;\n private readonly onNodeResponseHooks;\n /** Registration-time eligibility for the Node response twin lane. */\n private nodeResponseHooksComplete;\n /** True when every response hook only mutates headers and can run after a Bun fused response. */\n private bunNativeResponseHeadersOnly;\n /**\n * True once a bundle registers a RAW `onNodeResponse` twin - one handed the outcome's header\n * record itself rather than the case-normalizing view. Their names are contractually the wire\n * spelling, but registration cannot PROVE it, so such an app forgoes the all-lowercase mark and\n * every reader re-derives the answer, exactly as before the mark existed.\n */\n private hasRawNodeResponseHook;\n private readonly onResponseFinalizedHooks;\n /**\n * Statically declared response headers, merged and prebuilt at registration; `undefined` (the\n * default) leaves every render path in its original shape. These are NOT response hooks - they are\n * folded into response construction - so declaring them keeps the fused native lanes an\n * `onResponse` hook would have disabled.\n */\n private staticResponseHeaders;\n /** A group's view of the static headers its enclosing scopes declared before it was created. */\n private inheritedStatics;\n /** A group's view of the plugins its enclosing scopes applied before it was created; unset while\n * a plugin applies, so its own dependency `use()` shares the parent's copy. */\n private inheritedPlugins;\n /** `wrapResponse` for the Web lanes: identity until static headers exist to fold into the\n * framework's own error/404/timeout renders, which are built outside the header init. */\n private wrapWebResponse;\n private webResponseTimeout;\n /** Body/raw response hooks need a framework-payload marker; keep that decision per app. */\n private responseBodyTag;\n private readonly responseBodyOwners;\n private readonly finalizeResponse;\n private readonly responseRequests;\n /** A request the WebSocket handshake check ran the onRequest hooks on and then passed to HTTP →\n * what the hooks returned, so `fetch` routes that instead of running the hooks a second time. */\n private wsHookedPasses;\n /** Original source → request observed by generic request hooks, including in-place mutations. */\n private readonly responseSources;\n /** Memoized NodeRequestContext per plain-`Request` source - see {@link nodeRequestContextOf}. */\n private readonly nodeContexts;\n /** Plugins/middleware already applied via `use`, by name - for idempotent dedupe. */\n private readonly appliedPlugins;\n /** Order-scoped evidence captured by routes registered after an assured plugin. */\n private readonly activeAssurance;\n /** App-wide evidence from global hooks; applies retroactively to every route. */\n private readonly globalAssurance;\n /** App-declared MCP resources / prompts (via {@link resource} / {@link prompt}), read by `nifra mcp`. */\n private readonly mcpResourceList;\n private readonly mcpPromptList;\n /** Kept so a {@link group} scope is built with exactly this server's settings: fused lanes read\n * several of them at request time, so a group route must never run under different ones. */\n private readonly options;\n /** Static prefix joined onto every route this server registers; non-empty only on a group scope. */\n private routePrefix;\n constructor(options?: ServerOptions);\n private assertConfigurable;\n /** Register a callback awaited after graceful drain and server stop. Hung callbacks are bounded. */\n onStop(fn: StopHook): this;\n /**\n * Mount a legacy fetch handler under a literal path prefix. Mounted handlers sit behind typed\n * routes, so routes can move one at a time while the remaining legacy surface stays live.\n * Mounted responses are outside Nifra's typed route and response-contract checks.\n *\n * It carries HTTP only: a WebSocket upgrade under the prefix reaches the handler as an ordinary\n * request and never becomes a socket. Serve that path's sockets with `app.ws()` routes or a\n * mounted child app, or keep the legacy server running beside this one for them.\n */\n mountFetch(path: string, handler: FetchHandler<EnvOf<Ctx>>, options?: MountFetchOptions): this;\n /**\n * Compose a child fetch app under a literal path prefix.\n *\n * Composed mounts run after the app-global request phase and before the parent's route table. This\n * makes them safe to use in an SSR shell whose `/*` page route would otherwise swallow an API mount.\n * If the child exposes `resolveWebSocketUpgrade`, the same mount also participates in adapter-owned\n * WebSocket upgrades; the serving adapter still upgrades its original socket, while the child sees\n * the mounted request path (stripped when requested).\n *\n * `fallbackOn: 404` is deliberately limited to GET/HEAD/OPTIONS at dispatch time. Those methods are\n * replayable without buffering an untrusted request body; POST/PUT/PATCH and streaming requests\n * never get retried after a child has had a chance to consume them.\n */\n mount(options: MountOptions<EnvOf<Ctx>>): this;\n /**\n * Add a per-request, computed context extension. Order-scoped: it is snapshotted into every route\n * declared *after* this call, and reaches none declared before. One added after the last route\n * (e.g. on the app returned by a route-registering factory) covers nothing - see\n * {@link ServerOptions.unusedScopedHooks}.\n *\n * Returning a `status(...)` (or a `Response`) instead of an extension ends the request there - the\n * guard shape, and the cheap one: it renders as plain data on the same lane a handler's return\n * takes, where `throw new Response(...)` pays ~40% of the rejection lane to build the object. That\n * branch is control flow, so it does not widen the derived context type.\n */\n derive<H extends (context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx & ContextExtensionOf<ReturnType<H>>, HookOutput | StatusResponseOf<Awaited<ReturnType<H>>>>;\n /**\n * Add a static context value. Order-scoped: captured by every route declared *after* this call, and\n * by none before; one added after the last route reaches nothing\n * (see {@link ServerOptions.unusedScopedHooks}).\n */\n /**\n * Register a dedicated authentication stage for subsequent routes.\n *\n * Unlike `derive`, this stage receives a body-blind authentication capsule and is compiled before\n * route validation. Keeping it separate prevents an unrelated derive from accidentally becoming a\n * security gate and lets the route compiler retain a protected fast lane.\n *\n * A stage that throws, or returns anything but `authenticated(principal)` or `rejected(...)`, fails\n * closed with 503 `{ ok: false, error: \"auth_unavailable\" }`. The cause goes where a handler's error\n * goes: to `onError`, whose response replaces the 503, and when no hook answers, to the logger. A\n * thrown `Response` or `status(...)` is sent as thrown, as it is from a handler.\n */\n authenticate<Principal>(stage: AuthenticationStage<Principal, EnvOf<Ctx>>): Server<R, Ctx & {\n readonly principal: Principal;\n }, HookOutput>;\n decorate<const K extends string, V>(key: K, value: V): Server<R, Ctx & Record<K, V>, HookOutput>;\n /**\n * Run before routing on the raw request. Return a `Response` or a `status()` result to\n * short-circuit, or a replacement `Request` to continue routing with a rewritten method/URL/headers.\n * Global.\n */\n onRequest(fn: (req: Request, platform?: Platform<EnvOf<Ctx>>) => MaybePromise<OnRequestResult>): this;\n /**\n * Run after validation, before the handler; a non-`undefined` return short-circuits. Order-scoped:\n * it is snapshotted into every route declared *after* this call and covers none declared before, so\n * one added after the last route reaches nothing (see {@link ServerOptions.unusedScopedHooks}).\n */\n beforeHandle<H extends (context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /**\n * Wrap the matched route lifecycle for subsequent routes. This is intentionally generic over the\n * route output, so wrappers like async context storage do not force Node's direct JSON path through\n * a Web `Response`. The first registered wrapper is outermost.\n *\n * Order-scoped: captured by every route declared *after* this call, none before; one added after the\n * last route reaches nothing (see {@link ServerOptions.unusedScopedHooks}).\n */\n around<H extends (context: Context & Ctx, next: () => MaybePromise<unknown>) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /**\n * Asynchronously admit each subsequent `executeCapability()` call before its owned effect runs.\n * Interceptors receive token-only metadata plus an abort signal and must call `next()` exactly once\n * to admit. Returning without `next()`, timing out, aborting, or throwing fails the effect closed.\n */\n aroundCapability(interceptor: CapabilityInterceptor, options?: AroundCapabilityOptions): this;\n /** Observe token-only admission/execution lifecycle events for subsequent capability routes. */\n observeCapability(observer: EffectLifecycleObserver): this;\n /** Transform the handler's result before it is serialized. Order-scoped: captured by routes declared\n * *after* this call, none before; one added after the last route reaches nothing (see\n * {@link ServerOptions.unusedScopedHooks}). */\n afterHandle<H extends (result: unknown, context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /** Handle a thrown error; a non-`undefined` return becomes the response (else the default 500, or 503\n * `auth_unavailable` for a failed {@link authenticate} stage). Order-scoped: captured by routes\n * declared *after* this call, none before; one added after the last route reaches nothing (see\n * {@link ServerOptions.unusedScopedHooks}). */\n onError<H extends (error: unknown, context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /** Transform every outgoing response - success, error, 404, 405, short-circuit. Global. */\n onResponse(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /**\n * Declare response headers with NO per-request decision behind them - and pay nothing for them on\n * the request path.\n *\n * These are not a hook. Because the values are known at wire-up, they are folded into response\n * construction (one prebuilt init for JSON renders, one record merge where the request set its own\n * headers), so an app whose only response middleware is static keeps every fused and native lane -\n * `onResponse`/`onResponseHeaders` disable Bun's fused native routes and, for a full `onResponse`,\n * the Node direct writer. They apply to EVERY response, exactly as a response hook would: success,\n * error, 404/405, timeout, and short-circuit alike.\n *\n * app.responseHeaders({ \"x-frame-options\": \"DENY\", \"referrer-policy\": \"no-referrer\" })\n *\n * They are DEFAULTS: a value the request itself produced (`c.set.headers`, or a response hook)\n * wins, whatever casing it used. In a group, a name the group declares replaces the value its\n * enclosing scopes declared before the group, on the group's routes. Names are lowercased once here; a non-string value, an invalid\n * name, `__proto__`, or a name the render owns (`content-type`, `content-length`,\n * `transfer-encoding`, `set-cookie`) throws a `TypeError` at wire-up.\n *\n * ORDERING: declarations made before any response hook fold into one static record. One made AFTER\n * a response hook cannot - the hook may already have written that name and must keep winning - so\n * it registers as an ordinary `onResponseHeaders` hook instead, preserving registration order at\n * the cost of the static tier's speed. Declare static headers first.\n */\n responseHeaders(record: Readonly<Record<string, string>>): this;\n /** Wire an already-validated lowercase record into the static tier, or - once a dynamic response\n * hook owns part of the header state - into a hook that runs in the right order. */\n private addStaticResponseHeaders;\n private enableResponseBodyTagging;\n private responseObserverMethods;\n /** Observe the terminal response after all transformations. Observers are ordered and fail-open. */\n onResponseFinalized(fn: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>): this;\n /**\n * Apply `all()` or `method()` from `@nifrajs/core/methods`: one handler registered under several\n * methods, or under a method outside the standard seven. The standard methods join the registry.\n *\n * Declared first on purpose. The plugin's handler is typed against this app's context, which\n * TypeScript reads from the first overload it tries.\n */\n use<M extends string, Path extends string, S extends RouteSchema, Output>(plugin: MethodRoutesPlugin<M, Path, S, Output, Ctx>): Server<WithMethodRoutes<R, M, Path, S, Output, HookOutput>, Ctx, HookOutput>;\n /** Enable the opt-in portable response observer methods. */\n use(plugin: ResponseObserverPlugin): this & ResponseObserverMethods;\n /**\n * Apply a **context** plugin ({@link ContextPlugin}, from {@link defineContextPlugin}) - it adds `D`\n * to the handler context and changes nothing else, so the route registry `R` and the existing context\n * `Ctx` thread through untouched. Like the identity overload above, this exists because the generic\n * `(app: this) => Out` overload below cannot infer through a *generic* plugin signature: it erases the\n * plugin's own type parameters to their constraints, which silently widens `R` to `Registry`.\n */\n use<D extends object>(plugin: ContextPlugin<D>): Server<R, Ctx & D, HookOutput>;\n /**\n * Apply a type-**identity** plugin ({@link IdentityPlugin}, from {@link defineIdentityPlugin}) - it\n * registers routes/hooks but doesn't change the types, so this returns `this` with the route registry\n * and context fully intact. This overload exists specifically so a named identity plugin (e.g.\n * `@nifrajs/better-auth`) threads the registry: its `& { pluginName }` intersection would otherwise\n * defeat the generic inference of the transforming overload below and collapse the result to `any`.\n */\n use<AddedHookOutput = never>(plugin: IdentityPlugin<AddedHookOutput>): Server<R, Ctx, HookOutput | AddedHookOutput>;\n /**\n * Apply a **plugin function** - `(app) => app`, typically built with {@link definePlugin}. It's\n * called with `this` and its result is returned, so an inline plugin's `derive`/`decorate` thread\n * the added context to handlers defined after `use` (the overload is generic over the concrete\n * `this`). A named plugin already applied is skipped (idempotent dedupe), however it was configured,\n * so a plugin meant to stack - a second, stricter guard - needs a name of its own per instance.\n *\n * If the plugin's return type is unpinned - `Server<any, any>`, as a hand-rolled `(app) => app` or a\n * `NifraPlugin<AnyServer, AnyServer>` infers (e.g. an auth plugin whose own types collapsed) - this\n * returns the non-callable {@link PluginTypeCollapsed} instead of silently widening the whole typed\n * client to `any`. `.get()`/`.post()` then fail right here rather than surfacing as `any` hundreds of\n * lines away. Fix at the plugin: build it with {@link defineIdentityPlugin}/{@link defineContextPlugin},\n * or pin its input server type. This mirrors the guard {@link definePlugin} already applies.\n */\n use<Out extends AnyServer>(plugin: (app: this) => Out): [ServerTypeUnpinned<Out>] extends [true] ? PluginTypeCollapsed : Out;\n /**\n * Apply a {@link Middleware} bundle - wire each hook it provides to its lifecycle point. Returns\n * `this` (no context-type merging); call it before the routes its `beforeHandle`/`afterHandle`\n * should cover (those are order-scoped; `onRequest`/`onResponse` are global). A bundle applied after\n * the last route reaches nothing - {@link ServerOptions.unusedScopedHooks} logs that at seal. A named\n * bundle already applied is skipped (idempotent).\n */\n use<M extends Middleware>(mw: M): Server<R, Ctx, HookOutput | MiddlewareOutputOf<M>>;\n use(mw: Middleware): this;\n get<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n get<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Register a **typed SSE route** - an endpoint streaming `text/event-stream` whose event\n * payloads are contracted by `schema.sse`. It is a GET route, or a POST route when the schema\n * declares a `body` (a GET carries none): the body validates as on any POST, and the client sends\n * it with `.subscribe(onEvent, { body })` - the shape of a chat stream that posts its prompt. The handler receives the validated context plus a\n * {@link TypedSSEStream}: `stream.send(event)` is compile-time-checked against the schema and\n * JSON-serialized into the SSE `data:` field. The typed client sees the marker and grows a\n * `.subscribe(onEvent)` for the route with the same payload type - end-to-end typed streaming.\n *\n * import { streaming } from \"@nifrajs/core/sse\" // .use(streaming()) enables .sse()\n * const app = server().use(streaming()).sse(\"/feed\", { sse: t.object({ id: t.integer(), title: t.string() }) },\n * async (c, stream) => {\n * stream.send({ id: 1, title: \"hello\" }) // typed\n * await waitForDisconnect(stream.signal)\n * },\n * { keepAlive: 15_000 })\n *\n * // client: const off = api.feed.subscribe((post) => console.log(post.title))\n *\n * `init` passes through to the underlying {@link sse} helper (`keepAlive`, `maxBufferedBytes`,\n * extra headers). The connection closes when the handler resolves, `stream.close()` runs, or the\n * client disconnects (`stream.signal`). Query/body schemas validate exactly as on any other route.\n */\n sse<Path extends string, S extends RouteSchema & {\n sse: StandardSchemaV1;\n }>(path: Path, schema: S, run: (context: Context<Path, S> & Ctx, stream: TypedSSEStream<InferOutput<S[\"sse\"]>>) => void | Promise<void>, init?: SSEInit): Server<AddRoute<R, SseMethodOf<S>, Path, RouteInfoFor<Path, S, Response, HookOutput>>, Ctx, HookOutput>;\n post<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n post<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n put<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n put<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n patch<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n patch<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n delete<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n delete<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Declare an **MCP tool** an agent can call (via `nifra mcp`, or a mounted MCP endpoint): a typed\n * `POST /_nifra/tool/<name>` route whose `input`/`output` schemas contract the call and surface in\n * `tools/list`. Requires `.use(mcp())` - without it, `.tool()` is a registration error, so an\n * ordinary HTTP app never bundles the MCP wiring. Siblings: {@link resource}, {@link prompt}.\n *\n * import { mcp } from \"@nifrajs/core/mcp\"\n * const app = server().use(mcp()).tool(\n * \"search\",\n * { description: \"Search posts\", input: t.object({ q: t.string() }) },\n * ({ q }) => findPosts(q),\n * )\n */\n tool<Name extends string, S extends {\n description: string;\n input: StandardSchemaV1;\n output?: StandardSchemaV1;\n annotations?: ToolAnnotations;\n }, H extends (input: InferOutput<S[\"input\"]>, ctx: Context & Ctx) => MaybePromise<S[\"output\"] extends StandardSchemaV1 ? InferOutput<S[\"output\"]> : unknown>>(name: Name, config: S, handler: H): Server<AddRoute<R, \"POST\", `/_nifra/tool/${Name}`, RouteInfoFor<`/_nifra/tool/${Name}`, S[\"output\"] extends StandardSchemaV1 ? {\n body: S[\"input\"];\n response: S[\"output\"];\n } : {\n body: S[\"input\"];\n }, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Declare an MCP **resource** - read-only data an agent can fetch through `nifra mcp` (app config, a\n * generated document, …). `read` runs in the app process, so capture whatever app state it needs in the\n * closure. `uri` is the MCP resource identifier (e.g. `\"myapp://config\"`). The sibling of {@link tool}\n * for the resource half of MCP.\n */\n resource(uri: string, config: {\n readonly name: string;\n readonly description?: string;\n readonly mimeType?: string;\n }, read: McpResourceDescriptor[\"read\"]): Server<R, Ctx, HookOutput>;\n /**\n * Declare an MCP **prompt** - a reusable prompt template an agent can fetch through `nifra mcp`.\n * `handler` receives the caller's arguments and returns the rendered messages.\n */\n prompt(name: string, config: {\n readonly description: string;\n readonly arguments?: readonly PromptArgument[];\n }, handler: McpPromptDescriptor[\"handler\"]): Server<R, Ctx, HookOutput>;\n /** The MCP resources declared via {@link resource} - enumerated by `nifra mcp`. */\n mcpResources(): readonly McpResourceDescriptor[];\n /** The MCP prompts declared via {@link prompt} - enumerated by `nifra mcp`. */\n mcpPrompts(): readonly McpPromptDescriptor[];\n /**\n * Register a **WebSocket** route. The connection upgrades on a `GET` to `path` carrying\n * `Upgrade: websocket`. The handshake runs the chain an HTTP `GET` registered here would: the\n * `authenticate()` stages, `derive`s and `beforeHandle`s added before this call, then the optional\n * `handler.upgrade(c)`. Any of them may reject (a `Response`, a `status(...)`, a failed auth stage);\n * `upgrade()` may seed per-connection `ws.data`. To keep a socket public, register it before the\n * guard. WebSockets are served by the\n * adapter (`listen()`, `@nifrajs/node`, `@nifrajs/deno`, `toFetchHandler`) - not by bare `app.fetch`, which\n * has no socket (a WS path through `app.fetch` is a normal HTTP response).\n *\n * The route also enters the type-level registry (under the pseudo-method `\"WS\"`), so the typed\n * client grows a `.ws()` handle for it: `messageSchema` types what the client may `send`,\n * `sendSchema` types the frames it receives. Passing explicit type arguments (`ws<MyData>(…)`)\n * defeats path-literal inference and skips the registry entry - the route still serves, it is just\n * invisible to `client<App>`; prefer typing `data` via `upgrade()`'s return.\n *\n * app.ws(\"/chat\", { open: (ws) => ws.send(\"hi\"), message: (ws, data) => ws.send(data) })\n */\n ws<Data = unknown, Schema extends StandardSchemaV1 | undefined = undefined, Send extends StandardSchemaV1 | undefined = undefined, Path extends string = string>(path: Path, handler: WebSocketHandler<Data, EnvOf<Ctx>, Schema, Send, Ctx>): string extends Path ? Server<R, Ctx, HookOutput> : Server<AddRoute<R, \"WS\", Path, WsRouteInfoFor<Path, Schema, Send>>, Ctx, HookOutput>;\n /**\n * Broadcast `data` to every WebSocket connection subscribed to `topic` (via `ws.subscribe(topic)`).\n * In-process and **single-instance** (see {@link TopicRegistry}) - a multi-instance deploy must bridge\n * an external fan-out (Redis, a Durable Object) to this. A no-op when nobody is subscribed.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void;\n private route;\n /**\n * Low-level route registration shared by the inline builder and `implement()`.\n * Captures the server's current `derive`/`decorate` chain into the route - this\n * is the \"compiled\", order-scoped per-route chain.\n */\n register(method: string, path: string, schema: RouteSchema | undefined, handler: (context: never) => unknown): void;\n /** Register a contract/group route batch atomically. Every route captures the same current chain it\n * would capture through {@link register}; no route becomes visible unless the full batch validates.\n *\n * A path ending in optional parameters (`/users/:id?`) is one catalog route per concrete pattern,\n * so reflection, OpenAPI, evidence and the typed client all see ordinary routes. */\n registerBatch(routes: readonly {\n readonly method: string;\n readonly path: string;\n readonly schema: RouteSchema | undefined;\n readonly handler: (context: never) => unknown;\n }[]): void;\n /** Join a group scope's prefix BEFORE compilation, so the pattern, the reflected descriptor, the\n * capability guard, the ledger record, and assurance path matching all see the one served path. */\n private prefixed;\n private prepareRoute;\n /** @internal Symbol-keyed install seam for the `responseContract()` plugin. Off the public typed surface. */\n [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void;\n /** @internal Symbol-keyed install seam for the response observer plugin. */\n [INSTALL_RESPONSE_OBSERVER](runtime: ResponseObserverRuntime): ResponseObserverMethods;\n /** @internal Symbol-keyed install seam for the `idempotency()` plugin. Off the public typed surface. */\n [INSTALL_IDEMPOTENCY](runtime: IdempotencyRuntime): void;\n /** @internal Symbol-keyed install seam for the `mcp()` plugin. Off the public typed surface. */\n [INSTALL_MCP](runtime: McpRuntime): void;\n /** @internal Symbol-keyed install seam for the `notFound()` plugin. Off the public typed surface. */\n [INSTALL_NOT_FOUND](lane: NotFoundLane): void;\n /** @internal Symbol-keyed install seam for the `nodeDirect()` plugin. Off the public typed surface. */\n [INSTALL_NODE_DIRECT](runtime: NodeOutcomeRuntime): void;\n /** @internal An adapter reports a failure no response hook saw (a hook that threw past `fetch`, a\n * response the runtime refused to write), logged as Bun's `listen()` logs one. */\n [REPORT_ERROR](error: unknown): void;\n /** @internal Symbol-keyed install seam for the `streaming()` plugin. Off the public typed surface. */\n [INSTALL_SSE](runtime: SseRuntime): void;\n /** @internal Symbol-keyed install seam for the `websocket()` plugin. Off the public typed surface. */\n [INSTALL_WS](runtime: WsRuntime): void;\n /**\n * @internal The runtime Bun serves this app's WebSocket upgrades with, asked by `listen()` and by a\n * parent that mounts this app: `undefined` while nothing here can take one, `null` when something\n * can but no runtime is at hand. A mounted Nifra app answers through this same seam, so mounting an\n * app without a WebSocket route needs no runtime; a resolver without the seam cannot say, so it\n * counts. `seen` ends a mount cycle (an app mounted under itself to alias a prefix).\n */\n [GET_WS_RUNTIME](seen?: Set<unknown>): WsRuntime | null | undefined;\n /** The `[GET_WS_RUNTIME]` answer for the apps mounted here alone, whatever this app's own routes. */\n private mountedWsRuntime;\n /** Whether an app mounted here takes WebSocket upgrades. Worked out again only after a `ws()` or a\n * `mount()` somewhere, so the upgrade check on a plain request costs one comparison. */\n private mountsTakeUpgrades;\n /**\n * Merge another server's routes into this one - the composition escape hatch for large apps.\n *\n * WHY: the fluent chain accumulates one type-alias level per route, and TypeScript resolves\n * that stack in one recursion - a single chain hits TS2589 at ~95 routes. Groups keep every\n * chain short: build each domain (`listings`, `agents`, …) as its own `server()` (its registry\n * resolves independently), then `app.merge(listings).merge(agents)` - each merge adds ONE level\n * regardless of group size. 300+ routes stay fully typed (see many-routes.test-d.ts). The\n * other escape hatch is contract-first `implement()`, whose registry is a single object type.\n *\n * Semantics: merged routes keep the chains captured where they were DEFINED - the group's\n * `derive`/`decorate`/`beforeHandle`/`afterHandle`/`onError`/`around` apply to its routes\n * exactly as they did standalone, so a group wires its own plugins. The same locality rule\n * covers the group's `onRequest` hooks: they run only for requests that route to the GROUP's\n * routes, and for an `OPTIONS` preflight to a path they serve (a `bodyLimit()` mounted on an uploads group must not start gating the whole app\n * because the app composed it in), and the group's global assurance follows its hooks onto\n * exactly those routes. A group with hooks but NO routes is a middleware bundle - its hooks\n * can only mean app-wide intent, so they are appended globally, unchanged. Response-side hooks\n * (`onResponse`/`onResponseFinalized`) are appended to this server's. This server's\n * route-scoped chains do NOT retroactively wrap merged routes (order-scoped, like routes\n * registered before a `derive`). Fail closed: a path+method collision throws\n * `RouteConfigError` at merge time, and a group with WebSocket routes or mounts is refused\n * (register those on the parent).\n *\n * What this server's `.use()`, made BEFORE the merge, covers on a merged route versus a\n * `group()` route:\n *\n * | installed on this server | group() route | merge()d route |\n * | ------------------------------------------ | ------------- | ------------------------------ |\n * | derive/decorate/beforeHandle/afterHandle, | yes | no - wire it on the merged |\n * | onError/around, authenticate, route-scoped | | server |\n * | assurance | | |\n * | onRequest/onResponse/responseHeaders hooks | yes | yes (app-wide) |\n * | responseContract() | yes | yes, when the route declares a |\n * | | | response and its own server |\n * | | | installed no contract |\n * | effectLedger() | yes | yes, when the route declares |\n * | | | capabilities and has no ledger |\n * | idempotency() | yes | the merged server's own; a |\n * | | | route declaring it without one |\n * | | | is refused at registration |\n *\n * The response contract and the ledger can only add a check or a record, so a merged route is\n * recompiled under them. A runtime installed AFTER the merge covers neither kind of route.\n *\n * In development, {@link ServerOptions.unusedScopedHooks} reports a hook followed only by merges and\n * a contract or ledger installed after the routes it would cover; `nifra check` reports a merge whose\n * server authenticates none of its routes under this server's `authenticate()` (NF-C043).\n */\n merge<R2 extends Registry, Ctx2, HookOutput2>(other: Server<R2, Ctx2, HookOutput2>): Server<R & R2, Ctx, HookOutput>;\n /**\n * Declare routes under a static path prefix, with the prefix in the typed client, `routes()`,\n * OpenAPI, capability events, and the effect ledger - the counterpart of Hono's `route()`,\n * Elysia's `group()`, and Fastify's `register({ prefix })`.\n *\n * app\n * .derive(session)\n * .group(\"/admin\", (admin) =>\n * admin.beforeHandle(requireAdmin).get(\"/users\", listUsers).get(\"/users/:id\", getUser),\n * )\n * .get(\"/\", home) // not covered by requireAdmin\n *\n * The builder receives a scope that INHERITS this server's route chain as it stands at the call\n * (`derive`/`decorate`/`authenticate`/`beforeHandle`/`afterHandle`/`onError`/`around`, assurance,\n * capability interceptors, installed runtimes, applied plugins), exactly as a route declared here\n * would. {@link merge} documents how that differs for a merged server. A plugin this server already applied is in effect for the group: the group's `use()` of\n * that same instance does nothing, and its `use()` of another instance under the same name throws a\n * `RouteConfigError` (`PLUGIN_RECONFIGURED`), because that instance could never replace the parent's.\n * A plugin the group applies still shares the parent's copy of a dependency it `use()`s itself.\n * What it adds stays in the group: its chain additions apply only to its own routes, and its\n * request/response hooks (`onRequest`, `onResponse`, `responseHeaders`, `onResponseFinalized`, and\n * middleware bundles that use them) run only for requests whose path is the prefix or below it.\n * Per-route authorization belongs in `authenticate`/`beforeHandle`, which are compiled into each\n * route; request hooks are path prefilters.\n *\n * The prefix is static text - `\"/api\"`, `\"/api/v1\"` - validated when declared: no params,\n * wildcards, empty or dot segments, percent-escapes, or trailing slash. A group's `\"/\"` route\n * serves the prefix itself. Groups nest (`\"/api\"` then `\"/v1\"` serves `/api/v1/...`).\n *\n * Fail closed: the builder must synchronously return the scope it was given; a collision with an\n * existing route throws `RouteConfigError` and adds none of the group's routes; `.ws()`, mounts,\n * MCP `.tool()`s, and `merge()` inside a group are refused (register them on the parent). Once the\n * builder returns, the scope is closed - a leaked reference cannot add routes later.\n */\n group<const P extends string, R2 extends Registry, Ctx2, HookOutput2>(prefix: P, build: (group: Server<EmptyRegistry, Ctx, HookOutput>) => Server<R2, Ctx2, HookOutput2>): Server<R & PrefixRegistry<P, R2>, Ctx, HookOutput>;\n /**\n * Take over another server's routes and hooks - the shared core of {@link merge} and {@link group}.\n * `prefix` selects group semantics: hooks are scoped to requests under the prefix (response hooks\n * included), and the source's global assurance past `inheritedGlobal` (what it copied from this\n * server) is folded into its routes. Without a prefix, merge semantics: request hooks are scoped to\n * the source's routes when it has any, response hooks are appended app-wide.\n */\n private adopt;\n /** A fused renderer closes over runtime services to keep its seven-argument JSC fast path. Merging\n * rebinds that closure once to the executing server; generic plans already receive the runtime. */\n private bindFusedRuntime;\n /**\n * Enumerate the registered routes (method, path, input schemas), in registration\n * order. Powers `toOpenAPI` and other introspection; the router trie itself no\n * longer holds the original patterns.\n */\n routes(): ReadonlyArray<RouteDescriptor>;\n /**\n * Resolve a `Request` to a `Response` - the whole lifecycle, testable without a port. The\n * optional `platform` carries edge inputs (`env`, `waitUntil`); edge adapters pass it, and\n * Bun/Node/Deno omit it (then `c.env` is `undefined` and `c.waitUntil` runs fire-and-forget).\n */\n fetch(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<Response>;\n private fetchSource;\n private fetchSourceInner;\n /** Web response path when Bun already matched the route. The lifecycle and response hooks remain\n * exactly the same as {@link fetchSource}; only portable URL scanning + trie lookup are skipped. */\n private fetchMatched;\n private fetchMatchedInner;\n /**\n * Run `produce` under the capacity gate: admit → run → release exactly once when the response is\n * produced (or the run throws). Only reached when {@link capacityGate} is set, so the off path pays\n * nothing. The slot is held for the duration of handler execution, not the streaming of the body -\n * capacity here bounds concurrent *work*, matching how in-flight is counted.\n */\n private admitGated;\n private runAdmitted;\n /**\n * Select a mounted handler's native Node lane without materializing a Web Request. This is an\n * adapter seam, not a second lifecycle: any app-wide behavior that the ordinary mount path would\n * run makes the capability ineligible and the caller falls back to `resolveNodeSource`. Typed\n * routes keep precedence exactly as `routeAndRun` does, including the existing mount behavior for\n * a path whose registered route rejects this method.\n */\n [RESOLVE_NODE_MOUNT](source: RequestSource): NativeMountSelection | undefined;\n private firstMountUnder;\n /**\n * Like {@link fetch}, but renders a plain-data result **without** building a Web `Response` - the\n * `@nifrajs/node` adapter serializes the returned primitives straight to the socket, skipping the undici\n * `Response` build + body drain (the bulk of the Node bridge cost, measured ≈4µs/req). A handler that\n * returns a `Response`, an error/short-circuit, or a response hook that replaces/consumes the buffered\n * body stays on the full Web path; an in-place response hook can still use the direct writer. Same\n * lifecycle as {@link fetch} (body cap, validation, hooks all run); only the final render differs.\n */\n resolveNode(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<NodeServeOutcome>;\n resolveNodeSource(source: RequestSource, platform?: Platform<EnvOf<Ctx>>, suppliedRuntime?: NodeOutcomeRuntime): MaybePromise<NodeServeOutcome>;\n /** Run generic Web response middleware while retaining direct writes for untouched buffered bodies. */\n private finishNodeWebResponse;\n /** True only when every transforming Web response hook has a header-only Node equivalent. */\n private canUseNodeResponseHooks;\n /** Apply paired native hooks to data outcomes; preserve the complete Web hook pipeline for Response outcomes. */\n private finishNodeResponse;\n private withNodeResponseHeaders;\n /** Synchronous until a native response hook actually returns a Promise. */\n private applyNodeResponseHooks;\n private continueNodeResponseHooks;\n /**\n * Resolve a WebSocket upgrade - the seam every serving adapter uses. Returns `pass` (not a WS\n * upgrade for a registered route → handle as normal HTTP), `reject` (a WS route matched but\n * `upgrade()` rejected, or the path was malformed → return `response`), or `upgrade` (perform the\n * runtime upgrade, then dispatch the native socket's events to `handler`, seeding `ws.data` with\n * `data`). Runs the route's `upgrade(c)` guard in a real request context. Synchronous unless\n * `upgrade()` is async; a throw rejects with a flat 500 (no detail leaked).\n */\n private runWebSocketRequestHooks;\n private continueWebSocketRequestHooks;\n resolveWebSocketUpgrade(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<WebSocketUpgradeOutcome>;\n /** Bun `fetch` when WS routes exist: try a WS upgrade first, else run the normal HTTP lifecycle.\n * `undefined` ⇒ Bun owns the upgraded socket; a `Response` ⇒ a normal reply or a rejected upgrade.\n * (The socket dispatch itself lives in `ws-bun.ts`, loaded via `@nifrajs/core/ws`.) */\n private bunFetchWithWebSocket;\n /**\n * The shared lifecycle, generic over how the final value is rendered: `finalize` turns a handler's\n * result + `set` into the output `T` (`toResponse` → a Web `Response`; `toNodeOutcome` → node-direct\n * primitives), `wrapResponse` lifts an early/error `Response` into that same `T`, and `onTimeout`\n * produces the 503. The Web `fetch` and `resolveNode` are thin callers over this one routing +\n * context + lifecycle implementation - no duplication across the trust boundary.\n */\n /** Apply the `clientIp` trust declaration to the adapter's raw socket peer, returning a platform\n * whose `clientIp` is the derived caller. Only called when a trust declaration is configured. */\n private deriveClientIp;\n private trustedPlatform;\n private dispatch;\n /** Node-native request hook walk. A header-only hook can inspect the lazy source without forcing a\n * Web `Request`; arbitrary request rewrites and full Web hooks use {@link runWithOnRequest}. */\n private runWithNodeRequest;\n private continueNodeRequest;\n private canUseNodeRequestHooks;\n /**\n * onRequest short-circuit path. Synchronous as long as every hook returns synchronously (the\n * common case - e.g. CORS returning `undefined` for a non-preflight request): an `async` version\n * here put EVERY request of any app with one onRequest hook onto the promise machinery, profiled\n * at ~13% of a realistic request. The first hook that returns a Promise hands the REMAINING\n * hooks to the async continuation; behavior is identical.\n */\n private runWithOnRequest;\n /** Async tail of {@link runWithOnRequest}: applies the first awaited hook's outcome, then runs\n * the remaining hooks (awaiting freely - we're already async here). */\n private continueOnRequest;\n private takeResponseRequest;\n /**\n * The NodeRequestContext for a source, MEMOIZED per source so the request twins and the response\n * twins receive the exact same object within one request - that identity is the documented\n * contract stateful twins key their WeakMaps on. An adapter source (which already speaks the\n * interface) is returned as-is; a plain `Request` source (a direct `resolveNode` caller) gets one\n * cached wrapper.\n */\n private nodeRequestContextOf;\n /** Preserve the request visible to generic onRequest hooks for paired native response hooks. */\n private takeNodeResponseRequest;\n /**\n * Route → build context → run. Synchronous through to the handler for a **bare** route\n * (selected by its compiled plan), so a sync handler produces its result with zero promise allocations;\n * routes with validation/hooks keep the full compiled route program, unchanged.\n */\n private routeAndRun;\n private fetchMount;\n /** Run a route that has already been matched by the runtime or Nifra's portable router. */\n private runMatched;\n /** Supply request-specific deadline state to the route's precompiled execution plan. */\n private runMatchedLanes;\n /** @internal Symbol-keyed install seam for the `effectLedger()` plugin. Off the public typed surface. */\n [INSTALL_EFFECT_LEDGER](runtime: EffectLedgerRuntime): void;\n /** The narrowest bare route: a syntactic `() => ...` handler cannot observe the context argument, so\n * successful requests can skip allocating `RequestContext`. Errors still allocate one for logging. */\n private runContextlessBare;\n private contextlessBareError;\n /**\n * The synchronous fast path selected by a route's execution plan: apply static decorations, call the\n * handler, render the result - **no `await`** unless the handler itself returns a promise. It mirrors\n * the same error boundary as the compiled route program (which a bare route would otherwise no-op through) and shares\n * {@link logRequestError}; a bare route has no `onError` hooks, so error handling is fully synchronous\n * (a thrown `Response` is control flow; anything else is a logged flat 500). This is where nifra skips\n * the per-request async-frame tax - the same win codegen routers get, but without `eval`.\n */\n private runBare;\n /** Bare-route error rendering - identical to the compiled route program's catch minus the (absent) onError\n * loop: a thrown `Response` is returned as deliberate control flow; anything else is logged + 500. */\n /**\n * Build a route's fused Web renderer. Composition happens once at\n * registration; the returned closure is what every request to the route runs. Behavior is\n * byte-identical to the generic `runBare`/`runContextlessBare` + `toResponse` pair - same\n * decoration order, same error routing (thrown `Response` = control flow; anything else logs and\n * 500s), same respond semantics (the lifecycle parity suite pins it).\n */\n private buildFusedWeb;\n /** A fused Web lane's render in an async continuation, where a result that cannot be rendered\n * must fail like a handler throw; a synchronous render throw reaches {@link runMatchedLanes}. */\n private respondFused;\n /** Compile the eligible body-only route's parser → validator → handler continuation once. The\n * bounded parser remains shared with the generic lane; only the route-invariant entry lookups and\n * lifecycle dispatch disappear from the common synchronous-validator/synchronous-handler case. */\n private buildFusedBodyRunner;\n /** Web adapter wrapper for the shared body runner. Node passes its native finalizer directly through\n * the execution plan, while Web needs the live context to preserve lazy `c.set` controls. */\n private buildFusedBodyWeb;\n /** The fused Web lane for a route whose only lifecycle step is a query schema: parse + validate +\n * handler + respond in one closure, no lifecycle promise when the validator and handler are sync.\n * Eligibility is decided at registration (see `fusedQuery` in {@link register}); the semantics here\n * are exactly `runQueryOnly`'s for that eligible shape - invalid input returns\n * `validationError(issues)` (recovery hooks disqualify the route from this lane), a thrown\n * `Response` passes through, anything else logs and returns a flat 500, and an async validator\n * falls to a then-chain with the same steps. */\n private buildFusedQueryWeb;\n /**\n * Compile a route's `derive + before` lifecycle to a single closure: the per-request walk through\n * `runSync` → `runHooksSync` is a stack of 3 frames and 2 `Object.assign`s for what is by far the\n * most common middleware shape (auth/trace/id derivation, an auth/policy `beforeHandle`). Folding\n * the same steps into one closure hits the same monomorphic inline-cache site as `buildFusedWeb`,\n * and `Object.assign(ctx, deriveResult)` becomes one extra property write on the context's already\n * hot hidden class. Behavior is byte-identical to the compiled route program: the same thrown-value\n * contract (`Response` is control flow, anything else logs + 500), the same `c.set` semantics, the\n * same `fusedRespond` for the rendered body. The `LifecycleExecutionLane` guarantee\n * (`schema.params === undefined && schema.headers === undefined && derives === 1 &&\n * beforeHandle === 1 && afterHandle === 0 && onError === 0 && !hasResponseContract &&\n * !hasDecorations`) is enforced by `selectRouteLanes`; this lane is selected ONLY when all of those\n * hold. A `query` schema (the route declares `{ query }` alongside the hooks) is validated FIRST,\n * mirroring the compiled route program's stage order; the fused builder runs validate → derive →\n * before → handler in one frame.\n */\n private buildFusedDeriveBefore;\n private buildFusedDeriveBeforeAfter;\n /**\n * Body + lifecycle hooks fused: parse → validate → derive → before → handler → (after) in one\n * closure, the same win `buildFusedBodyRunner` gives for the no-hooks body shape. The shape is\n * `lifecycleHookLane` PLUS a body schema with no other validation conflicts; the lane is selected\n * ONLY when `schema.body !== undefined && schema.query/params/headers === undefined &&\n * schema.onValidationError === undefined && !defaultOnValidationError && !hasIdempotency &&\n * !hasLedger && derives === 1 && beforeHandle === 1 && afterHandle <= 1 && onError === 0 &&\n * !hasResponseContract && !hasDecorations && around === 0`. The same single `querySchema === undefined`\n * trick used in the no-body lane lets the build path stay simple: a query + body route falls back\n * to the generic program (this is rare in practice - validated query + validated body is usually a\n * \"search results\" route with a middleware chain on top, and the generic lane is fine there).\n */\n private buildFusedBodyDeriveBeforeAfter;\n /**\n * Generic (finalize/wrapResponse-parameterized) fused runner for the derive-before(-after) lane:\n * the Node-direct counterpart of `buildFusedDeriveBefore` / `buildFusedDeriveBeforeAfter`.\n *\n * The Web fused builders above return a `Response`, so the Node dispatcher (`webFast === false`)\n * cannot use them and a derive+before route falls back to the generic route program there - two\n * staged loops, per-stage dispatch, and the async-continuation machinery - while Bun rides the\n * single closure. That asymmetry is the realistic-route Node deficit against Fastify: this runner\n * closes it by running validate → derive → before → handler → (after) in one frame and finalizing\n * through the caller's own `finalize` (the Node outcome on the direct lane, `toResponse` on Web),\n * so the same registration feeds both runtimes with no per-lane copy of the lifecycle to drift.\n *\n * Semantics mirror the generic program stage-for-stage for the shapes this lane admits (exactly\n * one derive, one beforeHandle, zero-or-one afterHandle, no onError/around/decorations/contracts/\n * recovery hooks - enforced by `selectRouteLanes`): thrown `Response`/`status(...)` are control\n * flow through `wrapResponse`/`finalize`, anything else logs + 500s via the shared `bareError`\n * lane (identical to `handleLifecycleError` with no `onError` hooks), and a terminal `finalize`\n * throw (e.g. an unstringifiable handler return on the Node lane) is caught exactly as\n * `finishLifecycleContract` catches it. Step functions close over registration state only and take\n * the request state as arguments, so the hot path allocates no per-request closures.\n */\n private buildFusedDeriveBeforeRunner;\n /**\n * Generic fused runner for the body+derive-before(-after) lane: the Node-direct counterpart of\n * `buildFusedBodyDeriveBeforeAfter`. Same contract as `buildFusedDeriveBeforeRunner` above - one\n * frame running parse → validate → derive → before → handler → (after) through the caller's own\n * `finalize` - with the body read ahead of validation, exactly as the generic program orders its\n * body stage before the derive/before stages. `readBodyFramed` keeps the shared bounded-read,\n * content-type, and prototype-poisoning contracts; the 415/400 renders take `wrapResponse`\n * directly, which is what the generic lane's wrap-after-identity amounts to.\n */\n private buildFusedBodyDeriveBeforeAfterRunner;\n private bareError;\n /**\n * Keep the ordinary thrown-error response independent from the caught value. Deliberate Response\n * control flow is handled by `renderBareError`; every other throw gets this fixed public envelope.\n */\n private internalErrorResponse;\n private runWithAround;\n /** Execute the registration-compiled general stage program. */\n private runProgram;\n /** Bind a compiled validation stage to its stable schema and the existing recovery contract. */\n private validateProgramStage;\n /** Preserve the existing bounded body reader and its fail-closed framing/prototype checks. */\n private readProgramBody;\n /** Keep thrown Response/status and redacted 500 semantics in one existing error boundary. */\n private handleProgramError;\n /** Finish a successful program result through response-contract enforcement and finalization. */\n private finishProgramResult;\n private runAround;\n private runBodyOnly;\n /** Validate + run the handler for the bodyOnly path - shared by the inline fast path and the\n * streaming fallback. A method (not per-request closures) so the hot path allocates nothing\n * beyond the one `.then` continuation. */\n private finishBodyOnly;\n private executeHandler;\n private handleValidationErrorRecovery;\n private applyBodyValidation;\n private runQueryOnly;\n /** Validate-result → set `ctx.query` → run handler. A method (not a per-request closure), the\n * query analogue of {@link applyBodyValidation}. */\n private applyQueryValidation;\n /**\n * Thread the response through each global `onResponse` hook. Stays SYNCHRONOUS until a hook\n * actually returns a Promise - an `async` version forced a promise + microtask on EVERY response\n * of any app with an onResponse hook (cors/securityHeaders/etag/timing all use onResponse), the\n * same ~13%/req tax the onRequest walk was de-async'd to avoid. The first async hook hands the\n * rest to {@link continueOnResponse}.\n */\n private applyOnResponse;\n private applyOnResponseAndFinalize;\n private completeResponseFinalization;\n private failResponseFinalization;\n /** Notify terminal observers in order while isolating both sync and async failures. */\n private notifyResponseFinalized;\n /** Async tail of {@link applyOnResponse}: runs the remaining hooks once one has gone async. */\n private continueOnResponse;\n /**\n * Bound the response time. On timeout we abort `ctx.signal` (so cancellation-aware\n * handlers can bail) and return 503; the in-flight work keeps running but its\n * result is discarded - JS can't forcibly cancel a promise.\n */\n private withTimeout;\n private finishLifecycleContract;\n private finishContractOutcome;\n /** Synchronous by design, and `MaybePromise` rather than `Promise` for the same reason: control flow\n * out of a lifecycle stage must not cost a promise. An `async` method allocates one and defers the\n * result a microtask even when every branch it takes returns immediately, which is the common case\n * here - a thrown `status(...)`/`Response`, or a route with no `onError` hook at all. Only the hook\n * loop, which may await, drops into {@link runErrorHooks}. */\n private handleLifecycleError;\n /** The `onError` chain, split off {@link handleLifecycleError} so its `await` costs only the routes\n * that registered a hook. A hook may return a custom response; otherwise the default 500 stands. */\n private runErrorHooks;\n /** Log an unhandled request error to the (redacting) logger - shared by the compiled route program and the\n * bare fast path ({@link bareError}) so both record the same fields. Never throws; never leaks. */\n private logRequestError;\n private readAndValidateBody;\n /** Apply validation and its recovery hook on the generic lifecycle lane. Recovery is completed\n * before derives/beforeHandle run, matching the body-only and query-only execution lanes. */\n private applyLifecycleValidation;\n private finishLifecycleValidationRecovery;\n /** Adapt one route's compiled execution plan to Bun's already-matched request shape. Route\n * semantics remain in the plan; this closure only supplies native params and deadline fallback. */\n private compileBunNativeHandler;\n /** Compile portable route registrations into Bun's native route table. Apps with request-rewrite\n * hooks or WebSockets retain the single portable dispatcher because those features must run before\n * route selection/upgrade.\n *\n * Bun and the portable router agree on which of two static-and-`:param` paths wins a request, so\n * the table is kept to those paths. Where Bun would otherwise pass a request on to a less specific\n * path, the more specific one carries `fallback`, the portable dispatcher, under that method.\n * `peer` is the platform every request served from the table shares. */\n private buildBunNativeRoutes;\n /**\n * Start a `Bun.serve` instance bound to `port` (use `0` for an ephemeral port).\n *\n * `reusePort` sets `SO_REUSEPORT` so **multiple processes can bind the same port** and the kernel\n * load-balances connections across them - the standard way to use every core (Bun is\n * single-threaded per process). Spawn one process per core, each calling\n * `app.listen(PORT, { reusePort: true })`; see `examples/cluster.ts`. Every process must opt in,\n * and all of them must be the same app. Linux balances ~evenly; macOS accepts the flag but may\n * favor one socket (fine for dev, measure on Linux for production numbers).\n *\n * `hostname` is the bind address, defaulting to Bun's `0.0.0.0` (every interface). Pass\n * `\"127.0.0.1\"` to bind loopback only - an admin surface, a sidecar, or anything that must not be\n * reachable off the box. Omitting it when you meant to restrict is a real exposure, so it is a\n * first-class option rather than something a caller has to drop down to `Bun.serve` for.\n *\n * `idleTimeoutSec` is how long Bun tolerates a connection with no bytes moving before it closes\n * the socket. Bun's default is **10 seconds**, and a request whose handler is still working sends\n * nothing - so any endpoint slower than 10s (a render, an export, a long upstream call) has its\n * connection cut mid-flight regardless of `requestTimeoutMs`. Apps with such endpoints must raise\n * this above their slowest expected response, which is why it is a first-class option and not a\n * reason to drop down to `Bun.serve`. `0` disables the timeout entirely; max 255.\n *\n * `tls` serves HTTPS directly: `app.listen(443, { tls: { cert, key } })` with PEM text or bytes.\n * Requests then arrive with `https:` URLs. Behind a proxy or a platform that terminates TLS, leave\n * it unset.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n readonly idleTimeoutSec?: number;\n readonly tls?: ListenTlsOptions;\n }): RunningServer;\n /**\n * Gracefully stop: wait for in-flight requests to finish (up to `drainMs`), then\n * issue a single terminal stop - graceful if everything drained, forced if\n * stragglers remain. Safe to call when not listening.\n *\n * The Bun semantics: poll `pendingRequests` (awaiting\n * `stop()`'s promise drops in-flight requests), and decide graceful-vs-forced in\n * ONE call (Bun can't escalate an already-graceful `stop()` to a forced close).\n * New connections may be accepted during the drain window; in a real deploy the\n * load balancer has already stopped routing here, and `drainMs` bounds it.\n */\n stop({ drainMs }?: {\n drainMs?: number;\n }): Promise<void>;\n private installSignalHandlers;\n}",
|
|
14170
|
+
"signature": "export declare class Server<R extends Registry = EmptyRegistry, Ctx = EmptyContext, HookOutput = never> {\n /**\n * Which copy of `@nifrajs/core` declared this type. Two copies in one build (a linked sibling repo,\n * a hoisting split) produce two unrelated `Server` types whose assignment error is a wall of\n * missing internals; the brand puts the feature version in the type itself, so `typeof app` on\n * hover - and `NifraFeatureVersion` in an assertion - says which core an app is talking to.\n * `nifra doctor` is the diagnosis that names both install paths.\n *\n * `declare` = type-only: no field is emitted, nothing is allocated per server.\n */\n readonly __nifraCoreVersion: NifraFeatureVersion;\n private readonly catalog;\n /** WebSocket routes, matched separately at upgrade time (a GET + `Upgrade: websocket`). */\n private readonly wsRouter;\n /** Each socket path, its declared capabilities, the evidence declarations its handshake captured\n * and the chain it runs; reflection reads it. */\n private readonly wsRoutes;\n /** `wsChanges` when `wsMountsLive` was last worked out; -1 until then. */\n private wsMountsCheckedAt;\n /** Whether an app mounted here takes WebSocket upgrades, as of `wsMountsCheckedAt`. */\n private wsMountsLive;\n /** In-process pub/sub backing `ws.subscribe(topic)` + `app.publish(topic, data)` (single-instance).\n * Created by the first `app.ws()` via the `@nifrajs/core/ws` runtime - `undefined` until then, so a\n * no-WebSocket app never constructs (or bundles) it. */\n private topics;\n /** True once any `app.ws()` route sets `validateSend: true` - the one case where a broadcast frame\n * is validated (and possibly dropped) per socket, so `app.publish` must stay on the JS registry loop\n * rather than delegate to Bun's native `server.publish`. */\n private wsHasValidatedSend;\n /** Bun's native topic broadcast, bound by `listen()` in native-pubsub mode; `app.publish` uses it\n * instead of the JS registry. `undefined` off Bun, before `listen()`, with a validated-send route,\n * or when a mounted app takes upgrades. */\n private nativePublish;\n private readonly maxBodyBytes;\n private readonly protoPoisoning;\n private readonly formOrigins;\n /** `trustBodyFraming`: mark every `app.fetch` request as runtime-framed (see ServerOptions). */\n private readonly trustBodyFraming;\n private readonly wsMaxPayloadBytes;\n private readonly requestTimeoutMs;\n private readonly wsUpgradeTimeoutMs;\n /** Installed by the `responseContract()` plugin; `undefined` = not installed, which is the default\n * and the state in which a declared `response` schema stays a compile-time contract only. */\n private responseContractRuntime;\n /** Opt-in caller-IP trust declaration; `undefined` = socket peer only, no forwarded header believed. */\n private readonly clientIpTrust;\n private readonly acceptInboundDeadlines;\n private readonly maxInboundDeadlineMs;\n private readonly deadlineAdmissionOptions;\n private readonly gracefulSignals;\n private readonly stopHooks;\n private readonly fetchMounts;\n private mountOrder;\n /** Number of composed mounts that must run before the parent route table. Keeps legacy mounts off the hot path. */\n private preRouteMountCount;\n /** Capacity-admission gate; `undefined` = off (the request path pays nothing). */\n private readonly capacityGate;\n private readonly onCapabilityUse;\n private readonly capabilityInterceptors;\n private readonly capabilityObservers;\n /** The installed effect-ledger runtime (owns the sink + per-route resolution + settle), or\n * `undefined` when the effect-ledger plugin is not installed. */\n private effectLedgerRuntime;\n /** The installed idempotency runtime (owns the app-wide default store + the dedupe lane), or\n * `undefined` when the idempotency plugin is not installed. */\n private idempotencyRuntime;\n /** Installed opt-in runtime for `.tool()`/`.resource()`/`.prompt()`; `undefined` until `.use(mcp())`. */\n private mcpRuntime;\n /** Installed answer for a request no route matched; `undefined` (the plain 404) until `.use(notFound())`. */\n private notFoundLane;\n /** Installed Node-direct renderer for direct `resolveNode()` callers; `undefined` until `.use(nodeDirect())`. */\n private nodeOutcomeRuntime;\n /** Installed streaming runtime for `.sse()` routes; `undefined` until `.use(streaming())`. */\n private sseRuntime;\n /** Installed WebSocket runtime for `.ws()` routes; `undefined` until `.use(websocket())`. */\n private wsRuntime;\n private readonly logger;\n /** How much of an unhandled error {@link logRequestError} records. See `ServerOptions.errorLogDetail`. */\n private readonly errorLogDetail;\n /** App-wide validation-error fallback; a route's own `schema.onValidationError` takes precedence. */\n private readonly defaultOnValidationError?;\n private bunServer;\n private bunSockets;\n private signalHandler;\n private sealed;\n private readonly derives;\n /** Dedicated authentication stages captured by subsequent routes. */\n private readonly authStages;\n private readonly decorations;\n private readonly beforeHandleHooks;\n private readonly afterHandleHooks;\n private readonly onErrorHooks;\n private readonly aroundHooks;\n private readonly onRequestHooks;\n private readonly onNodeRequestHooks;\n /** Registration-time eligibility for the Node request twin lane. */\n private nodeRequestHooksComplete;\n /** True when every request hook is safe to skip on a Bun native route. */\n private bunNativeRequestHooksSafe;\n private readonly onResponseHooks;\n private readonly onNodeResponseHooks;\n /** Registration-time eligibility for the Node response twin lane. */\n private nodeResponseHooksComplete;\n /** True when every response hook only mutates headers and can run after a Bun fused response. */\n private bunNativeResponseHeadersOnly;\n /**\n * True once a bundle registers a RAW `onNodeResponse` twin - one handed the outcome's header\n * record itself rather than the case-normalizing view. Their names are contractually the wire\n * spelling, but registration cannot PROVE it, so such an app forgoes the all-lowercase mark and\n * every reader re-derives the answer, exactly as before the mark existed.\n */\n private hasRawNodeResponseHook;\n private readonly onResponseFinalizedHooks;\n /**\n * Statically declared response headers, merged and prebuilt at registration; `undefined` (the\n * default) leaves every render path in its original shape. These are NOT response hooks - they are\n * folded into response construction - so declaring them keeps the fused native lanes an\n * `onResponse` hook would have disabled.\n */\n private staticResponseHeaders;\n /** A group's view of the static headers its enclosing scopes declared before it was created. */\n private inheritedStatics;\n /** A group's view of the plugins its enclosing scopes applied before it was created; unset while\n * a plugin applies, so its own dependency `use()` shares the parent's copy. */\n private inheritedPlugins;\n /** `wrapResponse` for the Web lanes: identity until static headers exist to fold into the\n * framework's own error/404/timeout renders, which are built outside the header init. */\n private wrapWebResponse;\n private webResponseTimeout;\n /** Body/raw response hooks need a framework-payload marker; keep that decision per app. */\n private responseBodyTag;\n private readonly responseBodyOwners;\n private readonly finalizeResponse;\n private readonly responseRequests;\n /** A request the WebSocket handshake check ran the onRequest hooks on and then passed to HTTP →\n * what the hooks returned, so `fetch` routes that instead of running the hooks a second time. */\n private wsHookedPasses;\n /** Original source → request observed by generic request hooks, including in-place mutations. */\n private readonly responseSources;\n /** Memoized NodeRequestContext per plain-`Request` source - see {@link nodeRequestContextOf}. */\n private readonly nodeContexts;\n /** Plugins/middleware already applied via `use`, by name - for idempotent dedupe. */\n private readonly appliedPlugins;\n /** Order-scoped evidence captured by routes registered after an assured plugin. */\n private readonly activeAssurance;\n /** App-wide evidence from global hooks; applies retroactively to every route. */\n private readonly globalAssurance;\n /** App-declared MCP resources / prompts (via {@link resource} / {@link prompt}), read by `nifra mcp`. */\n private readonly mcpResourceList;\n private readonly mcpPromptList;\n /** Kept so a {@link group} scope is built with exactly this server's settings: fused lanes read\n * several of them at request time, so a group route must never run under different ones. */\n private readonly options;\n /** Static prefix joined onto every route this server registers; non-empty only on a group scope. */\n private routePrefix;\n constructor(options?: ServerOptions);\n private assertConfigurable;\n /** Register a callback awaited after graceful drain and server stop. Hung callbacks are bounded. */\n onStop(fn: StopHook): this;\n /**\n * Mount a legacy fetch handler under a literal path prefix. Mounted handlers sit behind typed\n * routes, so routes can move one at a time while the remaining legacy surface stays live.\n * Mounted responses are outside Nifra's typed route and response-contract checks.\n *\n * It carries HTTP only: a WebSocket upgrade under the prefix reaches the handler as an ordinary\n * request and never becomes a socket. Serve that path's sockets with `app.ws()` routes or a\n * mounted child app, or keep the legacy server running beside this one for them.\n */\n mountFetch(path: string, handler: FetchHandler<EnvOf<Ctx>>, options?: MountFetchOptions): this;\n /**\n * Compose a child fetch app under a literal path prefix.\n *\n * Composed mounts run after the app-global request phase and before the parent's route table. This\n * makes them safe to use in an SSR shell whose `/*` page route would otherwise swallow an API mount.\n * If the child exposes `resolveWebSocketUpgrade`, the same mount also participates in adapter-owned\n * WebSocket upgrades; the serving adapter still upgrades its original socket, while the child sees\n * the mounted request path (stripped when requested).\n *\n * `fallbackOn: 404` is deliberately limited to GET/HEAD/OPTIONS at dispatch time. Those methods are\n * replayable without buffering an untrusted request body; POST/PUT/PATCH and streaming requests\n * never get retried after a child has had a chance to consume them.\n */\n mount(options: MountOptions<EnvOf<Ctx>>): this;\n /**\n * Add a per-request, computed context extension. Order-scoped: it is snapshotted into every route\n * declared *after* this call, and reaches none declared before. One added after the last route\n * (e.g. on the app returned by a route-registering factory) covers nothing - see\n * {@link ServerOptions.unusedScopedHooks}.\n *\n * Returning a `status(...)` (or a `Response`) instead of an extension ends the request there - the\n * guard shape, and the cheap one: it renders as plain data on the same lane a handler's return\n * takes, where `throw new Response(...)` pays ~40% of the rejection lane to build the object. That\n * branch is control flow, so it does not widen the derived context type.\n */\n derive<H extends (context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx & ContextExtensionOf<ReturnType<H>>, HookOutput | StatusResponseOf<Awaited<ReturnType<H>>>>;\n /**\n * Add a static context value. Order-scoped: captured by every route declared *after* this call, and\n * by none before; one added after the last route reaches nothing\n * (see {@link ServerOptions.unusedScopedHooks}).\n */\n /**\n * Register a dedicated authentication stage for subsequent routes.\n *\n * Unlike `derive`, this stage receives a body-blind authentication capsule and is compiled before\n * route validation. Keeping it separate prevents an unrelated derive from accidentally becoming a\n * security gate and lets the route compiler retain a protected fast lane.\n *\n * A stage that throws, or returns anything but `authenticated(principal)` or `rejected(...)`, fails\n * closed with 503 `{ ok: false, error: \"auth_unavailable\" }`. The cause goes where a handler's error\n * goes: to `onError`, whose response replaces the 503, and when no hook answers, to the logger. A\n * thrown `Response` or `status(...)` is sent as thrown, as it is from a handler.\n */\n authenticate<Principal>(stage: AuthenticationStage<Principal, EnvOf<Ctx>>): Server<R, Ctx & {\n readonly principal: Principal;\n }, HookOutput>;\n decorate<const K extends string, V>(key: K, value: V): Server<R, Ctx & Record<K, V>, HookOutput>;\n /**\n * Run before routing on the raw request. Return a `Response` or a `status()` result to\n * short-circuit, or a replacement `Request` to continue routing with a rewritten method/URL/headers.\n * Global. A throw or rejection goes to every registered {@link onError} (route-less context), then\n * the logged default 500.\n */\n onRequest(fn: (req: Request, platform?: Platform<EnvOf<Ctx>>) => MaybePromise<OnRequestResult>): this;\n /**\n * Run after validation, before the handler; a non-`undefined` return short-circuits. Order-scoped:\n * it is snapshotted into every route declared *after* this call and covers none declared before, so\n * one added after the last route reaches nothing (see {@link ServerOptions.unusedScopedHooks}).\n */\n beforeHandle<H extends (context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /**\n * Wrap the matched route lifecycle for subsequent routes. This is intentionally generic over the\n * route output, so wrappers like async context storage do not force Node's direct JSON path through\n * a Web `Response`. The first registered wrapper is outermost.\n *\n * Order-scoped: captured by every route declared *after* this call, none before; one added after the\n * last route reaches nothing (see {@link ServerOptions.unusedScopedHooks}).\n */\n around<H extends (context: Context & Ctx, next: () => MaybePromise<unknown>) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /**\n * Asynchronously admit each subsequent `executeCapability()` call before its owned effect runs.\n * Interceptors receive token-only metadata plus an abort signal and must call `next()` exactly once\n * to admit. Returning without `next()`, timing out, aborting, or throwing fails the effect closed.\n */\n aroundCapability(interceptor: CapabilityInterceptor, options?: AroundCapabilityOptions): this;\n /** Observe token-only admission/execution lifecycle events for subsequent capability routes. */\n observeCapability(observer: EffectLifecycleObserver): this;\n /** Transform the handler's result before it is serialized. Order-scoped: captured by routes declared\n * *after* this call, none before; one added after the last route reaches nothing (see\n * {@link ServerOptions.unusedScopedHooks}). */\n afterHandle<H extends (result: unknown, context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /** Handle a thrown error; a non-`undefined` return becomes the response (else the default 500, or 503\n * `auth_unavailable` for a failed {@link authenticate} stage). Order-scoped: captured by routes\n * declared *after* this call, none before; one added after the last route reaches no route (see\n * {@link ServerOptions.unusedScopedHooks}). Every one answers an {@link onRequest} failure. */\n onError<H extends (error: unknown, context: Context & Ctx) => MaybePromise<unknown>>(fn: H): Server<R, Ctx, HookOutput | HookOutputOf<ReturnType<H>>>;\n /** Transform every outgoing response - success, error, 404, 405, short-circuit. Global. */\n onResponse(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n /**\n * Declare response headers with NO per-request decision behind them - and pay nothing for them on\n * the request path.\n *\n * These are not a hook. Because the values are known at wire-up, they are folded into response\n * construction (one prebuilt init for JSON renders, one record merge where the request set its own\n * headers), so an app whose only response middleware is static keeps every fused and native lane -\n * `onResponse`/`onResponseHeaders` disable Bun's fused native routes and, for a full `onResponse`,\n * the Node direct writer. They apply to EVERY response, exactly as a response hook would: success,\n * error, 404/405, timeout, and short-circuit alike.\n *\n * app.responseHeaders({ \"x-frame-options\": \"DENY\", \"referrer-policy\": \"no-referrer\" })\n *\n * They are DEFAULTS: a value the request itself produced (`c.set.headers`, or a response hook)\n * wins, whatever casing it used. In a group, a name the group declares replaces the value its\n * enclosing scopes declared before the group, on the group's routes. Names are lowercased once here; a non-string value, an invalid\n * name, `__proto__`, or a name the render owns (`content-type`, `content-length`,\n * `transfer-encoding`, `set-cookie`) throws a `TypeError` at wire-up.\n *\n * ORDERING: declarations made before any response hook fold into one static record. One made AFTER\n * a response hook cannot - the hook may already have written that name and must keep winning - so\n * it registers as an ordinary `onResponseHeaders` hook instead, preserving registration order at\n * the cost of the static tier's speed. Declare static headers first.\n */\n responseHeaders(record: Readonly<Record<string, string>>): this;\n /** Wire an already-validated lowercase record into the static tier, or - once a dynamic response\n * hook owns part of the header state - into a hook that runs in the right order. */\n private addStaticResponseHeaders;\n private enableResponseBodyTagging;\n private responseObserverMethods;\n /** Observe the terminal response after all transformations. Observers are ordered and fail-open. */\n onResponseFinalized(fn: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>): this;\n /**\n * Apply `all()` or `method()` from `@nifrajs/core/methods`: one handler registered under several\n * methods, or under a method outside the standard seven. The standard methods join the registry.\n *\n * Declared first on purpose. The plugin's handler is typed against this app's context, which\n * TypeScript reads from the first overload it tries.\n */\n use<M extends string, Path extends string, S extends RouteSchema, Output>(plugin: MethodRoutesPlugin<M, Path, S, Output, Ctx>): Server<WithMethodRoutes<R, M, Path, S, Output, HookOutput>, Ctx, HookOutput>;\n /** Enable the opt-in portable response observer methods. */\n use(plugin: ResponseObserverPlugin): this & ResponseObserverMethods;\n /**\n * Apply a **context** plugin ({@link ContextPlugin}, from {@link defineContextPlugin}) - it adds `D`\n * to the handler context and changes nothing else, so the route registry `R` and the existing context\n * `Ctx` thread through untouched. Like the identity overload above, this exists because the generic\n * `(app: this) => Out` overload below cannot infer through a *generic* plugin signature: it erases the\n * plugin's own type parameters to their constraints, which silently widens `R` to `Registry`.\n */\n use<D extends object>(plugin: ContextPlugin<D>): Server<R, Ctx & D, HookOutput>;\n /**\n * Apply a type-**identity** plugin ({@link IdentityPlugin}, from {@link defineIdentityPlugin}) - it\n * registers routes/hooks but doesn't change the types, so this returns `this` with the route registry\n * and context fully intact. This overload exists specifically so a named identity plugin (e.g.\n * `@nifrajs/better-auth`) threads the registry: its `& { pluginName }` intersection would otherwise\n * defeat the generic inference of the transforming overload below and collapse the result to `any`.\n */\n use<AddedHookOutput = never>(plugin: IdentityPlugin<AddedHookOutput>): Server<R, Ctx, HookOutput | AddedHookOutput>;\n /**\n * Apply a **plugin function** - `(app) => app`, typically built with {@link definePlugin}. It's\n * called with `this` and its result is returned, so an inline plugin's `derive`/`decorate` thread\n * the added context to handlers defined after `use` (the overload is generic over the concrete\n * `this`). A named plugin already applied is skipped (idempotent dedupe), however it was configured,\n * so a plugin meant to stack - a second, stricter guard - needs a name of its own per instance.\n *\n * If the plugin's return type is unpinned - `Server<any, any>`, as a hand-rolled `(app) => app` or a\n * `NifraPlugin<AnyServer, AnyServer>` infers (e.g. an auth plugin whose own types collapsed) - this\n * returns the non-callable {@link PluginTypeCollapsed} instead of silently widening the whole typed\n * client to `any`. `.get()`/`.post()` then fail right here rather than surfacing as `any` hundreds of\n * lines away. Fix at the plugin: build it with {@link defineIdentityPlugin}/{@link defineContextPlugin},\n * or pin its input server type. This mirrors the guard {@link definePlugin} already applies.\n */\n use<Out extends AnyServer>(plugin: (app: this) => Out): [ServerTypeUnpinned<Out>] extends [true] ? PluginTypeCollapsed : Out;\n /**\n * Apply a {@link Middleware} bundle - wire each hook it provides to its lifecycle point. Returns\n * `this` (no context-type merging); call it before the routes its `beforeHandle`/`afterHandle`\n * should cover (those are order-scoped; `onRequest`/`onResponse` are global). A bundle applied after\n * the last route reaches nothing - {@link ServerOptions.unusedScopedHooks} logs that at seal. A named\n * bundle already applied is skipped (idempotent).\n */\n use<M extends Middleware>(mw: M): Server<R, Ctx, HookOutput | MiddlewareOutputOf<M>>;\n use(mw: Middleware): this;\n get<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n get<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"GET\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Register a **typed SSE route** - an endpoint streaming `text/event-stream` whose event\n * payloads are contracted by `schema.sse`. It is a GET route, or a POST route when the schema\n * declares a `body` (a GET carries none): the body validates as on any POST, and the client sends\n * it with `.subscribe(onEvent, { body })` - the shape of a chat stream that posts its prompt. The handler receives the validated context plus a\n * {@link TypedSSEStream}: `stream.send(event)` is compile-time-checked against the schema and\n * JSON-serialized into the SSE `data:` field. The typed client sees the marker and grows a\n * `.subscribe(onEvent)` for the route with the same payload type - end-to-end typed streaming.\n *\n * import { streaming } from \"@nifrajs/core/sse\" // .use(streaming()) enables .sse()\n * const app = server().use(streaming()).sse(\"/feed\", { sse: t.object({ id: t.integer(), title: t.string() }) },\n * async (c, stream) => {\n * stream.send({ id: 1, title: \"hello\" }) // typed\n * await waitForDisconnect(stream.signal)\n * },\n * { keepAlive: 15_000 })\n *\n * // client: const off = api.feed.subscribe((post) => console.log(post.title))\n *\n * `init` passes through to the underlying {@link sse} helper (`keepAlive`, `maxBufferedBytes`,\n * extra headers). The connection closes when the handler resolves, `stream.close()` runs, or the\n * client disconnects (`stream.signal`). Query/body schemas validate exactly as on any other route.\n */\n sse<Path extends string, S extends RouteSchema & {\n sse: StandardSchemaV1;\n }>(path: Path, schema: S, run: (context: Context<Path, S> & Ctx, stream: TypedSSEStream<InferOutput<S[\"sse\"]>>) => void | Promise<void>, init?: SSEInit): Server<AddRoute<R, SseMethodOf<S>, Path, RouteInfoFor<Path, S, Response, HookOutput>>, Ctx, HookOutput>;\n post<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n post<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"POST\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n put<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n put<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PUT\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n patch<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n patch<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"PATCH\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n delete<Path extends string, S extends RouteSchema, H extends Handler<Path, S, Ctx>>(path: Path, schema: S, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, S, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n delete<Path extends string, H extends Handler<Path, RouteSchema, Ctx>>(path: Path, handler: H): Server<AddRoute<R, \"DELETE\", Path, RouteInfoFor<Path, Record<never, never>, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Declare an **MCP tool** an agent can call (via `nifra mcp`, or a mounted MCP endpoint): a typed\n * `POST /_nifra/tool/<name>` route whose `input`/`output` schemas contract the call and surface in\n * `tools/list`. Requires `.use(mcp())` - without it, `.tool()` is a registration error, so an\n * ordinary HTTP app never bundles the MCP wiring. Siblings: {@link resource}, {@link prompt}.\n *\n * import { mcp } from \"@nifrajs/core/mcp\"\n * const app = server().use(mcp()).tool(\n * \"search\",\n * { description: \"Search posts\", input: t.object({ q: t.string() }) },\n * ({ q }) => findPosts(q),\n * )\n */\n tool<Name extends string, S extends {\n description: string;\n input: StandardSchemaV1;\n output?: StandardSchemaV1;\n annotations?: ToolAnnotations;\n }, H extends (input: InferOutput<S[\"input\"]>, ctx: Context & Ctx) => MaybePromise<S[\"output\"] extends StandardSchemaV1 ? InferOutput<S[\"output\"]> : unknown>>(name: Name, config: S, handler: H): Server<AddRoute<R, \"POST\", `/_nifra/tool/${Name}`, RouteInfoFor<`/_nifra/tool/${Name}`, S[\"output\"] extends StandardSchemaV1 ? {\n body: S[\"input\"];\n response: S[\"output\"];\n } : {\n body: S[\"input\"];\n }, OutputOf<H>, HookOutput>>, Ctx, HookOutput>;\n /**\n * Declare an MCP **resource** - read-only data an agent can fetch through `nifra mcp` (app config, a\n * generated document, …). `read` runs in the app process, so capture whatever app state it needs in the\n * closure. `uri` is the MCP resource identifier (e.g. `\"myapp://config\"`). The sibling of {@link tool}\n * for the resource half of MCP.\n */\n resource(uri: string, config: {\n readonly name: string;\n readonly description?: string;\n readonly mimeType?: string;\n }, read: McpResourceDescriptor[\"read\"]): Server<R, Ctx, HookOutput>;\n /**\n * Declare an MCP **prompt** - a reusable prompt template an agent can fetch through `nifra mcp`.\n * `handler` receives the caller's arguments and returns the rendered messages.\n */\n prompt(name: string, config: {\n readonly description: string;\n readonly arguments?: readonly PromptArgument[];\n }, handler: McpPromptDescriptor[\"handler\"]): Server<R, Ctx, HookOutput>;\n /** The MCP resources declared via {@link resource} - enumerated by `nifra mcp`. */\n mcpResources(): readonly McpResourceDescriptor[];\n /** The MCP prompts declared via {@link prompt} - enumerated by `nifra mcp`. */\n mcpPrompts(): readonly McpPromptDescriptor[];\n /**\n * Register a **WebSocket** route. The connection upgrades on a `GET` to `path` carrying\n * `Upgrade: websocket`. The handshake runs the chain an HTTP `GET` registered here would: the\n * `authenticate()` stages, `derive`s and `beforeHandle`s added before this call, then the optional\n * `handler.upgrade(c)`. Any of them may reject (a `Response`, a `status(...)`, a failed auth stage);\n * `upgrade()` may seed per-connection `ws.data`. To keep a socket public, register it before the\n * guard. WebSockets are served by the\n * adapter (`listen()`, `@nifrajs/node`, `@nifrajs/deno`, `toFetchHandler`) - not by bare `app.fetch`, which\n * has no socket (a WS path through `app.fetch` is a normal HTTP response).\n *\n * The route also enters the type-level registry (under the pseudo-method `\"WS\"`), so the typed\n * client grows a `.ws()` handle for it: `messageSchema` types what the client may `send`,\n * `sendSchema` types the frames it receives. Passing explicit type arguments (`ws<MyData>(…)`)\n * defeats path-literal inference and skips the registry entry - the route still serves, it is just\n * invisible to `client<App>`; prefer typing `data` via `upgrade()`'s return.\n *\n * app.ws(\"/chat\", { open: (ws) => ws.send(\"hi\"), message: (ws, data) => ws.send(data) })\n */\n ws<Data = unknown, Schema extends StandardSchemaV1 | undefined = undefined, Send extends StandardSchemaV1 | undefined = undefined, Path extends string = string>(path: Path, handler: WebSocketHandler<Data, EnvOf<Ctx>, Schema, Send, Ctx>): string extends Path ? Server<R, Ctx, HookOutput> : Server<AddRoute<R, \"WS\", Path, WsRouteInfoFor<Path, Schema, Send>>, Ctx, HookOutput>;\n /**\n * Broadcast `data` to every WebSocket connection subscribed to `topic` (via `ws.subscribe(topic)`).\n * In-process and **single-instance** (see {@link TopicRegistry}) - a multi-instance deploy must bridge\n * an external fan-out (Redis, a Durable Object) to this. A no-op when nobody is subscribed.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void;\n private route;\n /**\n * Low-level route registration shared by the inline builder and `implement()`.\n * Captures the server's current `derive`/`decorate` chain into the route - this\n * is the \"compiled\", order-scoped per-route chain.\n */\n register(method: string, path: string, schema: RouteSchema | undefined, handler: (context: never) => unknown): void;\n /** Register a contract/group route batch atomically. Every route captures the same current chain it\n * would capture through {@link register}; no route becomes visible unless the full batch validates.\n *\n * A path ending in optional parameters (`/users/:id?`) is one catalog route per concrete pattern,\n * so reflection, OpenAPI, evidence and the typed client all see ordinary routes. */\n registerBatch(routes: readonly {\n readonly method: string;\n readonly path: string;\n readonly schema: RouteSchema | undefined;\n readonly handler: (context: never) => unknown;\n }[]): void;\n /** Join a group scope's prefix BEFORE compilation, so the pattern, the reflected descriptor, the\n * capability guard, the ledger record, and assurance path matching all see the one served path. */\n private prefixed;\n private prepareRoute;\n /** @internal Symbol-keyed install seam for the `responseContract()` plugin. Off the public typed surface. */\n [INSTALL_RESPONSE_CONTRACT](runtime: ResponseContractRuntime): void;\n /** @internal Symbol-keyed install seam for the response observer plugin. */\n [INSTALL_RESPONSE_OBSERVER](runtime: ResponseObserverRuntime): ResponseObserverMethods;\n /** @internal Symbol-keyed install seam for the `idempotency()` plugin. Off the public typed surface. */\n [INSTALL_IDEMPOTENCY](runtime: IdempotencyRuntime): void;\n /** @internal Symbol-keyed install seam for the `mcp()` plugin. Off the public typed surface. */\n [INSTALL_MCP](runtime: McpRuntime): void;\n /** @internal Symbol-keyed install seam for the `notFound()` plugin. Off the public typed surface. */\n [INSTALL_NOT_FOUND](lane: NotFoundLane): void;\n /** @internal Symbol-keyed install seam for the `nodeDirect()` plugin. Off the public typed surface. */\n [INSTALL_NODE_DIRECT](runtime: NodeOutcomeRuntime): void;\n /** @internal An adapter reports a failure no response hook saw (a hook that threw past `fetch`, a\n * response the runtime refused to write), logged as Bun's `listen()` logs one. */\n [REPORT_ERROR](error: unknown): void;\n /** @internal Symbol-keyed install seam for the `streaming()` plugin. Off the public typed surface. */\n [INSTALL_SSE](runtime: SseRuntime): void;\n /** @internal Symbol-keyed install seam for the `websocket()` plugin. Off the public typed surface. */\n [INSTALL_WS](runtime: WsRuntime): void;\n /**\n * @internal The runtime Bun serves this app's WebSocket upgrades with, asked by `listen()` and by a\n * parent that mounts this app: `undefined` while nothing here can take one, `null` when something\n * can but no runtime is at hand. A mounted Nifra app answers through this same seam, so mounting an\n * app without a WebSocket route needs no runtime; a resolver without the seam cannot say, so it\n * counts. `seen` ends a mount cycle (an app mounted under itself to alias a prefix).\n */\n [GET_WS_RUNTIME](seen?: Set<unknown>): WsRuntime | null | undefined;\n /** The `[GET_WS_RUNTIME]` answer for the apps mounted here alone, whatever this app's own routes. */\n private mountedWsRuntime;\n /** Whether an app mounted here takes WebSocket upgrades. Worked out again only after a `ws()` or a\n * `mount()` somewhere, so the upgrade check on a plain request costs one comparison. */\n private mountsTakeUpgrades;\n /**\n * Merge another server's routes into this one - the composition escape hatch for large apps.\n *\n * WHY: the fluent chain accumulates one type-alias level per route, and TypeScript resolves\n * that stack in one recursion - a single chain hits TS2589 at ~95 routes. Groups keep every\n * chain short: build each domain (`listings`, `agents`, …) as its own `server()` (its registry\n * resolves independently), then `app.merge(listings).merge(agents)` - each merge adds ONE level\n * regardless of group size. 300+ routes stay fully typed (see many-routes.test-d.ts). The\n * other escape hatch is contract-first `implement()`, whose registry is a single object type.\n *\n * Semantics: merged routes keep the chains captured where they were DEFINED - the group's\n * `derive`/`decorate`/`beforeHandle`/`afterHandle`/`onError`/`around` apply to its routes\n * exactly as they did standalone, so a group wires its own plugins. The same locality rule\n * covers the group's `onRequest` hooks: they run only for requests that route to the GROUP's\n * routes, and for an `OPTIONS` preflight to a path they serve (a `bodyLimit()` mounted on an uploads group must not start gating the whole app\n * because the app composed it in), and the group's global assurance follows its hooks onto\n * exactly those routes. A group with hooks but NO routes is a middleware bundle - its hooks\n * can only mean app-wide intent, so they are appended globally, unchanged. Response-side hooks\n * (`onResponse`/`onResponseFinalized`) are appended to this server's. This server's\n * route-scoped chains do NOT retroactively wrap merged routes (order-scoped, like routes\n * registered before a `derive`). Fail closed: a path+method collision throws\n * `RouteConfigError` at merge time, and a group with WebSocket routes or mounts is refused\n * (register those on the parent).\n *\n * What this server's `.use()`, made BEFORE the merge, covers on a merged route versus a\n * `group()` route:\n *\n * | installed on this server | group() route | merge()d route |\n * | ------------------------------------------ | ------------- | ------------------------------ |\n * | derive/decorate/beforeHandle/afterHandle, | yes | no - wire it on the merged |\n * | onError/around, authenticate, route-scoped | | server |\n * | assurance | | |\n * | onRequest/onResponse/responseHeaders hooks | yes | yes (app-wide) |\n * | responseContract() | yes | yes, when the route declares a |\n * | | | response and its own server |\n * | | | installed no contract |\n * | effectLedger() | yes | yes, when the route declares |\n * | | | capabilities and has no ledger |\n * | idempotency() | yes | the merged server's own; a |\n * | | | route declaring it without one |\n * | | | is refused at registration |\n *\n * The response contract and the ledger can only add a check or a record, so a merged route is\n * recompiled under them. A runtime installed AFTER the merge covers neither kind of route.\n *\n * In development, {@link ServerOptions.unusedScopedHooks} reports a hook followed only by merges and\n * a contract or ledger installed after the routes it would cover; `nifra check` reports a merge whose\n * server authenticates none of its routes under this server's `authenticate()` (NF-C043).\n */\n merge<R2 extends Registry, Ctx2, HookOutput2>(other: Server<R2, Ctx2, HookOutput2>): Server<R & R2, Ctx, HookOutput>;\n /**\n * Declare routes under a static path prefix, with the prefix in the typed client, `routes()`,\n * OpenAPI, capability events, and the effect ledger - the counterpart of Hono's `route()`,\n * Elysia's `group()`, and Fastify's `register({ prefix })`.\n *\n * app\n * .derive(session)\n * .group(\"/admin\", (admin) =>\n * admin.beforeHandle(requireAdmin).get(\"/users\", listUsers).get(\"/users/:id\", getUser),\n * )\n * .get(\"/\", home) // not covered by requireAdmin\n *\n * The builder receives a scope that INHERITS this server's route chain as it stands at the call\n * (`derive`/`decorate`/`authenticate`/`beforeHandle`/`afterHandle`/`onError`/`around`, assurance,\n * capability interceptors, installed runtimes, applied plugins), exactly as a route declared here\n * would. {@link merge} documents how that differs for a merged server. A plugin this server already applied is in effect for the group: the group's `use()` of\n * that same instance does nothing, and its `use()` of another instance under the same name throws a\n * `RouteConfigError` (`PLUGIN_RECONFIGURED`), because that instance could never replace the parent's.\n * A plugin the group applies still shares the parent's copy of a dependency it `use()`s itself.\n * What it adds stays in the group: its chain additions apply only to its own routes, and its\n * request/response hooks (`onRequest`, `onResponse`, `responseHeaders`, `onResponseFinalized`, and\n * middleware bundles that use them) run only for requests whose path is the prefix or below it.\n * Per-route authorization belongs in `authenticate`/`beforeHandle`, which are compiled into each\n * route; request hooks are path prefilters.\n *\n * The prefix is static text - `\"/api\"`, `\"/api/v1\"` - validated when declared: no params,\n * wildcards, empty or dot segments, percent-escapes, or trailing slash. A group's `\"/\"` route\n * serves the prefix itself. Groups nest (`\"/api\"` then `\"/v1\"` serves `/api/v1/...`).\n *\n * Fail closed: the builder must synchronously return the scope it was given; a collision with an\n * existing route throws `RouteConfigError` and adds none of the group's routes; `.ws()`, mounts,\n * MCP `.tool()`s, and `merge()` inside a group are refused (register them on the parent). Once the\n * builder returns, the scope is closed - a leaked reference cannot add routes later.\n */\n group<const P extends string, R2 extends Registry, Ctx2, HookOutput2>(prefix: P, build: (group: Server<EmptyRegistry, Ctx, HookOutput>) => Server<R2, Ctx2, HookOutput2>): Server<R & PrefixRegistry<P, R2>, Ctx, HookOutput>;\n /**\n * Take over another server's routes and hooks - the shared core of {@link merge} and {@link group}.\n * `prefix` selects group semantics: hooks are scoped to requests under the prefix (response hooks\n * included), and the source's global assurance past `inheritedGlobal` (what it copied from this\n * server) is folded into its routes. Without a prefix, merge semantics: request hooks are scoped to\n * the source's routes when it has any, response hooks are appended app-wide.\n */\n private adopt;\n /** A fused renderer closes over runtime services to keep its seven-argument JSC fast path. Merging\n * rebinds that closure once to the executing server; generic plans already receive the runtime. */\n private bindFusedRuntime;\n /**\n * Enumerate the registered routes (method, path, input schemas), in registration\n * order. Powers `toOpenAPI` and other introspection; the router trie itself no\n * longer holds the original patterns.\n */\n routes(): ReadonlyArray<RouteDescriptor>;\n /**\n * Resolve a `Request` to a `Response` - the whole lifecycle, testable without a port. The\n * optional `platform` carries edge inputs (`env`, `waitUntil`); edge adapters pass it, and\n * Bun/Node/Deno omit it (then `c.env` is `undefined` and `c.waitUntil` runs fire-and-forget).\n */\n fetch(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<Response>;\n private fetchSource;\n private fetchSourceInner;\n /** Web response path when Bun already matched the route. The lifecycle and response hooks remain\n * exactly the same as {@link fetchSource}; only portable URL scanning + trie lookup are skipped. */\n private fetchMatched;\n private fetchMatchedInner;\n /**\n * Run `produce` under the capacity gate: admit → run → release exactly once when the response is\n * produced (or the run throws). Only reached when {@link capacityGate} is set, so the off path pays\n * nothing. The slot is held for the duration of handler execution, not the streaming of the body -\n * capacity here bounds concurrent *work*, matching how in-flight is counted.\n */\n private admitGated;\n private runAdmitted;\n /**\n * Select a mounted handler's native Node lane without materializing a Web Request. This is an\n * adapter seam, not a second lifecycle: any app-wide behavior that the ordinary mount path would\n * run makes the capability ineligible and the caller falls back to `resolveNodeSource`. Typed\n * routes keep precedence exactly as `routeAndRun` does, including the existing mount behavior for\n * a path whose registered route rejects this method.\n */\n [RESOLVE_NODE_MOUNT](source: RequestSource): NativeMountSelection | undefined;\n private firstMountUnder;\n /**\n * Like {@link fetch}, but renders a plain-data result **without** building a Web `Response` - the\n * `@nifrajs/node` adapter serializes the returned primitives straight to the socket, skipping the undici\n * `Response` build + body drain (the bulk of the Node bridge cost, measured ≈4µs/req). A handler that\n * returns a `Response`, an error/short-circuit, or a response hook that replaces/consumes the buffered\n * body stays on the full Web path; an in-place response hook can still use the direct writer. Same\n * lifecycle as {@link fetch} (body cap, validation, hooks all run); only the final render differs.\n */\n resolveNode(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<NodeServeOutcome>;\n resolveNodeSource(source: RequestSource, platform?: Platform<EnvOf<Ctx>>, suppliedRuntime?: NodeOutcomeRuntime): MaybePromise<NodeServeOutcome>;\n /** Run generic Web response middleware while retaining direct writes for untouched buffered bodies. */\n private finishNodeWebResponse;\n /** True only when every transforming Web response hook has a header-only Node equivalent. */\n private canUseNodeResponseHooks;\n /** Apply paired native hooks to data outcomes; preserve the complete Web hook pipeline for Response outcomes. */\n private finishNodeResponse;\n private withNodeResponseHeaders;\n /** Synchronous until a native response hook actually returns a Promise. */\n private applyNodeResponseHooks;\n private continueNodeResponseHooks;\n /**\n * Resolve a WebSocket upgrade - the seam every serving adapter uses. Returns `pass` (not a WS\n * upgrade for a registered route → handle as normal HTTP), `reject` (a WS route matched but\n * `upgrade()` rejected, or the path was malformed → return `response`), or `upgrade` (perform the\n * runtime upgrade, then dispatch the native socket's events to `handler`, seeding `ws.data` with\n * `data`). Runs the route's `upgrade(c)` guard in a real request context. Synchronous unless\n * `upgrade()` is async; a throw rejects with a flat 500 (no detail leaked).\n */\n private runWebSocketRequestHooks;\n private continueWebSocketRequestHooks;\n resolveWebSocketUpgrade(req: Request, platform?: Platform<EnvOf<Ctx>>): MaybePromise<WebSocketUpgradeOutcome>;\n /** Bun `fetch` when WS routes exist: try a WS upgrade first, else run the normal HTTP lifecycle.\n * `undefined` ⇒ Bun owns the upgraded socket; a `Response` ⇒ a normal reply or a rejected upgrade.\n * (The socket dispatch itself lives in `ws-bun.ts`, loaded via `@nifrajs/core/ws`.) */\n private bunFetchWithWebSocket;\n /**\n * The shared lifecycle, generic over how the final value is rendered: `finalize` turns a handler's\n * result + `set` into the output `T` (`toResponse` → a Web `Response`; `toNodeOutcome` → node-direct\n * primitives), `wrapResponse` lifts an early/error `Response` into that same `T`, and `onTimeout`\n * produces the 503. The Web `fetch` and `resolveNode` are thin callers over this one routing +\n * context + lifecycle implementation - no duplication across the trust boundary.\n */\n /** Apply the `clientIp` trust declaration to the adapter's raw socket peer, returning a platform\n * whose `clientIp` is the derived caller. Only called when a trust declaration is configured. */\n private deriveClientIp;\n private trustedPlatform;\n private dispatch;\n /** Node-native request hook walk. A header-only hook can inspect the lazy source without forcing a\n * Web `Request`; arbitrary request rewrites and full Web hooks use {@link runWithOnRequest}. */\n private runWithNodeRequest;\n private continueNodeRequest;\n private canUseNodeRequestHooks;\n /**\n * onRequest short-circuit path. Synchronous as long as every hook returns synchronously (the\n * common case - e.g. CORS returning `undefined` for a non-preflight request): an `async` version\n * here put EVERY request of any app with one onRequest hook onto the promise machinery, profiled\n * at ~13% of a realistic request. The first hook that returns a Promise hands the REMAINING\n * hooks to the async continuation; behavior is identical.\n */\n private runWithOnRequest;\n /** Async tail of {@link runWithOnRequest}: applies the first awaited hook's outcome, then runs\n * the remaining hooks (awaiting freely - we're already async here). */\n private continueOnRequest;\n private takeResponseRequest;\n /**\n * The NodeRequestContext for a source, MEMOIZED per source so the request twins and the response\n * twins receive the exact same object within one request - that identity is the documented\n * contract stateful twins key their WeakMaps on. An adapter source (which already speaks the\n * interface) is returned as-is; a plain `Request` source (a direct `resolveNode` caller) gets one\n * cached wrapper.\n */\n private nodeRequestContextOf;\n /** Preserve the request visible to generic onRequest hooks for paired native response hooks. */\n private takeNodeResponseRequest;\n /**\n * Route → build context → run. Synchronous through to the handler for a **bare** route\n * (selected by its compiled plan), so a sync handler produces its result with zero promise allocations;\n * routes with validation/hooks keep the full compiled route program, unchanged.\n */\n private routeAndRun;\n private fetchMount;\n /** Run a route that has already been matched by the runtime or Nifra's portable router. */\n private runMatched;\n /** Supply request-specific deadline state to the route's precompiled execution plan. */\n private runMatchedLanes;\n /** @internal Symbol-keyed install seam for the `effectLedger()` plugin. Off the public typed surface. */\n [INSTALL_EFFECT_LEDGER](runtime: EffectLedgerRuntime): void;\n /** The narrowest bare route: a syntactic `() => ...` handler cannot observe the context argument, so\n * successful requests can skip allocating `RequestContext`. Errors still allocate one for logging. */\n private runContextlessBare;\n private contextlessBareError;\n /**\n * The synchronous fast path selected by a route's execution plan: apply static decorations, call the\n * handler, render the result - **no `await`** unless the handler itself returns a promise. It mirrors\n * the same error boundary as the compiled route program (which a bare route would otherwise no-op through) and shares\n * {@link logRequestError}; a bare route has no `onError` hooks, so error handling is fully synchronous\n * (a thrown `Response` is control flow; anything else is a logged flat 500). This is where nifra skips\n * the per-request async-frame tax - the same win codegen routers get, but without `eval`.\n */\n private runBare;\n /** Bare-route error rendering - identical to the compiled route program's catch minus the (absent) onError\n * loop: a thrown `Response` is returned as deliberate control flow; anything else is logged + 500. */\n /**\n * Build a route's fused Web renderer. Composition happens once at\n * registration; the returned closure is what every request to the route runs. Behavior is\n * byte-identical to the generic `runBare`/`runContextlessBare` + `toResponse` pair - same\n * decoration order, same error routing (thrown `Response` = control flow; anything else logs and\n * 500s), same respond semantics (the lifecycle parity suite pins it).\n */\n private buildFusedWeb;\n /** A fused Web lane's render in an async continuation, where a result that cannot be rendered\n * must fail like a handler throw; a synchronous render throw reaches {@link runMatchedLanes}. */\n private respondFused;\n /** Compile the eligible body-only route's parser → validator → handler continuation once. The\n * bounded parser remains shared with the generic lane; only the route-invariant entry lookups and\n * lifecycle dispatch disappear from the common synchronous-validator/synchronous-handler case. */\n private buildFusedBodyRunner;\n /** Web adapter wrapper for the shared body runner. Node passes its native finalizer directly through\n * the execution plan, while Web needs the live context to preserve lazy `c.set` controls. */\n private buildFusedBodyWeb;\n /** The fused Web lane for a route whose only lifecycle step is a query schema: parse + validate +\n * handler + respond in one closure, no lifecycle promise when the validator and handler are sync.\n * Eligibility is decided at registration (see `fusedQuery` in {@link register}); the semantics here\n * are exactly `runQueryOnly`'s for that eligible shape - invalid input returns\n * `validationError(issues)` (recovery hooks disqualify the route from this lane), a thrown\n * `Response` passes through, anything else logs and returns a flat 500, and an async validator\n * falls to a then-chain with the same steps. */\n private buildFusedQueryWeb;\n /**\n * Compile a route's `derive + before` lifecycle to a single closure: the per-request walk through\n * `runSync` → `runHooksSync` is a stack of 3 frames and 2 `Object.assign`s for what is by far the\n * most common middleware shape (auth/trace/id derivation, an auth/policy `beforeHandle`). Folding\n * the same steps into one closure hits the same monomorphic inline-cache site as `buildFusedWeb`,\n * and `Object.assign(ctx, deriveResult)` becomes one extra property write on the context's already\n * hot hidden class. Behavior is byte-identical to the compiled route program: the same thrown-value\n * contract (`Response` is control flow, anything else logs + 500), the same `c.set` semantics, the\n * same `fusedRespond` for the rendered body. The `LifecycleExecutionLane` guarantee\n * (`schema.params === undefined && schema.headers === undefined && derives === 1 &&\n * beforeHandle === 1 && afterHandle === 0 && onError === 0 && !hasResponseContract &&\n * !hasDecorations`) is enforced by `selectRouteLanes`; this lane is selected ONLY when all of those\n * hold. A `query` schema (the route declares `{ query }` alongside the hooks) is validated FIRST,\n * mirroring the compiled route program's stage order; the fused builder runs validate → derive →\n * before → handler in one frame.\n */\n private buildFusedDeriveBefore;\n private buildFusedDeriveBeforeAfter;\n /**\n * Body + lifecycle hooks fused: parse → validate → derive → before → handler → (after) in one\n * closure, the same win `buildFusedBodyRunner` gives for the no-hooks body shape. The shape is\n * `lifecycleHookLane` PLUS a body schema with no other validation conflicts; the lane is selected\n * ONLY when `schema.body !== undefined && schema.query/params/headers === undefined &&\n * schema.onValidationError === undefined && !defaultOnValidationError && !hasIdempotency &&\n * !hasLedger && derives === 1 && beforeHandle === 1 && afterHandle <= 1 && onError === 0 &&\n * !hasResponseContract && !hasDecorations && around === 0`. The same single `querySchema === undefined`\n * trick used in the no-body lane lets the build path stay simple: a query + body route falls back\n * to the generic program (this is rare in practice - validated query + validated body is usually a\n * \"search results\" route with a middleware chain on top, and the generic lane is fine there).\n */\n private buildFusedBodyDeriveBeforeAfter;\n /**\n * Generic (finalize/wrapResponse-parameterized) fused runner for the derive-before(-after) lane:\n * the Node-direct counterpart of `buildFusedDeriveBefore` / `buildFusedDeriveBeforeAfter`.\n *\n * The Web fused builders above return a `Response`, so the Node dispatcher (`webFast === false`)\n * cannot use them and a derive+before route falls back to the generic route program there - two\n * staged loops, per-stage dispatch, and the async-continuation machinery - while Bun rides the\n * single closure. That asymmetry is the realistic-route Node deficit against Fastify: this runner\n * closes it by running validate → derive → before → handler → (after) in one frame and finalizing\n * through the caller's own `finalize` (the Node outcome on the direct lane, `toResponse` on Web),\n * so the same registration feeds both runtimes with no per-lane copy of the lifecycle to drift.\n *\n * Semantics mirror the generic program stage-for-stage for the shapes this lane admits (exactly\n * one derive, one beforeHandle, zero-or-one afterHandle, no onError/around/decorations/contracts/\n * recovery hooks - enforced by `selectRouteLanes`): thrown `Response`/`status(...)` are control\n * flow through `wrapResponse`/`finalize`, anything else logs + 500s via the shared `bareError`\n * lane (identical to `handleLifecycleError` with no `onError` hooks), and a terminal `finalize`\n * throw (e.g. an unstringifiable handler return on the Node lane) is caught exactly as\n * `finishLifecycleContract` catches it. Step functions close over registration state only and take\n * the request state as arguments, so the hot path allocates no per-request closures.\n */\n private buildFusedDeriveBeforeRunner;\n /**\n * Generic fused runner for the body+derive-before(-after) lane: the Node-direct counterpart of\n * `buildFusedBodyDeriveBeforeAfter`. Same contract as `buildFusedDeriveBeforeRunner` above - one\n * frame running parse → validate → derive → before → handler → (after) through the caller's own\n * `finalize` - with the body read ahead of validation, exactly as the generic program orders its\n * body stage before the derive/before stages. `readBodyFramed` keeps the shared bounded-read,\n * content-type, and prototype-poisoning contracts; the 415/400 renders take `wrapResponse`\n * directly, which is what the generic lane's wrap-after-identity amounts to.\n */\n private buildFusedBodyDeriveBeforeAfterRunner;\n private bareError;\n /**\n * Keep the ordinary thrown-error response independent from the caught value. Deliberate Response\n * control flow is handled by `renderBareError`; every other throw gets this fixed public envelope.\n */\n private internalErrorResponse;\n private runWithAround;\n /** Execute the registration-compiled general stage program. */\n private runProgram;\n /** Bind a compiled validation stage to its stable schema and the existing recovery contract. */\n private validateProgramStage;\n /** Preserve the existing bounded body reader and its fail-closed framing/prototype checks. */\n private readProgramBody;\n /** Keep thrown Response/status and redacted 500 semantics in one existing error boundary. */\n private handleProgramError;\n /** Finish a successful program result through response-contract enforcement and finalization. */\n private finishProgramResult;\n private runAround;\n private runBodyOnly;\n /** Validate + run the handler for the bodyOnly path - shared by the inline fast path and the\n * streaming fallback. A method (not per-request closures) so the hot path allocates nothing\n * beyond the one `.then` continuation. */\n private finishBodyOnly;\n private executeHandler;\n private handleValidationErrorRecovery;\n private applyBodyValidation;\n private runQueryOnly;\n /** Validate-result → set `ctx.query` → run handler. A method (not a per-request closure), the\n * query analogue of {@link applyBodyValidation}. */\n private applyQueryValidation;\n /**\n * Thread the response through each global `onResponse` hook. Stays SYNCHRONOUS until a hook\n * actually returns a Promise - an `async` version forced a promise + microtask on EVERY response\n * of any app with an onResponse hook (cors/securityHeaders/etag/timing all use onResponse), the\n * same ~13%/req tax the onRequest walk was de-async'd to avoid. The first async hook hands the\n * rest to {@link continueOnResponse}.\n */\n private applyOnResponse;\n private applyOnResponseAndFinalize;\n private completeResponseFinalization;\n private failResponseFinalization;\n /** Notify terminal observers in order while isolating both sync and async failures. */\n private notifyResponseFinalized;\n /** Async tail of {@link applyOnResponse}: runs the remaining hooks once one has gone async. */\n private continueOnResponse;\n /**\n * Bound the response time. On timeout we abort `ctx.signal` (so cancellation-aware\n * handlers can bail) and return 503; the in-flight work keeps running but its\n * result is discarded - JS can't forcibly cancel a promise.\n */\n private withTimeout;\n private finishLifecycleContract;\n private finishContractOutcome;\n /** Synchronous by design, and `MaybePromise` rather than `Promise` for the same reason: control flow\n * out of a lifecycle stage must not cost a promise. An `async` method allocates one and defers the\n * result a microtask even when every branch it takes returns immediately, which is the common case\n * here - a thrown `status(...)`/`Response`, or a route with no `onError` hook at all. Only the hook\n * loop, which may await, drops into {@link runErrorHooks}. */\n private handleLifecycleError;\n /** An `onRequest` hook threw or rejected. No route has matched, so every `onError` the app holds\n * answers it, with a route-less context; otherwise the logged default 500, as for a handler. */\n private onRequestFailure;\n /** The `onError` chain, split off {@link handleLifecycleError} so its `await` costs only the routes\n * that registered a hook. A hook may return a custom response; otherwise the default 500 stands.\n * Never rejects: nothing outside it re-enters `onError`, so a hook that throws, or an answer that\n * cannot be rendered, is logged and answered here. */\n private runErrorHooks;\n /** Log an unhandled request error to the (redacting) logger - shared by the compiled route program and the\n * bare fast path ({@link bareError}) so both record the same fields. Never throws; never leaks. */\n private logRequestError;\n private readAndValidateBody;\n /** Apply validation and its recovery hook on the generic lifecycle lane. Recovery is completed\n * before derives/beforeHandle run, matching the body-only and query-only execution lanes. */\n private applyLifecycleValidation;\n private finishLifecycleValidationRecovery;\n /** Adapt one route's compiled execution plan to Bun's already-matched request shape. Route\n * semantics remain in the plan; this closure only supplies native params and deadline fallback. */\n private compileBunNativeHandler;\n /** Compile portable route registrations into Bun's native route table. Apps with request-rewrite\n * hooks or WebSockets retain the single portable dispatcher because those features must run before\n * route selection/upgrade.\n *\n * Bun and the portable router agree on which of two static-and-`:param` paths wins a request, so\n * the table is kept to those paths. Where Bun would otherwise pass a request on to a less specific\n * path, the more specific one carries `fallback`, the portable dispatcher, under that method.\n * `peer` is the platform every request served from the table shares. */\n private buildBunNativeRoutes;\n /**\n * Start a `Bun.serve` instance bound to `port` (use `0` for an ephemeral port).\n *\n * `reusePort` sets `SO_REUSEPORT` so **multiple processes can bind the same port** and the kernel\n * load-balances connections across them - the standard way to use every core (Bun is\n * single-threaded per process). Spawn one process per core, each calling\n * `app.listen(PORT, { reusePort: true })`; see `examples/cluster.ts`. Every process must opt in,\n * and all of them must be the same app. Linux balances ~evenly; macOS accepts the flag but may\n * favor one socket (fine for dev, measure on Linux for production numbers).\n *\n * `hostname` is the bind address, defaulting to Bun's `0.0.0.0` (every interface). Pass\n * `\"127.0.0.1\"` to bind loopback only - an admin surface, a sidecar, or anything that must not be\n * reachable off the box. Omitting it when you meant to restrict is a real exposure, so it is a\n * first-class option rather than something a caller has to drop down to `Bun.serve` for.\n *\n * `idleTimeoutSec` is how long Bun tolerates a connection with no bytes moving before it closes\n * the socket. Bun's default is **10 seconds**, and a request whose handler is still working sends\n * nothing - so any endpoint slower than 10s (a render, an export, a long upstream call) has its\n * connection cut mid-flight regardless of `requestTimeoutMs`. Apps with such endpoints must raise\n * this above their slowest expected response, which is why it is a first-class option and not a\n * reason to drop down to `Bun.serve`. `0` disables the timeout entirely; max 255.\n *\n * `tls` serves HTTPS directly: `app.listen(443, { tls: { cert, key } })` with PEM text or bytes.\n * Requests then arrive with `https:` URLs. Behind a proxy or a platform that terminates TLS, leave\n * it unset.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n readonly idleTimeoutSec?: number;\n readonly tls?: ListenTlsOptions;\n }): RunningServer;\n /**\n * Gracefully stop: wait for in-flight requests to finish (up to `drainMs`), then\n * issue a single terminal stop - graceful if everything drained, forced if\n * stragglers remain. Safe to call when not listening.\n *\n * The Bun semantics: poll `pendingRequests` (awaiting\n * `stop()`'s promise drops in-flight requests), and decide graceful-vs-forced in\n * ONE call (Bun can't escalate an already-graceful `stop()` to a forced close).\n * New connections may be accepted during the drain window; in a real deploy the\n * load balancer has already stopped routing here, and `drainMs` bounds it. Open WebSockets\n * get a 1001 close at once and the same window to finish it, before any `onStop` hook runs.\n */\n stop({ drainMs }?: {\n drainMs?: number;\n }): Promise<void>;\n private installSignalHandlers;\n}",
|
|
14098
14171
|
"doc": "/**\n * The inline server. Routes are chainable and fully type-inferred. `derive`/\n * `decorate` extend the handler context (`Ctx`) for routes defined *after* them,\n * with full types; `Ctx` is server-only and never touches the client registry.\n *\n * app.decorate(\"db\", db).derive((c) => ({ user: auth(c) }))\n * .get(\"/me\", (c) => c.user) // c.user + c.db are typed\n */"
|
|
14099
14172
|
},
|
|
14100
14173
|
{
|
|
@@ -14335,13 +14408,13 @@
|
|
|
14335
14408
|
"name": "ServerOptions",
|
|
14336
14409
|
"kind": "interface",
|
|
14337
14410
|
"package": "@nifrajs/core",
|
|
14338
|
-
"signature": "export interface ServerOptions {\n /**\n * Max request body size (bytes), the default transport cap for every route. Default 1_000_000.\n * A route can choose a finite `schema.bodyLimit` of its own; an explicit `'unlimited'` route\n * requires `schema.bodyLimitReason` and is intended only for a separately bounded streaming or\n * upload integration.\n *\n * Framework readers (the body-schema lane, `c.boundedJson`) enforce the cap when they read. A\n * route WITHOUT a body schema (raw body, file upload, BYO-validation) is covered too: direct\n * `c.req` reads (`json()`, `arrayBuffer()`, the raw `body` stream, ...) are capped in place -\n * lazily, nothing is buffered until code actually reads - and answer 413 past the limit.\n * `c.boundedBody(n)` states its own explicit per-read limit, above or below the route's cap.\n */\n readonly maxBodyBytes?: number;\n /**\n * Prototype-poisoning policy for JSON bodies (the schema path and `c.boundedJson`). An own\n * `__proto__` key, or a `constructor` carrying a `prototype`, is the payload shape that turns a\n * later innocent merge/assign into prototype pollution. `\"reject\"` (default) answers the same\n * flat 400 as malformed JSON; `\"strip\"` removes the offending keys and continues; `\"ignore\"`\n * parses as-is (only for routes that never merge body input into other objects). Every guarded\n * payload pays one iterative pass over its parsed object nodes; `\"ignore\"` skips it.\n */\n readonly protoPoisoning?: \"reject\" | \"strip\" | \"ignore\";\n /**\n * Other sites whose HTML forms may post to a body-schema route: exact origins, or a function that\n * receives the `Origin`. A urlencoded, multipart or `text/plain` body is one a form on any site can\n * send with the visitor's cookies and no preflight, so one whose `Origin` names another site is\n * refused with `403` before it is read. Same-origin posts and requests without an `Origin`, such\n * as server-to-server calls, pass. JSON is not affected: a browser preflights it, so CORS decides.\n */\n readonly formOrigins?: ReadonlyArray<string> | ((origin: string) => boolean);\n /**\n * Declare that every `Request` reaching `app.fetch` was framed by a runtime HTTP parser, so its\n * `Content-Length` is an exact transport boundary rather than a hint. Set this ONLY when the\n * runtime's own request object is handed through untouched with no adapter in between to mark it -\n * a bare `export default app` on an edge runtime. Every supported ingress already marks itself:\n * `listen()` on Bun, `toFetchHandler(app)` on Workers/edge, `@nifrajs/deno`, and `@nifrajs/node`\n * (which reads exact bytes and never needs the mark). Reach for this option only for an ingress\n * nifra does not ship an adapter for.\n *\n * Left off (default), the JSON body lane copies the body out and enforces the cap on DELIVERED\n * bytes, because an unmarked request may have been rebuilt by an adapter that kept a caller's\n * `content-length` while decoding a payload of a different size. That check costs an extra pass\n * over the body, which is why an edge deployment that cannot be lied to may opt out of it.\n *\n * Do not set this on an app whose `fetch` is also called with `Request`s assembled from\n * untrusted input.\n */\n readonly trustBodyFraming?: boolean;\n /**\n * Max inbound WebSocket message size (bytes). A larger message never reaches the handler and the\n * socket closes with `1009`. Default: `maxBodyBytes` (1 MB). Bun and Node stop buffering at the cap,\n * so a huge frame is never held in memory; on Bun a mounted app's smaller cap, and on Deno and\n * Workers every cap, is checked after the runtime has buffered the whole message.\n */\n readonly wsMaxPayloadBytes?: number;\n /** Per-request timeout (ms): a slower request gets a 503 and `ctx.signal` aborts. 0 disables (default). */\n readonly requestTimeoutMs?: number;\n /** WebSocket upgrade admission/guard timeout (ms). Default 10_000; set to 0 only for a deliberate unbounded guard. */\n readonly wsUpgradeTimeoutMs?: number;\n /**\n * How to derive `c.clientIp` behind a reverse proxy or CDN. Omit (default) to trust only the raw\n * socket peer and never believe a forwarded header. Set `{ trustedHops: n }` when the app sits\n * behind `n` proxies you operate (the caller is read from `X-Forwarded-For` past those hops), or\n * `{ header: name }` to trust one edge-set header's first value. Declaring trust the app can't\n * actually enforce lets clients forge their IP, so leave it unset unless a proxy really fronts you.\n */\n readonly clientIp?: ClientIpTrust;\n /**\n * Admit the public `x-nifra-deadline` header and let it shorten local work. Disabled by default:\n * services that participate in trusted cross-service deadline propagation opt in explicitly,\n * while ordinary/public HTTP routes pay no header-admission tax and ignore hostile client values.\n */\n readonly acceptInboundDeadlines?: boolean;\n /**\n * Maximum time accepted from an inbound `x-nifra-deadline`, in milliseconds. An incoming absolute\n * deadline may shorten this cap (and `requestTimeoutMs`, when configured), never extend it.\n * Default 30_000; applies only when `acceptInboundDeadlines` is enabled and the header is present.\n */\n readonly maxInboundDeadlineMs?: number;\n /**\n * When `listen()`ing, install SIGTERM/SIGINT handlers that gracefully `stop()`. Default false.\n * `{ drainMs }` sets how long in-flight requests get to finish before the stop forces them closed\n * (default 10_000) - keep it under the platform's kill grace period (`docker stop` waits 10 s).\n */\n readonly gracefulSignals?: boolean | {\n readonly drainMs?: number;\n };\n /**\n * Capacity-admission gate (see {@link AdmissionController}). Bounds concurrent in-flight work so a\n * healthy instance sheds load (`429` + `Retry-After`) instead of accepting more than it can finish.\n * Off by default. Enabling it disables the fused native-route fast path (requests route through the\n * shared matched lane where the gate runs); when unset, the request path pays nothing.\n */\n readonly admission?: AdmissionController;\n /**\n * Optional token-only observation hook called by `useCapability(c, id)`. It receives no request,\n * parameters, body, tenant, or values. Routes without capability declarations keep the old hot path.\n */\n readonly onCapabilityUse?: (event: CapabilityUseEvent) => void;\n /** Structured logger for framework events (redacts secrets). Default: JSON to stderr. */\n readonly logger?: Logger;\n /**\n * How much of an unhandled error reaches the log for a 500. Never reaches the client either way -\n * the response is always a bare `internal_error`.\n *\n * - `\"full\"` (default) - `name`, the error's own text as `detail`, and `stack`.\n * - `\"message\"` - `name` and `detail`, no stack.\n * - `\"none\"` - `name` only.\n *\n * An error's text can quote the input that produced it, which is how request data ends up in a log\n * sink. The framework's answer is the redacting logger rather than blanket suppression: pass\n * `logger: jsonLogger({ valuePatterns: commonSecretPatterns })` to scrub tokens, JWTs, and emails\n * out of `detail` and `stack` while keeping the diagnosis. Reach for `\"none\"` when the sink itself\n * is the thing you don't trust.\n */\n readonly errorLogDetail?: \"full\" | \"message\" | \"none\";\n /**\n * App-wide fallback fired when a route **without its own `onValidationError`** fails body/query\n * validation. Same contract as the per-route hook (`(issues, ctx, kind) => Response | repaired-value |\n * undefined`): a route's own hook takes precedence, and a route can fall through to the plain `422` by\n * returning `undefined`. Use it for one app-wide error envelope (like tRPC's `errorFormatter` /\n * Fastify's `setErrorHandler`) instead of repeating a formatter per route.\n */\n readonly onValidationError?: RouteSchema[\"onValidationError\"];\n /**\n * What to do when an order-scoped hook (`derive`/`authenticate`/`beforeHandle`/`around`/\n * `aroundCapability`/`afterHandle`/`onError`/`decorate`) covers no route because it was added after\n * the last route was registered. `register()` snapshots the current chain into each route as it is\n * declared, so a hook appended after every route reaches nothing and is silently dead. A `merge()`d\n * route keeps the chain of the server that declared it, so a hook followed only by merges is dead\n * too. The same report covers `responseContract()` and `effectLedger()` installed after routes they\n * would have covered (a declared response, declared capabilities). `\"warn\"` (default) logs once at\n * seal (first `listen()`/`fetch`/`resolveNode`); `\"error\"` throws a `FrameworkError`\n * (`UNUSED_SCOPED_HOOKS`); `\"off\"` skips the bookkeeping entirely, including the one-frame stack\n * capture. App-global hooks (`onRequest`/`onResponse`/...) are unaffected in every mode.\n *\n * This is a development-time diagnostic: the whole audit is guarded by `process.env.NODE_ENV !==\n * \"production\"`, so any bundler that defines `NODE_ENV` (vite/esbuild/webpack/next, `bun build\n * --production`) dead-code-eliminates it, leaving zero bytes and zero per-request cost in the shipped\n * bundle. It fires in development, test, and CI - where you catch the mistake - not in production.\n */\n readonly unusedScopedHooks?: \"warn\" | \"error\" | \"off\";\n}"
|
|
14411
|
+
"signature": "export interface ServerOptions {\n /**\n * Max request body size (bytes), the default transport cap for every route. Default 1_000_000.\n * A route can choose a finite `schema.bodyLimit` of its own; an explicit `'unlimited'` route\n * requires `schema.bodyLimitReason` and is intended only for a separately bounded streaming or\n * upload integration.\n *\n * Framework readers (the body-schema lane, `c.boundedJson`) enforce the cap when they read. A\n * route WITHOUT a body schema (raw body, file upload, BYO-validation) is covered too: direct\n * `c.req` reads (`json()`, `arrayBuffer()`, the raw `body` stream, ...) are capped in place -\n * lazily, nothing is buffered until code actually reads - and answer 413 past the limit.\n * `c.boundedBody(n)` states its own explicit per-read limit, above or below the route's cap.\n */\n readonly maxBodyBytes?: number;\n /**\n * Prototype-poisoning policy for JSON bodies (the schema path and `c.boundedJson`). An own\n * `__proto__` key, or a `constructor` carrying a `prototype`, is the payload shape that turns a\n * later innocent merge/assign into prototype pollution. `\"reject\"` (default) answers the same\n * flat 400 as malformed JSON; `\"strip\"` removes the offending keys and continues; `\"ignore\"`\n * parses as-is (only for routes that never merge body input into other objects). Every guarded\n * payload pays one iterative pass over its parsed object nodes; `\"ignore\"` skips it.\n */\n readonly protoPoisoning?: \"reject\" | \"strip\" | \"ignore\";\n /**\n * Other sites whose HTML forms may post to a body-schema route: exact origins, or a function that\n * receives the `Origin`. A urlencoded, multipart or `text/plain` body is one a form on any site can\n * send with the visitor's cookies and no preflight, so one whose `Origin` names another site is\n * refused with `403` before it is read. Same-origin posts and requests without an `Origin`, such\n * as server-to-server calls, pass. JSON is not affected: a browser preflights it, so CORS decides.\n */\n readonly formOrigins?: ReadonlyArray<string> | ((origin: string) => boolean);\n /**\n * Declare that every `Request` reaching `app.fetch` was framed by a runtime HTTP parser, so its\n * `Content-Length` is an exact transport boundary rather than a hint. Set this ONLY when the\n * runtime's own request object is handed through untouched with no adapter in between to mark it -\n * a bare `export default app` on an edge runtime. Every supported ingress already marks itself:\n * `listen()` on Bun, `toFetchHandler(app)` on Workers/edge, `@nifrajs/deno`, and `@nifrajs/node`\n * (which reads exact bytes and never needs the mark). Reach for this option only for an ingress\n * nifra does not ship an adapter for.\n *\n * Left off (default), the JSON body lane copies the body out and enforces the cap on DELIVERED\n * bytes, because an unmarked request may have been rebuilt by an adapter that kept a caller's\n * `content-length` while decoding a payload of a different size. That check costs an extra pass\n * over the body, which is why an edge deployment that cannot be lied to may opt out of it.\n *\n * Do not set this on an app whose `fetch` is also called with `Request`s assembled from\n * untrusted input.\n */\n readonly trustBodyFraming?: boolean;\n /**\n * Max inbound WebSocket message size (bytes). A larger message never reaches the handler and the\n * socket closes with `1009`; when Bun's own frame limit refuses it, Bun drops the connection and the\n * client sees `1006`, while the `close` handler still gets `1009`. Default: `maxBodyBytes` (1 MB).\n * Bun and Node stop buffering at the cap, so a huge frame is never held in memory; on Bun a mounted\n * app's smaller cap, and on Deno and Workers every cap, is checked after the runtime has buffered\n * the whole message.\n */\n readonly wsMaxPayloadBytes?: number;\n /** Per-request timeout (ms): a slower request gets a 503 and `ctx.signal` aborts. 0 disables (default). */\n readonly requestTimeoutMs?: number;\n /** WebSocket upgrade admission/guard timeout (ms). Default 10_000; set to 0 only for a deliberate unbounded guard. */\n readonly wsUpgradeTimeoutMs?: number;\n /**\n * How to derive `c.clientIp` behind a reverse proxy or CDN. Omit (default) to trust only the raw\n * socket peer and never believe a forwarded header. Set `{ trustedHops: n }` when the app sits\n * behind `n` proxies you operate (the caller is read from `X-Forwarded-For` past those hops), or\n * `{ header: name }` to trust one edge-set header's first value. Declaring trust the app can't\n * actually enforce lets clients forge their IP, so leave it unset unless a proxy really fronts you.\n */\n readonly clientIp?: ClientIpTrust;\n /**\n * Admit the public `x-nifra-deadline` header and let it shorten local work. Disabled by default:\n * services that participate in trusted cross-service deadline propagation opt in explicitly,\n * while ordinary/public HTTP routes pay no header-admission tax and ignore hostile client values.\n */\n readonly acceptInboundDeadlines?: boolean;\n /**\n * Maximum time accepted from an inbound `x-nifra-deadline`, in milliseconds. An incoming absolute\n * deadline may shorten this cap (and `requestTimeoutMs`, when configured), never extend it.\n * Default 30_000; applies only when `acceptInboundDeadlines` is enabled and the header is present.\n */\n readonly maxInboundDeadlineMs?: number;\n /**\n * When `listen()`ing, install SIGTERM/SIGINT handlers that gracefully `stop()`. Default false.\n * `{ drainMs }` sets how long in-flight requests get to finish before the stop forces them closed\n * (default 10_000) - keep it under the platform's kill grace period (`docker stop` waits 10 s).\n */\n readonly gracefulSignals?: boolean | {\n readonly drainMs?: number;\n };\n /**\n * Capacity-admission gate (see {@link AdmissionController}). Bounds concurrent in-flight work so a\n * healthy instance sheds load (`429` + `Retry-After`) instead of accepting more than it can finish.\n * Off by default. Enabling it disables the fused native-route fast path (requests route through the\n * shared matched lane where the gate runs); when unset, the request path pays nothing.\n */\n readonly admission?: AdmissionController;\n /**\n * Optional token-only observation hook called by `useCapability(c, id)`. It receives no request,\n * parameters, body, tenant, or values. Routes without capability declarations keep the old hot path.\n */\n readonly onCapabilityUse?: (event: CapabilityUseEvent) => void;\n /** Structured logger for framework events (redacts secrets). Default: JSON to stderr. */\n readonly logger?: Logger;\n /**\n * How much of an unhandled error reaches the log for a 500. Never reaches the client either way -\n * the response is always a bare `internal_error`.\n *\n * - `\"full\"` (default) - `name`, the error's own text as `detail`, and `stack`.\n * - `\"message\"` - `name` and `detail`, no stack.\n * - `\"none\"` - `name` only.\n *\n * An error's text can quote the input that produced it, which is how request data ends up in a log\n * sink. The framework's answer is the redacting logger rather than blanket suppression: pass\n * `logger: jsonLogger({ valuePatterns: commonSecretPatterns })` to scrub tokens, JWTs, and emails\n * out of `detail` and `stack` while keeping the diagnosis. Reach for `\"none\"` when the sink itself\n * is the thing you don't trust.\n */\n readonly errorLogDetail?: \"full\" | \"message\" | \"none\";\n /**\n * App-wide fallback fired when a route **without its own `onValidationError`** fails body/query\n * validation. Same contract as the per-route hook (`(issues, ctx, kind) => Response | repaired-value |\n * undefined`): a route's own hook takes precedence, and a route can fall through to the plain `422` by\n * returning `undefined`. Use it for one app-wide error envelope (like tRPC's `errorFormatter` /\n * Fastify's `setErrorHandler`) instead of repeating a formatter per route.\n */\n readonly onValidationError?: RouteSchema[\"onValidationError\"];\n /**\n * What to do when an order-scoped hook (`derive`/`authenticate`/`beforeHandle`/`around`/\n * `aroundCapability`/`afterHandle`/`onError`/`decorate`) covers no route because it was added after\n * the last route was registered. `register()` snapshots the current chain into each route as it is\n * declared, so a hook appended after every route reaches nothing and is silently dead. A `merge()`d\n * route keeps the chain of the server that declared it, so a hook followed only by merges is dead\n * too. The same report covers `responseContract()` and `effectLedger()` installed after routes they\n * would have covered (a declared response, declared capabilities). `\"warn\"` (default) logs once at\n * seal (first `listen()`/`fetch`/`resolveNode`); `\"error\"` throws a `FrameworkError`\n * (`UNUSED_SCOPED_HOOKS`); `\"off\"` skips the bookkeeping entirely, including the one-frame stack\n * capture. App-global hooks (`onRequest`/`onResponse`/...) are unaffected in every mode.\n *\n * This is a development-time diagnostic: the whole audit is guarded by `process.env.NODE_ENV !==\n * \"production\"`, so any bundler that defines `NODE_ENV` (vite/esbuild/webpack/next, `bun build\n * --production`) dead-code-eliminates it, leaving zero bytes and zero per-request cost in the shipped\n * bundle. It fires in development, test, and CI - where you catch the mistake - not in production.\n */\n readonly unusedScopedHooks?: \"warn\" | \"error\" | \"off\";\n}"
|
|
14339
14412
|
},
|
|
14340
14413
|
{
|
|
14341
14414
|
"name": "ServerOptions",
|
|
14342
14415
|
"kind": "interface",
|
|
14343
14416
|
"package": "nifra",
|
|
14344
|
-
"signature": "export interface ServerOptions {\n /**\n * Max request body size (bytes), the default transport cap for every route. Default 1_000_000.\n * A route can choose a finite `schema.bodyLimit` of its own; an explicit `'unlimited'` route\n * requires `schema.bodyLimitReason` and is intended only for a separately bounded streaming or\n * upload integration.\n *\n * Framework readers (the body-schema lane, `c.boundedJson`) enforce the cap when they read. A\n * route WITHOUT a body schema (raw body, file upload, BYO-validation) is covered too: direct\n * `c.req` reads (`json()`, `arrayBuffer()`, the raw `body` stream, ...) are capped in place -\n * lazily, nothing is buffered until code actually reads - and answer 413 past the limit.\n * `c.boundedBody(n)` states its own explicit per-read limit, above or below the route's cap.\n */\n readonly maxBodyBytes?: number;\n /**\n * Prototype-poisoning policy for JSON bodies (the schema path and `c.boundedJson`). An own\n * `__proto__` key, or a `constructor` carrying a `prototype`, is the payload shape that turns a\n * later innocent merge/assign into prototype pollution. `\"reject\"` (default) answers the same\n * flat 400 as malformed JSON; `\"strip\"` removes the offending keys and continues; `\"ignore\"`\n * parses as-is (only for routes that never merge body input into other objects). Every guarded\n * payload pays one iterative pass over its parsed object nodes; `\"ignore\"` skips it.\n */\n readonly protoPoisoning?: \"reject\" | \"strip\" | \"ignore\";\n /**\n * Other sites whose HTML forms may post to a body-schema route: exact origins, or a function that\n * receives the `Origin`. A urlencoded, multipart or `text/plain` body is one a form on any site can\n * send with the visitor's cookies and no preflight, so one whose `Origin` names another site is\n * refused with `403` before it is read. Same-origin posts and requests without an `Origin`, such\n * as server-to-server calls, pass. JSON is not affected: a browser preflights it, so CORS decides.\n */\n readonly formOrigins?: ReadonlyArray<string> | ((origin: string) => boolean);\n /**\n * Declare that every `Request` reaching `app.fetch` was framed by a runtime HTTP parser, so its\n * `Content-Length` is an exact transport boundary rather than a hint. Set this ONLY when the\n * runtime's own request object is handed through untouched with no adapter in between to mark it -\n * a bare `export default app` on an edge runtime. Every supported ingress already marks itself:\n * `listen()` on Bun, `toFetchHandler(app)` on Workers/edge, `@nifrajs/deno`, and `@nifrajs/node`\n * (which reads exact bytes and never needs the mark). Reach for this option only for an ingress\n * nifra does not ship an adapter for.\n *\n * Left off (default), the JSON body lane copies the body out and enforces the cap on DELIVERED\n * bytes, because an unmarked request may have been rebuilt by an adapter that kept a caller's\n * `content-length` while decoding a payload of a different size. That check costs an extra pass\n * over the body, which is why an edge deployment that cannot be lied to may opt out of it.\n *\n * Do not set this on an app whose `fetch` is also called with `Request`s assembled from\n * untrusted input.\n */\n readonly trustBodyFraming?: boolean;\n /**\n * Max inbound WebSocket message size (bytes). A larger message never reaches the handler and the\n * socket closes with `1009`. Default: `maxBodyBytes` (1 MB). Bun and Node stop buffering at the cap,\n * so a huge frame is never held in memory; on Bun a mounted app's smaller cap, and on Deno and\n * Workers every cap, is checked after the runtime has buffered the whole message.\n */\n readonly wsMaxPayloadBytes?: number;\n /** Per-request timeout (ms): a slower request gets a 503 and `ctx.signal` aborts. 0 disables (default). */\n readonly requestTimeoutMs?: number;\n /** WebSocket upgrade admission/guard timeout (ms). Default 10_000; set to 0 only for a deliberate unbounded guard. */\n readonly wsUpgradeTimeoutMs?: number;\n /**\n * How to derive `c.clientIp` behind a reverse proxy or CDN. Omit (default) to trust only the raw\n * socket peer and never believe a forwarded header. Set `{ trustedHops: n }` when the app sits\n * behind `n` proxies you operate (the caller is read from `X-Forwarded-For` past those hops), or\n * `{ header: name }` to trust one edge-set header's first value. Declaring trust the app can't\n * actually enforce lets clients forge their IP, so leave it unset unless a proxy really fronts you.\n */\n readonly clientIp?: ClientIpTrust;\n /**\n * Admit the public `x-nifra-deadline` header and let it shorten local work. Disabled by default:\n * services that participate in trusted cross-service deadline propagation opt in explicitly,\n * while ordinary/public HTTP routes pay no header-admission tax and ignore hostile client values.\n */\n readonly acceptInboundDeadlines?: boolean;\n /**\n * Maximum time accepted from an inbound `x-nifra-deadline`, in milliseconds. An incoming absolute\n * deadline may shorten this cap (and `requestTimeoutMs`, when configured), never extend it.\n * Default 30_000; applies only when `acceptInboundDeadlines` is enabled and the header is present.\n */\n readonly maxInboundDeadlineMs?: number;\n /**\n * When `listen()`ing, install SIGTERM/SIGINT handlers that gracefully `stop()`. Default false.\n * `{ drainMs }` sets how long in-flight requests get to finish before the stop forces them closed\n * (default 10_000) - keep it under the platform's kill grace period (`docker stop` waits 10 s).\n */\n readonly gracefulSignals?: boolean | {\n readonly drainMs?: number;\n };\n /**\n * Capacity-admission gate (see {@link AdmissionController}). Bounds concurrent in-flight work so a\n * healthy instance sheds load (`429` + `Retry-After`) instead of accepting more than it can finish.\n * Off by default. Enabling it disables the fused native-route fast path (requests route through the\n * shared matched lane where the gate runs); when unset, the request path pays nothing.\n */\n readonly admission?: AdmissionController;\n /**\n * Optional token-only observation hook called by `useCapability(c, id)`. It receives no request,\n * parameters, body, tenant, or values. Routes without capability declarations keep the old hot path.\n */\n readonly onCapabilityUse?: (event: CapabilityUseEvent) => void;\n /** Structured logger for framework events (redacts secrets). Default: JSON to stderr. */\n readonly logger?: Logger;\n /**\n * How much of an unhandled error reaches the log for a 500. Never reaches the client either way -\n * the response is always a bare `internal_error`.\n *\n * - `\"full\"` (default) - `name`, the error's own text as `detail`, and `stack`.\n * - `\"message\"` - `name` and `detail`, no stack.\n * - `\"none\"` - `name` only.\n *\n * An error's text can quote the input that produced it, which is how request data ends up in a log\n * sink. The framework's answer is the redacting logger rather than blanket suppression: pass\n * `logger: jsonLogger({ valuePatterns: commonSecretPatterns })` to scrub tokens, JWTs, and emails\n * out of `detail` and `stack` while keeping the diagnosis. Reach for `\"none\"` when the sink itself\n * is the thing you don't trust.\n */\n readonly errorLogDetail?: \"full\" | \"message\" | \"none\";\n /**\n * App-wide fallback fired when a route **without its own `onValidationError`** fails body/query\n * validation. Same contract as the per-route hook (`(issues, ctx, kind) => Response | repaired-value |\n * undefined`): a route's own hook takes precedence, and a route can fall through to the plain `422` by\n * returning `undefined`. Use it for one app-wide error envelope (like tRPC's `errorFormatter` /\n * Fastify's `setErrorHandler`) instead of repeating a formatter per route.\n */\n readonly onValidationError?: RouteSchema[\"onValidationError\"];\n /**\n * What to do when an order-scoped hook (`derive`/`authenticate`/`beforeHandle`/`around`/\n * `aroundCapability`/`afterHandle`/`onError`/`decorate`) covers no route because it was added after\n * the last route was registered. `register()` snapshots the current chain into each route as it is\n * declared, so a hook appended after every route reaches nothing and is silently dead. A `merge()`d\n * route keeps the chain of the server that declared it, so a hook followed only by merges is dead\n * too. The same report covers `responseContract()` and `effectLedger()` installed after routes they\n * would have covered (a declared response, declared capabilities). `\"warn\"` (default) logs once at\n * seal (first `listen()`/`fetch`/`resolveNode`); `\"error\"` throws a `FrameworkError`\n * (`UNUSED_SCOPED_HOOKS`); `\"off\"` skips the bookkeeping entirely, including the one-frame stack\n * capture. App-global hooks (`onRequest`/`onResponse`/...) are unaffected in every mode.\n *\n * This is a development-time diagnostic: the whole audit is guarded by `process.env.NODE_ENV !==\n * \"production\"`, so any bundler that defines `NODE_ENV` (vite/esbuild/webpack/next, `bun build\n * --production`) dead-code-eliminates it, leaving zero bytes and zero per-request cost in the shipped\n * bundle. It fires in development, test, and CI - where you catch the mistake - not in production.\n */\n readonly unusedScopedHooks?: \"warn\" | \"error\" | \"off\";\n}"
|
|
14417
|
+
"signature": "export interface ServerOptions {\n /**\n * Max request body size (bytes), the default transport cap for every route. Default 1_000_000.\n * A route can choose a finite `schema.bodyLimit` of its own; an explicit `'unlimited'` route\n * requires `schema.bodyLimitReason` and is intended only for a separately bounded streaming or\n * upload integration.\n *\n * Framework readers (the body-schema lane, `c.boundedJson`) enforce the cap when they read. A\n * route WITHOUT a body schema (raw body, file upload, BYO-validation) is covered too: direct\n * `c.req` reads (`json()`, `arrayBuffer()`, the raw `body` stream, ...) are capped in place -\n * lazily, nothing is buffered until code actually reads - and answer 413 past the limit.\n * `c.boundedBody(n)` states its own explicit per-read limit, above or below the route's cap.\n */\n readonly maxBodyBytes?: number;\n /**\n * Prototype-poisoning policy for JSON bodies (the schema path and `c.boundedJson`). An own\n * `__proto__` key, or a `constructor` carrying a `prototype`, is the payload shape that turns a\n * later innocent merge/assign into prototype pollution. `\"reject\"` (default) answers the same\n * flat 400 as malformed JSON; `\"strip\"` removes the offending keys and continues; `\"ignore\"`\n * parses as-is (only for routes that never merge body input into other objects). Every guarded\n * payload pays one iterative pass over its parsed object nodes; `\"ignore\"` skips it.\n */\n readonly protoPoisoning?: \"reject\" | \"strip\" | \"ignore\";\n /**\n * Other sites whose HTML forms may post to a body-schema route: exact origins, or a function that\n * receives the `Origin`. A urlencoded, multipart or `text/plain` body is one a form on any site can\n * send with the visitor's cookies and no preflight, so one whose `Origin` names another site is\n * refused with `403` before it is read. Same-origin posts and requests without an `Origin`, such\n * as server-to-server calls, pass. JSON is not affected: a browser preflights it, so CORS decides.\n */\n readonly formOrigins?: ReadonlyArray<string> | ((origin: string) => boolean);\n /**\n * Declare that every `Request` reaching `app.fetch` was framed by a runtime HTTP parser, so its\n * `Content-Length` is an exact transport boundary rather than a hint. Set this ONLY when the\n * runtime's own request object is handed through untouched with no adapter in between to mark it -\n * a bare `export default app` on an edge runtime. Every supported ingress already marks itself:\n * `listen()` on Bun, `toFetchHandler(app)` on Workers/edge, `@nifrajs/deno`, and `@nifrajs/node`\n * (which reads exact bytes and never needs the mark). Reach for this option only for an ingress\n * nifra does not ship an adapter for.\n *\n * Left off (default), the JSON body lane copies the body out and enforces the cap on DELIVERED\n * bytes, because an unmarked request may have been rebuilt by an adapter that kept a caller's\n * `content-length` while decoding a payload of a different size. That check costs an extra pass\n * over the body, which is why an edge deployment that cannot be lied to may opt out of it.\n *\n * Do not set this on an app whose `fetch` is also called with `Request`s assembled from\n * untrusted input.\n */\n readonly trustBodyFraming?: boolean;\n /**\n * Max inbound WebSocket message size (bytes). A larger message never reaches the handler and the\n * socket closes with `1009`; when Bun's own frame limit refuses it, Bun drops the connection and the\n * client sees `1006`, while the `close` handler still gets `1009`. Default: `maxBodyBytes` (1 MB).\n * Bun and Node stop buffering at the cap, so a huge frame is never held in memory; on Bun a mounted\n * app's smaller cap, and on Deno and Workers every cap, is checked after the runtime has buffered\n * the whole message.\n */\n readonly wsMaxPayloadBytes?: number;\n /** Per-request timeout (ms): a slower request gets a 503 and `ctx.signal` aborts. 0 disables (default). */\n readonly requestTimeoutMs?: number;\n /** WebSocket upgrade admission/guard timeout (ms). Default 10_000; set to 0 only for a deliberate unbounded guard. */\n readonly wsUpgradeTimeoutMs?: number;\n /**\n * How to derive `c.clientIp` behind a reverse proxy or CDN. Omit (default) to trust only the raw\n * socket peer and never believe a forwarded header. Set `{ trustedHops: n }` when the app sits\n * behind `n` proxies you operate (the caller is read from `X-Forwarded-For` past those hops), or\n * `{ header: name }` to trust one edge-set header's first value. Declaring trust the app can't\n * actually enforce lets clients forge their IP, so leave it unset unless a proxy really fronts you.\n */\n readonly clientIp?: ClientIpTrust;\n /**\n * Admit the public `x-nifra-deadline` header and let it shorten local work. Disabled by default:\n * services that participate in trusted cross-service deadline propagation opt in explicitly,\n * while ordinary/public HTTP routes pay no header-admission tax and ignore hostile client values.\n */\n readonly acceptInboundDeadlines?: boolean;\n /**\n * Maximum time accepted from an inbound `x-nifra-deadline`, in milliseconds. An incoming absolute\n * deadline may shorten this cap (and `requestTimeoutMs`, when configured), never extend it.\n * Default 30_000; applies only when `acceptInboundDeadlines` is enabled and the header is present.\n */\n readonly maxInboundDeadlineMs?: number;\n /**\n * When `listen()`ing, install SIGTERM/SIGINT handlers that gracefully `stop()`. Default false.\n * `{ drainMs }` sets how long in-flight requests get to finish before the stop forces them closed\n * (default 10_000) - keep it under the platform's kill grace period (`docker stop` waits 10 s).\n */\n readonly gracefulSignals?: boolean | {\n readonly drainMs?: number;\n };\n /**\n * Capacity-admission gate (see {@link AdmissionController}). Bounds concurrent in-flight work so a\n * healthy instance sheds load (`429` + `Retry-After`) instead of accepting more than it can finish.\n * Off by default. Enabling it disables the fused native-route fast path (requests route through the\n * shared matched lane where the gate runs); when unset, the request path pays nothing.\n */\n readonly admission?: AdmissionController;\n /**\n * Optional token-only observation hook called by `useCapability(c, id)`. It receives no request,\n * parameters, body, tenant, or values. Routes without capability declarations keep the old hot path.\n */\n readonly onCapabilityUse?: (event: CapabilityUseEvent) => void;\n /** Structured logger for framework events (redacts secrets). Default: JSON to stderr. */\n readonly logger?: Logger;\n /**\n * How much of an unhandled error reaches the log for a 500. Never reaches the client either way -\n * the response is always a bare `internal_error`.\n *\n * - `\"full\"` (default) - `name`, the error's own text as `detail`, and `stack`.\n * - `\"message\"` - `name` and `detail`, no stack.\n * - `\"none\"` - `name` only.\n *\n * An error's text can quote the input that produced it, which is how request data ends up in a log\n * sink. The framework's answer is the redacting logger rather than blanket suppression: pass\n * `logger: jsonLogger({ valuePatterns: commonSecretPatterns })` to scrub tokens, JWTs, and emails\n * out of `detail` and `stack` while keeping the diagnosis. Reach for `\"none\"` when the sink itself\n * is the thing you don't trust.\n */\n readonly errorLogDetail?: \"full\" | \"message\" | \"none\";\n /**\n * App-wide fallback fired when a route **without its own `onValidationError`** fails body/query\n * validation. Same contract as the per-route hook (`(issues, ctx, kind) => Response | repaired-value |\n * undefined`): a route's own hook takes precedence, and a route can fall through to the plain `422` by\n * returning `undefined`. Use it for one app-wide error envelope (like tRPC's `errorFormatter` /\n * Fastify's `setErrorHandler`) instead of repeating a formatter per route.\n */\n readonly onValidationError?: RouteSchema[\"onValidationError\"];\n /**\n * What to do when an order-scoped hook (`derive`/`authenticate`/`beforeHandle`/`around`/\n * `aroundCapability`/`afterHandle`/`onError`/`decorate`) covers no route because it was added after\n * the last route was registered. `register()` snapshots the current chain into each route as it is\n * declared, so a hook appended after every route reaches nothing and is silently dead. A `merge()`d\n * route keeps the chain of the server that declared it, so a hook followed only by merges is dead\n * too. The same report covers `responseContract()` and `effectLedger()` installed after routes they\n * would have covered (a declared response, declared capabilities). `\"warn\"` (default) logs once at\n * seal (first `listen()`/`fetch`/`resolveNode`); `\"error\"` throws a `FrameworkError`\n * (`UNUSED_SCOPED_HOOKS`); `\"off\"` skips the bookkeeping entirely, including the one-frame stack\n * capture. App-global hooks (`onRequest`/`onResponse`/...) are unaffected in every mode.\n *\n * This is a development-time diagnostic: the whole audit is guarded by `process.env.NODE_ENV !==\n * \"production\"`, so any bundler that defines `NODE_ENV` (vite/esbuild/webpack/next, `bun build\n * --production`) dead-code-eliminates it, leaving zero bytes and zero per-request cost in the shipped\n * bundle. It fires in development, test, and CI - where you catch the mistake - not in production.\n */\n readonly unusedScopedHooks?: \"warn\" | \"error\" | \"off\";\n}"
|
|
14345
14418
|
},
|
|
14346
14419
|
{
|
|
14347
14420
|
"name": "ServerPrerenderedPage",
|
|
@@ -14368,7 +14441,7 @@
|
|
|
14368
14441
|
"name": "ServiceWorkerOptions",
|
|
14369
14442
|
"kind": "interface",
|
|
14370
14443
|
"package": "@nifrajs/web",
|
|
14371
|
-
"signature": "export interface ServiceWorkerOptions {\n /**\n * Distinguishes this build's cache from the last one. Use something that changes exactly when the\n * assets do - a content hash, a commit sha, a release version.\n */\n readonly buildId: string;\n /**\n * URL of a page to serve when a navigation fails and the network is unreachable. It must be a\n * static, user-independent document (a prerendered `/offline`), because every visitor gets the same\n * bytes. Omit it and failed navigations simply fail, which is the honest default.\n */\n readonly offlineUrl?: string;\n /**\n * Cache name prefix, and the namespace activation cleans: every cache named `<cacheName>:<id>` other\n * than this build's is deleted. Give each worker sharing an origin its own. Default `nifra`.\n */\n readonly cacheName?: string;\n /** Extra same-origin URLs to precache. Only pass immutable ones. */\n readonly additionalPrecache?: readonly string[];\n}"
|
|
14444
|
+
"signature": "export interface ServiceWorkerOptions {\n /**\n * Distinguishes this build's cache from the last one. Use something that changes exactly when the\n * assets do - a content hash, a commit sha, a release version.\n */\n readonly buildId: string;\n /**\n * URL of a page to serve when a navigation fails and the network is unreachable. It must be a\n * static, user-independent document (a prerendered `/offline`), because every visitor gets the same\n * bytes. Install fails rather than store it, or any precached URL, when the response is an error, a\n * redirect, or marked `private` or `no-store`. Omit it and failed navigations simply fail, which is\n * the honest default.\n */\n readonly offlineUrl?: string;\n /**\n * Cache name prefix, and the namespace activation cleans: every cache named `<cacheName>:<id>` other\n * than this build's is deleted. Give each worker sharing an origin its own. Default `nifra`.\n */\n readonly cacheName?: string;\n /** Extra same-origin URLs to precache. Only pass immutable ones. */\n readonly additionalPrecache?: readonly string[];\n}"
|
|
14372
14445
|
},
|
|
14373
14446
|
{
|
|
14374
14447
|
"name": "Session",
|
|
@@ -14446,7 +14519,7 @@
|
|
|
14446
14519
|
"name": "SessionOptions",
|
|
14447
14520
|
"kind": "interface",
|
|
14448
14521
|
"package": "@nifrajs/auth",
|
|
14449
|
-
"signature": "export interface SessionOptions {\n /** Signing secret (≥ 32 bytes), or a rotation list: the **first** secret signs new cookies and\n * any listed secret verifies, so rotating without invalidating live sessions is: prepend the new\n * secret, drop the old one after `maxAge` has elapsed. A bare secret swap (no list) invalidates\n * all existing sessions. */\n readonly secret: string | readonly string[];\n /**
|
|
14522
|
+
"signature": "export interface SessionOptions {\n /** Signing secret (≥ 32 bytes), or a rotation list: the **first** secret signs new cookies and\n * any listed secret verifies, so rotating without invalidating live sessions is: prepend the new\n * secret, drop the old one after `maxAge` has elapsed. A bare secret swap (no list) invalidates\n * all existing sessions. */\n readonly secret: string | readonly string[];\n /** Strongly consistent backend for **store mode**; omit for **cookie mode** (stateless).\n * Declared eventually consistent stores (including KVSessionStore) are refused. */\n readonly store?: SessionStore;\n /** Cookie name. Default `nifra_session`. */\n readonly cookieName?: string;\n /** Session lifetime in **seconds**. Default 7 days. */\n readonly maxAge?: number;\n /** Slide the expiry forward on every commit (default `true`); `false` = fixed absolute expiry. */\n readonly rolling?: boolean;\n /** Extra cookie attributes (the session cookie is always HttpOnly; `Secure`/`SameSite=Lax`/`Path=/`\n * default via `c.set.cookie`). Pass `{ secure: false }` for local http dev. */\n readonly cookie?: SessionCookieOptions;\n /** Clock (ms) - injected for testability; production passes `() => Date.now()` (the default). */\n readonly now?: () => number;\n /**\n * Also accept a session cookie signed by `@nifrajs/auth` before 5.0, whose signature does not cover\n * the cookie name, so upgrading from 4.x signs no one out. Off by default: while it is on, any\n * value the app signs with this secret through `@nifrajs/core`'s `signValue` (a signed preference\n * cookie, say) and that parses as a session reads as one. Turn it on for one `maxAge` after the\n * upgrade, then remove it; each such session is re-signed in the current form on its next commit.\n */\n readonly acceptLegacyCookies?: boolean;\n}"
|
|
14450
14523
|
},
|
|
14451
14524
|
{
|
|
14452
14525
|
"name": "SessionRecord",
|
|
@@ -14465,8 +14538,8 @@
|
|
|
14465
14538
|
"name": "SessionStore",
|
|
14466
14539
|
"kind": "interface",
|
|
14467
14540
|
"package": "@nifrajs/auth",
|
|
14468
|
-
"signature": "export interface SessionStore {\n /** The record for `id`, or `undefined` on a miss. */\n get(id: string): Promise<SessionRecord | undefined>;\n /** Store (or overwrite) the record for `id`. */\n set(id: string, record: SessionRecord): Promise<void>;\n /** Drop `id` (logout / regeneration). A no-op if absent. */\n delete(id: string): Promise<void>;\n}",
|
|
14469
|
-
"doc": "/**\n * Pluggable session backend (store mode).
|
|
14541
|
+
"signature": "export interface SessionStore {\n /** Read consistency. Omission asserts strong consistency for existing custom adapters. */\n readonly consistency?: \"strong\" | \"eventual\";\n /** The record for `id`, or `undefined` on a miss. */\n get(id: string): Promise<SessionRecord | undefined>;\n /** Store (or overwrite) the record for `id`. */\n set(id: string, record: SessionRecord): Promise<void>;\n /** Drop `id` (logout / regeneration). A no-op if absent. */\n delete(id: string): Promise<void>;\n /**\n * Overwrite `id` only while it still holds a record, resolving whether it wrote. The check and the\n * write must be one atomic step that also sets the new expiry, such as Redis\n * `SET key value XX PXAT <record.expiresAt>` (a bare `XX` drops the key's TTL) or a SQL\n * `UPDATE ... WHERE id = ?` that reports the rows it changed. Optional: when present, a loaded session renews through it instead\n * of `set`, so a logout that lands between the renewal's checks and its write wins even after the\n * logout's revocation marker is gone.\n */\n replace?(id: string, record: SessionRecord): Promise<boolean>;\n /**\n * Move the record at `previousId` to `nextId` only while it exists, is unrevoked and was not rotated\n * already, resolving whether it moved. One atomic step writes `marker` under `<previousId>.rotated`,\n * deletes `previousId` and stores `record` at `nextId`; it refuses when `<previousId>.revoked` or the\n * revocation marker of the original ID (the part before `~`) exists. Optional: without it, rotation\n * makes those writes one at a time and checks the revocation afterwards.\n */\n rotate?(previousId: string, nextId: string, record: SessionRecord, marker: SessionRecord): Promise<boolean>;\n}",
|
|
14542
|
+
"doc": "/**\n * Pluggable session backend (store mode). Reads must observe completed writes and deletes, including\n * revocation markers, across all instances. Eventual consistency cannot provide logout guarantees.\n * **Production needs a shared/durable store** so sessions hold across instances - {@link MemorySessionStore}\n * prod-guards against the per-instance footgun. Logout and rotation also write a revocation marker, an\n * empty record under `<id>.revoked`, and rotation one under `<id>.rotated`, so a store must accept those\n * keys like any other and keep each until its `expiresAt`. A dropped marker lets a request that loaded\n * the session before the logout write it back, unless the store implements `replace`; it also lets a\n * rotated generation outlive a logout made with an earlier generation's cookie.\n */"
|
|
14470
14543
|
},
|
|
14471
14544
|
{
|
|
14472
14545
|
"name": "SessionStore",
|
|
@@ -14561,7 +14634,7 @@
|
|
|
14561
14634
|
"name": "SignDownloadUrlOptions",
|
|
14562
14635
|
"kind": "interface",
|
|
14563
14636
|
"package": "@nifrajs/uploads",
|
|
14564
|
-
"signature": "export interface SignDownloadUrlOptions {\n /**
|
|
14637
|
+
"signature": "export interface SignDownloadUrlOptions {\n /** Whole seconds until the URL expires, at least 1. */\n readonly expiresInSeconds: number;\n /** Current unix time in whole seconds; defaults to `Date.now()/1000` rounded down. Injectable for tests. */\n readonly now?: number;\n}",
|
|
14565
14638
|
"doc": "/**\n * Short-TTL **signed download URLs** - serve an uploaded file back via a tamper-evident, expiring URL\n * (HMAC-SHA256 over the path + query + expiry). WebCrypto only (portable across Bun/Node/Deno/workerd,\n * no `node:crypto`). Verification is constant-time (`crypto.subtle.verify`). Sign a *relative*\n * URL/path; the returned string is relative so it works behind any host. `vexp` / `vsig` are reserved\n * signature fields and are excluded from the payload.\n */"
|
|
14566
14639
|
},
|
|
14567
14640
|
{
|
|
@@ -15151,7 +15224,7 @@
|
|
|
15151
15224
|
"name": "StripImageMetadataOptions",
|
|
15152
15225
|
"kind": "interface",
|
|
15153
15226
|
"package": "@nifrajs/uploads",
|
|
15154
|
-
"signature": "export interface StripImageMetadataOptions {\n /** Output format. Default: keep png/jpeg, else re-encode to webp. */\n readonly format?: StripFormat;\n /** Encode quality (1-100). Default 82. */\n readonly quality?: number;\n}"
|
|
15227
|
+
"signature": "export interface StripImageMetadataOptions {\n /** Output format. Default: keep png/jpeg, else re-encode to webp. */\n readonly format?: StripFormat;\n /** Encode quality (1-100). Default 82. */\n readonly quality?: number;\n /**\n * Largest source (width x height) the backend may decode. A few hundred compressed bytes can\n * declare a picture that decodes to gigabytes, so this is checked against the probed header\n * before any decode. Default 40 MP, the same as `@nifrajs/image`'s `createImageHandler`.\n */\n readonly maxPixels?: number;\n}"
|
|
15155
15228
|
},
|
|
15156
15229
|
{
|
|
15157
15230
|
"name": "StructuredOutputParser",
|
|
@@ -16009,14 +16082,14 @@
|
|
|
16009
16082
|
"name": "VERSION",
|
|
16010
16083
|
"kind": "const",
|
|
16011
16084
|
"package": "@nifrajs/core",
|
|
16012
|
-
"signature": "export declare const VERSION: \"5.
|
|
16085
|
+
"signature": "export declare const VERSION: \"5.5.1\";",
|
|
16013
16086
|
"doc": "/**\n * Current package version. A hardcoded literal on purpose - core runs on the edge (no fs), so it can't\n * read its own package.json at runtime. `scripts/version.ts` rewrites it on every release bump and\n * `check:publish` asserts it equals `@nifrajs/core`'s package version.\n */"
|
|
16014
16087
|
},
|
|
16015
16088
|
{
|
|
16016
16089
|
"name": "VERSION",
|
|
16017
16090
|
"kind": "const",
|
|
16018
16091
|
"package": "nifra",
|
|
16019
|
-
"signature": "export declare const VERSION: \"5.
|
|
16092
|
+
"signature": "export declare const VERSION: \"5.5.1\";",
|
|
16020
16093
|
"doc": "/**\n * Current package version. A hardcoded literal on purpose - core runs on the edge (no fs), so it can't\n * read its own package.json at runtime. `scripts/version.ts` rewrites it on every release bump and\n * `check:publish` asserts it equals `@nifrajs/core`'s package version.\n */"
|
|
16021
16094
|
},
|
|
16022
16095
|
{
|
|
@@ -16449,7 +16522,8 @@
|
|
|
16449
16522
|
"name": "WsCallOptions",
|
|
16450
16523
|
"kind": "interface",
|
|
16451
16524
|
"package": "@nifrajs/client",
|
|
16452
|
-
"signature": "export interface WsCallOptions {\n /** Sent on the handshake URL as an HTTP call sends it: an array repeats its key once per item,\n * and an `undefined` value is left out. */\n query?: Record<string, string | number | boolean | readonly (string | number | boolean)[] | undefined>;\n /** WebSocket subprotocols. A browser handshake cannot carry custom headers - authenticate via\n * `upgrade()` reading cookies/query/subprotocol, not an Authorization header. */\n protocols?: string | string[];\n /** Abort to close the socket (same effect as calling `close()`). */\n signal?: AbortSignal;\n /** Socket-level failures (connection refused, abnormal close). */\n onError?: (error: unknown) => void;\n}"
|
|
16525
|
+
"signature": "export interface WsCallOptions<Out = unknown> {\n /** Sent on the handshake URL as an HTTP call sends it: an array repeats its key once per item,\n * and an `undefined` value is left out. */\n query?: Record<string, string | number | boolean | readonly (string | number | boolean)[] | undefined>;\n /** WebSocket subprotocols. A browser handshake cannot carry custom headers - authenticate via\n * `upgrade()` reading cookies/query/subprotocol, not an Authorization header. */\n protocols?: string | string[];\n /** Abort to close the socket (same effect as calling `close()`). */\n signal?: AbortSignal;\n /** Socket-level failures (connection refused, abnormal close), and frames `validateReceive` refuses. */\n onError?: (error: unknown) => void;\n /**\n * Check every received frame against this schema - the route's `sendSchema`, imported from the\n * module that declares it (the typed client carries the contract's types, not its schemas). A frame\n * that fails is not delivered: `onError` gets a `TypeError` naming the issues, with the frame as its\n * `cause`. Frames are still delivered in the order they arrived, an async schema included.\n */\n validateReceive?: StandardSchemaV1<unknown, Out>;\n}",
|
|
16526
|
+
"doc": "/** `Out` is what the handle delivers: a `validateReceive` schema must produce that type. */"
|
|
16453
16527
|
},
|
|
16454
16528
|
{
|
|
16455
16529
|
"name": "WsHandle",
|
|
@@ -16480,7 +16554,7 @@
|
|
|
16480
16554
|
"name": "ZoneConfig",
|
|
16481
16555
|
"kind": "interface",
|
|
16482
16556
|
"package": "@nifrajs/web",
|
|
16483
|
-
"signature": "export interface ZoneConfig {\n /**\n * The side of a package that does not declare one in its own package.json, by name: exact\n * (`\"@shop/db\"`) or a trailing-`*` prefix (`\"@shop/*\"`). The exact name wins over a prefix, the\n * longest prefix over a shorter one, and a package's own declaration over all of them.\n */\n readonly packages?: Readonly<Record<string, PackageEnvironment>>;\n /**\n * App-relative folders or files holding backend code, beside `backend/` (`\"migrations\"`). A path\n * listed inside another one's folder overrides it: the most specific entry wins.\n */\n readonly backend?: readonly string[];\n /** App-relative folders or files holding frontend code, beside `frontend/`. */\n readonly frontend?: readonly string[];\n
|
|
16557
|
+
"signature": "export interface ZoneConfig {\n /**\n * The side of a package that does not declare one in its own package.json, by name: exact\n * (`\"@shop/db\"`) or a trailing-`*` prefix (`\"@shop/*\"`). The exact name wins over a prefix, the\n * longest prefix over a shorter one, and a package's own declaration over all of them.\n */\n readonly packages?: Readonly<Record<string, PackageEnvironment>>;\n /**\n * App-relative folders or files holding backend code, beside `backend/` (`\"migrations\"`). A path\n * listed inside another one's folder overrides it: the most specific entry wins.\n */\n readonly backend?: readonly string[];\n /** App-relative folders or files holding frontend code, beside `frontend/`. */\n readonly frontend?: readonly string[];\n /**\n * App-relative folders or files holding code both sides import, beside `shared/`. Unlike the other\n * sides, an entry may sit inside `frontend/` or `backend/`: a module there that both sides import\n * stays where it is, held to the shared rules (it may import only shared code and packages).\n */\n readonly shared?: readonly string[];\n}",
|
|
16484
16558
|
"doc": "/**\n * App-side zone settings, read from `\"nifra\": { \"zones\": ... }` in the app's package.json so every\n * build, dev server, `nifra check` and the editor plugin see the same ones without running app code.\n */"
|
|
16485
16559
|
},
|
|
16486
16560
|
{
|
|
@@ -16994,6 +17068,13 @@
|
|
|
16994
17068
|
"signature": "export declare function browserDenial(classification: Classification, specifier?: string): string | undefined;",
|
|
16995
17069
|
"doc": "/**\n * Why a classified file may not ship to a browser, or `undefined` when it may. A `drizzle-orm` driver\n * entry is recognized by the import as written (`specifier`) or by the file's path in the package.\n */"
|
|
16996
17070
|
},
|
|
17071
|
+
{
|
|
17072
|
+
"name": "buildAssetPaths",
|
|
17073
|
+
"kind": "function",
|
|
17074
|
+
"package": "@nifrajs/web",
|
|
17075
|
+
"signature": "export declare function buildAssetPaths(client: BuildManifest): string[];",
|
|
17076
|
+
"doc": "/** Every file a client build emitted, by request path: its `assets` and the `public/` files it copied. */"
|
|
17077
|
+
},
|
|
16997
17078
|
{
|
|
16998
17079
|
"name": "buildClient",
|
|
16999
17080
|
"kind": "function",
|
|
@@ -17033,7 +17114,8 @@
|
|
|
17033
17114
|
"name": "buildFailureDetail",
|
|
17034
17115
|
"kind": "function",
|
|
17035
17116
|
"package": "@nifrajs/web",
|
|
17036
|
-
"signature": "export declare function buildFailureDetail(err: unknown): string;"
|
|
17117
|
+
"signature": "export declare function buildFailureDetail(err: unknown): string;",
|
|
17118
|
+
"doc": "/**\n * Format a client-build rejection for the guard's report. Bun.build rejects with an AggregateError\n * whose message is just \"Bundle failed\" - the actionable part (which file, which import) lives in\n * `.errors`. Surface it, or the guard reports a failure while hiding the reason.\n */"
|
|
17037
17119
|
},
|
|
17038
17120
|
{
|
|
17039
17121
|
"name": "buildFixPrompt",
|
|
@@ -17295,6 +17377,13 @@
|
|
|
17295
17377
|
"signature": "export declare function checkCatalogs<K extends string>(options: CatalogCheckOptions<K>): CatalogCheckResult;",
|
|
17296
17378
|
"doc": "/** Check every locale's catalog in `locales` against the default locale's. */"
|
|
17297
17379
|
},
|
|
17380
|
+
{
|
|
17381
|
+
"name": "checkHostReach",
|
|
17382
|
+
"kind": "function",
|
|
17383
|
+
"package": "@nifrajs/web",
|
|
17384
|
+
"signature": "export declare function checkHostReach(options: HostReachOptions): Promise<HostReachReport>;",
|
|
17385
|
+
"doc": "/**\n * Render each page on `host`, then fetch every same-origin file each page references, following\n * scripts' imports and stylesheets' `url()`s, and expect 200 for all of them; then expect each\n * `refused` path to answer `refusedStatus`. Cross-origin references are skipped: they are not this\n * app's to serve.\n */"
|
|
17386
|
+
},
|
|
17298
17387
|
{
|
|
17299
17388
|
"name": "checkResponseContract",
|
|
17300
17389
|
"kind": "function",
|
|
@@ -17606,7 +17695,7 @@
|
|
|
17606
17695
|
"kind": "function",
|
|
17607
17696
|
"package": "@nifrajs/middleware",
|
|
17608
17697
|
"signature": "export declare function compression(options?: CompressionOptions): import(\"@nifrajs/core\").IdentityPlugin<never>;",
|
|
17609
|
-
"doc": "/**\n * Transparently **gzip** responses when the client sends `Accept-Encoding: gzip` and the body is a\n * compressible type larger than `threshold`. Uses the Web-standard `CompressionStream`, so it runs\n * on every nifra runtime including the edge; gzip is the one encoding `CompressionStream`\n * guarantees everywhere, so brotli isn't offered.\n *\n * Built on the portable `onResponseBody` tier for framework-serialized bytes, with a stream-safe raw\n * fallback for handler-returned/proxied Responses. The common JSON path stays on Node's direct\n * writer; raw streams are compressed incrementally without being fully buffered.\n *\n * Skips: clients that don't accept gzip, already-encoded responses, bodyless responses,\n * `Range` responses (206 / `Content-Range`), `Cache-Control: no-transform`, non-compressible\n * types, and bodies below `threshold` (gzip's ~20-byte overhead would enlarge them). Adds\n * `Vary: Accept-Encoding
|
|
17698
|
+
"doc": "/**\n * Transparently **gzip** responses when the client sends `Accept-Encoding: gzip` and the body is a\n * compressible type larger than `threshold`. Uses the Web-standard `CompressionStream`, so it runs\n * on every nifra runtime including the edge; gzip is the one encoding `CompressionStream`\n * guarantees everywhere, so brotli isn't offered.\n *\n * Built on the portable `onResponseBody` tier for framework-serialized bytes, with a stream-safe raw\n * fallback for handler-returned/proxied Responses. The common JSON path stays on Node's direct\n * writer; raw streams are compressed incrementally without being fully buffered.\n *\n * Skips: clients that don't accept gzip, already-encoded responses, bodyless responses,\n * `Range` responses (206 / `Content-Range`), `Cache-Control: no-transform`, non-compressible\n * types, and bodies below `threshold` (gzip's ~20-byte overhead would enlarge them). Adds\n * `Vary: Accept-Encoding` to every response it would compress for a gzip-accepting client, the\n * identity one sent to any other client included.\n *\n * **Security (BREACH).** Compression makes the response length depend on its content, so a response\n * that mixes a secret with attacker-reflected input leaks the secret through the compressed size\n * (the BREACH class of attacks). This applies to any HTTP compression, not this middleware\n * specifically. Nifra's own CSRF tokens are HMAC-signed per session and safe to compress, but if a\n * response body reflects request input **and** carries a per-request secret, exclude that route via\n * `compressible`/route scoping, or split the secret and the reflection into separate responses.\n *\n * ```ts\n * app.use(compression())\n * ```\n */"
|
|
17610
17699
|
},
|
|
17611
17700
|
{
|
|
17612
17701
|
"name": "computeEffectDigest",
|
|
@@ -17995,6 +18084,13 @@
|
|
|
17995
18084
|
"signature": "export declare function createFormatter<M extends object = RegisteredMessages>(locale: string, messages: NoInfer<CatalogFor<M>>, options?: NoInfer<FormatterOptions<M>>): Formatter<M>;",
|
|
17996
18085
|
"doc": "/**\n * Build (or reuse) a {@link Formatter} bound to a locale + its message catalog. Cheap to call per\n * request/render - instances are cached per `(messages, locale, options)`, and parsed ASTs + `Intl.*`\n * are memoized. The catalog is the app's (import a JSON file); this only negotiates (see\n * `negotiateLocale`) and formats.\n *\n * ```ts\n * const t = createFormatter(\"fr-CA\", catalogs[\"fr-CA\"], {\n * fallback: [catalogs.fr, catalogs.en],\n * timeZone: user.timeZone,\n * onMissing: reportMissingKey,\n * })\n * ```\n *\n * Throws, like `Intl`, for an invalid locale, `timeZone` or `numberingSystem`.\n */"
|
|
17997
18086
|
},
|
|
18087
|
+
{
|
|
18088
|
+
"name": "createHostPolicy",
|
|
18089
|
+
"kind": "function",
|
|
18090
|
+
"package": "@nifrajs/web",
|
|
18091
|
+
"signature": "export declare function createHostPolicy(options: HostPolicyOptions): HostPolicy;",
|
|
18092
|
+
"doc": "/**\n * Declare which pages and files each host serves. Hand the result to `createWebApp({ hostPolicy })`\n * (or export it as `hostPolicy` from the framework module, which `nifra build`'s server entry reads):\n * it is evaluated before the build's static files, the prerendered pages, the mounts and every page.\n * On Vercel the CDN answers the build's files before the function runs, so there it covers the rest.\n * A hand-written entry calls `check(request, buildAssets)` first, before its own static handler.\n *\n * ```ts\n * export const hostPolicy = createHostPolicy({\n * rules: [{\n * hosts: (host) => !OWN_HOSTS.has(host),\n * pages: [\"/\", \"/p/:id\", \"/share/*\"],\n * paths: [\"/api/submissions/*\"],\n * }],\n * })\n * ```\n */"
|
|
18093
|
+
},
|
|
17998
18094
|
{
|
|
17999
18095
|
"name": "createImageHandler",
|
|
18000
18096
|
"kind": "function",
|
|
@@ -18053,7 +18149,7 @@
|
|
|
18053
18149
|
"kind": "function",
|
|
18054
18150
|
"package": "@nifrajs/agent",
|
|
18055
18151
|
"signature": "export declare function createMemoryAgentEvidenceLog(options?: MemoryAgentEvidenceLogOptions): AgentEvidenceLog;",
|
|
18056
|
-
"doc": "/**\n * In-memory {@link AgentEvidenceLog} reference for local development and tests. Single-process by\n * construction: replay only sees runs recorded by this instance. Retention is bounded by\n * `maxTurns` with oldest-first eviction, so a reconnect to an evicted turn reports
|
|
18152
|
+
"doc": "/**\n * In-memory {@link AgentEvidenceLog} reference for local development and tests. Single-process by\n * construction: replay only sees runs recorded by this instance. Retention is bounded by\n * `maxTurns` with oldest-first eviction and by `maxEvidencePerTurn` within a turn, so a reconnect to\n * an evicted turn or a dropped cursor reports replay-unavailable rather than growing memory without\n * bound.\n */"
|
|
18057
18153
|
},
|
|
18058
18154
|
{
|
|
18059
18155
|
"name": "createMemoryAssureSink",
|
|
@@ -19379,6 +19475,13 @@
|
|
|
19379
19475
|
"package": "@nifrajs/cli",
|
|
19380
19476
|
"signature": "export declare function formatAssuranceReport(report: AssuranceReport): string;"
|
|
19381
19477
|
},
|
|
19478
|
+
{
|
|
19479
|
+
"name": "formatBuildLog",
|
|
19480
|
+
"kind": "function",
|
|
19481
|
+
"package": "@nifrajs/web",
|
|
19482
|
+
"signature": "export declare function formatBuildLog(log: unknown, root?: string): string;",
|
|
19483
|
+
"doc": "/**\n * One bundler log as `file:line:column: message`, the source line it points at underneath. Bun's\n * `BuildMessage`/`ResolveMessage` carry the place in `position`, which their `String()` drops: a\n * failed build said \"Could not resolve: ./db\" without naming the module that imported it.\n */"
|
|
19484
|
+
},
|
|
19382
19485
|
{
|
|
19383
19486
|
"name": "formatBytes",
|
|
19384
19487
|
"kind": "function",
|
|
@@ -19862,7 +19965,7 @@
|
|
|
19862
19965
|
"kind": "function",
|
|
19863
19966
|
"package": "@nifrajs/schema",
|
|
19864
19967
|
"signature": "export declare function importOpenAPI(document: unknown, options?: ImportOpenAPIOptions): ImportedApiInventory;",
|
|
19865
|
-
"doc": "/** Parse an OpenAPI 3.0
|
|
19968
|
+
"doc": "/** Parse an OpenAPI 3.0, 3.1 or 3.2 document into a canonical route inventory. Throws on invalid input. */"
|
|
19866
19969
|
},
|
|
19867
19970
|
{
|
|
19868
19971
|
"name": "importRuleMessage",
|
|
@@ -20061,6 +20164,13 @@
|
|
|
20061
20164
|
"signature": "export declare function isHiddenPath(rel: string): boolean;",
|
|
20062
20165
|
"doc": "/**\n * Whether a relative path crosses a dot-segment other than `.well-known` (RFC 8615, public by\n * definition). Serving, the build's `public/` copy and the parity listing all apply it, so an editor\n * or VCS artifact (`.env`, `.git/`, `.DS_Store`) is neither served nor shipped. Both separators split:\n * a request path uses `/`, a relative file path the OS separator.\n */"
|
|
20063
20166
|
},
|
|
20167
|
+
{
|
|
20168
|
+
"name": "isHostPolicy",
|
|
20169
|
+
"kind": "function",
|
|
20170
|
+
"package": "@nifrajs/web",
|
|
20171
|
+
"signature": "export declare function isHostPolicy(value: unknown): value is HostPolicy;",
|
|
20172
|
+
"doc": "/** Whether `value` came from {@link createHostPolicy}. */"
|
|
20173
|
+
},
|
|
20064
20174
|
{
|
|
20065
20175
|
"name": "isHydrationMismatch",
|
|
20066
20176
|
"kind": "function",
|
|
@@ -21137,6 +21247,13 @@
|
|
|
21137
21247
|
"signature": "export declare function parseHandoffSnapshot(value: unknown): HandoffSnapshot;",
|
|
21138
21248
|
"doc": "/**\n * Decode a handoff snapshot. Forward-compatible about unknown additive fields; forbidden content\n * keys are rejected.\n */"
|
|
21139
21249
|
},
|
|
21250
|
+
{
|
|
21251
|
+
"name": "parseManifestBuildAssets",
|
|
21252
|
+
"kind": "function",
|
|
21253
|
+
"package": "@nifrajs/web",
|
|
21254
|
+
"signature": "export declare function parseManifestBuildAssets(source: string): string[] | undefined;",
|
|
21255
|
+
"doc": "/** The baked `buildAssets` set in a committed server-manifest, or `undefined` when it bakes none. Pure. */"
|
|
21256
|
+
},
|
|
21140
21257
|
{
|
|
21141
21258
|
"name": "parseManifestClientEntry",
|
|
21142
21259
|
"kind": "function",
|
|
@@ -22815,7 +22932,7 @@
|
|
|
22815
22932
|
"kind": "function",
|
|
22816
22933
|
"package": "@nifrajs/web",
|
|
22817
22934
|
"signature": "export declare function serializeData(data: unknown): string;",
|
|
22818
|
-
"doc": "/**\n * Serialize loader data for embedding inside an inline `<script>`. `JSON.stringify` alone\n * is NOT safe there: a string containing `</script>` or `<!--` would break out of the\n * script element (an XSS vector). Escape `<`/`>` to `\\uXXXX`, plus the U+2028/U+2029\n * separators.\n */"
|
|
22935
|
+
"doc": "/**\n * Serialize loader data for embedding inside an inline `<script>`. `JSON.stringify` alone\n * is NOT safe there: a string containing `</script>` or `<!--` would break out of the\n * script element (an XSS vector). Escape `<`/`>` to `\\uXXXX`, plus the U+2028/U+2029\n * separators. The result is JSON text: read it with `JSON.parse` (or from a\n * `type=\"application/json\"` script), never as a JavaScript object literal, where a `\"__proto__\"`\n * key sets the object's prototype instead of becoming a property.\n */"
|
|
22819
22936
|
},
|
|
22820
22937
|
{
|
|
22821
22938
|
"name": "serializeManifest",
|
|
@@ -22884,7 +23001,7 @@
|
|
|
22884
23001
|
"kind": "function",
|
|
22885
23002
|
"package": "@nifrajs/web",
|
|
22886
23003
|
"signature": "export declare function servePublicDir(options: ServePublicDirOptions): (request: Request) => Promise<Response | undefined>;",
|
|
22887
|
-
"doc": "/**\n * Build a static-file handler for `dir`.\n *\n * Returns `undefined` on any miss so the caller **falls through to routing** - a static probe must\n * never shadow a route. That ordering is also why a `routes/robots.txt.tsx` beats a\n * `public/robots.txt` only if the caller checks routes first; the documented precedence is that the\n * static probe runs first, so `public/` wins, and an app wanting the route should not ship both.\n *\n *
|
|
23004
|
+
"doc": "/**\n * Build a static-file handler for `dir`.\n *\n * Returns `undefined` on any miss so the caller **falls through to routing** - a static probe must\n * never shadow a route. That ordering is also why a `routes/robots.txt.tsx` beats a\n * `public/robots.txt` only if the caller checks routes first; the documented precedence is that the\n * static probe runs first, so `public/` wins, and an app wanting the route should not ship both.\n *\n * Files up to 256 KiB carry a strong `ETag` from the exact snapshot served, matching the Node and\n * Deno readers. Those snapshots carry `Last-Modified` only while mtime reflects their own last change.\n * Larger files stream without an `ETag`: an open inode can change after a separate hash pass. They\n * are dated once settled, but an `If-Range` request gets the whole file rather than spliced versions.\n */"
|
|
22888
23005
|
},
|
|
22889
23006
|
{
|
|
22890
23007
|
"name": "serveTestApp",
|
|
@@ -23083,7 +23200,7 @@
|
|
|
23083
23200
|
"kind": "function",
|
|
23084
23201
|
"package": "@nifrajs/uploads",
|
|
23085
23202
|
"signature": "export declare function signDownloadUrl(url: string, secret: string, options: SignDownloadUrlOptions): Promise<string>;",
|
|
23086
|
-
"doc": "
|
|
23203
|
+
"doc": "/**\n * Sign a relative URL/path → a relative URL with `?vexp=&vsig=` appended. Throws a `RangeError` for\n * an `expiresInSeconds` or `now` that is not a whole number of seconds, since\n * {@link verifyDownloadUrl} accepts only a whole-second expiry.\n */"
|
|
23087
23204
|
},
|
|
23088
23205
|
{
|
|
23089
23206
|
"name": "signImageUrl",
|
|
@@ -23378,6 +23495,13 @@
|
|
|
23378
23495
|
"signature": "export declare function streamHandle(app: FetchHandler, options?: LambdaOptions): (event: LambdaEvent, responseStream: ResponseStream, context?: LambdaContext) => Promise<void>;",
|
|
23379
23496
|
"doc": "/**\n * A streaming Lambda handler for Function URLs with `InvokeMode: RESPONSE_STREAM`, via the\n * runtime's `awslambda.streamifyResponse`. Response bytes flow as the app produces them - no\n * buffering, no base64. Requires the managed AWS Lambda Node runtime (the `awslambda` global);\n * API Gateway does not support response streaming - use {@link handle} there.\n */"
|
|
23380
23497
|
},
|
|
23498
|
+
{
|
|
23499
|
+
"name": "streamedLastModifiedOf",
|
|
23500
|
+
"kind": "function",
|
|
23501
|
+
"package": "@nifrajs/core",
|
|
23502
|
+
"signature": "export declare function streamedLastModifiedOf(version: FileVersion, now?: number): number | undefined;",
|
|
23503
|
+
"doc": "/**\n * {@link lastModifiedOf} for a body streamed after its stat, where a write can still reach the bytes\n * sent. Dated only once its change is older than the racy window, so such a write falls in a later\n * HTTP-date second and the next `If-Modified-Since` fetches it. A weak validator: never pass it to\n * {@link ifRangeAllowsPartial}, which would resume a range across two versions.\n */"
|
|
23504
|
+
},
|
|
23381
23505
|
{
|
|
23382
23506
|
"name": "streaming",
|
|
23383
23507
|
"kind": "function",
|
|
@@ -23404,7 +23528,7 @@
|
|
|
23404
23528
|
"kind": "function",
|
|
23405
23529
|
"package": "@nifrajs/uploads",
|
|
23406
23530
|
"signature": "export declare function stripImageMetadata(bytes: Uint8Array, backend: ImageReencoder, options?: StripImageMetadataOptions): Promise<Uint8Array>;",
|
|
23407
|
-
"doc": "
|
|
23531
|
+
"doc": "/**\n * Re-encode an image to its intrinsic size, dropping all embedded metadata. Returns clean bytes.\n * A source over `maxPixels` throws {@link ImagePixelLimitError} without being decoded. Each call\n * holds a full decoded image in memory, so bound how many run at once where uploads arrive.\n */"
|
|
23408
23532
|
},
|
|
23409
23533
|
{
|
|
23410
23534
|
"name": "stripSvgPreamble",
|