@nifrajs/cli 5.14.0 → 5.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -0
- package/dist/check-diagnostics.d.ts.map +1 -1
- package/dist/check-diagnostics.js +22 -2
- package/dist/check-diagnostics.js.map +1 -1
- package/dist/check-scan.d.ts.map +1 -1
- package/dist/check-scan.js +7 -1
- package/dist/check-scan.js.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/frontend-guidance.js +12 -12
- package/dist/frontend-guidance.js.map +1 -1
- package/dist/mcp-http.js +1 -1
- package/dist/recipes/5.15.0.d.ts +12 -0
- package/dist/recipes/5.15.0.d.ts.map +1 -0
- package/dist/recipes/5.15.0.js +30 -0
- package/dist/recipes/5.15.0.js.map +1 -0
- package/dist/recipes/index.d.ts.map +1 -1
- package/dist/recipes/index.js +2 -0
- package/dist/recipes/index.js.map +1 -1
- package/docs/examples.json +7 -1
- package/docs/llms-full.txt +72 -33
- package/docs/types.json +43 -15
- package/package.json +12 -12
- package/src/check-diagnostics.ts +26 -2
- package/src/check-scan.ts +8 -1
- package/src/cli.ts +1 -1
- package/src/frontend-guidance.ts +12 -12
- package/src/mcp-http.ts +1 -1
- package/src/recipes/5.15.0.ts +40 -0
- package/src/recipes/index.ts +2 -0
package/docs/types.json
CHANGED
|
@@ -914,7 +914,7 @@
|
|
|
914
914
|
"name": "AgentSharedState",
|
|
915
915
|
"kind": "interface",
|
|
916
916
|
"package": "@nifrajs/agent",
|
|
917
|
-
"signature": "export interface AgentSharedState<State = unknown> {\n /** A defensive deep copy of the current document. */\n snapshot(): State;\n
|
|
917
|
+
"signature": "export interface AgentSharedState<State = unknown> {\n /** A defensive deep copy of the current document. */\n snapshot(): State;\n /**\n * Apply ops atomically - on an invalid op the whole batch is rejected with a TypeError. Values are\n * copied, so later changes to a value the caller passed never reach the document, and a value a copy\n * would change or share (a function, a class instance, an accessor, shared memory) is refused with a\n * TypeError before anything commits.\n */\n patch(ops: readonly AgentStatePatchOp[]): void;\n /**\n * Observe applied patches. Each listener receives its own copy of the batch, so one observer\n * cannot change the document or what another observer sees. Returns the unsubscribe function.\n * Listener failures are isolated.\n */\n subscribe(listener: (ops: readonly AgentStatePatchOp[]) => void): () => void;\n}",
|
|
918
918
|
"doc": "/**\n * A shared, observable state document for one run - the state a live UI mirrors while the agent\n * works. App code (a model port, a tool executor) calls `patch` with RFC 6902 operations; every\n * subscriber sees the applied ops, and protocol bridges project them onto their wire (AG-UI\n * `STATE_SNAPSHOT`/`STATE_DELTA`). The document is transient per-run observer data - it is not\n * turn state, not evidence, and never persisted by the runtime.\n */"
|
|
919
919
|
},
|
|
920
920
|
{
|
|
@@ -1793,7 +1793,7 @@
|
|
|
1793
1793
|
"name": "AwaitProps",
|
|
1794
1794
|
"kind": "interface",
|
|
1795
1795
|
"package": "@nifrajs/web-solid",
|
|
1796
|
-
"signature": "export interface AwaitProps<T> {\n /** A `Deferred<T>` from a loader's `defer(...)`, or an already-resolved value (client nav). */\n readonly resolve: Deferred<T> | T;\n readonly fallback?: JSX.Element;\n /** Rendered if the deferred rejects. Without it the error propagates to the nearest\n * `<
|
|
1796
|
+
"signature": "export interface AwaitProps<T> {\n /** A `Deferred<T>` from a loader's `defer(...)`, or an already-resolved value (client nav). */\n readonly resolve: Deferred<T> | T;\n readonly fallback?: JSX.Element;\n /** Rendered if the deferred rejects. Without it the error propagates to the nearest\n * `<Errored>`. */\n readonly errorFallback?: (error: unknown) => JSX.Element;\n readonly children: (value: T) => JSX.Element;\n}"
|
|
1797
1797
|
},
|
|
1798
1798
|
{
|
|
1799
1799
|
"name": "AwaitProps",
|
|
@@ -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\", \"
|
|
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}"
|
|
2367
2367
|
},
|
|
2368
2368
|
{
|
|
2369
2369
|
"name": "BuildClientViteOptions",
|
|
@@ -10065,14 +10065,14 @@
|
|
|
10065
10065
|
"name": "Middleware",
|
|
10066
10066
|
"kind": "interface",
|
|
10067
10067
|
"package": "@nifrajs/core",
|
|
10068
|
-
"signature": "export interface Middleware {\n readonly name?: string;\n readonly onRequest?: (req: Request, platform?: Platform) => MaybePromise<OnRequestResult>;\n /** Allocation-light Node equivalent of `onRequest` for header-only hooks. */\n readonly onNodeRequest?: NodeRequestHook;\n readonly around?: <T>(context: Context, next: () => MaybePromise<T>) => MaybePromise<T>;\n readonly beforeHandle?: (context: Context) => MaybePromise<unknown>;\n readonly afterHandle?: (result: unknown, context: Context) => MaybePromise<unknown>;\n readonly onResponse?: (response: Response, req: Request) => MaybePromise<Response>;\n /**\n * Header-only equivalent of `onResponse` for the Node-direct serializer. It is used only when every\n * response hook in the app supplies this paired native implementation; arbitrary response transforms\n * continue through the Web Response path.\n */\n readonly onNodeResponse?: NodeResponseHook;\n /**\n * Response headers with NO per-request decision behind them. Declared here instead of written by a\n * hook, they are folded into response construction, so a bundle that only sets static headers does\n * not cost the app its fused/native lanes (see {@link Server.responseHeaders}). They are defaults:\n * anything the request produced wins. Reach for `onResponseHeaders` the moment a value depends on\n * the request, the route, or the response.\n */\n readonly responseHeaders?: Readonly<Record<string, string>>;\n /**\n * PORTABLE header-only response hook - the recommended shape when the middleware only reads or\n * writes headers. One implementation runs on every runtime: inside the Web `onResponse` walk\n * against the response's own `Headers`, and on Node as a self-paired native hook against the\n * outcome record - so it never forces the Node adapter off its direct writer. Use `onResponse` +\n * an optional `onNodeResponse` twin only when the hook must see a real `Response`.\n */\n readonly onResponseHeaders?: ResponseHeadersHook;\n /** Allocation-light Node-direct twin for a portable header-only hook; keep its wire semantics identical. */\n readonly onNodeResponseHeaders?: NodeResponseHook;\n /**\n * PORTABLE post-serialization body hook - the payload tier. Receives the final\n * framework-serialized bytes (already resident on every runtime; no stream is drained) plus the\n * header view and status, and may return replacement bytes. Raw handler-returned `Response`s\n * (proxies, SSE, streamed SSR) are skipped by contract - transforming those needs `onResponse`.\n */\n readonly onResponseBody?: ResponseBodyHook;\n /** Allocation-light Node-direct twin for a portable body hook; keep its wire semantics identical. */\n readonly onNodeResponseBody?: NodeResponseBodyHook;\n /**\n * Response transform for untagged/raw responses (streams, proxied fetches, and framework errors).\n * Framework-serialized payloads use `onResponseBody` and remain on the Node direct lane.\n */\n readonly onResponseRaw?: (response: Response, req: Request) => MaybePromise<Response>;\n readonly onResponseFinalized?: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>;\n readonly onError?: (error: unknown, context: Context) => MaybePromise<unknown>;\n}",
|
|
10068
|
+
"signature": "export interface Middleware {\n readonly name?: string;\n readonly onRequest?: (req: Request, platform?: Platform) => MaybePromise<OnRequestResult>;\n /** Allocation-light Node equivalent of `onRequest` for header-only hooks. */\n readonly onNodeRequest?: NodeRequestHook;\n readonly around?: <T>(context: Context, next: () => MaybePromise<T>) => MaybePromise<T>;\n readonly beforeHandle?: (context: Context) => MaybePromise<unknown>;\n readonly afterHandle?: (result: unknown, context: Context) => MaybePromise<unknown>;\n readonly onResponse?: (response: Response, req: Request) => MaybePromise<Response>;\n /**\n * Header-only equivalent of `onResponse` for the Node-direct serializer. It is used only when every\n * response hook in the app supplies this paired native implementation; arbitrary response transforms\n * continue through the Web Response path.\n */\n readonly onNodeResponse?: NodeResponseHook;\n /**\n * Response headers with NO per-request decision behind them. Declared here instead of written by a\n * hook, they are folded into response construction, so a bundle that only sets static headers does\n * not cost the app its fused/native lanes (see {@link Server.responseHeaders}). They are defaults:\n * anything the request produced wins. Reach for `onResponseHeaders` the moment a value depends on\n * the request, the route, or the response.\n */\n readonly responseHeaders?: Readonly<Record<string, string>>;\n /**\n * PORTABLE header-only response hook - the recommended shape when the middleware only reads or\n * writes headers. One implementation runs on every runtime: inside the Web `onResponse` walk\n * against the response's own `Headers`, and on Node as a self-paired native hook against the\n * outcome record - so it never forces the Node adapter off its direct writer. Use `onResponse` +\n * an optional `onNodeResponse` twin only when the hook must see a real `Response`.\n */\n readonly onResponseHeaders?: ResponseHeadersHook;\n /** Allocation-light Node-direct twin for a portable header-only hook; keep its wire semantics identical. */\n readonly onNodeResponseHeaders?: NodeResponseHook;\n /**\n * PORTABLE post-serialization body hook - the payload tier. Receives the final\n * framework-serialized bytes (already resident on every runtime; no stream is drained) plus the\n * header view and status, and may return replacement bytes. Raw handler-returned `Response`s\n * (proxies, SSE, streamed SSR) are skipped by contract - transforming those needs `onResponse`.\n */\n readonly onResponseBody?: ResponseBodyHook;\n /** Allocation-light Node-direct twin for a portable body hook; keep its wire semantics identical. */\n readonly onNodeResponseBody?: NodeResponseBodyHook;\n /**\n * A synchronous fast path for `onResponseBody`, taken when the framework renders a value a handler\n * returned: one `Response` is built from its result instead of two. Only for a hook that is\n * idempotent on its own output (a reply it rendered with new bytes skips the hook on the Web\n * path, and any other pass over it must find nothing left to do). It applies only while this hook is the first response hook of the app, so\n * nothing registered before it can have run first, and not on a response carrying `c.set` headers,\n * cookies, static response headers, or the idempotency plugin. A throw is logged and declines the fast path for the next 100,000\n * replies: `onResponseBody` then handles them and fails through the response pipeline, as it always has.\n */\n readonly renderBody?: RenderBodyHook;\n /**\n * Response transform for untagged/raw responses (streams, proxied fetches, and framework errors).\n * Framework-serialized payloads use `onResponseBody` and remain on the Node direct lane.\n */\n readonly onResponseRaw?: (response: Response, req: Request) => MaybePromise<Response>;\n readonly onResponseFinalized?: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>;\n readonly onError?: (error: unknown, context: Context) => MaybePromise<unknown>;\n}",
|
|
10069
10069
|
"doc": "/**\n * A bundle of lifecycle hooks applied together via {@link Server.use} - the unit\n * `@nifrajs/middleware` ships (cors, security headers, rate-limit). Every hook is\n * optional and wired to its lifecycle point. Middleware carrying a portable response tier must be\n * marked with `withResponseObserver()` from `@nifrajs/core/response-observer`, or the server must\n * install `responseObserver()` before the bundle is applied. Middleware is context-agnostic (sees\n * the base `Context`); `use` does no context-type merging - the full type-merging\n * plugin system is deferred, and `.use` is reserved as its future entry point.\n */"
|
|
10070
10070
|
},
|
|
10071
10071
|
{
|
|
10072
10072
|
"name": "Middleware",
|
|
10073
10073
|
"kind": "interface",
|
|
10074
10074
|
"package": "nifra",
|
|
10075
|
-
"signature": "export interface Middleware {\n readonly name?: string;\n readonly onRequest?: (req: Request, platform?: Platform) => MaybePromise<OnRequestResult>;\n /** Allocation-light Node equivalent of `onRequest` for header-only hooks. */\n readonly onNodeRequest?: NodeRequestHook;\n readonly around?: <T>(context: Context, next: () => MaybePromise<T>) => MaybePromise<T>;\n readonly beforeHandle?: (context: Context) => MaybePromise<unknown>;\n readonly afterHandle?: (result: unknown, context: Context) => MaybePromise<unknown>;\n readonly onResponse?: (response: Response, req: Request) => MaybePromise<Response>;\n /**\n * Header-only equivalent of `onResponse` for the Node-direct serializer. It is used only when every\n * response hook in the app supplies this paired native implementation; arbitrary response transforms\n * continue through the Web Response path.\n */\n readonly onNodeResponse?: NodeResponseHook;\n /**\n * Response headers with NO per-request decision behind them. Declared here instead of written by a\n * hook, they are folded into response construction, so a bundle that only sets static headers does\n * not cost the app its fused/native lanes (see {@link Server.responseHeaders}). They are defaults:\n * anything the request produced wins. Reach for `onResponseHeaders` the moment a value depends on\n * the request, the route, or the response.\n */\n readonly responseHeaders?: Readonly<Record<string, string>>;\n /**\n * PORTABLE header-only response hook - the recommended shape when the middleware only reads or\n * writes headers. One implementation runs on every runtime: inside the Web `onResponse` walk\n * against the response's own `Headers`, and on Node as a self-paired native hook against the\n * outcome record - so it never forces the Node adapter off its direct writer. Use `onResponse` +\n * an optional `onNodeResponse` twin only when the hook must see a real `Response`.\n */\n readonly onResponseHeaders?: ResponseHeadersHook;\n /** Allocation-light Node-direct twin for a portable header-only hook; keep its wire semantics identical. */\n readonly onNodeResponseHeaders?: NodeResponseHook;\n /**\n * PORTABLE post-serialization body hook - the payload tier. Receives the final\n * framework-serialized bytes (already resident on every runtime; no stream is drained) plus the\n * header view and status, and may return replacement bytes. Raw handler-returned `Response`s\n * (proxies, SSE, streamed SSR) are skipped by contract - transforming those needs `onResponse`.\n */\n readonly onResponseBody?: ResponseBodyHook;\n /** Allocation-light Node-direct twin for a portable body hook; keep its wire semantics identical. */\n readonly onNodeResponseBody?: NodeResponseBodyHook;\n /**\n * Response transform for untagged/raw responses (streams, proxied fetches, and framework errors).\n * Framework-serialized payloads use `onResponseBody` and remain on the Node direct lane.\n */\n readonly onResponseRaw?: (response: Response, req: Request) => MaybePromise<Response>;\n readonly onResponseFinalized?: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>;\n readonly onError?: (error: unknown, context: Context) => MaybePromise<unknown>;\n}",
|
|
10075
|
+
"signature": "export interface Middleware {\n readonly name?: string;\n readonly onRequest?: (req: Request, platform?: Platform) => MaybePromise<OnRequestResult>;\n /** Allocation-light Node equivalent of `onRequest` for header-only hooks. */\n readonly onNodeRequest?: NodeRequestHook;\n readonly around?: <T>(context: Context, next: () => MaybePromise<T>) => MaybePromise<T>;\n readonly beforeHandle?: (context: Context) => MaybePromise<unknown>;\n readonly afterHandle?: (result: unknown, context: Context) => MaybePromise<unknown>;\n readonly onResponse?: (response: Response, req: Request) => MaybePromise<Response>;\n /**\n * Header-only equivalent of `onResponse` for the Node-direct serializer. It is used only when every\n * response hook in the app supplies this paired native implementation; arbitrary response transforms\n * continue through the Web Response path.\n */\n readonly onNodeResponse?: NodeResponseHook;\n /**\n * Response headers with NO per-request decision behind them. Declared here instead of written by a\n * hook, they are folded into response construction, so a bundle that only sets static headers does\n * not cost the app its fused/native lanes (see {@link Server.responseHeaders}). They are defaults:\n * anything the request produced wins. Reach for `onResponseHeaders` the moment a value depends on\n * the request, the route, or the response.\n */\n readonly responseHeaders?: Readonly<Record<string, string>>;\n /**\n * PORTABLE header-only response hook - the recommended shape when the middleware only reads or\n * writes headers. One implementation runs on every runtime: inside the Web `onResponse` walk\n * against the response's own `Headers`, and on Node as a self-paired native hook against the\n * outcome record - so it never forces the Node adapter off its direct writer. Use `onResponse` +\n * an optional `onNodeResponse` twin only when the hook must see a real `Response`.\n */\n readonly onResponseHeaders?: ResponseHeadersHook;\n /** Allocation-light Node-direct twin for a portable header-only hook; keep its wire semantics identical. */\n readonly onNodeResponseHeaders?: NodeResponseHook;\n /**\n * PORTABLE post-serialization body hook - the payload tier. Receives the final\n * framework-serialized bytes (already resident on every runtime; no stream is drained) plus the\n * header view and status, and may return replacement bytes. Raw handler-returned `Response`s\n * (proxies, SSE, streamed SSR) are skipped by contract - transforming those needs `onResponse`.\n */\n readonly onResponseBody?: ResponseBodyHook;\n /** Allocation-light Node-direct twin for a portable body hook; keep its wire semantics identical. */\n readonly onNodeResponseBody?: NodeResponseBodyHook;\n /**\n * A synchronous fast path for `onResponseBody`, taken when the framework renders a value a handler\n * returned: one `Response` is built from its result instead of two. Only for a hook that is\n * idempotent on its own output (a reply it rendered with new bytes skips the hook on the Web\n * path, and any other pass over it must find nothing left to do). It applies only while this hook is the first response hook of the app, so\n * nothing registered before it can have run first, and not on a response carrying `c.set` headers,\n * cookies, static response headers, or the idempotency plugin. A throw is logged and declines the fast path for the next 100,000\n * replies: `onResponseBody` then handles them and fails through the response pipeline, as it always has.\n */\n readonly renderBody?: RenderBodyHook;\n /**\n * Response transform for untagged/raw responses (streams, proxied fetches, and framework errors).\n * Framework-serialized payloads use `onResponseBody` and remain on the Node direct lane.\n */\n readonly onResponseRaw?: (response: Response, req: Request) => MaybePromise<Response>;\n readonly onResponseFinalized?: (outcome: ResponseFinalization, req: Request) => MaybePromise<void>;\n readonly onError?: (error: unknown, context: Context) => MaybePromise<unknown>;\n}",
|
|
10076
10076
|
"doc": "/**\n * A bundle of lifecycle hooks applied together via {@link Server.use} - the unit\n * `@nifrajs/middleware` ships (cors, security headers, rate-limit). Every hook is\n * optional and wired to its lifecycle point. Middleware carrying a portable response tier must be\n * marked with `withResponseObserver()` from `@nifrajs/core/response-observer`, or the server must\n * install `responseObserver()` before the bundle is applied. Middleware is context-agnostic (sees\n * the base `Context`); `use` does no context-type merging - the full type-merging\n * plugin system is deferred, and `.use` is reserved as its future entry point.\n */"
|
|
10077
10077
|
},
|
|
10078
10078
|
{
|
|
@@ -13230,6 +13230,20 @@
|
|
|
13230
13230
|
"signature": "export interface RenderAssemblyCache {\n /** Shell up to (not including) the deferred-runtime insertion point. */\n shellPre?: string;\n /** Shell from after the deferred-runtime insertion point through `<body>`. */\n shellPost?: string;\n /** The open `#root` container. */\n rootOpen?: string;\n /** Tail opener: the handover script open tag + the data member's key. */\n tailPre?: string;\n /** Tail from after the per-request handover members (the route id, prerendered paths, the handover\n * close) through `</html>`. */\n tailPost?: string;\n}",
|
|
13231
13231
|
"doc": "/** The mutable per-route slot {@link RenderPageOptions.assemblyCache} fills. Opaque - create as `{}`. */"
|
|
13232
13232
|
},
|
|
13233
|
+
{
|
|
13234
|
+
"name": "RenderBodyHook",
|
|
13235
|
+
"kind": "type",
|
|
13236
|
+
"package": "@nifrajs/core",
|
|
13237
|
+
"signature": "export type RenderBodyHook = (body: string, headers: RenderHeadersView, req: NodeRequestContext, status: number) => Uint8Array | undefined;",
|
|
13238
|
+
"doc": "/**\n * A synchronous fast path for a body hook, run when the framework renders a returned value: the hook\n * sees the serialized text before any `Response` exists, so one `Response` is built where the body\n * tier would build two (the rendered one, then its replacement). It returns replacement bytes, or\n * `undefined` to leave the body as it is. Provide one only for a hook that is idempotent on its own\n * output: the full hook still runs on the rendered response afterwards, and must find nothing left to\n * do. It may write headers, and it must not start asynchronous work.\n */"
|
|
13239
|
+
},
|
|
13240
|
+
{
|
|
13241
|
+
"name": "RenderHeadersView",
|
|
13242
|
+
"kind": "type",
|
|
13243
|
+
"package": "@nifrajs/core",
|
|
13244
|
+
"signature": "export type RenderHeadersView = Pick<ResponseHeadersView, \"get\" | \"has\" | \"set\" | \"delete\">;",
|
|
13245
|
+
"doc": "/** The header view a {@link RenderBodyHook} gets: no `append`, as the headers are one plain record. */"
|
|
13246
|
+
},
|
|
13233
13247
|
{
|
|
13234
13248
|
"name": "RenderMode",
|
|
13235
13249
|
"kind": "type",
|
|
@@ -13267,7 +13281,7 @@
|
|
|
13267
13281
|
"name": "RenderPropsContext",
|
|
13268
13282
|
"kind": "const",
|
|
13269
13283
|
"package": "@nifrajs/web-solid",
|
|
13270
|
-
"signature": "export declare const RenderPropsContext: Context<RenderProps |
|
|
13284
|
+
"signature": "export declare const RenderPropsContext: Context<RenderProps | null>;"
|
|
13271
13285
|
},
|
|
13272
13286
|
{
|
|
13273
13287
|
"name": "RenderPropsProvider",
|
|
@@ -13688,7 +13702,7 @@
|
|
|
13688
13702
|
"name": "ResponseObserverMethods",
|
|
13689
13703
|
"kind": "interface",
|
|
13690
13704
|
"package": "@nifrajs/core",
|
|
13691
|
-
"signature": "export interface ResponseObserverMethods {\n /**\n * Register a portable header hook. `node` is an optional equivalent for the Node-direct record;\n * it must preserve the portable hook's observable header semantics.\n */\n onResponseHeaders(fn: ResponseHeadersHook, node?: NodeResponseHook): this;\n onResponseBody(fn: ResponseBodyHook, node?: NodeResponseBodyHook): this;\n onResponseRaw(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n}"
|
|
13705
|
+
"signature": "export interface ResponseObserverMethods {\n /**\n * Register a portable header hook. `node` is an optional equivalent for the Node-direct record;\n * it must preserve the portable hook's observable header semantics.\n */\n onResponseHeaders(fn: ResponseHeadersHook, node?: NodeResponseHook): this;\n onResponseBody(fn: ResponseBodyHook, node?: NodeResponseBodyHook, render?: RenderBodyHook): this;\n onResponseRaw(fn: (response: Response, req: Request) => MaybePromise<Response>): this;\n}"
|
|
13692
13706
|
},
|
|
13693
13707
|
{
|
|
13694
13708
|
"name": "ResponseObserverPlugin",
|
|
@@ -15420,7 +15434,7 @@
|
|
|
15420
15434
|
"name": "SearchContext",
|
|
15421
15435
|
"kind": "const",
|
|
15422
15436
|
"package": "@nifrajs/web-solid",
|
|
15423
|
-
"signature": "export declare const SearchContext: Context<Accessor<Record<string, unknown>> |
|
|
15437
|
+
"signature": "export declare const SearchContext: Context<Accessor<Record<string, unknown>> | null>;"
|
|
15424
15438
|
},
|
|
15425
15439
|
{
|
|
15426
15440
|
"name": "SearchOf",
|
|
@@ -15621,14 +15635,14 @@
|
|
|
15621
15635
|
"name": "Server",
|
|
15622
15636
|
"kind": "class",
|
|
15623
15637
|
"package": "@nifrajs/core",
|
|
15624
|
-
"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 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}",
|
|
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}",
|
|
15625
15639
|
"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 */"
|
|
15626
15640
|
},
|
|
15627
15641
|
{
|
|
15628
15642
|
"name": "Server",
|
|
15629
15643
|
"kind": "class",
|
|
15630
15644
|
"package": "nifra",
|
|
15631
|
-
"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 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}",
|
|
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}",
|
|
15632
15646
|
"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 */"
|
|
15633
15647
|
},
|
|
15634
15648
|
{
|
|
@@ -17917,14 +17931,14 @@
|
|
|
17917
17931
|
"name": "VERSION",
|
|
17918
17932
|
"kind": "const",
|
|
17919
17933
|
"package": "@nifrajs/core",
|
|
17920
|
-
"signature": "export declare const VERSION: \"5.
|
|
17934
|
+
"signature": "export declare const VERSION: \"5.15.1\";",
|
|
17921
17935
|
"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 */"
|
|
17922
17936
|
},
|
|
17923
17937
|
{
|
|
17924
17938
|
"name": "VERSION",
|
|
17925
17939
|
"kind": "const",
|
|
17926
17940
|
"package": "nifra",
|
|
17927
|
-
"signature": "export declare const VERSION: \"5.
|
|
17941
|
+
"signature": "export declare const VERSION: \"5.15.1\";",
|
|
17928
17942
|
"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 */"
|
|
17929
17943
|
},
|
|
17930
17944
|
{
|
|
@@ -21130,6 +21144,20 @@
|
|
|
21130
21144
|
"signature": "export declare function e2eWebSocket<App>(baseUrl: string, path: E2EPaths<App>): string;",
|
|
21131
21145
|
"doc": "/**\n * Build a real WebSocket URL for an adapter-backed test server. The path uses the same-origin guard as\n * {@link e2eUrl}; `http`/`https` are translated to `ws`/`wss` so callers cannot accidentally dial an\n * HTTP URL with a WebSocket client or escape the test server origin.\n */"
|
|
21132
21146
|
},
|
|
21147
|
+
{
|
|
21148
|
+
"name": "echoParam",
|
|
21149
|
+
"kind": "function",
|
|
21150
|
+
"package": "@nifrajs/core",
|
|
21151
|
+
"signature": "export declare function echoParam(path: string): (context: {\n readonly params: Readonly<Record<string, string>>;\n readonly req: Request;\n}) => Response;",
|
|
21152
|
+
"doc": "/**\n * Answer 200 with the route's final path parameter as plain text, exactly as the request spelled it:\n * percent-escapes are left in, not decoded. Pass the route's own path:\n *\n * const USER = \"/user/:id\"\n * server().get(USER, echoParam(USER))\n *\n * `/user/%41b` answers `%41b`. The path is a static prefix followed by one `:name` segment; anything\n * else throws, so the parameter is always the last segment. The answer is defined by the path given\n * here: a request that does not match it (the handler registered elsewhere) answers with the decoded\n * value, and one that does gets its final segment as sent, whatever route matched it.\n *\n * The raw spelling is the contract because a transport can then answer the route itself (uWS fills the\n * body in from the path without calling into JavaScript) and the bytes stay the same either way. Two\n * inputs are outside that: a malformed escape such as `%zz` is echoed as sent when the node-uws native\n * lane answers, and refused with 400 by ordinary routing; and a segment of only dots written as escapes\n * is read differently by each runtime's URL parser.\n */"
|
|
21153
|
+
},
|
|
21154
|
+
{
|
|
21155
|
+
"name": "echoParam",
|
|
21156
|
+
"kind": "function",
|
|
21157
|
+
"package": "nifra",
|
|
21158
|
+
"signature": "export declare function echoParam(path: string): (context: {\n readonly params: Readonly<Record<string, string>>;\n readonly req: Request;\n}) => Response;",
|
|
21159
|
+
"doc": "/**\n * Answer 200 with the route's final path parameter as plain text, exactly as the request spelled it:\n * percent-escapes are left in, not decoded. Pass the route's own path:\n *\n * const USER = \"/user/:id\"\n * server().get(USER, echoParam(USER))\n *\n * `/user/%41b` answers `%41b`. The path is a static prefix followed by one `:name` segment; anything\n * else throws, so the parameter is always the last segment. The answer is defined by the path given\n * here: a request that does not match it (the handler registered elsewhere) answers with the decoded\n * value, and one that does gets its final segment as sent, whatever route matched it.\n *\n * The raw spelling is the contract because a transport can then answer the route itself (uWS fills the\n * body in from the path without calling into JavaScript) and the bytes stay the same either way. Two\n * inputs are outside that: a malformed escape such as `%zz` is echoed as sent when the node-uws native\n * lane answers, and refused with 400 by ordinary routing; and a segment of only dots written as escapes\n * is read differently by each runtime's URL parser.\n */"
|
|
21160
|
+
},
|
|
21133
21161
|
{
|
|
21134
21162
|
"name": "effect",
|
|
21135
21163
|
"kind": "function",
|
|
@@ -21175,7 +21203,7 @@
|
|
|
21175
21203
|
"name": "emitRequestErrorLog",
|
|
21176
21204
|
"kind": "function",
|
|
21177
21205
|
"package": "@nifrajs/core",
|
|
21178
|
-
"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): void;",
|
|
21206
|
+
"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;",
|
|
21179
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 */"
|
|
21180
21208
|
},
|
|
21181
21209
|
{
|
|
@@ -21278,7 +21306,7 @@
|
|
|
21278
21306
|
"kind": "function",
|
|
21279
21307
|
"package": "@nifrajs/web-solid",
|
|
21280
21308
|
"signature": "export declare function errorBoundary(fallback: unknown): unknown;",
|
|
21281
|
-
"doc": "/**\n * Build an error-boundary chain element bound to `fallback` (a route's `_error` component). nifra's\n * client codegen inserts it before the page in the matched chain; a render error in the subtree renders\n * `fallback` with `{ data: { name, message } }` (via Solid's `<
|
|
21309
|
+
"doc": "/**\n * Build an error-boundary chain element bound to `fallback` (a route's `_error` component). nifra's\n * client codegen inserts it before the page in the matched chain; a render error in the subtree renders\n * `fallback` with `{ data: { name, message } }` (via Solid's `<Errored>`) instead of crashing.\n * DOM-transparent (renders its children directly - no wrapper element), so it never disturbs hydration.\n */"
|
|
21282
21310
|
},
|
|
21283
21311
|
{
|
|
21284
21312
|
"name": "errorBoundary",
|
|
@@ -26004,7 +26032,7 @@
|
|
|
26004
26032
|
"kind": "function",
|
|
26005
26033
|
"package": "@nifrajs/web-solid",
|
|
26006
26034
|
"signature": "export declare function solidBunPlugin(generate: \"dom\" | \"ssr\"): BunPlugin;",
|
|
26007
|
-
"doc": "/**\n * Bun build/runtime plugin that compiles Solid components with
|
|
26035
|
+
"doc": "/**\n * Bun build/runtime plugin that compiles Solid components with Solid 2.0's native compiler -\n * `generate: \"ssr\"` for the server, `\"dom\"` for the client, `hydratable` so SSR and hydrate align. Runs\n * at build time, on `.tsx` files only. The compiler parses TypeScript but keeps its types, so Bun's own\n * `ts` loader strips them after the JSX is gone.\n *\n * Under a dev server the client half additionally runs the compiler's refresh pass, which is what makes\n * an edit patch the running component tree instead of reloading the page - see {@link setupSolidRefresh}.\n */"
|
|
26008
26036
|
},
|
|
26009
26037
|
{
|
|
26010
26038
|
"name": "solidComponentClient",
|