@nifrajs/cli 5.8.0 → 5.9.0

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.
Files changed (248) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/dist/agent-files.d.ts +0 -22
  3. package/dist/agent-files.d.ts.map +1 -1
  4. package/dist/agent-files.js +3 -1
  5. package/dist/agent-files.js.map +1 -1
  6. package/dist/assure-hydration.d.ts.map +1 -1
  7. package/dist/assure-hydration.js +2 -10
  8. package/dist/assure-hydration.js.map +1 -1
  9. package/dist/assure.d.ts.map +1 -1
  10. package/dist/assure.js +3 -3
  11. package/dist/assure.js.map +1 -1
  12. package/dist/check-scan.d.ts +2 -0
  13. package/dist/check-scan.d.ts.map +1 -1
  14. package/dist/check-scan.js +54 -86
  15. package/dist/check-scan.js.map +1 -1
  16. package/dist/check.d.ts +3 -0
  17. package/dist/check.d.ts.map +1 -1
  18. package/dist/check.js +20 -23
  19. package/dist/check.js.map +1 -1
  20. package/dist/cli.d.ts +8 -0
  21. package/dist/cli.d.ts.map +1 -1
  22. package/dist/cli.js +42 -13
  23. package/dist/cli.js.map +1 -1
  24. package/dist/command-catalog.d.ts.map +1 -1
  25. package/dist/command-catalog.js +20 -30
  26. package/dist/command-catalog.js.map +1 -1
  27. package/dist/config-target.js +1 -1
  28. package/dist/config-target.js.map +1 -1
  29. package/dist/db-child.js +3 -10
  30. package/dist/db-child.js.map +1 -1
  31. package/dist/db-config.d.ts +2 -0
  32. package/dist/db-config.d.ts.map +1 -1
  33. package/dist/db-config.js +2 -0
  34. package/dist/db-config.js.map +1 -1
  35. package/dist/doctor.d.ts +14 -3
  36. package/dist/doctor.d.ts.map +1 -1
  37. package/dist/doctor.js +91 -6
  38. package/dist/doctor.js.map +1 -1
  39. package/dist/frontend-guidance.d.ts +19 -0
  40. package/dist/frontend-guidance.d.ts.map +1 -1
  41. package/dist/frontend-guidance.js +267 -23
  42. package/dist/frontend-guidance.js.map +1 -1
  43. package/dist/hand-built-manifest.d.ts.map +1 -1
  44. package/dist/hand-built-manifest.js +1 -1
  45. package/dist/hand-built-manifest.js.map +1 -1
  46. package/dist/internal/control-character.d.ts +3 -0
  47. package/dist/internal/control-character.d.ts.map +1 -0
  48. package/dist/internal/control-character.js +10 -0
  49. package/dist/internal/control-character.js.map +1 -0
  50. package/dist/internal/escape-regexp.d.ts +3 -0
  51. package/dist/internal/escape-regexp.d.ts.map +1 -0
  52. package/dist/internal/escape-regexp.js +5 -0
  53. package/dist/internal/escape-regexp.js.map +1 -0
  54. package/dist/internal/line-at.d.ts +3 -0
  55. package/dist/internal/line-at.d.ts.map +1 -0
  56. package/dist/internal/line-at.js +5 -0
  57. package/dist/internal/line-at.js.map +1 -0
  58. package/dist/internal/nifra-project.d.ts.map +1 -1
  59. package/dist/internal/nifra-project.js +35 -41
  60. package/dist/internal/nifra-project.js.map +1 -1
  61. package/dist/internal/posix-path.d.ts +3 -0
  62. package/dist/internal/posix-path.d.ts.map +1 -0
  63. package/dist/internal/posix-path.js +5 -0
  64. package/dist/internal/posix-path.js.map +1 -0
  65. package/dist/internal/project-specifiers.d.ts.map +1 -1
  66. package/dist/internal/project-specifiers.js +3 -10
  67. package/dist/internal/project-specifiers.js.map +1 -1
  68. package/dist/internal/realpath-or-self.d.ts +3 -0
  69. package/dist/internal/realpath-or-self.d.ts.map +1 -0
  70. package/dist/internal/realpath-or-self.js +11 -0
  71. package/dist/internal/realpath-or-self.js.map +1 -0
  72. package/dist/internal/record.d.ts +3 -0
  73. package/dist/internal/record.d.ts.map +1 -0
  74. package/dist/internal/record.js +5 -0
  75. package/dist/internal/record.js.map +1 -0
  76. package/dist/internal/source-facts.d.ts.map +1 -1
  77. package/dist/internal/source-facts.js +28 -25
  78. package/dist/internal/source-facts.js.map +1 -1
  79. package/dist/introspect.d.ts +0 -22
  80. package/dist/introspect.d.ts.map +1 -1
  81. package/dist/introspect.js +11 -151
  82. package/dist/introspect.js.map +1 -1
  83. package/dist/levels-tool.d.ts +2 -0
  84. package/dist/levels-tool.d.ts.map +1 -1
  85. package/dist/levels-tool.js +54 -64
  86. package/dist/levels-tool.js.map +1 -1
  87. package/dist/load.d.ts +6 -1
  88. package/dist/load.d.ts.map +1 -1
  89. package/dist/load.js.map +1 -1
  90. package/dist/local-cli.d.ts +7 -0
  91. package/dist/local-cli.d.ts.map +1 -1
  92. package/dist/local-cli.js +13 -0
  93. package/dist/local-cli.js.map +1 -1
  94. package/dist/mcp-docs-tools.d.ts +1 -1
  95. package/dist/mcp-docs-tools.d.ts.map +1 -1
  96. package/dist/mcp-docs-tools.js +46 -3
  97. package/dist/mcp-docs-tools.js.map +1 -1
  98. package/dist/mcp-http.d.ts +1 -1
  99. package/dist/mcp-http.js +2 -2
  100. package/dist/mcp-io.d.ts +16 -0
  101. package/dist/mcp-io.d.ts.map +1 -1
  102. package/dist/mcp-io.js +63 -0
  103. package/dist/mcp-io.js.map +1 -1
  104. package/dist/mcp-isolate.d.ts.map +1 -1
  105. package/dist/mcp-isolate.js +2 -1
  106. package/dist/mcp-isolate.js.map +1 -1
  107. package/dist/mcp-project-child.d.ts.map +1 -1
  108. package/dist/mcp-project-child.js +5 -12
  109. package/dist/mcp-project-child.js.map +1 -1
  110. package/dist/mcp-render.d.ts.map +1 -1
  111. package/dist/mcp-render.js +9 -51
  112. package/dist/mcp-render.js.map +1 -1
  113. package/dist/mcp-root.js +1 -1
  114. package/dist/mcp-root.js.map +1 -1
  115. package/dist/mcp-run.d.ts.map +1 -1
  116. package/dist/mcp-run.js +3 -46
  117. package/dist/mcp-run.js.map +1 -1
  118. package/dist/mcp-ws.d.ts.map +1 -1
  119. package/dist/mcp-ws.js +2 -18
  120. package/dist/mcp-ws.js.map +1 -1
  121. package/dist/migrate-layout.d.ts.map +1 -1
  122. package/dist/migrate-layout.js +36 -57
  123. package/dist/migrate-layout.js.map +1 -1
  124. package/dist/output-schemas.d.ts.map +1 -1
  125. package/dist/output-schemas.js +7 -7
  126. package/dist/output-schemas.js.map +1 -1
  127. package/dist/port.d.ts.map +1 -1
  128. package/dist/port.js +1 -2
  129. package/dist/port.js.map +1 -1
  130. package/dist/ppr-read-fix.js +2 -2
  131. package/dist/ppr-read-fix.js.map +1 -1
  132. package/dist/recipes/5.9.0.d.ts +10 -0
  133. package/dist/recipes/5.9.0.d.ts.map +1 -0
  134. package/dist/recipes/5.9.0.js +41 -0
  135. package/dist/recipes/5.9.0.js.map +1 -0
  136. package/dist/recipes/index.d.ts +5 -0
  137. package/dist/recipes/index.d.ts.map +1 -1
  138. package/dist/recipes/index.js +2 -0
  139. package/dist/recipes/index.js.map +1 -1
  140. package/dist/review.d.ts.map +1 -1
  141. package/dist/review.js +9 -13
  142. package/dist/review.js.map +1 -1
  143. package/dist/rules/contract-visibility.d.ts.map +1 -1
  144. package/dist/rules/contract-visibility.js +3 -9
  145. package/dist/rules/contract-visibility.js.map +1 -1
  146. package/dist/rules/data-guard.d.ts.map +1 -1
  147. package/dist/rules/data-guard.js +3 -10
  148. package/dist/rules/data-guard.js.map +1 -1
  149. package/dist/rules/pages.d.ts.map +1 -1
  150. package/dist/rules/pages.js +41 -58
  151. package/dist/rules/pages.js.map +1 -1
  152. package/dist/rules/routes.d.ts.map +1 -1
  153. package/dist/rules/routes.js +20 -27
  154. package/dist/rules/routes.js.map +1 -1
  155. package/dist/rules/security.d.ts.map +1 -1
  156. package/dist/rules/security.js +206 -313
  157. package/dist/rules/security.js.map +1 -1
  158. package/dist/rules/zones.d.ts.map +1 -1
  159. package/dist/rules/zones.js +3 -10
  160. package/dist/rules/zones.js.map +1 -1
  161. package/dist/runtime-differences.d.ts +62 -0
  162. package/dist/runtime-differences.d.ts.map +1 -0
  163. package/dist/runtime-differences.js +222 -0
  164. package/dist/runtime-differences.js.map +1 -0
  165. package/dist/sdk.d.ts.map +1 -1
  166. package/dist/sdk.js +43 -43
  167. package/dist/sdk.js.map +1 -1
  168. package/dist/smoke.d.ts.map +1 -1
  169. package/dist/smoke.js +4 -12
  170. package/dist/smoke.js.map +1 -1
  171. package/dist/source-rewrites.d.ts +27 -0
  172. package/dist/source-rewrites.d.ts.map +1 -0
  173. package/dist/source-rewrites.js +402 -0
  174. package/dist/source-rewrites.js.map +1 -0
  175. package/dist/stylex-migrate.d.ts.map +1 -1
  176. package/dist/stylex-migrate.js +1 -1
  177. package/dist/stylex-migrate.js.map +1 -1
  178. package/dist/symptom-search.d.ts +5 -0
  179. package/dist/symptom-search.d.ts.map +1 -0
  180. package/dist/symptom-search.js +21 -0
  181. package/dist/symptom-search.js.map +1 -0
  182. package/dist/upgrade.d.ts +28 -3
  183. package/dist/upgrade.d.ts.map +1 -1
  184. package/dist/upgrade.js +153 -64
  185. package/dist/upgrade.js.map +1 -1
  186. package/dist/verification-plan.d.ts.map +1 -1
  187. package/dist/verification-plan.js +5 -3
  188. package/dist/verification-plan.js.map +1 -1
  189. package/docs/examples.json +32 -2
  190. package/docs/llms-full.txt +749 -95
  191. package/docs/types.json +300 -61
  192. package/package.json +11 -11
  193. package/src/agent-files.ts +4 -1
  194. package/src/assure-hydration.ts +2 -9
  195. package/src/assure.ts +3 -4
  196. package/src/check-scan.ts +65 -82
  197. package/src/check.ts +25 -23
  198. package/src/cli.ts +61 -13
  199. package/src/command-catalog.ts +22 -32
  200. package/src/config-target.ts +1 -1
  201. package/src/db-child.ts +3 -10
  202. package/src/db-config.ts +4 -0
  203. package/src/doctor.ts +128 -12
  204. package/src/frontend-guidance.ts +344 -25
  205. package/src/hand-built-manifest.ts +1 -2
  206. package/src/internal/control-character.ts +8 -0
  207. package/src/internal/escape-regexp.ts +4 -0
  208. package/src/internal/line-at.ts +4 -0
  209. package/src/internal/nifra-project.ts +39 -35
  210. package/src/internal/posix-path.ts +4 -0
  211. package/src/internal/project-specifiers.ts +3 -10
  212. package/src/internal/realpath-or-self.ts +10 -0
  213. package/src/internal/record.ts +4 -0
  214. package/src/internal/source-facts.ts +39 -29
  215. package/src/introspect.ts +16 -156
  216. package/src/levels-tool.ts +71 -78
  217. package/src/load.ts +6 -1
  218. package/src/local-cli.ts +12 -0
  219. package/src/mcp-docs-tools.ts +51 -3
  220. package/src/mcp-http.ts +2 -2
  221. package/src/mcp-io.ts +77 -0
  222. package/src/mcp-isolate.ts +2 -3
  223. package/src/mcp-project-child.ts +5 -14
  224. package/src/mcp-render.ts +11 -59
  225. package/src/mcp-root.ts +1 -1
  226. package/src/mcp-run.ts +5 -54
  227. package/src/mcp-ws.ts +2 -19
  228. package/src/migrate-layout.ts +52 -72
  229. package/src/output-schemas.ts +7 -8
  230. package/src/port.ts +1 -4
  231. package/src/ppr-read-fix.ts +2 -2
  232. package/src/recipes/5.9.0.ts +42 -0
  233. package/src/recipes/index.ts +7 -0
  234. package/src/review.ts +12 -15
  235. package/src/rules/contract-visibility.ts +3 -8
  236. package/src/rules/data-guard.ts +3 -10
  237. package/src/rules/pages.ts +47 -58
  238. package/src/rules/routes.ts +21 -27
  239. package/src/rules/security.ts +224 -255
  240. package/src/rules/zones.ts +3 -10
  241. package/src/runtime-differences.ts +302 -0
  242. package/src/sdk.ts +55 -58
  243. package/src/smoke.ts +4 -13
  244. package/src/source-rewrites.ts +463 -0
  245. package/src/stylex-migrate.ts +1 -3
  246. package/src/symptom-search.ts +27 -0
  247. package/src/upgrade.ts +194 -74
  248. package/src/verification-plan.ts +10 -4
package/docs/types.json CHANGED
@@ -115,7 +115,7 @@
115
115
  "kind": "const",
116
116
  "package": "@nifrajs/agent-protocol",
117
117
  "signature": "export declare const AGENT_PROTOCOL_VERSION: 1;",
118
- "doc": "/**\n * Backend-neutral protocol for local coding-agent hosts.\n *\n * This package deliberately has no runtime dependencies. A Pi adapter, a Nifra-native backend,\n * the CLI, and the Workbench can all implement or consume these contracts without pulling any\n * framework, model provider, or UI code into an application.\n */"
118
+ "doc": "/** The session protocol version every snapshot and event carries; one with another version is refused. */"
119
119
  },
120
120
  {
121
121
  "name": "ALARM_GAP_MS",
@@ -1173,6 +1173,13 @@
1173
1173
  "signature": "export interface AppLike {\n fetch(request: Request): Response | Promise<Response>;\n}",
1174
1174
  "doc": "/** The minimal shape a nifra `server()` app satisfies - its own `fetch`. */"
1175
1175
  },
1176
+ {
1177
+ "name": "AppliedInvariantSetup",
1178
+ "kind": "interface",
1179
+ "package": "@nifrajs/core",
1180
+ "signature": "export interface AppliedInvariantSetup {\n /** The config with the setup's executor, witnesses and prepareRequest merged over it. */\n readonly invariants: InvariantsConfig;\n /** The `\"METHOD /path\"` witness keys the setup returned, in its order. */\n readonly setupWitnesses: readonly string[];\n}",
1181
+ "doc": "/** One L4 run's options once `invariants.setup` has provisioned its target. */"
1182
+ },
1176
1183
  {
1177
1184
  "name": "ApprovalBindingError",
1178
1185
  "kind": "class",
@@ -2349,13 +2356,13 @@
2349
2356
  "name": "BuildServerOptions",
2350
2357
  "kind": "interface",
2351
2358
  "package": "@nifrajs/web",
2352
- "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}"
2359
+ "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 /** Node built-ins the runtime that runs the bundle has besides what `target` implies, kept as imports\n * of the runtime's own module: neither polyfilled nor refused. `buildTarget` passes `node:crypto` for\n * Deno, where Bun's `browser` stand-in for it has no working `createHash`. */\n readonly providedBuiltins?: readonly string[];\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}"
2353
2360
  },
2354
2361
  {
2355
2362
  "name": "BuildServerViteOptions",
2356
2363
  "kind": "interface",
2357
2364
  "package": "@nifrajs/web",
2358
- "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}",
2365
+ "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 /** Node built-ins the runtime provides besides what `target` implies - mirrors `buildServer`. */\n readonly providedBuiltins?: readonly string[];\n}",
2359
2366
  "doc": "/** Options for {@link buildServerVite} - the same surface as `buildServer` minus Bun-plugin specifics. */"
2360
2367
  },
2361
2368
  {
@@ -2368,7 +2375,7 @@
2368
2375
  "name": "BuildTargetOptions",
2369
2376
  "kind": "interface",
2370
2377
  "package": "@nifrajs/web",
2371
- "signature": "export interface BuildTargetOptions {\n /** The `routes/` directory to discover (absolute path). */\n readonly routesDir: string;\n /** Output directory for the assembled deploy dir (absolute path). Cleared and recreated, so the\n * build refuses one that is a filesystem root or is or contains the routes directory, the public\n * directory, an absolute entry module, or the working directory. */\n readonly outDir: string;\n /** A scratch directory for intermediate codegen (the generated server entry + manifest) and the\n * server bundle, cleaned up after. Absolute path. Checked the same way as `outDir`. */\n readonly workDir: string;\n /** The adapter's client runtime module (exports `mountRouter`), e.g. `\"@nifrajs/web-react/client\"`. */\n readonly clientModule: string;\n /** Import specifier (resolvable from `workDir`) of the module exporting `adapter`. */\n readonly adapterImport: string;\n /** Import specifier (resolvable from `workDir`) of the module exporting `backend`, or `undefined`. */\n readonly backendImport?: string;\n /** Import specifier (resolvable from `workDir`) of the module exporting `use` (app-level middleware\n * applied before page routes are declared), or `undefined`. Must resolve to the same edge-safe\n * module as `adapterImport`. */\n readonly useImport?: string;\n /** `createWebApp` options the server entry imports by name (`apiPrefix`, `mounts`, `csp`, ...), each\n * mapped to the specifier (resolvable from `workDir`) of the same edge-safe module as `adapterImport`. */\n readonly optionImports?: ServerEntryOptionImports;\n /** Factory that builds the app for `static` prerendering, GIVEN the client build's manifest - so the\n * emitted hydration `<script src>` uses the REAL content-hashed entry (`client.entry`) plus the same\n * styles/route-preload the server targets use. A pre-built instance can't work here: the hash isn't known\n * until `buildClient` runs inside `buildTarget`, so a hardcoded entry 404s → pages render but never\n * hydrate. Required for `target: \"static\"` (SSG drives `app.fetch`). For `bun` and `node` it is\n * optional: given, the opted-in routes are prerendered into `_prerendered/` and the server answers\n * them from their file; the other targets ignore it. */\n readonly prerenderApp?: (client: BuildManifest) => PrerenderAppLike | Promise<PrerenderAppLike>;\n /** Client-build plugins (e.g. the MDX/Vue/Solid Bun plugins). */\n readonly clientPlugins?: readonly BunPlugin[];\n /** Server-build plugins (e.g. the SSR variants). */\n readonly serverPlugins?: readonly BunPlugin[];\n /** Extra Bun.build resolve conditions for the CLIENT build. */\n readonly conditions?: readonly string[];\n /** Compile-time `define` replacements layered onto both builds. */\n readonly define?: Readonly<Record<string, string>>;\n /** Project-root static directory copied to deploy root. `false` disables it. */\n readonly publicDir?: string | false;\n /** Prefix of environment variables allowed into the client bundle (default `\"PUBLIC_\"`). */\n readonly publicEnvPrefix?: string;\n /** Reviewed false positives of the secret scan over the bundle, `public/` and prerendered pages. */\n readonly secretExemptions?: readonly SecretExemption[];\n /**\n * Vite-only CSS output policy. `false` emits one aggregate stylesheet. The native Bun build does not\n * support this switch and fails closed if it is supplied instead of silently ignoring it.\n */\n readonly cssCodeSplit?: boolean;\n /**\n * Activation policy for framework-owned SSR stylesheet links. Defaults to `\"blocking\"`; `\"deferred\"`\n * fetches with `media=\"print\"` and promotes before hydration. With Vite, pair it with\n * `cssCodeSplit: false`; the native Bun build supports the activation policy but keeps its existing\n * CSS output strategy.\n */\n readonly cssLoading?: CssLoadingMode;\n /** Document `<title>` for the generated server entry. */\n readonly title?: string;\n /** Trust the edge platform's client-address header for `c.clientIp` (`cloudflare`, `vercel`). Off by\n * default, leaving an edge app with no caller address. See {@link ServerEntryClientIp}. */\n readonly clientIp?: ServerEntryClientIp;\n /** The client entry for a server built with `optionImports.live`: that runtime's `clientEntry`. */\n readonly live?: LiveClientEntry | undefined;\n}"
2378
+ "signature": "export interface BuildTargetOptions {\n /** The `routes/` directory to discover (absolute path). */\n readonly routesDir: string;\n /** Output directory for the assembled deploy dir (absolute path). Cleared and recreated, so the\n * build refuses one that is a filesystem root or is or contains the routes directory, the public\n * directory, an absolute entry module, or the working directory. */\n readonly outDir: string;\n /** A scratch directory for intermediate codegen (the generated server entry + manifest) and the\n * server bundle, cleaned up after. Absolute path. Checked the same way as `outDir`. */\n readonly workDir: string;\n /** The adapter's client runtime module (exports `mountRouter`), e.g. `\"@nifrajs/web-react/client\"`. */\n readonly clientModule: string;\n /** Import specifier (resolvable from `workDir`) of the module exporting `adapter`. */\n readonly adapterImport: string;\n /** Import specifier (resolvable from `workDir`) of the module exporting `backend`, or `undefined`. */\n readonly backendImport?: string;\n /** Import specifier (resolvable from `workDir`) of the module exporting `use` (app-level middleware\n * applied before page routes are declared), or `undefined`. Must resolve to the same edge-safe\n * module as `adapterImport`. */\n readonly useImport?: string;\n /** `createWebApp` options the server entry imports by name (`apiPrefix`, `mounts`, `csp`, ...), each\n * mapped to the specifier (resolvable from `workDir`) of the same edge-safe module as `adapterImport`. */\n readonly optionImports?: ServerEntryOptionImports;\n /** Factory that builds the app for `static` prerendering, GIVEN the client build's manifest - so the\n * emitted hydration `<script src>` uses the REAL content-hashed entry (`client.entry`) plus the same\n * styles/route-preload the server targets use. A pre-built instance can't work here: the hash isn't known\n * until `buildClient` runs inside `buildTarget`, so a hardcoded entry 404s → pages render but never\n * hydrate. Required for `target: \"static\"` (SSG drives `app.fetch`). For `bun` and `node` it is\n * optional: given, the opted-in routes are prerendered into `_prerendered/` and the server answers\n * them from their file; the other targets ignore it. */\n readonly prerenderApp?: (client: BuildManifest) => PrerenderAppLike | Promise<PrerenderAppLike>;\n /** Client-build plugins (e.g. the MDX/Vue/Solid Bun plugins). */\n readonly clientPlugins?: readonly BunPlugin[];\n /** Server-build plugins (e.g. the SSR variants). */\n readonly serverPlugins?: readonly BunPlugin[];\n /** Extra Bun.build resolve conditions for the CLIENT build. */\n readonly conditions?: readonly string[];\n /** Compile-time `define` replacements layered onto both builds. */\n readonly define?: Readonly<Record<string, string>>;\n /** Project-root static directory copied to deploy root. `false` disables it. */\n readonly publicDir?: string | false;\n /** Prefix of environment variables allowed into the client bundle (default `\"PUBLIC_\"`). */\n readonly publicEnvPrefix?: string;\n /** Reviewed false positives of the secret scan over the bundle, `public/` and prerendered pages. */\n readonly secretExemptions?: readonly SecretExemption[];\n /**\n * Vite-only CSS output policy. `false` emits one aggregate stylesheet. The native Bun build does not\n * support this switch and fails closed if it is supplied instead of silently ignoring it.\n */\n readonly cssCodeSplit?: boolean;\n /**\n * Activation policy for framework-owned SSR stylesheet links. Defaults to `\"blocking\"`; `\"deferred\"`\n * fetches with `media=\"print\"` and promotes before hydration. With Vite, pair it with\n * `cssCodeSplit: false`; the native Bun build supports the activation policy but keeps its existing\n * CSS output strategy.\n */\n readonly cssLoading?: CssLoadingMode;\n /** Document `<title>` for the generated server entry. */\n readonly title?: string;\n /** Trust the edge platform's client-address header for `c.clientIp` (`cloudflare`, `vercel`). Off by\n * default, leaving an edge app with no caller address. See {@link ServerEntryClientIp}. */\n readonly clientIp?: ServerEntryClientIp;\n /** How a `bun`, `node` or `deno` server stops and keeps idle connections. See\n * {@link ServerEntrySelfHost}. */\n readonly selfHost?: ServerEntrySelfHost;\n /** The client entry for a server built with `optionImports.live`: that runtime's `clientEntry`. */\n readonly live?: LiveClientEntry | undefined;\n}"
2372
2379
  },
2373
2380
  {
2374
2381
  "name": "BuildTargetPlan",
@@ -2393,7 +2400,7 @@
2393
2400
  "name": "Bundler",
2394
2401
  "kind": "interface",
2395
2402
  "package": "@nifrajs/web",
2396
- "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 /** The client entry for a live server (`BuildClientOptions.live`). */\n readonly live?: LiveClientEntry | undefined;\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}",
2403
+ "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 /** The client entry for a live server (`BuildClientOptions.live`). */\n readonly live?: LiveClientEntry | undefined;\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 /** Node built-ins the runtime provides besides what `target` implies, kept as imports. */\n readonly providedBuiltins?: readonly string[];\n }): Promise<ServerBuild>;\n}",
2397
2404
  "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 */"
2398
2405
  },
2399
2406
  {
@@ -3287,7 +3294,7 @@
3287
3294
  "kind": "interface",
3288
3295
  "package": "@nifrajs/testing",
3289
3296
  "signature": "export interface CertificationContext {\n /** Deterministic per-check key safe for shared test backends and stable re-runs. */\n readonly key: (suffix: string) => string;\n}",
3290
- "doc": "/**\n * Profile-based adapter certification. Profiles are structural and dependency-free: an adapter package\n * uses this only in its test/CI surface, while the resulting capability matrix is portable JSON evidence.\n */"
3297
+ "doc": "/** What a certification check receives besides the adapter under test. */"
3291
3298
  },
3292
3299
  {
3293
3300
  "name": "CertificationTarget",
@@ -4316,7 +4323,7 @@
4316
4323
  "name": "CreateWebAppOptions",
4317
4324
  "kind": "interface",
4318
4325
  "package": "@nifrajs/web",
4319
- "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 /** Experimental and unstable: features whose API may change in any release. */\n readonly experimental?: {\n /**\n * Partial prerendering, from `partialPrerendering()` in `@nifrajs/web/ppr`. A route whose backend\n * half exports `shellLoader` streams a shell shared by every visitor, then each `dynamic` boundary\n * as it settles. Needs `csp` (hashes), not `nonce`.\n */\n readonly ppr?: PprSetup;\n };\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 /**\n * Live data refresh, from `live()` in `@nifrajs/web/live`. Loaders declare keys with `ctx.live()`;\n * the app answers live loads at the runtime's load endpoint. Omit and nothing live is loaded.\n */\n readonly live?: LiveRuntimeHandle;\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 * Which cookies say who is signed in, for an app with a `keepAlive` route. A response that changes\n * or deletes one rotates the readable identity epoch cookie, and every tab drops the pages it kept\n * for the previous visitor. The session cookies of `@nifrajs/auth` and Auth.js count under their\n * default names, Better Auth's under any `cookiePrefix`; name any other in `identityCookies`. An app\n * run by `nifra dev` and `nifra build` exports this from `backend/framework.ts`. Development reports, once per\n * name, an `HttpOnly` cookie that changes and is in neither list (`NIFRA_KEEPALIVE_IDENTITY_COOKIE`).\n */\n readonly keepAlive?: KeepAliveServerOptions;\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}"
4326
+ "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. Pass {@link cspHeader} to have nifra write the\n * Content-Security-Policy header from the same value.\n */\n readonly nonce?: NonceResolver<Env>;\n /**\n * Build the Content-Security-Policy value for each document a {@link nonce} app renders, or return\n * `undefined` to send none. nifra sets it on every document it renders - pages, status pages,\n * `_error`, streamed and deferred documents - from the nonce it put on that document's scripts, so\n * the header never depends on which `Request` object a wrapper holds. `sources` is the\n * `script-src` list the document needs: `'nonce-…'` plus a `'sha256-…'` hash for each constant\n * inline script nifra writes, which covers a document the resolver left nonce-free.\n *\n * ```ts\n * cspHeader: ({ sources }) => `default-src 'self'; script-src 'self' ${sources}; object-src 'none'`\n * ```\n *\n * Needs `nonce`; `csp` writes its own header, so the two are refused together.\n */\n readonly cspHeader?: (context: CspHeaderContext) => string | undefined;\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 /** Experimental and unstable: features whose API may change in any release. */\n readonly experimental?: {\n /**\n * Partial prerendering, from `partialPrerendering()` in `@nifrajs/web/ppr`. A route whose backend\n * half exports `shellLoader` streams a shell shared by every visitor, then each `dynamic` boundary\n * as it settles. Needs `csp` (hashes), not `nonce`.\n */\n readonly ppr?: PprSetup;\n };\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 /**\n * Live data refresh, from `live()` in `@nifrajs/web/live`. Loaders declare keys with `ctx.live()`;\n * the app answers live loads at the runtime's load endpoint. Omit and nothing live is loaded.\n */\n readonly live?: LiveRuntimeHandle;\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 * Which cookies say who is signed in, for an app with a `keepAlive` route. A response that changes\n * or deletes one rotates the readable identity epoch cookie, and every tab drops the pages it kept\n * for the previous visitor. The session cookies of `@nifrajs/auth` and Auth.js count under their\n * default names, Better Auth's under any `cookiePrefix`; name any other in `identityCookies`. An app\n * run by `nifra dev` and `nifra build` exports this from `backend/framework.ts`. Development reports, once per\n * name, an `HttpOnly` cookie that changes and is in neither list (`NIFRA_KEEPALIVE_IDENTITY_COOKIE`).\n */\n readonly keepAlive?: KeepAliveServerOptions;\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}"
4320
4327
  },
4321
4328
  {
4322
4329
  "name": "CronError",
@@ -4829,7 +4836,7 @@
4829
4836
  "name": "DbRefusalCode",
4830
4837
  "kind": "type",
4831
4838
  "package": "@nifrajs/mcp-db",
4832
- "signature": "export type DbRefusalCode = \"NIFRA_DB_NOT_DECLARED\" | \"NIFRA_DB_CONFIG\" | \"NIFRA_DB_OUTSIDE_ROOT\" | \"NIFRA_DB_REMOTE_HOST\" | \"NIFRA_DB_SUPERUSER\" | \"NIFRA_DB_EXTENSION\" | \"NIFRA_DB_QUERY_OFF\" | \"NIFRA_DB_WRITE_REFUSED\" | \"NIFRA_DB_FUNCTION_REFUSED\" | \"NIFRA_DB_TABLE_EXCLUDED\" | \"NIFRA_DB_COLUMN_REFUSED\" | \"NIFRA_DB_TIMEOUT\" | \"NIFRA_DB_QUERY_FAILED\" | \"NIFRA_DB_DRIVER\";",
4839
+ "signature": "export type DbRefusalCode = \"NIFRA_DB_NOT_DECLARED\" | \"NIFRA_DB_CONFIG\" | \"NIFRA_DB_OUTSIDE_ROOT\" | \"NIFRA_DB_REMOTE_HOST\" | \"NIFRA_DB_SUPERUSER\" | \"NIFRA_DB_EXTENSION\" | \"NIFRA_DB_ROLE_GRANTS\" | \"NIFRA_DB_QUERY_OFF\" | \"NIFRA_DB_WRITE_REFUSED\" | \"NIFRA_DB_FUNCTION_REFUSED\" | \"NIFRA_DB_TABLE_EXCLUDED\" | \"NIFRA_DB_COLUMN_REFUSED\" | \"NIFRA_DB_TIMEOUT\" | \"NIFRA_DB_QUERY_FAILED\" | \"NIFRA_DB_DRIVER\";",
4833
4840
  "doc": "/** Every reason a database call is refused or fails, as a stable code. */"
4834
4841
  },
4835
4842
  {
@@ -5520,7 +5527,7 @@
5520
5527
  "name": "DurableObjectRecordBackend",
5521
5528
  "kind": "class",
5522
5529
  "package": "@nifrajs/core",
5523
- "signature": "export declare class DurableObjectRecordBackend implements DurableRecordBackend {\n private readonly storage;\n constructor(storage: DurableObjectStorage);\n private recordKey;\n private leaseKey;\n create(kind: DurableRecordKind, id: string, record: {\n readonly version: number;\n readonly state?: string;\n readonly updatedAt?: number;\n }): Promise<boolean>;\n get<T extends {\n readonly version: number;\n }>(kind: DurableRecordKind, id: string): Promise<T | undefined>;\n compareAndSet(kind: DurableRecordKind, id: string, expectedVersion: number, record: {\n readonly version: number;\n readonly state?: string;\n readonly updatedAt?: number;\n }): Promise<boolean>;\n scan<T extends {\n readonly state: string;\n readonly updatedAt: number;\n }>(kind: DurableRecordKind, input: ReconciliationScanOptions<string>): Promise<ReconciliationScanPage<T>>;\n acquireLease(input: Parameters<DurableRecordBackend[\"acquireLease\"]>[0]): Promise<ReconciliationLease | undefined>;\n renewLease(input: Parameters<DurableRecordBackend[\"renewLease\"]>[0]): Promise<boolean>;\n checkpointLease(input: Parameters<DurableRecordBackend[\"checkpointLease\"]>[0]): Promise<boolean>;\n releaseLease(input: Parameters<DurableRecordBackend[\"releaseLease\"]>[0]): Promise<boolean>;\n}"
5530
+ "signature": "export declare class DurableObjectRecordBackend implements DurableRecordBackend {\n private readonly storage;\n constructor(storage: DurableObjectStorage);\n private recordKey;\n private leaseKey;\n create(kind: DurableRecordKind, id: string, record: {\n readonly version: number;\n readonly state?: string;\n readonly updatedAt?: number;\n }): Promise<boolean>;\n get<T extends {\n readonly version: number;\n }>(kind: DurableRecordKind, id: string): Promise<T | undefined>;\n compareAndSet(kind: DurableRecordKind, id: string, expectedVersion: number, record: {\n readonly version: number;\n readonly state?: string;\n readonly updatedAt?: number;\n }): Promise<boolean>;\n scan<T extends {\n readonly state: string;\n readonly updatedAt: number;\n }>(kind: DurableRecordKind, input: ReconciliationScanOptions<string>): Promise<ReconciliationScanPage<T>>;\n acquireLease(input: Parameters<DurableRecordBackend[\"acquireLease\"]>[0]): Promise<ReconciliationLease | undefined>;\n renewLease(input: Parameters<DurableRecordBackend[\"renewLease\"]>[0]): Promise<boolean>;\n checkpointLease(input: Parameters<DurableRecordBackend[\"checkpointLease\"]>[0]): Promise<boolean>;\n releaseLease(input: Parameters<DurableRecordBackend[\"releaseLease\"]>[0]): Promise<boolean>;\n /** Write `next(current)` over the lease while `input`'s owner and token still hold it. */\n private updateHeldLease;\n}"
5524
5531
  },
5525
5532
  {
5526
5533
  "name": "DurableObjectStorage",
@@ -6335,7 +6342,7 @@
6335
6342
  "kind": "interface",
6336
6343
  "package": "@nifrajs/web",
6337
6344
  "signature": "export interface Fetcher {\n /** Current state; stable reference between transitions. */\n snapshot: () => FetcherState;\n /** Subscribe to this fetcher's transitions; returns an unsubscribe fn. */\n subscribe: (listener: () => void) => () => void;\n /** Load a route path's loader data into this fetcher's own `data` (also writes the shared cache).\n * A no-op for an unmatched path. */\n load: (path: string) => Promise<void>;\n /** Submit an action into this fetcher's own state; honors `X-Nifra-Revalidate` by refreshing the\n * active route + any mounted fetcher showing a changed path. Rejects on failure (caller falls back).\n * (No `revalidate` opt-out - a fetcher has no active loader of its own to skip.) */\n submit: (action: string, body: NonNullable<RequestInit[\"body\"]>) => Promise<void>;\n}",
6338
- "doc": "/**\n * An independent load/submit state machine, retrieved by `router.fetcher(key)`. Runs **concurrently**\n * with the main router and with other fetchers - each is single-flight against *itself* (its own\n * monotonic generation), so N row-level mutations / side-channel loads can be in flight at once without\n * disturbing the active view. Loads/submits write the shared cache and honor `X-Nifra-Revalidate`.\n */"
6345
+ "doc": "/**\n * An independent load/submit state machine, retrieved by `router.fetcher(key)`. Runs **concurrently**\n * with the main router and with other fetchers - each is single-flight against *itself* (its own\n * monotonic generation), so N row-level mutations / side-channel loads can be in flight at once without\n * disturbing the active view. Loads/submits write the shared cache and honor `X-Nifra-Revalidate`.\n * When the visitor changes (`identityChanged()` in this tab, or a new identity epoch cookie, read on\n * the next `fetcher()`), every fetcher goes back to idle; a submit in flight still answers.\n */"
6339
6346
  },
6340
6347
  {
6341
6348
  "name": "FetcherHandle",
@@ -6796,6 +6803,27 @@
6796
6803
  "signature": "export interface HandoffView {\n readonly requestId: string;\n readonly runId: string;\n readonly nodeId: string;\n readonly capability: string;\n readonly vector: number;\n readonly expiresAt: number;\n readonly state: HandoffLifecycleState;\n /** Opaque origin role. */\n readonly from: string;\n /** Opaque owner role once assigned. */\n readonly to?: string;\n}",
6797
6804
  "doc": "/** Content-free projection of one handoff boundary for a list/inspect view. */"
6798
6805
  },
6806
+ {
6807
+ "name": "HashedFiles",
6808
+ "kind": "type",
6809
+ "package": "@nifrajs/core",
6810
+ "signature": "export type HashedFiles = Iterable<string> | readonly RegExp[] | ((pathname: string) => boolean);",
6811
+ "doc": "/** Which files {@link ServeStaticOptions.hashedFiles} names: paths, patterns, or a predicate. */"
6812
+ },
6813
+ {
6814
+ "name": "HashedFiles",
6815
+ "kind": "type",
6816
+ "package": "@nifrajs/deno",
6817
+ "signature": "export type HashedFiles = Iterable<string> | readonly RegExp[] | ((pathname: string) => boolean);",
6818
+ "doc": "/** Which files {@link ServeStaticOptions.hashedFiles} names: paths, patterns, or a predicate. */"
6819
+ },
6820
+ {
6821
+ "name": "HashedFiles",
6822
+ "kind": "type",
6823
+ "package": "@nifrajs/node",
6824
+ "signature": "export type HashedFiles = Iterable<string> | readonly RegExp[] | ((pathname: string) => boolean);",
6825
+ "doc": "/** Which files {@link ServeStaticOptions.hashedFiles} names: paths, patterns, or a predicate. */"
6826
+ },
6799
6827
  {
6800
6828
  "name": "HealingEvent",
6801
6829
  "kind": "type",
@@ -7142,6 +7170,13 @@
7142
7170
  "signature": "export declare const IDLE_BLOCKER: Blocker;",
7143
7171
  "doc": "/** The idle blocker - a stable reference (no needless adapter re-renders while unblocked). */"
7144
7172
  },
7173
+ {
7174
+ "name": "IMMUTABLE",
7175
+ "kind": "const",
7176
+ "package": "@nifrajs/core",
7177
+ "signature": "export declare const IMMUTABLE = \"public, max-age=31536000, immutable\";",
7178
+ "doc": "/** `cache-control` for a content-hashed file: its name changes with its bytes. */"
7179
+ },
7145
7180
  {
7146
7181
  "name": "ISRApp",
7147
7182
  "kind": "interface",
@@ -7717,13 +7752,13 @@
7717
7752
  "kind": "type",
7718
7753
  "package": "@nifrajs/core",
7719
7754
  "signature": "export type InvariantSetup = () => Promise<InvariantSetupResult | undefined | void>;",
7720
- "doc": "/** Provisions a throwaway L4 target. Called once, before the first L4 request - never on import. */"
7755
+ "doc": "/**\n * Provisions a throwaway L4 target. Called once per L4 run, before its first case is generated, so\n * the witnesses it returns are known to every case - never on import.\n */"
7721
7756
  },
7722
7757
  {
7723
7758
  "name": "InvariantSetupResult",
7724
7759
  "kind": "interface",
7725
7760
  "package": "@nifrajs/core",
7726
- "signature": "export interface InvariantSetupResult {\n /** The isolated target for this run. Replaces `invariants.executor`. */\n readonly executor?: InvariantExecutor;\n /** Called once the run ends, after a failure too. */\n readonly teardown?: () => void | Promise<void>;\n}",
7761
+ "signature": "export interface InvariantSetupResult {\n /** The isolated target for this run. Replaces `invariants.executor`. */\n readonly executor?: InvariantExecutor;\n /**\n * Known-good requests that name what only exists once the target is up - a real slug, a row id,\n * a signed-in session - keyed by `\"METHOD /path\"`. Merged over `invariants.witnesses`: a key in\n * both takes this one. Validated as the static ones are.\n */\n readonly witnesses?: Readonly<Record<string, ContractWitness>>;\n /** Replaces `invariants.prepareRequest` for this run, so it can attach what setup created. */\n readonly prepareRequest?: InvariantRunOptions[\"prepareRequest\"];\n /** Called once the run ends, after a failure too. */\n readonly teardown?: () => void | Promise<void>;\n}",
7727
7762
  "doc": "/** What `invariants.setup` provisions for one L4 run. */"
7728
7763
  },
7729
7764
  {
@@ -9997,7 +10032,14 @@
9997
10032
  "name": "NativeApprovalPort",
9998
10033
  "kind": "interface",
9999
10034
  "package": "@nifrajs/coding-agent",
10000
- "signature": "export interface NativeApprovalPort {\n request(input: {\n readonly sessionId: string;\n /** Stable, bounded identifier for this approval boundary. */\n readonly approvalId: string;\n readonly turnId: string;\n readonly callId: string;\n readonly action: string;\n readonly capability: string;\n readonly tool: NativeTool;\n readonly input: unknown;\n readonly signal: AbortSignal;\n }): boolean | PromiseLike<boolean>;\n}"
10035
+ "signature": "export interface NativeApprovalPort {\n request(input: NativeApprovalRequest): boolean | PromiseLike<boolean>;\n /**\n * Decides before anyone is asked. Anything but a valid answer counts as \"ask\", and so does a\n * review still unsettled after `reviewTimeoutMs`; \"ask\" raises the approval as if there were no\n * review. An allow or a deny emits no approval events.\n */\n review?(input: NativeApprovalRequest): NativeReviewAnswer | PromiseLike<NativeReviewAnswer>;\n}"
10036
+ },
10037
+ {
10038
+ "name": "NativeApprovalRequest",
10039
+ "kind": "interface",
10040
+ "package": "@nifrajs/coding-agent",
10041
+ "signature": "export interface NativeApprovalRequest {\n readonly sessionId: string;\n /** Stable, bounded identifier for this approval boundary. */\n readonly approvalId: string;\n readonly turnId: string;\n readonly callId: string;\n readonly action: string;\n readonly capability: string;\n readonly tool: NativeTool;\n readonly input: unknown;\n readonly signal: AbortSignal;\n}",
10042
+ "doc": "/** One tool call an approval port is asked about. */"
10001
10043
  },
10002
10044
  {
10003
10045
  "name": "NativeGatewayModelPortOptions",
@@ -10077,6 +10119,13 @@
10077
10119
  "package": "@nifrajs/web",
10078
10120
  "signature": "export type NativeRender = (component: unknown, props: Record<string, unknown>, renderId: string) => string | Promise<string>;"
10079
10121
  },
10122
+ {
10123
+ "name": "NativeReviewAnswer",
10124
+ "kind": "type",
10125
+ "package": "@nifrajs/coding-agent",
10126
+ "signature": "export type NativeReviewAnswer = {\n readonly decision: \"allow\";\n} | {\n readonly decision: \"deny\";\n readonly reason: string;\n} | {\n readonly decision: \"ask\";\n};",
10127
+ "doc": "/** A review's decision on one tool call. A deny's reason reaches the model. */"
10128
+ },
10080
10129
  {
10081
10130
  "name": "NativeServerView",
10082
10131
  "kind": "interface",
@@ -10241,14 +10290,14 @@
10241
10290
  "name": "NifraBackend",
10242
10291
  "kind": "class",
10243
10292
  "package": "@nifrajs/coding-agent",
10244
- "signature": "export declare class NifraBackend implements AgentBackend {\n readonly info: AgentBackendInfo;\n private readonly options;\n private readonly sessions;\n private readonly pendingApprovals;\n constructor(options: NifraBackendOptions);\n createSession(input: CreateSessionInput): Promise<AgentSessionSnapshot>;\n send(input: SendMessageInput): AsyncIterable<AgentEvent>;\n cancel(sessionId: string, reason?: string): Promise<void>;\n snapshot(sessionId: string): Promise<AgentSessionSnapshot>;\n reload(sessionId: string): Promise<ReloadResult>;\n resolveApproval(sessionId: string, approvalId: string, approved: boolean, reason?: string): Promise<boolean | undefined>;\n close(sessionId: string): Promise<void>;\n private run;\n private consumeModel;\n private finish;\n private requestApproval;\n private settleApproval;\n private cancelTurn;\n private clearTurnSignal;\n private clearTurn;\n private isCurrentTurn;\n private assertCurrentTurn;\n private emit;\n private update;\n private requireSession;\n private now;\n private remember;\n private trimHistory;\n}",
10293
+ "signature": "export declare class NifraBackend implements AgentBackend {\n readonly info: AgentBackendInfo;\n private readonly options;\n private readonly sessions;\n private readonly pendingApprovals;\n constructor(options: NifraBackendOptions);\n createSession(input: CreateSessionInput): Promise<AgentSessionSnapshot>;\n send(input: SendMessageInput): AsyncIterable<AgentEvent>;\n cancel(sessionId: string, reason?: string): Promise<void>;\n snapshot(sessionId: string): Promise<AgentSessionSnapshot>;\n reload(sessionId: string): Promise<ReloadResult>;\n resolveApproval(sessionId: string, approvalId: string, approved: boolean, reason?: string): Promise<boolean | undefined>;\n close(sessionId: string): Promise<void>;\n private run;\n private consumeModel;\n private finish;\n private requestApproval;\n /**\n * Settles on an allow, a deny, or the turn's abort, and on undefined for everything that goes on\n * to an approval: an ask, a malformed answer, a throw or rejection, and a late answer.\n */\n private review;\n private askApproval;\n private settleApproval;\n private cancelTurn;\n private clearTurnSignal;\n private clearTurn;\n private isCurrentTurn;\n private assertCurrentTurn;\n private emit;\n private update;\n private requireSession;\n private now;\n private remember;\n private trimHistory;\n}",
10245
10294
  "doc": "/**\n * Small provider port for a future Nifra-native backend.\n *\n * It deliberately knows only messages, tools, and the protocol. Provider SDKs, credentials, UI,\n * and framework packages stay outside this module. A model may return one response or stream\n * deltas followed by a final response.\n */"
10246
10295
  },
10247
10296
  {
10248
10297
  "name": "NifraBackendOptions",
10249
10298
  "kind": "interface",
10250
10299
  "package": "@nifrajs/coding-agent",
10251
- "signature": "export interface NifraBackendOptions {\n readonly model: NativeModelPort;\n readonly tools?: readonly NativeTool[];\n readonly approval?: NativeApprovalPort;\n /**\n * Maximum time a protocol-visible native approval may remain unresolved (default 5 minutes, at\n * most 24 h). `\"never\"` removes the timer: the approval waits for an answer, a cancel, the end of\n * its turn, or session close.\n */\n readonly approvalTimeoutMs?: ApprovalTimeout;\n readonly maxSteps?: number;\n /** Longest message `send` accepts (default 64 KiB). */\n readonly maxMessageChars?: number;\n /**\n * Longest reply the model may give in one turn (default 1 MiB); past it the reply is cut with\n * a marker. A reply longer than one event's text travels as consecutive `assistant.message`\n * events, and the model's history keeps it whole.\n */\n readonly maxReplyChars?: number;\n /**\n * Character budget for the conversation a session sends to the model (default 1 MiB). Past it,\n * whole earlier turns are dropped, oldest first; the current turn is always sent in full.\n */\n readonly maxHistoryChars?: number;\n readonly now?: () => number;\n}"
10300
+ "signature": "export interface NifraBackendOptions {\n readonly model: NativeModelPort;\n readonly tools?: readonly NativeTool[];\n readonly approval?: NativeApprovalPort;\n /**\n * Maximum time a protocol-visible native approval may remain unresolved (default 5 minutes, at\n * most 24 h). `\"never\"` removes the timer: the approval waits for an answer, a cancel, the end of\n * its turn, or session close.\n */\n readonly approvalTimeoutMs?: ApprovalTimeout;\n /**\n * Longest the approval port's `review` may take before the call goes on to an approval (default\n * 30 s, at most 10 minutes).\n */\n readonly reviewTimeoutMs?: number;\n readonly maxSteps?: number;\n /** Longest message `send` accepts (default 64 KiB). */\n readonly maxMessageChars?: number;\n /**\n * Longest reply the model may give in one turn (default 1 MiB); past it the reply is cut with\n * a marker. A reply longer than one event's text travels as consecutive `assistant.message`\n * events, and the model's history keeps it whole.\n */\n readonly maxReplyChars?: number;\n /**\n * Character budget for the conversation a session sends to the model (default 1 MiB). Past it,\n * whole earlier turns are dropped, oldest first; the current turn is always sent in full.\n */\n readonly maxHistoryChars?: number;\n readonly now?: () => number;\n}"
10252
10301
  },
10253
10302
  {
10254
10303
  "name": "NifraContextLike",
@@ -10582,6 +10631,13 @@
10582
10631
  "signature": "export interface NotFoundScope {\n /** The directory's URL prefix (`/admin`) or everything beneath it (`/admin/*`). */\n readonly pattern: string;\n /** Param names each layout in {@link NotFoundEntry.layoutIds} owns on this pattern, by index. */\n readonly layoutParams: ReadonlyArray<readonly string[]>;\n /** Param names each middleware in {@link NotFoundEntry.middlewareIds} sees on this pattern, by\n * index. Absent when the page has no middleware. */\n readonly middlewareParams?: ReadonlyArray<readonly string[]>;\n}",
10583
10632
  "doc": "/** One URL pattern a nested `_404` answers when no route matches it. */"
10584
10633
  },
10634
+ {
10635
+ "name": "ONE_DAY",
10636
+ "kind": "const",
10637
+ "package": "@nifrajs/core",
10638
+ "signature": "export declare const ONE_DAY = \"public, max-age=86400\";",
10639
+ "doc": "/** `cache-control` for a file that keeps its name across deploys, as a build's `public/` files do. */"
10640
+ },
10585
10641
  {
10586
10642
  "name": "ObservationAdapter",
10587
10643
  "kind": "interface",
@@ -10779,7 +10835,7 @@
10779
10835
  "name": "OrchestrationHost",
10780
10836
  "kind": "class",
10781
10837
  "package": "@nifrajs/coding-agent",
10782
- "signature": "export declare class OrchestrationHost {\n private readonly catalog;\n private readonly limits;\n private readonly maxSteps;\n private readonly maxDepth;\n private readonly policy;\n private readonly vectors;\n private readonly runs;\n private counter;\n private readonly subagentAbandonment;\n private readonly onSubagentAbandoned;\n private readonly onStepFailed;\n constructor(options: OrchestrationHostOptions);\n /** Subagent executors abandoned by any run of this host that are still running. */\n get abandonedSubagents(): number;\n /**\n * Admit a capability descriptor against the host policy before it can be invoked. Throws\n * {@link OrchestrationStateError} (`E_POLICY_REJECTED`) carrying the admission reason when refused.\n * With no policy configured this is a passthrough - the host admits nothing it is not told to gate.\n */\n admit(descriptor: CapabilityDescriptor): void;\n /**\n * Allocate the next monotonic child vector for a live run, addressing a decision boundary the run\n * pauses on. Strictly increasing per run, so a decision carrying any other vector is provably stale.\n */\n openBoundaryVector(runId: string): number;\n /**\n * Parse, compile, and register a run in `submitted`. All structural ceilings and capability\n * authority are enforced here (a `CompileError` with a stable code), so an over-limit or\n * unauthorized plan never reaches `running`.\n */\n submit(source: RunPlan | unknown, options?: SubmitOptions): Promise<string>;\n /** Content-free progress view. Throws `E_NOT_FOUND` for an unknown run. */\n inspect(runId: string): RunStatus;\n /** `submitted` -> `running`. Begins the driver. */\n start(runId: string): void;\n /** `running` -> `paused`. Takes effect at the next layer boundary; in-flight nodes finish. */\n pause(runId: string): void;\n /** `paused` -> `running`. Releases the layer boundary. */\n resume(runId: string): void;\n /**\n * Cancel from any non-terminal state. Aborts the in-flight layer and any bounded subagent, frees a\n * paused gate, and freezes the run in `cancelled`. A late completion cannot revive it.\n */\n cancel(runId: string): void;\n /** Terminal result. Throws `E_NOT_TERMINAL` while the run is still live. */\n result(runId: string): Promise<RunResult>;\n /** Await the run reaching a terminal state, then return its result. */\n settled(runId: string): Promise<RunResult>;\n private require;\n private transition;\n private buildResult;\n private drive;\n /** Project one kernel event into a content-free evidence record. Frozen once the run is terminal. */\n private project;\n private reportFailure;\n /** Walk the plan tree once: node kinds, idempotency flags, and the full id set. */\n private indexPlan;\n}",
10838
+ "signature": "export declare class OrchestrationHost {\n private readonly catalog;\n private readonly limits;\n private readonly maxSteps;\n private readonly maxDepth;\n private readonly policy;\n private readonly vectors;\n private readonly runs;\n private counter;\n private readonly subagentAbandonment;\n private readonly onSubagentAbandoned;\n private readonly onStepFailed;\n constructor(options: OrchestrationHostOptions);\n /** Subagent executors abandoned by any run of this host that are still running. */\n get abandonedSubagents(): number;\n /**\n * Admit a capability descriptor against the host policy before it can be invoked. Throws\n * {@link OrchestrationStateError} (`E_POLICY_REJECTED`) carrying the admission reason when refused.\n * With no policy configured this is a passthrough - the host admits nothing it is not told to gate.\n */\n admit(descriptor: CapabilityDescriptor): void;\n /**\n * Allocate the next monotonic child vector for a live run, addressing a decision boundary the run\n * pauses on. Strictly increasing per run, so a decision carrying any other vector is provably stale.\n */\n openBoundaryVector(runId: string): number;\n /**\n * Parse, compile, and register a run in `submitted`. All structural ceilings and capability\n * authority are enforced here (a `CompileError` with a stable code), so an over-limit or\n * unauthorized plan never reaches `running`.\n */\n submit(source: RunPlan | unknown, options?: SubmitOptions): Promise<string>;\n /** Content-free progress view. Throws `E_NOT_FOUND` for an unknown run. */\n inspect(runId: string): RunStatus;\n /** `submitted` -> `running`. Begins the driver. */\n start(runId: string): void;\n /** `running` -> `paused`. Takes effect at the next layer boundary; in-flight nodes finish. */\n pause(runId: string): void;\n /** `paused` -> `running`. Releases the layer boundary. */\n resume(runId: string): void;\n /**\n * Cancel from any non-terminal state. Aborts the in-flight layer and any bounded subagent, frees a\n * paused gate, and freezes the run in `cancelled`. A late completion cannot revive it.\n */\n cancel(runId: string): void;\n /** Terminal result. Throws `E_NOT_TERMINAL` while the run is still live. */\n result(runId: string): Promise<RunResult>;\n /** Await the run reaching a terminal state, then return its result. */\n settled(runId: string): Promise<RunResult>;\n private require;\n private transition;\n private buildResult;\n private drive;\n /** Project one kernel event into a content-free evidence record. Frozen once the run is terminal. */\n private project;\n private reportFailure;\n}",
10783
10839
  "doc": "/** Owns run lifecycle and evidence projection over the kernel WorkflowRunner. */"
10784
10840
  },
10785
10841
  {
@@ -11284,7 +11340,7 @@
11284
11340
  "name": "PostgresQueryOptions",
11285
11341
  "kind": "interface",
11286
11342
  "package": "@nifrajs/mcp-db",
11287
- "signature": "export interface PostgresQueryOptions extends ShapeRowsOptions, PostgresScope {\n readonly timeoutMs: number;\n /** Extensions or untrusted languages to accept although the role can use them. */\n readonly allowExtensions?: readonly string[];\n}",
11343
+ "signature": "export interface PostgresQueryOptions extends ShapeRowsOptions, PostgresScope {\n readonly timeoutMs: number;\n /** Extensions or untrusted languages to accept although the role can use them. */\n readonly allowExtensions?: readonly string[];\n /** Functions (`name` or `schema.name`) to accept although the function allowlist refuses them. */\n readonly allowFunctions?: readonly string[];\n}",
11288
11344
  "doc": "/** Options for {@link queryPostgres}. */"
11289
11345
  },
11290
11346
  {
@@ -11311,7 +11367,7 @@
11311
11367
  "name": "PostgresRoleSqlOptions",
11312
11368
  "kind": "interface",
11313
11369
  "package": "@nifrajs/mcp-db",
11314
- "signature": "export interface PostgresRoleSqlOptions extends PostgresScope {\n readonly timeoutMs: number;\n /** The role to create (default `nifra_dev_reader`). */\n readonly role?: string;\n}",
11370
+ "signature": "export interface PostgresRoleSqlOptions extends PostgresScope {\n readonly timeoutMs: number;\n /** The role to create (default `nifra_dev_reader`). */\n readonly role?: string;\n /** The masking the queries will run with: its masked columns are left out of the grants. */\n readonly redaction?: DbRedaction;\n /** The `allowFunctions` the queries will run with: SECURITY DEFINER functions it names are accepted. */\n readonly allowFunctions?: readonly string[];\n}",
11315
11371
  "doc": "/** Options for {@link postgresRoleSql}. */"
11316
11372
  },
11317
11373
  {
@@ -11827,13 +11883,6 @@
11827
11883
  "signature": "export interface ProxyUpstreamResponse {\n readonly status: number;\n /** Empty string is fine - HTTP/2 has no reason phrase, and nothing downstream depends on it. */\n readonly statusText: string;\n readonly headers: Headers;\n readonly body: ReadableStream<Uint8Array> | null;\n /**\n * Whether `body` is still exactly the bytes the upstream sent, `Content-Encoding` intact. `fetch`\n * transparently decodes a compressed response, so its body is identity and the stored\n * `content-encoding`/`content-length` no longer describe it - both are dropped on relay (the\n * default when this is omitted). A transport that does NOT decode (undici's `request` does not)\n * MUST set this `true` so the encoding and length are relayed instead, letting the client decode\n * the bytes it actually receives. Getting this wrong ships a gzip body labelled identity.\n */\n readonly bodyEncoded?: boolean;\n}",
11828
11884
  "doc": "/** What a {@link ProxyTransport} returns. Header hygiene on the way back is the proxy's job. */"
11829
11885
  },
11830
- {
11831
- "name": "PublicDirCache",
11832
- "kind": "interface",
11833
- "package": "@nifrajs/web",
11834
- "signature": "export interface PublicDirCache {\n /** `cache-control` for content-hashed assets (default immutable, one year). */\n readonly hashed?: string;\n /** `cache-control` for everything else under `public/` (default one day). */\n readonly assets?: string;\n}",
11835
- "doc": "/** How long each subtree may be cached. Content-hashed bundle output can be immutable; a\n * user-authored file keeps its name across deploys, so it gets a day and a revalidation. */"
11836
- },
11837
11886
  {
11838
11887
  "name": "PurgeAttempt",
11839
11888
  "kind": "type",
@@ -11863,7 +11912,7 @@
11863
11912
  "name": "QueryClient",
11864
11913
  "kind": "interface",
11865
11914
  "package": "@nifrajs/web",
11866
- "signature": "export interface QueryClient {\n /** Get the stable {@link QueryHandle} for `key`, fetched via `fn`. Re-binds the latest `fn` (and\n * `options`) each call (closures change between renders); returns the same handle for the same\n * (hashed) key. */\n query: <T>(key: unknown, fn: () => Promise<T>, options?: QueryOptions) => QueryHandle<T>;\n /** Get the stable {@link InfiniteQueryHandle} for `key`, whose pages are fetched via `fn(pageParam)`. */\n infiniteQuery: <T, P>(key: unknown, fn: (pageParam: P) => Promise<T>, options: InfiniteQueryOptions<T, P>) => InfiniteQueryHandle<T, P>;\n /** Mark matching cached queries, infinite ones included, stale and refetch the **mounted** ones\n * (subscribers > 0). Array keys match by **prefix** (`[\"todo\"]` ⇒ every `[\"todo\", …]`); other keys\n * match exactly. */\n invalidateQueries: (keyOrPrefix: unknown) => void;\n /** Read a cached query's data (`undefined` if absent or not yet successful). Synchronous, no fetch. */\n getQueryData: <T>(key: unknown) => T | undefined;\n /** Write a query's data directly (optimistic updates, or seeding). Creates the entry if absent; marks\n * it fresh (`updatedAt = now`). `updater` may be a value or a function of the previous data. */\n setQueryData: <T>(key: unknown, updater: T | ((prev: T | undefined) => T)) => void;\n /** Fetch + cache a query's data WITHOUT subscribing (SSR prefetch, hover warm). Resolves when cached;\n * a fresh entry is a no-op. Rejects if the fetch throws (caller may swallow). */\n prefetchQuery: <T>(key: unknown, fn: () => Promise<T>, options?: QueryOptions) => Promise<void>;\n /** Serialize every successful query to a transferable snapshot (server → client SSR bridge). */\n dehydrate: () => DehydratedState;\n /** Seed the cache from a {@link dehydrate} snapshot (client boot). Existing fresher entries win. */\n hydrate: (state: DehydratedState) => void;\n /** Drop every cached query: mounted ones go back to pending and refetch, the rest are removed. A\n * live app calls it on every query client in the page when the viewer changes. */\n clear: () => void;\n}",
11915
+ "signature": "export interface QueryClient {\n /** Get the stable {@link QueryHandle} for `key`, fetched via `fn`. Re-binds the latest `fn` (and\n * `options`) each call (closures change between renders); returns the same handle for the same\n * (hashed) key. */\n query: <T>(key: unknown, fn: () => Promise<T>, options?: QueryOptions) => QueryHandle<T>;\n /** Get the stable {@link InfiniteQueryHandle} for `key`, whose pages are fetched via `fn(pageParam)`. */\n infiniteQuery: <T, P>(key: unknown, fn: (pageParam: P) => Promise<T>, options: InfiniteQueryOptions<T, P>) => InfiniteQueryHandle<T, P>;\n /** Mark matching cached queries, infinite ones included, stale and refetch the **mounted** ones\n * (subscribers > 0). Array keys match by **prefix** (`[\"todo\"]` ⇒ every `[\"todo\", …]`); other keys\n * match exactly. */\n invalidateQueries: (keyOrPrefix: unknown) => void;\n /** Read a cached query's data (`undefined` if absent or not yet successful). Synchronous, no fetch. */\n getQueryData: <T>(key: unknown) => T | undefined;\n /** Write a query's data directly (optimistic updates, or seeding). Creates the entry if absent; marks\n * it fresh (`updatedAt = now`). `updater` may be a value or a function of the previous data. */\n setQueryData: <T>(key: unknown, updater: T | ((prev: T | undefined) => T)) => void;\n /** Fetch + cache a query's data WITHOUT subscribing (SSR prefetch, hover warm). Resolves when cached;\n * a fresh entry is a no-op. Rejects if the fetch throws (caller may swallow). */\n prefetchQuery: <T>(key: unknown, fn: () => Promise<T>, options?: QueryOptions) => Promise<void>;\n /** Serialize every successful query to a transferable snapshot (server → client SSR bridge). */\n dehydrate: () => DehydratedState;\n /** Seed the cache from a {@link dehydrate} snapshot (client boot). Existing fresher entries win. */\n hydrate: (state: DehydratedState) => void;\n /** Drop every cached query: mounted ones go back to pending and refetch, the rest are removed. Every\n * client in the page runs it when the visitor changes: `identityChanged()` in this tab, a live\n * account switch, or, on the client's next read, a new identity epoch cookie. */\n clear: () => void;\n}",
11867
11916
  "doc": "/** The keyed query cache. One per app (a binding registers it like the router). */"
11868
11917
  },
11869
11918
  {
@@ -12190,8 +12239,8 @@
12190
12239
  "name": "RateLimitTier",
12191
12240
  "kind": "interface",
12192
12241
  "package": "@nifrajs/middleware",
12193
- "signature": "export interface RateLimitTier {\n /** Static path prefix such as `/api/public`: no params, wildcards, dot segments or trailing slash. */\n readonly prefix: string;\n readonly max: number;\n readonly windowMs: number;\n /** Bucket key for this tier only. Default: the limiter's `key`, or the derived client IP. Like\n * {@link RateLimitOptions.key} it may be async, and a throw or rejection is charged to the client IP. */\n readonly key?: (req: Request, platform?: Platform) => string | Promise<string>;\n}",
12194
- "doc": "/** One bucket of a {@link rateLimitTiers} limiter: the requests at `prefix` or below it. */"
12242
+ "signature": "export interface RateLimitTier {\n /**\n * Static path prefix such as `/api/public`: no params, wildcards, dot segments or trailing slash.\n * A list charges every prefix in it to this tier's one bucket, so\n * `[\"/api/exports\", \"/api/reports/download\"]` with `max: 30` allows 30 across both, not 30 each.\n */\n readonly prefix: string | readonly string[];\n /**\n * The bucket's store scope, `tier:<name>:`. Default: the first prefix. Name a tier whose prefix\n * list may change, so editing the list keeps its live counters. Letters, digits, `/` and\n * `-._~%!$&'()+,;=@`; unique across tiers.\n */\n readonly name?: string;\n readonly max: number;\n readonly windowMs: number;\n /** Bucket key for this tier only. Default: the limiter's `key`, or the derived client IP. Like\n * {@link RateLimitOptions.key} it may be async, and a throw or rejection is charged to the client IP. */\n readonly key?: (req: Request, platform?: Platform) => string | Promise<string>;\n}",
12243
+ "doc": "/** One bucket of a {@link rateLimitTiers} limiter: the requests at a `prefix` or below it. */"
12195
12244
  },
12196
12245
  {
12197
12246
  "name": "RateLimitTiersOptions",
@@ -12199,6 +12248,13 @@
12199
12248
  "package": "@nifrajs/middleware",
12200
12249
  "signature": "export interface RateLimitTiersOptions extends Omit<RateLimitOptions, \"max\" | \"windowMs\"> {\n /**\n * The bucket for every request no tier claims. Omit it when something in front of the app already\n * applies a base limit: a request no tier claims is then not charged and gets no `RateLimit-*`\n * headers, and the rate-limit route evidence covers only the routes under a tier.\n */\n readonly floor?: {\n readonly max: number;\n readonly windowMs: number;\n };\n readonly tiers: readonly RateLimitTier[];\n}"
12201
12250
  },
12251
+ {
12252
+ "name": "RateLimiter",
12253
+ "kind": "interface",
12254
+ "package": "@nifrajs/middleware",
12255
+ "signature": "export interface RateLimiter extends Middleware {\n /**\n * The exact store key `request` would be charged to, so a test or an ops tool can pre-spend,\n * inspect or reset that bucket through the store. A custom key runs as it would on a request,\n * async included, and a key that throws or rejects resolves to the client-IP bucket. `undefined`\n * when the request would not be charged: `skip` leaves it, no tier claims it and there is no\n * floor, or no key can be derived. Nothing is counted.\n */\n keyOf(request: Request, platform?: Platform): Promise<string | undefined>;\n}",
12256
+ "doc": "/** A rate-limit {@link Middleware} that can name the counter a request is charged to. */"
12257
+ },
12202
12258
  {
12203
12259
  "name": "RawHtml",
12204
12260
  "kind": "class",
@@ -12761,6 +12817,20 @@
12761
12817
  "signature": "export interface RequestLedger {\n /** Validate, freeze, and record one entry. Throws on invalid input, overflow, or after seal. */\n append(input: EffectEntryInput): EffectEntry;\n /** Entries recorded so far (frozen snapshot view). */\n entries(): readonly EffectEntry[];\n readonly size: number;\n readonly sealed: boolean;\n /** Finalize the ledger (computing the chain when enabled). Idempotent - always the same result. */\n seal(): Promise<SealedEffectLedger>;\n}",
12762
12818
  "doc": "/** Per-request ledger. `append` is synchronous (hot-path safe); `seal` is idempotent and async. */"
12763
12819
  },
12820
+ {
12821
+ "name": "RequestLocal",
12822
+ "kind": "interface",
12823
+ "package": "@nifrajs/core",
12824
+ "signature": "export interface RequestLocal<T> {\n /** The value set through `request` or any request in its scope, else `undefined`. */\n get(request: Request): T | undefined;\n /** Set the value for `request`'s whole scope. */\n set(request: Request, value: T): void;\n has(request: Request): boolean;\n /** Remove the value from `request`'s scope; `true` when there was one. */\n delete(request: Request): boolean;\n}",
12825
+ "doc": "/** One request-local slot from {@link requestLocal}. */"
12826
+ },
12827
+ {
12828
+ "name": "RequestLocal",
12829
+ "kind": "interface",
12830
+ "package": "nifra",
12831
+ "signature": "export interface RequestLocal<T> {\n /** The value set through `request` or any request in its scope, else `undefined`. */\n get(request: Request): T | undefined;\n /** Set the value for `request`'s whole scope. */\n set(request: Request, value: T): void;\n has(request: Request): boolean;\n /** Remove the value from `request`'s scope; `true` when there was one. */\n delete(request: Request): boolean;\n}",
12832
+ "doc": "/** One request-local slot from {@link requestLocal}. */"
12833
+ },
12764
12834
  {
12765
12835
  "name": "RequestLogFields",
12766
12836
  "kind": "interface",
@@ -12945,7 +13015,7 @@
12945
13015
  "name": "ResponseContractRuntime",
12946
13016
  "kind": "interface",
12947
13017
  "package": "@nifrajs/core",
12948
- "signature": "export interface ResponseContractRuntime {\n readonly mode: ResponseContractMode;\n check(definition: ResponseContractDefinition, result: unknown, context?: {\n readonly req?: Request;\n readonly jsonReply?: Response | undefined;\n readonly jsonBody?: unknown;\n }): ResponseContractOutcome | Promise<ResponseContractOutcome>;\n}",
13018
+ "signature": "export interface ResponseContractRuntime {\n readonly mode: ResponseContractMode;\n check(definition: ResponseContractDefinition, result: unknown, context?: {\n readonly req?: Request;\n readonly jsonReply?: Response | undefined;\n readonly jsonBody?: unknown;\n }): ResponseContractOutcome | Promise<ResponseContractOutcome>;\n /**\n * What a `c.json(body)` reply with this status writes, each `toJSON` hook applied as `check` judges\n * it, so the reply's bytes and its check share one call of each. Without it, as from a plugin of\n * an older copy of core, the reply writes `body` as given.\n */\n write?(definition: ResponseContractDefinition, body: unknown, status: number | undefined): unknown;\n}",
12949
13019
  "doc": "/**\n * What the server holds when the plugin is installed. The kernel calls `check` through this object and\n * never imports the implementation, so an app that does not install the plugin does not carry it.\n */"
12950
13020
  },
12951
13021
  {
@@ -13749,7 +13819,7 @@
13749
13819
  "name": "RouterState",
13750
13820
  "kind": "interface",
13751
13821
  "package": "@nifrajs/web",
13752
- "signature": "export interface RouterState {\n readonly serverComponents?: import(\"./server-components/types.js\").ComponentState | undefined;\n readonly routeId: string;\n readonly params: Record<string, string>;\n /** The current URL path (used to revalidate the active loader after an action). While\n * {@link intercepted} is set it is the target shown in the boundary, not the page's own. */\n readonly path: string;\n readonly data: unknown;\n /** Per-layout loader data, aligned with the matched chain's leading layout prefix. Absent when no\n * layout in that chain has a loader. */\n readonly layoutData?: readonly unknown[] | undefined;\n /** Neutral named-boundary states for the active route. */\n readonly boundaries?: BoundaryStates;\n /** An action's data return after a client-side submit (cleared on navigation). */\n readonly actionData?: unknown;\n /** True while a navigation or submit is in flight (drives loading UI). */\n readonly pending: boolean;\n /** The path a navigation or a submit's redirect is loading while `pending`; a redirect the router\n * follows moves it to the target. Lets a `NavLink` know whether its own `to` is the one loading;\n * `undefined` when idle. */\n readonly pendingPath?: string | undefined;\n /** The in-flight submit (set during a `submit`, cleared when it settles) - for optimistic UI. */\n readonly submission?: Submission;\n /** Set while an intercept boundary shows a navigation's target over the page: the boundary holding\n * it, and the path the page underneath was loaded from. The page revalidates under `pagePath`, the\n * boundary under `path`. */\n readonly intercepted?: Intercepted;\n /** Opaque: which live load the page data on screen came from (`@nifrajs/web/live-client`). */\n readonly live?: unknown;\n /** The page instance on screen, when the app keeps pages alive (`@nifrajs/web/keep-alive`). */\n readonly instance?: string | undefined;\n /** Pages kept mounted and hidden, least recently shown first. Absent when none is kept. */\n readonly kept?: readonly KeptPage[] | undefined;\n /** This publish showed a kept page again. */\n readonly restored?: boolean | undefined;\n /** A page shown again is reloading its data in place: not a navigation, so `pending` stays false. */\n readonly revalidating?: boolean | undefined;\n}",
13822
+ "signature": "export interface RouterState {\n readonly serverComponents?: import(\"./server-components/types.js\").ComponentState | undefined;\n readonly routeId: string;\n readonly params: Record<string, string>;\n /** The current URL path (used to revalidate the active loader after an action). While\n * {@link intercepted} is set it is the target shown in the boundary, not the page's own. */\n readonly path: string;\n readonly data: unknown;\n /** Per-layout loader data, aligned with the matched chain's leading layout prefix. Absent when no\n * layout in that chain has a loader. */\n readonly layoutData?: readonly unknown[] | undefined;\n /** Neutral named-boundary states for the active route. */\n readonly boundaries?: BoundaryStates;\n /** An action's data return after a client-side submit (cleared on navigation). */\n readonly actionData?: unknown;\n /** True while a navigation or submit is in flight (drives loading UI). */\n readonly pending: boolean;\n /** The path a navigation or a submit's redirect is loading while `pending`; a redirect the router\n * follows moves it to the target. Lets a `NavLink` know whether its own `to` is the one loading;\n * `undefined` when idle. */\n readonly pendingPath?: string | undefined;\n /** The in-flight submit (set during a `submit`, cleared when it settles) - for optimistic UI. */\n readonly submission?: Submission;\n /** Set while an intercept boundary shows a navigation's target over the page: the boundary holding\n * it, and the path the page underneath was loaded from. The page revalidates under `pagePath`, the\n * boundary under `path`. */\n readonly intercepted?: Intercepted;\n /** Opaque: which live load the page data on screen came from (`@nifrajs/web/live-client`). */\n readonly live?: unknown;\n /** The page instance on screen, when the app keeps pages alive (`@nifrajs/web/keep-alive`). */\n readonly instance?: string | undefined;\n /** Pages kept mounted and hidden, least recently shown first. Absent when none is kept. */\n readonly kept?: readonly KeptPage[] | undefined;\n /** This publish showed a kept page again. */\n readonly restored?: boolean | undefined;\n /** A page shown again is reloading its data in place: not a navigation, so `pending` stays false. */\n readonly revalidating?: boolean | undefined;\n /**\n * The page on screen was loaded for the previous visitor and a load for the visitor now here failed:\n * reloading it, or a navigation or submit away from it. A browser loads this URL as a document in its\n * place (`installHistory` does, replacing the entry): the server's redirect target, else the URL a\n * native load would show.\n */\n readonly documentLoad?: string | undefined;\n}",
13753
13823
  "doc": "/** The router's observable state. A new object is published on every transition. */"
13754
13824
  },
13755
13825
  {
@@ -14754,26 +14824,34 @@
14754
14824
  "name": "ServeOptions",
14755
14825
  "kind": "interface",
14756
14826
  "package": "@nifrajs/deno",
14757
- "signature": "export interface ServeOptions {\n readonly port: number;\n readonly hostname?: string;\n /**\n * Install SIGTERM/SIGINT handlers that call `stop()` for a graceful drain on\n * `docker stop` / Ctrl-C. Off by default - taking over process signals is opt-in,\n * mirroring nifra's Bun `listen({ gracefulSignals })`. The object form is passed to `stop()`.\n */\n readonly signals?: boolean | DenoStopOptions;\n /**\n * Serve HTTPS directly, with no proxy in front: `cert` and `key` as PEM text or the files' bytes.\n * Unset, the server speaks plain HTTP, which is what a proxy or platform that terminates TLS\n * expects.\n */\n readonly tls?: {\n readonly cert: string | Uint8Array;\n readonly key: string | Uint8Array;\n };\n}"
14827
+ "signature": "export interface ServeOptions {\n readonly port: number;\n readonly hostname?: string;\n /**\n * Install SIGTERM/SIGINT handlers that call `stop()` for a graceful drain on\n * `docker stop` / Ctrl-C. Off by default - taking over process signals is opt-in, as\n * `server({ gracefulSignals })` is for Bun's `listen()`. The object form is passed to `stop()`.\n */\n readonly gracefulSignals?: boolean | DenoStopOptions;\n /**\n * Serve HTTPS directly, with no proxy in front: `cert` and `key` as PEM text or the files' bytes.\n * Unset, the server speaks plain HTTP, which is what a proxy or platform that terminates TLS\n * expects.\n */\n readonly tls?: {\n readonly cert: string | Uint8Array;\n readonly key: string | Uint8Array;\n };\n /**\n * Sees every request before the app does, so a file it answers wins over any route at the same\n * path. It returns the file's response, or `undefined` to let the app route the request. No hook\n * of the app runs for a request it answers. {@link serveStatic} builds one for files on disk, and\n * `@nifrajs/web`'s Deno build serves its client bundle and public files through it.\n */\n readonly static?: (request: Request) => Response | Promise<Response | undefined> | undefined;\n}"
14758
14828
  },
14759
14829
  {
14760
14830
  "name": "ServeOptions",
14761
14831
  "kind": "interface",
14762
14832
  "package": "@nifrajs/node",
14763
- "signature": "export interface ServeOptions {\n readonly port: number;\n readonly hostname?: string;\n /**\n * Protocol used when the adapter constructs `Request.url`.\n *\n * The default is `\"https\"` when {@link ServeOptions.tls} is set and `\"http\"` otherwise. Deployments\n * behind TLS termination can set `\"https\"` (or a trusted infra-aware function) so app code that reads\n * `request.url` sees the public scheme. Forwarded headers are not trusted implicitly.\n */\n readonly protocol?: RequestProtocolOption;\n /**\n * Serve HTTPS directly, with no proxy in front: `{ cert, key }` as PEM text or the files' bytes\n * (`readFileSync(\"cert.pem\")`), plus any other `node:tls` server option (`passphrase`, `ca`,\n * `requestCert` for client certificates, `minVersion`, `SNICallback`, ...). Unset, the server speaks\n * plain HTTP, which is what a proxy or platform that terminates TLS expects.\n */\n readonly tls?: TlsOptions;\n /** Reject requests whose normalized Host authority is not in this allowlist or callback result. */\n readonly allowedHosts?: readonly string[] | ((host: string) => boolean);\n /** Use this validated authority when constructing Request.url, ignoring the inbound Host value. */\n readonly canonicalHost?: string;\n /**\n * Install SIGTERM/SIGINT handlers that call `stop()` for a graceful drain on\n * `docker stop` / Ctrl-C. Off by default - taking over process signals is opt-in,\n * mirroring nifra's Bun `listen({ gracefulSignals })`. The object form is passed to `stop()`.\n *\n * The app-level request timeout (`server({ requestTimeoutMs })` → 503) and body cap\n * are *not* set here - they live inside `app.fetch`, so they already apply through\n * this adapter. Slow-client protection is Node's built-in `requestTimeout` (300s) /\n * `headersTimeout` (60s) defaults.\n */\n readonly signals?: boolean | NodeStopOptions;\n /**\n * Serve static files from disk for matching GET/HEAD requests *before* the app runs - non-matching\n * requests fall through to `app.fetch` with the node-direct fast path intact (no perf regression on\n * SSR/API routes). Replaces the hand-rolled `/assets/*` reader in self-hosted entries. An array\n * serves several directories; the first mount whose prefix (and `files`, when set) takes a path\n * answers it.\n */\n readonly static?: ServeStaticOptions | readonly ServeStaticOptions[];\n /**\n * Make a hand-rolled `return new Response(body)` ride the direct-write lane, by swapping\n * `globalThis.Response` for a stand-in that defers a *simple* construction (a string body, no\n * `statusText`, no headers or a plain header record) the way `c.text` / `c.json` already do.\n *\n * Off by default: prefer `c.text` / `c.json`, which get this without a global swap. Reach for the\n * flag only when handlers construct `Response` by hand on the hot path. It patches a process-global\n * builtin, so every `new Response(...)` anywhere in the process goes through the stand-in -\n * transparent (non-simple bodies build a real `Response`, and simple ones stay `instanceof\n * Response`), but a broad enough change to be opt-in.\n */\n readonly fastResponse?: boolean;\n}"
14833
+ "signature": "export interface ServeOptions {\n readonly port: number;\n readonly hostname?: string;\n /**\n * Protocol used when the adapter constructs `Request.url`.\n *\n * The default is `\"https\"` when {@link ServeOptions.tls} is set and `\"http\"` otherwise. Deployments\n * behind TLS termination can set `\"https\"` (or a trusted infra-aware function) so app code that reads\n * `request.url` sees the public scheme. Forwarded headers are not trusted implicitly.\n */\n readonly protocol?: RequestProtocolOption;\n /**\n * Serve HTTPS directly, with no proxy in front: `{ cert, key }` as PEM text or the files' bytes\n * (`readFileSync(\"cert.pem\")`), plus any other `node:tls` server option (`passphrase`, `ca`,\n * `requestCert` for client certificates, `minVersion`, `SNICallback`, ...). Unset, the server speaks\n * plain HTTP, which is what a proxy or platform that terminates TLS expects.\n */\n readonly tls?: TlsOptions;\n /** Reject requests whose normalized Host authority is not in this allowlist or callback result. */\n readonly allowedHosts?: readonly string[] | ((host: string) => boolean);\n /** Use this validated authority when constructing Request.url, ignoring the inbound Host value. */\n readonly canonicalHost?: string;\n /**\n * Route a request on the path a WHATWG parser would give it. Bun and workerd deliver a parsed URL,\n * so `/public/../admin` reaches the app as `/admin`; Node's `IncomingMessage.url` is the target as\n * sent. Off, Node routes the text received, as most frameworks do: a guard on `/admin` does not see\n * `/public/../admin`, and a proxy that normalizes paths before forwarding disagrees with the app\n * about which route a request is for. On, dot segments (`.`, `..`, `%2e`), backslashes and the\n * characters a parser percent-encodes are resolved before routing, so every runtime routes the\n * same path. Off by default; enable it when path guards, or a path-normalizing proxy, sit in front\n * of or inside the app. The same option as `server({ normalizeTarget })` on Deno.\n *\n * Off applies to requests the adapter serves from Node's own request object. A request the adapter\n * must hand over as a Web `Request` - one a `static` callback sees, and every WebSocket upgrade -\n * is built by the platform's URL parser, which resolves dot segments whatever this option says.\n */\n readonly normalizeTarget?: boolean;\n /**\n * Install SIGTERM/SIGINT handlers that call `stop()` for a graceful drain on\n * `docker stop` / Ctrl-C. Off by default - taking over process signals is opt-in, as\n * `server({ gracefulSignals })` is for Bun's `listen()`. The object form is passed to `stop()`.\n *\n * The app-level request timeout (`server({ requestTimeoutMs })` → 503) and body cap\n * are *not* set here - they live inside `app.fetch`, so they already apply through\n * this adapter. Slow-client protection is Node's built-in `requestTimeout` (300s) /\n * `headersTimeout` (60s) defaults.\n */\n readonly gracefulSignals?: boolean | NodeStopOptions;\n /**\n * Sees every request before the app does, so a file it answers wins over any route at the same\n * path. It returns the file's response, or `undefined` to let the app route the request. No hook\n * of the app runs for a request it answers. The same option as Bun's `app.listen()` and\n * `@nifrajs/deno`'s `serve()`.\n *\n * {@link serveStatic} is the one to pass for files on disk: this adapter runs its mounts on Node's\n * own request, so a request they pass on keeps the app's direct lane. Any other function needs a\n * Web `Request` for every request, which roughly doubles the cost of a small route.\n */\n readonly static?: (request: Request) => Response | Promise<Response | undefined> | undefined;\n /**\n * Make a hand-rolled `return new Response(body)` ride the direct-write lane, by swapping\n * `globalThis.Response` for a stand-in that defers a *simple* construction (a string body, no\n * `statusText`, no headers or a plain header record) the way `c.text` / `c.json` already do.\n *\n * Off by default: prefer `c.text` / `c.json`, which get this without a global swap. Reach for the\n * flag only when handlers construct `Response` by hand on the hot path. It patches a process-global\n * builtin, so every `new Response(...)` anywhere in the process goes through the stand-in -\n * transparent (non-simple bodies build a real `Response`, and simple ones stay `instanceof\n * Response`), but a broad enough change to be opt-in.\n */\n readonly fastResponse?: boolean;\n}"
14764
14834
  },
14765
14835
  {
14766
- "name": "ServePublicDirOptions",
14836
+ "name": "ServeStaticOptions",
14767
14837
  "kind": "interface",
14768
- "package": "@nifrajs/web",
14769
- "signature": "export interface ServePublicDirOptions {\n /** Absolute path of the directory to serve. */\n readonly dir: string;\n /** URL prefix whose files are content-hashed and may be cached immutably (default `\"/assets/\"`).\n * Ignored when `hashedFiles` is set. */\n readonly hashedPrefix?: string;\n /**\n * Encoded URL paths of the content-hashed files, such as a build manifest's `assets`. When set, only\n * these are cached immutably and every other file gets the `assets` policy, so a user-authored file\n * that happens to sit under the hashed prefix still revalidates.\n */\n readonly hashedFiles?: ReadonlySet<string>;\n readonly cache?: PublicDirCache;\n /** Optional encoded URL-path allowlist. When present, route misses avoid a filesystem probe. */\n readonly files?: ReadonlySet<string>;\n}"
14838
+ "package": "@nifrajs/core",
14839
+ "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 * The content-hashed files, matched on the URL path as sent. When set, `immutable` applies only to\n * these, and any other file is sent with `cacheControl`, so a file that keeps its name across deploys\n * still revalidates. One of:\n *\n * - paths, such as a build manifest's `assets`;\n * - patterns, for files a pre-build step hashed that no manifest lists:\n * `[/^\\/fonts\\/[\\w-]+-[0-9a-f]{16}\\.woff2$/]`;\n * - a predicate, to combine the two: `(path) => assets.has(path) || FONT.test(path)`. It runs as\n * written, so a RegExp it tests should be neither global nor sticky.\n */\n readonly hashedFiles?: HashedFiles;\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`. `false` passes the request on, without touching the filesystem, to the next mount and then\n * the app - the seam a host policy uses so a host's refused file meets the app's own refusal instead\n * 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 as a missing file is, so probing can't distinguish \"hidden\" from\n * \"absent\". `/.well-known` is public by definition (RFC 8615) and always served. The rule applies to\n * the requested path and again to the file it resolves to, so a visible name linking to `.env` is\n * denied too. Set `\"allow\"` if the directory deliberately holds dotfiles.\n */\n readonly dotfiles?: \"deny\" | \"allow\";\n /**\n * What a path under `prefix` this mount cannot serve does: a missing or hidden file, a link out of\n * the directory, a malformed or traversing path. Default `false`: answered `404` (`400` malformed,\n * `403` traversing), so a missing asset is never rendered as a page. `true` passes it to the next\n * mount, then the app - for a mount at `\"/\"` beside the app's own routes.\n */\n readonly fallthrough?: boolean;\n}",
14840
+ "doc": "/**\n * One directory `serveStatic()` serves under a URL prefix: the same options on Bun\n * (`@nifrajs/core/serve-static`), `@nifrajs/node` and `@nifrajs/deno`. Each runtime reads the files\n * with its own fastest file API; which request a mount takes, and how it answers, is decided here.\n */"
14841
+ },
14842
+ {
14843
+ "name": "ServeStaticOptions",
14844
+ "kind": "interface",
14845
+ "package": "@nifrajs/deno",
14846
+ "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 * The content-hashed files, matched on the URL path as sent. When set, `immutable` applies only to\n * these, and any other file is sent with `cacheControl`, so a file that keeps its name across deploys\n * still revalidates. One of:\n *\n * - paths, such as a build manifest's `assets`;\n * - patterns, for files a pre-build step hashed that no manifest lists:\n * `[/^\\/fonts\\/[\\w-]+-[0-9a-f]{16}\\.woff2$/]`;\n * - a predicate, to combine the two: `(path) => assets.has(path) || FONT.test(path)`. It runs as\n * written, so a RegExp it tests should be neither global nor sticky.\n */\n readonly hashedFiles?: HashedFiles;\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`. `false` passes the request on, without touching the filesystem, to the next mount and then\n * the app - the seam a host policy uses so a host's refused file meets the app's own refusal instead\n * 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 as a missing file is, so probing can't distinguish \"hidden\" from\n * \"absent\". `/.well-known` is public by definition (RFC 8615) and always served. The rule applies to\n * the requested path and again to the file it resolves to, so a visible name linking to `.env` is\n * denied too. Set `\"allow\"` if the directory deliberately holds dotfiles.\n */\n readonly dotfiles?: \"deny\" | \"allow\";\n /**\n * What a path under `prefix` this mount cannot serve does: a missing or hidden file, a link out of\n * the directory, a malformed or traversing path. Default `false`: answered `404` (`400` malformed,\n * `403` traversing), so a missing asset is never rendered as a page. `true` passes it to the next\n * mount, then the app - for a mount at `\"/\"` beside the app's own routes.\n */\n readonly fallthrough?: boolean;\n}",
14847
+ "doc": "/**\n * One directory `serveStatic()` serves under a URL prefix: the same options on Bun\n * (`@nifrajs/core/serve-static`), `@nifrajs/node` and `@nifrajs/deno`. Each runtime reads the files\n * with its own fastest file API; which request a mount takes, and how it answers, is decided here.\n */"
14770
14848
  },
14771
14849
  {
14772
14850
  "name": "ServeStaticOptions",
14773
14851
  "kind": "interface",
14774
14852
  "package": "@nifrajs/node",
14775
- "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}",
14776
- "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 */"
14853
+ "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 * The content-hashed files, matched on the URL path as sent. When set, `immutable` applies only to\n * these, and any other file is sent with `cacheControl`, so a file that keeps its name across deploys\n * still revalidates. One of:\n *\n * - paths, such as a build manifest's `assets`;\n * - patterns, for files a pre-build step hashed that no manifest lists:\n * `[/^\\/fonts\\/[\\w-]+-[0-9a-f]{16}\\.woff2$/]`;\n * - a predicate, to combine the two: `(path) => assets.has(path) || FONT.test(path)`. It runs as\n * written, so a RegExp it tests should be neither global nor sticky.\n */\n readonly hashedFiles?: HashedFiles;\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`. `false` passes the request on, without touching the filesystem, to the next mount and then\n * the app - the seam a host policy uses so a host's refused file meets the app's own refusal instead\n * 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 as a missing file is, so probing can't distinguish \"hidden\" from\n * \"absent\". `/.well-known` is public by definition (RFC 8615) and always served. The rule applies to\n * the requested path and again to the file it resolves to, so a visible name linking to `.env` is\n * denied too. Set `\"allow\"` if the directory deliberately holds dotfiles.\n */\n readonly dotfiles?: \"deny\" | \"allow\";\n /**\n * What a path under `prefix` this mount cannot serve does: a missing or hidden file, a link out of\n * the directory, a malformed or traversing path. Default `false`: answered `404` (`400` malformed,\n * `403` traversing), so a missing asset is never rendered as a page. `true` passes it to the next\n * mount, then the app - for a mount at `\"/\"` beside the app's own routes.\n */\n readonly fallthrough?: boolean;\n}",
14854
+ "doc": "/**\n * One directory `serveStatic()` serves under a URL prefix: the same options on Bun\n * (`@nifrajs/core/serve-static`), `@nifrajs/node` and `@nifrajs/deno`. Each runtime reads the files\n * with its own fastest file API; which request a mount takes, and how it answers, is decided here.\n */"
14777
14855
  },
14778
14856
  {
14779
14857
  "name": "ServeStdioOptions",
@@ -14797,14 +14875,14 @@
14797
14875
  "name": "Server",
14798
14876
  "kind": "class",
14799
14877
  "package": "@nifrajs/core",
14800
- "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 validateHost;\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 stoppingHooks;\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 * Register a callback awaited as soon as `stop()` begins, while the server still serves: readiness\n * should fail from here, and work that outlives a request (a poller, a queue consumer) should stop\n * taking more. Hung callbacks are bounded.\n */\n onStopping(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. An\n * `authenticate()` stage registered before the mount, or a required auth plugin built on one\n * (`bearer()`, `jwt()`, `basicAuth()`, `apiKey()`), refuses a request before the handler sees it;\n * mount before the stage to keep the legacy surface public.\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, and for the `mount()` and\n * `mountFetch()` handlers registered after it: a request it refuses never reaches them.\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; `delayMs` is the time a load balancer\n * gets to stop routing here first. The `onStopping` hooks run before that delay, the `onStop`\n * hooks after the drain. Open WebSockets get a 1001 close when the drain starts and the same\n * window to finish it; a socket opened after `stop()` began is closed at once.\n */\n stop({ drainMs, delayMs }?: StopOptions): Promise<void>;\n /**\n * @internal Run the `onStopping` or the `onStop` hooks, each bounded. A runtime adapter that drains\n * its own listener calls it on either side of the drain, as `stop()` does here.\n */\n [SERVER_LIFECYCLE](phase: \"stopping\" | \"stopped\"): Promise<void>;\n private installSignalHandlers;\n}",
14878
+ "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 validateHost;\n private readonly normalizeTarget;\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 stoppingHooks;\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 * Register a callback awaited as soon as `stop()` begins, while the server still serves: readiness\n * should fail from here, and work that outlives a request (a poller, a queue consumer) should stop\n * taking more. Hung callbacks are bounded.\n */\n onStopping(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. An\n * `authenticate()` stage registered before the mount, or a required auth plugin built on one\n * (`bearer()`, `jwt()`, `basicAuth()`, `apiKey()`), refuses a request before the handler sees it;\n * mount before the stage to keep the legacy surface public.\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, and for the `mount()` and\n * `mountFetch()` handlers registered after it: a request it refuses never reaches them.\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 /** {@link fetchMatched} for an app whose `onRequest` hooks run before the route does: the hooks see\n * the request first, and the route Bun matched runs unless one of them replaced the request. */\n private fetchMatchedHooked;\n private fetchMatchedHookedInner;\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 * The stage chain a hook shape runs - derive, before, handler, after, respond - for the Web lane,\n * built once per server and shared by every route with the same number of hooks in each phase (none,\n * one or several). The chain reads a route's handler and hooks from its `FusedHooks` per request, so\n * a route's own closure (see {@link buildFusedLifecycleWeb}) holds only that record and its schemas,\n * and memory grows with the number of distinct shapes, not routes or hook functions.\n */\n private fusedWebStages;\n /**\n * Compile a fused lifecycle route's entry closure: parse (body) → validate → the shared stage chain\n * of its hook shape (derive → before → handler → after → respond, see {@link fusedWebStages}) in a\n * single frame, where the generic program walks staged hook loops. `selectRouteLanes` admits only\n * derive, before and after hooks - no params or headers schema, onError, around, decorations,\n * response contract or recovery hook, and never a query schema beside a body schema - so the behavior\n * is the compiled program's: the same stage order, the same thrown-value contract (`Response` is\n * control flow, anything else logs and 500s), the same `c.set` semantics and `fusedRespond` render.\n * The route's own closure holds only its `FusedHooks` and schemas and takes the request's context as\n * an argument, so a request allocates no step closures.\n */\n /**\n * Keep the common one-derive/one-before shape bound to its hooks. Inline its synchronous path to\n * avoid stage calls; retain helper closures only for promise continuations.\n */\n private buildFusedLifecycleWebSingle;\n private buildFusedLifecycleWeb;\n /**\n * The Node-direct twin of {@link fusedWebStages}: the same chain, finalizing through the caller's\n * own `finalize`, shared by every route with the same hook shape. A terminal `finalize` throw (an\n * unstringifiable handler return on the Node lane) is caught as `finishLifecycleContract` catches it.\n */\n private fusedNodeStages;\n /**\n * The Node-direct twin of {@link buildFusedLifecycleWeb}: the same steps, finalizing through the\n * caller's own `finalize` (the Node outcome on the direct lane) instead of building a `Response`, so\n * the `!webFast` dispatcher runs these routes in one frame rather than the generic program. A\n * terminal `finalize` throw (an unstringifiable handler return on the Node lane) is caught as\n * `finishLifecycleContract` catches it; the body's 415/400 renders take `wrapResponse` directly.\n */\n private buildFusedLifecycleRunner;\n /** The thrown-value render of the Web fused lifecycle lanes for a route with no error hooks: a\n * `Response` is control flow, anything else is logged and answered with a plain 500. */\n private fusedWebFail;\n /** {@link fusedWebFail} for a fused route that may have error hooks. */\n private fusedWebRouteFail;\n /** The thrown-value render of a fused lifecycle route. A `Response` or `status(...)` is control flow\n * that no error hook sees, unless it cannot render, which is a fault like any other. Anything else\n * goes to the route's error hooks; with none it is logged and answered with a plain 500. */\n private fusedFail;\n /** {@link respondFused} for a fused lifecycle route, whose failures reach its error hooks. */\n private respondHooks;\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. Paths a composed mount or\n * a WebSocket handshake may reach stay with the portable dispatcher; provably disjoint HTTP routes\n * keep native matching. Request hooks run before the matched route and rewrites return to dispatch.\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`, or hold those requests' connections alone with\n * `withIdleTimeout()` from `@nifrajs/core/idle-timeout`. `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 * `static` sees every request before the app does, the ones Bun's route table serves included, so\n * a file it answers wins over any route at the same path. It returns the file's response, or\n * `undefined` to let the app route the request. No hook of the app runs for a request it answers.\n * `@nifrajs/web`'s Bun build serves its client bundle and public files this way.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n readonly idleTimeoutSec?: number;\n readonly tls?: ListenTlsOptions;\n readonly static?: (request: Request) => MaybePromise<Response | undefined>;\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; `delayMs` is the time a load balancer\n * gets to stop routing here first. The `onStopping` hooks run before that delay, the `onStop`\n * hooks after the drain. Open WebSockets get a 1001 close when the drain starts and the same\n * window to finish it; a socket opened after `stop()` began is closed at once.\n */\n stop({ drainMs, delayMs }?: StopOptions): Promise<void>;\n /**\n * @internal Run the `onStopping` or the `onStop` hooks, each bounded. A runtime adapter that drains\n * its own listener calls it on either side of the drain, as `stop()` does here.\n */\n [SERVER_LIFECYCLE](phase: \"stopping\" | \"stopped\"): Promise<void>;\n private installSignalHandlers;\n}",
14801
14879
  "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 */"
14802
14880
  },
14803
14881
  {
14804
14882
  "name": "Server",
14805
14883
  "kind": "class",
14806
14884
  "package": "nifra",
14807
- "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 validateHost;\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 stoppingHooks;\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 * Register a callback awaited as soon as `stop()` begins, while the server still serves: readiness\n * should fail from here, and work that outlives a request (a poller, a queue consumer) should stop\n * taking more. Hung callbacks are bounded.\n */\n onStopping(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. An\n * `authenticate()` stage registered before the mount, or a required auth plugin built on one\n * (`bearer()`, `jwt()`, `basicAuth()`, `apiKey()`), refuses a request before the handler sees it;\n * mount before the stage to keep the legacy surface public.\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, and for the `mount()` and\n * `mountFetch()` handlers registered after it: a request it refuses never reaches them.\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; `delayMs` is the time a load balancer\n * gets to stop routing here first. The `onStopping` hooks run before that delay, the `onStop`\n * hooks after the drain. Open WebSockets get a 1001 close when the drain starts and the same\n * window to finish it; a socket opened after `stop()` began is closed at once.\n */\n stop({ drainMs, delayMs }?: StopOptions): Promise<void>;\n /**\n * @internal Run the `onStopping` or the `onStop` hooks, each bounded. A runtime adapter that drains\n * its own listener calls it on either side of the drain, as `stop()` does here.\n */\n [SERVER_LIFECYCLE](phase: \"stopping\" | \"stopped\"): Promise<void>;\n private installSignalHandlers;\n}",
14885
+ "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 validateHost;\n private readonly normalizeTarget;\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 stoppingHooks;\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 * Register a callback awaited as soon as `stop()` begins, while the server still serves: readiness\n * should fail from here, and work that outlives a request (a poller, a queue consumer) should stop\n * taking more. Hung callbacks are bounded.\n */\n onStopping(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. An\n * `authenticate()` stage registered before the mount, or a required auth plugin built on one\n * (`bearer()`, `jwt()`, `basicAuth()`, `apiKey()`), refuses a request before the handler sees it;\n * mount before the stage to keep the legacy surface public.\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, and for the `mount()` and\n * `mountFetch()` handlers registered after it: a request it refuses never reaches them.\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 /** {@link fetchMatched} for an app whose `onRequest` hooks run before the route does: the hooks see\n * the request first, and the route Bun matched runs unless one of them replaced the request. */\n private fetchMatchedHooked;\n private fetchMatchedHookedInner;\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 * The stage chain a hook shape runs - derive, before, handler, after, respond - for the Web lane,\n * built once per server and shared by every route with the same number of hooks in each phase (none,\n * one or several). The chain reads a route's handler and hooks from its `FusedHooks` per request, so\n * a route's own closure (see {@link buildFusedLifecycleWeb}) holds only that record and its schemas,\n * and memory grows with the number of distinct shapes, not routes or hook functions.\n */\n private fusedWebStages;\n /**\n * Compile a fused lifecycle route's entry closure: parse (body) → validate → the shared stage chain\n * of its hook shape (derive → before → handler → after → respond, see {@link fusedWebStages}) in a\n * single frame, where the generic program walks staged hook loops. `selectRouteLanes` admits only\n * derive, before and after hooks - no params or headers schema, onError, around, decorations,\n * response contract or recovery hook, and never a query schema beside a body schema - so the behavior\n * is the compiled program's: the same stage order, the same thrown-value contract (`Response` is\n * control flow, anything else logs and 500s), the same `c.set` semantics and `fusedRespond` render.\n * The route's own closure holds only its `FusedHooks` and schemas and takes the request's context as\n * an argument, so a request allocates no step closures.\n */\n /**\n * Keep the common one-derive/one-before shape bound to its hooks. Inline its synchronous path to\n * avoid stage calls; retain helper closures only for promise continuations.\n */\n private buildFusedLifecycleWebSingle;\n private buildFusedLifecycleWeb;\n /**\n * The Node-direct twin of {@link fusedWebStages}: the same chain, finalizing through the caller's\n * own `finalize`, shared by every route with the same hook shape. A terminal `finalize` throw (an\n * unstringifiable handler return on the Node lane) is caught as `finishLifecycleContract` catches it.\n */\n private fusedNodeStages;\n /**\n * The Node-direct twin of {@link buildFusedLifecycleWeb}: the same steps, finalizing through the\n * caller's own `finalize` (the Node outcome on the direct lane) instead of building a `Response`, so\n * the `!webFast` dispatcher runs these routes in one frame rather than the generic program. A\n * terminal `finalize` throw (an unstringifiable handler return on the Node lane) is caught as\n * `finishLifecycleContract` catches it; the body's 415/400 renders take `wrapResponse` directly.\n */\n private buildFusedLifecycleRunner;\n /** The thrown-value render of the Web fused lifecycle lanes for a route with no error hooks: a\n * `Response` is control flow, anything else is logged and answered with a plain 500. */\n private fusedWebFail;\n /** {@link fusedWebFail} for a fused route that may have error hooks. */\n private fusedWebRouteFail;\n /** The thrown-value render of a fused lifecycle route. A `Response` or `status(...)` is control flow\n * that no error hook sees, unless it cannot render, which is a fault like any other. Anything else\n * goes to the route's error hooks; with none it is logged and answered with a plain 500. */\n private fusedFail;\n /** {@link respondFused} for a fused lifecycle route, whose failures reach its error hooks. */\n private respondHooks;\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. Paths a composed mount or\n * a WebSocket handshake may reach stay with the portable dispatcher; provably disjoint HTTP routes\n * keep native matching. Request hooks run before the matched route and rewrites return to dispatch.\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`, or hold those requests' connections alone with\n * `withIdleTimeout()` from `@nifrajs/core/idle-timeout`. `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 * `static` sees every request before the app does, the ones Bun's route table serves included, so\n * a file it answers wins over any route at the same path. It returns the file's response, or\n * `undefined` to let the app route the request. No hook of the app runs for a request it answers.\n * `@nifrajs/web`'s Bun build serves its client bundle and public files this way.\n */\n listen(port: number, options?: {\n readonly reusePort?: boolean;\n readonly hostname?: string;\n readonly idleTimeoutSec?: number;\n readonly tls?: ListenTlsOptions;\n readonly static?: (request: Request) => MaybePromise<Response | undefined>;\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; `delayMs` is the time a load balancer\n * gets to stop routing here first. The `onStopping` hooks run before that delay, the `onStop`\n * hooks after the drain. Open WebSockets get a 1001 close when the drain starts and the same\n * window to finish it; a socket opened after `stop()` began is closed at once.\n */\n stop({ drainMs, delayMs }?: StopOptions): Promise<void>;\n /**\n * @internal Run the `onStopping` or the `onStop` hooks, each bounded. A runtime adapter that drains\n * its own listener calls it on either side of the drain, as `stop()` does here.\n */\n [SERVER_LIFECYCLE](phase: \"stopping\" | \"stopped\"): Promise<void>;\n private installSignalHandlers;\n}",
14808
14886
  "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 */"
14809
14887
  },
14810
14888
  {
@@ -14943,6 +15021,13 @@
14943
15021
  "signature": "export type ServerEntryOptionImports = Readonly<Partial<Record<ServerEntryOption, string>>>;",
14944
15022
  "doc": "/** Each importable option mapped to the specifier of the module that exports it. */"
14945
15023
  },
15024
+ {
15025
+ "name": "ServerEntrySelfHost",
15026
+ "kind": "interface",
15027
+ "package": "@nifrajs/web",
15028
+ "signature": "export interface ServerEntrySelfHost {\n readonly gracefulSignals?: boolean | {\n readonly drainMs?: number;\n readonly delayMs?: number;\n };\n readonly idleTimeoutSec?: number;\n}",
15029
+ "doc": "/**\n * Settings the server of a self-hosting target (`bun`, `node`, `deno`) starts with; an edge target has\n * no process of its own and ignores them. `gracefulSignals` stops the server gracefully on SIGTERM and\n * SIGINT (`docker stop`, Ctrl-C): `true`, or the `{ drainMs, delayMs }` its `stop()` takes.\n * `idleTimeoutSec` is how long Bun keeps a connection that moves no bytes, a whole number from `0`\n * (never) to 255, a request whose handler is still working included. Node and Deno do not close a\n * connection while its request is being handled, so they ignore it.\n */"
15030
+ },
14946
15031
  {
14947
15032
  "name": "ServerFn",
14948
15033
  "kind": "interface",
@@ -15045,13 +15130,13 @@
15045
15130
  "name": "ServerOptions",
15046
15131
  "kind": "interface",
15047
15132
  "package": "@nifrajs/core",
15048
- "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 * Answer `400 invalid_host` on Bun to every Host that Node and Deno refuse: one sent twice, one\n * no URL can be built on (a space, a byte past ASCII, a port past 65535, an IPv6 literal no parser\n * takes), a percent-encoded or sub-delimiter one, and serve an HTTP/1.0 request with no Host as\n * `localhost`. Bun serves those requests itself, building `c.req.url` on the first Host or leaving\n * it relative, so `new URL(c.req.url)` can throw in a handler.\n *\n * Disabled by default: the check reads the Host on every request, which measured about 6% of a bare\n * route on Bun. Left off, a target with `.` or `..` segments is still checked, so a dot segment is\n * never routed raw. Node and Deno refuse these Hosts either way; the option changes nothing there.\n */\n readonly validateHost?: 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 up to 1.4.3 drops the\n * connection (the client sees `1006`) and Bun 1.4.4 sends `1009`, while the `close` handler gets\n * `1009` either way. 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 * The object form is passed to `stop()`: see {@link StopOptions}.\n */\n readonly gracefulSignals?: boolean | StopOptions;\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}"
15133
+ "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 * Answer `400 invalid_host` for Hosts the request target cannot safely be built on: one sent\n * twice, one with a space or byte past ASCII, a port past 65535, an IPv6 literal no URL parser\n * takes, a percent-encoded or sub-delimiter Host, or an authority that can change Deno's route.\n * Bun may leave `c.req.url` relative or build it on the first Host, so `new URL(c.req.url)` can\n * throw in a handler.\n *\n * Disabled by default: checking Host on every request measured about 6% of a bare route on Bun.\n * Deno builds `Request.url` from Host; without this check, a malformed Host can change the routed\n * path. Enable it when Deno receives requests with an untrusted Host header.\n */\n readonly validateHost?: boolean;\n /**\n * Route a Deno request on the path a WHATWG parser would give it. Bun and workerd deliver a parsed\n * URL, so `/public/../admin` reaches the app as `/admin`; Deno hands over the target as sent. Off,\n * Deno routes the text received, as most frameworks do: a guard on `/admin` does not see\n * `/public/../admin`, and a proxy that normalizes paths before forwarding disagrees with the app\n * about which route a request is for. On, dot segments (`.`, `..`, `%2e`), backslashes and the\n * characters a parser percent-encodes are resolved before routing, so every runtime routes the\n * same path.\n *\n * Disabled by default: the check reads and scans the whole URL of every request, measured at about\n * 3% of a bare route on Deno. Enable it when path guards, or a path-normalizing proxy, sit in\n * front of or inside the app. Bun already delivers parsed targets and is unaffected; `@nifrajs/node`\n * has the same option on `serve()`.\n */\n readonly normalizeTarget?: 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 up to 1.4.3 drops the\n * connection (the client sees `1006`) and Bun 1.4.4 sends `1009`, while the `close` handler gets\n * `1009` either way. 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 * The object form is passed to `stop()`: see {@link StopOptions}.\n */\n readonly gracefulSignals?: boolean | StopOptions;\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}"
15049
15134
  },
15050
15135
  {
15051
15136
  "name": "ServerOptions",
15052
15137
  "kind": "interface",
15053
15138
  "package": "nifra",
15054
- "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 * Answer `400 invalid_host` on Bun to every Host that Node and Deno refuse: one sent twice, one\n * no URL can be built on (a space, a byte past ASCII, a port past 65535, an IPv6 literal no parser\n * takes), a percent-encoded or sub-delimiter one, and serve an HTTP/1.0 request with no Host as\n * `localhost`. Bun serves those requests itself, building `c.req.url` on the first Host or leaving\n * it relative, so `new URL(c.req.url)` can throw in a handler.\n *\n * Disabled by default: the check reads the Host on every request, which measured about 6% of a bare\n * route on Bun. Left off, a target with `.` or `..` segments is still checked, so a dot segment is\n * never routed raw. Node and Deno refuse these Hosts either way; the option changes nothing there.\n */\n readonly validateHost?: 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 up to 1.4.3 drops the\n * connection (the client sees `1006`) and Bun 1.4.4 sends `1009`, while the `close` handler gets\n * `1009` either way. 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 * The object form is passed to `stop()`: see {@link StopOptions}.\n */\n readonly gracefulSignals?: boolean | StopOptions;\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}"
15139
+ "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 * Answer `400 invalid_host` for Hosts the request target cannot safely be built on: one sent\n * twice, one with a space or byte past ASCII, a port past 65535, an IPv6 literal no URL parser\n * takes, a percent-encoded or sub-delimiter Host, or an authority that can change Deno's route.\n * Bun may leave `c.req.url` relative or build it on the first Host, so `new URL(c.req.url)` can\n * throw in a handler.\n *\n * Disabled by default: checking Host on every request measured about 6% of a bare route on Bun.\n * Deno builds `Request.url` from Host; without this check, a malformed Host can change the routed\n * path. Enable it when Deno receives requests with an untrusted Host header.\n */\n readonly validateHost?: boolean;\n /**\n * Route a Deno request on the path a WHATWG parser would give it. Bun and workerd deliver a parsed\n * URL, so `/public/../admin` reaches the app as `/admin`; Deno hands over the target as sent. Off,\n * Deno routes the text received, as most frameworks do: a guard on `/admin` does not see\n * `/public/../admin`, and a proxy that normalizes paths before forwarding disagrees with the app\n * about which route a request is for. On, dot segments (`.`, `..`, `%2e`), backslashes and the\n * characters a parser percent-encodes are resolved before routing, so every runtime routes the\n * same path.\n *\n * Disabled by default: the check reads and scans the whole URL of every request, measured at about\n * 3% of a bare route on Deno. Enable it when path guards, or a path-normalizing proxy, sit in\n * front of or inside the app. Bun already delivers parsed targets and is unaffected; `@nifrajs/node`\n * has the same option on `serve()`.\n */\n readonly normalizeTarget?: 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 up to 1.4.3 drops the\n * connection (the client sees `1006`) and Bun 1.4.4 sends `1009`, while the `close` handler gets\n * `1009` either way. 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 * The object form is passed to `stop()`: see {@link StopOptions}.\n */\n readonly gracefulSignals?: boolean | StopOptions;\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}"
15055
15140
  },
15056
15141
  {
15057
15142
  "name": "ServerPrerenderedPage",
@@ -15156,7 +15241,7 @@
15156
15241
  "name": "SessionOptions",
15157
15242
  "kind": "interface",
15158
15243
  "package": "@nifrajs/auth",
15159
- "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}"
15244
+ "signature": "export interface SessionOptions<Data extends Record<string, unknown> = Record<string, unknown>> {\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 /**\n * The data keys that say who the visitor is: a user id, and any key that changes what a page may\n * show, such as an organization or a role. The session cookie carries a tag that changes only when\n * one of them does, so `@nifrajs/web` keep-alive keeps the pages it holds across a commit that\n * writes other data, a cart say. Unset, every key counts and any change to the data changes the\n * tag. Leaving out a key that decides what a page shows lets the next visitor of a browser see the\n * pages kept for the previous one.\n */\n readonly identity?: readonly (keyof Data & string)[];\n}"
15160
15245
  },
15161
15246
  {
15162
15247
  "name": "SessionRecord",
@@ -15729,6 +15814,27 @@
15729
15814
  "signature": "export interface StaticCtx {\n readonly phase: \"build\";\n /** The deployment's origin, when the caller resolving static boundaries knows it. A request never\n * supplies it: the value is cached for every visitor, and a Host header is the client's to choose. */\n readonly origin?: string;\n}",
15730
15815
  "doc": "/** Build-safe inputs available to a static boundary. It intentionally has no request/session/params API. */"
15731
15816
  },
15817
+ {
15818
+ "name": "StaticFileAccess",
15819
+ "kind": "interface",
15820
+ "package": "@nifrajs/core",
15821
+ "signature": "export interface StaticFileAccess {\n /** The real path the file was opened at: what tags and types it. */\n readonly path: string;\n readonly version: FileVersion;\n /** Read the whole file, up to {@link CONTENT_SNAPSHOT_MAX} bytes, through the open descriptor. */\n readonly readWhole: () => Promise<Uint8Array>;\n /** Stat the open descriptor again. */\n readonly restat: () => Promise<FileVersion>;\n readonly tags: ContentTags;\n /** `@nifrajs/core/range`'s parser, passed in so this module imports nothing. */\n readonly parseRange: (value: string, size: number) => {\n readonly kind: \"none\" | \"unsatisfiable\";\n } | {\n readonly kind: \"satisfiable\";\n readonly ranges: readonly {\n readonly start: number;\n readonly end: number;\n }[];\n };\n}",
15822
+ "doc": "/** How a reader reaches the opened, pinned file for {@link planStatic}. */"
15823
+ },
15824
+ {
15825
+ "name": "StaticMatch",
15826
+ "kind": "type",
15827
+ "package": "@nifrajs/core",
15828
+ "signature": "export type StaticMatch = \"pass\" | {\n readonly status: 400 | 403 | 404;\n} | {\n readonly rel: string;\n readonly immutable: boolean;\n};",
15829
+ "doc": "/**\n * What a mount does with a request path: `\"pass\"` to the next mount and then the app, a status to\n * answer with, or the decoded path relative to the mount's directory (no leading slash, no `.` or `..`\n * segment, no backslash or NUL) to read.\n */"
15830
+ },
15831
+ {
15832
+ "name": "StaticMount",
15833
+ "kind": "interface",
15834
+ "package": "@nifrajs/core",
15835
+ "signature": "export interface StaticMount {\n readonly root: string;\n /** `\"/\"`, or the prefix with one leading and no trailing slash. */\n readonly prefix: string;\n readonly isImmutable: (path: string) => boolean;\n readonly cacheControl: string | undefined;\n readonly files: ReadonlySet<string> | undefined;\n readonly allow: ((host: string, pathname: string) => boolean) | undefined;\n /** Lowercased names. */\n readonly headers: Readonly<Record<string, string>> | undefined;\n readonly denyDotfiles: boolean;\n readonly fallthrough: boolean;\n}",
15836
+ "doc": "/** A {@link ServeStaticOptions} checked once, with its directory resolved by the runtime's reader. */"
15837
+ },
15732
15838
  {
15733
15839
  "name": "StaticPath",
15734
15840
  "kind": "interface",
@@ -15743,6 +15849,20 @@
15743
15849
  "signature": "export interface StaticPaths {\n readonly paths: readonly StaticPath[];\n /**\n * How a path NOT in `paths` is handled. `\"ssr\"` (default) → rendered on-demand by the worker\n * (the natural hybrid behavior - an unlisted path simply isn't a static file); `\"404\"` → only the\n * listed paths exist. Recorded by `prerenderRoutes` for the deploy layer.\n */\n readonly fallback?: \"ssr\" | \"404\";\n}",
15744
15850
  "doc": "/** What a route's `getStaticPaths` returns: the param sets to prerender + the unlisted-path policy. */"
15745
15851
  },
15852
+ {
15853
+ "name": "StaticPlan",
15854
+ "kind": "type",
15855
+ "package": "@nifrajs/core",
15856
+ "signature": "export type StaticPlan = {\n readonly status: 200 | 206 | 304 | 416;\n readonly headers: Record<string, string>;\n readonly body: false;\n} | {\n readonly status: 200 | 206;\n readonly headers: Record<string, string>;\n readonly body: true;\n readonly start: number;\n readonly length: number;\n};",
15857
+ "doc": "/**\n * What a reader sends for a file a mount took: a header-only answer, or `length` bytes from `start`.\n * When tagging it called `readWhole`, the body comes from those same bytes.\n */"
15858
+ },
15859
+ {
15860
+ "name": "StaticRequest",
15861
+ "kind": "interface",
15862
+ "package": "@nifrajs/core",
15863
+ "signature": "export interface StaticRequest {\n readonly method: \"GET\" | \"HEAD\";\n readonly header: (name: string) => string | null;\n}",
15864
+ "doc": "/** A request's part of a static answer: its method and its headers by lowercase name. */"
15865
+ },
15746
15866
  {
15747
15867
  "name": "StaticRoutes",
15748
15868
  "kind": "interface",
@@ -16852,14 +16972,14 @@
16852
16972
  "name": "VERSION",
16853
16973
  "kind": "const",
16854
16974
  "package": "@nifrajs/core",
16855
- "signature": "export declare const VERSION: \"5.8.0\";",
16975
+ "signature": "export declare const VERSION: \"5.9.0\";",
16856
16976
  "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 */"
16857
16977
  },
16858
16978
  {
16859
16979
  "name": "VERSION",
16860
16980
  "kind": "const",
16861
16981
  "package": "nifra",
16862
- "signature": "export declare const VERSION: \"5.8.0\";",
16982
+ "signature": "export declare const VERSION: \"5.9.0\";",
16863
16983
  "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 */"
16864
16984
  },
16865
16985
  {
@@ -17442,6 +17562,13 @@
17442
17562
  "signature": "export declare function applyHead(head: Meta, path?: string): void;",
17443
17563
  "doc": "/**\n * Sync the document head to a route's resolved {@link Meta} on client navigation. Sets the title\n * (when provided) and replaces the **managed** (`data-nifra`) `<meta>`/`<link>` tags - static head\n * content (charset, hand-written tags) is never touched. SSR injects the same `data-nifra` tags, so\n * the first navigation cleanly takes over from the server-rendered head.\n */"
17444
17564
  },
17565
+ {
17566
+ "name": "applyInvariantSetup",
17567
+ "kind": "function",
17568
+ "package": "@nifrajs/core",
17569
+ "signature": "export declare function applyInvariantSetup(invariants: InvariantsConfig, result: InvariantSetupResult | undefined): AppliedInvariantSetup;",
17570
+ "doc": "/**\n * Merge what `invariants.setup` returned over the static `invariants`, validating it the way\n * `defineAssuranceConfig` validates the static fields: its executor and prepareRequest replace the\n * static ones, and its witnesses are merged over theirs, a key in both taking the setup's. For a\n * harness that runs L4 itself; `nifra levels` calls it once setup resolves.\n */"
17571
+ },
17445
17572
  {
17446
17573
  "name": "applyResponseHeaders",
17447
17574
  "kind": "function",
@@ -18055,7 +18182,14 @@
18055
18182
  "kind": "function",
18056
18183
  "package": "@nifrajs/coding-agent",
18057
18184
  "signature": "export declare function canonicalJson(value: unknown): string;",
18058
- "doc": "/** Deterministic JSON with recursively sorted object keys. Arrays keep order. Rejects non-finite numbers. */"
18185
+ "doc": "/** The canonical JSON text of `value`. Throws a `TypeError` on a value JSON cannot carry. */"
18186
+ },
18187
+ {
18188
+ "name": "canonicalJson",
18189
+ "kind": "function",
18190
+ "package": "@nifrajs/core",
18191
+ "signature": "export declare function canonicalJson(value: unknown): string;",
18192
+ "doc": "/** The canonical JSON text of `value`. Throws a `TypeError` on a value JSON cannot carry. */"
18059
18193
  },
18060
18194
  {
18061
18195
  "name": "canonicalManifest",
@@ -18106,6 +18240,20 @@
18106
18240
  "signature": "export declare function captureInto(feed: DevFeed): () => void;",
18107
18241
  "doc": "/**\n * Record the process's console and stream output into `feed`: every line as a log entry, and core's\n * `unhandled request error` line additionally as an `api` error with a full Diagnostic. The one sink\n * both dev servers and `nifra_run` use. Returns the detach function.\n */"
18108
18242
  },
18243
+ {
18244
+ "name": "carryRequestLocals",
18245
+ "kind": "function",
18246
+ "package": "@nifrajs/core",
18247
+ "signature": "export declare function carryRequestLocals(from: Request, to: Request): void;",
18248
+ "doc": "/**\n * Join `to` to `from`'s request-local scope: each then reads every value set through either, now\n * and later. nifra does this wherever it rebuilds a request itself; call it where a wrapper or an\n * `onRequest` hook rebuilds one, right after `new Request(url, req)`. A value `to` already holds is\n * kept where `from` has none.\n */"
18249
+ },
18250
+ {
18251
+ "name": "carryRequestLocals",
18252
+ "kind": "function",
18253
+ "package": "nifra",
18254
+ "signature": "export declare function carryRequestLocals(from: Request, to: Request): void;",
18255
+ "doc": "/**\n * Join `to` to `from`'s request-local scope: each then reads every value set through either, now\n * and later. nifra does this wherever it rebuilds a request itself; call it where a wrapper or an\n * `onRequest` hook rebuilds one, right after `new Request(url, req)`. A value `to` already holds is\n * kept where `from` has none.\n */"
18256
+ },
18109
18257
  {
18110
18258
  "name": "catalogFixPrompts",
18111
18259
  "kind": "function",
@@ -18675,7 +18823,7 @@
18675
18823
  "kind": "function",
18676
18824
  "package": "@nifrajs/web",
18677
18825
  "signature": "export declare function copyPublicDir(from: string, to: string): Promise<string[]>;",
18678
- "doc": "/**\n * Copy `from` into `to`, returning the URL paths copied (sorted). Hidden entries other than\n * `.well-known` are skipped, as development never serves them: every target ships this list, and a\n * CDN-hosted one serves whatever was copied.\n *\n * Lives here, not beside `servePublicDir`, because it is BUILD-time: it reaches for `Bun.Glob` and\n * `node:fs`, and `public-dir.ts` is reachable from the client bundle graph through the package\n * entry - a dynamic `import(\"bun\")` there fails the browser build outright.\n */"
18826
+ "doc": "/**\n * Copy `from` into `to`, returning the URL paths copied (sorted). Hidden entries other than\n * `.well-known` are skipped, as development never serves them: every target ships this list, and a\n * CDN-hosted one serves whatever was copied.\n *\n * Lives here, not in `public-dir.ts`, because it is BUILD-time: it reaches for `Bun.Glob` and\n * `node:fs`, and `public-dir.ts` is reachable from the client bundle graph through the package\n * entry - a dynamic `import(\"bun\")` there fails the browser build outright.\n */"
18679
18827
  },
18680
18828
  {
18681
18829
  "name": "copyRef",
@@ -19185,7 +19333,7 @@
19185
19333
  "name": "createSessions",
19186
19334
  "kind": "function",
19187
19335
  "package": "@nifrajs/auth",
19188
- "signature": "export declare function createSessions<Data extends Record<string, unknown> = Record<string, unknown>>(options: SessionOptions): SessionManager<Data>;"
19336
+ "signature": "export declare function createSessions<Data extends Record<string, unknown> = Record<string, unknown>>(options: SessionOptions<Data>): SessionManager<Data>;"
19189
19337
  },
19190
19338
  {
19191
19339
  "name": "createSlotParking",
@@ -19897,7 +20045,7 @@
19897
20045
  "kind": "function",
19898
20046
  "package": "@nifrajs/cli",
19899
20047
  "signature": "export declare function docsTools(loadDocs: () => Promise<string | undefined>, loadExamples: () => Promise<Example[] | undefined>, loadTypes: () => Promise<TypeEntry[] | undefined>): McpTool[];",
19900
- "doc": "/** Build `nifra_docs` + `nifra_example` + `nifra_types` over injected corpus loaders. */"
20048
+ "doc": "/** Build the read-only docs, examples, types, learning, and frontend tools over injected loaders. */"
19901
20049
  },
19902
20050
  {
19903
20051
  "name": "durableCommand",
@@ -20458,8 +20606,8 @@
20458
20606
  "name": "generateServerEntry",
20459
20607
  "kind": "function",
20460
20608
  "package": "@nifrajs/web",
20461
- "signature": "export declare function generateServerEntry(options: {\n readonly target: BuildTarget;\n /** Import specifier for the module exporting `adapter` (e.g. `\"../framework.ts\"`). */\n readonly adapterImport: string;\n /** Import specifier for the module exporting `backend`, or `undefined` for a frontend-only app. */\n readonly backendImport?: string;\n /** Import specifier for the module exporting `use`, or `undefined`. Must resolve to the\n * same edge-safe module as `adapterImport`. */\n readonly useImport?: string;\n /** `createWebApp` options to import by name, each mapped to the specifier of the edge-safe module\n * that exports it. */\n readonly optionImports?: ServerEntryOptionImports;\n /** Document `<title>` passed to `createWebApp`. */\n readonly title?: string;\n /** Encoded root-relative public file paths copied into the deploy directory. */\n readonly publicFiles?: readonly string[];\n /** URL paths of the content-hashed client outputs (the build manifest's `assets`). When given, a\n * self-hosted entry caches only these immutably; otherwise every file under `/assets/` is. */\n readonly hashedFiles?: readonly string[];\n /** Trust the edge platform's client-address header for `c.clientIp`. See {@link ServerEntryClientIp}. */\n readonly clientIp?: ServerEntryClientIp;\n /** The server manifest exports `copyChunks` (the client build split copy tables by locale). */\n readonly copyChunks?: boolean;\n /** `bun` / `node` only: the pages the build prerendered into `_prerendered/`, by request path, which\n * the app answers from their file (see `createWebApp`'s `prerenderedPages`). */\n readonly prerenderedPages?: Readonly<Record<string, ServerPrerenderedPage>>;\n}): string;",
20462
- "doc": "/**\n * Codegen the per-target **server entry** module (source text) for `buildServer` to bundle. It imports\n * the app's `adapter` (from `framework.ts`), the optional `backend` (from `backend.ts`), and the\n * generated `{ manifest, clientEntry }` (from `./server-manifest`), builds `createWebApp`, then wires\n * the right host:\n * - `cloudflare` / `vercel`: `export default` the fetch handler (the platform serves /assets/* itself).\n * - `deno`: same fetch-handler default, plus `Deno.serve` self-host when run directly.\n * - `bun` / `node`: a self-hosting server that ALSO serves the client bundle from disk (those\n * runtimes have a filesystem; the static `/assets/*` sit next to the entry).\n * `adapterImport`/`backendImport` are the specifiers the entry uses (relative to where it's written) -\n * `buildServer` writes the entry next to `serverEntry`, so they're resolved from there. Pure (string in,\n * string out) so the generation is unit-testable without a real build.\n */"
20609
+ "signature": "export declare function generateServerEntry(options: {\n readonly target: BuildTarget;\n /** Import specifier for the module exporting `adapter` (e.g. `\"../framework.ts\"`). */\n readonly adapterImport: string;\n /** Import specifier for the module exporting `backend`, or `undefined` for a frontend-only app. */\n readonly backendImport?: string;\n /** Import specifier for the module exporting `use`, or `undefined`. Must resolve to the\n * same edge-safe module as `adapterImport`. */\n readonly useImport?: string;\n /** `createWebApp` options to import by name, each mapped to the specifier of the edge-safe module\n * that exports it. */\n readonly optionImports?: ServerEntryOptionImports;\n /** Document `<title>` passed to `createWebApp`. */\n readonly title?: string;\n /** Encoded root-relative public file paths copied into the deploy directory. */\n readonly publicFiles?: readonly string[];\n /** URL paths of the content-hashed client outputs (the build manifest's `assets`). When given, a\n * self-hosted entry caches only these immutably; otherwise every file under `/assets/` is. */\n readonly hashedFiles?: readonly string[];\n /** Trust the edge platform's client-address header for `c.clientIp`. See {@link ServerEntryClientIp}. */\n readonly clientIp?: ServerEntryClientIp;\n /** How a self-hosted server stops and keeps idle connections. See {@link ServerEntrySelfHost}. */\n readonly selfHost?: ServerEntrySelfHost;\n /** The server manifest exports `copyChunks` (the client build split copy tables by locale). */\n readonly copyChunks?: boolean;\n /** `bun` / `node` only: the pages the build prerendered into `_prerendered/`, by request path, which\n * the app answers from their file (see `createWebApp`'s `prerenderedPages`). */\n readonly prerenderedPages?: Readonly<Record<string, ServerPrerenderedPage>>;\n}): string;",
20610
+ "doc": "/**\n * Codegen the per-target **server entry** module (source text) for `buildServer` to bundle. It imports\n * the app's `adapter` (from `framework.ts`), the optional `backend` (from `backend.ts`), and the\n * generated `{ manifest, clientEntry }` (from `./server-manifest`), builds `createWebApp`, then wires\n * the right host:\n * - `cloudflare` / `vercel`: `export default` the fetch handler (the platform serves /assets/* itself).\n * - `deno`: a `@nifrajs/deno` server that serves the client bundle with Deno's file API.\n * - `bun` / `node`: a self-hosting server that ALSO serves the client bundle from disk (those\n * runtimes have a filesystem; the static `/assets/*` sit next to the entry).\n * `adapterImport`/`backendImport` are the specifiers the entry uses (relative to where it's written) -\n * `buildServer` writes the entry next to `serverEntry`, so they're resolved from there. Pure (string in,\n * string out) so the generation is unit-testable without a real build.\n */"
20463
20611
  },
20464
20612
  {
20465
20613
  "name": "generateServerManifest",
@@ -21319,7 +21467,7 @@
21319
21467
  "kind": "function",
21320
21468
  "package": "@nifrajs/mcp-db",
21321
21469
  "signature": "export declare function lintPostgresStatement(sql: string): DbRefusal | undefined;",
21322
- "doc": "/** Refuse what the tokenizer layer refuses: a non-query, several statements, a denied function. */"
21470
+ "doc": "/**\n * Refuse what the tokenizer layer refuses before connecting: a non-query, several statements, a row\n * lock, text it cannot read safely. Functions are checked against the catalog once connected.\n */"
21323
21471
  },
21324
21472
  {
21325
21473
  "name": "listFixRecipes",
@@ -21458,6 +21606,13 @@
21458
21606
  "signature": "export declare function matchRoutePattern(compiled: CompiledRoutePattern, pathname: string): RoutePatternMatch;",
21459
21607
  "doc": "/** Match one compiled pattern and return decoded captures. The caller decides cross-pattern order. */"
21460
21608
  },
21609
+ {
21610
+ "name": "matchStatic",
21611
+ "kind": "function",
21612
+ "package": "@nifrajs/core",
21613
+ "signature": "export declare function matchStatic(mount: StaticMount, path: string, host: () => string): StaticMatch;",
21614
+ "doc": "/**\n * Match `path` (the URL path as sent, without the query) against `mount`, without touching the\n * filesystem. `host` names the request's host, read only when the mount has an `allow`.\n */"
21615
+ },
21461
21616
  {
21462
21617
  "name": "matches",
21463
21618
  "kind": "function",
@@ -22059,6 +22214,13 @@
22059
22214
  "signature": "export declare function parseAcceptHeader(value: string | null): readonly ContentPreference[];",
22060
22215
  "doc": "/** Parse an `Accept` header, preserving quality and wildcard specificity. */"
22061
22216
  },
22217
+ {
22218
+ "name": "parseAgentResume",
22219
+ "kind": "function",
22220
+ "package": "@nifrajs/agent",
22221
+ "signature": "export declare function parseAgentResume(raw: unknown): AgentTurnInput[\"resume\"] | undefined;",
22222
+ "doc": "/**\n * The `resume` of an {@link AgentTurnInput} read from an untrusted wire value, or `undefined` when it\n * is not one. Every agent transport parses a resume with this, so a continuation is accepted on the\n * same terms however it arrives.\n */"
22223
+ },
22062
22224
  {
22063
22225
  "name": "parseArtifactRef",
22064
22226
  "kind": "function",
@@ -22537,6 +22699,13 @@
22537
22699
  "signature": "export declare function planSingleCopy(options?: SingleCopyOptions): SingleCopyPlan;",
22538
22700
  "doc": "/**\n * Work out which foreign copies exist and which of them may be redirected.\n *\n * Pure discovery: it reads `package.json` files and symlink targets, never application source, and\n * never mutates anything. Both the plugin and `nifra check`'s verification are built on it, so the\n * enforcement and the report cannot drift apart.\n */"
22539
22701
  },
22702
+ {
22703
+ "name": "planStatic",
22704
+ "kind": "function",
22705
+ "package": "@nifrajs/core",
22706
+ "signature": "export declare function planStatic(mount: StaticMount, immutable: boolean, request: StaticRequest, file: StaticFileAccess): Promise<StaticPlan>;",
22707
+ "doc": "/**\n * The answer for an opened file, the one sequence every runtime's reader runs: the mount's headers\n * (a caller's own `cache-control`, `last-modified` or `etag` kept), a strong tag from the snapshot\n * served for a file up to {@link CONTENT_SNAPSHOT_MAX} bytes, a `304` for a current copy, then one\n * byte range or the whole file. A larger file streams with no tag, and its date is weak: an\n * `If-Range` gets the whole file rather than a range spliced from two versions.\n */"
22708
+ },
22540
22709
  {
22541
22710
  "name": "port",
22542
22711
  "kind": "function",
@@ -22577,7 +22746,7 @@
22577
22746
  "kind": "function",
22578
22747
  "package": "@nifrajs/mcp-db",
22579
22748
  "signature": "export declare function postgresRoleSql(client: PostgresClient, options: PostgresRoleSqlOptions): Promise<PostgresRoleSql | DbRefusal>;",
22580
- "doc": "/**\n * Write the SQL for a login role that can read the allowed schemas and nothing else: `GRANT SELECT`\n * per schema plus default privileges, and a `REVOKE` for each excluded table and its partitions.\n * `pg_read_all_data` is never used: it reaches every schema, present and future, and overrides a\n * REVOKE. Nothing is executed.\n */"
22749
+ "doc": "/**\n * Write the SQL for a login role that can read the allowed schemas and nothing the declaration hides:\n * `USAGE` on each allowed schema, `SELECT` on its tables plus default privileges, then a `REVOKE` for\n * each excluded table, its partitions and children, and each view or materialized view that reads\n * hidden data, and, for a table with a masked column, a `REVOKE` followed by a column-level `GRANT` of\n * the other columns. That is what the grant gate checks before each query. A grant the role would\n * still read hidden data through (to PUBLIC, or, for a role that exists, to a role whose privileges it\n * has) is listed in comments with the `REVOKE` the gate needs, since that reaches other roles; so is\n * each SECURITY DEFINER function the role may execute, where a grant to the role itself is revoked\n * outright. `pg_read_all_data` is never used: it reaches every schema, present and future, and\n * overrides a REVOKE. Nothing is executed.\n */"
22581
22750
  },
22582
22751
  {
22583
22752
  "name": "poweredBy",
@@ -22752,7 +22921,7 @@
22752
22921
  "kind": "function",
22753
22922
  "package": "@nifrajs/mcp-db",
22754
22923
  "signature": "export declare function queryPostgres(client: PostgresClient, sql: string, options: PostgresQueryOptions): Promise<DbRows | DbRefusal>;",
22755
- "doc": "/**\n * Run one read-only query through every layer and return capped rows. A column `redaction.column`\n * masks is refused wherever the plan uses it (selected under any alias, inside an expression, in a\n * filter, or within a whole row); a matching result name is masked as well.\n */"
22924
+ "doc": "/**\n * Run one read-only query through every layer and return capped rows. A column `redaction.column`\n * masks is one the role may not read (the grant gate), and is refused wherever the plan uses it\n * (selected under any alias, inside an expression, in a filter, or within a whole row); a matching\n * result name is masked as well.\n */"
22756
22925
  },
22757
22926
  {
22758
22927
  "name": "querySqlite",
@@ -22779,15 +22948,15 @@
22779
22948
  "name": "rateLimit",
22780
22949
  "kind": "function",
22781
22950
  "package": "@nifrajs/middleware",
22782
- "signature": "export declare function rateLimit(options: RateLimitOptions): Middleware;",
22951
+ "signature": "export declare function rateLimit(options: RateLimitOptions): RateLimiter;",
22783
22952
  "doc": "/**\n * Rate limiting as a {@link Middleware}. Runs in `onRequest` (before routing, so it\n * also covers 404s); over the limit → `429` + `Retry-After`. Every response carries\n * `RateLimit-Limit/Remaining/Reset` (added in `onResponse`, keyed off the request).\n */"
22784
22953
  },
22785
22954
  {
22786
22955
  "name": "rateLimitTiers",
22787
22956
  "kind": "function",
22788
22957
  "package": "@nifrajs/middleware",
22789
- "signature": "export declare function rateLimitTiers(options: RateLimitTiersOptions): Middleware;",
22790
- "doc": "/**\n * Rate limiting in tiers under one app-wide floor, as a single {@link Middleware}. Every request is\n * charged to at most one bucket: the tier with the longest `prefix` that is the request's path or an\n * ancestor of it, else the `floor`, else none when there is no floor. Tiers never stack, so a tier\n * may sit above the floor (`600/min` for `/api/public` under a `120/min` floor). It runs in\n * `onRequest`, before routing, so a 404, a 405 or a body that fails validation is charged too.\n * Prefixes are validated here; each tier counts in its own keys, so tiers can share one store.\n */"
22958
+ "signature": "export declare function rateLimitTiers(options: RateLimitTiersOptions): RateLimiter;",
22959
+ "doc": "/**\n * Rate limiting in tiers under one app-wide floor, as a single {@link Middleware}. Every request is\n * charged to at most one bucket: the tier owning the longest prefix that is the request's path or an\n * ancestor of it, across every tier's prefixes, else the `floor`, else none when there is no floor.\n * Tiers never stack, so a tier may sit above the floor (`600/min` for `/api/public` under a\n * `120/min` floor). It runs in `onRequest`, before routing, so a 404, a 405 or a body that fails\n * validation is charged too. Prefixes and names are validated here; each tier counts in its own\n * keys, so tiers can share one store.\n */"
22791
22960
  },
22792
22961
  {
22793
22962
  "name": "raw",
@@ -23304,6 +23473,20 @@
23304
23473
  "signature": "export declare function requestId(options?: RequestIdOptions): ContextPlugin<{\n requestId: string;\n}>;",
23305
23474
  "doc": "/**\n * A {@link defineContextPlugin} plugin that gives every request a stable id: it reuses an inbound\n * `x-request-id` (or generates one), exposes it on the handler context as **`c.requestId`** (typed,\n * threaded by `derive`), and echoes it on EVERY response leaving the app - handler-returned raw\n * `Response`s and redirects, `onRequest` short-circuits (an auth 401, an admission 429), and\n * framework-generated 404/405/422/timeout responses included. Core deliberately does not merge\n * `c.set.headers` onto a handler-returned `Response`, so the echo lives in an app-global\n * `onResponse` hook (paired with the derive through a `WeakMap` keyed on the request) with a node\n * twin, keeping the Node adapter on its direct writer with no request-walk cost. Idempotent -\n * applying it twice is a no-op.\n *\n * ```ts\n * app.use(requestId()) // c.requestId available downstream; X-Request-Id on responses\n * ```\n */"
23306
23475
  },
23476
+ {
23477
+ "name": "requestLocal",
23478
+ "kind": "function",
23479
+ "package": "@nifrajs/core",
23480
+ "signature": "export declare function requestLocal<T>(): RequestLocal<T>;",
23481
+ "doc": "/**\n * A slot for one per-request value - a verified client IP, a request id, an auth decision - that\n * survives the request copies nifra makes (a mount's prefix strip, a WebSocket pass reused for HTTP,\n * target resolution) and the ones a wrapper makes with {@link carryRequestLocals}. A copy made any\n * other way starts empty. Values are held weakly and never cross requests. Make slots at startup, as\n * below: copies are linked only once a first slot exists, so a request copied before then starts\n * empty.\n *\n * ```ts\n * const clientIp = requestLocal<string>()\n * app.onRequest((req, platform) => { clientIp.set(req, platform?.clientIp ?? \"\") })\n * // ... in a mounted child app, after the prefix strip:\n * clientIp.get(c.req)\n * ```\n */"
23482
+ },
23483
+ {
23484
+ "name": "requestLocal",
23485
+ "kind": "function",
23486
+ "package": "nifra",
23487
+ "signature": "export declare function requestLocal<T>(): RequestLocal<T>;",
23488
+ "doc": "/**\n * A slot for one per-request value - a verified client IP, a request id, an auth decision - that\n * survives the request copies nifra makes (a mount's prefix strip, a WebSocket pass reused for HTTP,\n * target resolution) and the ones a wrapper makes with {@link carryRequestLocals}. A copy made any\n * other way starts empty. Values are held weakly and never cross requests. Make slots at startup, as\n * below: copies are linked only once a first slot exists, so a request copied before then starts\n * empty.\n *\n * ```ts\n * const clientIp = requestLocal<string>()\n * app.onRequest((req, platform) => { clientIp.set(req, platform?.clientIp ?? \"\") })\n * // ... in a mounted child app, after the prefix strip:\n * clientIp.get(c.req)\n * ```\n */"
23489
+ },
23307
23490
  {
23308
23491
  "name": "requireAuthUser",
23309
23492
  "kind": "function",
@@ -24071,11 +24254,25 @@
24071
24254
  "doc": "/**\n * Serve `db` as a mountable MCP server (`mcp.fetch` at `POST /mcp`). See module docs for the\n * security model. Throws {@link McpDbConfigError} on any unsafe configuration - always at\n * construction (boot), never at request time.\n */"
24072
24255
  },
24073
24256
  {
24074
- "name": "servePublicDir",
24257
+ "name": "serveStatic",
24075
24258
  "kind": "function",
24076
- "package": "@nifrajs/web",
24077
- "signature": "export declare function servePublicDir(options: ServePublicDirOptions): (request: Request) => Promise<Response | undefined>;",
24078
- "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 */"
24259
+ "package": "@nifrajs/core",
24260
+ "signature": "export declare function serveStatic(mounts: ServeStaticOptions | readonly ServeStaticOptions[]): (request: Request) => Promise<Response | undefined> | undefined;",
24261
+ "doc": "/**\n * The `static` handler for files on disk, for Bun's `listen()`: each mount serves a directory under a\n * URL prefix, and the first mount whose prefix (and `files`, when set) takes a GET or HEAD path\n * answers it. A request no mount takes returns `undefined` synchronously and reaches the app. The\n * same mounts work with `@nifrajs/node`'s and `@nifrajs/deno`'s `serveStatic`.\n *\n * Files up to 256 KiB carry a strong `ETag` from the exact bytes served. Larger files stream with no\n * tag and a weak date, so an `If-Range` gets the whole file rather than a range spliced from two\n * versions.\n *\n * @example\n * ```ts\n * import { serveStatic } from \"@nifrajs/core/serve-static\"\n *\n * app.listen(3000, { static: serveStatic({ dir: new URL(\"./assets/\", import.meta.url) }) })\n * ```\n */"
24262
+ },
24263
+ {
24264
+ "name": "serveStatic",
24265
+ "kind": "function",
24266
+ "package": "@nifrajs/deno",
24267
+ "signature": "export declare function serveStatic(mounts: ServeStaticOptions | readonly ServeStaticOptions[]): (request: Request) => Promise<Response | undefined> | undefined;",
24268
+ "doc": "/**\n * The `static` handler for files on disk: each mount serves a directory under a URL prefix, and the\n * first mount whose prefix (and `files`, when set) takes a GET or HEAD path answers it. A request no\n * mount takes returns `undefined` synchronously and reaches the app. The same mounts work with Bun's\n * `@nifrajs/core/serve-static` and `@nifrajs/node`.\n *\n * Files up to 256 KiB carry a strong `ETag` from the exact bytes served. Larger files stream with no\n * tag and a weak date, so an `If-Range` gets the whole file rather than a range spliced from two\n * versions.\n *\n * @example\n * ```ts\n * await serve(app, { port: 3000, static: serveStatic({ dir: new URL(\"./assets/\", import.meta.url) }) })\n * ```\n */"
24269
+ },
24270
+ {
24271
+ "name": "serveStatic",
24272
+ "kind": "function",
24273
+ "package": "@nifrajs/node",
24274
+ "signature": "export declare function serveStatic(mounts: ServeStaticOptions | readonly ServeStaticOptions[]): (request: Request) => Promise<Response | undefined> | undefined;",
24275
+ "doc": "/**\n * The `static` handler for files on disk: each mount serves a directory under a URL prefix, and the\n * first mount whose prefix (and `files`, when set) takes a GET or HEAD path answers it. Passed to\n * {@link serve}, the mounts run on Node's own request, so a request none of them takes reaches the\n * app on its direct lane. Called with a Web `Request`, it answers the same way. Bun's\n * `@nifrajs/core/serve-static` and `@nifrajs/deno` take the same mounts.\n *\n * @example\n * ```ts\n * await serve(app, { port: 3000, static: serveStatic({ dir: new URL(\"./assets/\", import.meta.url) }) })\n * ```\n */"
24079
24276
  },
24080
24277
  {
24081
24278
  "name": "serveStdio",
@@ -24544,6 +24741,13 @@
24544
24741
  "signature": "export declare function startDynamicBoundaries(boundaries: readonly BoundaryRegistration[], context: BoundaryRequestCtx): DynamicBoundaryBatch;",
24545
24742
  "doc": "/**\n * Start all dynamic boundary loads at once without making the page wait for the slowest sibling.\n * The initial states contain `status: \"pending\"`; callers that support deferred values can attach\n * each `pending.promise` to its own slot. `complete` still provides settled, isolated states to\n * non-streaming callers, preserving the simple reference API.\n */"
24546
24743
  },
24744
+ {
24745
+ "name": "staticCacheControl",
24746
+ "kind": "function",
24747
+ "package": "@nifrajs/core",
24748
+ "signature": "export declare function staticCacheControl(mount: StaticMount, immutable: boolean): string | undefined;",
24749
+ "doc": "/** The `cache-control` a file a mount serves carries, or `undefined` for its validators alone. */"
24750
+ },
24547
24751
  {
24548
24752
  "name": "staticComponentPipeline",
24549
24753
  "kind": "function",
@@ -24551,6 +24755,20 @@
24551
24755
  "signature": "export declare function staticComponentPipeline(source: string, file: string): unknown;",
24552
24756
  "doc": "/** The `componentPipeline` a config module exports as a plain literal, read without running the\n * module, or `undefined` when it exports none or one that is not a literal. */"
24553
24757
  },
24758
+ {
24759
+ "name": "staticMountOf",
24760
+ "kind": "function",
24761
+ "package": "@nifrajs/core",
24762
+ "signature": "export declare function staticMountOf(options: ServeStaticOptions, root: string): StaticMount;",
24763
+ "doc": "/** Check `options` once, with `root` the absolute path its runtime resolved `options.dir` to. */"
24764
+ },
24765
+ {
24766
+ "name": "staticMountsOf",
24767
+ "kind": "function",
24768
+ "package": "@nifrajs/core",
24769
+ "signature": "export declare function staticMountsOf(mounts: ServeStaticOptions | readonly ServeStaticOptions[], rootOf: (dir: string | URL) => string): readonly StaticMount[];",
24770
+ "doc": "/** One mount or several, as `serveStatic()` takes them, each checked by {@link staticMountOf}. */"
24771
+ },
24554
24772
  {
24555
24773
  "name": "status",
24556
24774
  "kind": "function",
@@ -24771,7 +24989,7 @@
24771
24989
  "name": "t",
24772
24990
  "kind": "const",
24773
24991
  "package": "@nifrajs/schema",
24774
- "signature": "export declare const t: {\n readonly string: (options?: StringOptions) => NifraSchema<import(\"@sinclair/typebox\").TString>;\n readonly number: (options?: NumberOptions) => NifraSchema<import(\"@sinclair/typebox\").TNumber>;\n readonly integer: (options?: IntegerOptions) => NifraSchema<import(\"@sinclair/typebox\").TInteger>;\n readonly boolean: () => NifraSchema<import(\"@sinclair/typebox\").TBoolean>;\n readonly null: () => NifraSchema<import(\"@sinclair/typebox\").TNull>;\n readonly literal: <const L extends TLiteralValue>(value: L) => NifraSchema<import(\"@sinclair/typebox\").TLiteral<L>>;\n readonly object: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /** Like `t.object` but ACCEPTS (and passes through) unknown fields - the explicit opt-out of the\n * strict default. Prefer `t.object` unless you genuinely need an open object. */\n readonly looseObject: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /**\n * A list. A list of `t.file()` (from `@nifrajs/schema/form`) honors `minItems` / `maxItems` and is\n * used inside `t.form`.\n */\n readonly array: <T extends TSchema>(item: NifraSchema<T>, options?: ArrayOptions) => NifraSchema<TArray<T>>;\n /** Marks a property optional inside `t.object` / `t.form`; standalone it is `T | undefined`. */\n readonly optional: <T extends TSchema>(schema: NifraSchema<T>) => NifraSchema<T extends import(\"@sinclair/typebox\").TOptional<infer S extends TSchema> ? import(\"@sinclair/typebox\").TOptional<S> : import(\"@sinclair/typebox\").Ensure<import(\"@sinclair/typebox\").TOptional<T>>>;\n readonly union: <const S extends readonly NifraSchema[]>(schemas: S) => NifraSchema<TUnion<{ -readonly [K in keyof S]: S[K][\"jsonSchema\"]; }>>;\n readonly record: <T extends TSchema>(value: NifraSchema<T>, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TRecord<import(\"@sinclair/typebox\").TString, T>>;\n /** A cursor-pagination response envelope: `{ items: T[]; nextCursor: string | null }` (`null` = last page). */\n readonly paginated: <T extends TSchema>(item: NifraSchema<T>, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{\n items: TArray<T>;\n nextCursor: TUnion<[import(\"@sinclair/typebox\").TString, import(\"@sinclair/typebox\").TNull]>;\n }>>;\n /** A request query schema for cursor pagination: `{ cursor?: string; limit?: number }`. `maxLimit`\n * caps `limit` - a larger value fails validation (a 422), so a client can't request an unbounded page.\n * `coerce` is on because query values arrive as strings (`?limit=20` → `\"20\"`); it's what makes `limit`\n * a real `number` in the handler (`c.query.limit`), not a string. */\n readonly pageQuery: (options?: {\n maxLimit?: number;\n }) => NifraSchema<import(\"@sinclair/typebox\").TObject<{\n cursor: import(\"@sinclair/typebox\").TOptional<import(\"@sinclair/typebox\").TString>;\n limit: import(\"@sinclair/typebox\").TOptional<import(\"@sinclair/typebox\").TInteger>;\n }>>;\n /** A request-query schema with string->scalar COERCION on. Query values always arrive as strings\n * (`?limit=20` -> `\"20\"`), so `t.integer()`/`t.number()`/`t.boolean()` fields become real numbers/\n * booleans in `c.query`. A `t.object` in a `query` slot is converted the same way, and stays closed.\n * **Open by default** (unknown query fields pass through - `additionalProperties:\n * true`): query params are read by name, not spread into a DB write, so unknown params (UTM tracking,\n * `fbclid`, etc.) passing through is safe, and rejecting them is a production-only footgun (ad/social\n * traffic appends params your schema never declares, causing 422s that never appear in dev/CI). Pass\n * `{ additionalProperties: false }` to enforce a strict allowlist. A body slot converts nothing: a\n * JSON body is already typed. */\n readonly query: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /** A request-cookie schema for the `cookies` route slot, with the same string->scalar COERCION as\n * `t.query` (cookie values always arrive as strings). **Open by default**: a browser sends every\n * cookie the site has set - analytics, consent, other routes' sessions - so a strict allowlist\n * would 422 real traffic. Declare the cookies the route reads; the rest pass through. */\n readonly cookies: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /** A request-header schema for the `headers` route slot, with the same string->scalar COERCION as\n * `t.query` (header values always arrive as strings). **Open**: it receives every header the client\n * sent, names lower-cased, so the declared names must be lower-case too. A closed `t.object` in the\n * slot also works: it validates only the names it declares, converted from text the same way. */\n readonly headers: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /**\n * A loader value marked with `defer()`, streamed in after the shell. `inner` describes what the\n * promise resolves to; `@nifrajs/web` projects and validates the resolved value by it before it\n * streams, so a deferred value is held to the same output contract as the rest of the data.\n */\n readonly deferred: <T extends TSchema>(inner: NifraSchema<T>) => NifraSchema<TUnsafe<DeferredValue<Static<T>>>>;\n /**\n * Any JSON value: strings, finite numbers, booleans, `null`, and arrays and plain objects of them, at\n * any depth. A function, a class instance, `NaN` or a cycle fails. The output guard cannot see inside\n * it, so `nifra check` and the sensitive-field rule do not either: prefer a declared shape for\n * anything that might hold a credential.\n */\n readonly json: () => NifraSchema<TUnsafe<JsonValue>>;\n /**\n * A `Date` for page data: `loaderOutput`, `actionOutput` and a server function's `output`. The\n * loader may return a `Date` or an ISO 8601 string; the page receives a `Date`, on the server render\n * and in the browser alike. A request body or a `backend/app.ts` response is plain JSON, which has\n * no dates: use `t.string({ format: \"date-time\" })` there.\n */\n readonly date: () => NifraSchema<TUnsafe<Date>>;\n /**\n * Bytes in a JSON response, as a base64 string. The handler returns a `Uint8Array` (or a `Buffer`); a\n * route whose `response` or `errors` declares this field writes every `Uint8Array` in its answer as\n * base64, the one a `beforeHandle`, `afterHandle` or `onError` hook answers in the handler's place\n * included, and the typed client reads a `string`. Response-only for now: a request or `sse` schema\n * that declares it is refused when the route is registered.\n */\n readonly bytes: () => NifraSchema<TUnsafe<Base64Bytes>>;\n /**\n * Allow a field with a sensitive name (`token`, `password`, `apiKey`, ...) in an output schema.\n * An output schema that declares one without this fails at route load; `reason` records why this\n * value may reach the browser, for the reviewer who finds it later.\n */\n readonly declassified: <T extends TSchema>(reason: string, schema: NifraSchema<T>) => NifraSchema<T>;\n};",
24992
+ "signature": "export declare const t: {\n readonly string: (options?: StringOptions) => NifraSchema<import(\"@sinclair/typebox\").TString>;\n readonly number: (options?: NumberOptions) => NifraSchema<import(\"@sinclair/typebox\").TNumber>;\n readonly integer: (options?: IntegerOptions) => NifraSchema<import(\"@sinclair/typebox\").TInteger>;\n readonly boolean: () => NifraSchema<import(\"@sinclair/typebox\").TBoolean>;\n readonly null: () => NifraSchema<import(\"@sinclair/typebox\").TNull>;\n readonly literal: <const L extends TLiteralValue>(value: L) => NifraSchema<import(\"@sinclair/typebox\").TLiteral<L>>;\n readonly object: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /** Like `t.object` but ACCEPTS (and passes through) unknown fields - the explicit opt-out of the\n * strict default. Prefer `t.object` unless you genuinely need an open object. */\n readonly looseObject: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /**\n * A list. A list of `t.file()` (from `@nifrajs/schema/form`) honors `minItems` / `maxItems` and is\n * used inside `t.form`.\n */\n readonly array: <T extends TSchema>(item: NifraSchema<T>, options?: ArrayOptions) => NifraSchema<TArray<T>>;\n /** Marks a property optional inside `t.object` / `t.form`; standalone it is `T | undefined`. */\n readonly optional: <T extends TSchema>(schema: NifraSchema<T>) => NifraSchema<T extends import(\"@sinclair/typebox\").TOptional<infer S extends TSchema> ? import(\"@sinclair/typebox\").TOptional<S> : import(\"@sinclair/typebox\").Ensure<import(\"@sinclair/typebox\").TOptional<T>>>;\n readonly union: <const S extends readonly NifraSchema[]>(schemas: S) => NifraSchema<TUnion<{ -readonly [K in keyof S]: S[K][\"jsonSchema\"]; }>>;\n readonly record: <T extends TSchema>(value: NifraSchema<T>, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TRecord<import(\"@sinclair/typebox\").TString, T>>;\n /** A cursor-pagination response envelope: `{ items: T[]; nextCursor: string | null }` (`null` = last page). */\n readonly paginated: <T extends TSchema>(item: NifraSchema<T>, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{\n items: TArray<T>;\n nextCursor: TUnion<[import(\"@sinclair/typebox\").TString, import(\"@sinclair/typebox\").TNull]>;\n }>>;\n /** A request query schema for cursor pagination: `{ cursor?: string; limit?: number }`. `maxLimit`\n * caps `limit` - a larger value fails validation (a 422), so a client can't request an unbounded page.\n * `coerce` is on because query values arrive as strings (`?limit=20` → `\"20\"`); it's what makes `limit`\n * a real `number` in the handler (`c.query.limit`), not a string. */\n readonly pageQuery: (options?: {\n maxLimit?: number;\n }) => NifraSchema<import(\"@sinclair/typebox\").TObject<{\n cursor: import(\"@sinclair/typebox\").TOptional<import(\"@sinclair/typebox\").TString>;\n limit: import(\"@sinclair/typebox\").TOptional<import(\"@sinclair/typebox\").TInteger>;\n }>>;\n /** A request-query schema with string->scalar COERCION on. Query values always arrive as strings\n * (`?limit=20` -> `\"20\"`), so `t.integer()`/`t.number()`/`t.boolean()` fields become real numbers/\n * booleans in `c.query`. A `t.object` in a `query` slot is converted the same way, and stays closed.\n * **Open by default** (unknown query fields pass through - `additionalProperties:\n * true`): query params are read by name, not spread into a DB write, so unknown params (UTM tracking,\n * `fbclid`, etc.) passing through is safe, and rejecting them is a production-only footgun (ad/social\n * traffic appends params your schema never declares, causing 422s that never appear in dev/CI). Pass\n * `{ additionalProperties: false }` to enforce a strict allowlist. A body slot converts nothing: a\n * JSON body is already typed. */\n readonly query: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /** A request-cookie schema for the `cookies` route slot, with the same string->scalar COERCION as\n * `t.query` (cookie values always arrive as strings). **Open by default**: a browser sends every\n * cookie the site has set - analytics, consent, other routes' sessions - so a strict allowlist\n * would 422 real traffic. Declare the cookies the route reads; the rest pass through. */\n readonly cookies: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /** A request-header schema for the `headers` route slot, with the same string->scalar COERCION as\n * `t.query` (header values always arrive as strings). **Open**: it receives every header the client\n * sent, names lower-cased, so the declared names must be lower-case too. A closed `t.object` in the\n * slot also works: it validates only the names it declares, converted from text the same way. */\n readonly headers: <P extends Props>(props: P, options?: ObjectOptions) => NifraSchema<import(\"@sinclair/typebox\").TObject<{ [K in keyof P]: P[K][\"jsonSchema\"]; }>>;\n /**\n * A loader value marked with `defer()`, streamed in after the shell. `inner` describes what the\n * promise resolves to; `@nifrajs/web` projects and validates the resolved value by it before it\n * streams, so a deferred value is held to the same output contract as the rest of the data.\n */\n readonly deferred: <T extends TSchema>(inner: NifraSchema<T>) => NifraSchema<TUnsafe<DeferredValue<Static<T>>>>;\n /**\n * Any JSON value: strings, finite numbers, booleans, `null`, and arrays and plain objects of them, at\n * any depth. A function, a class instance, `NaN` or a cycle fails. The output guard cannot see inside\n * it, so `nifra check` and the sensitive-field rule do not either: prefer a declared shape for\n * anything that might hold a credential.\n */\n readonly json: () => NifraSchema<TUnsafe<JsonValue>>;\n /**\n * A `Date` in your code, an RFC 3339 `date-time` string on the wire (JSON Schema and OpenAPI say\n * `type: \"string\", format: \"date-time\"`).\n *\n * - A route's `response` or `errors`: the handler returns a `Date` (a timestamp column) or such a\n * string; the JSON carries the string, and the typed client reads a `string`.\n * - A request's `body`, `query` or `params`, and a server function's `input`: the string is checked\n * (calendar included, so no `2026-02-30`) and the handler receives a `Date`.\n * - Page data (`loaderOutput`, `actionOutput`, a server function's `output`): the loader returns a\n * `Date` or an ISO 8601 string, and the page receives a `Date` on the server render and in the\n * browser alike.\n *\n * In a union, a string becomes a `Date` only under the first branch that accepts the value, so\n * `t.union([t.date(), t.string()])` hands over a `Date`.\n */\n readonly date: () => NifraSchema<TUnsafe<Date>>;\n /**\n * Bytes in a JSON response, as a base64 string. The handler returns a `Uint8Array` (or a `Buffer`); a\n * route whose `response` or `errors` declares this field writes every `Uint8Array` in its answer as\n * base64, the one a `beforeHandle`, `afterHandle` or `onError` hook answers in the handler's place\n * included, and the typed client reads a `string`. Response-only for now: a request or `sse` schema\n * that declares it is refused when the route is registered.\n */\n readonly bytes: () => NifraSchema<TUnsafe<Base64Bytes>>;\n /**\n * Allow a field with a sensitive name (`token`, `password`, `apiKey`, ...) in an output schema.\n * An output schema that declares one without this fails at route load; `reason` records why this\n * value may reach the browser, for the reviewer who finds it later.\n */\n readonly declassified: <T extends TSchema>(reason: string, schema: NifraSchema<T>) => NifraSchema<T>;\n};",
24775
24993
  "doc": "/**\n * The built-in schema builder. Each constructor returns a `NifraSchema` - a\n * Standard Schema whose validated output type flows into `c.body`/`c.query`, and\n * whose `jsonSchema` powers `toOpenAPI`. Options (min/max, length, pattern, …)\n * pass straight through to TypeBox and so become JSON Schema constraints.\n *\n * Composite constructors are generic over the *inner* TypeBox schema `T extends\n * TSchema` (not over `NifraSchema`): reading `.jsonSchema` off a value typed only as\n * `NifraSchema` would erase to the `TSchema` constraint and collapse the output type\n * to `unknown`. Capturing `T` keeps `Static<T>` precise (`string[]`, not\n * `unknown[]`).\n */"
24776
24994
  },
24777
24995
  {
@@ -25737,6 +25955,20 @@
25737
25955
  "signature": "export declare const vanillaAdapter: RenderAdapter;",
25738
25956
  "doc": "/** The zero-framework server render adapter - pass to @nifrajs/web's `renderPage`/`createWebApp`. */"
25739
25957
  },
25958
+ {
25959
+ "name": "varyOn",
25960
+ "kind": "function",
25961
+ "package": "@nifrajs/core",
25962
+ "signature": "export declare function varyOn(value: string | null, names: readonly string[]): string;",
25963
+ "doc": "/**\n * A `Vary` header value (`null` when the response has none) that names each of `names` once, matched\n * without regard to case. `Vary: *` already covers every request header, so it comes back unchanged.\n */"
25964
+ },
25965
+ {
25966
+ "name": "varyOn",
25967
+ "kind": "function",
25968
+ "package": "nifra",
25969
+ "signature": "export declare function varyOn(value: string | null, names: readonly string[]): string;",
25970
+ "doc": "/**\n * A `Vary` header value (`null` when the response has none) that names each of `names` once, matched\n * without regard to case. `Vary: *` already covers every request header, so it comes back unchanged.\n */"
25971
+ },
25740
25972
  {
25741
25973
  "name": "vectorAdvances",
25742
25974
  "kind": "function",
@@ -25949,6 +26181,13 @@
25949
26181
  "signature": "export declare function withISR(app: ISRApp, options: ISROptions): (req: Request, platform?: ISRPlatform) => Promise<Response>;",
25950
26182
  "doc": "/**\n * Wrap a nifra app with **Incremental Static Regeneration**: a cacheable page is served from\n * {@link CacheStore} when fresh, served **stale while a fresh copy regenerates in the background**\n * (`platform.waitUntil` on edge), or rendered + stored on a miss. Framework-agnostic (it caches the\n * rendered bytes). Returns a `fetch(req, platform?)` handler - hand it to `Bun.serve`/the Workers\n * `export default`, etc. Regeneration is single-flight per key (no stampede on a hot stale page).\n *\n * Each route's freshness comes from the `revalidate` header the app sets (per-route\n * `export const revalidate`), falling back to `options.revalidate`. Only full-document `text/html`\n * GET 200s are cached; everything else (assets, data-mode GETs, redirects, errors) passes through.\n */"
25951
26183
  },
26184
+ {
26185
+ "name": "withIdleTimeout",
26186
+ "kind": "function",
26187
+ "package": "@nifrajs/core",
26188
+ "signature": "export declare function withIdleTimeout<T>(c: Context, seconds: number, work: () => MaybePromise<T>): MaybePromise<T>;",
26189
+ "doc": "/**\n * Run `work` with the idle timeout of the request's connection set to `seconds` (`0` turns it off),\n * then put back the listener's.\n *\n * Bun closes a connection that moves no bytes for `listen()`'s `idleTimeoutSec` seconds (10 by\n * default), and a handler that is still working sends none, so an export or a long upstream call is\n * cut mid-flight. Raising `idleTimeoutSec` raises it for every connection, idle keep-alive ones\n * included; this raises it for one request. The listener's value is back before the response goes\n * out because Bun keeps the last value on the socket for the requests that follow on it, so a value\n * left in place would hold an idle connection open.\n *\n * The request's deadline (`requestTimeoutMs`, an inbound deadline) still bounds the response: when it\n * fires, the 503 is sent with the listener's timeout back and `c.signal` aborts, but `work`\n * keeps running unless it stops on that signal. Scopes nest: while several run on one request the\n * longest applies, and `0` outlasts any number. `seconds` runs from 0 to 255, the longest Bun holds\n * an idle connection; work that may idle longer takes `0`.\n *\n * A streamed response is sent after the handler returns, so call this inside the stream's producer\n * to hold it until the last chunk. Off `listen()` - another adapter, `app.fetch` in a test - it runs\n * `work` unchanged.\n *\n * @example\n * ```ts\n * import { withIdleTimeout } from \"@nifrajs/core/idle-timeout\"\n *\n * app.post(\"/exports\", (c) => withIdleTimeout(c, 0, () => buildExport(c.body)))\n * // Every route declared after this one:\n * app.around((c, next) => withIdleTimeout(c, 120, next))\n * ```\n */"
26190
+ },
25952
26191
  {
25953
26192
  "name": "withResponseObserver",
25954
26193
  "kind": "function",