@nifrajs/cli 5.15.1 → 5.16.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 (166) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +11 -0
  3. package/dist/build-provenance.d.ts +14 -0
  4. package/dist/build-provenance.d.ts.map +1 -0
  5. package/dist/build-provenance.js +82 -0
  6. package/dist/build-provenance.js.map +1 -0
  7. package/dist/check-diagnostics.d.ts +1 -0
  8. package/dist/check-diagnostics.d.ts.map +1 -1
  9. package/dist/check-diagnostics.js +4 -0
  10. package/dist/check-diagnostics.js.map +1 -1
  11. package/dist/check-scan.d.ts +1 -1
  12. package/dist/check-scan.d.ts.map +1 -1
  13. package/dist/check-scan.js +6 -5
  14. package/dist/check-scan.js.map +1 -1
  15. package/dist/check-timings.d.ts +11 -0
  16. package/dist/check-timings.d.ts.map +1 -0
  17. package/dist/check-timings.js +23 -0
  18. package/dist/check-timings.js.map +1 -0
  19. package/dist/check.d.ts +3 -0
  20. package/dist/check.d.ts.map +1 -1
  21. package/dist/check.js +68 -28
  22. package/dist/check.js.map +1 -1
  23. package/dist/cli.d.ts.map +1 -1
  24. package/dist/cli.js +26 -11
  25. package/dist/cli.js.map +1 -1
  26. package/dist/command-catalog.d.ts +3 -0
  27. package/dist/command-catalog.d.ts.map +1 -1
  28. package/dist/command-catalog.js +25 -4
  29. package/dist/command-catalog.js.map +1 -1
  30. package/dist/dev-feed-tool.d.ts.map +1 -1
  31. package/dist/dev-feed-tool.js +4 -2
  32. package/dist/dev-feed-tool.js.map +1 -1
  33. package/dist/doctor.d.ts +5 -2
  34. package/dist/doctor.d.ts.map +1 -1
  35. package/dist/doctor.js +27 -9
  36. package/dist/doctor.js.map +1 -1
  37. package/dist/internal/named-imports.d.ts +4 -0
  38. package/dist/internal/named-imports.d.ts.map +1 -0
  39. package/dist/internal/named-imports.js +19 -0
  40. package/dist/internal/named-imports.js.map +1 -0
  41. package/dist/internal/rewrite-kit.d.ts +35 -0
  42. package/dist/internal/rewrite-kit.d.ts.map +1 -0
  43. package/dist/internal/rewrite-kit.js +14 -0
  44. package/dist/internal/rewrite-kit.js.map +1 -0
  45. package/dist/internal/source-facts.d.ts +37 -0
  46. package/dist/internal/source-facts.d.ts.map +1 -1
  47. package/dist/internal/source-facts.js +115 -0
  48. package/dist/internal/source-facts.js.map +1 -1
  49. package/dist/levels-tool.d.ts +3 -0
  50. package/dist/levels-tool.d.ts.map +1 -1
  51. package/dist/levels-tool.js +28 -18
  52. package/dist/levels-tool.js.map +1 -1
  53. package/dist/mcp-exec.js +1 -1
  54. package/dist/mcp-exec.js.map +1 -1
  55. package/dist/mcp-http.js +1 -1
  56. package/dist/mcp-io.d.ts +3 -1
  57. package/dist/mcp-io.d.ts.map +1 -1
  58. package/dist/mcp-io.js +9 -2
  59. package/dist/mcp-io.js.map +1 -1
  60. package/dist/mcp-isolate.d.ts.map +1 -1
  61. package/dist/mcp-isolate.js +3 -1
  62. package/dist/mcp-isolate.js.map +1 -1
  63. package/dist/mcp-project-child.d.ts +10 -0
  64. package/dist/mcp-project-child.d.ts.map +1 -1
  65. package/dist/mcp-project-child.js +12 -1
  66. package/dist/mcp-project-child.js.map +1 -1
  67. package/dist/mcp-tool-meta.d.ts.map +1 -1
  68. package/dist/mcp-tool-meta.js +4 -1
  69. package/dist/mcp-tool-meta.js.map +1 -1
  70. package/dist/recipes/5.16.0.d.ts +12 -0
  71. package/dist/recipes/5.16.0.d.ts.map +1 -0
  72. package/dist/recipes/5.16.0.js +31 -0
  73. package/dist/recipes/5.16.0.js.map +1 -0
  74. package/dist/recipes/index.d.ts.map +1 -1
  75. package/dist/recipes/index.js +2 -0
  76. package/dist/recipes/index.js.map +1 -1
  77. package/dist/review.d.ts.map +1 -1
  78. package/dist/review.js +3 -0
  79. package/dist/review.js.map +1 -1
  80. package/dist/rules/codes.d.ts +3 -0
  81. package/dist/rules/codes.d.ts.map +1 -1
  82. package/dist/rules/codes.js +3 -0
  83. package/dist/rules/codes.js.map +1 -1
  84. package/dist/rules/explanations.d.ts.map +1 -1
  85. package/dist/rules/explanations.js +15 -0
  86. package/dist/rules/explanations.js.map +1 -1
  87. package/dist/rules/route-hooks.d.ts +10 -0
  88. package/dist/rules/route-hooks.d.ts.map +1 -0
  89. package/dist/rules/route-hooks.js +88 -0
  90. package/dist/rules/route-hooks.js.map +1 -0
  91. package/dist/rules/silent-sse.d.ts +9 -0
  92. package/dist/rules/silent-sse.d.ts.map +1 -0
  93. package/dist/rules/silent-sse.js +89 -0
  94. package/dist/rules/silent-sse.js.map +1 -0
  95. package/dist/rules/source-scan.d.ts +4 -2
  96. package/dist/rules/source-scan.d.ts.map +1 -1
  97. package/dist/rules/source-scan.js +3 -1
  98. package/dist/rules/source-scan.js.map +1 -1
  99. package/dist/source-rewrites.d.ts +2 -20
  100. package/dist/source-rewrites.d.ts.map +1 -1
  101. package/dist/source-rewrites.js +3 -13
  102. package/dist/source-rewrites.js.map +1 -1
  103. package/dist/typecheck-cache.d.ts +6 -0
  104. package/dist/typecheck-cache.d.ts.map +1 -0
  105. package/dist/typecheck-cache.js +37 -0
  106. package/dist/typecheck-cache.js.map +1 -0
  107. package/dist/typecheck-coverage.js +1 -1
  108. package/dist/typecheck-coverage.js.map +1 -1
  109. package/dist/typed-api-rewrites.d.ts +3 -0
  110. package/dist/typed-api-rewrites.d.ts.map +1 -0
  111. package/dist/typed-api-rewrites.js +253 -0
  112. package/dist/typed-api-rewrites.js.map +1 -0
  113. package/dist/upgrade.d.ts.map +1 -1
  114. package/dist/upgrade.js +3 -1
  115. package/dist/upgrade.js.map +1 -1
  116. package/dist/verification-gates.d.ts +23 -0
  117. package/dist/verification-gates.d.ts.map +1 -0
  118. package/dist/verification-gates.js +8 -0
  119. package/dist/verification-gates.js.map +1 -0
  120. package/dist/verification.d.ts +2 -0
  121. package/dist/verification.d.ts.map +1 -1
  122. package/dist/verification.js +6 -0
  123. package/dist/verification.js.map +1 -1
  124. package/dist/work-graph.d.ts +17 -8
  125. package/dist/work-graph.d.ts.map +1 -1
  126. package/dist/work-graph.js +157 -104
  127. package/dist/work-graph.js.map +1 -1
  128. package/docs/examples.json +2 -2
  129. package/docs/llms-full.txt +563 -46
  130. package/docs/types.json +269 -84
  131. package/package.json +12 -12
  132. package/src/build-provenance.ts +107 -0
  133. package/src/check-diagnostics.ts +5 -0
  134. package/src/check-scan.ts +7 -4
  135. package/src/check-timings.ts +27 -0
  136. package/src/check.ts +77 -32
  137. package/src/cli.ts +33 -12
  138. package/src/command-catalog.ts +28 -4
  139. package/src/dev-feed-tool.ts +8 -3
  140. package/src/doctor.ts +37 -18
  141. package/src/internal/named-imports.ts +26 -0
  142. package/src/internal/rewrite-kit.ts +49 -0
  143. package/src/internal/source-facts.ts +158 -0
  144. package/src/levels-tool.ts +27 -18
  145. package/src/mcp-exec.ts +1 -1
  146. package/src/mcp-http.ts +1 -1
  147. package/src/mcp-io.ts +13 -1
  148. package/src/mcp-isolate.ts +4 -0
  149. package/src/mcp-project-child.ts +19 -1
  150. package/src/mcp-tool-meta.ts +5 -1
  151. package/src/recipes/5.16.0.ts +41 -0
  152. package/src/recipes/index.ts +2 -0
  153. package/src/review.ts +3 -0
  154. package/src/rules/codes.ts +3 -0
  155. package/src/rules/explanations.ts +15 -0
  156. package/src/rules/route-hooks.ts +112 -0
  157. package/src/rules/silent-sse.ts +95 -0
  158. package/src/rules/source-scan.ts +8 -3
  159. package/src/source-rewrites.ts +18 -52
  160. package/src/typecheck-cache.ts +33 -0
  161. package/src/typecheck-coverage.ts +1 -1
  162. package/src/typed-api-rewrites.ts +308 -0
  163. package/src/upgrade.ts +2 -1
  164. package/src/verification-gates.ts +9 -0
  165. package/src/verification.ts +8 -0
  166. package/src/work-graph.ts +200 -121
package/docs/types.json CHANGED
@@ -2363,7 +2363,7 @@
2363
2363
  "name": "BuildClientOptions",
2364
2364
  "kind": "interface",
2365
2365
  "package": "@nifrajs/web",
2366
- "signature": "export interface BuildClientOptions {\n /** The `routes/` directory to discover (absolute path). */\n readonly routesDir: string;\n /** Output directory for the bundle + `manifest.json` (absolute path). */\n readonly outDir: string;\n /** The adapter's client runtime (exports `mountRouter`), e.g. `\"@nifrajs/web-solid/client\"`. */\n readonly clientModule: string;\n /** Route/layout file → import specifier (default: `${routesDir}/${file}`). */\n readonly resolve?: (file: string) => string;\n /** Adapter build plugins (e.g. `solidBunPlugin(\"dom\")`). */\n readonly plugins?: readonly BunPlugin[];\n /** `Bun.build` export conditions (e.g. `[\"bun\", \"browser\"]`). */\n readonly conditions?: readonly string[];\n /** Compile-time replacements (e.g. `{ \"process.env.NODE_ENV\": '\"production\"' }`). */\n readonly define?: Readonly<Record<string, string>>;\n /** Minify the output (default `true`). */\n readonly minify?: boolean;\n /** URL prefix the assets are served under (default `\"/assets/\"`); also Bun's chunk `publicPath`. */\n readonly publicPath?: string;\n /**\n * Directory of user-authored static files copied into the build and served at the root (default\n * `\"public\"`). Absent directory ⇒ nothing copied, no error.\n *\n * NOT the same thing as {@link publicPath}, despite the names: that is the URL prefix for\n * content-hashed bundle chunks and never covers files an author put on disk. The collision is a\n * real source of confusion, which is why both are spelled out here.\n */\n readonly publicDir?: string | false;\n /**\n * Prefix that opts an environment variable into the **client** bundle (Vite/Next convention; default\n * `\"PUBLIC_\"`). Every var in the build environment whose name starts with this prefix is baked into\n * the client `define` as `\"process.env.NAME\": JSON.stringify(value)`, so `process.env.PUBLIC_API_URL`\n * compiles to its literal value in the browser. Vars WITHOUT the prefix are never exposed - the bare\n * `process.env` define resolves them to `undefined`, so server secrets can't leak into the client\n * bundle. Set to `\"\"` to disable auto-exposure entirely (no var is baked in). `options.define` still\n * wins over an auto-exposed var (it's layered last). Sourced from `Bun.env` (falls back to\n * `process.env`) at build time. */\n readonly publicEnvPrefix?: string;\n /**\n * Reviewed false positives of the secret scan, which fails the build when a bundle, source map or\n * `public/` file carries what looks like a credential or the value of a non-public environment\n * variable. Each names its rule, its file (or, for an environment value, its variable) and a reason.\n */\n readonly secretExemptions?: readonly SecretExemption[];\n /**\n * Move copy tables (`@nifrajs/i18n/copy`) into one chunk per locale, so a page's JavaScript carries\n * only the copy of the locale it renders in (default: on when minifying). The server bundle keeps\n * every table whole; the server entry passes the manifest's `copyChunks` to `createWebApp`.\n */\n readonly copySplit?: boolean;\n /**\n * The server runs `createWebApp({ live })`: the client entry sends route loads through its live load\n * endpoint and keeps what is on screen fresh: the runtime's `clientEntry`.\n */\n readonly live?: LiveClientEntry | undefined;\n /**\n * A module whose default export is the `fetch` the client router reaches its server through (see\n * {@link serverFetch}). For pages that ship inside a native shell while the server lives elsewhere:\n * the route-data GETs, prefetches and action POSTs go through it.\n */\n readonly transport?: string | undefined;\n}"
2366
+ "signature": "export interface BuildClientOptions {\n /** Collect initial client assets for the build report without adding data to deploy artifacts. */\n readonly onRouteAssets?: ((routes: readonly ClientRouteAssets[]) => void) | undefined;\n /** The `routes/` directory to discover (absolute path). */\n readonly routesDir: string;\n /** Output directory for the bundle + `manifest.json` (absolute path). */\n readonly outDir: string;\n /** The adapter's client runtime (exports `mountRouter`), e.g. `\"@nifrajs/web-solid/client\"`. */\n readonly clientModule: string;\n /** Route/layout file → import specifier (default: `${routesDir}/${file}`). */\n readonly resolve?: (file: string) => string;\n /** Adapter build plugins (e.g. `solidBunPlugin(\"dom\")`). */\n readonly plugins?: readonly BunPlugin[];\n /** `Bun.build` export conditions (e.g. `[\"bun\", \"browser\"]`). */\n readonly conditions?: readonly string[];\n /** Compile-time replacements (e.g. `{ \"process.env.NODE_ENV\": '\"production\"' }`). */\n readonly define?: Readonly<Record<string, string>>;\n /** Minify the output (default `true`). */\n readonly minify?: boolean;\n /** URL prefix the assets are served under (default `\"/assets/\"`); also Bun's chunk `publicPath`. */\n readonly publicPath?: string;\n /**\n * Directory of user-authored static files copied into the build and served at the root (default\n * `\"public\"`). Absent directory ⇒ nothing copied, no error.\n *\n * NOT the same thing as {@link publicPath}, despite the names: that is the URL prefix for\n * content-hashed bundle chunks and never covers files an author put on disk. The collision is a\n * real source of confusion, which is why both are spelled out here.\n */\n readonly publicDir?: string | false;\n /**\n * Prefix that opts an environment variable into the **client** bundle (Vite/Next convention; default\n * `\"PUBLIC_\"`). Every var in the build environment whose name starts with this prefix is baked into\n * the client `define` as `\"process.env.NAME\": JSON.stringify(value)`, so `process.env.PUBLIC_API_URL`\n * compiles to its literal value in the browser. Vars WITHOUT the prefix are never exposed - the bare\n * `process.env` define resolves them to `undefined`, so server secrets can't leak into the client\n * bundle. Set to `\"\"` to disable auto-exposure entirely (no var is baked in). `options.define` still\n * wins over an auto-exposed var (it's layered last). Sourced from `Bun.env` (falls back to\n * `process.env`) at build time. */\n readonly publicEnvPrefix?: string;\n /**\n * Reviewed false positives of the secret scan, which fails the build when a bundle, source map or\n * `public/` file carries what looks like a credential or the value of a non-public environment\n * variable. Each names its rule, its file (or, for an environment value, its variable) and a reason.\n */\n readonly secretExemptions?: readonly SecretExemption[];\n /**\n * Move copy tables (`@nifrajs/i18n/copy`) into one chunk per locale, so a page's JavaScript carries\n * only the copy of the locale it renders in (default: on when minifying). The server bundle keeps\n * every table whole; the server entry passes the manifest's `copyChunks` to `createWebApp`.\n */\n readonly copySplit?: boolean;\n /**\n * The server runs `createWebApp({ live })`: the client entry sends route loads through its live load\n * endpoint and keeps what is on screen fresh: the runtime's `clientEntry`.\n */\n readonly live?: LiveClientEntry | undefined;\n /**\n * A module whose default export is the `fetch` the client router reaches its server through (see\n * {@link serverFetch}). For pages that ship inside a native shell while the server lives elsewhere:\n * the route-data GETs, prefetches and action POSTs go through it.\n */\n readonly transport?: string | undefined;\n}"
2367
2367
  },
2368
2368
  {
2369
2369
  "name": "BuildClientViteOptions",
@@ -2382,7 +2382,7 @@
2382
2382
  "name": "BuildFreshness",
2383
2383
  "kind": "interface",
2384
2384
  "package": "@nifrajs/cli",
2385
- "signature": "export interface BuildFreshness {\n readonly ok: boolean;\n readonly buildDir?: string;\n readonly newestSourceMs?: number;\n readonly newestBuildMs?: number;\n readonly reason?: string;\n}"
2385
+ "signature": "export interface BuildFreshness {\n readonly ok: boolean;\n readonly buildDir?: string;\n readonly newestSourceMs?: number;\n readonly newestBuildMs?: number;\n readonly buildDigest?: string | undefined;\n readonly sourceDigest?: string;\n readonly reason?: string;\n}"
2386
2386
  },
2387
2387
  {
2388
2388
  "name": "BuildManifest",
@@ -2419,7 +2419,7 @@
2419
2419
  "name": "BuildTargetOptions",
2420
2420
  "kind": "interface",
2421
2421
  "package": "@nifrajs/web",
2422
- "signature": "export interface BuildTargetOptions {\n /** Vercel-only: opt into Node.js 22 serverless SSR instead of the default Edge function. */\n readonly vercelRuntime?: VercelRuntime;\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 /** `static` only: pages to prerender for this build whether or not their route exports `prerender`, by\n * path. A shell build uses it to ship the page the shell opens on without making a web build of the\n * same app serve that page as a snapshot. Refused for any other target. */\n readonly prerenderPaths?: readonly string[] | undefined;\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 /** A module whose default export is the `fetch` the client router reaches its server through: see\n * {@link BuildClientOptions.transport}. */\n readonly transport?: string | undefined;\n}"
2422
+ "signature": "export interface BuildTargetOptions {\n /** Include the initial client asset graph per route in the size report. */\n readonly reportRouteAssets?: boolean;\n /** Vercel-only: opt into Node.js 22 serverless SSR instead of the default Edge function. */\n readonly vercelRuntime?: VercelRuntime;\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 /** `static` only: pages to prerender for this build whether or not their route exports `prerender`, by\n * path. A shell build uses it to ship the page the shell opens on without making a web build of the\n * same app serve that page as a snapshot. Refused for any other target. */\n readonly prerenderPaths?: readonly string[] | undefined;\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 /** A module whose default export is the `fetch` the client router reaches its server through: see\n * {@link BuildClientOptions.transport}. */\n readonly transport?: string | undefined;\n}"
2423
2423
  },
2424
2424
  {
2425
2425
  "name": "BuildTargetPlan",
@@ -2444,7 +2444,7 @@
2444
2444
  "name": "Bundler",
2445
2445
  "kind": "interface",
2446
2446
  "package": "@nifrajs/web",
2447
- "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 /** The router's server `fetch` module (`BuildClientOptions.transport`). */\n readonly transport?: string | 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}",
2447
+ "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 readonly onRouteAssets?: ((routes: readonly ClientRouteAssets[]) => void) | undefined;\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 /** The router's server `fetch` module (`BuildClientOptions.transport`). */\n readonly transport?: string | 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}",
2448
2448
  "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 */"
2449
2449
  },
2450
2450
  {
@@ -3534,6 +3534,12 @@
3534
3534
  "signature": "export interface ClientRetryOptions {\n /** Max RETRIES after the first attempt. Default 2. */\n readonly attempts?: number;\n /** Response statuses to retry. Default `[502, 503, 504]`. 4xx/429 are never added by default. */\n readonly on?: readonly number[];\n /** Methods eligible for retry. Default the idempotent set `GET/HEAD/OPTIONS/PUT/DELETE/QUERY`. */\n readonly methods?: readonly string[];\n /** Delay (ms) before retry `n` (1-based). Default exponential backoff with jitter, capped at 3s. */\n readonly backoff?: (attempt: number) => number;\n}",
3535
3535
  "doc": "/** Safe retry policy. Off unless `retry` is set; retries ONLY idempotent methods and transient 5xx -\n * never a 4xx/429 and never a non-idempotent method, so a retry can't double a side effect. */"
3536
3536
  },
3537
+ {
3538
+ "name": "ClientRouteAssets",
3539
+ "kind": "interface",
3540
+ "package": "@nifrajs/web",
3541
+ "signature": "export interface ClientRouteAssets {\n readonly pattern: string;\n readonly javascript: readonly string[];\n readonly stylesheets: readonly string[];\n /** The build could not determine whether the route enables framework hydration. */\n readonly hydrationUnknown?: true;\n}"
3542
+ },
3537
3543
  {
3538
3544
  "name": "ClientRouteHooks",
3539
3545
  "kind": "interface",
@@ -3541,6 +3547,12 @@
3541
3547
  "signature": "export interface ClientRouteHooks {\n /** page's registered independently navigable route-slot identities. */\n readonly routeSlots?: Readonly<Record<string, readonly string[]>>;\n readonly clientLoader?: ClientLoader;\n readonly clientAction?: ClientAction;\n /** The page's `shareData` export: `false` gives every reload of it fresh data. */\n readonly shareData?: boolean;\n /** The page's `keepAlive` export: the page stays mounted after a visitor leaves it. */\n readonly keepAlive?: true | KeepAliveOptions;\n /** Neutral boundary descriptors needed for soft-navigation interception. A boundary's loader lives in\n * the route's backend half, so the browser never learns whether one exists. */\n readonly boundaries?: ReadonlyArray<Omit<BoundaryDescriptor, \"hasLoad\">>;\n}",
3542
3548
  "doc": "/** Client hooks populated by the generated route entry after a route chunk loads. */"
3543
3549
  },
3550
+ {
3551
+ "name": "ClientRouteSize",
3552
+ "kind": "interface",
3553
+ "package": "@nifrajs/web",
3554
+ "signature": "export interface ClientRouteSize extends ClientRouteAssets {\n readonly javascriptGzip: number | null;\n readonly stylesheetsGzip: number;\n}"
3555
+ },
3544
3556
  {
3545
3557
  "name": "ClientRouter",
3546
3558
  "kind": "interface",
@@ -4336,7 +4348,7 @@
4336
4348
  "name": "CorsOptions",
4337
4349
  "kind": "interface",
4338
4350
  "package": "@nifrajs/middleware",
4339
- "signature": "export interface CorsOptions {\n /** Allowed origin(s): `\"*\"`, an exact origin, a list, or a predicate. Default `\"*\"`. A named origin\n * is also trusted to post a form or a bodyless unsafe request to the server, as if it were in the\n * server's `formOrigins`; `\"*\"` adds nothing. */\n readonly origin?: string | ReadonlyArray<string> | ((origin: string) => boolean);\n /** Methods advertised in the preflight response. Default the common verbs. */\n readonly methods?: ReadonlyArray<string>;\n /** Headers allowed on the actual request. Default: reflect the preflight's requested headers. */\n readonly allowedHeaders?: ReadonlyArray<string>;\n /** Response headers exposed to the browser. */\n readonly exposedHeaders?: ReadonlyArray<string>;\n /** Allow credentials (cookies / `Authorization`). Cannot be combined with `origin: \"*\"`. Default false. */\n readonly credentials?: boolean;\n /** Preflight cache duration, in seconds. */\n readonly maxAge?: number;\n}"
4351
+ "signature": "export interface CorsOptions {\n /** Allowed origin(s): `\"*\"`, an exact origin, a list, or a predicate. Default `\"*\"`. A named origin\n * is also trusted to post a form or a bodyless unsafe request to the server, as if it were in the\n * server's `formOrigins`; `\"*\"` adds nothing. A predicate runs for a preflight and again when the\n * response headers are added, so keep it free of side effects. */\n readonly origin?: string | ReadonlyArray<string> | ((origin: string) => boolean);\n /** Methods advertised in the preflight response. Default the common verbs. */\n readonly methods?: ReadonlyArray<string>;\n /** Headers allowed on the actual request. Default: reflect the preflight's requested headers. */\n readonly allowedHeaders?: ReadonlyArray<string>;\n /** Response headers exposed to the browser. */\n readonly exposedHeaders?: ReadonlyArray<string>;\n /** Allow credentials (cookies / `Authorization`). Cannot be combined with `origin: \"*\"`. Default false. */\n readonly credentials?: boolean;\n /** Preflight cache duration, in seconds. */\n readonly maxAge?: number;\n}"
4340
4352
  },
4341
4353
  {
4342
4354
  "name": "Counter",
@@ -4431,7 +4443,7 @@
4431
4443
  "name": "CreateWebAppOptions",
4432
4444
  "kind": "interface",
4433
4445
  "package": "@nifrajs/web",
4434
- "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 /**\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. `csp` (hashes) is optional; `nonce` is refused, since a per-request nonce would\n * make every shell unique.\n */\n readonly ppr?: PprSetup;\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; the routing layer\n * must strip the mount prefix before dispatching.\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}"
4446
+ "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 /**\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. `csp` (hashes) is optional; `nonce` is refused, since a per-request nonce would\n * make every shell unique.\n */\n readonly ppr?: PprSetup;\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; the routing layer\n * must strip the mount prefix before dispatching.\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 /** Collect matched page GET timing before the initial response. */\n readonly routeTiming?: RouteTimingFor | undefined;\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}"
4435
4447
  },
4436
4448
  {
4437
4449
  "name": "CronError",
@@ -5369,7 +5381,7 @@
5369
5381
  "name": "DevAppHooks",
5370
5382
  "kind": "interface",
5371
5383
  "package": "@nifrajs/web",
5372
- "signature": "export interface DevAppHooks {\n /** Pass to `createWebApp({ onLoaderError })`: failures an `_error` boundary renders reach the feed. */\n readonly onLoaderError: (err: unknown, ctx: {\n readonly request: Request;\n readonly route: string;\n readonly params?: unknown;\n }) => void;\n}",
5384
+ "signature": "export interface DevAppHooks {\n /** Pass to `createWebApp({ routeTiming })` to attach page phases to the request feed. */\n readonly routeTiming?: RouteTimingFor;\n /** Pass to `createWebApp({ onLoaderError })`: failures an `_error` boundary renders reach the feed. */\n readonly onLoaderError: (err: unknown, ctx: {\n readonly request: Request;\n readonly route: string;\n readonly params?: unknown;\n }) => void;\n}",
5373
5385
  "doc": "/** What a dev server hands `createApp` so the app reports into the session. */"
5374
5386
  },
5375
5387
  {
@@ -5406,7 +5418,7 @@
5406
5418
  "name": "DevFeed",
5407
5419
  "kind": "interface",
5408
5420
  "package": "@nifrajs/web",
5409
- "signature": "export interface DevFeed {\n /** Identifies this feed's requests to the process-wide capture. */\n readonly id: string;\n readonly root: string;\n readonly generation: number;\n readonly cursor: number;\n recordError(error: unknown, meta: ErrorMeta): DevErrorEntry;\n recordDiagnostic(diagnostic: Diagnostic, meta: ErrorMeta): DevErrorEntry;\n recordLog(level: DevLogLevel, message: string, meta?: LogMeta): void;\n startRequest(requestId: string, method: string, path: string): void;\n finishRequest(requestId: string, response: {\n readonly status: number;\n readonly bytes?: number | undefined;\n readonly isr?: string | undefined;\n }, durationMs: number): void;\n /** A watched file changed: everything recorded so far becomes stale. */\n markChange(): void;\n /** A later success cleared every open error of `category`. */\n resolve(category: DevErrorCategory): void;\n errors(query?: DevErrorsQuery): DevErrorsResult;\n logs(query?: DevLogsQuery): DevLogsResult;\n requests(query?: DevRequestsQuery): DevRequestsResult;\n counts(): DevServerIdentity[\"counts\"];\n redact(text: string): string;\n /** Flush persisted entries; the feed stays usable. */\n flush(): void;\n /** Flush and stop persisting. */\n close(): void;\n}"
5421
+ "signature": "export interface DevFeed {\n /** Identifies this feed's requests to the process-wide capture. */\n readonly id: string;\n readonly root: string;\n readonly generation: number;\n readonly cursor: number;\n recordError(error: unknown, meta: ErrorMeta): DevErrorEntry;\n recordDiagnostic(diagnostic: Diagnostic, meta: ErrorMeta): DevErrorEntry;\n recordLog(level: DevLogLevel, message: string, meta?: LogMeta): void;\n startRequest(requestId: string, method: string, path: string): void;\n finishRequest(requestId: string, response: {\n readonly status: number;\n readonly bytes?: number | undefined;\n readonly isr?: string | undefined;\n readonly routeTiming?: DevRouteTiming | undefined;\n }, durationMs: number): void;\n /** A watched file changed: everything recorded so far becomes stale. */\n markChange(): void;\n /** A later success cleared every open error of `category`. */\n resolve(category: DevErrorCategory): void;\n errors(query?: DevErrorsQuery): DevErrorsResult;\n logs(query?: DevLogsQuery): DevLogsResult;\n requests(query?: DevRequestsQuery): DevRequestsResult;\n counts(): DevServerIdentity[\"counts\"];\n redact(text: string): string;\n /** Flush persisted entries; the feed stays usable. */\n flush(): void;\n /** Flush and stop persisting. */\n close(): void;\n}"
5410
5422
  },
5411
5423
  {
5412
5424
  "name": "DevFeedLimits",
@@ -5454,13 +5466,13 @@
5454
5466
  "name": "DevRequestContext",
5455
5467
  "kind": "interface",
5456
5468
  "package": "@nifrajs/web",
5457
- "signature": "export interface DevRequestContext {\n readonly feedId: string;\n readonly requestId: string;\n readonly method: string;\n readonly path: string;\n}"
5469
+ "signature": "export interface DevRequestContext {\n readonly feedId: string;\n readonly requestId: string;\n readonly method: string;\n readonly path: string;\n readonly routeTiming?: RouteTimingFor;\n}"
5458
5470
  },
5459
5471
  {
5460
5472
  "name": "DevRequestTrace",
5461
5473
  "kind": "interface",
5462
5474
  "package": "@nifrajs/web",
5463
- "signature": "export interface DevRequestTrace {\n readonly seq: number;\n readonly requestId: string;\n readonly method: string;\n readonly path: string;\n readonly at: string;\n /** Undefined while the request has not produced its response yet. */\n readonly status?: number;\n /** Until the response started (a streamed body keeps flowing after). */\n readonly durationMs?: number;\n readonly bytes?: number;\n readonly isr?: string;\n readonly errorIds: readonly string[];\n readonly logCount: number;\n}"
5475
+ "signature": "export interface DevRequestTrace {\n readonly seq: number;\n readonly requestId: string;\n readonly method: string;\n readonly path: string;\n readonly at: string;\n /** Undefined while the request has not produced its response yet. */\n readonly status?: number;\n /** Until the response started (a streamed body keeps flowing after). */\n readonly durationMs?: number;\n readonly bytes?: number;\n readonly isr?: string;\n readonly routeTiming?: DevRouteTiming;\n readonly errorIds: readonly string[];\n readonly logCount: number;\n}"
5464
5476
  },
5465
5477
  {
5466
5478
  "name": "DevRequestsQuery",
@@ -5474,6 +5486,12 @@
5474
5486
  "package": "@nifrajs/web",
5475
5487
  "signature": "export interface DevRequestsResult extends PageInfo {\n readonly requests: readonly DevRequestTrace[];\n}"
5476
5488
  },
5489
+ {
5490
+ "name": "DevRouteTiming",
5491
+ "kind": "interface",
5492
+ "package": "@nifrajs/web",
5493
+ "signature": "export interface DevRouteTiming {\n readonly pattern: string;\n /** Sum of completed phase samples, in milliseconds. Parallel loader times can overlap. */\n readonly phases: Readonly<Partial<Record<RoutePhase, number>>>;\n}"
5494
+ },
5477
5495
  {
5478
5496
  "name": "DevServer",
5479
5497
  "kind": "interface",
@@ -5536,7 +5554,7 @@
5536
5554
  "name": "Diagnostic",
5537
5555
  "kind": "interface",
5538
5556
  "package": "@nifrajs/web",
5539
- "signature": "export interface Diagnostic {\n /** Stable, greppable identifier, e.g. `NIFRA_BACKEND_IN_CLIENT`. `NIFRA_UNHANDLED` when unrecognised. */\n readonly code: string;\n readonly name: string;\n readonly message: string;\n readonly request?: {\n readonly method: string;\n readonly url: string;\n } | undefined;\n readonly frames: readonly DiagnosticFrame[];\n readonly codeframe?: Codeframe | undefined;\n /** Plain-language \"why this happened\", when the failure is recognised. */\n readonly cause?: string | undefined;\n /** Plain-language \"do this\", when the failure is recognised. */\n readonly fix?: string | undefined;\n /** Docs section anchor for the code, e.g. `errors#backend-in-client`. */\n readonly docsAnchor?: string | undefined;\n /** The distinct ways to fix it, when more than one is right; `fix` covers them all in one line. */\n readonly fixOptions?: readonly FixOption[] | undefined;\n}",
5557
+ "signature": "export interface Diagnostic {\n /** Stable, greppable identifier, e.g. `NIFRA_BACKEND_IN_CLIENT`. `NIFRA_UNHANDLED` when unrecognised. */\n readonly code: string;\n readonly name: string;\n readonly message: string;\n readonly request?: {\n readonly method: string;\n readonly url: string;\n } | undefined;\n readonly frames: readonly DiagnosticFrame[];\n readonly codeframe?: Codeframe | undefined;\n /** Plain-language \"why this happened\", when the failure is recognised. */\n readonly cause?: string | undefined;\n /** Plain-language \"do this\", when the failure is recognised. */\n readonly fix?: string | undefined;\n /** Docs section anchor for the code, e.g. `errors#backend-in-client`. */\n readonly docsAnchor?: string | undefined;\n /** The distinct ways to fix it, when more than one is right; `fix` covers them all in one line. */\n readonly fixOptions?: readonly FixOption[] | undefined;\n /** Present as \"warning\" for a framework development warning; absent means an error. */\n readonly severity?: \"warning\" | undefined;\n}",
5540
5558
  "doc": "/** The structured failure. Serialisable as-is to JSON for the agent surfaces. */"
5541
5559
  },
5542
5560
  {
@@ -6169,7 +6187,7 @@
6169
6187
  "name": "EvidenceBundle",
6170
6188
  "kind": "interface",
6171
6189
  "package": "@nifrajs/cli",
6172
- "signature": "export interface EvidenceBundle {\n readonly version: 1;\n readonly graphDigest: string;\n readonly changedFiles: readonly string[];\n readonly targetLevel: number;\n readonly plan: ProofPlan;\n readonly proofs: readonly ProofEvidence[];\n readonly stop: {\n readonly done: boolean;\n readonly missing: readonly string[];\n readonly next?: ProofStep;\n };\n}"
6190
+ "signature": "export interface EvidenceBundle {\n readonly version: 2;\n readonly graphDigest: string;\n readonly buildDigest?: string | undefined;\n readonly changedFiles: readonly string[];\n readonly targetLevel: number;\n readonly plan: ProofPlan;\n readonly proofs: readonly ProofEvidence[];\n readonly stop: {\n readonly done: boolean;\n readonly missing: readonly string[];\n readonly next?: ProofStep;\n };\n}"
6173
6191
  },
6174
6192
  {
6175
6193
  "name": "EvidenceCounters",
@@ -6829,11 +6847,17 @@
6829
6847
  "package": "@nifrajs/agent-protocol",
6830
6848
  "signature": "export interface ForkSessionResult {\n readonly sessionId: string;\n readonly parentSessionId: string;\n}"
6831
6849
  },
6850
+ {
6851
+ "name": "FormFor",
6852
+ "kind": "interface",
6853
+ "package": "@nifrajs/web",
6854
+ "signature": "export interface FormFor<App> {\n <Path extends PostPaths<App>>(path: Path, ...params: ParamsArgument<Path>): FormHandle<App, Path, \"post\">;\n <Path extends RoutePaths<App>, Method extends RouteMethods<App, Path>>(path: Path, method: Method, ...params: ParamsArgument<Path>): FormHandle<App, Path, Method>;\n}"
6855
+ },
6832
6856
  {
6833
6857
  "name": "FormHandle",
6834
6858
  "kind": "interface",
6835
6859
  "package": "@nifrajs/web",
6836
- "signature": "export interface FormHandle<App, Path extends string, Method extends string> {\n /** Input props for a schema field. `name` is constrained to the body's keys - a typo, or a field the\n * schema doesn't have, is a COMPILE error. Spread onto an element: `<input {...f.field(\"text\")} />`. */\n field<K extends FieldKey<App, Path, Method>>(name: K, props?: FieldProps): FieldProps & {\n name: K;\n };\n /** `formData.get`, key-constrained to the body's fields - reading an orphan key won't compile. */\n read<K extends FieldKey<App, Path, Method>>(form: FormData, name: K): FormEntry;\n /** `formData.getAll`, key-checked the same way. */\n readAll<K extends FieldKey<App, Path, Method>>(form: FormData, name: K): FormEntries;\n}"
6860
+ "signature": "export interface FormHandle<App, Path extends string, Method extends string> {\n /** The route's URL, for `<form action>`: the path with its params filled in. */\n readonly action: string;\n /** The route's method, lowercase, for `<form method>` or a `fetch`. */\n readonly method: Method;\n /** Input props for a schema field. `name` is constrained to the body's keys - a typo, or a field the\n * schema doesn't have, is a COMPILE error. Spread onto an element: `<input {...f.field(\"text\")} />`. */\n field<K extends FieldKey<App, Path, Method>>(name: K, props?: FieldProps): FieldProps & {\n name: K;\n };\n /** `formData.get`, key-constrained to the body's fields - reading an orphan key won't compile. */\n read<K extends FieldKey<App, Path, Method>>(form: FormData, name: K): FormEntry;\n /** `formData.getAll`, key-checked the same way. */\n readAll<K extends FieldKey<App, Path, Method>>(form: FormData, name: K): FormEntries;\n}"
6837
6861
  },
6838
6862
  {
6839
6863
  "name": "FormOptions",
@@ -7335,7 +7359,14 @@
7335
7359
  "kind": "type",
7336
7360
  "package": "@nifrajs/web",
7337
7361
  "signature": "export type HrefOptions<K extends Pattern> = {\n readonly to: K;\n readonly search?: SearchOfRoute<K> | undefined;\n readonly hash?: string | undefined;\n} & ParamsOption<K> & SlotOptions<K>;",
7338
- "doc": "/**\n * What {@link href} takes: the route's pattern as `to`, its `params` (required when the pattern has\n * any, absent when it has none), the route's `search` as its `searchSchema` outputs it, and the `hash`\n * without its `#`.\n */"
7362
+ "doc": "/**\n * What {@link href} takes: the route's pattern as `to`, its `params` (required when the pattern has\n * any, absent when it has none), the route's `search` as its `searchSchema` accepts it (a defaulted field\n * may be left out), and the `hash` without its `#`.\n */"
7363
+ },
7364
+ {
7365
+ "name": "HrefRefusal",
7366
+ "kind": "interface",
7367
+ "package": "@nifrajs/web",
7368
+ "signature": "export interface HrefRefusal {\n readonly call: \"href\" | \"rawHref\";\n /** The route pattern `href()` was given; undefined for `rawHref`. */\n readonly route?: string;\n /** What was refused, in words: the same text the default log writes. */\n readonly message: string;\n}",
7369
+ "doc": "/** One refused call, as {@link onHrefRefused} hands it over. It never holds a param, hash or path value. */"
7339
7370
  },
7340
7371
  {
7341
7372
  "name": "HreflangLink",
@@ -9768,7 +9799,7 @@
9768
9799
  "name": "MemoryCacheStore",
9769
9800
  "kind": "class",
9770
9801
  "package": "@nifrajs/web",
9771
- "signature": "export declare class MemoryCacheStore implements CacheStore {\n private readonly cache;\n private readonly max;\n private readonly tagEpoch;\n private order;\n private readonly purgedKeys;\n private readonly purgedTags;\n private purgeFloor;\n constructor(options?: MemoryCacheStoreOptions);\n get(key: string): Promise<CachedResponse | undefined>;\n fence(): number;\n set(key: string, value: CachedResponse): Promise<void>;\n delete(key: string): Promise<void>;\n invalidateTag(tag: string): Promise<void>;\n private purgedAfter;\n private markPurged;\n private pruneTagEpochs;\n}",
9802
+ "signature": "export declare class MemoryCacheStore implements CacheStore {\n private readonly cache;\n private readonly max;\n private readonly tagEpoch;\n private readonly tagIndex;\n private order;\n private readonly purgedKeys;\n private readonly purgedTags;\n private purgeFloor;\n constructor(options?: MemoryCacheStoreOptions);\n get(key: string): Promise<CachedResponse | undefined>;\n fence(): number;\n set(key: string, value: CachedResponse): Promise<void>;\n delete(key: string): Promise<void>;\n invalidateTag(tag: string): Promise<void>;\n private evict;\n private purgedAfter;\n private markPurged;\n}",
9772
9803
  "doc": "/**\n * In-process ISR cache. Refuses to run in production unless explicitly allowed (mirrors the\n * rate-limit `MemoryStore` - a per-instance cache is unsafe across instances). Bounded **LRU**: a\n * read or write bumps the entry, so the least-recently-used evicts past `max` (a hot, frequently-read\n * page survives a burst of new pages).\n */"
9773
9804
  },
9774
9805
  {
@@ -9787,7 +9818,7 @@
9787
9818
  "name": "MemoryChannelHubOptions",
9788
9819
  "kind": "interface",
9789
9820
  "package": "@nifrajs/core",
9790
- "signature": "export interface MemoryChannelHubOptions {\n /** Default queue bound per subscriber. Default 64. */\n readonly maxQueue?: number;\n /** Maximum events retained per channel for local cursor replay. Default: the queue bound. */\n readonly historySize?: number;\n}"
9821
+ "signature": "export interface MemoryChannelHubOptions {\n /** Default queue bound per subscriber. Default 64. */\n readonly maxQueue?: number;\n /** Maximum events retained per channel for local cursor replay. Default: the queue bound. */\n readonly historySize?: number;\n /** Maximum inactive channels retained in sequence/history maps before evicting oldest. Default 4096. */\n readonly maxChannels?: number;\n}"
9791
9822
  },
9792
9823
  {
9793
9824
  "name": "MemoryCompactedView",
@@ -9883,13 +9914,13 @@
9883
9914
  "name": "MemoryResponseCache",
9884
9915
  "kind": "class",
9885
9916
  "package": "@nifrajs/middleware",
9886
- "signature": "export declare class MemoryResponseCache implements ResponseCacheStore {\n private readonly entries;\n private readonly maxEntries;\n constructor(options?: MemoryResponseCacheOptions);\n get(key: string): CachedResponse | undefined;\n set(key: string, response: CachedResponse): void;\n delete(key: string): void;\n}"
9917
+ "signature": "export declare class MemoryResponseCache implements ResponseCacheStore {\n private readonly entries;\n private readonly maxEntries;\n private readonly maxTotalBytes;\n private totalBytes;\n constructor(options?: MemoryResponseCacheOptions);\n get(key: string): CachedResponse | undefined;\n set(key: string, response: CachedResponse): void;\n delete(key: string): void;\n}"
9887
9918
  },
9888
9919
  {
9889
9920
  "name": "MemoryResponseCacheOptions",
9890
9921
  "kind": "interface",
9891
9922
  "package": "@nifrajs/middleware",
9892
- "signature": "export interface MemoryResponseCacheOptions {\n /** Maximum entries retained. Default `1000`. Oldest entries are evicted first. */\n readonly maxEntries?: number;\n /** Allow in-process cache in production. Off by default because it is per-instance. */\n readonly allowInProduction?: boolean;\n}"
9923
+ "signature": "export interface MemoryResponseCacheOptions {\n /** Maximum entries retained. Default `1000`. Least-recently-used entries are evicted first. */\n readonly maxEntries?: number;\n /** Maximum total cached body bytes retained in memory. Default `64 * 1024 * 1024` (64 MiB). */\n readonly maxTotalBytes?: number;\n /** Allow in-process cache in production. Off by default because it is per-instance. */\n readonly allowInProduction?: boolean;\n}"
9893
9924
  },
9894
9925
  {
9895
9926
  "name": "MemorySagaStore",
@@ -9926,7 +9957,7 @@
9926
9957
  "name": "MemoryStore",
9927
9958
  "kind": "class",
9928
9959
  "package": "@nifrajs/middleware",
9929
- "signature": "export declare class MemoryStore implements RateLimitStore {\n private readonly windows;\n private scan;\n private readonly maxKeys;\n private readonly sweepIntervalMs;\n private lastSweep;\n private evictionScans;\n /** Cumulative entries inspected by the eviction scan since construction - an eviction-pressure\n * gauge. The bounded scan keeps this ~O(1) per over-cap insert (≤ {@link MAX_EVICTION_SCAN}); a\n * regressed full O(n) sweep would make it ~maxKeys per insert (what the regression test asserts). */\n get evictionScanCount(): number;\n constructor(options?: MemoryStoreOptions);\n hit(key: string, windowMs: number): Promise<RateLimitResult>;\n private sweepExpired;\n private reclaimExpired;\n}",
9960
+ "signature": "export declare class MemoryStore implements RateLimitStore {\n private readonly windows;\n private scan;\n private sweepScan;\n private readonly maxKeys;\n private readonly sweepIntervalMs;\n private lastSweep;\n private evictionScans;\n /** Cumulative entries inspected by the eviction scan since construction - an eviction-pressure\n * gauge. The bounded scan keeps this ~O(1) per over-cap insert (≤ {@link MAX_EVICTION_SCAN}); a\n * regressed full O(n) sweep would make it ~maxKeys per insert (what the regression test asserts). */\n get evictionScanCount(): number;\n constructor(options?: MemoryStoreOptions);\n hit(key: string, windowMs: number): Promise<RateLimitResult>;\n private stepSweep;\n private reclaimExpired;\n}",
9930
9961
  "doc": "/**\n * In-process fixed-window store. Refuses to run in production unless explicitly allowed.\n *\n * Bounded against unbounded growth: expired windows are swept lazily (amortized, at most once per\n * `sweepIntervalMs`) and the key set is hard-capped at `maxKeys` (expired keys are evicted first,\n * then new keys are refused without resetting live quotas).\n * Without this, expired entries for keys never seen again - and the unbounded key space of a bot scan\n * - would accumulate in the map forever and OOM a single-instance deploy.\n */"
9931
9962
  },
9932
9963
  {
@@ -11595,6 +11626,13 @@
11595
11626
  "signature": "export type Params<Path extends string> = Path extends `${string}?` ? SplitOptionalRun<Path> extends [infer Head extends string, infer Run extends string] ? Prettify<RawParams<Head> & Partial<RawParams<Run>>> : Prettify<RawParams<Path>> : Prettify<RawParams<Path>>;",
11596
11627
  "doc": "/**\n * The params a handler for `Path` reads. A parameter in a trailing optional run is optional, since\n * the one handler serves the path with and without it: `/users/:id?` → `{ id?: string }`.\n */"
11597
11628
  },
11629
+ {
11630
+ "name": "ParamsOfFrom",
11631
+ "kind": "type",
11632
+ "package": "@nifrajs/web",
11633
+ "signature": "export type ParamsOfFrom<K extends string> = K extends RouteTablePattern ? Readonly<RouteParamsOf<K>> : Readonly<Record<string, string>>;",
11634
+ "doc": "/** The params `useParams(from)` gives: the route's, or the loose record for a pattern outside the table. */"
11635
+ },
11598
11636
  {
11599
11637
  "name": "ParseEntryOptions",
11600
11638
  "kind": "interface",
@@ -11688,6 +11726,20 @@
11688
11726
  "package": "@nifrajs/pi",
11689
11727
  "signature": "export interface PiBackendOptions {\n /** Defaults to `pi`, resolved through PATH. */\n readonly command?: string;\n /** Extra arguments appended after `--mode rpc`. */\n readonly args?: readonly string[];\n /**\n * Variables Pi runs with, on top of the base set (`PATH`, `HOME`, locale, terminal, and the\n * model-provider credentials Pi reads, such as `ANTHROPIC_API_KEY`). Nothing else from the parent\n * environment passes; a key mapped to `undefined` is withheld even when the parent has it.\n */\n readonly env?: Readonly<Record<string, string | undefined>>;\n readonly sessionDir?: string;\n readonly noSession?: boolean;\n /** Override the generated Pi flags for a test double or a compatible RPC executable. */\n readonly rpcArgs?: readonly string[];\n /**\n * Reload transport. Pi's documented RPC protocol uses a slash command bridged by a tiny\n * extension; compatible RPC implementations may opt into their legacy top-level command.\n */\n readonly reloadCommand?: \"restart\" | \"prompt\" | \"rpc\";\n /** Load the tiny public-API reload bridge. Defaults to true for generated Pi processes. */\n readonly enableReloadBridge?: boolean;\n readonly maxEventQueueSize?: number;\n /** Maximum UTF-8 bytes accepted for one Pi JSONL record. Defaults to 1 MiB. */\n readonly maxRecordBytes?: number;\n /** Maximum prompt characters accepted by the adapter. Defaults to 64 KiB. */\n readonly maxMessageChars?: number;\n /** Optional project instructions passed through Pi's documented append-system-prompt flag. */\n readonly appendSystemPrompt?: string;\n /** Opt-in loading of the separately packaged Nifra verification tools extension. */\n readonly enableNifraTools?: boolean;\n}"
11690
11728
  },
11729
+ {
11730
+ "name": "PlainKeyDefault",
11731
+ "kind": "type",
11732
+ "package": "@nifrajs/web",
11733
+ "signature": "export type PlainKeyDefault = string | number | readonly unknown[] | Record<string, unknown> | object;",
11734
+ "doc": "/**\n * The key type a plain-key overload assumes when its caller names only the data type\n * (`useQuery<Todo>(...)`). A fallback to `unknown` would let a typed key of another data type through.\n */"
11735
+ },
11736
+ {
11737
+ "name": "PlainQueryKey",
11738
+ "kind": "type",
11739
+ "package": "@nifrajs/web",
11740
+ "signature": "export type PlainQueryKey<K> = K & {\n readonly \"~nifraQueryData\"?: undefined;\n};",
11741
+ "doc": "/**\n * A key that is not a {@link QueryKey}. A typed key does not fit it, so the plain-key overload of `query`\n * / `useQuery` cannot take one: a typed key goes through the overload that checks its data type.\n */"
11742
+ },
11691
11743
  {
11692
11744
  "name": "PlainRender",
11693
11745
  "kind": "interface",
@@ -12325,13 +12377,13 @@
12325
12377
  "name": "ProofEvidence",
12326
12378
  "kind": "interface",
12327
12379
  "package": "@nifrajs/cli",
12328
- "signature": "export interface ProofEvidence {\n readonly id: string;\n readonly status: ProofStatus;\n readonly level: number;\n readonly nodeIds: readonly string[];\n readonly command: string;\n readonly fix?: string;\n}"
12380
+ "signature": "export interface ProofEvidence {\n readonly graphDigest: string;\n readonly buildDigest?: string | undefined;\n readonly id: string;\n readonly status: ProofStatus;\n readonly level: number;\n readonly nodeIds: readonly string[];\n readonly command: string;\n readonly fix?: string | undefined;\n}"
12329
12381
  },
12330
12382
  {
12331
12383
  "name": "ProofKind",
12332
12384
  "kind": "type",
12333
12385
  "package": "@nifrajs/cli",
12334
- "signature": "export type ProofKind = \"typecheck\" | \"contract\" | \"assurance\" | \"suite\";"
12386
+ "signature": "export type ProofKind = VerificationGate[\"kind\"];"
12335
12387
  },
12336
12388
  {
12337
12389
  "name": "ProofPlan",
@@ -12349,7 +12401,7 @@
12349
12401
  "name": "ProofStep",
12350
12402
  "kind": "interface",
12351
12403
  "package": "@nifrajs/cli",
12352
- "signature": "export interface ProofStep {\n readonly id: string;\n readonly kind: ProofKind;\n readonly level: number;\n readonly cost: number;\n readonly command: string;\n readonly nodeIds: readonly string[];\n readonly fix?: string;\n}"
12404
+ "signature": "export interface ProofStep {\n readonly id: string;\n readonly kind: ProofKind;\n readonly level: number;\n readonly cost: number;\n readonly command: string;\n /** Impact hints. Every ladder gate verifies the project as a whole. */\n readonly nodeIds: readonly string[];\n readonly fix?: string;\n}"
12353
12405
  },
12354
12406
  {
12355
12407
  "name": "ProtoPoisoning",
@@ -12459,7 +12511,7 @@
12459
12511
  "name": "QueryClient",
12460
12512
  "kind": "interface",
12461
12513
  "package": "@nifrajs/web",
12462
- "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 the successful queries that `options.shouldDehydrateQuery` selects to a transferable\n * snapshot (server → client SSR bridge). Deny by default: with no filter the snapshot is empty. */\n dehydrate: (options?: DehydrateOptions) => 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}",
12514
+ "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: {\n <T>(key: QueryKey<T>, fn: () => Promise<T>, options?: QueryOptions): QueryHandle<T>;\n <T, K = PlainKeyDefault>(key: PlainQueryKey<K>, fn: () => Promise<T>, options?: QueryOptions): QueryHandle<T>;\n };\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: QueryKey<T>) => 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: QueryKey<T>, 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: {\n <T>(key: QueryKey<T>, fn: () => Promise<T>, options?: QueryOptions): Promise<void>;\n <T, K = PlainKeyDefault>(key: PlainQueryKey<K>, fn: () => Promise<T>, options?: QueryOptions): Promise<void>;\n };\n /** Serialize the successful queries that `options.shouldDehydrateQuery` selects to a transferable\n * snapshot (server → client SSR bridge). Deny by default: with no filter the snapshot is empty. */\n dehydrate: (options?: DehydrateOptions) => 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}",
12463
12515
  "doc": "/** The keyed query cache. One per app (a binding registers it like the router). */"
12464
12516
  },
12465
12517
  {
@@ -12496,6 +12548,13 @@
12496
12548
  "signature": "export interface QueryHandle<T = unknown> {\n snapshot: () => QueryState<T>;\n subscribe: (listener: () => void) => () => void;\n /** Fetch when stale or absent (fresh ⇒ no-op); joins an in-flight fetch (dedup). Resolves to the\n * data, or rejects if the fetch threw. */\n fetch: () => Promise<T>;\n /** Refetch regardless of staleness (still joins an in-flight fetch). */\n refetch: () => Promise<T>;\n}",
12497
12549
  "doc": "/** A stable per-key handle: subscribe to its state, read a snapshot, trigger a fetch/refetch. */"
12498
12550
  },
12551
+ {
12552
+ "name": "QueryKey",
12553
+ "kind": "type",
12554
+ "package": "@nifrajs/web",
12555
+ "signature": "export type QueryKey<T> = {\n readonly \"~nifraQueryData\": T;\n};",
12556
+ "doc": "/**\n * What a typed query key adds to the key itself: the type of the data stored under it. Make one with\n * {@link queryKey} - `const todosKey = queryKey<Todo[]>([\"todos\"])` - and use it everywhere: the fetcher\n * must return that type, and `getQueryData` / `setQueryData` read and write it, so a key and its data\n * cannot drift apart. At run time it is the key itself, so prefix invalidation\n * (`invalidateQueries([\"todos\"])`) works unchanged.\n */"
12557
+ },
12499
12558
  {
12500
12559
  "name": "QueryOptions",
12501
12560
  "kind": "interface",
@@ -12568,7 +12627,7 @@
12568
12627
  "name": "R2BucketLike",
12569
12628
  "kind": "interface",
12570
12629
  "package": "@nifrajs/storage",
12571
- "signature": "export interface R2BucketLike {\n put(key: string, value: ArrayBuffer | ArrayBufferView, options?: {\n httpMetadata?: {\n contentType?: string;\n };\n customMetadata?: Record<string, string>;\n }): Promise<unknown>;\n get(key: string): Promise<(R2ObjectLike & {\n arrayBuffer(): Promise<ArrayBuffer>;\n }) | null>;\n head(key: string): Promise<R2ObjectLike | null>;\n delete(key: string): Promise<void>;\n list(options?: {\n prefix?: string;\n limit?: number;\n cursor?: string;\n }): Promise<{\n objects: ReadonlyArray<{\n key: string;\n }>;\n truncated?: boolean;\n cursor?: string;\n }>;\n}",
12630
+ "signature": "export interface R2BucketLike {\n put(key: string, value: ArrayBuffer | ArrayBufferView, options?: {\n httpMetadata?: {\n contentType?: string;\n };\n customMetadata?: Record<string, string>;\n }): Promise<unknown>;\n get(key: string): Promise<(R2ObjectLike & {\n readonly body?: ReadableStream<Uint8Array>;\n arrayBuffer(): Promise<ArrayBuffer>;\n }) | null>;\n head(key: string): Promise<R2ObjectLike | null>;\n delete(key: string): Promise<void>;\n list(options?: {\n prefix?: string;\n limit?: number;\n cursor?: string;\n }): Promise<{\n objects: ReadonlyArray<{\n key: string;\n }>;\n truncated?: boolean;\n cursor?: string;\n }>;\n}",
12572
12631
  "doc": "/** The slice of the R2 bucket binding this adapter calls. `env.<BUCKET>` satisfies it. */"
12573
12632
  },
12574
12633
  {
@@ -12582,7 +12641,7 @@
12582
12641
  "name": "R2Storage",
12583
12642
  "kind": "class",
12584
12643
  "package": "@nifrajs/storage",
12585
- "signature": "export declare class R2Storage implements StorageAdapter {\n private readonly bucket;\n constructor(bucket: R2BucketLike);\n put(key: string, data: StorageData, options?: PutOptions): Promise<void>;\n get(key: string): Promise<StorageObject | null>;\n delete(key: string): Promise<void>;\n exists(key: string): Promise<boolean>;\n /** Every key (up to `limit`), following R2's cursor past the 1000 keys one call returns. */\n list(options?: ListOptions): Promise<string[]>;\n /** One page of at most 1000 keys, and the cursor for the next while there are more. */\n listPage(options?: StorageListPageOptions): Promise<StorageListPage>;\n}"
12644
+ "signature": "export declare class R2Storage implements StorageAdapter {\n private readonly bucket;\n private readonly maxReadBytes;\n constructor(bucket: R2BucketLike, options?: {\n readonly maxReadBytes?: number;\n });\n put(key: string, data: StorageData, options?: PutOptions): Promise<void>;\n /** Read up to `maxReadBytes` (16 MiB by default). An oversized object throws a RangeError. */\n get(key: string): Promise<StorageObject | null>;\n delete(key: string): Promise<void>;\n exists(key: string): Promise<boolean>;\n /** Every key (up to `limit`), following R2's cursor past the 1000 keys one call returns. */\n list(options?: ListOptions): Promise<string[]>;\n /** One page of at most 1000 keys, and the cursor for the next while there are more. */\n listPage(options?: StorageListPageOptions): Promise<StorageListPage>;\n}"
12586
12645
  },
12587
12646
  {
12588
12647
  "name": "REDACTED_CELL",
@@ -13012,7 +13071,7 @@
13012
13071
  "name": "RedirectOptions",
13013
13072
  "kind": "interface",
13014
13073
  "package": "@nifrajs/web",
13015
- "signature": "export interface RedirectOptions {\n /** HTTP status (default 303 See Other; pass 307/308 to preserve the method). */\n readonly status?: number;\n /** Allow an off-origin / absolute destination. Off by default: only a same-origin path (a single\n * leading `/`) is permitted, so an action can't be turned into an open redirect by passing\n * attacker-controlled input straight through. Set `true` for a deliberate external redirect. */\n readonly external?: boolean;\n /** Extra response headers. A redirect is no longer a `Response`, so there is no `.headers` to\n * mutate after the fact - name them here. Cookies queued with `ctx.set.cookie()` still ride it. */\n readonly headers?: Readonly<Record<string, string>>;\n}",
13074
+ "signature": "export interface RedirectOptions {\n /** HTTP status (default 303 See Other; pass 307/308 to preserve the method). */\n readonly status?: number;\n /** Allow an off-origin / absolute destination. Off by default: only a same-origin path (a single\n * leading `/`) is permitted, so an action can't be turned into an open redirect by passing\n * attacker-controlled input straight through. Set `true` for a deliberate external redirect. */\n readonly external?: boolean;\n /** Extra response headers. A redirect is no longer a `Response`, so there is no `.headers` to\n * mutate after the fact - name them here. Cookies queued with `ctx.set.cookie()` still ride it. */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * Where to go when `location` is the inert `Href` that `href()` or `rawHref()` returned for a value\n * it refused (a bad param from data, already reported). Without it `redirect` throws, since there\n * is nowhere to send the visitor; a Post/Redirect/Get action that has already written passes one\n * so a bad value costs the destination, not a 500 after the write.\n */\n readonly fallback?: Href;\n}",
13016
13075
  "doc": "/** Options for {@link redirect}. */"
13017
13076
  },
13018
13077
  {
@@ -13262,7 +13321,7 @@
13262
13321
  "name": "RenderPageOptions",
13263
13322
  "kind": "interface",
13264
13323
  "package": "@nifrajs/web",
13265
- "signature": "export interface RenderPageOptions {\n readonly serverComponents?: import(\"../server-components/types.js\").ComponentState;\n readonly adapter: RenderAdapter;\n /** The layout chain to render - outermost layout → page (opaque; the adapter renders it). */\n readonly chain: readonly unknown[];\n /** The loader output for this request. */\n readonly data: unknown;\n /** An action's data return (POST only) - surfaced to the page as `actionData` + serialized\n * for the client so post-POST hydration matches. Omit on GETs. */\n readonly actionData?: unknown;\n /**\n * A live runtime's seed for this page (`createWebApp({ live })` sets it): handed to the client\n * entry, which exchanges it for a grant instead of loading the page again.\n */\n readonly live?: unknown;\n /**\n * URL of the built client entry (loaded as a module script).\n *\n * Optional ONLY on a `hydrate: false` page, where there is no client takeover to feed and this value\n * reaches no output at all. The union below is what enforces that: omitting it on a hydrating page\n * stays a compile error rather than rendering `src=\"\"`.\n */\n readonly clientEntry?: string;\n /** Chunk URLs for the **matched** route (its layout chain + own chunk) to `modulepreload` in the\n * shell - so the route code downloads in parallel with the entry instead of after it\n * (`buildClient`'s per-route map). Empty/omitted ⇒ only the entry is preloaded (unchanged). */\n readonly preload?: readonly string[];\n /** Stylesheet URLs for the **matched** route (its layout chain + own CSS, from `buildClient`'s\n * `BuildManifest.css`) - injected as `<link rel=\"stylesheet\">` in `<head>` so styles arrive with the\n * first paint (no FOUC). Rendered even on non-hydrated pages. Empty/omitted ⇒ none (unchanged). */\n readonly styles?: readonly string[];\n /**\n * Activation policy for these framework-owned stylesheet links (default `\"blocking\"`). In\n * `\"deferred\"` mode, hydrating pages fetch with `media=\"print\"` and the generated client promotes\n * them to `media=\"all\"` after load/error/timeout. Non-hydrated pages remain blocking so JS-off pages\n * and terminal documents are styled.\n */\n readonly cssLoading?: CssLoadingMode;\n /** SSG: the prerendered-path set, serialized to `window.__NIFRA_PRERENDERED__` so the client fetches\n * a static `_data.json` on soft-nav into a prerendered route. Empty/omitted ⇒ not injected. */\n readonly prerenderedPaths?: readonly string[];\n /** SSG: the URL of a JSON array of the prerendered paths, handed over in place of\n * {@link prerenderedPaths} so a large set is fetched once instead of riding in every page. */\n readonly prerenderedListUrl?: string;\n /** Locale key -> copy chunk URL (`buildClient`'s `BuildManifest.copyChunks`), handed over to the\n * client; the chunks this page reads its copy from are preloaded. Omit ⇒ none. */\n readonly copyChunks?: Readonly<Record<string, string>>;\n /** The page's locale from the app's locale routing: `<html lang dir>` default to it unless `head`\n * sets `lang`, the response carries `Content-Language`, and the adapter reads it as\n * `RenderProps.locale`. Omit ⇒ none of these. */\n readonly locale?: PageLocale;\n /** The served locales, handed to the client so it names each page's locale on navigation. */\n readonly locales?: PageLocales;\n /** ISR: route freshness in seconds, emitted as the `x-nifra-isr-revalidate` header for a `withISR`\n * wrapper to read. Omit ⇒ no header (the wrapper's default TTL applies). */\n readonly revalidate?: number;\n /** ISR invalidation tags emitted as a bounded `x-nifra-isr-tags` header. */\n readonly revalidateTags?: readonly string[];\n /** Matched route id; written to `window.__NIFRA_ROUTE__` so the client hydrates this chain. */\n readonly routeId?: string;\n /** The matched route's decoded path params - surfaced to the page as `params` (via {@link RenderProps})\n * so an adapter's `useParams` is SSR-correct. Omit ⇒ `{}` (a route with no dynamic segments, or an\n * error/404 render). */\n readonly params?: Readonly<Record<string, string>>;\n /** The request's `pathname + search` - surfaced as `path` (via {@link RenderProps}) so an adapter's\n * `useLocation`/`useSearchParams` render the right URL server-side and hydrate without drift. Omit ⇒\n * `\"\"`. */\n readonly path?: string;\n /** The route's validated search (`searchOf(mod.searchSchema, url.search)`, the same value handed to\n * the loader as `ctx.search`), surfaced as `search` (via {@link RenderProps}) so an adapter's\n * `useSearch` is SSR-correct. Omit ⇒ `{}` (a render with no search context). */\n readonly search?: Record<string, unknown>;\n /** Per-layout loader data, forwarded to the adapter as `RenderProps.layoutData`. Aligned with the\n * chain's layout prefix; omitted when no layout in the chain has a loader. */\n readonly layoutData?: readonly unknown[];\n /** Dynamic-boundary states, forwarded to the adapter and serialized for hydration when present. */\n readonly boundaries?: BoundaryStates;\n /** The chain's ids and `handle` exports, forwarded as `RenderProps.matchChain` for `useMatches`. */\n readonly matchChain?: MatchChain;\n /** HTTP status for the response (default 200; e.g. 404 for a not-found page). */\n readonly status?: number;\n /**\n * The slot an `x-nifra-swap` request names. When the adapter renders slots and nothing is\n * deferred, the response is that slot's HTML alone; otherwise the whole document.\n */\n readonly swapSlot?: string;\n /** Chain indices the adapter renders inside the slot wrappers of a kept page (`keepAlive`), so the\n * browser can keep the page this document shows without remounting it. */\n readonly slots?: readonly number[];\n /** Extra response headers - e.g. the `cache-control` a terminal status page wants. `content-type`\n * is ignored (the document is always HTML) and the ISR freshness header is applied after these,\n * so neither can be overridden from here. */\n readonly headers?: HeadersLike;\n /** Document title (fallback when `head.title` is unset). */\n readonly title?: string;\n /** Resolved route head - `title` overrides `title` above; `meta`/`link` render as managed\n * (`data-nifra`) tags the client updates on navigation.\n *\n * **Head contract (the layout chain contributes).** `createWebApp` resolves this via\n * {@link mergeHeads}: a route's head is its **layout chain's** `meta`/`head` exports merged with the\n * page's. A `_layout.tsx` may `export const meta` (or `export function meta(args)`) - its tags land\n * on every page below it (the home for `hreflang`, `preconnect`, a section-default `<title>`). The\n * merge is **nearest-wins for scalars** (the page's `title` overrides an inner layout's, which\n * overrides an outer one; an undefined page title keeps the layout's) and **concatenated for the\n * `meta`/`link` arrays** (outermost layout first, page last). `<meta>`/`<link>` attributes pass a\n * shared tag-specific allowlist (including inert `data-*` metadata) and values are escaped. */\n readonly head?: Meta;\n /** Id of the container wrapping the app markup (default `\"root\"`). A non-default id also gets\n * {@link ROOT_ATTRIBUTE}, which is how the generated client entry finds the container to hydrate -\n * the entry is built once and cannot know what a given render chose. */\n readonly rootId?: string;\n /** When `false`, emit a complete but **non-hydrated** document - no client entry script, data\n * globals, or modulepreloads. Used for server-rendered `_error` pages: a terminal state that needs no\n * client takeover, and it sidesteps an SSR/hydrate mismatch (the server rendered the boundary, not\n * the page the client manifest maps this route id to). Default `true`. */\n readonly hydrate?: boolean;\n /** Island client bundles (`@nifrajs/web/islands`) to load as `<script type=\"module\">` in the document\n * tail - emitted **regardless of `hydrate`**, so a static (`hydrate: false`) page can still mount\n * no-framework islands. URLs are attribute-escaped. Empty/omitted ⇒ none (unchanged output). */\n readonly islandScripts?: readonly string[];\n /** CSP nonce applied to every framework-owned executable script in this document. Nonce-bearing\n * documents are marked `private, no-store` so a request-specific nonce is never replayed. */\n readonly nonce?: string;\n /** The request's abort signal. A deferred value that rejects because it aborted is the client\n * leaving, not a failure, so the server log skips it. Omit ⇒ every rejection is logged. */\n readonly signal?: AbortSignal;\n /** Where a rejected deferred value is logged: the app's error log. Omit ⇒ the console. */\n readonly logError?: ((error: unknown) => void) | undefined;\n /**\n * A hash-based Content-Security-Policy from `createCspPolicy`. The document then carries `nonce`\n * only when it needs one (it defers a value, or a head tag names the nonce); otherwise it renders\n * nonce-free and cacheable. The policy's header is set on the response either way.\n */\n readonly csp?: CspPolicy;\n /**\n * Advanced: a per-route slot the renderer fills with the request-invariant document pieces (shell\n * prefix/suffix, tail statics) on the first render and reuses afterwards, skipping their re-assembly.\n *\n * Only pass a cache when every shell-shaping input is IDENTICAL across the requests sharing it:\n * same `head` content (a static meta chain - never a `meta(data)` function), `locale`, `title`, `styles`,\n * `cssLoading`, `preload`, `islandScripts`, `clientEntry`, `rootId`, `hydrate`, and `prerenderedPaths`.\n * Per-request\n * values (`data`, `params`, `search`, `actionData`, `layoutData`, deferred state) are always assembled\n * fresh and safe. A per-request `nonce` disables the cache automatically. `createWebApp` wires this\n * per route, gated on the route + layout metas being static.\n */\n readonly assemblyCache?: RenderAssemblyCache;\n}"
13324
+ "signature": "export interface RenderPageOptions {\n /** Initial response timing, when an inspector is attached. */\n readonly timing?: RouteTiming;\n readonly serverComponents?: import(\"../server-components/types.js\").ComponentState;\n readonly adapter: RenderAdapter;\n /** The layout chain to render - outermost layout → page (opaque; the adapter renders it). */\n readonly chain: readonly unknown[];\n /** The loader output for this request. */\n readonly data: unknown;\n /** An action's data return (POST only) - surfaced to the page as `actionData` + serialized\n * for the client so post-POST hydration matches. Omit on GETs. */\n readonly actionData?: unknown;\n /**\n * A live runtime's seed for this page (`createWebApp({ live })` sets it): handed to the client\n * entry, which exchanges it for a grant instead of loading the page again.\n */\n readonly live?: unknown;\n /**\n * URL of the built client entry (loaded as a module script).\n *\n * Optional ONLY on a `hydrate: false` page, where there is no client takeover to feed and this value\n * reaches no output at all. The union below is what enforces that: omitting it on a hydrating page\n * stays a compile error rather than rendering `src=\"\"`.\n */\n readonly clientEntry?: string;\n /** Chunk URLs for the **matched** route (its layout chain + own chunk) to `modulepreload` in the\n * shell - so the route code downloads in parallel with the entry instead of after it\n * (`buildClient`'s per-route map). Empty/omitted ⇒ only the entry is preloaded (unchanged). */\n readonly preload?: readonly string[];\n /** Stylesheet URLs for the **matched** route (its layout chain + own CSS, from `buildClient`'s\n * `BuildManifest.css`) - injected as `<link rel=\"stylesheet\">` in `<head>` so styles arrive with the\n * first paint (no FOUC). Rendered even on non-hydrated pages. Empty/omitted ⇒ none (unchanged). */\n readonly styles?: readonly string[];\n /**\n * Activation policy for these framework-owned stylesheet links (default `\"blocking\"`). In\n * `\"deferred\"` mode, hydrating pages fetch with `media=\"print\"` and the generated client promotes\n * them to `media=\"all\"` after load/error/timeout. Non-hydrated pages remain blocking so JS-off pages\n * and terminal documents are styled.\n */\n readonly cssLoading?: CssLoadingMode;\n /** SSG: the prerendered-path set, serialized to `window.__NIFRA_PRERENDERED__` so the client fetches\n * a static `_data.json` on soft-nav into a prerendered route. Empty/omitted ⇒ not injected. */\n readonly prerenderedPaths?: readonly string[];\n /** SSG: the URL of a JSON array of the prerendered paths, handed over in place of\n * {@link prerenderedPaths} so a large set is fetched once instead of riding in every page. */\n readonly prerenderedListUrl?: string;\n /** Locale key -> copy chunk URL (`buildClient`'s `BuildManifest.copyChunks`), handed over to the\n * client; the chunks this page reads its copy from are preloaded. Omit ⇒ none. */\n readonly copyChunks?: Readonly<Record<string, string>>;\n /** The page's locale from the app's locale routing: `<html lang dir>` default to it unless `head`\n * sets `lang`, the response carries `Content-Language`, and the adapter reads it as\n * `RenderProps.locale`. Omit ⇒ none of these. */\n readonly locale?: PageLocale;\n /** The served locales, handed to the client so it names each page's locale on navigation. */\n readonly locales?: PageLocales;\n /** ISR: route freshness in seconds, emitted as the `x-nifra-isr-revalidate` header for a `withISR`\n * wrapper to read. Omit ⇒ no header (the wrapper's default TTL applies). */\n readonly revalidate?: number;\n /** ISR invalidation tags emitted as a bounded `x-nifra-isr-tags` header. */\n readonly revalidateTags?: readonly string[];\n /** Matched route id; written to `window.__NIFRA_ROUTE__` so the client hydrates this chain. */\n readonly routeId?: string;\n /** The matched route's decoded path params - surfaced to the page as `params` (via {@link RenderProps})\n * so an adapter's `useParams` is SSR-correct. Omit ⇒ `{}` (a route with no dynamic segments, or an\n * error/404 render). */\n readonly params?: Readonly<Record<string, string>>;\n /** The request's `pathname + search` - surfaced as `path` (via {@link RenderProps}) so an adapter's\n * `useLocation`/`useSearchParams` render the right URL server-side and hydrate without drift. Omit ⇒\n * `\"\"`. */\n readonly path?: string;\n /** The route's validated search (`searchOf(mod.searchSchema, url.search)`, the same value handed to\n * the loader as `ctx.search`), surfaced as `search` (via {@link RenderProps}) so an adapter's\n * `useSearch` is SSR-correct. Omit ⇒ `{}` (a render with no search context). */\n readonly search?: Record<string, unknown>;\n /** Per-layout loader data, forwarded to the adapter as `RenderProps.layoutData`. Aligned with the\n * chain's layout prefix; omitted when no layout in the chain has a loader. */\n readonly layoutData?: readonly unknown[];\n /** Dynamic-boundary states, forwarded to the adapter and serialized for hydration when present. */\n readonly boundaries?: BoundaryStates;\n /** The chain's ids and `handle` exports, forwarded as `RenderProps.matchChain` for `useMatches`. */\n readonly matchChain?: MatchChain;\n /** HTTP status for the response (default 200; e.g. 404 for a not-found page). */\n readonly status?: number;\n /**\n * The slot an `x-nifra-swap` request names. When the adapter renders slots and nothing is\n * deferred, the response is that slot's HTML alone; otherwise the whole document.\n */\n readonly swapSlot?: string;\n /** Chain indices the adapter renders inside the slot wrappers of a kept page (`keepAlive`), so the\n * browser can keep the page this document shows without remounting it. */\n readonly slots?: readonly number[];\n /** Extra response headers - e.g. the `cache-control` a terminal status page wants. `content-type`\n * is ignored (the document is always HTML) and the ISR freshness header is applied after these,\n * so neither can be overridden from here. */\n readonly headers?: HeadersLike;\n /** Document title (fallback when `head.title` is unset). */\n readonly title?: string;\n /** Resolved route head - `title` overrides `title` above; `meta`/`link` render as managed\n * (`data-nifra`) tags the client updates on navigation.\n *\n * **Head contract (the layout chain contributes).** `createWebApp` resolves this via\n * {@link mergeHeads}: a route's head is its **layout chain's** `meta`/`head` exports merged with the\n * page's. A `_layout.tsx` may `export const meta` (or `export function meta(args)`) - its tags land\n * on every page below it (the home for `hreflang`, `preconnect`, a section-default `<title>`). The\n * merge is **nearest-wins for scalars** (the page's `title` overrides an inner layout's, which\n * overrides an outer one; an undefined page title keeps the layout's) and **concatenated for the\n * `meta`/`link` arrays** (outermost layout first, page last). `<meta>`/`<link>` attributes pass a\n * shared tag-specific allowlist (including inert `data-*` metadata) and values are escaped. */\n readonly head?: Meta;\n /** Id of the container wrapping the app markup (default `\"root\"`). A non-default id also gets\n * {@link ROOT_ATTRIBUTE}, which is how the generated client entry finds the container to hydrate -\n * the entry is built once and cannot know what a given render chose. */\n readonly rootId?: string;\n /** When `false`, emit a complete but **non-hydrated** document - no client entry script, data\n * globals, or modulepreloads. Used for server-rendered `_error` pages: a terminal state that needs no\n * client takeover, and it sidesteps an SSR/hydrate mismatch (the server rendered the boundary, not\n * the page the client manifest maps this route id to). Default `true`. */\n readonly hydrate?: boolean;\n /** Island client bundles (`@nifrajs/web/islands`) to load as `<script type=\"module\">` in the document\n * tail - emitted **regardless of `hydrate`**, so a static (`hydrate: false`) page can still mount\n * no-framework islands. URLs are attribute-escaped. Empty/omitted ⇒ none (unchanged output). */\n readonly islandScripts?: readonly string[];\n /** CSP nonce applied to every framework-owned executable script in this document. Nonce-bearing\n * documents are marked `private, no-store` so a request-specific nonce is never replayed. */\n readonly nonce?: string;\n /** The request's abort signal. A deferred value that rejects because it aborted is the client\n * leaving, not a failure, so the server log skips it. Omit ⇒ every rejection is logged. */\n readonly signal?: AbortSignal;\n /** Where a rejected deferred value is logged: the app's error log. Omit ⇒ the console. */\n readonly logError?: ((error: unknown) => void) | undefined;\n /**\n * A hash-based Content-Security-Policy from `createCspPolicy`. The document then carries `nonce`\n * only when it needs one (it defers a value, or a head tag names the nonce); otherwise it renders\n * nonce-free and cacheable. The policy's header is set on the response either way.\n */\n readonly csp?: CspPolicy;\n /**\n * Advanced: a per-route slot the renderer fills with the request-invariant document pieces (shell\n * prefix/suffix, tail statics) on the first render and reuses afterwards, skipping their re-assembly.\n *\n * Only pass a cache when every shell-shaping input is IDENTICAL across the requests sharing it:\n * same `head` content (a static meta chain - never a `meta(data)` function), `locale`, `title`, `styles`,\n * `cssLoading`, `preload`, `islandScripts`, `clientEntry`, `rootId`, `hydrate`, and `prerenderedPaths`.\n * Per-request\n * values (`data`, `params`, `search`, `actionData`, `layoutData`, deferred state) are always assembled\n * fresh and safe. A per-request `nonce` disables the cache automatically. `createWebApp` wires this\n * per route, gated on the route + layout metas being static.\n */\n readonly assemblyCache?: RenderAssemblyCache;\n}"
13266
13325
  },
13267
13326
  {
13268
13327
  "name": "RenderProps",
@@ -14180,6 +14239,13 @@
14180
14239
  "signature": "export interface RouteEntry {\n readonly id: string;\n readonly pattern: string;\n readonly layoutIds: readonly string[];\n /**\n * Param names each layout in {@link layoutIds} owns, aligned by index.\n *\n * A layout wraps a URL prefix, so these are the params it may read and the ones whose change should\n * re-run its loader - everything deeper belongs to routes beneath it. Derived per (route, layout)\n * pair rather than per layout, because one layout can own different params on different expanded\n * patterns: `[[lang]]/docs/_layout` owns nothing on `/docs/:slug` and `{lang}` on `/:lang/docs/:slug`.\n * Optional only so hand-built test manifests may omit it.\n */\n readonly layoutParams?: ReadonlyArray<readonly string[]>;\n /** `_middleware` ids in this route's ancestor chain (outermost → innermost), run before its\n * layouts. Absent ⇒ none. */\n readonly middlewareIds?: readonly string[];\n /** Param names each middleware in {@link middlewareIds} sees, aligned by index: the params of its\n * directory's URL prefix, as {@link layoutParams} holds them for a layout. */\n readonly middlewareParams?: ReadonlyArray<readonly string[]>;\n /** `_error` boundary ids in this route's ancestor chain (outermost → innermost). The last is the\n * **nearest** boundary, rendered when the route's loader throws. Always set by `buildManifest`\n * (optional only so hand-built test manifests may omit it); absent/empty ⇒ no boundary (error 500s). */\n readonly errorIds?: readonly string[];\n /** Nested `_404` page ids in this route's ancestor chain (outermost → innermost); the root `_404`\n * is not listed. The last is the **nearest**, rendered when the route's loader answers\n * `notFound()`. Absent ⇒ the root `_404`. */\n readonly notFoundIds?: readonly string[];\n /** `_loading` page ids in this route's ancestor chain (outermost → innermost). A client navigation\n * to the route shows the innermost one whose layouts are already on screen. Absent ⇒ none. */\n readonly loadingIds?: readonly string[];\n /** The frontend half: the file the browser bundle imports. */\n readonly file: string;\n /** Set when the frontend half exports `keepAlive` (found by a scan of its source): its page renders\n * inside the slot wrappers a kept page needs, on the server and in the browser. */\n readonly keepAlive?: true;\n /** The backend half (`x.backend.ts`), when the route has one. Server-only. */\n readonly backend?: string;\n /** Both halves, merged and checked. */\n readonly load: () => Promise<RouteModule>;\n}",
14181
14240
  "doc": "/** One matched route: pattern, nested layout ids (outermost → innermost), source file, loader. */"
14182
14241
  },
14242
+ {
14243
+ "name": "RouteFrom",
14244
+ "kind": "type",
14245
+ "package": "@nifrajs/web",
14246
+ "signature": "export type RouteFrom = [RouteTablePattern] extends [never] ? string : RouteTablePattern;",
14247
+ "doc": "/**\n * What a route hook's argument accepts: a {@link RouteTable} key, or any string while the table is empty\n * (before `nifra types` has run, or in a program that never loads it), the way `href` does.\n */"
14248
+ },
14183
14249
  {
14184
14250
  "name": "RouteInfo",
14185
14251
  "kind": "interface",
@@ -14278,6 +14344,13 @@
14278
14344
  "signature": "export type RouteMethod = Method | (string & {});",
14279
14345
  "doc": "/**\n * A method a route is registered under: a standard {@link Method}, or another token that\n * {@link isRegistrableMethod} accepts (`PROPFIND`, `PURGE`, ...).\n */"
14280
14346
  },
14347
+ {
14348
+ "name": "RouteMethods",
14349
+ "kind": "type",
14350
+ "package": "@nifrajs/web",
14351
+ "signature": "export type RouteMethods<App, Path extends string> = Path extends keyof RegistryOf<App> ? Lowercase<keyof RegistryOf<App>[Path] & string> : never;",
14352
+ "doc": "/** The lowercase methods `App` declares for `Path`: what a form for that route may use. */"
14353
+ },
14281
14354
  {
14282
14355
  "name": "RouteMiddleware",
14283
14356
  "kind": "type",
@@ -14292,6 +14365,13 @@
14292
14365
  "signature": "export interface RouteModule {\n readonly default: unknown;\n readonly loader?: Loader;\n /**\n * Named, independently navigable route regions. Each name is bound to route patterns from the\n * generated route table; URL state selects only one of these registered identities.\n */\n readonly routeSlots?: Readonly<Record<string, readonly string[]>>;\n /** Layout loader that must run before actions and is not retained across the action's render. */\n readonly gate?: boolean;\n readonly action?: Action;\n /**\n * Backend half only: which browser origins may POST to {@link action}. When omitted, a request\n * whose `Origin` is another site's is refused with 403 before middleware, gates or the action run;\n * requests without an `Origin` (non-browser clients) pass. An array allows exactly those origins\n * (and refuses a request without one); a function decides, receiving `null` when there is none and,\n * as its second argument, whether the default same-origin check would admit the request, so a route\n * can accept its own site and one more origin: `(origin, sameOrigin) => sameOrigin || origin === shell`.\n * Use it for a callback a third party posts to, such as an identity provider's `form_post`.\n * `Origin` is browser-enforced, not authentication: keep the action's own auth checks.\n */\n readonly allowedOrigins?: ReadonlyArray<string> | ((origin: string | null, sameOrigin: boolean) => boolean);\n /**\n * Backend half only: the schema of what {@link loader} sends to the browser. Required whenever the\n * loader returns data. Keys it does not declare are dropped before the page renders; a declared\n * field of the wrong shape fails the request with a 500 naming the field's path.\n */\n readonly loaderOutput?: StandardSchemaV1;\n /** Backend half only: the schema of what {@link action} sends back, held to the same rule. */\n readonly actionOutput?: StandardSchemaV1;\n /**\n * Backend half only: the loader of a partially prerendered page's shared shell. It\n * receives no request, so its output is the same for every visitor and the shell is cached.\n */\n readonly shellLoader?: (ctx: ShellCtx) => unknown;\n /** Backend half only: the schema of what {@link shellLoader} returns. */\n readonly shellOutput?: StandardSchemaV1;\n /**\n * Backend half only: query parameters that select a different shell, each with its\n * closed set of values (`{ search: { color: [\"red\", \"blue\"] } }`). Any other parameter, or a value\n * outside its set, builds the default shell; holes still read the whole query.\n */\n readonly shellVariations?: ShellVariations;\n /** Optional client-only loader. It runs after hydration and on client navigations. */\n readonly clientLoader?: ClientLoader;\n /** Optional client-only submit wrapper. The server action remains mandatory for mutations. */\n readonly clientAction?: ClientAction;\n /** Named async boundaries owned by this route. The adapter renders their neutral state seam. A\n * boundary's `load` comes from {@link boundaryLoaders} in the route's backend half; the frontend\n * file declares only how it renders. */\n readonly boundaries?: readonly BoundaryRegistration[];\n /** Backend half only: each boundary's server loader, keyed by boundary name. */\n readonly boundaryLoaders?: Readonly<Record<string, BoundaryLoaderEntry>>;\n /** A Standard Schema validating this route's URL search params. When present, `ctx.search` is parsed +\n * validated against it (failing closed to the schema's defaults on invalid input); type it into the\n * loader with `LoaderArgs<Api, Env, typeof searchSchema>`. */\n readonly searchSchema?: StandardSchemaV1<unknown, Record<string, unknown>>;\n /** Search keys that are purely client-side UI (`\"tab\"`, a client-side `\"sort\"`, `\"modal\"`) and do NOT\n * affect this route's loader. When a client navigation stays on the same route + pathname and changes\n * ONLY these keys, the router updates the URL (so `useSearch` re-renders) WITHOUT re-running the loader.\n * Any other key change revalidates as usual - so omitting a data-affecting key here can never serve\n * stale data, it only forgoes the optimization. Client-only: the server always renders fresh. */\n readonly searchClientKeys?: readonly string[];\n /**\n * `false` gives every client reload of this page (an action's revalidation, `invalidate()`, a live\n * refresh) fresh data. By default a reload keeps the identity of the parts of `data` and the layouts'\n * data that it did not change, so an unchanged row keeps its DOM and component state, and a renderer\n * that memoizes on identity skips it. Not every unchanged row, though: an array whose first 32\n * elements all changed is taken whole, later unchanged elements included, so code that needs a row's\n * identity must not count on it. Opt out for a page whose code compares `data` against its value\n * from before the reload, or whose rows re-render whatever their identity, which then pay the\n * comparison for nothing. Client-only.\n */\n readonly shareData?: boolean;\n /**\n * Keep this page mounted after the visitor leaves it, so back and forward show it again as it was\n * left: its component state, form fields, inner scroll offsets and focus. At most three pages are\n * kept per tab, each for at most 10 minutes; a kept page is shown again only by a back or forward to\n * its own history entry, and its data reloads in place. A sign-in or sign-out drops every kept page.\n * Client-only.\n */\n readonly keepAlive?: true | KeepAliveOptions;\n readonly meta?: MetaInput;\n /**\n * Opt this route out of nifra's full-document client hydration. The server still renders the full\n * HTML document, loaders/actions still run, and native links/forms still work; the generated app\n * client, route chunks, and loader globals are omitted for hard navigations. Intended for static or\n * island-hydrated pages where interactivity is mounted by smaller, explicit client entries.\n */\n readonly hydrate?: boolean;\n /**\n * `false` renders this route's component in the browser only. The server still matches the route,\n * runs its gates and loaders, renders the layouts around it and embeds the data - it skips the\n * component alone, putting {@link HydrateFallback} (or nothing) in the page slot. The browser\n * hydrates against that, then renders the component. For a component that cannot render on a\n * server: one that reads `window` or a browser-only API while it renders.\n *\n * The module itself is still imported on the server, for its loader and options - so an import\n * that needs a browser at load time belongs inside the component (a dynamic `import()`), not at the\n * top of the file. Cannot be combined with `hydrate = false`: nothing would ever render the page.\n */\n readonly ssr?: boolean;\n /**\n * What the server renders in the page slot of an `ssr = false` route, and what the browser hydrates\n * before the component takes over - a skeleton, a spinner. Receives the same props as the\n * component, loader `data` included. Omitted ⇒ the slot is empty until the component renders.\n */\n readonly HydrateFallback?: unknown;\n /**\n * Any value to report through `useMatches` - a breadcrumb label, a render function, a flag a layout\n * reads about the page inside it. Layouts, pages, and status pages may export one. It is read from\n * the module on the server and in the browser, so it must be the same value on both.\n */\n readonly handle?: unknown;\n /**\n * On a root status page (`_404.tsx`, `_<status>.tsx`) or an `_error.tsx`. By default (`true`) the\n * page renders inside the layouts above it with their loader data and `meta`, as a nested `_404`\n * renders. When those layouts cannot render it - a loader throws, a gate or the middleware refuses -\n * a root status page renders alone and an `_error` inside its layouts without their data, with the\n * same status. `false` always renders them that way, and runs no layout loader for them.\n */\n readonly inLayouts?: boolean;\n /**\n * Opt a **static** route (no `:param`/`*`) into build-time prerendering (SSG): `prerenderRoutes`\n * (from `@nifrajs/web/build`) renders it to a static `index.html` at build. The loader runs at build\n * with the in-process `api` (build-safe data only - no per-request cookies/secrets); `defer()` on a\n * prerendered route resolves at build. For **dynamic** routes use {@link getStaticPaths} instead.\n */\n readonly prerender?: boolean;\n /**\n * Enumerate the concrete params to prerender for a **dynamic** (`:param`) route - the SSG path list\n * (blogs/docs/etc.). Runs at build; `prerenderRoutes` renders one `index.html` per returned path.\n */\n readonly getStaticPaths?: GetStaticPaths;\n /**\n * ISR freshness for this route, in **seconds**. `createWebApp` emits it as an\n * `x-nifra-isr-revalidate` response header that `withISR` reads to set the page's cache TTL\n * (overriding the wrapper's default). Older-than-`revalidate` cached pages are served stale while\n * regenerating. (Distinct from the action-revalidation `x-nifra-revalidate` header - a CSV path\n * list the client parses to refetch - so the two channels never alias.)\n */\n readonly revalidate?: number;\n /**\n * Bounded tags ISR on-demand invalidation (`?tag=...`) and a CDN purge reach this page by. A list, or\n * a function of the route's params and URL (`({ params }) => [\\`product:${params.id}\\`]`) for tags\n * per page. Tags travel to the CDN and reach anyone reading the origin: never put personal data in one.\n */\n readonly revalidateTags?: RevalidateTags;\n /**\n * No-framework island bundles (`@nifrajs/web/islands`) to load on this route, as `<script\n * type=\"module\">` in the document tail. Loaded **regardless of `hydrate`** - pair with\n * `export const hydrate = false` for a static page that ships zero framework JS and mounts\n * interactivity through `<Island>` markers + `mountIslands` enhancers instead.\n */\n readonly islandScripts?: readonly string[];\n}",
14293
14366
  "doc": "/** A route module - the default component + optional loader / action / meta. */"
14294
14367
  },
14368
+ {
14369
+ "name": "RouteParamsOf",
14370
+ "kind": "type",
14371
+ "package": "@nifrajs/web",
14372
+ "signature": "export type RouteParamsOf<K extends RouteTablePattern> = RouteTable[K] extends {\n readonly params: infer Params;\n} ? Params : never;",
14373
+ "doc": "/** The params of route `K`, as its pattern declares them (an empty object type when it has none). */"
14374
+ },
14295
14375
  {
14296
14376
  "name": "RoutePaths",
14297
14377
  "kind": "type",
@@ -14344,6 +14424,20 @@
14344
14424
  "signature": "export interface RouteSchema {\n /** Explicit external-protocol mode. The handler owns raw `c.req` parsing/streaming; no JSON body\n * parser or schema-driven 422 path is installed. A finite transport cap still applies by default. */\n readonly wire?: \"raw\";\n /**\n * Choose trust-boundary order for sensitive routes. Public routes validate first by default;\n * routes with `authenticate()` default to auth first. `validate-before-auth` is an explicit\n * compatibility escape hatch, while `auth-before-validation` can reject without parsing the body.\n */\n readonly validationOrder?: \"validate-before-auth\" | \"auth-before-validation\";\n /** Transport body cap for this route. Defaults to the server's maxBodyBytes. Use a finite\n * smaller/larger limit for a specific endpoint. The 'unlimited' value is an explicit\n * streaming/upload exemption and requires a non-empty bodyLimitReason for auditability.\n *\n * 'unlimited' is legal only for schema-less streaming/upload routes. It is rejected with `body` or\n * `idempotency`, because those lanes buffer the body before user code can apply a protocol-specific\n * bound. Read an unlimited route from `c.req.body` as a stream and bound it by the protocol it speaks;\n * `nifra.body-bounded` is deliberately NOT published for an unlimited route. */\n readonly bodyLimit?: number | \"unlimited\";\n /** Required explanation when bodyLimit is 'unlimited' (for example, a streaming upload is\n * bounded by an upstream object-store protocol). */\n readonly bodyLimitReason?: string;\n /** Declared effect tokens. Reflected for assurance; never read by validation or serialization. */\n readonly capabilities?: readonly string[];\n /**\n * Dedupe retries of this (mutating) route on an `Idempotency-Key` header. The first request runs and\n * its response is stored; a retry with the same key replays that response without re-running the\n * handler, and a key reused with a different body is rejected (409). A missing key on an\n * idempotency-required route fails closed (400). Off the hot path - routes without it are unchanged.\n */\n readonly idempotency?: IdempotencyConfig;\n /**\n * Highest data-sensitivity this route's response body carries (`public` | `pii` | `secret`). A\n * declarative, compile-time + introspection fact - never validated at runtime. Reflected for tooling,\n * recorded in the capability lockfile (so a route that starts returning PII is a reviewable change),\n * and read by downstream policy (e.g. a partner-API surface refusing to expose `pii`/`secret`).\n */\n readonly classification?: DataClassification;\n /**\n * Inline **route-assurance evidence**: the enforcement posture this route carries, declared adjacent to\n * the handler (e.g. `[NIFRA_ASSURANCE.AUTHENTICATED]`). Each id becomes route-scoped `declared` evidence\n * in reflection, so a `nifra.assurance.ts` policy `require:` clause is satisfiable WITHOUT rewriting an\n * in-handler guard into a `withRouteAssurance`-marked middleware. Ids are lowercase dot/dash segments\n * (invalid ids throw at registration). Reflected for the assurance gate; never read on the hot path.\n *\n * This is an author ASSERTION (recorded as `source: \"declared\"`), not runtime proof - like every\n * assurance marker it is trusted by the static gate, which matches on the evidence id, not its source.\n * Declare an id only on a route whose guard actually enforces it; a false declaration silently satisfies\n * the policy. (`source` is retained in reflection, so a stricter policy or reviewer can still tell\n * declared evidence from enforcement-module evidence.)\n */\n readonly assurance?: readonly string[];\n /**\n * Mark this route a **dynamic route family**: a template (`/api/:slug/:resource`) whose concrete\n * resources are resolved at runtime (auto-CRUD over tenant-defined tables, a catch-all dispatcher).\n * Purely declarative - it does not change dispatch. It surfaces in reflection so the assurance gate and\n * tooling treat the one templated route as a deliberate family whose evidence covers every runtime-\n * resolved resource, instead of reading it as a single forgotten route.\n */\n readonly family?: boolean;\n /** Optional **path-params schema**. Path params arrive as strings (`/users/:id` -> `c.params.id`);\n * declaring a schema validates them at the boundary (a malformed `:id` is a `422` before the handler,\n * like `body`/`query`) and can coerce them (use `t.query({ id: t.integer() })` for a numeric param).\n * The schema must cover every path param; with the strict default an undeclared path param is rejected.\n * When omitted, `c.params` stays the path-inferred `Record<name, string>`. */\n readonly params?: StandardSchemaV1;\n /** Optional request-header schema; the validated output is `c.headers` and a failure is a `422`.\n * Every client sends headers a route never declares (`host`, `user-agent`, `accept`), so a closed\n * object schema (`t.object`) validates only the names it declares, each read case-insensitively and\n * keyed as declared. `t.headers` is the open form: it receives every header, names lower-cased,\n * and coerces values like `t.query`. A schema that does not expose its JSON Schema (a zod\n * `.strict()` or valibot `strictObject`) receives every header, so declare it open. */\n readonly headers?: StandardSchemaV1;\n /** Optional request-cookie schema. It validates the cookies parsed from the `Cookie` header -\n * names as sent, values URL-decoded strings, the first of a repeated name - before the handler\n * runs, and the validated output is `c.cookies`. A failure is a `422`, like `headers`. A browser\n * sends every cookie the site has set, so declare the ones the route reads with an open schema\n * (`t.cookies`, `t.looseObject`) rather than rejecting the rest. */\n readonly cookies?: StandardSchemaV1;\n readonly body?: StandardSchemaV1;\n readonly query?: StandardSchemaV1;\n /** Optional **response contract**. When declared: the handler's return is type-checked against it\n * (the implementation can't drift from the contract), the typed client sees THIS as the response type\n * (the contract - not the handler's incidental return), and it's emitted into OpenAPI/JSON-Schema so\n * tooling and coding agents can read the exact shape. It is **not** validated at runtime (zero\n * hot-path cost) - purely a compile-time + introspection contract. */\n readonly response?: StandardSchemaV1;\n /**\n * Optional **error-response contract**: a map of HTTP status code → the Standard Schema of that error's\n * body. Declares a route's failure modes so they flow into OpenAPI (as non-2xx `responses`), the\n * `/llms.txt` context, and other introspection - the whole contract, not just the happy path, is legible\n * to tooling and coding agents. Like `response`, it is **not** validated at runtime (zero hot-path cost);\n * it's a compile-time + introspection contract. Example: `{ 404: NotFound, 409: Conflict }`. */\n readonly errors?: Readonly<Record<number, StandardSchemaV1>>;\n /**\n * Optional **SSE event contract**: the Standard Schema of each event's `data` payload on a\n * streaming route (declared via `app.sse()`). Marks the route as a typed event stream - the\n * typed client grows a `.subscribe()` for it, and the schema flows into reflection. Like\n * `response`, it is **not** validated at runtime (zero hot-path cost); the server-side\n * `stream.send()` is compile-time-checked against it instead.\n */\n readonly sse?: StandardSchemaV1;\n /**\n * Hook fired when the request fails `headers`/`cookies`/`params`/`body`/`query` validation, before the handler\n * runs. `kind` says which input failed. Its return value selects one of three outcomes (may be async):\n * - a **`Response`** → returned as-is, short-circuiting the route (custom error envelope, redirect, …).\n * - **any other value** → treated as a repaired payload and **re-validated once** against the same\n * schema. If it now passes, the handler runs with it; if it still fails, the original `422` stands.\n * Re-validation means a bad return can't bypass the schema - the trust boundary holds.\n * - **`undefined`** → give up; the original validation `422` is returned unchanged.\n * A route hook **overrides** the app-wide default set via `server({ onValidationError })`; return\n * `undefined` to fall through to the plain `422` even when an app default exists. Typical uses: a custom\n * error envelope, coercing the input, or prompting an LLM to repair the payload (re-validated, so it can't\n * bypass the schema).\n */\n readonly onValidationError?: (issues: ReadonlyArray<StandardIssue>, ctx: Context, kind: \"body\" | \"query\" | \"params\" | \"headers\" | \"cookies\") => Response | unknown | Promise<Response | unknown>;\n}",
14345
14425
  "doc": "/** Per-route input schemas. Each is any Standard Schema (zod/valibot/arktype/…). */"
14346
14426
  },
14427
+ {
14428
+ "name": "RouteSearchInOf",
14429
+ "kind": "type",
14430
+ "package": "@nifrajs/web",
14431
+ "signature": "export type RouteSearchInOf<K extends RouteTablePattern> = RouteTable[K] extends {\n readonly searchIn: infer Input;\n} ? Input : RouteSearchOf<K>;",
14432
+ "doc": "/**\n * The search a link to route `K` may carry: the entry's `searchIn` (the schema's input, so a defaulted\n * field is optional), else its `search`. A hand-written entry with only `search` keeps working.\n */"
14433
+ },
14434
+ {
14435
+ "name": "RouteSearchOf",
14436
+ "kind": "type",
14437
+ "package": "@nifrajs/web",
14438
+ "signature": "export type RouteSearchOf<K extends RouteTablePattern> = RouteTable[K] extends {\n readonly search: infer Search;\n} ? Search : never;",
14439
+ "doc": "/** The search of route `K`, as its `searchSchema` outputs it. */"
14440
+ },
14347
14441
  {
14348
14442
  "name": "RouteSlot",
14349
14443
  "kind": "function",
@@ -14487,7 +14581,14 @@
14487
14581
  "kind": "interface",
14488
14582
  "package": "@nifrajs/web",
14489
14583
  "signature": "export interface RouteTable {\n}",
14490
- "doc": "/**\n * Every route the app serves, keyed by URL pattern. An entry is `{ params, search }`: `params` is the\n * object a link to the route needs (`Record<string, never>` when the pattern has none), `search` the\n * output of the route's `searchSchema` (the raw query when it declares none). Empty here; `nifra types`\n * writes `.nifra/types/routes.d.ts`, which fills it from the route files:\n *\n * ```ts\n * declare module \"@nifrajs/web\" {\n * interface RouteTable {\n * \"/users/:id\": { readonly params: { readonly id: string }; readonly search: { tab: string } }\n * }\n * }\n * ```\n *\n * There is one key per pattern, so an optional segment (`[[lang]]`) is two keys with exact params each.\n * With an empty table every `to` is accepted and `search` is loose.\n */"
14584
+ "doc": "/**\n * Every route the app serves, keyed by URL pattern. An entry is `{ params, search }`: `params` is the\n * object a link to the route needs (an empty object type when the pattern has none), `search` the\n * output of the route's `searchSchema` (the raw query when it declares none). Empty here; `nifra types`\n * writes `.nifra/types/routes.d.ts`, which fills it from the route files:\n *\n * ```ts\n * declare module \"@nifrajs/web\" {\n * interface RouteTable {\n * \"/users/:id\": { readonly params: { readonly id: string }; readonly search: { tab: string } }\n * }\n * }\n * ```\n *\n * There is one key per pattern, so an optional segment (`[[lang]]`) is two keys with exact params each.\n * With an empty table every `to` is accepted and `search` is loose.\n */"
14585
+ },
14586
+ {
14587
+ "name": "RouteTablePattern",
14588
+ "kind": "type",
14589
+ "package": "@nifrajs/web",
14590
+ "signature": "export type RouteTablePattern = keyof RouteTable & string;",
14591
+ "doc": "/** A {@link RouteTable} key: the pattern of one route. `never` until `nifra types` fills the table. */"
14491
14592
  },
14492
14593
  {
14493
14594
  "name": "RouteTypesOptions",
@@ -15059,6 +15160,13 @@
15059
15160
  "signature": "export declare const SINGLE_COPY_STRICT_ENV = \"NIFRA_SINGLE_COPY_STRICT\";",
15060
15161
  "doc": "/** Environment switch for strict mode when the declaration does not set it: `1` or `true`. */"
15061
15162
  },
15163
+ {
15164
+ "name": "SOLID_ERROR_CODES",
15165
+ "kind": "const",
15166
+ "package": "@nifrajs/web",
15167
+ "signature": "export declare const SOLID_ERROR_CODES: readonly string[];",
15168
+ "doc": "/** The codes Solid 2.0 raises at error severity (the rest are warnings), from its diagnostics.json. */"
15169
+ },
15062
15170
  {
15063
15171
  "name": "SQLiteClient",
15064
15172
  "kind": "interface",
@@ -15107,13 +15215,13 @@
15107
15215
  "name": "SSEInit",
15108
15216
  "kind": "interface",
15109
15217
  "package": "@nifrajs/core",
15110
- "signature": "export interface SSEInit {\n readonly status?: number;\n readonly headers?: ConstructorParameters<typeof Headers>[0];\n /** Send a `: ` comment ping every N ms so idle proxies don't drop the connection. */\n readonly keepAlive?: number;\n /**\n * Bytes of sent events one client may leave unread, default 1 MiB. Past it the client is dropped:\n * `signal` aborts, the queued frames are released, and later sends are no-ops, so a reader that\n * stalls cannot hold server memory without limit. Raise it for a burst larger than this sent before\n * the client can read. A single frame over the cap is also refused; `Infinity` turns the limit off.\n */\n readonly maxBufferedBytes?: number;\n}"
15218
+ "signature": "export interface SSEInit {\n readonly status?: number;\n readonly headers?: ConstructorParameters<typeof Headers>[0];\n /**\n * Send a `: ` comment ping every N ms. There is no default: without it a quiet stream sends no\n * bytes. That keeps a proxy from dropping the connection, and it keeps a Bun server from closing\n * it: Bun cuts a connection that moves no bytes for the idle timeout (`idleTimeoutSec` of\n * `listen()`, `idleTimeout` of `Bun.serve`; 10 seconds by default), so on Bun use an interval\n * well under the timeout you run with. Under `listen()`, `withIdleTimeout` from\n * `@nifrajs/core/idle-timeout` holds one stream's connection open instead. `app.fetch` has no\n * listener, so a test through it never sees the cut.\n */\n readonly keepAlive?: number;\n /**\n * Bytes of sent events one client may leave unread, default 1 MiB. Past it the client is dropped:\n * `signal` aborts, the queued frames are released, and later sends are no-ops, so a reader that\n * stalls cannot hold server memory without limit. Raise it for a burst larger than this sent before\n * the client can read. A single frame over the cap is also refused; `Infinity` turns the limit off.\n */\n readonly maxBufferedBytes?: number;\n}"
15111
15219
  },
15112
15220
  {
15113
15221
  "name": "SSEInit",
15114
15222
  "kind": "interface",
15115
15223
  "package": "nifra",
15116
- "signature": "export interface SSEInit {\n readonly status?: number;\n readonly headers?: ConstructorParameters<typeof Headers>[0];\n /** Send a `: ` comment ping every N ms so idle proxies don't drop the connection. */\n readonly keepAlive?: number;\n /**\n * Bytes of sent events one client may leave unread, default 1 MiB. Past it the client is dropped:\n * `signal` aborts, the queued frames are released, and later sends are no-ops, so a reader that\n * stalls cannot hold server memory without limit. Raise it for a burst larger than this sent before\n * the client can read. A single frame over the cap is also refused; `Infinity` turns the limit off.\n */\n readonly maxBufferedBytes?: number;\n}"
15224
+ "signature": "export interface SSEInit {\n readonly status?: number;\n readonly headers?: ConstructorParameters<typeof Headers>[0];\n /**\n * Send a `: ` comment ping every N ms. There is no default: without it a quiet stream sends no\n * bytes. That keeps a proxy from dropping the connection, and it keeps a Bun server from closing\n * it: Bun cuts a connection that moves no bytes for the idle timeout (`idleTimeoutSec` of\n * `listen()`, `idleTimeout` of `Bun.serve`; 10 seconds by default), so on Bun use an interval\n * well under the timeout you run with. Under `listen()`, `withIdleTimeout` from\n * `@nifrajs/core/idle-timeout` holds one stream's connection open instead. `app.fetch` has no\n * listener, so a test through it never sees the cut.\n */\n readonly keepAlive?: number;\n /**\n * Bytes of sent events one client may leave unread, default 1 MiB. Past it the client is dropped:\n * `signal` aborts, the queued frames are released, and later sends are no-ops, so a reader that\n * stalls cannot hold server memory without limit. Raise it for a burst larger than this sent before\n * the client can read. A single frame over the cap is also refused; `Infinity` turns the limit off.\n */\n readonly maxBufferedBytes?: number;\n}"
15117
15225
  },
15118
15226
  {
15119
15227
  "name": "SSEMessage",
@@ -15436,6 +15544,13 @@
15436
15544
  "package": "@nifrajs/web-solid",
15437
15545
  "signature": "export declare const SearchContext: Context<Accessor<Record<string, unknown>> | null>;"
15438
15546
  },
15547
+ {
15548
+ "name": "SearchInputOf",
15549
+ "kind": "type",
15550
+ "package": "@nifrajs/web",
15551
+ "signature": "export type SearchInputOf<Module> = Module extends {\n searchSchema: infer S;\n} ? S extends StandardSchemaV1 ? InferInput<S> extends Record<string, unknown> ? InferInput<S> : SearchOf<Module> : Record<string, unknown> : Record<string, unknown>;",
15552
+ "doc": "/**\n * The search INPUT type for a route MODULE - what a link may carry, so a field its `searchSchema` defaults\n * is optional. The schema's input when it is an object, else the {@link SearchOf} output. The route table\n * holds it as `searchIn`, and `href()` reads it, where the hooks and `ctx.search` read the output.\n */"
15553
+ },
15439
15554
  {
15440
15555
  "name": "SearchOf",
15441
15556
  "kind": "type",
@@ -15443,6 +15558,13 @@
15443
15558
  "signature": "export type SearchOf<Module> = Module extends {\n searchSchema: infer S;\n} ? S extends StandardSchemaV1 ? InferOutput<S> extends Record<string, unknown> ? InferOutput<S> : never : Record<string, unknown> : Record<string, unknown>;",
15444
15559
  "doc": "/**\n * The search OUTPUT type for a route MODULE - its `searchSchema`'s validated output, or the raw parsed\n * query (`Record<string, unknown>`) when it declares none. The building block for typed cross-route\n * navigation: `nifra types` maps each route pattern to\n * `SearchOf<typeof import(\"./routes/<file>\")>` in `.nifra/types/routes.d.ts`, populating the augmentable\n * `RouteTable` interface.\n */"
15445
15560
  },
15561
+ {
15562
+ "name": "SearchOfFrom",
15563
+ "kind": "type",
15564
+ "package": "@nifrajs/web",
15565
+ "signature": "export type SearchOfFrom<K extends string> = K extends RouteTablePattern ? RouteSearchOf<K> : Record<string, unknown>;",
15566
+ "doc": "/** The search `useSearch(from)` gives: the route's, or the loose record for a pattern outside the table. */"
15567
+ },
15446
15568
  {
15447
15569
  "name": "SearchParamsInit",
15448
15570
  "kind": "type",
@@ -15635,14 +15757,14 @@
15635
15757
  "name": "Server",
15636
15758
  "kind": "class",
15637
15759
  "package": "@nifrajs/core",
15638
- "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 /** Configured topic adapter, or the in-process default created by the first `app.ws()` route. */\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 adapter 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 custom topic adapter,\n * a validated-send route, or when a mounted app takes upgrades. */\n private nativePublish;\n private readonly maxBodyBytes;\n private readonly protoPoisoning;\n private 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 stopRun;\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 /** The response hook whose `renderBody` fast path the owner carries: still first in line, or the\n * fast path would run ahead of a hook registered before it. */\n private renderBodyAnchor;\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 * Uses the configured {@link ServerOptions.topicAdapter}, or the in-process topic registry by\n * default. Await the result when a custom adapter publishes asynchronously.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void | Promise<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 route's params → 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 routes with path params and/or a query schema: validate + handler + respond\n * in one closure, with no lifecycle promise when the validators and handler are sync. */\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 ordinary\n * validation stages and derive/before/after/error hooks, while excluding auth-first ordering, custom\n * validation recovery, outer wrappers and response contracts. The shared input sequence preserves\n * the program's validation order around body parsing; the hook chain preserves thrown-value, `c.set`\n * and response-rendering semantics. The route's closure holds its `FusedHooks` and schemas, so a\n * 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(options?: StopOptions): Promise<void>;\n private stopListener;\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}",
15760
+ "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 /** Configured topic adapter, or the in-process default created by the first `app.ws()` route. */\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 adapter 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 custom topic adapter,\n * a validated-send route, or when a mounted app takes upgrades. */\n private nativePublish;\n private readonly maxBodyBytes;\n private readonly protoPoisoning;\n private 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 stopRun;\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 /** The response hook whose `renderBody` fast path the owner carries: still first in line, or the\n * fast path would run ahead of a hook registered before it. */\n private renderBodyAnchor;\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: 5_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 * Uses the configured {@link ServerOptions.topicAdapter}, or the in-process topic registry by\n * default. Await the result when a custom adapter publishes asynchronously.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void | Promise<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 route's params → 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 routes with path params and/or a query schema: validate + handler + respond\n * in one closure, with no lifecycle promise when the validators and handler are sync. */\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 ordinary\n * validation stages and derive/before/after/error hooks, while excluding auth-first ordering, custom\n * validation recovery, outer wrappers and response contracts. The shared input sequence preserves\n * the program's validation order around body parsing; the hook chain preserves thrown-value, `c.set`\n * and response-rendering semantics. The route's closure holds its `FusedHooks` and schemas, so a\n * 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(options?: StopOptions): Promise<void>;\n private stopListener;\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}",
15639
15761
  "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 */"
15640
15762
  },
15641
15763
  {
15642
15764
  "name": "Server",
15643
15765
  "kind": "class",
15644
15766
  "package": "nifra",
15645
- "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 /** Configured topic adapter, or the in-process default created by the first `app.ws()` route. */\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 adapter 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 custom topic adapter,\n * a validated-send route, or when a mounted app takes upgrades. */\n private nativePublish;\n private readonly maxBodyBytes;\n private readonly protoPoisoning;\n private 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 stopRun;\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 /** The response hook whose `renderBody` fast path the owner carries: still first in line, or the\n * fast path would run ahead of a hook registered before it. */\n private renderBodyAnchor;\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 * Uses the configured {@link ServerOptions.topicAdapter}, or the in-process topic registry by\n * default. Await the result when a custom adapter publishes asynchronously.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void | Promise<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 route's params → 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 routes with path params and/or a query schema: validate + handler + respond\n * in one closure, with no lifecycle promise when the validators and handler are sync. */\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 ordinary\n * validation stages and derive/before/after/error hooks, while excluding auth-first ordering, custom\n * validation recovery, outer wrappers and response contracts. The shared input sequence preserves\n * the program's validation order around body parsing; the hook chain preserves thrown-value, `c.set`\n * and response-rendering semantics. The route's closure holds its `FusedHooks` and schemas, so a\n * 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(options?: StopOptions): Promise<void>;\n private stopListener;\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}",
15767
+ "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 /** Configured topic adapter, or the in-process default created by the first `app.ws()` route. */\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 adapter 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 custom topic adapter,\n * a validated-send route, or when a mounted app takes upgrades. */\n private nativePublish;\n private readonly maxBodyBytes;\n private readonly protoPoisoning;\n private 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 stopRun;\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 /** The response hook whose `renderBody` fast path the owner carries: still first in line, or the\n * fast path would run ahead of a hook registered before it. */\n private renderBodyAnchor;\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: 5_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 * Uses the configured {@link ServerOptions.topicAdapter}, or the in-process topic registry by\n * default. Await the result when a custom adapter publishes asynchronously.\n */\n publish(topic: string, data: string | ArrayBufferView | ArrayBuffer): void | Promise<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 route's params → 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 routes with path params and/or a query schema: validate + handler + respond\n * in one closure, with no lifecycle promise when the validators and handler are sync. */\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 ordinary\n * validation stages and derive/before/after/error hooks, while excluding auth-first ordering, custom\n * validation recovery, outer wrappers and response contracts. The shared input sequence preserves\n * the program's validation order around body parsing; the hook chain preserves thrown-value, `c.set`\n * and response-rendering semantics. The route's closure holds its `FusedHooks` and schemas, so a\n * 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(options?: StopOptions): Promise<void>;\n private stopListener;\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}",
15646
15768
  "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 */"
15647
15769
  },
15648
15770
  {
@@ -15805,8 +15927,8 @@
15805
15927
  "name": "ServerFn",
15806
15928
  "kind": "interface",
15807
15929
  "package": "@nifrajs/web",
15808
- "signature": "export interface ServerFn<Input, Output> {\n (input: Input, context: Context): MaybePromise<Output>;\n readonly [SERVER_FN]: ServerFnConfig<Input>;\n}",
15809
- "doc": "/**\n * A declared server function. Callable directly on the server (the same value your own server-side\n * code can await); in a client build, this module becomes typed stubs that POST under its\n * file's name (`todos.fn.ts` posts under `todos`), so {@link serverFunctions} must mount it\n * under that name.\n *\n * This is the SERVER declaration type, so context is required. Client builds replace the module with\n * a one-argument {@link ClientServerFn}; UI bindings accept either shape and adapt at that boundary.\n * Keeping the types separate prevents a direct server call from type-checking while handing the\n * declaration `undefined` for a context its implementation requires.\n */"
15930
+ "signature": "export interface ServerFn<Input, Output, Direct = Output> {\n (input: Input, context: Context): MaybePromise<Direct>;\n readonly [SERVER_FN]: ServerFnConfig<Input>;\n /** Type-only: the browser's view of the result. Never present at run time. */\n readonly \"~nifraOutput\"?: Output;\n}",
15931
+ "doc": "/**\n * A declared server function. Callable directly on the server (the same value your own server-side\n * code can await); in a client build, this module becomes typed stubs that POST under its\n * file's name (`todos.fn.ts` posts under `todos`), so {@link serverFunctions} must mount it\n * under that name.\n *\n * This is the SERVER declaration type, so context is required. Client builds replace the module with\n * a one-argument {@link ClientServerFn}; UI bindings accept either shape and adapt at that boundary.\n * Keeping the types separate prevents a direct server call from type-checking while handing the\n * declaration `undefined` for a context its implementation requires.\n *\n * `Output` is what the browser receives, after the `output` schema ran over the return. `Direct` is\n * what a direct server call returns: the function's own return, which the schema has not touched.\n */"
15810
15932
  },
15811
15933
  {
15812
15934
  "name": "ServerFnConfig",
@@ -15868,7 +15990,7 @@
15868
15990
  "name": "ServerFnReference",
15869
15991
  "kind": "type",
15870
15992
  "package": "@nifrajs/web",
15871
- "signature": "export type ServerFnReference<Input, Output> = ServerFn<Input, Output> | ClientServerFn<Input, Output>;",
15993
+ "signature": "export type ServerFnReference<Input, Output> = ServerFn<Input, Output, unknown> | ClientServerFn<Input, Output>;",
15872
15994
  "doc": "/** A UI binding boundary: source declarations and generated client stubs are both accepted. */"
15873
15995
  },
15874
15996
  {
@@ -15909,13 +16031,13 @@
15909
16031
  "name": "ServerOptions",
15910
16032
  "kind": "interface",
15911
16033
  "package": "@nifrajs/core",
15912
- "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 route: exact origins, or a function that receives the\n * `Origin`. A urlencoded, multipart or `text/plain` body is one a form on any site can send with the\n * visitor's cookies and no preflight, so one whose `Origin` names another site is refused with `403`\n * before it is read. A route without a body schema refuses the same sites' unsafe requests that carry\n * no content type too, which `fetch` with `no-cors` sends; one with a script-set `Authorization` header\n * passes, since a browser preflights it, but `Basic`, `Digest`, `Negotiate` and `NTLM` do not, because\n * a browser re-sends those from its auth cache without one. Same-origin posts and requests without an `Origin`, such as\n * server-to-server calls, pass. JSON is not affected: a browser preflights it, so CORS decides.\n * The origins a `cors()` list or predicate and a `csrf({ origins })` list name are trusted as well,\n * so a frontend those already allow needs no second list here; `cors()` with `\"*\"` adds none. That\n * trust is for form posts to this server's own routes only: a mounted or grouped server keeps its own\n * policy, so a parent that must accept the same sites sets them in its own `formOrigins`, and a web\n * page action checks the origin against the backend's `allowedOrigins`, not this list.\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 /**\n * Topic membership and broadcast implementation for WebSocket routes. By default, Nifra uses an\n * in-process `TopicRegistry`; pass an adapter to bridge subscriptions and publishes to a shared\n * fan-out service. `app.publish()` returns a promise when the adapter publishes asynchronously.\n */\n readonly topicAdapter?: TopicAdapter;\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}"
16034
+ "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 route: exact origins, or a function that receives the\n * `Origin`. A urlencoded, multipart or `text/plain` body is one a form on any site can send with the\n * visitor's cookies and no preflight, so one whose `Origin` names another site is refused with `403`\n * before it is read. A route without a body schema refuses the same sites' unsafe requests that carry\n * no content type too, which `fetch` with `no-cors` sends; one with a script-set `Authorization` header\n * passes, since a browser preflights it, but `Basic`, `Digest`, `Negotiate` and `NTLM` do not, because\n * a browser re-sends those from its auth cache without one. Same-origin posts and requests without an `Origin`, such as\n * server-to-server calls, pass. JSON is not affected: a browser preflights it, so CORS decides.\n * The origins a `cors()` list or predicate and a `csrf({ origins })` list name are trusted as well,\n * so a frontend those already allow needs no second list here; `cors()` with `\"*\"` adds none. That\n * trust is for form posts to this server's own routes only: a mounted or grouped server keeps its own\n * policy, so a parent that must accept the same sites sets them in its own `formOrigins`, and a web\n * page action checks the origin against the backend's `allowedOrigins`, not this list.\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 /**\n * Topic membership and broadcast implementation for WebSocket routes. By default, Nifra uses an\n * in-process `TopicRegistry`; pass an adapter to bridge subscriptions and publishes to a shared\n * fan-out service. `app.publish()` returns a promise when the adapter publishes asynchronously.\n */\n readonly topicAdapter?: TopicAdapter;\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 with a non-production `process.env`) - `name`, `detail` and `stack`.\n * - `\"message\"` - `name` and `detail`, no stack.\n * - `\"none\"` (default in production or when env access is unavailable) - request metadata and a generic error name.\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. To opt back into detail with redaction, set `errorLogDetail: \"full\"` and pass\n * `logger: jsonLogger({ valuePatterns: commonSecretPatterns })` to scrub tokens, JWTs, and emails\n * out of `detail` and `stack` while keeping the diagnosis.\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}"
15913
16035
  },
15914
16036
  {
15915
16037
  "name": "ServerOptions",
15916
16038
  "kind": "interface",
15917
16039
  "package": "nifra",
15918
- "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 route: exact origins, or a function that receives the\n * `Origin`. A urlencoded, multipart or `text/plain` body is one a form on any site can send with the\n * visitor's cookies and no preflight, so one whose `Origin` names another site is refused with `403`\n * before it is read. A route without a body schema refuses the same sites' unsafe requests that carry\n * no content type too, which `fetch` with `no-cors` sends; one with a script-set `Authorization` header\n * passes, since a browser preflights it, but `Basic`, `Digest`, `Negotiate` and `NTLM` do not, because\n * a browser re-sends those from its auth cache without one. Same-origin posts and requests without an `Origin`, such as\n * server-to-server calls, pass. JSON is not affected: a browser preflights it, so CORS decides.\n * The origins a `cors()` list or predicate and a `csrf({ origins })` list name are trusted as well,\n * so a frontend those already allow needs no second list here; `cors()` with `\"*\"` adds none. That\n * trust is for form posts to this server's own routes only: a mounted or grouped server keeps its own\n * policy, so a parent that must accept the same sites sets them in its own `formOrigins`, and a web\n * page action checks the origin against the backend's `allowedOrigins`, not this list.\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 /**\n * Topic membership and broadcast implementation for WebSocket routes. By default, Nifra uses an\n * in-process `TopicRegistry`; pass an adapter to bridge subscriptions and publishes to a shared\n * fan-out service. `app.publish()` returns a promise when the adapter publishes asynchronously.\n */\n readonly topicAdapter?: TopicAdapter;\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}"
16040
+ "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 route: exact origins, or a function that receives the\n * `Origin`. A urlencoded, multipart or `text/plain` body is one a form on any site can send with the\n * visitor's cookies and no preflight, so one whose `Origin` names another site is refused with `403`\n * before it is read. A route without a body schema refuses the same sites' unsafe requests that carry\n * no content type too, which `fetch` with `no-cors` sends; one with a script-set `Authorization` header\n * passes, since a browser preflights it, but `Basic`, `Digest`, `Negotiate` and `NTLM` do not, because\n * a browser re-sends those from its auth cache without one. Same-origin posts and requests without an `Origin`, such as\n * server-to-server calls, pass. JSON is not affected: a browser preflights it, so CORS decides.\n * The origins a `cors()` list or predicate and a `csrf({ origins })` list name are trusted as well,\n * so a frontend those already allow needs no second list here; `cors()` with `\"*\"` adds none. That\n * trust is for form posts to this server's own routes only: a mounted or grouped server keeps its own\n * policy, so a parent that must accept the same sites sets them in its own `formOrigins`, and a web\n * page action checks the origin against the backend's `allowedOrigins`, not this list.\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 /**\n * Topic membership and broadcast implementation for WebSocket routes. By default, Nifra uses an\n * in-process `TopicRegistry`; pass an adapter to bridge subscriptions and publishes to a shared\n * fan-out service. `app.publish()` returns a promise when the adapter publishes asynchronously.\n */\n readonly topicAdapter?: TopicAdapter;\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 with a non-production `process.env`) - `name`, `detail` and `stack`.\n * - `\"message\"` - `name` and `detail`, no stack.\n * - `\"none\"` (default in production or when env access is unavailable) - request metadata and a generic error name.\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. To opt back into detail with redaction, set `errorLogDetail: \"full\"` and pass\n * `logger: jsonLogger({ valuePatterns: commonSecretPatterns })` to scrub tokens, JWTs, and emails\n * out of `detail` and `stack` while keeping the diagnosis.\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}"
15919
16041
  },
15920
16042
  {
15921
16043
  "name": "ServerPrerenderedPage",
@@ -16020,7 +16142,7 @@
16020
16142
  "name": "SessionOptions",
16021
16143
  "kind": "interface",
16022
16144
  "package": "@nifrajs/auth",
16023
- "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}"
16145
+ "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. In store mode, changes to these keys also rotate an existing\n * session ID. Without configured keys, every data change updates the tag and ID rotation is\n * explicit via `regenerate()`. Leaving out a key that decides what a page shows lets the next\n * visitor of a browser see the pages kept for the previous one.\n */\n readonly identity?: readonly (keyof Data & string)[];\n}"
16024
16146
  },
16025
16147
  {
16026
16148
  "name": "SessionRecord",
@@ -16284,7 +16406,7 @@
16284
16406
  "name": "SizeReport",
16285
16407
  "kind": "interface",
16286
16408
  "package": "@nifrajs/web",
16287
- "signature": "export interface SizeReport {\n /** Per-chunk sizes, sorted biggest gzip first (the regression you want to see at the top). */\n readonly chunks: readonly ChunkSize[];\n /** Sum of every chunk's raw bytes. */\n readonly totalBytes: number;\n /** Sum of every chunk's gzip bytes. */\n readonly totalGzip: number;\n}",
16409
+ "signature": "export interface SizeReport {\n /** Per-chunk sizes, sorted biggest gzip first (the regression you want to see at the top). */\n readonly chunks: readonly ChunkSize[];\n /** Sum of every chunk's raw bytes. */\n readonly totalBytes: number;\n /** Sum of every chunk's gzip bytes. */\n readonly totalGzip: number;\n readonly routes?: readonly ClientRouteSize[];\n}",
16288
16410
  "doc": "/** A whole build's size report - every chunk (largest first) + the totals. */"
16289
16411
  },
16290
16412
  {
@@ -17931,14 +18053,14 @@
17931
18053
  "name": "VERSION",
17932
18054
  "kind": "const",
17933
18055
  "package": "@nifrajs/core",
17934
- "signature": "export declare const VERSION: \"5.15.1\";",
18056
+ "signature": "export declare const VERSION: \"5.16.0\";",
17935
18057
  "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 */"
17936
18058
  },
17937
18059
  {
17938
18060
  "name": "VERSION",
17939
18061
  "kind": "const",
17940
18062
  "package": "nifra",
17941
- "signature": "export declare const VERSION: \"5.15.1\";",
18063
+ "signature": "export declare const VERSION: \"5.16.0\";",
17942
18064
  "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 */"
17943
18065
  },
17944
18066
  {
@@ -19402,7 +19524,7 @@
19402
19524
  "name": "classify",
19403
19525
  "kind": "function",
19404
19526
  "package": "@nifrajs/web",
19405
- "signature": "export declare function classify(name: string, message: string): {\n code: string;\n cause?: string;\n fix?: string;\n docsAnchor?: string;\n fixOptions?: readonly FixOption[] | undefined;\n};",
19527
+ "signature": "export declare function classify(name: string, message: string, fromNifra?: boolean): {\n code: string;\n cause?: string;\n fix?: string;\n docsAnchor?: string;\n fixOptions?: readonly FixOption[] | undefined;\n severity?: \"warning\" | undefined;\n};",
19406
19528
  "doc": "/** Classify an error name+message against the catalog; falls back to the generic unhandled code. */"
19407
19529
  },
19408
19530
  {
@@ -19424,6 +19546,13 @@
19424
19546
  "package": "@nifrajs/web",
19425
19547
  "signature": "export declare function clientIsland<Props>(contract: ClientIsland<Props>, key: ComponentKey, props: NoInfer<Props>, slots?: Readonly<Record<string, string>>): IslandInstance;"
19426
19548
  },
19549
+ {
19550
+ "name": "clientRouteAssets",
19551
+ "kind": "function",
19552
+ "package": "@nifrajs/web",
19553
+ "signature": "export declare function clientRouteAssets(manifest: BuildManifest, routes: readonly (Pick<RouteEntry, \"id\" | \"pattern\"> & {\n readonly hydrate?: boolean | \"unknown\";\n})[], imports: ReadonlyMap<string, readonly string[]>): readonly ClientRouteAssets[];",
19554
+ "doc": "/** The client entry plus the matched page and layout chunks and their eager dependencies. */"
19555
+ },
19427
19556
  {
19428
19557
  "name": "closeBoundary",
19429
19558
  "kind": "function",
@@ -19489,7 +19618,7 @@
19489
19618
  "name": "collectProjectWorkGraph",
19490
19619
  "kind": "function",
19491
19620
  "package": "@nifrajs/cli",
19492
- "signature": "export declare function collectProjectWorkGraph(cwd: string, options?: {\n readonly changedFiles?: readonly string[];\n readonly minLevel?: number;\n}): Promise<ProjectWorkGraphResult>;"
19621
+ "signature": "export declare function collectProjectWorkGraph(cwd: string, options?: WorkGraphOptions): Promise<ProjectWorkGraphResult>;"
19493
19622
  },
19494
19623
  {
19495
19624
  "name": "combine",
@@ -20041,7 +20170,7 @@
20041
20170
  "name": "createEventLoopLagSampler",
20042
20171
  "kind": "function",
20043
20172
  "package": "@nifrajs/middleware",
20044
- "signature": "export declare function createEventLoopLagSampler(resolutionMs?: number, monitor?: LoopDelayMonitor): () => number;",
20173
+ "signature": "export declare function createEventLoopLagSampler(resolutionMs?: number, monitor?: LoopDelayMonitor): EventLoopLagSampler;",
20045
20174
  "doc": "/**\n * Event-loop-lag sampler. By default it measures timer drift using only Web/JS runtime primitives, so\n * it works under Node ESM, Bun, Deno, and workers without a hidden CommonJS `require` fallback. An\n * injected histogram remains available for deterministic tests or a runtime-native monitor. A read\n * returns the mean lag of the samples taken since the previous read and starts a new window; a read\n * with no new sample since then returns the same value again, so every request that arrives between\n * two samples of a lagging loop sees the lag.\n */"
20046
20175
  },
20047
20176
  {
@@ -20287,8 +20416,7 @@
20287
20416
  "name": "createQuery",
20288
20417
  "kind": "function",
20289
20418
  "package": "@nifrajs/web-solid",
20290
- "signature": "export declare function createQuery<T>(key: unknown, fn: () => Promise<T>, options?: QueryOptions): CreateQueryResult<T>;",
20291
- "doc": "/**\n * Bind the keyed query for `key`, fetched via `fn`. Returns a reactive `state()` accessor + `refetch`.\n * Concurrent `createQuery`s with the same key share one cache entry + one in-flight fetch (dedup).\n * Fetches on mount; SSR-idle. Call inside a component (owns the subscription). `options.live` names\n * the live keys that refetch it.\n */"
20419
+ "signature": "export declare function createQuery<T, K = PlainKeyDefault>(key: PlainQueryKey<K>, fn: () => Promise<T>, options?: QueryOptions): CreateQueryResult<T>;"
20292
20420
  },
20293
20421
  {
20294
20422
  "name": "createQueryClient",
@@ -21204,7 +21332,7 @@
21204
21332
  "kind": "function",
21205
21333
  "package": "@nifrajs/core",
21206
21334
  "signature": "export declare function emitRequestErrorLog(logger: Logger, detail: ErrorLogDetail, err: unknown, ctx: {\n readonly req: {\n readonly method: string;\n readonly url: string;\n };\n} | undefined, message?: string): void;",
21207
- "doc": "/**\n * Write an unhandled request error to the log. An error's own text can quote the input that produced\n * it, so how much of it reaches the sink is the app's call (`detail`). The default keeps it: a 500\n * with no message and no stack is an incident nobody can diagnose, and the framework already ships\n * the narrower instrument for the leak - a redacting logger with `valuePatterns`. `\"none\"` is there\n * for an untrusted sink.\n */"
21335
+ "doc": "/**\n * Write an unhandled request error to the log. An error's own text can quote the input that produced\n * it. The `\"none\"` policy keeps thrown values out of the sink, including custom error names.\n */"
21208
21336
  },
21209
21337
  {
21210
21338
  "name": "enableDraft",
@@ -21598,8 +21726,8 @@
21598
21726
  "name": "formFor",
21599
21727
  "kind": "function",
21600
21728
  "package": "@nifrajs/web",
21601
- "signature": "export declare function formFor<App, Path extends RoutePaths<App>, Method extends string = \"post\">(): FormHandle<App, Path, Method>;",
21602
- "doc": "/**\n * Bind a form to a backend route's body schema at the type level. `App` is `typeof backend`; `Path` is\n * constrained to the app's real routes (a wrong path is a type error); `Method` defaults to `\"post\"`.\n */"
21729
+ "signature": "export declare function formFor<App>(): FormFor<App>;",
21730
+ "doc": "/**\n * Bind a form to a backend route at the type level. `App` is `typeof backend`; the path is one of the\n * app's real routes (a wrong path is a type error), and the method one that route declares: left out, it\n * is `\"post\"`, and a route with no POST handler needs its method named. A path with params takes them\n * after the method, `formFor<App>()(\"/users/:id\", \"post\", { id })`, and `action` is the URL they fill. The\n * handle carries the route's own `action` and `method`, and checks every field name against the route's\n * body schema.\n */"
21603
21731
  },
21604
21732
  {
21605
21733
  "name": "formatAssuranceReport",
@@ -21999,42 +22127,42 @@
21999
22127
  "kind": "function",
22000
22128
  "package": "@nifrajs/web",
22001
22129
  "signature": "export declare function href<K extends Pattern>(options: HrefOptions<K>): Href<K>;",
22002
- "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate) throws a `TypeError` naming it, in production too: a link built from it would go\n * somewhere else. The result is a pure function of its input, so the server and the browser build the\n * same string. A link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22130
+ "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate), a `hash` with an unpaired surrogate, a `search` key reserved for route-slot state, and a\n * slot target that was itself refused come from data, so they do not throw: the result is the inert\n * `Href`, which every consumer (`Link`, `Navigate`, `navigate`, and a click on a plain `<a>`) ignores,\n * and a `console.error` (once per distinct message, within a bounded memory; see {@link onHrefRefused}\n * to take over) names the route and the param, never the value. A link built from such a value would go somewhere else, so no link is built.\n * The result is a pure function of its input, so the server and the browser build the same string. A\n * link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22003
22131
  },
22004
22132
  {
22005
22133
  "name": "href",
22006
22134
  "kind": "function",
22007
22135
  "package": "@nifrajs/web-preact",
22008
22136
  "signature": "export declare function href<K extends Pattern>(options: HrefOptions<K>): Href<K>;",
22009
- "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate) throws a `TypeError` naming it, in production too: a link built from it would go\n * somewhere else. The result is a pure function of its input, so the server and the browser build the\n * same string. A link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22137
+ "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate), a `hash` with an unpaired surrogate, a `search` key reserved for route-slot state, and a\n * slot target that was itself refused come from data, so they do not throw: the result is the inert\n * `Href`, which every consumer (`Link`, `Navigate`, `navigate`, and a click on a plain `<a>`) ignores,\n * and a `console.error` (once per distinct message, within a bounded memory; see {@link onHrefRefused}\n * to take over) names the route and the param, never the value. A link built from such a value would go somewhere else, so no link is built.\n * The result is a pure function of its input, so the server and the browser build the same string. A\n * link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22010
22138
  },
22011
22139
  {
22012
22140
  "name": "href",
22013
22141
  "kind": "function",
22014
22142
  "package": "@nifrajs/web-react",
22015
22143
  "signature": "export declare function href<K extends Pattern>(options: HrefOptions<K>): Href<K>;",
22016
- "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate) throws a `TypeError` naming it, in production too: a link built from it would go\n * somewhere else. The result is a pure function of its input, so the server and the browser build the\n * same string. A link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22144
+ "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate), a `hash` with an unpaired surrogate, a `search` key reserved for route-slot state, and a\n * slot target that was itself refused come from data, so they do not throw: the result is the inert\n * `Href`, which every consumer (`Link`, `Navigate`, `navigate`, and a click on a plain `<a>`) ignores,\n * and a `console.error` (once per distinct message, within a bounded memory; see {@link onHrefRefused}\n * to take over) names the route and the param, never the value. A link built from such a value would go somewhere else, so no link is built.\n * The result is a pure function of its input, so the server and the browser build the same string. A\n * link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22017
22145
  },
22018
22146
  {
22019
22147
  "name": "href",
22020
22148
  "kind": "function",
22021
22149
  "package": "@nifrajs/web-solid",
22022
22150
  "signature": "export declare function href<K extends Pattern>(options: HrefOptions<K>): Href<K>;",
22023
- "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate) throws a `TypeError` naming it, in production too: a link built from it would go\n * somewhere else. The result is a pure function of its input, so the server and the browser build the\n * same string. A link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22151
+ "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate), a `hash` with an unpaired surrogate, a `search` key reserved for route-slot state, and a\n * slot target that was itself refused come from data, so they do not throw: the result is the inert\n * `Href`, which every consumer (`Link`, `Navigate`, `navigate`, and a click on a plain `<a>`) ignores,\n * and a `console.error` (once per distinct message, within a bounded memory; see {@link onHrefRefused}\n * to take over) names the route and the param, never the value. A link built from such a value would go somewhere else, so no link is built.\n * The result is a pure function of its input, so the server and the browser build the same string. A\n * link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22024
22152
  },
22025
22153
  {
22026
22154
  "name": "href",
22027
22155
  "kind": "function",
22028
22156
  "package": "@nifrajs/web-svelte",
22029
22157
  "signature": "export declare function href<K extends Pattern>(options: HrefOptions<K>): Href<K>;",
22030
- "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate) throws a `TypeError` naming it, in production too: a link built from it would go\n * somewhere else. The result is a pure function of its input, so the server and the browser build the\n * same string. A link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22158
+ "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate), a `hash` with an unpaired surrogate, a `search` key reserved for route-slot state, and a\n * slot target that was itself refused come from data, so they do not throw: the result is the inert\n * `Href`, which every consumer (`Link`, `Navigate`, `navigate`, and a click on a plain `<a>`) ignores,\n * and a `console.error` (once per distinct message, within a bounded memory; see {@link onHrefRefused}\n * to take over) names the route and the param, never the value. A link built from such a value would go somewhere else, so no link is built.\n * The result is a pure function of its input, so the server and the browser build the same string. A\n * link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22031
22159
  },
22032
22160
  {
22033
22161
  "name": "href",
22034
22162
  "kind": "function",
22035
22163
  "package": "@nifrajs/web-vue",
22036
22164
  "signature": "export declare function href<K extends Pattern>(options: HrefOptions<K>): Href<K>;",
22037
- "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate) throws a `TypeError` naming it, in production too: a link built from it would go\n * somewhere else. The result is a pure function of its input, so the server and the browser build the\n * same string. A link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22165
+ "doc": "/**\n * The in-app URL for a route: the pattern filled with `params` (each value encoded as one path\n * segment), then `search` serialized as the router reads it, then the `hash`. `to` is a key of the\n * generated route table, so a misspelt route, a missing or misspelt param and a `search` that breaks the\n * route's schema are compile errors; the result is an {@link Href}, the only thing `navigate` takes.\n *\n * ```ts\n * navigate(href({ to: \"/users/:id\", params: { id }, search: { tab: \"posts\" }, hash: \"top\" }))\n * ```\n *\n * A param that is missing, empty, or holds a value no path segment can carry (`.`, `..`, an unpaired\n * surrogate), a `hash` with an unpaired surrogate, a `search` key reserved for route-slot state, and a\n * slot target that was itself refused come from data, so they do not throw: the result is the inert\n * `Href`, which every consumer (`Link`, `Navigate`, `navigate`, and a click on a plain `<a>`) ignores,\n * and a `console.error` (once per distinct message, within a bounded memory; see {@link onHrefRefused}\n * to take over) names the route and the param, never the value. A link built from such a value would go somewhere else, so no link is built.\n * The result is a pure function of its input, so the server and the browser build the same string. A\n * link to a path built elsewhere is {@link rawHref}; one to another site is a plain `<a>`.\n */"
22038
22166
  },
22039
22167
  {
22040
22168
  "name": "html",
@@ -22418,6 +22546,13 @@
22418
22546
  "signature": "export declare function isHydrationMismatch(message: string): boolean;",
22419
22547
  "doc": "/** True when `message` is a framework's report of a server/browser render mismatch. */"
22420
22548
  },
22549
+ {
22550
+ "name": "isInertHref",
22551
+ "kind": "function",
22552
+ "package": "@nifrajs/web",
22553
+ "signature": "export declare function isInertHref(value: string): boolean;",
22554
+ "doc": "/** Whether `value` is what `href()` and `rawHref()` return for input they refused. */"
22555
+ },
22421
22556
  {
22422
22557
  "name": "isJsonRpcRequest",
22423
22558
  "kind": "function",
@@ -23328,6 +23463,13 @@
23328
23463
  "signature": "export declare function ogImageResponse(options: OgImageOptions, request?: Request): Promise<Response>;",
23329
23464
  "doc": "/**\n * Build a cacheable OG image response. GET and HEAD are supported; conditional requests short-circuit\n * rasterization, so a crawler revalidation never repeats expensive codec work. The ETag still names the\n * bytes a rasterizer produced: a revalidation is answered from the tag this process last sent for the\n * same SVG and rasterizer, and rasterizes only when it has none.\n */"
23330
23465
  },
23466
+ {
23467
+ "name": "onHrefRefused",
23468
+ "kind": "function",
23469
+ "package": "@nifrajs/web",
23470
+ "signature": "export declare function onHrefRefused(report: (refusal: HrefRefusal) => void): () => void;",
23471
+ "doc": "/**\n * Take over what happens when `href()` or `rawHref()` refuses a value. `report` runs for every refusal,\n * in place of the default `console.error`, so an app can send them to its error tracker or count them;\n * pass `console.error` to keep the default as well. Returns a function that removes it. One reporter at\n * a time: a second call replaces the first. A throw from `report` is swallowed, since a link must not\n * cost the render. The refusal holds no value: a CMS link can carry a token into a log.\n */"
23472
+ },
23331
23473
  {
23332
23474
  "name": "onPageHide",
23333
23475
  "kind": "function",
@@ -24210,6 +24352,12 @@
24210
24352
  "package": "@nifrajs/cli",
24211
24353
  "signature": "export declare function queryImpact(graph: WorkGraph, changedFiles: readonly string[]): ImpactReport;"
24212
24354
  },
24355
+ {
24356
+ "name": "queryKey",
24357
+ "kind": "function",
24358
+ "package": "@nifrajs/web",
24359
+ "signature": "export declare function queryKey<T = unknown, K = unknown>(key: K): K & QueryKey<T>;"
24360
+ },
24213
24361
  {
24214
24362
  "name": "queryObjectOf",
24215
24363
  "kind": "function",
@@ -24277,42 +24425,42 @@
24277
24425
  "kind": "function",
24278
24426
  "package": "@nifrajs/web",
24279
24427
  "signature": "export declare function rawHref(path: string): Href;",
24280
- "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else throws a `TypeError`. A route of this app is {@link href}; another site is a\n * plain `<a href>`.\n */"
24428
+ "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else is a path from data this function cannot vouch for, so it does not throw:\n * the result is the inert `Href` that `Link`, `Navigate` and `navigate` ignore, with a `console.error`\n * that leaves the value out. A route of this app is {@link href}; another site is a plain `<a href>`.\n */"
24281
24429
  },
24282
24430
  {
24283
24431
  "name": "rawHref",
24284
24432
  "kind": "function",
24285
24433
  "package": "@nifrajs/web-preact",
24286
24434
  "signature": "export declare function rawHref(path: string): Href;",
24287
- "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else throws a `TypeError`. A route of this app is {@link href}; another site is a\n * plain `<a href>`.\n */"
24435
+ "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else is a path from data this function cannot vouch for, so it does not throw:\n * the result is the inert `Href` that `Link`, `Navigate` and `navigate` ignore, with a `console.error`\n * that leaves the value out. A route of this app is {@link href}; another site is a plain `<a href>`.\n */"
24288
24436
  },
24289
24437
  {
24290
24438
  "name": "rawHref",
24291
24439
  "kind": "function",
24292
24440
  "package": "@nifrajs/web-react",
24293
24441
  "signature": "export declare function rawHref(path: string): Href;",
24294
- "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else throws a `TypeError`. A route of this app is {@link href}; another site is a\n * plain `<a href>`.\n */"
24442
+ "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else is a path from data this function cannot vouch for, so it does not throw:\n * the result is the inert `Href` that `Link`, `Navigate` and `navigate` ignore, with a `console.error`\n * that leaves the value out. A route of this app is {@link href}; another site is a plain `<a href>`.\n */"
24295
24443
  },
24296
24444
  {
24297
24445
  "name": "rawHref",
24298
24446
  "kind": "function",
24299
24447
  "package": "@nifrajs/web-solid",
24300
24448
  "signature": "export declare function rawHref(path: string): Href;",
24301
- "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else throws a `TypeError`. A route of this app is {@link href}; another site is a\n * plain `<a href>`.\n */"
24449
+ "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else is a path from data this function cannot vouch for, so it does not throw:\n * the result is the inert `Href` that `Link`, `Navigate` and `navigate` ignore, with a `console.error`\n * that leaves the value out. A route of this app is {@link href}; another site is a plain `<a href>`.\n */"
24302
24450
  },
24303
24451
  {
24304
24452
  "name": "rawHref",
24305
24453
  "kind": "function",
24306
24454
  "package": "@nifrajs/web-svelte",
24307
24455
  "signature": "export declare function rawHref(path: string): Href;",
24308
- "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else throws a `TypeError`. A route of this app is {@link href}; another site is a\n * plain `<a href>`.\n */"
24456
+ "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else is a path from data this function cannot vouch for, so it does not throw:\n * the result is the inert `Href` that `Link`, `Navigate` and `navigate` ignore, with a `console.error`\n * that leaves the value out. A route of this app is {@link href}; another site is a plain `<a href>`.\n */"
24309
24457
  },
24310
24458
  {
24311
24459
  "name": "rawHref",
24312
24460
  "kind": "function",
24313
24461
  "package": "@nifrajs/web-vue",
24314
24462
  "signature": "export declare function rawHref(path: string): Href;",
24315
- "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else throws a `TypeError`. A route of this app is {@link href}; another site is a\n * plain `<a href>`.\n */"
24463
+ "doc": "/**\n * An {@link Href} for a same-origin path built elsewhere: a CMS link, a `@nifrajs/content` page, a public\n * file such as `/llms.txt`. The path is returned as written, never encoded, after `isSameOriginPath`\n * (the check `redirect()` makes) accepts it: one leading `/`, not `//`, no backslash and no control\n * character. Anything else is a path from data this function cannot vouch for, so it does not throw:\n * the result is the inert `Href` that `Link`, `Navigate` and `navigate` ignore, with a `console.error`\n * that leaves the value out. A route of this app is {@link href}; another site is a plain `<a href>`.\n */"
24316
24464
  },
24317
24465
  {
24318
24466
  "name": "reactAdapter",
@@ -24911,6 +25059,13 @@
24911
25059
  "signature": "export declare function resolveDynamicBoundaries(boundaries: readonly BoundaryRegistration[], context: BoundaryRequestCtx): Promise<BoundaryStates>;",
24912
25060
  "doc": "/**\n * Resolve all dynamic boundaries concurrently. Each receives a fresh frozen context object; one\n * failure becomes that boundary's error state and never rejects a sibling or exposes sibling data.\n * Static/intercepting modes remain `unresolved` until their phase-specific runtime owns them.\n */"
24913
25061
  },
25062
+ {
25063
+ "name": "resolveErrorLogDetail",
25064
+ "kind": "function",
25065
+ "package": "@nifrajs/core",
25066
+ "signature": "export declare function resolveErrorLogDetail(detail?: ErrorLogDetail): ErrorLogDetail;",
25067
+ "doc": "/** Resolve the app's request error log policy, falling back safely when env access is denied. */"
25068
+ },
24914
25069
  {
24915
25070
  "name": "resolveImage",
24916
25071
  "kind": "function",
@@ -25425,7 +25580,7 @@
25425
25580
  "name": "runWorkGraph",
25426
25581
  "kind": "function",
25427
25582
  "package": "@nifrajs/cli",
25428
- "signature": "export declare function runWorkGraph(cwd: string, options?: {\n readonly changedFiles?: readonly string[];\n readonly minLevel?: number;\n readonly json?: boolean;\n}): Promise<boolean>;"
25583
+ "signature": "export declare function runWorkGraph(cwd: string, options?: WorkGraphOptions & {\n readonly json?: boolean;\n}): Promise<boolean>;"
25429
25584
  },
25430
25585
  {
25431
25586
  "name": "runtimeAdapterCertificationProfile",
@@ -25725,8 +25880,7 @@
25725
25880
  "name": "serverFn",
25726
25881
  "kind": "function",
25727
25882
  "package": "@nifrajs/web",
25728
- "signature": "export declare function serverFn<Input = void, Output = unknown>(config: ServerFnConfig<Input>, fn: (input: Input, context: Context) => MaybePromise<Output>): ServerFn<Input, Output>;",
25729
- "doc": "/**\n * Declare a server function.\n *\n * export const addTodo = serverFn(\n * { input: t.object({ text: t.string({ minLength: 1 }) }), capabilities: [\"db.write\"] },\n * async ({ text }, c) => db.todos.insert({ text }),\n * )\n *\n * The second argument receives the validated input and the ordinary nifra `Context` - `c.env`,\n * `c.clientIp`, `c.budget`, cookies, and the capability guard are all present, because this is a route.\n */"
25883
+ "signature": "export declare function serverFn<Input = void>(config: ServerFnConfig<Input> & {\n readonly output?: undefined;\n}, fn: (input: Input, context: Context) => MaybePromise<void | null | undefined | ServerFnControl>): ServerFn<Input, void>;"
25730
25884
  },
25731
25885
  {
25732
25886
  "name": "serverFnStubPlugin",
@@ -26445,6 +26599,13 @@
26445
26599
  "package": "@nifrajs/testing",
26446
26600
  "signature": "export declare function testToolAdapter<Input, Output>(tool: ToolContract<Input, Output>, baseOptions?: ToolCallOptions): ToolAdapter;"
26447
26601
  },
26602
+ {
26603
+ "name": "thrownByNifra",
26604
+ "kind": "function",
26605
+ "package": "@nifrajs/web",
26606
+ "signature": "export declare function thrownByNifra(frames: readonly DiagnosticFrame[]): boolean;",
26607
+ "doc": "/**\n * True when the error was thrown from inside an installed nifra package (the innermost located frame\n * sits under `node_modules/@nifrajs/`), as opposed to app code that happens to word a message alike.\n */"
26608
+ },
26448
26609
  {
26449
26610
  "name": "timing",
26450
26611
  "kind": "function",
@@ -27193,12 +27354,40 @@
27193
27354
  "signature": "export declare function usePageVisibility(): Readonly<Ref<boolean>>;",
27194
27355
  "doc": "/**\n * Whether the page this component renders in is on screen, as a ref: `false` while it is kept hidden\n * behind another page, where it keeps running. Always `true` on the server and on a page that does not\n * keep alive.\n */"
27195
27356
  },
27357
+ {
27358
+ "name": "useParams",
27359
+ "kind": "function",
27360
+ "package": "@nifrajs/web-preact",
27361
+ "signature": "export declare function useParams<K extends RouteFrom>(from: K): ParamsOfFrom<K>;",
27362
+ "doc": "/**\n * The matched route's decoded path params, typed from the generated route table:\n * `useParams(\"/users/:id\")` is `{ readonly id: string }`. The argument only names the route for the\n * compiler (nothing is read from it at runtime), and a pattern the table does not hold is a compile\n * error. SSR-correct: the same value on the server render and the client mount.\n *\n * ```tsx\n * const { id } = useParams(\"/users/:id\") // id: string\n * ```\n */"
27363
+ },
27196
27364
  {
27197
27365
  "name": "useParams",
27198
27366
  "kind": "function",
27199
27367
  "package": "@nifrajs/web-react",
27200
- "signature": "export declare function useParams<T extends Record<string, string | undefined> = Record<string, string>>(): Readonly<T>;",
27201
- "doc": "/**\n * The matched route's decoded path params - `/users/:id` on `/users/7` → `{ id: \"7\" }`. SSR-correct:\n * `compose` provides the same value server-side (from the request match) and client-side (from router\n * state), so a param rendered into markup doesn't flash on hydration.\n */"
27368
+ "signature": "export declare function useParams<K extends RouteFrom>(from: K): ParamsOfFrom<K>;",
27369
+ "doc": "/**\n * The matched route's decoded path params, typed from the generated route table:\n * `useParams(\"/users/:id\")` is `{ readonly id: string }`. The argument only names the route for the\n * compiler (nothing is read from it at runtime), and a pattern the table does not hold is a compile\n * error. SSR-correct: the same value on the server render and the client mount.\n *\n * ```tsx\n * const { id } = useParams(\"/users/:id\") // id: string\n * ```\n */"
27370
+ },
27371
+ {
27372
+ "name": "useParams",
27373
+ "kind": "function",
27374
+ "package": "@nifrajs/web-solid",
27375
+ "signature": "export declare function useParams<K extends RouteFrom>(from: K): Accessor<ParamsOfFrom<K>>;",
27376
+ "doc": "/**\n * The matched route's decoded path params as a reactive accessor, typed from the generated route table:\n * `useParams(\"/users/:id\")` is `{ readonly id: string }`. The argument only names the route for the\n * compiler (nothing is read from it at runtime), and a pattern the table does not hold is a compile\n * error. SSR-correct: the same value on the server render and the client mount.\n *\n * ```tsx\n * const params = useParams(\"/users/:id\") // Accessor<{ id: string }>\n * return <span>{params().id}</span>\n * ```\n */"
27377
+ },
27378
+ {
27379
+ "name": "useParams",
27380
+ "kind": "function",
27381
+ "package": "@nifrajs/web-svelte",
27382
+ "signature": "export declare function useParams<K extends RouteFrom>(from: K): () => ParamsOfFrom<K>;",
27383
+ "doc": "/**\n * The matched route's decoded path params as a reactive accessor, typed from the generated route table:\n * `useParams(\"/users/:id\")` is `{ readonly id: string }`. The argument only names the route for the\n * compiler (nothing is read from it at runtime), and a pattern the table does not hold is a compile\n * error. SSR-correct: the same value on the server render and the client mount.\n *\n * ```svelte\n * <script>\n * const params = useParams(\"/users/:id\") // () => { id: string }\n * </script>\n * <span>{params().id}</span>\n * ```\n */"
27384
+ },
27385
+ {
27386
+ "name": "useParams",
27387
+ "kind": "function",
27388
+ "package": "@nifrajs/web-vue",
27389
+ "signature": "export declare function useParams<K extends RouteFrom>(from: K): Readonly<Ref<ParamsOfFrom<K>>>;",
27390
+ "doc": "/**\n * The matched route's decoded path params as a reactive ref, typed from the generated route table:\n * `useParams(\"/users/:id\")` is `{ readonly id: string }`. The argument only names the route for the\n * compiler (nothing is read from it at runtime), and a pattern the table does not hold is a compile\n * error. SSR-correct: the same value on the server render and the client mount.\n *\n * ```vue\n * const params = useParams(\"/users/:id\") // Ref<{ id: string }>\n * // template: {{ params.id }}\n * ```\n */"
27202
27391
  },
27203
27392
  {
27204
27393
  "name": "usePending",
@@ -27211,29 +27400,25 @@
27211
27400
  "name": "useQuery",
27212
27401
  "kind": "function",
27213
27402
  "package": "@nifrajs/web-preact",
27214
- "signature": "export declare function useQuery<T>(key: unknown, fn: () => Promise<T>, options?: QueryOptions): UseQueryResult<T>;",
27215
- "doc": "/**\n * Subscribe to the keyed query for `key`, fetched via `fn`. Returns `{ status, data, error, isFetching,\n * updatedAt, isPending, refetch }`. Concurrent `useQuery`s with the same key share one cache entry +\n * one in-flight fetch (dedup). Refetches on mount and when the key changes; SSR-idle. `options.live`\n * names the live keys that refetch it.\n */"
27403
+ "signature": "export declare function useQuery<T, K = PlainKeyDefault>(key: PlainQueryKey<K>, fn: () => Promise<T>, options?: QueryOptions): UseQueryResult<T>;"
27216
27404
  },
27217
27405
  {
27218
27406
  "name": "useQuery",
27219
27407
  "kind": "function",
27220
27408
  "package": "@nifrajs/web-react",
27221
- "signature": "export declare function useQuery<T>(key: unknown, fn: () => Promise<T>, options?: UseQueryOptions): UseQueryResult<T>;",
27222
- "doc": "/**\n * Subscribe to the keyed query for `key`, fetched via `fn`. Returns `{ status, data, error, isFetching,\n * updatedAt, isPending, isError, isSuccess, refetch }`. Concurrent `useQuery`s with the same key share\n * one cache entry + one in-flight fetch (dedup). Fetches on mount and when the key changes; `enabled:\n * false` keeps it idle (dependent queries). SSR-idle unless a `QueryClientProvider` supplies a hydrated\n * client.\n */"
27409
+ "signature": "export declare function useQuery<T, K = PlainKeyDefault>(key: PlainQueryKey<K>, fn: () => Promise<T>, options?: UseQueryOptions): UseQueryResult<T>;"
27223
27410
  },
27224
27411
  {
27225
27412
  "name": "useQuery",
27226
27413
  "kind": "function",
27227
27414
  "package": "@nifrajs/web-svelte",
27228
- "signature": "export declare function useQuery<T>(key: unknown, fn: () => Promise<T>, options?: QueryOptions): QueryStore<T>;",
27229
- "doc": "/**\n * Subscribe to the keyed query for `key`, fetched via `fn`. Returns a store of `{ status, data, error,\n * isFetching, updatedAt }` augmented with `refetch`. Fetches on mount (first `$`-subscription); SSR-idle.\n * `options.live` names the live keys that refetch it.\n */"
27415
+ "signature": "export declare function useQuery<T, K = PlainKeyDefault>(key: PlainQueryKey<K>, fn: () => Promise<T>, options?: QueryOptions): QueryStore<T>;"
27230
27416
  },
27231
27417
  {
27232
27418
  "name": "useQuery",
27233
27419
  "kind": "function",
27234
27420
  "package": "@nifrajs/web-vue",
27235
- "signature": "export declare function useQuery<T>(key: unknown, fn: () => Promise<T>, options?: QueryOptions): UseQueryResult<T>;",
27236
- "doc": "/**\n * Subscribe to the keyed query for `key`, fetched via `fn`. Returns a reactive `state` ref (`status`,\n * `data`, `error`, `isFetching`, `updatedAt`) + `refetch`. Concurrent `useQuery`s with the same key\n * share one cache entry + one in-flight fetch (dedup). Fetches on mount; SSR-idle. `options.live`\n * names the live keys that refetch it.\n */"
27421
+ "signature": "export declare function useQuery<T, K = PlainKeyDefault>(key: PlainQueryKey<K>, fn: () => Promise<T>, options?: QueryOptions): UseQueryResult<T>;"
27237
27422
  },
27238
27423
  {
27239
27424
  "name": "useQueryClient",
@@ -27301,36 +27486,36 @@
27301
27486
  "name": "useSearch",
27302
27487
  "kind": "function",
27303
27488
  "package": "@nifrajs/web-preact",
27304
- "signature": "export declare function useSearch<Schema extends StandardSchemaV1 | undefined = undefined>(): Schema extends StandardSchemaV1 ? InferOutput<Schema> : Record<string, unknown>;",
27305
- "doc": "/**\n * The route's typed, validated search params - the SAME value the loader received as `ctx.search`.\n * SSR-correct: `compose` provides it from the URL server-side and from the identical derivation on the\n * client mount, so a value rendered from it doesn't flash on hydration. Hostile input already failed\n * closed to the schema's defaults at match time. Pass the route's `searchSchema` as the type argument to\n * get its output type; bare, it's the raw parsed query (`Record<string, unknown>`).\n *\n * ```tsx\n * export const searchSchema = v.object({ page: v.optional(v.fallback(v.number(), 1), 1) })\n * const { page } = useSearch<typeof searchSchema>() // page: number\n * ```\n */"
27489
+ "signature": "export declare function useSearch<K extends RouteFrom>(from: K): SearchOfFrom<K>;",
27490
+ "doc": "/**\n * The route's validated search params - the SAME value the loader received as `ctx.search`,\n * typed from the generated route table: `useSearch(\"/reports\")` is that route's `searchSchema` output.\n * The argument only names the route for the compiler (nothing is read from it at runtime), and a pattern\n * the table does not hold is a compile error. SSR-correct: the value is derived from the URL identically\n * on the server and on each client navigation, so a value rendered from it doesn't flash on hydration.\n * Hostile input already failed closed to the schema's defaults at match time.\n *\n * ```tsx\n * const { page } = useSearch(\"/reports\") // page: number\n * ```\n */"
27306
27491
  },
27307
27492
  {
27308
27493
  "name": "useSearch",
27309
27494
  "kind": "function",
27310
27495
  "package": "@nifrajs/web-react",
27311
- "signature": "export declare function useSearch<Schema extends StandardSchemaV1 | undefined = undefined>(): Schema extends StandardSchemaV1 ? InferOutput<Schema> : Record<string, unknown>;",
27312
- "doc": "/**\n * The route's typed, validated search params: the SAME value the loader received as `ctx.search`.\n * SSR-correct: `compose` provides it from `searchOf(searchSchema, url.search)` server-side and from the\n * identical derivation on the client mount, so a value rendered from it doesn't flash on hydration.\n * Hostile input already failed closed to the schema's defaults at match time, so a component never\n * parses `window.location.search` or guards against a bad query.\n *\n * Pass the route's `searchSchema` as the type argument to get its output type; bare, it's the raw parsed\n * query (`Record<string, unknown>`), which is also what a route without a `searchSchema` yields.\n *\n * ```tsx\n * export const searchSchema = v.object({ page: v.optional(v.fallback(v.number(), 1), 1) })\n * const { page } = useSearch<typeof searchSchema>() // page: number\n * ```\n */"
27496
+ "signature": "export declare function useSearch<K extends RouteFrom>(from: K): SearchOfFrom<K>;",
27497
+ "doc": "/**\n * The route's validated search params - the SAME value the loader received as `ctx.search`,\n * typed from the generated route table: `useSearch(\"/reports\")` is that route's `searchSchema` output.\n * The argument only names the route for the compiler (nothing is read from it at runtime), and a pattern\n * the table does not hold is a compile error. SSR-correct: the value is derived from the URL identically\n * on the server and on each client navigation, so a value rendered from it doesn't flash on hydration.\n * Hostile input already failed closed to the schema's defaults at match time.\n *\n * ```tsx\n * const { page } = useSearch(\"/reports\") // page: number\n * ```\n */"
27313
27498
  },
27314
27499
  {
27315
27500
  "name": "useSearch",
27316
27501
  "kind": "function",
27317
27502
  "package": "@nifrajs/web-solid",
27318
- "signature": "export declare function useSearch<Schema extends StandardSchemaV1 | undefined = undefined>(): Accessor<Schema extends StandardSchemaV1 ? InferOutput<Schema> : Record<string, unknown>>;",
27319
- "doc": "/**\n * The route's typed, validated search params as a reactive accessor - the SAME value the loader received\n * as `ctx.search`. SSR-correct: `compose` provides it from the URL server-side and from the identical\n * client-mount derivation, so a value rendered from it doesn't flash on hydration. Call it to read the\n * current search (`useSearch()().page`); it updates in place on a same-route navigation. Pass the route's\n * `searchSchema` as the type argument for its output type.\n *\n * ```tsx\n * const search = useSearch<typeof searchSchema>() // Accessor<{ page: number }>\n * return <span>{search().page}</span>\n * ```\n */"
27503
+ "signature": "export declare function useSearch<K extends RouteFrom>(from: K): Accessor<SearchOfFrom<K>>;",
27504
+ "doc": "/**\n * The route's validated search params as a reactive accessor - the SAME value the loader received as `ctx.search`,\n * typed from the generated route table: `useSearch(\"/reports\")` is that route's `searchSchema` output.\n * The argument only names the route for the compiler (nothing is read from it at runtime), and a pattern\n * the table does not hold is a compile error. SSR-correct: the value is derived from the URL identically\n * on the server and on each client navigation, so a value rendered from it doesn't flash on hydration.\n * Hostile input already failed closed to the schema's defaults at match time.\n *\n * ```tsx\n * const search = useSearch(\"/reports\") // Accessor<{ page: number }>\n * return <span>{search().page}</span>\n * ```\n */"
27320
27505
  },
27321
27506
  {
27322
27507
  "name": "useSearch",
27323
27508
  "kind": "function",
27324
27509
  "package": "@nifrajs/web-svelte",
27325
- "signature": "export declare function useSearch<Schema extends StandardSchemaV1 | undefined = undefined>(): () => Schema extends StandardSchemaV1 ? InferOutput<Schema> : Record<string, unknown>;",
27326
- "doc": "/**\n * The route's typed, validated search params as a reactive accessor - the SAME value the loader received\n * as `ctx.search`. SSR-correct: `Chain.svelte` provides it from the URL server-side and from the\n * identical client derivation, so a value rendered from it doesn't flash on hydration. Call it (in a\n * `$derived` or the template) to read the current search - it updates on navigation. Pass the route's\n * `searchSchema` as the type argument for its output type.\n *\n * ```svelte\n * <script>\n * const search = useSearch() // () => { page: number, ... }\n * </script>\n * <span>{search().page}</span>\n * ```\n */"
27510
+ "signature": "export declare function useSearch<K extends RouteFrom>(from: K): () => SearchOfFrom<K>;",
27511
+ "doc": "/**\n * The route's validated search params as a reactive accessor - the SAME value the loader received as `ctx.search`,\n * typed from the generated route table: `useSearch(\"/reports\")` is that route's `searchSchema` output.\n * The argument only names the route for the compiler (nothing is read from it at runtime), and a pattern\n * the table does not hold is a compile error. SSR-correct: the value is derived from the URL identically\n * on the server and on each client navigation, so a value rendered from it doesn't flash on hydration.\n * Hostile input already failed closed to the schema's defaults at match time.\n *\n * ```svelte\n * <script>\n * const search = useSearch(\"/reports\") // () => { page: number }\n * </script>\n * <span>{search().page}</span>\n * ```\n */"
27327
27512
  },
27328
27513
  {
27329
27514
  "name": "useSearch",
27330
27515
  "kind": "function",
27331
27516
  "package": "@nifrajs/web-vue",
27332
- "signature": "export declare function useSearch<Schema extends StandardSchemaV1 | undefined = undefined>(): Readonly<Ref<Schema extends StandardSchemaV1 ? InferOutput<Schema> : Record<string, unknown>>>;",
27333
- "doc": "/**\n * The route's typed, validated search params as a reactive ref - the SAME value the loader received as\n * `ctx.search`. SSR-correct: `compose` provides it from the URL server-side and from the identical\n * client-mount derivation, so a value rendered from it doesn't flash on hydration. Read `search.value`\n * (reactive across navigation). Pass the route's `searchSchema` as the type argument for its output type.\n *\n * ```vue\n * const search = useSearch<typeof searchSchema>() // Ref<{ page: number }>\n * // template: {{ search.page }}\n * ```\n */"
27517
+ "signature": "export declare function useSearch<K extends RouteFrom>(from: K): Readonly<Ref<SearchOfFrom<K>>>;",
27518
+ "doc": "/**\n * The route's validated search params as a reactive ref - the SAME value the loader received as `ctx.search`,\n * typed from the generated route table: `useSearch(\"/reports\")` is that route's `searchSchema` output.\n * The argument only names the route for the compiler (nothing is read from it at runtime), and a pattern\n * the table does not hold is a compile error. SSR-correct: the value is derived from the URL identically\n * on the server and on each client navigation, so a value rendered from it doesn't flash on hydration.\n * Hostile input already failed closed to the schema's defaults at match time.\n *\n * ```vue\n * const search = useSearch(\"/reports\") // Ref<{ page: number }>\n * // template: {{ search.page }}\n * ```\n */"
27334
27519
  },
27335
27520
  {
27336
27521
  "name": "useSearchParams",