theokit 0.36.1 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{actions-virtual-module-SYGQE6JQ.js → actions-virtual-module-H3LY5Q22.js} +3 -3
- package/dist/{actions-virtual-module-3KSP3WPJ.js → actions-virtual-module-WLOT2SPR.js} +3 -3
- package/dist/{agent-DX5LHD6X.js → agent-VQMWM5BK.js} +2 -2
- package/dist/{app-typed-client-N4TRX5FI.js → app-typed-client-67GBLYD6.js} +113 -24
- package/dist/app-typed-client-67GBLYD6.js.map +1 -0
- package/dist/{app-typed-client-ESMMLPYK.js → app-typed-client-SPFNGVZL.js} +113 -24
- package/dist/app-typed-client-SPFNGVZL.js.map +1 -0
- package/dist/{build-3C2KQPME.js → build-3BFIACHN.js} +6 -6
- package/dist/{chunk-RVJAM77M.js → chunk-2HKRQUWU.js} +2 -2
- package/dist/{chunk-3KD2O6DC.js → chunk-BKYFOEBK.js} +58 -54
- package/dist/chunk-BKYFOEBK.js.map +1 -0
- package/dist/{chunk-V3X5FWJA.js → chunk-EV33DOG6.js} +1 -1
- package/dist/{chunk-V3X5FWJA.js.map → chunk-EV33DOG6.js.map} +1 -1
- package/dist/{chunk-UDG6JPVP.js → chunk-GW5H4KB4.js} +2 -2
- package/dist/{chunk-DISADTFZ.js → chunk-IPSFSNEJ.js} +2 -2
- package/dist/{chunk-RPMKF6BC.js → chunk-OLZLYLOE.js} +109 -7
- package/dist/chunk-OLZLYLOE.js.map +1 -0
- package/dist/{chunk-CEHXC5NI.js → chunk-Q3C3KH3C.js} +24 -5
- package/dist/chunk-Q3C3KH3C.js.map +1 -0
- package/dist/{chunk-MNQC5XEJ.js → chunk-QCB7ZNR2.js} +94 -37
- package/dist/chunk-QCB7ZNR2.js.map +1 -0
- package/dist/{chunk-T4TCLEFB.js → chunk-QMV3R6D5.js} +91 -36
- package/dist/chunk-QMV3R6D5.js.map +1 -0
- package/dist/chunk-QNFVYST4.js +110 -0
- package/dist/chunk-QNFVYST4.js.map +1 -0
- package/dist/{chunk-WL4AX5FI.js → chunk-QWBXUZAX.js} +57 -54
- package/dist/chunk-QWBXUZAX.js.map +1 -0
- package/dist/cli/index.js +5 -5
- package/dist/client/core.d.ts +12 -1
- package/dist/client/core.js +1 -1
- package/dist/client/index.d.ts +7 -1
- package/dist/client/index.js +2 -1
- package/dist/client/index.js.map +1 -1
- package/dist/controller-swc-transform-URELVCBM.js +27 -0
- package/dist/controller-swc-transform-URELVCBM.js.map +1 -0
- package/dist/controller-swc-transform-XV3ETSE3.js +28 -0
- package/dist/controller-swc-transform-XV3ETSE3.js.map +1 -0
- package/dist/{dev-CNPT7COE.js → dev-IBCZYFZZ.js} +8 -8
- package/dist/{index-C3ged4mn.d.ts → index-BeAsvfPr.d.ts} +2 -2
- package/dist/index.js +4 -4
- package/dist/{internal-api-4IXBITVV.js → internal-api-MDCX7A7H.js} +10 -3
- package/dist/{internal-api-5JKDYRGM.js → internal-api-OLNM25HS.js} +9 -3
- package/dist/{mcp-INKDONQS.js → mcp-DKRODZAL.js} +2 -2
- package/dist/{plugin-runner-CMprWWHZ.d.ts → plugin-runner-BFEcgtmJ.d.ts} +1 -1
- package/dist/{plugin-types-L49QYMb5.d.ts → plugin-types-D69-lJZ9.d.ts} +9 -2
- package/dist/{registry-3NB7KOUI.js → registry-FKPH7XEL.js} +1 -1
- package/dist/server/define/index.d.ts +1 -1
- package/dist/server/define/index.js +1 -1
- package/dist/server/http/index.d.ts +3 -3
- package/dist/server/http/index.js +1 -1
- package/dist/server/index.d.ts +4 -4
- package/dist/server/index.js +3 -3
- package/dist/server/plugins/index.d.ts +3 -3
- package/dist/{start-LNJZNKF6.js → start-WB7GYXEW.js} +3 -3
- package/dist/vite-plugin/index.js +4 -4
- package/dist/{vite-plugin-NC5ETNMV.js → vite-plugin-5Y3LDTXI.js} +5 -5
- package/package.json +2 -2
- package/dist/app-typed-client-ESMMLPYK.js.map +0 -1
- package/dist/app-typed-client-N4TRX5FI.js.map +0 -1
- package/dist/chunk-3KD2O6DC.js.map +0 -1
- package/dist/chunk-CEHXC5NI.js.map +0 -1
- package/dist/chunk-MNQC5XEJ.js.map +0 -1
- package/dist/chunk-RPMKF6BC.js.map +0 -1
- package/dist/chunk-RSVN727G.js +0 -1
- package/dist/chunk-T4TCLEFB.js.map +0 -1
- package/dist/chunk-WL4AX5FI.js.map +0 -1
- package/dist/vite-plugin-NC5ETNMV.js.map +0 -1
- /package/dist/{actions-virtual-module-SYGQE6JQ.js.map → actions-virtual-module-H3LY5Q22.js.map} +0 -0
- /package/dist/{actions-virtual-module-3KSP3WPJ.js.map → actions-virtual-module-WLOT2SPR.js.map} +0 -0
- /package/dist/{agent-DX5LHD6X.js.map → agent-VQMWM5BK.js.map} +0 -0
- /package/dist/{build-3C2KQPME.js.map → build-3BFIACHN.js.map} +0 -0
- /package/dist/{chunk-RVJAM77M.js.map → chunk-2HKRQUWU.js.map} +0 -0
- /package/dist/{chunk-UDG6JPVP.js.map → chunk-GW5H4KB4.js.map} +0 -0
- /package/dist/{chunk-DISADTFZ.js.map → chunk-IPSFSNEJ.js.map} +0 -0
- /package/dist/{dev-CNPT7COE.js.map → dev-IBCZYFZZ.js.map} +0 -0
- /package/dist/{chunk-RSVN727G.js.map → internal-api-MDCX7A7H.js.map} +0 -0
- /package/dist/{internal-api-4IXBITVV.js.map → internal-api-OLNM25HS.js.map} +0 -0
- /package/dist/{mcp-INKDONQS.js.map → mcp-DKRODZAL.js.map} +0 -0
- /package/dist/{registry-3NB7KOUI.js.map → registry-FKPH7XEL.js.map} +0 -0
- /package/dist/{start-LNJZNKF6.js.map → start-WB7GYXEW.js.map} +0 -0
- /package/dist/{internal-api-5JKDYRGM.js.map → vite-plugin-5Y3LDTXI.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/define/define-route.ts","../src/server/define/route-builder.ts","../src/server/define/define-action.ts","../src/server/define/action-builder.ts","../src/server/define/define-websocket.ts","../src/server/define/websocket-builder.ts","../src/server/define/define-middleware.ts","../src/server/define/middleware-builder.ts","../src/server/define/tool-builder.ts","../src/server/plugin-types.ts","../src/server/define/plugin-builder.ts","../src/server/define/ui-message-stream-response.ts","../src/server/define/define-channel.ts"],"sourcesContent":["import type { z } from 'zod'\n\n// T2.2 (architecture-cleanup) — RouteConfig type moved to core/contracts/\n// (canonical home per ADR-0001 v3). Re-export preserves the public path\n// `import { type RouteConfig } from 'theokit/server'`.\nexport type { RouteConfig } from '../../core/contracts/route-config.js'\n\nimport type { RouteConfig } from '../../core/contracts/route-config.js'\n\n/**\n * Define a typed HTTP route.\n * Identity function — provides type inference for route handlers.\n */\nexport function defineRoute<\n TQuery extends z.ZodType = z.ZodUndefined,\n TBody extends z.ZodType = z.ZodUndefined,\n TParams extends z.ZodType = z.ZodUndefined,\n TCtx = unknown,\n TResponse = unknown,\n>(\n config: RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>,\n): RouteConfig<TQuery, TBody, TParams, TCtx, TResponse> {\n return config\n}\n","/**\n * M31 Phase 3 — `route()`, the fluent builder that replaces `defineRoute({...})`.\n *\n * Pure type-state (mirrors `tool-builder.ts`). `.query/.body/.params` set Zod schemas whose\n * `z.infer<>` flows into the handler's `ctx`; `.handler()` is required before `.build()`. `.build()`\n * delegates to the internal {@link defineRoute} (an identity fn), emitting the identical\n * `RouteConfig` — the scan/execute path is UNCHANGED (identity-shape delegation, blueprint §2).\n *\n * export const POST = route()\n * .params(z.object({ id: z.string() }))\n * .body(z.object({ text: z.string() }))\n * .handler(({ params, body }) => save(params.id, body.text))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport type { RouteConfig } from '../../core/contracts/route-config.js'\n\nimport { defineRoute } from './define-route.js'\n\n/** Compile-error carrier: `.build()` called before `.handler()`. */\ninterface MissingHandlerError {\n readonly __theokitError: 'a route needs .handler(fn) before .build()'\n}\n\n/**\n * The fluent route builder. `TQuery/TBody/TParams` track the input schemas (default `z.ZodUndefined`,\n * matching {@link RouteConfig}); `TResponse` tracks the handler return; `THandlerSet` gates `.build()`.\n */\nexport interface RouteBuilder<\n TQuery extends z.ZodType = z.ZodUndefined,\n TBody extends z.ZodType = z.ZodUndefined,\n TParams extends z.ZodType = z.ZodUndefined,\n TCtx = unknown,\n TResponse = unknown,\n THandlerSet extends boolean = false,\n> {\n /** Set the URL search-params schema. Inferred into `ctx.query`. */\n query<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<S, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Set the request-body schema. Inferred into `ctx.body`. */\n body<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<TQuery, S, TParams, TCtx, TResponse, THandlerSet>\n /** Set the path-params schema. Inferred into `ctx.params`. */\n params<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<TQuery, TBody, S, TCtx, TResponse, THandlerSet>\n /** Runtime-only validation of the handler's plain-object return (500 on mismatch). Not inferred (YAGNI). */\n response(schema: z.ZodType): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Override the HTTP status for a plain-object return (default 200; 204 for void). */\n status(code: number): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Opt out of CSRF enforcement for this route (webhooks / OAuth callbacks). */\n csrf(disabled: false): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /**\n * Set the handler. Its `ctx` infers `query/body/params` from the schemas set above. Required\n * before `.build()`.\n */\n handler<R>(\n fn: (ctx: {\n query: z.infer<TQuery>\n body: z.infer<TBody>\n params: z.infer<TParams>\n request: Request\n ctx: TCtx\n }) => R | Promise<R>,\n ): RouteBuilder<TQuery, TBody, TParams, TCtx, R, true>\n /**\n * Resolve to the `RouteConfig` — the SAME value `defineRoute({...})` returns. COMPILE ERROR when\n * `.handler()` was never called.\n */\n build(\n ...guard: THandlerSet extends true ? [] : [error: MissingHandlerError]\n ): RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>\n}\n\n/**\n * Permissive internal shape — the runtime seam works with `z.ZodType` schemas (ctx fields typed\n * `unknown`); the precise per-schema types are carried to callers by the {@link RouteBuilder}\n * interface via the `as unknown as RouteBuilder` bridge. `defineRoute` is an identity fn.\n */\ntype AnyRouteConfig = RouteConfig<z.ZodType, z.ZodType, z.ZodType>\n\ninterface RouteSpecAccumulator {\n query?: z.ZodType\n body?: z.ZodType\n params?: z.ZodType\n response?: z.ZodType\n status?: number\n csrf?: false\n handler?: AnyRouteConfig['handler']\n}\n\nfunction makeRouteBuilder(spec: RouteSpecAccumulator): RouteBuilder {\n const runtime = {\n query: (schema: z.ZodType) => makeRouteBuilder({ ...spec, query: schema }),\n body: (schema: z.ZodType) => makeRouteBuilder({ ...spec, body: schema }),\n params: (schema: z.ZodType) => makeRouteBuilder({ ...spec, params: schema }),\n response: (schema: z.ZodType) => makeRouteBuilder({ ...spec, response: schema }),\n status: (code: number) => makeRouteBuilder({ ...spec, status: code }),\n csrf: (disabled: false) => makeRouteBuilder({ ...spec, csrf: disabled }),\n handler: (fn: AnyRouteConfig['handler']) => makeRouteBuilder({ ...spec, handler: fn }),\n build: (): AnyRouteConfig => {\n // Fail-fast for untyped (JS) callers — the type-state guard makes this unreachable from TS.\n if (spec.handler === undefined) {\n throw new Error('route(): call .handler(fn) before .build()')\n }\n const config: AnyRouteConfig = {\n ...(spec.query !== undefined ? { query: spec.query } : {}),\n ...(spec.body !== undefined ? { body: spec.body } : {}),\n ...(spec.params !== undefined ? { params: spec.params } : {}),\n ...(spec.response !== undefined ? { response: spec.response } : {}),\n ...(spec.status !== undefined ? { status: spec.status } : {}),\n ...(spec.csrf !== undefined ? { csrf: spec.csrf } : {}),\n handler: spec.handler,\n }\n return defineRoute(config)\n },\n }\n return runtime as unknown as RouteBuilder\n}\n\n/**\n * Start a fluent route definition. Chain `.query/.body/.params/.response/.status/.csrf` (all\n * optional), then `.handler()` (required) and `.build()` for the `RouteConfig`.\n */\nexport function route(): RouteBuilder {\n return makeRouteBuilder({})\n}\n","import type { z } from 'zod'\n\n/**\n * Action wire-protocol accept mode per plan g3-server-actions-and-useaction\n * v1.2 ADR D1. Default behavior (when omitted) is `'json'`. `'form'` opts the\n * action into FormData multipart parsing for progressive-enhancement forms;\n * the runtime in `server/http/action-execute.ts` will coerce FormData entries\n * against the `input` schema via `formDataToObject` (Astro pattern).\n */\nexport type ActionAccept = 'form' | 'json'\n\nexport interface ActionConfig<TInput extends z.ZodType, TCtx = unknown> {\n /**\n * Zod input schema. Required: every action declares its input contract via\n * Zod (architecture rule: zod-is-SSOT). The shape becomes the handler's\n * typed `input` parameter via `z.infer<TInput>`.\n */\n input: TInput\n /**\n * Wire-protocol accept mode. Defaults to `'json'` when omitted. Setting\n * `'form'` switches the runtime to FormData multipart parsing — the input\n * schema MUST be `z.object(...)` so field-by-field coercion can drive\n * boolean string / number / array coercion (Astro pattern).\n */\n accept?: ActionAccept\n /**\n * Opt OUT of CSRF enforcement for this action. Default (omitted) keeps the\n * multi-header CSRF gate active. Set `false` for endpoints intentionally\n * callable without the `X-Theo-Action` header (e.g. public webhooks). The\n * runtime in `server/http/action-execute.ts` reads this flag.\n */\n csrf?: false\n handler: (ctx: { input: z.infer<TInput>; ctx: TCtx }) => unknown\n}\n\n/**\n * Define a typed server action.\n *\n * Identity function — provides type inference for action handlers. The\n * runtime that consumes the config (validation + invocation + serialization)\n * lives in `server/http/action-execute.ts`.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.2: the new\n * `accept?: 'form' | 'json'` field is the only contract change vs the\n * pre-G3 identity. Existing callsites (`defineAction({input, handler})`)\n * continue to compile — `accept` is opt-in.\n */\nexport function defineAction<TInput extends z.ZodType, TCtx = unknown>(\n config: ActionConfig<TInput, TCtx>,\n): ActionConfig<TInput, TCtx> {\n return config\n}\n","/**\n * M31 Phase 3 — `action()`, the fluent builder that replaces `defineAction({...})`.\n *\n * Pure type-state (mirrors `route-builder.ts`). `.input()` (required) sets the Zod schema whose\n * `z.infer<>` types the handler's `ctx.input`; `.handler()` (required) closes the chain. `.build()`\n * delegates to the internal {@link defineAction} (identity) — the action-execute path is UNCHANGED.\n *\n * export const createUser = action()\n * .input(z.object({ email: z.string().email() }))\n * .handler(({ input }) => createUser(input.email))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport { defineAction, type ActionConfig, type ActionAccept } from './define-action.js'\n\n/** Compile-error carrier: `.execute`/`.build()` reached before `.input()`. */\ninterface MissingInputError {\n readonly __theokitError: 'call .input(schema) before .handler(fn)'\n}\n/** Compile-error carrier: `.build()` before both `.input()` and `.handler()` are set. */\ninterface IncompleteActionError {\n readonly __theokitError: 'an action needs .input(schema) and .handler(fn) before .build()'\n}\n\n/** A required-but-unset field. Branded so no ordinary value satisfies it (tRPC UnsetMarker). */\ntype UnsetMarker = 'theokit.unset' & { readonly __brand: 'theokit.unset' }\n\n/**\n * The fluent action builder. `TInput` tracks the Zod schema (drives `ctx.input` inference);\n * `THandlerSet` gates `.build()`.\n */\nexport interface ActionBuilder<\n TInput extends z.ZodType | UnsetMarker = UnsetMarker,\n TCtx = unknown,\n THandlerSet extends boolean = false,\n> {\n /** Set the Zod input schema. Required — every action declares its input contract (zod-is-SSOT). */\n input<S extends z.ZodType>(schema: S): ActionBuilder<S, TCtx, THandlerSet>\n /** Wire-protocol accept mode (`'json'` default, `'form'` for FormData multipart). */\n accept(mode: ActionAccept): ActionBuilder<TInput, TCtx, THandlerSet>\n /** Opt out of CSRF enforcement for this action. */\n csrf(disabled: false): ActionBuilder<TInput, TCtx, THandlerSet>\n /**\n * Set the handler. COMPILE ERROR before `.input()` — the param type collapses to\n * {@link MissingInputError}. `ctx.input` is inferred via `z.infer<TInput>`.\n */\n handler(\n fn: TInput extends z.ZodType\n ? (ctx: { input: z.infer<TInput>; ctx: TCtx }) => unknown\n : MissingInputError,\n ): ActionBuilder<TInput, TCtx, true>\n /**\n * Resolve to the `ActionConfig` — the SAME value `defineAction({...})` returns. COMPILE ERROR when\n * `.input()` or `.handler()` was never called.\n */\n build(\n ...guard: THandlerSet extends true\n ? TInput extends z.ZodType\n ? []\n : [error: IncompleteActionError]\n : [error: IncompleteActionError]\n ): ActionConfig<TInput extends z.ZodType ? TInput : z.ZodType, TCtx>\n}\n\ntype AnyActionConfig = ActionConfig<z.ZodType>\n\ninterface ActionSpecAccumulator {\n input?: z.ZodType\n accept?: ActionAccept\n csrf?: false\n handler?: AnyActionConfig['handler']\n}\n\nfunction makeActionBuilder(spec: ActionSpecAccumulator): ActionBuilder {\n const runtime = {\n input: (schema: z.ZodType) => makeActionBuilder({ ...spec, input: schema }),\n accept: (mode: ActionAccept) => makeActionBuilder({ ...spec, accept: mode }),\n csrf: (disabled: false) => makeActionBuilder({ ...spec, csrf: disabled }),\n handler: (fn: AnyActionConfig['handler']) => makeActionBuilder({ ...spec, handler: fn }),\n build: (): AnyActionConfig => {\n // Fail-fast for untyped (JS) callers — the type-state guards make this unreachable from TS.\n if (spec.input === undefined) {\n throw new Error('action(): call .input(schema) before .build()')\n }\n if (spec.handler === undefined) {\n throw new Error('action(): call .handler(fn) before .build()')\n }\n const config: AnyActionConfig = {\n input: spec.input,\n handler: spec.handler,\n ...(spec.accept !== undefined ? { accept: spec.accept } : {}),\n ...(spec.csrf !== undefined ? { csrf: spec.csrf } : {}),\n }\n return defineAction(config)\n },\n }\n return runtime as unknown as ActionBuilder\n}\n\n/**\n * Start a fluent action definition. Chain `.input()` (required), optionally `.accept()` / `.csrf()`,\n * then `.handler()` (required) and `.build()` for the `ActionConfig`.\n */\nexport function action(): ActionBuilder {\n return makeActionBuilder({})\n}\n","import type { IncomingMessage } from 'node:http'\n\nexport interface WebSocketLike {\n send(data: string | Buffer): void\n close(code?: number, reason?: string): void\n}\n\nexport interface WebSocketHandler {\n onOpen?: (ws: WebSocketLike, req: IncomingMessage) => void\n onMessage?: (ws: WebSocketLike, data: string | Buffer) => void\n onClose?: (ws: WebSocketLike, code: number, reason: Buffer) => void\n onError?: (ws: WebSocketLike, error: Error) => void\n}\n\n/**\n * Define a WebSocket endpoint handler.\n * Identity function — provides type inference for WebSocket handlers.\n */\nexport function defineWebSocket(handler: WebSocketHandler): WebSocketHandler {\n return handler\n}\n\n/**\n * T5a.2 Phase F slice 3/3 — Web-Standards WebSocket endpoint handler.\n *\n * Mirror of `WebSocketHandler` for the Web `Request` shape. `onOpen`\n * receives `request: Request` instead of `req: IncomingMessage`. The\n * rest of the lifecycle (onMessage, onClose, onError) is shape-agnostic\n * (`WebSocketLike` is already Web-standards-compatible per the existing\n * design — `send(string | Buffer)` works on both Node `ws` and Web\n * `WebSocket` instances; CF Workers / Bun / Deno coerce as needed at\n * the adapter boundary).\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase F (closes Phase F).\n *\n * **Architectural note — WebSocket upgrade semantics differ across runtimes:**\n * - Node + `ws`: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —\n * `req` is `IncomingMessage`. Use `WebSocketHandler`.\n * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade\n * handshake IS a Web Request). Use `WebSocketHandlerWeb`.\n * - Bun: `server.upgrade(request, { data })` — same Web Request shape.\n * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.\n *\n * Cross-runtime WebSocket endpoints ship BOTH `WebSocketHandler` +\n * `WebSocketHandlerWeb` exports; the runtime adapter picks the matching\n * one. This is the canonical Hono / Nitric pattern.\n */\nexport interface WebSocketHandlerWeb {\n onOpen?: (ws: WebSocketLike, request: Request) => void\n onMessage?: (ws: WebSocketLike, data: string | Uint8Array) => void\n onClose?: (ws: WebSocketLike, code: number, reason: string) => void\n onError?: (ws: WebSocketLike, error: Error) => void\n}\n\n/**\n * Web-Standards `defineWebSocket` sibling. Identity function — provides\n * type inference for Web WebSocket handlers.\n *\n * **Type difference note vs Node path:**\n * - `onMessage` data is `string | Uint8Array` instead of `string | Buffer`\n * (Web standards have no `Buffer`; Node's Buffer is a Uint8Array\n * subclass so the Node path's Buffer values flow through unchanged\n * when adapters wrap them).\n * - `onClose` reason is `string` instead of `Buffer` (Web `CloseEvent`\n * exposes the reason as a UTF-8 string natively).\n */\nexport function defineWebSocketWeb(handler: WebSocketHandlerWeb): WebSocketHandlerWeb {\n return handler\n}\n","/**\n * M31 Phase 3 — `websocket()`, the fluent builder that replaces `defineWebSocket({...})`.\n *\n * Lifecycle setters (`onOpen/onMessage/onClose/onError`), all optional; `.build()` delegates to the\n * internal {@link defineWebSocket} (identity) — the ws handler loading path is UNCHANGED.\n *\n * export default websocket()\n * .onOpen((ws) => ws.send('hi'))\n * .onMessage((ws, data) => ws.send(`echo:${data}`))\n * .build()\n */\nimport { defineWebSocket, type WebSocketHandler } from './define-websocket.js'\n\n/** The fluent WebSocket builder. Each lifecycle hook is optional; `.build()` returns the handler. */\nexport interface WebSocketBuilder {\n onOpen(fn: NonNullable<WebSocketHandler['onOpen']>): WebSocketBuilder\n onMessage(fn: NonNullable<WebSocketHandler['onMessage']>): WebSocketBuilder\n onClose(fn: NonNullable<WebSocketHandler['onClose']>): WebSocketBuilder\n onError(fn: NonNullable<WebSocketHandler['onError']>): WebSocketBuilder\n /** Resolve to the `WebSocketHandler` — the SAME value `defineWebSocket({...})` returns. */\n build(): WebSocketHandler\n}\n\nfunction makeWebSocketBuilder(spec: WebSocketHandler): WebSocketBuilder {\n const runtime: WebSocketBuilder = {\n onOpen: (fn) => makeWebSocketBuilder({ ...spec, onOpen: fn }),\n onMessage: (fn) => makeWebSocketBuilder({ ...spec, onMessage: fn }),\n onClose: (fn) => makeWebSocketBuilder({ ...spec, onClose: fn }),\n onError: (fn) => makeWebSocketBuilder({ ...spec, onError: fn }),\n build: () => defineWebSocket(spec),\n }\n return runtime\n}\n\n/** Start a fluent WebSocket definition. Chain any of the lifecycle hooks, then `.build()`. */\nexport function websocket(): WebSocketBuilder {\n return makeWebSocketBuilder({})\n}\n","export type MiddlewareHandler = (\n request: Request,\n next: (request: Request) => Promise<Response>,\n) => Response | Promise<Response>\n\n/**\n * Define a middleware handler.\n * Identity function — provides type annotation for middleware.\n */\nexport function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler {\n return handler\n}\n","/**\n * M31 Phase 3 — `middleware()`, the fluent builder that replaces `defineMiddleware(fn)`.\n *\n * A middleware IS a single function `(request, next) => Response`. The builder's `.handle()` sets it\n * (required); `.build()` delegates to the internal {@link defineMiddleware} (identity) and returns\n * the handler the runtime expects.\n *\n * export default middleware()\n * .handle(async (request, next) => {\n * const res = await next(request)\n * res.headers.set('x-mw', '1')\n * return res\n * })\n * .build()\n */\nimport { defineMiddleware, type MiddlewareHandler } from './define-middleware.js'\n\n/** Compile-error carrier: `.build()` called before `.handle()`. */\ninterface MissingHandleError {\n readonly __theokitError: 'middleware needs .handle(fn) before .build()'\n}\n\n/** The fluent middleware builder. `THandleSet` gates `.build()`. */\nexport interface MiddlewareBuilder<THandleSet extends boolean = false> {\n /** Set the `(request, next) => Response` handler. Required before `.build()`. */\n handle(fn: MiddlewareHandler): MiddlewareBuilder<true>\n /** Resolve to the `MiddlewareHandler`. COMPILE ERROR when `.handle()` was never called. */\n build(...guard: THandleSet extends true ? [] : [error: MissingHandleError]): MiddlewareHandler\n}\n\nfunction makeMiddlewareBuilder(fn: MiddlewareHandler | undefined): MiddlewareBuilder {\n const runtime = {\n handle: (handler: MiddlewareHandler) => makeMiddlewareBuilder(handler),\n build: (): MiddlewareHandler => {\n // Fail-fast for untyped (JS) callers — the type-state guard makes this unreachable from TS.\n if (fn === undefined) {\n throw new Error('middleware(): call .handle(fn) before .build()')\n }\n return defineMiddleware(fn)\n },\n }\n return runtime as unknown as MiddlewareBuilder\n}\n\n/** Start a fluent middleware definition. Chain `.handle()` (required), then `.build()`. */\nexport function middleware(): MiddlewareBuilder {\n return makeMiddlewareBuilder(undefined)\n}\n","/**\n * M31 Phase 1 — `tool()`, the fluent builder that replaces `defineAgentTool({...})`.\n *\n * Pure type-state (tRPC `UnsetMarker` technique, mirroring `agent-builder.ts`). The runtime is a\n * plain accumulator; `.build()` delegates to the internal {@link defineAgentTool}, so the emitted\n * `CustomTool` is byte-for-byte the legacy shape — the SDK/agent compile path is UNCHANGED\n * (identity-shape delegation, blueprint §2).\n *\n * PURE metadata (G2 / sdk-runtime.md): a tool describes a capability; it NEVER calls an LLM.\n *\n * tool('read')\n * .describe('Read a UTF-8 file')\n * .input(z.object({ path: z.string() }))\n * .execute(async ({ path }, ctx) => readFile(resolveInProject(ctx, path)))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport { defineAgentTool, type CustomTool, type ToolTransform } from './define-agent-tool.js'\n\n/** A required-but-unset builder field. Branded so no ordinary value satisfies it (tRPC UnsetMarker). */\ntype UnsetMarker = 'theokit.unset' & { readonly __brand: 'theokit.unset' }\n\n/** Compile-error carrier: `.execute()` called before `.input()`. */\ninterface MissingInputError {\n readonly __theokitError: 'call .input(schema) before .execute(handler)'\n}\n/** Compile-error carrier: `.build()` called before both `.input()` and `.execute()` are set. */\ninterface IncompleteToolError {\n readonly __theokitError: 'a tool needs .input(schema) and .execute(handler) before .build()'\n}\n\n/** The run context a tool handler receives (M7). */\ninterface ToolCtx {\n signal?: AbortSignal\n context?: unknown\n}\n\n/**\n * The fluent tool builder. Each method returns a NEW builder type with the relevant type parameter\n * advanced. `TInput` tracks the Zod schema (drives `execute` input inference); `R` tracks the\n * handler result; `THandlerSet` gates `.build()`.\n */\nexport interface ToolBuilder<\n TName extends string = string,\n TInput extends z.ZodType | UnsetMarker = UnsetMarker,\n R = string,\n THandlerSet extends boolean = false,\n> {\n /** Set the LLM-facing description. Optional; an empty description warns at build (LLM selection). */\n describe(description: string): ToolBuilder<TName, TInput, R, THandlerSet>\n /** Set the Zod input schema (must be `z.object(...)` at the root). Required before `.execute()`. */\n input<S extends z.ZodType>(schema: S): ToolBuilder<TName, S, R, THandlerSet>\n /**\n * Set the handler. COMPILE ERROR when `.input()` was not called first — the parameter type\n * collapses to {@link MissingInputError}. The `input` argument is inferred via `z.infer<TInput>`.\n */\n execute<R2>(\n handler: TInput extends z.ZodType\n ? (input: z.infer<TInput>, ctx?: ToolCtx) => R2 | Promise<R2>\n : MissingInputError,\n ): ToolBuilder<TName, TInput, R2, true>\n /** M18 — map a rich handler result to the model-visible string. */\n toModelOutput(fn: (result: R) => string): ToolBuilder<TName, TInput, R, THandlerSet>\n /** M18 — per-target formatters (`display` / `transcript`) for the app UI/transcript. */\n transform(t: ToolTransform<R>): ToolBuilder<TName, TInput, R, THandlerSet>\n /**\n * Resolve to the `CustomTool` — the SAME value `defineAgentTool({...})` returns. COMPILE ERROR\n * when `.input()` or `.execute()` was never called.\n */\n build(\n ...guard: THandlerSet extends true\n ? TInput extends z.ZodType\n ? []\n : [error: IncompleteToolError]\n : [error: IncompleteToolError]\n ): CustomTool\n}\n\ninterface ToolSpecAccumulator {\n name: string\n description?: string\n inputSchema?: z.ZodType\n handler?: (input: unknown, ctx?: ToolCtx) => unknown\n toModelOutput?: (result: unknown) => string\n transform?: ToolTransform\n}\n\n/**\n * Build the runtime accumulator. The public method signatures carry the type-state generics + the\n * compile-time guards; the runtime cannot track generics, so the object is bridged to the typed\n * interface once here (the single, documented type-state impl seam — same technique as agent-builder).\n */\nfunction makeToolBuilder(spec: ToolSpecAccumulator): ToolBuilder {\n const runtime = {\n describe: (description: string) => makeToolBuilder({ ...spec, description }),\n input: (schema: z.ZodType) => makeToolBuilder({ ...spec, inputSchema: schema }),\n execute: (handler: (input: unknown, ctx?: ToolCtx) => unknown) =>\n makeToolBuilder({ ...spec, handler }),\n toModelOutput: (fn: (result: unknown) => string) =>\n makeToolBuilder({ ...spec, toModelOutput: fn }),\n transform: (t: ToolTransform) => makeToolBuilder({ ...spec, transform: t }),\n build: (): CustomTool => {\n // Fail-fast: the type-state guards make these unreachable from typed callers, but an untyped\n // (JS) caller could skip them — surface a clear error instead of a confusing downstream one.\n if (spec.inputSchema === undefined) {\n throw new Error(`tool(${JSON.stringify(spec.name)}): call .input(schema) before .build()`)\n }\n if (spec.handler === undefined) {\n throw new Error(\n `tool(${JSON.stringify(spec.name)}): call .execute(handler) before .build()`,\n )\n }\n return defineAgentTool({\n name: spec.name,\n description: spec.description ?? '',\n inputSchema: spec.inputSchema,\n handler: spec.handler,\n ...(spec.toModelOutput !== undefined ? { toModelOutput: spec.toModelOutput } : {}),\n ...(spec.transform !== undefined ? { transform: spec.transform } : {}),\n })\n },\n }\n return runtime as unknown as ToolBuilder\n}\n\n/**\n * Start a fluent tool definition. Chain `.input()` + `.execute()` (both required), optionally\n * `.describe()` / `.toModelOutput()` / `.transform()`, then `.build()` for the `CustomTool`.\n */\nexport function tool<TName extends string>(name: TName): ToolBuilder<TName> {\n return makeToolBuilder({ name })\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nexport interface PluginContext {\n request: IncomingMessage\n response: ServerResponse\n ctx: Record<string, unknown>\n requestId: string\n}\n\nexport interface PluginErrorContext extends PluginContext {\n error: unknown\n}\n\nexport interface RunHookOptions {\n inErrorPath?: boolean\n}\n\nexport interface HookResult {\n shortCircuited: boolean\n}\n\nexport type OnRequestHook = (ctx: PluginContext) => void | Promise<void>\nexport type PreHandlerHook = (ctx: PluginContext) => void | Promise<void>\nexport type OnResponseHook = (ctx: PluginContext) => void | Promise<void>\nexport type OnErrorHook = (ctx: PluginErrorContext) => void | Promise<void>\n\nexport type HookName = 'onRequest' | 'preHandler' | 'onResponse' | 'onError'\n\nexport type HookByName<K extends HookName> = K extends 'onError'\n ? OnErrorHook\n : K extends 'onRequest'\n ? OnRequestHook\n : K extends 'preHandler'\n ? PreHandlerHook\n : K extends 'onResponse'\n ? OnResponseHook\n : never\n\nexport interface TheoApp {\n addHook<K extends HookName>(name: K, fn: HookByName<K>): void\n // `T` lets plugin authors document the per-key shape of decorations.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the value type for plugin authors\n decorateRequest<T>(key: string, value: T): void\n}\n\nexport interface TheoPlugin {\n name: string\n register(app: TheoApp): void | Promise<void>\n}\n\n/**\n * Identity function for plugin authors. Provides auto-completion + type\n * inference at the call site (TanStack/Vite/Astro pattern). Pure runtime\n * no-op — returns the input unchanged.\n *\n * @example\n * import { definePlugin } from 'theokit/server'\n * export default definePlugin({\n * name: 'my-plugin',\n * register(app) {\n * app.addHook('onRequest', (req) => { ... })\n * },\n * })\n *\n * Equivalent to `const p: TheoPlugin = {...}` but more ergonomic. See\n * ADR-0008 (D1 + D6) for the rationale.\n */\nexport function definePlugin(plugin: TheoPlugin): TheoPlugin {\n return plugin\n}\n\n// ===== T5a.2 Phase F slice 1/3 — Web-Standards plugin context types =====\n//\n// Mirror of the IncomingMessage/ServerResponse-shaped `PluginContext` for\n// the Web `Request`/`Headers` shape. Per `docs/plans/t5a2-incoming-message-\n// to-request-shape-refactor-plan.md` v1.0 § Phase F.\n//\n// **Key difference vs IncomingMessage path:** the Web path has no\n// `ServerResponse` to mutate. Plugins instead get a `responseHeaders: Headers`\n// instance they can append to (e.g., add Set-Cookie, CORS headers) and the\n// runtime composes the final `Response` after the hook chain runs. The\n// `response` object (if any) is the in-flight Response constructed by the\n// handler — present only during `onResponse` / `onError` hooks AFTER the\n// handler returned, NOT during `onRequest` / `preHandler` (which fire BEFORE\n// the handler runs).\n//\n// This split mirrors Hono's `c.res` + Fastify's `reply.headers` semantics\n// — plugins mutate headers freely; the body is the handler's responsibility.\n\n/**\n * Web-Standards plugin context. Available during all 4 hook lifecycle\n * stages (onRequest, preHandler, onResponse, onError).\n *\n * - `request` — the incoming Web Request (read-only at the runtime level;\n * plugins can call `request.headers.get()`, `request.clone()`, etc.).\n * - `responseHeaders` — a mutable `Headers` instance the runtime threads\n * through the hook chain. Plugins append (e.g., CORS, Set-Cookie); the\n * final Response composes these.\n * - `response` — set to the handler's Response AFTER the handler returns.\n * Available during `onResponse` / `onError`. `undefined` during\n * `onRequest` / `preHandler` (which fire before the handler runs).\n * - `ctx` / `requestId` — same semantics as the IncomingMessage path.\n */\nexport interface WebPluginContext {\n request: Request\n responseHeaders: Headers\n response?: Response\n ctx: Record<string, unknown>\n requestId: string\n}\n\nexport interface WebPluginErrorContext extends WebPluginContext {\n error: unknown\n}\n\nexport type WebOnRequestHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebPreHandlerHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebOnResponseHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebOnErrorHook = (ctx: WebPluginErrorContext) => void | Promise<void>\n\nexport type WebHookByName<K extends HookName> = K extends 'onError'\n ? WebOnErrorHook\n : K extends 'onRequest'\n ? WebOnRequestHook\n : K extends 'preHandler'\n ? WebPreHandlerHook\n : K extends 'onResponse'\n ? WebOnResponseHook\n : never\n\n/**\n * Web-Standards `TheoApp` facade. Same `addHook` + `decorateRequest`\n * surface as the IncomingMessage path; only the hook function signatures\n * differ (they receive `WebPluginContext` instead of `PluginContext`).\n *\n * Plugin authors who target both shapes can branch on the context type\n * via a type guard (`'responseHeaders' in ctx`) OR ship two separate\n * `register()` exports — one for each runtime adapter. Most plugins\n * register hooks at the IncomingMessage path today (legacy); future\n * Web-native plugins will register against `WebTheoApp`.\n */\nexport interface WebTheoApp {\n addHook<K extends HookName>(name: K, fn: WebHookByName<K>): void\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the value type for plugin authors\n decorateRequest<T>(key: string, value: T): void\n}\n\n/**\n * Web-Standards plugin shape. Identical to `TheoPlugin` except the\n * `register(app)` argument is `WebTheoApp` instead of `TheoApp`.\n *\n * Cross-runtime plugins ship BOTH `TheoPlugin` + `WebTheoPlugin` exports;\n * the adapter (Node, CF Workers, Bun, Deno) picks the matching one based\n * on which runtime executes the plugin chain. This is the canonical\n * Hono/Nitro pattern.\n */\nexport interface WebTheoPlugin {\n name: string\n register(app: WebTheoApp): void | Promise<void>\n}\n\n/**\n * Identity function for Web plugin authors — same auto-completion +\n * type-inference DX as `definePlugin`, but for the Web-shaped `WebTheoApp`.\n */\nexport function defineWebPlugin(plugin: WebTheoPlugin): WebTheoPlugin {\n return plugin\n}\n","/**\n * M31 Phase 3 — `plugin()`, the fluent builder that replaces `definePlugin({...})`.\n *\n * Collects lifecycle hooks + request decorations and SYNTHESIZES the `register(app)` function, so\n * authors never write the imperative `register` body. `.build()` returns a `TheoPlugin` the plugin\n * runner consumes UNCHANGED.\n *\n * export default plugin('request-id')\n * .onRequest((ctx) => { ctx.ctx.requestId = crypto.randomUUID() })\n * .onResponse((ctx) => { ctx.response.setHeader('x-request-id', String(ctx.ctx.requestId)) })\n * .build()\n */\nimport {\n definePlugin,\n type TheoPlugin,\n type TheoApp,\n type OnRequestHook,\n type PreHandlerHook,\n type OnResponseHook,\n type OnErrorHook,\n} from '../plugin-types.js'\n\n/** The fluent plugin builder. `name` is set at entry; every hook is optional and may repeat. */\nexport interface PluginBuilder {\n /** Register an `onRequest` hook (runs before the CSRF gate). May be called multiple times. */\n onRequest(fn: OnRequestHook): PluginBuilder\n /** Register a `preHandler` hook (after CSRF, before the route handler). */\n preHandler(fn: PreHandlerHook): PluginBuilder\n /** Register an `onResponse` hook (after the handler returns). */\n onResponse(fn: OnResponseHook): PluginBuilder\n /** Register an `onError` hook (error path). */\n onError(fn: OnErrorHook): PluginBuilder\n /** Decorate every request with a key/value pair (available on `ctx.ctx[key]`). */\n decorateRequest<T>(key: string, value: T): PluginBuilder\n /** Resolve to the `TheoPlugin` — a synthesized `{ name, register }` the runner consumes. */\n build(): TheoPlugin\n}\n\ninterface PluginSpecAccumulator {\n name: string\n onRequest: OnRequestHook[]\n preHandler: PreHandlerHook[]\n onResponse: OnResponseHook[]\n onError: OnErrorHook[]\n decorations: { key: string; value: unknown }[]\n}\n\nfunction makePluginBuilder(spec: PluginSpecAccumulator): PluginBuilder {\n const runtime: PluginBuilder = {\n onRequest: (fn) => makePluginBuilder({ ...spec, onRequest: [...spec.onRequest, fn] }),\n preHandler: (fn) => makePluginBuilder({ ...spec, preHandler: [...spec.preHandler, fn] }),\n onResponse: (fn) => makePluginBuilder({ ...spec, onResponse: [...spec.onResponse, fn] }),\n onError: (fn) => makePluginBuilder({ ...spec, onError: [...spec.onError, fn] }),\n decorateRequest: (key, value) =>\n makePluginBuilder({ ...spec, decorations: [...spec.decorations, { key, value }] }),\n build: () =>\n definePlugin({\n name: spec.name,\n register(app: TheoApp): void {\n for (const fn of spec.onRequest) app.addHook('onRequest', fn)\n for (const fn of spec.preHandler) app.addHook('preHandler', fn)\n for (const fn of spec.onResponse) app.addHook('onResponse', fn)\n for (const fn of spec.onError) app.addHook('onError', fn)\n for (const d of spec.decorations) app.decorateRequest(d.key, d.value)\n },\n }),\n }\n return runtime\n}\n\n/** Start a fluent plugin definition. `name` is required; chain hooks/decorations, then `.build()`. */\nexport function plugin(name: string): PluginBuilder {\n return makePluginBuilder({\n name,\n onRequest: [],\n preHandler: [],\n onResponse: [],\n onError: [],\n decorations: [],\n })\n}\n","import type { UIMessageChunk } from 'ai'\n\n/**\n * M0 (theokit-ai-first) — serialize a stream of ai-sdk `UIMessageChunk`s into a\n * Web-Standards `Response` on the UIMessageStream wire so `@ai-sdk/react`'s\n * `useChat` consumes it WITHOUT a custom adapter.\n *\n * Wire contract (must match ai-sdk's consumer transport exactly):\n * - `content-type: text/event-stream`\n * - `x-vercel-ai-ui-message-stream: v1` — the version marker `useChat` checks\n * - each chunk framed as `data: ${JSON.stringify(chunk)}\\n\\n`\n * - a terminal `data: [DONE]\\n\\n` after the last chunk (ignored by the parser)\n *\n * Web Standards only — `Response` + `ReadableStream` (G8, no node:http). The\n * headers commit before the stream starts.\n *\n * Fail-clear (error-handling.md): if the source iterable throws mid-stream, the\n * `[DONE]` terminal is still flushed and the stream is closed — never left\n * hanging. (The translator upstream already closes gracefully; this is defense\n * in depth for any other chunk source.)\n */\nconst UI_MESSAGE_STREAM_HEADERS = {\n 'content-type': 'text/event-stream',\n 'x-vercel-ai-ui-message-stream': 'v1',\n} as const\n\nconst DONE_FRAME = 'data: [DONE]\\n\\n'\n\nfunction encode(text: string): Uint8Array {\n return new TextEncoder().encode(text)\n}\n\nexport function uiMessageStreamResponse(chunks: AsyncIterable<UIMessageChunk>): Response {\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n try {\n for await (const chunk of chunks) {\n controller.enqueue(encode(`data: ${JSON.stringify(chunk)}\\n\\n`))\n }\n } catch {\n // The source iterable aborted mid-stream. The upstream translator owns\n // error semantics (it surfaces failures as chunks + closes gracefully);\n // this transport's sole guarantee is a terminated stream — fall through\n // to the DONE terminal rather than re-throw and error an open stream.\n } finally {\n controller.enqueue(encode(DONE_FRAME))\n controller.close()\n }\n },\n })\n return new Response(stream, { headers: UI_MESSAGE_STREAM_HEADERS })\n}\n","import type { IncomingMessage } from 'node:http'\n\nimport type { WebSocketLike } from './define-websocket.js'\n\nexport interface ChannelHandler<TMessage = unknown> {\n onSubscribe?: (ws: WebSocketLike, room: string, req: IncomingMessage) => void\n onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void\n onUnsubscribe?: (ws: WebSocketLike, room: string) => void\n}\n\n/**\n * Define a channel handler for WebSocket rooms.\n * Identity function — provides type inference for channel handlers.\n */\nexport function defineChannel<TMessage = unknown>(\n handler: ChannelHandler<TMessage>,\n): ChannelHandler<TMessage> {\n return handler\n}\n\n/**\n * T5a.2 Phase F slice 2/3 — Web-Standards channel handler.\n *\n * Mirror of `ChannelHandler<TMessage>` for the Web `Request` shape.\n * `onSubscribe` receives `request: Request` instead of `req: IncomingMessage`\n * — the rest of the surface (onMessage, onUnsubscribe) is shape-agnostic\n * (WebSocketLike is already Web-standards-compatible per `define-websocket.ts`).\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase F.\n *\n * **Architectural note:** WebSocket upgrade semantics differ across\n * runtimes:\n * - Node: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —\n * hands you `req: IncomingMessage` at the upgrade handshake.\n * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade\n * handshake IS a Web Request) — hands you `request: Request`.\n * - Bun: `server.upgrade(request, { data })` — same Web Request shape.\n * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.\n *\n * Channel handlers targeting CF/Bun/Deno use `WebChannelHandler`; legacy\n * Node consumers stay on `ChannelHandler`. Cross-runtime channels ship\n * both shapes.\n */\nexport interface WebChannelHandler<TMessage = unknown> {\n onSubscribe?: (ws: WebSocketLike, room: string, request: Request) => void\n onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void\n onUnsubscribe?: (ws: WebSocketLike, room: string) => void\n}\n\n/**\n * Web-Standards `defineChannel` sibling. Identity function — provides\n * type inference for Web channel handlers.\n */\nexport function defineWebChannel<TMessage = unknown>(\n handler: WebChannelHandler<TMessage>,\n): WebChannelHandler<TMessage> {\n return handler\n}\n"],"mappings":";;;;;AAaO,SAAS,YAOd,QACsD;AACtD,SAAO;AACT;;;ACuEA,SAAS,iBAAiB,MAA0C;AAClE,QAAM,UAAU;AAAA,IACd,OAAO,CAAC,WAAsB,iBAAiB,EAAE,GAAG,MAAM,OAAO,OAAO,CAAC;AAAA,IACzE,MAAM,CAAC,WAAsB,iBAAiB,EAAE,GAAG,MAAM,MAAM,OAAO,CAAC;AAAA,IACvE,QAAQ,CAAC,WAAsB,iBAAiB,EAAE,GAAG,MAAM,QAAQ,OAAO,CAAC;AAAA,IAC3E,UAAU,CAAC,WAAsB,iBAAiB,EAAE,GAAG,MAAM,UAAU,OAAO,CAAC;AAAA,IAC/E,QAAQ,CAAC,SAAiB,iBAAiB,EAAE,GAAG,MAAM,QAAQ,KAAK,CAAC;AAAA,IACpE,MAAM,CAAC,aAAoB,iBAAiB,EAAE,GAAG,MAAM,MAAM,SAAS,CAAC;AAAA,IACvE,SAAS,CAAC,OAAkC,iBAAiB,EAAE,GAAG,MAAM,SAAS,GAAG,CAAC;AAAA,IACrF,OAAO,MAAsB;AAE3B,UAAI,KAAK,YAAY,QAAW;AAC9B,cAAM,IAAI,MAAM,4CAA4C;AAAA,MAC9D;AACA,YAAM,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C;AAEO,SAAS,wBAAwB,QAAiD;AACvF,QAAM,SAAS,IAAI,eAA2B;AAAA,IAC5C,MAAM,MAAM,YAAY;AACtB,UAAI;AACF,yBAAiB,SAAS,QAAQ;AAChC,qBAAW,QAAQ,OAAO,SAAS,KAAK,UAAU,KAAK,CAAC;AAAA;AAAA,CAAM,CAAC;AAAA,QACjE;AAAA,MACF,QAAQ;AAAA,MAKR,UAAE;AACA,mBAAW,QAAQ,OAAO,UAAU,CAAC;AACrC,mBAAW,MAAM;AAAA,MACnB;AAAA,IACF;AAAA,EACF,CAAC;AACD,SAAO,IAAI,SAAS,QAAQ,EAAE,SAAS,0BAA0B,CAAC;AACpE;;;ACrCO,SAAS,cACd,SAC0B;AAC1B,SAAO;AACT;AAoCO,SAAS,iBACd,SAC6B;AAC7B,SAAO;AACT;","names":["plugin"]}
|
|
1
|
+
{"version":3,"sources":["../src/server/define/define-route.ts","../src/server/define/route-builder.ts","../src/server/define/define-action.ts","../src/server/define/action-builder.ts","../src/server/define/define-websocket.ts","../src/server/define/websocket-builder.ts","../src/server/define/define-middleware.ts","../src/server/define/middleware-builder.ts","../src/server/define/tool-builder.ts","../src/server/plugin-types.ts","../src/server/define/plugin-builder.ts","../src/server/define/ui-message-stream-response.ts","../src/server/define/define-channel.ts"],"sourcesContent":["import type { z } from 'zod'\n\n// T2.2 (architecture-cleanup) — RouteConfig type moved to core/contracts/\n// (canonical home per ADR-0001 v3). Re-export preserves the public path\n// `import { type RouteConfig } from 'theokit/server'`.\nexport type { RouteConfig } from '../../core/contracts/route-config.js'\n\nimport type { RouteConfig } from '../../core/contracts/route-config.js'\n\n/**\n * Define a typed HTTP route.\n * Identity function — provides type inference for route handlers.\n */\nexport function defineRoute<\n TQuery extends z.ZodType = z.ZodUndefined,\n TBody extends z.ZodType = z.ZodUndefined,\n TParams extends z.ZodType = z.ZodUndefined,\n TCtx = unknown,\n TResponse = unknown,\n>(\n config: RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>,\n): RouteConfig<TQuery, TBody, TParams, TCtx, TResponse> {\n return config\n}\n","/**\n * M31 Phase 3 — `route()`, the fluent builder that replaces `defineRoute({...})`.\n *\n * Pure type-state (mirrors `tool-builder.ts`). `.query/.body/.params` set Zod schemas whose\n * `z.infer<>` flows into the handler's `ctx`; `.handler()` is required before `.build()`. `.build()`\n * delegates to the internal {@link defineRoute} (an identity fn), emitting the identical\n * `RouteConfig` — the scan/execute path is UNCHANGED (identity-shape delegation, blueprint §2).\n *\n * export const POST = route()\n * .params(z.object({ id: z.string() }))\n * .body(z.object({ text: z.string() }))\n * .handler(({ params, body }) => save(params.id, body.text))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport type { RouteConfig } from '../../core/contracts/route-config.js'\n\nimport { defineRoute } from './define-route.js'\n\n/** Compile-error carrier: `.build()` called before `.handler()`. */\ninterface MissingHandlerError {\n readonly __theokitError: 'a route needs .handler(fn) before .build()'\n}\n\n/**\n * The fluent route builder. `TQuery/TBody/TParams` track the input schemas (default `z.ZodUndefined`,\n * matching {@link RouteConfig}); `TResponse` tracks the handler return; `THandlerSet` gates `.build()`.\n */\nexport interface RouteBuilder<\n TQuery extends z.ZodType = z.ZodUndefined,\n TBody extends z.ZodType = z.ZodUndefined,\n TParams extends z.ZodType = z.ZodUndefined,\n TCtx = unknown,\n TResponse = unknown,\n THandlerSet extends boolean = false,\n> {\n /** Set the URL search-params schema. Inferred into `ctx.query`. */\n query<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<S, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Set the request-body schema. Inferred into `ctx.body`. */\n body<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<TQuery, S, TParams, TCtx, TResponse, THandlerSet>\n /** Set the path-params schema. Inferred into `ctx.params`. */\n params<S extends z.ZodType>(\n schema: S,\n ): RouteBuilder<TQuery, TBody, S, TCtx, TResponse, THandlerSet>\n /** Runtime-only validation of the handler's plain-object return (500 on mismatch). Not inferred (YAGNI). */\n response(schema: z.ZodType): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Override the HTTP status for a plain-object return (default 200; 204 for void). */\n status(code: number): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /** Opt out of CSRF enforcement for this route (webhooks / OAuth callbacks). */\n csrf(disabled: false): RouteBuilder<TQuery, TBody, TParams, TCtx, TResponse, THandlerSet>\n /**\n * Set the handler. Its `ctx` infers `query/body/params` from the schemas set above. Required\n * before `.build()`.\n */\n handler<R>(\n fn: (ctx: {\n query: z.infer<TQuery>\n body: z.infer<TBody>\n params: z.infer<TParams>\n request: Request\n ctx: TCtx\n }) => R | Promise<R>,\n ): RouteBuilder<TQuery, TBody, TParams, TCtx, R, true>\n /**\n * Resolve to the `RouteConfig` — the SAME value `defineRoute({...})` returns. COMPILE ERROR when\n * `.handler()` was never called.\n */\n build(\n ...guard: THandlerSet extends true ? [] : [error: MissingHandlerError]\n ): RouteConfig<TQuery, TBody, TParams, TCtx, TResponse>\n}\n\n/**\n * Permissive internal shape — the runtime seam works with `z.ZodType` schemas (ctx fields typed\n * `unknown`); the precise per-schema types are carried to callers by the {@link RouteBuilder}\n * interface via the `as unknown as RouteBuilder` bridge. `defineRoute` is an identity fn.\n */\ntype AnyRouteConfig = RouteConfig<z.ZodType, z.ZodType, z.ZodType>\n\ninterface RouteSpecAccumulator {\n query?: z.ZodType\n body?: z.ZodType\n params?: z.ZodType\n response?: z.ZodType\n status?: number\n csrf?: false\n handler?: AnyRouteConfig['handler']\n}\n\nfunction makeRouteBuilder(spec: RouteSpecAccumulator): RouteBuilder {\n const runtime = {\n query: (schema: z.ZodType) => makeRouteBuilder({ ...spec, query: schema }),\n body: (schema: z.ZodType) => makeRouteBuilder({ ...spec, body: schema }),\n params: (schema: z.ZodType) => makeRouteBuilder({ ...spec, params: schema }),\n response: (schema: z.ZodType) => makeRouteBuilder({ ...spec, response: schema }),\n status: (code: number) => makeRouteBuilder({ ...spec, status: code }),\n csrf: (disabled: false) => makeRouteBuilder({ ...spec, csrf: disabled }),\n handler: (fn: AnyRouteConfig['handler']) => makeRouteBuilder({ ...spec, handler: fn }),\n build: (): AnyRouteConfig => {\n // Fail-fast for untyped (JS) callers — the type-state guard makes this unreachable from TS.\n if (spec.handler === undefined) {\n throw new Error('route(): call .handler(fn) before .build()')\n }\n const config: AnyRouteConfig = {\n ...(spec.query !== undefined ? { query: spec.query } : {}),\n ...(spec.body !== undefined ? { body: spec.body } : {}),\n ...(spec.params !== undefined ? { params: spec.params } : {}),\n ...(spec.response !== undefined ? { response: spec.response } : {}),\n ...(spec.status !== undefined ? { status: spec.status } : {}),\n ...(spec.csrf !== undefined ? { csrf: spec.csrf } : {}),\n handler: spec.handler,\n }\n return defineRoute(config)\n },\n }\n return runtime as unknown as RouteBuilder\n}\n\n/**\n * Start a fluent route definition. Chain `.query/.body/.params/.response/.status/.csrf` (all\n * optional), then `.handler()` (required) and `.build()` for the `RouteConfig`.\n */\nexport function route(): RouteBuilder {\n return makeRouteBuilder({})\n}\n","import type { z } from 'zod'\n\n/**\n * Action wire-protocol accept mode per plan g3-server-actions-and-useaction\n * v1.2 ADR D1. Default behavior (when omitted) is `'json'`. `'form'` opts the\n * action into FormData multipart parsing for progressive-enhancement forms;\n * the runtime in `server/http/action-execute.ts` will coerce FormData entries\n * against the `input` schema via `formDataToObject` (Astro pattern).\n */\nexport type ActionAccept = 'form' | 'json'\n\nexport interface ActionConfig<TInput extends z.ZodType, TCtx = unknown> {\n /**\n * Zod input schema. Required: every action declares its input contract via\n * Zod (architecture rule: zod-is-SSOT). The shape becomes the handler's\n * typed `input` parameter via `z.infer<TInput>`.\n */\n input: TInput\n /**\n * Wire-protocol accept mode. Defaults to `'json'` when omitted. Setting\n * `'form'` switches the runtime to FormData multipart parsing — the input\n * schema MUST be `z.object(...)` so field-by-field coercion can drive\n * boolean string / number / array coercion (Astro pattern).\n */\n accept?: ActionAccept\n /**\n * Opt OUT of CSRF enforcement for this action. Default (omitted) keeps the\n * multi-header CSRF gate active. Set `false` for endpoints intentionally\n * callable without the `X-Theo-Action` header (e.g. public webhooks). The\n * runtime in `server/http/action-execute.ts` reads this flag.\n */\n csrf?: false\n handler: (ctx: { input: z.infer<TInput>; ctx: TCtx }) => unknown\n}\n\n/**\n * Define a typed server action.\n *\n * Identity function — provides type inference for action handlers. The\n * runtime that consumes the config (validation + invocation + serialization)\n * lives in `server/http/action-execute.ts`.\n *\n * Per plan g3-server-actions-and-useaction v1.2 § Phase 1 / T1.2: the new\n * `accept?: 'form' | 'json'` field is the only contract change vs the\n * pre-G3 identity. Existing callsites (`defineAction({input, handler})`)\n * continue to compile — `accept` is opt-in.\n */\nexport function defineAction<TInput extends z.ZodType, TCtx = unknown>(\n config: ActionConfig<TInput, TCtx>,\n): ActionConfig<TInput, TCtx> {\n return config\n}\n","/**\n * M31 Phase 3 — `action()`, the fluent builder that replaces `defineAction({...})`.\n *\n * Pure type-state (mirrors `route-builder.ts`). `.input()` (required) sets the Zod schema whose\n * `z.infer<>` types the handler's `ctx.input`; `.handler()` (required) closes the chain. `.build()`\n * delegates to the internal {@link defineAction} (identity) — the action-execute path is UNCHANGED.\n *\n * export const createUser = action()\n * .input(z.object({ email: z.string().email() }))\n * .handler(({ input }) => createUser(input.email))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport { defineAction, type ActionConfig, type ActionAccept } from './define-action.js'\n\n/** Compile-error carrier: `.execute`/`.build()` reached before `.input()`. */\ninterface MissingInputError {\n readonly __theokitError: 'call .input(schema) before .handler(fn)'\n}\n/** Compile-error carrier: `.build()` before both `.input()` and `.handler()` are set. */\ninterface IncompleteActionError {\n readonly __theokitError: 'an action needs .input(schema) and .handler(fn) before .build()'\n}\n\n/** A required-but-unset field. Branded so no ordinary value satisfies it (tRPC UnsetMarker). */\ntype UnsetMarker = 'theokit.unset' & { readonly __brand: 'theokit.unset' }\n\n/**\n * The fluent action builder. `TInput` tracks the Zod schema (drives `ctx.input` inference);\n * `THandlerSet` gates `.build()`.\n */\nexport interface ActionBuilder<\n TInput extends z.ZodType | UnsetMarker = UnsetMarker,\n TCtx = unknown,\n THandlerSet extends boolean = false,\n> {\n /** Set the Zod input schema. Required — every action declares its input contract (zod-is-SSOT). */\n input<S extends z.ZodType>(schema: S): ActionBuilder<S, TCtx, THandlerSet>\n /** Wire-protocol accept mode (`'json'` default, `'form'` for FormData multipart). */\n accept(mode: ActionAccept): ActionBuilder<TInput, TCtx, THandlerSet>\n /** Opt out of CSRF enforcement for this action. */\n csrf(disabled: false): ActionBuilder<TInput, TCtx, THandlerSet>\n /**\n * Set the handler. COMPILE ERROR before `.input()` — the param type collapses to\n * {@link MissingInputError}. `ctx.input` is inferred via `z.infer<TInput>`.\n */\n handler(\n fn: TInput extends z.ZodType\n ? (ctx: { input: z.infer<TInput>; ctx: TCtx }) => unknown\n : MissingInputError,\n ): ActionBuilder<TInput, TCtx, true>\n /**\n * Resolve to the `ActionConfig` — the SAME value `defineAction({...})` returns. COMPILE ERROR when\n * `.input()` or `.handler()` was never called.\n */\n build(\n ...guard: THandlerSet extends true\n ? TInput extends z.ZodType\n ? []\n : [error: IncompleteActionError]\n : [error: IncompleteActionError]\n ): ActionConfig<TInput extends z.ZodType ? TInput : z.ZodType, TCtx>\n}\n\ntype AnyActionConfig = ActionConfig<z.ZodType>\n\ninterface ActionSpecAccumulator {\n input?: z.ZodType\n accept?: ActionAccept\n csrf?: false\n handler?: AnyActionConfig['handler']\n}\n\nfunction makeActionBuilder(spec: ActionSpecAccumulator): ActionBuilder {\n const runtime = {\n input: (schema: z.ZodType) => makeActionBuilder({ ...spec, input: schema }),\n accept: (mode: ActionAccept) => makeActionBuilder({ ...spec, accept: mode }),\n csrf: (disabled: false) => makeActionBuilder({ ...spec, csrf: disabled }),\n handler: (fn: AnyActionConfig['handler']) => makeActionBuilder({ ...spec, handler: fn }),\n build: (): AnyActionConfig => {\n // Fail-fast for untyped (JS) callers — the type-state guards make this unreachable from TS.\n if (spec.input === undefined) {\n throw new Error('action(): call .input(schema) before .build()')\n }\n if (spec.handler === undefined) {\n throw new Error('action(): call .handler(fn) before .build()')\n }\n const config: AnyActionConfig = {\n input: spec.input,\n handler: spec.handler,\n ...(spec.accept !== undefined ? { accept: spec.accept } : {}),\n ...(spec.csrf !== undefined ? { csrf: spec.csrf } : {}),\n }\n return defineAction(config)\n },\n }\n return runtime as unknown as ActionBuilder\n}\n\n/**\n * Start a fluent action definition. Chain `.input()` (required), optionally `.accept()` / `.csrf()`,\n * then `.handler()` (required) and `.build()` for the `ActionConfig`.\n */\nexport function action(): ActionBuilder {\n return makeActionBuilder({})\n}\n","import type { IncomingMessage } from 'node:http'\n\nexport interface WebSocketLike {\n send(data: string | Buffer): void\n close(code?: number, reason?: string): void\n}\n\nexport interface WebSocketHandler {\n onOpen?: (ws: WebSocketLike, req: IncomingMessage) => void\n onMessage?: (ws: WebSocketLike, data: string | Buffer) => void\n onClose?: (ws: WebSocketLike, code: number, reason: Buffer) => void\n onError?: (ws: WebSocketLike, error: Error) => void\n}\n\n/**\n * Define a WebSocket endpoint handler.\n * Identity function — provides type inference for WebSocket handlers.\n */\nexport function defineWebSocket(handler: WebSocketHandler): WebSocketHandler {\n return handler\n}\n\n/**\n * T5a.2 Phase F slice 3/3 — Web-Standards WebSocket endpoint handler.\n *\n * Mirror of `WebSocketHandler` for the Web `Request` shape. `onOpen`\n * receives `request: Request` instead of `req: IncomingMessage`. The\n * rest of the lifecycle (onMessage, onClose, onError) is shape-agnostic\n * (`WebSocketLike` is already Web-standards-compatible per the existing\n * design — `send(string | Buffer)` works on both Node `ws` and Web\n * `WebSocket` instances; CF Workers / Bun / Deno coerce as needed at\n * the adapter boundary).\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase F (closes Phase F).\n *\n * **Architectural note — WebSocket upgrade semantics differ across runtimes:**\n * - Node + `ws`: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —\n * `req` is `IncomingMessage`. Use `WebSocketHandler`.\n * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade\n * handshake IS a Web Request). Use `WebSocketHandlerWeb`.\n * - Bun: `server.upgrade(request, { data })` — same Web Request shape.\n * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.\n *\n * Cross-runtime WebSocket endpoints ship BOTH `WebSocketHandler` +\n * `WebSocketHandlerWeb` exports; the runtime adapter picks the matching\n * one. This is the canonical Hono / Nitric pattern.\n */\nexport interface WebSocketHandlerWeb {\n onOpen?: (ws: WebSocketLike, request: Request) => void\n onMessage?: (ws: WebSocketLike, data: string | Uint8Array) => void\n onClose?: (ws: WebSocketLike, code: number, reason: string) => void\n onError?: (ws: WebSocketLike, error: Error) => void\n}\n\n/**\n * Web-Standards `defineWebSocket` sibling. Identity function — provides\n * type inference for Web WebSocket handlers.\n *\n * **Type difference note vs Node path:**\n * - `onMessage` data is `string | Uint8Array` instead of `string | Buffer`\n * (Web standards have no `Buffer`; Node's Buffer is a Uint8Array\n * subclass so the Node path's Buffer values flow through unchanged\n * when adapters wrap them).\n * - `onClose` reason is `string` instead of `Buffer` (Web `CloseEvent`\n * exposes the reason as a UTF-8 string natively).\n */\nexport function defineWebSocketWeb(handler: WebSocketHandlerWeb): WebSocketHandlerWeb {\n return handler\n}\n","/**\n * M31 Phase 3 — `websocket()`, the fluent builder that replaces `defineWebSocket({...})`.\n *\n * Lifecycle setters (`onOpen/onMessage/onClose/onError`), all optional; `.build()` delegates to the\n * internal {@link defineWebSocket} (identity) — the ws handler loading path is UNCHANGED.\n *\n * export default websocket()\n * .onOpen((ws) => ws.send('hi'))\n * .onMessage((ws, data) => ws.send(`echo:${data}`))\n * .build()\n */\nimport { defineWebSocket, type WebSocketHandler } from './define-websocket.js'\n\n/** The fluent WebSocket builder. Each lifecycle hook is optional; `.build()` returns the handler. */\nexport interface WebSocketBuilder {\n onOpen(fn: NonNullable<WebSocketHandler['onOpen']>): WebSocketBuilder\n onMessage(fn: NonNullable<WebSocketHandler['onMessage']>): WebSocketBuilder\n onClose(fn: NonNullable<WebSocketHandler['onClose']>): WebSocketBuilder\n onError(fn: NonNullable<WebSocketHandler['onError']>): WebSocketBuilder\n /** Resolve to the `WebSocketHandler` — the SAME value `defineWebSocket({...})` returns. */\n build(): WebSocketHandler\n}\n\nfunction makeWebSocketBuilder(spec: WebSocketHandler): WebSocketBuilder {\n const runtime: WebSocketBuilder = {\n onOpen: (fn) => makeWebSocketBuilder({ ...spec, onOpen: fn }),\n onMessage: (fn) => makeWebSocketBuilder({ ...spec, onMessage: fn }),\n onClose: (fn) => makeWebSocketBuilder({ ...spec, onClose: fn }),\n onError: (fn) => makeWebSocketBuilder({ ...spec, onError: fn }),\n build: () => defineWebSocket(spec),\n }\n return runtime\n}\n\n/** Start a fluent WebSocket definition. Chain any of the lifecycle hooks, then `.build()`. */\nexport function websocket(): WebSocketBuilder {\n return makeWebSocketBuilder({})\n}\n","export type MiddlewareHandler = (\n request: Request,\n next: (request: Request) => Promise<Response>,\n) => Response | Promise<Response>\n\n/**\n * Define a middleware handler.\n * Identity function — provides type annotation for middleware.\n */\nexport function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler {\n return handler\n}\n","/**\n * M31 Phase 3 — `middleware()`, the fluent builder that replaces `defineMiddleware(fn)`.\n *\n * A middleware IS a single function `(request, next) => Response`. The builder's `.handle()` sets it\n * (required); `.build()` delegates to the internal {@link defineMiddleware} (identity) and returns\n * the handler the runtime expects.\n *\n * export default middleware()\n * .handle(async (request, next) => {\n * const res = await next(request)\n * res.headers.set('x-mw', '1')\n * return res\n * })\n * .build()\n */\nimport { defineMiddleware, type MiddlewareHandler } from './define-middleware.js'\n\n/** Compile-error carrier: `.build()` called before `.handle()`. */\ninterface MissingHandleError {\n readonly __theokitError: 'middleware needs .handle(fn) before .build()'\n}\n\n/** The fluent middleware builder. `THandleSet` gates `.build()`. */\nexport interface MiddlewareBuilder<THandleSet extends boolean = false> {\n /** Set the `(request, next) => Response` handler. Required before `.build()`. */\n handle(fn: MiddlewareHandler): MiddlewareBuilder<true>\n /** Resolve to the `MiddlewareHandler`. COMPILE ERROR when `.handle()` was never called. */\n build(...guard: THandleSet extends true ? [] : [error: MissingHandleError]): MiddlewareHandler\n}\n\nfunction makeMiddlewareBuilder(fn: MiddlewareHandler | undefined): MiddlewareBuilder {\n const runtime = {\n handle: (handler: MiddlewareHandler) => makeMiddlewareBuilder(handler),\n build: (): MiddlewareHandler => {\n // Fail-fast for untyped (JS) callers — the type-state guard makes this unreachable from TS.\n if (fn === undefined) {\n throw new Error('middleware(): call .handle(fn) before .build()')\n }\n return defineMiddleware(fn)\n },\n }\n return runtime as unknown as MiddlewareBuilder\n}\n\n/** Start a fluent middleware definition. Chain `.handle()` (required), then `.build()`. */\nexport function middleware(): MiddlewareBuilder {\n return makeMiddlewareBuilder(undefined)\n}\n","/**\n * M31 Phase 1 — `tool()`, the fluent builder that replaces `defineAgentTool({...})`.\n *\n * Pure type-state (tRPC `UnsetMarker` technique, mirroring `agent-builder.ts`). The runtime is a\n * plain accumulator; `.build()` delegates to the internal {@link defineAgentTool}, so the emitted\n * `CustomTool` is byte-for-byte the legacy shape — the SDK/agent compile path is UNCHANGED\n * (identity-shape delegation, blueprint §2).\n *\n * PURE metadata (G2 / sdk-runtime.md): a tool describes a capability; it NEVER calls an LLM.\n *\n * tool('read')\n * .describe('Read a UTF-8 file')\n * .input(z.object({ path: z.string() }))\n * .execute(async ({ path }, ctx) => readFile(resolveInProject(ctx, path)))\n * .build()\n */\nimport type { z } from 'zod'\n\nimport { defineAgentTool, type CustomTool, type ToolTransform } from './define-agent-tool.js'\n\n/** A required-but-unset builder field. Branded so no ordinary value satisfies it (tRPC UnsetMarker). */\ntype UnsetMarker = 'theokit.unset' & { readonly __brand: 'theokit.unset' }\n\n/** Compile-error carrier: `.execute()` called before `.input()`. */\ninterface MissingInputError {\n readonly __theokitError: 'call .input(schema) before .execute(handler)'\n}\n/** Compile-error carrier: `.build()` called before both `.input()` and `.execute()` are set. */\ninterface IncompleteToolError {\n readonly __theokitError: 'a tool needs .input(schema) and .execute(handler) before .build()'\n}\n\n/** The run context a tool handler receives (M7). */\ninterface ToolCtx {\n signal?: AbortSignal\n context?: unknown\n}\n\n/**\n * The fluent tool builder. Each method returns a NEW builder type with the relevant type parameter\n * advanced. `TInput` tracks the Zod schema (drives `execute` input inference); `R` tracks the\n * handler result; `THandlerSet` gates `.build()`.\n */\nexport interface ToolBuilder<\n TName extends string = string,\n TInput extends z.ZodType | UnsetMarker = UnsetMarker,\n R = string,\n THandlerSet extends boolean = false,\n> {\n /** Set the LLM-facing description. Optional; an empty description warns at build (LLM selection). */\n describe(description: string): ToolBuilder<TName, TInput, R, THandlerSet>\n /** Set the Zod input schema (must be `z.object(...)` at the root). Required before `.execute()`. */\n input<S extends z.ZodType>(schema: S): ToolBuilder<TName, S, R, THandlerSet>\n /**\n * Set the handler. COMPILE ERROR when `.input()` was not called first — the parameter type\n * collapses to {@link MissingInputError}. The `input` argument is inferred via `z.infer<TInput>`.\n */\n execute<R2>(\n handler: TInput extends z.ZodType\n ? (input: z.infer<TInput>, ctx?: ToolCtx) => R2 | Promise<R2>\n : MissingInputError,\n ): ToolBuilder<TName, TInput, R2, true>\n /** M18 — map a rich handler result to the model-visible string. */\n toModelOutput(fn: (result: R) => string): ToolBuilder<TName, TInput, R, THandlerSet>\n /** M18 — per-target formatters (`display` / `transcript`) for the app UI/transcript. */\n transform(t: ToolTransform<R>): ToolBuilder<TName, TInput, R, THandlerSet>\n /**\n * Resolve to the `CustomTool` — the SAME value `defineAgentTool({...})` returns. COMPILE ERROR\n * when `.input()` or `.execute()` was never called.\n */\n build(\n ...guard: THandlerSet extends true\n ? TInput extends z.ZodType\n ? []\n : [error: IncompleteToolError]\n : [error: IncompleteToolError]\n ): CustomTool\n}\n\ninterface ToolSpecAccumulator {\n name: string\n description?: string\n inputSchema?: z.ZodType\n handler?: (input: unknown, ctx?: ToolCtx) => unknown\n toModelOutput?: (result: unknown) => string\n transform?: ToolTransform\n}\n\n/**\n * Build the runtime accumulator. The public method signatures carry the type-state generics + the\n * compile-time guards; the runtime cannot track generics, so the object is bridged to the typed\n * interface once here (the single, documented type-state impl seam — same technique as agent-builder).\n */\nfunction makeToolBuilder(spec: ToolSpecAccumulator): ToolBuilder {\n const runtime = {\n describe: (description: string) => makeToolBuilder({ ...spec, description }),\n input: (schema: z.ZodType) => makeToolBuilder({ ...spec, inputSchema: schema }),\n execute: (handler: (input: unknown, ctx?: ToolCtx) => unknown) =>\n makeToolBuilder({ ...spec, handler }),\n toModelOutput: (fn: (result: unknown) => string) =>\n makeToolBuilder({ ...spec, toModelOutput: fn }),\n transform: (t: ToolTransform) => makeToolBuilder({ ...spec, transform: t }),\n build: (): CustomTool => {\n // Fail-fast: the type-state guards make these unreachable from typed callers, but an untyped\n // (JS) caller could skip them — surface a clear error instead of a confusing downstream one.\n if (spec.inputSchema === undefined) {\n throw new Error(`tool(${JSON.stringify(spec.name)}): call .input(schema) before .build()`)\n }\n if (spec.handler === undefined) {\n throw new Error(\n `tool(${JSON.stringify(spec.name)}): call .execute(handler) before .build()`,\n )\n }\n return defineAgentTool({\n name: spec.name,\n description: spec.description ?? '',\n inputSchema: spec.inputSchema,\n handler: spec.handler,\n ...(spec.toModelOutput !== undefined ? { toModelOutput: spec.toModelOutput } : {}),\n ...(spec.transform !== undefined ? { transform: spec.transform } : {}),\n })\n },\n }\n return runtime as unknown as ToolBuilder\n}\n\n/**\n * Start a fluent tool definition. Chain `.input()` + `.execute()` (both required), optionally\n * `.describe()` / `.toModelOutput()` / `.transform()`, then `.build()` for the `CustomTool`.\n */\nexport function tool<TName extends string>(name: TName): ToolBuilder<TName> {\n return makeToolBuilder({ name })\n}\n","import type { ServerResponse } from 'node:http'\n\nexport interface PluginContext {\n /**\n * The incoming request as a Web `Request` — the same shape a plugin hook sees on the edge adapters\n * (`WebPluginContext.request`), so a hook that reads `request.headers.get(...)` / `request.url` /\n * `request.method` is portable across `theokit dev` / `theokit start` (Node) and Web runtimes (#119,\n * ADR-0028 R3a). Method + absolute URL + headers; the request body is not exposed here (onRequest /\n * preHandler fire before the body is parsed — the handler reads it via `ctx.body`).\n */\n request: Request\n response: ServerResponse\n ctx: Record<string, unknown>\n requestId: string\n}\n\nexport interface PluginErrorContext extends PluginContext {\n error: unknown\n}\n\nexport interface RunHookOptions {\n inErrorPath?: boolean\n}\n\nexport interface HookResult {\n shortCircuited: boolean\n}\n\nexport type OnRequestHook = (ctx: PluginContext) => void | Promise<void>\nexport type PreHandlerHook = (ctx: PluginContext) => void | Promise<void>\nexport type OnResponseHook = (ctx: PluginContext) => void | Promise<void>\nexport type OnErrorHook = (ctx: PluginErrorContext) => void | Promise<void>\n\nexport type HookName = 'onRequest' | 'preHandler' | 'onResponse' | 'onError'\n\nexport type HookByName<K extends HookName> = K extends 'onError'\n ? OnErrorHook\n : K extends 'onRequest'\n ? OnRequestHook\n : K extends 'preHandler'\n ? PreHandlerHook\n : K extends 'onResponse'\n ? OnResponseHook\n : never\n\nexport interface TheoApp {\n addHook<K extends HookName>(name: K, fn: HookByName<K>): void\n // `T` lets plugin authors document the per-key shape of decorations.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the value type for plugin authors\n decorateRequest<T>(key: string, value: T): void\n}\n\nexport interface TheoPlugin {\n name: string\n register(app: TheoApp): void | Promise<void>\n}\n\n/**\n * Identity function for plugin authors. Provides auto-completion + type\n * inference at the call site (TanStack/Vite/Astro pattern). Pure runtime\n * no-op — returns the input unchanged.\n *\n * @example\n * import { definePlugin } from 'theokit/server'\n * export default definePlugin({\n * name: 'my-plugin',\n * register(app) {\n * app.addHook('onRequest', (req) => { ... })\n * },\n * })\n *\n * Equivalent to `const p: TheoPlugin = {...}` but more ergonomic. See\n * ADR-0008 (D1 + D6) for the rationale.\n */\nexport function definePlugin(plugin: TheoPlugin): TheoPlugin {\n return plugin\n}\n\n// ===== T5a.2 Phase F slice 1/3 — Web-Standards plugin context types =====\n//\n// Mirror of the IncomingMessage/ServerResponse-shaped `PluginContext` for\n// the Web `Request`/`Headers` shape. Per `docs/plans/t5a2-incoming-message-\n// to-request-shape-refactor-plan.md` v1.0 § Phase F.\n//\n// **Key difference vs IncomingMessage path:** the Web path has no\n// `ServerResponse` to mutate. Plugins instead get a `responseHeaders: Headers`\n// instance they can append to (e.g., add Set-Cookie, CORS headers) and the\n// runtime composes the final `Response` after the hook chain runs. The\n// `response` object (if any) is the in-flight Response constructed by the\n// handler — present only during `onResponse` / `onError` hooks AFTER the\n// handler returned, NOT during `onRequest` / `preHandler` (which fire BEFORE\n// the handler runs).\n//\n// This split mirrors Hono's `c.res` + Fastify's `reply.headers` semantics\n// — plugins mutate headers freely; the body is the handler's responsibility.\n\n/**\n * Web-Standards plugin context. Available during all 4 hook lifecycle\n * stages (onRequest, preHandler, onResponse, onError).\n *\n * - `request` — the incoming Web Request (read-only at the runtime level;\n * plugins can call `request.headers.get()`, `request.clone()`, etc.).\n * - `responseHeaders` — a mutable `Headers` instance the runtime threads\n * through the hook chain. Plugins append (e.g., CORS, Set-Cookie); the\n * final Response composes these.\n * - `response` — set to the handler's Response AFTER the handler returns.\n * Available during `onResponse` / `onError`. `undefined` during\n * `onRequest` / `preHandler` (which fire before the handler runs).\n * - `ctx` / `requestId` — same semantics as the IncomingMessage path.\n */\nexport interface WebPluginContext {\n request: Request\n responseHeaders: Headers\n response?: Response\n ctx: Record<string, unknown>\n requestId: string\n}\n\nexport interface WebPluginErrorContext extends WebPluginContext {\n error: unknown\n}\n\nexport type WebOnRequestHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebPreHandlerHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebOnResponseHook = (ctx: WebPluginContext) => void | Promise<void>\nexport type WebOnErrorHook = (ctx: WebPluginErrorContext) => void | Promise<void>\n\nexport type WebHookByName<K extends HookName> = K extends 'onError'\n ? WebOnErrorHook\n : K extends 'onRequest'\n ? WebOnRequestHook\n : K extends 'preHandler'\n ? WebPreHandlerHook\n : K extends 'onResponse'\n ? WebOnResponseHook\n : never\n\n/**\n * Web-Standards `TheoApp` facade. Same `addHook` + `decorateRequest`\n * surface as the IncomingMessage path; only the hook function signatures\n * differ (they receive `WebPluginContext` instead of `PluginContext`).\n *\n * Plugin authors who target both shapes can branch on the context type\n * via a type guard (`'responseHeaders' in ctx`) OR ship two separate\n * `register()` exports — one for each runtime adapter. Most plugins\n * register hooks at the IncomingMessage path today (legacy); future\n * Web-native plugins will register against `WebTheoApp`.\n */\nexport interface WebTheoApp {\n addHook<K extends HookName>(name: K, fn: WebHookByName<K>): void\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- T documents the value type for plugin authors\n decorateRequest<T>(key: string, value: T): void\n}\n\n/**\n * Web-Standards plugin shape. Identical to `TheoPlugin` except the\n * `register(app)` argument is `WebTheoApp` instead of `TheoApp`.\n *\n * Cross-runtime plugins ship BOTH `TheoPlugin` + `WebTheoPlugin` exports;\n * the adapter (Node, CF Workers, Bun, Deno) picks the matching one based\n * on which runtime executes the plugin chain. This is the canonical\n * Hono/Nitro pattern.\n */\nexport interface WebTheoPlugin {\n name: string\n register(app: WebTheoApp): void | Promise<void>\n}\n\n/**\n * Identity function for Web plugin authors — same auto-completion +\n * type-inference DX as `definePlugin`, but for the Web-shaped `WebTheoApp`.\n */\nexport function defineWebPlugin(plugin: WebTheoPlugin): WebTheoPlugin {\n return plugin\n}\n","/**\n * M31 Phase 3 — `plugin()`, the fluent builder that replaces `definePlugin({...})`.\n *\n * Collects lifecycle hooks + request decorations and SYNTHESIZES the `register(app)` function, so\n * authors never write the imperative `register` body. `.build()` returns a `TheoPlugin` the plugin\n * runner consumes UNCHANGED.\n *\n * export default plugin('request-id')\n * .onRequest((ctx) => { ctx.ctx.requestId = crypto.randomUUID() })\n * .onResponse((ctx) => { ctx.response.setHeader('x-request-id', String(ctx.ctx.requestId)) })\n * .build()\n */\nimport {\n definePlugin,\n type TheoPlugin,\n type TheoApp,\n type OnRequestHook,\n type PreHandlerHook,\n type OnResponseHook,\n type OnErrorHook,\n} from '../plugin-types.js'\n\n/** The fluent plugin builder. `name` is set at entry; every hook is optional and may repeat. */\nexport interface PluginBuilder {\n /** Register an `onRequest` hook (runs before the CSRF gate). May be called multiple times. */\n onRequest(fn: OnRequestHook): PluginBuilder\n /** Register a `preHandler` hook (after CSRF, before the route handler). */\n preHandler(fn: PreHandlerHook): PluginBuilder\n /** Register an `onResponse` hook (after the handler returns). */\n onResponse(fn: OnResponseHook): PluginBuilder\n /** Register an `onError` hook (error path). */\n onError(fn: OnErrorHook): PluginBuilder\n /** Decorate every request with a key/value pair (available on `ctx.ctx[key]`). */\n decorateRequest<T>(key: string, value: T): PluginBuilder\n /** Resolve to the `TheoPlugin` — a synthesized `{ name, register }` the runner consumes. */\n build(): TheoPlugin\n}\n\ninterface PluginSpecAccumulator {\n name: string\n onRequest: OnRequestHook[]\n preHandler: PreHandlerHook[]\n onResponse: OnResponseHook[]\n onError: OnErrorHook[]\n decorations: { key: string; value: unknown }[]\n}\n\nfunction makePluginBuilder(spec: PluginSpecAccumulator): PluginBuilder {\n const runtime: PluginBuilder = {\n onRequest: (fn) => makePluginBuilder({ ...spec, onRequest: [...spec.onRequest, fn] }),\n preHandler: (fn) => makePluginBuilder({ ...spec, preHandler: [...spec.preHandler, fn] }),\n onResponse: (fn) => makePluginBuilder({ ...spec, onResponse: [...spec.onResponse, fn] }),\n onError: (fn) => makePluginBuilder({ ...spec, onError: [...spec.onError, fn] }),\n decorateRequest: (key, value) =>\n makePluginBuilder({ ...spec, decorations: [...spec.decorations, { key, value }] }),\n build: () =>\n definePlugin({\n name: spec.name,\n register(app: TheoApp): void {\n for (const fn of spec.onRequest) app.addHook('onRequest', fn)\n for (const fn of spec.preHandler) app.addHook('preHandler', fn)\n for (const fn of spec.onResponse) app.addHook('onResponse', fn)\n for (const fn of spec.onError) app.addHook('onError', fn)\n for (const d of spec.decorations) app.decorateRequest(d.key, d.value)\n },\n }),\n }\n return runtime\n}\n\n/** Start a fluent plugin definition. `name` is required; chain hooks/decorations, then `.build()`. */\nexport function plugin(name: string): PluginBuilder {\n return makePluginBuilder({\n name,\n onRequest: [],\n preHandler: [],\n onResponse: [],\n onError: [],\n decorations: [],\n })\n}\n","import type { UIMessageChunk } from 'ai'\n\n/**\n * M0 (theokit-ai-first) — serialize a stream of ai-sdk `UIMessageChunk`s into a\n * Web-Standards `Response` on the UIMessageStream wire so `@ai-sdk/react`'s\n * `useChat` consumes it WITHOUT a custom adapter.\n *\n * Wire contract (must match ai-sdk's consumer transport exactly):\n * - `content-type: text/event-stream`\n * - `x-vercel-ai-ui-message-stream: v1` — the version marker `useChat` checks\n * - each chunk framed as `data: ${JSON.stringify(chunk)}\\n\\n`\n * - a terminal `data: [DONE]\\n\\n` after the last chunk (ignored by the parser)\n *\n * Web Standards only — `Response` + `ReadableStream` (G8, no node:http). The\n * headers commit before the stream starts.\n *\n * Fail-clear (error-handling.md): if the source iterable throws mid-stream, the\n * `[DONE]` terminal is still flushed and the stream is closed — never left\n * hanging. (The translator upstream already closes gracefully; this is defense\n * in depth for any other chunk source.)\n */\nconst UI_MESSAGE_STREAM_HEADERS = {\n 'content-type': 'text/event-stream',\n 'x-vercel-ai-ui-message-stream': 'v1',\n} as const\n\nconst DONE_FRAME = 'data: [DONE]\\n\\n'\n\nfunction encode(text: string): Uint8Array {\n return new TextEncoder().encode(text)\n}\n\nexport function uiMessageStreamResponse(chunks: AsyncIterable<UIMessageChunk>): Response {\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n try {\n for await (const chunk of chunks) {\n controller.enqueue(encode(`data: ${JSON.stringify(chunk)}\\n\\n`))\n }\n } catch {\n // The source iterable aborted mid-stream. The upstream translator owns\n // error semantics (it surfaces failures as chunks + closes gracefully);\n // this transport's sole guarantee is a terminated stream — fall through\n // to the DONE terminal rather than re-throw and error an open stream.\n } finally {\n controller.enqueue(encode(DONE_FRAME))\n controller.close()\n }\n },\n })\n return new Response(stream, { headers: UI_MESSAGE_STREAM_HEADERS })\n}\n","import type { IncomingMessage } from 'node:http'\n\nimport type { WebSocketLike } from './define-websocket.js'\n\nexport interface ChannelHandler<TMessage = unknown> {\n onSubscribe?: (ws: WebSocketLike, room: string, req: IncomingMessage) => void\n onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void\n onUnsubscribe?: (ws: WebSocketLike, room: string) => void\n}\n\n/**\n * Define a channel handler for WebSocket rooms.\n * Identity function — provides type inference for channel handlers.\n */\nexport function defineChannel<TMessage = unknown>(\n handler: ChannelHandler<TMessage>,\n): ChannelHandler<TMessage> {\n return handler\n}\n\n/**\n * T5a.2 Phase F slice 2/3 — Web-Standards channel handler.\n *\n * Mirror of `ChannelHandler<TMessage>` for the Web `Request` shape.\n * `onSubscribe` receives `request: Request` instead of `req: IncomingMessage`\n * — the rest of the surface (onMessage, onUnsubscribe) is shape-agnostic\n * (WebSocketLike is already Web-standards-compatible per `define-websocket.ts`).\n *\n * Per `docs/plans/t5a2-incoming-message-to-request-shape-refactor-plan.md`\n * v1.0 § Phase F.\n *\n * **Architectural note:** WebSocket upgrade semantics differ across\n * runtimes:\n * - Node: `WebSocketServer.handleUpgrade(req, socket, head, cb)` —\n * hands you `req: IncomingMessage` at the upgrade handshake.\n * - CF Workers: `new WebSocketPair()` + `request.headers` (the upgrade\n * handshake IS a Web Request) — hands you `request: Request`.\n * - Bun: `server.upgrade(request, { data })` — same Web Request shape.\n * - Deno: `Deno.upgradeWebSocket(request)` — same Web Request shape.\n *\n * Channel handlers targeting CF/Bun/Deno use `WebChannelHandler`; legacy\n * Node consumers stay on `ChannelHandler`. Cross-runtime channels ship\n * both shapes.\n */\nexport interface WebChannelHandler<TMessage = unknown> {\n onSubscribe?: (ws: WebSocketLike, room: string, request: Request) => void\n onMessage?: (ws: WebSocketLike, room: string, data: TMessage) => void\n onUnsubscribe?: (ws: WebSocketLike, room: string) => void\n}\n\n/**\n * Web-Standards `defineChannel` sibling. Identity function — provides\n * type inference for Web channel handlers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EAAE,SAAS,0BAA0B,CAAC;AACpE;;;ACrCO,SAAS,cACd,SAC0B;AAC1B,SAAO;AACT;AAoCO,SAAS,iBACd,SAC6B;AAC7B,SAAO;AACT;","names":["plugin"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isZodLike
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-QWBXUZAX.js";
|
|
4
4
|
import {
|
|
5
5
|
validateCsrfRequest
|
|
6
6
|
} from "./chunk-TSLSIRBR.js";
|
|
@@ -454,4 +454,4 @@ export {
|
|
|
454
454
|
validateRouteInput,
|
|
455
455
|
executeWebRequest
|
|
456
456
|
};
|
|
457
|
-
//# sourceMappingURL=chunk-
|
|
457
|
+
//# sourceMappingURL=chunk-GW5H4KB4.js.map
|
|
@@ -178,7 +178,7 @@ async function agentCommand(name, message, deps = {}) {
|
|
|
178
178
|
async function createAgentSsrLoader(projectRoot) {
|
|
179
179
|
const { createServer } = await import("vite");
|
|
180
180
|
const react = (await import("@vitejs/plugin-react")).default;
|
|
181
|
-
const { theoPluginAsync } = await import("./vite-plugin-
|
|
181
|
+
const { theoPluginAsync } = await import("./vite-plugin-5Y3LDTXI.js");
|
|
182
182
|
const { loadConfig } = await import("./load-config-3EAQTXPH.js");
|
|
183
183
|
const config = await loadConfig(projectRoot);
|
|
184
184
|
const theoPlugins = await theoPluginAsync({
|
|
@@ -212,4 +212,4 @@ export {
|
|
|
212
212
|
agentCommand,
|
|
213
213
|
createAgentSsrLoader
|
|
214
214
|
};
|
|
215
|
-
//# sourceMappingURL=chunk-
|
|
215
|
+
//# sourceMappingURL=chunk-IPSFSNEJ.js.map
|
|
@@ -1,8 +1,107 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
dispatchCsrfWarn,
|
|
5
|
+
enforceCsrf,
|
|
6
|
+
incomingMessageToWebRequest,
|
|
7
|
+
safeAudit,
|
|
8
|
+
sendError
|
|
9
|
+
} from "./chunk-BKYFOEBK.js";
|
|
10
|
+
|
|
11
|
+
// src/server/http/controller-dispatch.ts
|
|
12
|
+
import { readdirSync } from "fs";
|
|
13
|
+
import { join } from "path";
|
|
14
|
+
import { createDecoratorHandler, isControllerClass } from "@theokit/http";
|
|
15
|
+
var CSRF_PROTECTED_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
16
|
+
function findControllerFiles(dir) {
|
|
17
|
+
const found = [];
|
|
18
|
+
const walk = (current) => {
|
|
19
|
+
let entries;
|
|
20
|
+
try {
|
|
21
|
+
entries = readdirSync(current, { withFileTypes: true });
|
|
22
|
+
} catch {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
for (const entry of entries) {
|
|
26
|
+
const full = join(current, entry.name);
|
|
27
|
+
if (entry.isDirectory()) walk(full);
|
|
28
|
+
else if (entry.name.endsWith(".controller.ts")) found.push(full);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
walk(dir);
|
|
32
|
+
return found;
|
|
33
|
+
}
|
|
34
|
+
async function scanControllerModules(controllersDir, loadModule) {
|
|
35
|
+
const files = findControllerFiles(controllersDir);
|
|
36
|
+
const modules = [];
|
|
37
|
+
for (const filePath of files) {
|
|
38
|
+
const mod = await loadModule(filePath);
|
|
39
|
+
for (const exported of Object.values(mod)) {
|
|
40
|
+
if (typeof exported === "function" && isControllerClass(exported)) {
|
|
41
|
+
modules.push({ filePath, cls: exported });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return modules;
|
|
46
|
+
}
|
|
47
|
+
async function scanControllers(controllersDir, loadModule) {
|
|
48
|
+
const modules = await scanControllerModules(controllersDir, loadModule);
|
|
49
|
+
return modules.map((m) => m.cls);
|
|
50
|
+
}
|
|
51
|
+
async function createControllerDispatcher(opts) {
|
|
52
|
+
const classes = await scanControllers(opts.controllersDir, opts.loadModule);
|
|
53
|
+
if (classes.length === 0) return null;
|
|
54
|
+
const handle = createDecoratorHandler(classes);
|
|
55
|
+
return {
|
|
56
|
+
dispatch: (request) => handle(request),
|
|
57
|
+
matches: (method, pathname) => handle.matches(method, pathname)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
async function writeControllerResponse(res, response) {
|
|
61
|
+
const headersBag = {};
|
|
62
|
+
for (const [k, v] of response.headers) {
|
|
63
|
+
if (k.toLowerCase() !== "set-cookie") headersBag[k] = v;
|
|
64
|
+
}
|
|
65
|
+
const setCookies = response.headers.getSetCookie();
|
|
66
|
+
if (setCookies.length > 0) res.setHeader("Set-Cookie", setCookies);
|
|
67
|
+
res.writeHead(response.status, headersBag);
|
|
68
|
+
const body = response.body ? await response.text() : "";
|
|
69
|
+
res.end(body || void 0);
|
|
70
|
+
}
|
|
71
|
+
async function dispatchControllerRequest(args) {
|
|
72
|
+
const { req, res, csrfMode, disallowed, requestId } = args;
|
|
73
|
+
const dispatcher = await createControllerDispatcher({
|
|
74
|
+
controllersDir: args.controllersDir,
|
|
75
|
+
loadModule: args.loadModule
|
|
76
|
+
});
|
|
77
|
+
if (!dispatcher) return false;
|
|
78
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
79
|
+
const webRequest = incomingMessageToWebRequest(req);
|
|
80
|
+
const pathname = new URL(webRequest.url).pathname;
|
|
81
|
+
if (CSRF_PROTECTED_METHODS.has(method) && dispatcher.matches(method, pathname)) {
|
|
82
|
+
const decision = enforceCsrf(
|
|
83
|
+
req,
|
|
84
|
+
csrfMode,
|
|
85
|
+
{ warn: dispatchCsrfWarn, path: req.url },
|
|
86
|
+
disallowed
|
|
87
|
+
);
|
|
88
|
+
if (!decision.allow) {
|
|
89
|
+
sendError(
|
|
90
|
+
res,
|
|
91
|
+
"CSRF_INVALID",
|
|
92
|
+
decision.reason ?? "CSRF check failed",
|
|
93
|
+
403,
|
|
94
|
+
void 0,
|
|
95
|
+
requestId
|
|
96
|
+
);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const response = await dispatcher.dispatch(webRequest);
|
|
101
|
+
if (response === null) return false;
|
|
102
|
+
await writeControllerResponse(res, response);
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
6
105
|
|
|
7
106
|
// src/server/http/batch-handler.ts
|
|
8
107
|
import { z } from "zod";
|
|
@@ -327,7 +426,7 @@ function sendNoContent(res) {
|
|
|
327
426
|
res.writeHead(204);
|
|
328
427
|
res.end();
|
|
329
428
|
}
|
|
330
|
-
function
|
|
429
|
+
function sendError2(res, status, code, message) {
|
|
331
430
|
res.writeHead(status, { "content-type": "application/json" });
|
|
332
431
|
res.end(JSON.stringify({ error: { code, message } }));
|
|
333
432
|
}
|
|
@@ -339,17 +438,17 @@ async function handleCsrfReadiness(req, res, store) {
|
|
|
339
438
|
sendJson(res, 200, store.summary());
|
|
340
439
|
return true;
|
|
341
440
|
}
|
|
342
|
-
|
|
441
|
+
sendError2(res, 405, "METHOD_NOT_ALLOWED", `Use GET on ${CSRF_READINESS_PATH}`);
|
|
343
442
|
return true;
|
|
344
443
|
}
|
|
345
444
|
if (url === CSRF_READINESS_RESET_PATH) {
|
|
346
445
|
if (method !== "POST") {
|
|
347
|
-
|
|
446
|
+
sendError2(res, 405, "METHOD_NOT_ALLOWED", `Use POST on ${CSRF_READINESS_RESET_PATH}`);
|
|
348
447
|
return true;
|
|
349
448
|
}
|
|
350
449
|
const hasHeader = req.headers["x-theo-action"] === "1";
|
|
351
450
|
if (!hasHeader || !originMatchesHost(req)) {
|
|
352
|
-
|
|
451
|
+
sendError2(res, 403, "CSRF_INVALID", "Reset requires X-Theo-Action: 1 + same-origin");
|
|
353
452
|
return true;
|
|
354
453
|
}
|
|
355
454
|
store.reset();
|
|
@@ -408,6 +507,9 @@ var CsrfReadinessStore = class _CsrfReadinessStore {
|
|
|
408
507
|
};
|
|
409
508
|
|
|
410
509
|
export {
|
|
510
|
+
scanControllerModules,
|
|
511
|
+
createControllerDispatcher,
|
|
512
|
+
dispatchControllerRequest,
|
|
411
513
|
BATCH_PATH,
|
|
412
514
|
handleBatchRequest,
|
|
413
515
|
createCorsHandler,
|
|
@@ -418,4 +520,4 @@ export {
|
|
|
418
520
|
handleCsrfReadiness,
|
|
419
521
|
CsrfReadinessStore
|
|
420
522
|
};
|
|
421
|
-
//# sourceMappingURL=chunk-
|
|
523
|
+
//# sourceMappingURL=chunk-OLZLYLOE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/http/controller-dispatch.ts","../src/server/http/batch-handler.ts","../src/server/http/cors.ts","../src/server/http/trace-context.ts","../src/server/security/csp-report.ts","../src/server/security/csrf-readiness-endpoint.ts","../src/server/security/csrf-readiness-store.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Controller files are walked from the developer's `serverDir/controllers`\n * (a build-time config path), never from HTTP input. No injection vector.\n */\nimport { readdirSync, type Dirent } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { join } from 'node:path'\n\nimport { createDecoratorHandler, isControllerClass } from '@theokit/http'\n\nimport { dispatchCsrfWarn } from '../security/csrf-warn-dispatch.js'\nimport { enforceCsrf, type DisallowedConfig } from '../security/csrf.js'\n\nimport { incomingMessageToWebRequest } from './node-request.js'\nimport { sendError } from './send-response.js'\n\n/** A decorator controller constructor (`@Controller` class). */\ntype ControllerClass = new (...args: never[]) => object\n\n/** Loads a controller module by absolute path. In dev this is Vite's `ssrLoadModule`\n * (the Task 1.1 swc transform has already compiled the parameter decorators); tests\n * inject `@theokit/http`'s `loadControllerWithSwc`. */\nexport type ControllerModuleLoader = (absPath: string) => Promise<Record<string, unknown>>\n\n/** A built controller route table exposed as a pure Web-Standard handler. */\nexport interface ControllerDispatcher {\n /** `null` = no controller route matched — the host owns the miss (404 / fall-through). */\n dispatch(request: Request): Promise<Response | null>\n /** Non-executing route probe — true when a controller route owns `method` + `pathname`. */\n matches(method: string, pathname: string): boolean\n}\n\n// State-mutating methods get CSRF, mirroring the file-route pipeline (execute.ts).\nconst CSRF_PROTECTED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])\n\n/** Recursively collect `*.controller.ts` files under `dir` (absolute paths). */\nfunction findControllerFiles(dir: string): string[] {\n const found: string[] = []\n const walk = (current: string): void => {\n let entries: Dirent[]\n try {\n entries = readdirSync(current, { withFileTypes: true })\n } catch {\n return // dir doesn't exist — no controllers\n }\n for (const entry of entries) {\n const full = join(current, entry.name)\n if (entry.isDirectory()) walk(full)\n else if (entry.name.endsWith('.controller.ts')) found.push(full)\n }\n }\n walk(dir)\n return found\n}\n\n/** A discovered controller: its source file + the loaded `@Controller` class. */\nexport interface ControllerModule {\n filePath: string\n cls: ControllerClass\n}\n\n/**\n * Load every `@Controller` class under `controllersDir` via the injected loader,\n * keeping each class paired with its source file (needed by the typed-client\n * codegen to emit `import type { X } from '<file>'`). Non-controller exports are\n * ignored (`isControllerClass` — reused from @theokit/http).\n */\nexport async function scanControllerModules(\n controllersDir: string,\n loadModule: ControllerModuleLoader,\n): Promise<ControllerModule[]> {\n const files = findControllerFiles(controllersDir)\n const modules: ControllerModule[] = []\n for (const filePath of files) {\n const mod = await loadModule(filePath)\n for (const exported of Object.values(mod)) {\n if (typeof exported === 'function' && isControllerClass(exported)) {\n modules.push({ filePath, cls: exported as ControllerClass })\n }\n }\n }\n return modules\n}\n\n/** Load every `@Controller` class under `controllersDir` (classes only). */\nexport async function scanControllers(\n controllersDir: string,\n loadModule: ControllerModuleLoader,\n): Promise<ControllerClass[]> {\n const modules = await scanControllerModules(controllersDir, loadModule)\n return modules.map((m) => m.cls)\n}\n\n/**\n * Scan `controllersDir` and build a Web-Standard dispatcher over the decorator\n * controllers found. Returns `null` when the directory has no controllers, so\n * the host can skip the controller path entirely (zero cost for routes-only apps).\n *\n * Dispatch REUSES @theokit/http's `createDecoratorHandler` (match + `@Param`\n * binding + `@Body` validation + Response building) — never re-implemented (ADR-1).\n */\nexport async function createControllerDispatcher(opts: {\n controllersDir: string\n loadModule: ControllerModuleLoader\n}): Promise<ControllerDispatcher | null> {\n const classes = await scanControllers(opts.controllersDir, opts.loadModule)\n if (classes.length === 0) return null\n const handle = createDecoratorHandler(classes)\n return {\n dispatch: (request) => handle(request),\n matches: (method, pathname) => handle.matches(method, pathname),\n }\n}\n\n/** Write a buffered Web `Response` (controllers never stream) to a Node response. */\nasync function writeControllerResponse(res: ServerResponse, response: Response): Promise<void> {\n const headersBag: Record<string, string> = {}\n for (const [k, v] of response.headers) {\n if (k.toLowerCase() !== 'set-cookie') headersBag[k] = v\n }\n const setCookies = response.headers.getSetCookie()\n if (setCookies.length > 0) res.setHeader('Set-Cookie', setCookies)\n res.writeHead(response.status, headersBag)\n const body = response.body ? await response.text() : ''\n res.end(body || undefined)\n}\n\n/**\n * The `api-middleware` fall-through in one call: scan `controllersDir`, build the\n * dispatcher, and serve the request. Builds a body-ful Web `Request` (`@Body`\n * needs the body; the raw stream is undrained at a route miss) and enforces CSRF\n * with the SAME gate file routes use (parity). Returns `true` when a controller\n * handled it (or CSRF blocked it), `false` when there are no controllers OR none\n * matched (the host continues to its own 404). Built per-miss so controller edits\n * reflect via HMR.\n */\nexport async function dispatchControllerRequest(args: {\n controllersDir: string\n loadModule: ControllerModuleLoader\n req: IncomingMessage\n res: ServerResponse\n csrfMode: 'off' | 'warn' | 'strict'\n disallowed?: DisallowedConfig\n requestId: string\n}): Promise<boolean> {\n const { req, res, csrfMode, disallowed, requestId } = args\n const dispatcher = await createControllerDispatcher({\n controllersDir: args.controllersDir,\n loadModule: args.loadModule,\n })\n if (!dispatcher) return false\n\n const method = (req.method ?? 'GET').toUpperCase()\n const webRequest = incomingMessageToWebRequest(req)\n const pathname = new URL(webRequest.url).pathname\n\n // CSRF parity: enforce ONLY when a protected-method controller route actually\n // owns this path (probe with the non-executing matcher — never double-dispatch,\n // which would run the handler + its side effects). An unrouted path falls\n // through to the host's own 404, not a 403.\n if (CSRF_PROTECTED_METHODS.has(method) && dispatcher.matches(method, pathname)) {\n const decision = enforceCsrf(\n req,\n csrfMode,\n { warn: dispatchCsrfWarn, path: req.url },\n disallowed,\n )\n if (!decision.allow) {\n sendError(\n res,\n 'CSRF_INVALID',\n decision.reason ?? 'CSRF check failed',\n 403,\n undefined,\n requestId,\n )\n return true\n }\n }\n\n const response = await dispatcher.dispatch(webRequest)\n if (response === null) return false\n await writeControllerResponse(res, response)\n return true\n}\n","/**\n * T1.4 — Server-side batch handler.\n *\n * Receives `{ requests: [...] }` POSTed to `/api/__theo_batch__` and returns\n * `{ results: [...] }` with per-item error isolation. EC-2: items cannot\n * override auth/forwarded headers (would be a session-bypass vector).\n */\n\nimport { z } from 'zod'\n\nexport const STRIPPED_HEADERS = [\n 'authorization',\n 'cookie',\n 'x-forwarded-for',\n 'x-forwarded-host',\n 'x-forwarded-proto',\n 'x-real-ip',\n 'host',\n] as const\n\nexport const BATCH_PATH = '/api/__theo_batch__'\nconst DEFAULT_MAX_BATCH = 32\n\nexport class BatchPathConflictError extends Error {\n constructor(path: string) {\n super(\n `Server route conflicts with reserved batch path ${path}. ` +\n `Rename the route or disable batching in theo.config.ts.`,\n )\n this.name = 'BatchPathConflictError'\n }\n}\n\nconst batchRequestSchema = z.object({\n path: z.string().min(1),\n method: z.string().min(1),\n query: z.record(z.string(), z.unknown()).optional(),\n body: z.unknown().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n})\n\nconst batchPayloadSchema = z.object({\n requests: z.array(batchRequestSchema).min(1),\n})\n\nexport type BatchRequestItem = z.infer<typeof batchRequestSchema>\nexport type BatchPayload = z.infer<typeof batchPayloadSchema>\n\nexport type BatchExecuteFn = (\n req: BatchRequestItem,\n) => Promise<{ data: unknown } | { error: { message: string; code?: string } }>\n\nexport interface HandleBatchOptions {\n execute: BatchExecuteFn\n /** Max number of items per batch. Default 32. */\n max?: number\n /** Outer-request headers that override per-item headers in STRIPPED_HEADERS. */\n outerHeaders?: Record<string, string>\n}\n\nexport type BatchResultItem = { data: unknown } | { error: { message: string; code?: string } }\n\nexport interface BatchResponse {\n results: BatchResultItem[]\n}\n\n/**\n * Sanitize a per-item header object: keys in STRIPPED_HEADERS are removed,\n * then the outer request's values for those keys are layered on top so that\n * downstream middlewares see the real session/auth headers.\n */\nfunction sanitizeItemHeaders(\n itemHeaders: Record<string, string> | undefined,\n outerHeaders: Record<string, string> | undefined,\n): Record<string, string> {\n const out: Record<string, string> = {}\n if (itemHeaders) {\n for (const [k, v] of Object.entries(itemHeaders)) {\n const lower = k.toLowerCase()\n if (!(STRIPPED_HEADERS as readonly string[]).includes(lower)) {\n out[lower] = v\n }\n }\n }\n if (outerHeaders) {\n for (const stripped of STRIPPED_HEADERS) {\n // `Object.hasOwn` defends against missing keys without triggering\n // `no-unnecessary-condition` (TypeScript types `outerHeaders` keys\n // as defined; `hasOwn` keeps the conditional honest at runtime).\n if (Object.hasOwn(outerHeaders, stripped)) {\n out[stripped] = outerHeaders[stripped]\n }\n }\n }\n return out\n}\n\n/**\n * Validate + execute a batch request.\n *\n * CR-028 fix: previously the signature was `payload: BatchPayload`,\n * suggesting the caller had already validated. In reality `api-middleware`\n * passes `JSON.parse(rawBody) as BatchPayload` — an unsafe cast over raw\n * HTTP input. We widen the input type to `unknown` so the type system\n * forces validation, then run Zod once at this single trust boundary.\n */\nexport async function handleBatchRequest(\n payload: unknown,\n options: HandleBatchOptions,\n): Promise<BatchResponse> {\n const parsed = batchPayloadSchema.parse(payload)\n const max = options.max ?? DEFAULT_MAX_BATCH\n if (parsed.requests.length > max) {\n throw new Error(`Batch size ${parsed.requests.length} exceeds max ${max}`)\n }\n\n const results: BatchResultItem[] = []\n for (const item of parsed.requests) {\n const sanitized: BatchRequestItem = {\n ...item,\n headers: sanitizeItemHeaders(item.headers, options.outerHeaders),\n }\n try {\n const r = await options.execute(sanitized)\n results.push(r)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n results.push({ error: { message } })\n }\n }\n return { results }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\n/**\n * T1.2 — CORS middleware.\n *\n * Single global middleware that runs FIRST in the request pipeline:\n * CORS preflight → rate limit → CSRF → security headers → handler\n *\n * Preflight (`OPTIONS` with `Access-Control-Request-Method`) is handled\n * by `handlePreflight`, which short-circuits the response with 204 +\n * Access-Control-* headers.\n *\n * Non-preflight requests pass through; `applyHeaders` adds\n * `Access-Control-Allow-Origin` (echoing the request's Origin),\n * `Access-Control-Expose-Headers`, and `Access-Control-Allow-Credentials`.\n *\n * Per ADR D3: preflight responses are deterministic and only the matched\n * origin is echoed back (never `'*'` when credentials are enabled —\n * required by the CORS spec).\n */\n\n// `'*'` is conceptually distinct from a regular host string (it means\n// \"any origin\"), but TypeScript-wise it is just `string`, so we collapse\n// the union and document the wildcard via the type's name. Callers should\n// still pass the literal `'*'` to mean \"allow anywhere\" for readability.\nexport type CorsOrigin =\n | string\n | RegExp\n | readonly (string | RegExp)[]\n | ((origin: string) => boolean)\n\nexport interface CorsConfig {\n origins: CorsOrigin\n methods?: readonly ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD')[]\n allowedHeaders?: readonly string[]\n exposedHeaders?: readonly string[]\n credentials?: boolean\n maxAge?: number\n}\n\nexport interface CorsHandler {\n handlePreflight(req: IncomingMessage, res: ServerResponse): boolean\n applyHeaders(req: IncomingMessage, res: ServerResponse): void\n}\n\nconst DEFAULT_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'] as const\nconst DEFAULT_ALLOWED_HEADERS = ['Content-Type', 'X-Theo-Action', 'Authorization'] as const\nconst DEFAULT_MAX_AGE = 600\n\n/**\n * Read the request Origin header. Per Node typing, it can be a string,\n * string[] (proxy doubled), or undefined. We take the FIRST non-empty\n * value (consistent with `csrf.ts:121-122`).\n */\nfunction readOrigin(req: IncomingMessage): string | undefined {\n const raw = req.headers.origin\n if (raw === undefined) return undefined\n if (Array.isArray(raw)) {\n return raw.find((v): v is string => typeof v === 'string' && v.length > 0)\n }\n return raw\n}\n\n/**\n * Test whether `origin` is allowed by `allowed`. Pure function — no I/O.\n *\n * EC-8: callback variants that throw are fail-closed (deny). Without\n * this, a transient datastore outage would silently widen CORS during\n * the failure window.\n */\nexport function matchesOrigin(origin: string, allowed: CorsOrigin): boolean {\n if (allowed === '*') return true\n if (typeof allowed === 'string') return origin === allowed\n if (allowed instanceof RegExp) {\n allowed.lastIndex = 0\n return allowed.test(origin)\n }\n if (Array.isArray(allowed)) {\n for (const entry of allowed) {\n if (typeof entry === 'string' && origin === entry) return true\n if (entry instanceof RegExp) {\n entry.lastIndex = 0\n if (entry.test(origin)) return true\n }\n }\n return false\n }\n if (typeof allowed === 'function') {\n // EC-8: fail-closed on any throw\n try {\n return allowed(origin)\n } catch {\n return false\n }\n }\n return false\n}\n\nexport function createCorsHandler(config: CorsConfig): CorsHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflight(req, res) {\n if (req.method !== 'OPTIONS') return false\n const acMethod = req.headers['access-control-request-method']\n if (!acMethod) return false\n const origin = readOrigin(req)\n if (!origin) return false\n\n if (!matchesOrigin(origin, config.origins)) {\n res.statusCode = 403\n res.end()\n return true\n }\n\n // Echo the matched origin (NEVER '*' when credentials are enabled —\n // browsers reject wildcard responses with credentials per CORS spec).\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Access-Control-Allow-Methods', methods.join(', '))\n res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', '))\n res.setHeader('Access-Control-Max-Age', maxAge)\n // Mark the response as origin-varying so caches don't poison\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n res.statusCode = 204\n res.end()\n return true\n },\n\n applyHeaders(req, res) {\n const origin = readOrigin(req)\n if (!origin) return\n if (!matchesOrigin(origin, config.origins)) return\n\n res.setHeader('Access-Control-Allow-Origin', origin)\n res.setHeader('Vary', 'Origin')\n if (credentials) res.setHeader('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders && config.exposedHeaders.length > 0) {\n res.setHeader('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n\n/**\n * T5a.2 Phase B slice 5/6 — Web-Standards CORS handler.\n *\n * Mirror of `createCorsHandler(config): CorsHandler` for the Web `Request`\n * shape. Same `CorsConfig`, same `matchesOrigin` logic (pure helper\n * already), same security guarantees (echo matched origin only — never\n * `'*'` when credentials enabled; EC-8 fail-closed on callback throw).\n *\n * Signature differences vs the IncomingMessage pair:\n * - `handlePreflightRequest(request, config): Response | null` — returns\n * `Response` when this is a CORS preflight; `null` when not. Caller\n * short-circuits accordingly (same control-flow semantic as boolean).\n * - `applyCorsHeaders(request, target, config): void` — mutates a\n * `Headers` instance in place. Caller passes the headers they're\n * building for their Response.\n */\nexport interface CorsWebHandler {\n handlePreflightRequest(request: Request): Response | null\n applyCorsHeaders(request: Request, target: Headers): void\n}\n\nexport function createCorsWebHandler(config: CorsConfig): CorsWebHandler {\n const methods = (config.methods ?? DEFAULT_METHODS).slice()\n const allowedHeaders = (config.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS).slice()\n const maxAge = String(config.maxAge ?? DEFAULT_MAX_AGE)\n const credentials = config.credentials === true\n\n return {\n handlePreflightRequest(request) {\n if (request.method !== 'OPTIONS') return null\n const acMethod = request.headers.get('access-control-request-method')\n if (acMethod === null || acMethod.length === 0) return null\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return null\n\n if (!matchesOrigin(origin, config.origins)) {\n return new Response(null, { status: 403 })\n }\n\n // Echo matched origin only (security: never `'*'` when credentials\n // enabled — browsers reject per CORS spec).\n const headers = new Headers({\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': methods.join(', '),\n 'Access-Control-Allow-Headers': allowedHeaders.join(', '),\n 'Access-Control-Max-Age': maxAge,\n Vary: 'Origin',\n })\n if (credentials) headers.set('Access-Control-Allow-Credentials', 'true')\n return new Response(null, { status: 204, headers })\n },\n\n applyCorsHeaders(request, target) {\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return\n if (!matchesOrigin(origin, config.origins)) return\n\n target.set('Access-Control-Allow-Origin', origin)\n target.set('Vary', 'Origin')\n if (credentials) target.set('Access-Control-Allow-Credentials', 'true')\n if (config.exposedHeaders !== undefined && config.exposedHeaders.length > 0) {\n target.set('Access-Control-Expose-Headers', config.exposedHeaders.join(', '))\n }\n },\n }\n}\n","// T5a.1b — Web Crypto migration. randomUUID() moved to globalThis.crypto.\n// IncomingMessage stays as a type-only import (runtime-clean — TS erases at\n// build); full IncomingMessage→Request boundary migration deferred to a\n// later T5a.1c+ slice per ADR-0028 incremental leaf-first sequence.\nimport type { IncomingMessage } from 'node:http'\n\n/**\n * Phase 7 — Observability: traceId propagation (D7).\n *\n * Extract a stable identifier from incoming requests so a single value\n * correlates the client request, every server log line, the response\n * envelope, and any downstream span. Precedence:\n *\n * 1. `traceparent` (W3C Trace Context — `00-{32-hex}-{16-hex}-{flags}`)\n * 2. `x-request-id` (Heroku / GCP / generic proxy header)\n * 3. Generated UUID (fresh per request)\n *\n * UUIDs are accepted as trace identifiers by every major vendor that\n * does not enforce strict 32-hex (Datadog, Honeycomb, Sentry, Logflare,\n * Axiom, etc). We don't need ULIDs to ship this surface.\n */\n\nexport const TRACE_HEADER = 'x-trace-id'\nexport const TRACE_PARENT_HEADER = 'traceparent'\nconst REQUEST_ID_HEADER = 'x-request-id'\n\n// W3C Trace Context: 00-<trace-id 32 hex>-<span-id 16 hex>-<flags 2 hex>\nconst TRACEPARENT_RE = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/\n\n/**\n * Parse a W3C Trace Context `traceparent` header value. Returns the\n * 32-hex trace-id when valid (and not the reserved all-zeros), else\n * `null`.\n */\nexport function parseTraceparent(value: string): string | null {\n if (!value) return null\n const m = TRACEPARENT_RE.exec(value)\n if (!m) return null\n const traceId = m[1]\n // W3C: trace-id of all zeroes is invalid by spec\n if (/^0+$/.test(traceId)) return null\n return traceId\n}\n\n/**\n * Pick the first string value out of an IncomingMessage header. Node\n * collapses repeated headers into arrays; proxies sometimes do this for\n * `x-request-id`. Empty strings count as absent.\n */\nfunction pickHeader(value: string | string[] | undefined): string | null {\n if (Array.isArray(value)) {\n for (const v of value) {\n if (typeof v === 'string' && v.length > 0) return v\n }\n return null\n }\n if (typeof value === 'string' && value.length > 0) return value\n return null\n}\n\n/**\n * T5a.2 Phase C slice 1/2 — pure traceId resolution from pre-extracted\n * header values. Shared between IncomingMessage and Web Request wrappers.\n */\nfunction resolveTraceIdFromHeaders(traceparent: string | null, requestId: string | null): string {\n if (traceparent !== null) {\n const parsed = parseTraceparent(traceparent)\n if (parsed !== null) return parsed\n }\n if (requestId !== null) return requestId\n return globalThis.crypto.randomUUID()\n}\n\n/**\n * Resolve the request's traceId following the precedence above.\n */\nexport function extractTraceId(req: IncomingMessage): string {\n return resolveTraceIdFromHeaders(\n pickHeader(req.headers[TRACE_PARENT_HEADER]),\n pickHeader(req.headers[REQUEST_ID_HEADER]),\n )\n}\n\n/**\n * T5a.2 Phase C slice 1/2 — Web-Standards-shaped traceId resolver.\n *\n * Mirror of `extractTraceId(req: IncomingMessage)` for the Web `Request`\n * shape. Same precedence (`traceparent` → `x-request-id` → generated\n * UUID). Uses `request.headers.get(name)` (native Web `Headers` API)\n * instead of the Node indexer.\n *\n * **Multi-value note:** Web `Headers` collapses repeated headers into a\n * single comma-separated string at parse. The IncomingMessage path's\n * `pickHeader` \"first non-empty value\" semantic is naturally satisfied\n * because there's no array to pick from on the Web side — `.get()`\n * returns the comma-joined value, which for `traceparent` / `x-request-id`\n * is treated as a single string anyway (both headers are conventionally\n * single-valued).\n */\nexport function extractTraceIdFromRequest(request: Request): string {\n return resolveTraceIdFromHeaders(\n request.headers.get(TRACE_PARENT_HEADER),\n request.headers.get(REQUEST_ID_HEADER),\n )\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { safeAudit, type AuditLogger } from '../observability/audit-log.js'\n\n/**\n * T5.1 — Built-in CSP report endpoint.\n *\n * Browsers POST violation reports to `report-uri` (legacy `application/csp-report`)\n * or `Reporting API` (`application/reports+json`). Framework auto-registers this\n * endpoint so `cspMode: 'report-only'` is actually useful out of the box.\n *\n * Forwards normalized violations to:\n * - audit logger (`csp.violation`)\n * - devtools dispatcher (dev only, for Errors tab)\n * - optional user hook (Sentry, etc.)\n *\n * EC-2: browser MAY send `{\"csp-report\": null}`, empty `{}`, or\n * reports+json entries lacking `body`. Handler MUST short-circuit to\n * 204 (valid format, no violation), NEVER crash via null deref.\n */\n\nexport const CSP_REPORT_PATH = '/__theo/csp-report'\n\n/** Max body bytes accepted. Real CSP reports are < 2 KB; 16 KB is generous. */\nconst MAX_BODY = 16 * 1024\n\nexport interface CspViolation {\n blockedUrl: string\n documentUrl: string\n violatedDirective: string\n effectiveDirective?: string\n originalPolicy?: string\n disposition?: 'enforce' | 'report'\n statusCode?: number\n sourceFile?: string\n lineNumber?: number\n columnNumber?: number\n}\n\nexport interface CspReportHandlerOptions {\n auditLogger?: AuditLogger\n devtoolsDispatcher?: {\n onCspViolation?: (v: CspViolation) => void\n }\n /** Optional user-provided sink (Sentry, custom log router). Errors here are swallowed. */\n onViolation?: (v: CspViolation) => void\n}\n\n/**\n * Map a legacy `application/csp-report` payload to the internal shape.\n * Caller must ensure `raw` is a non-null object.\n */\nfunction pickHeader(value: string | string[] | undefined): string {\n if (typeof value === 'string') return value\n if (Array.isArray(value) && value.length > 0) return value[0]\n return ''\n}\n\nfunction toStringSafe(value: unknown, fallback = '(missing)'): string {\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return fallback\n}\n\nexport function normalizeLegacy(raw: Record<string, unknown>): CspViolation {\n return {\n blockedUrl: toStringSafe(raw['blocked-uri']),\n documentUrl: toStringSafe(raw['document-uri']),\n violatedDirective: toStringSafe(raw['violated-directive']),\n effectiveDirective:\n typeof raw['effective-directive'] === 'string' ? raw['effective-directive'] : undefined,\n originalPolicy: typeof raw['original-policy'] === 'string' ? raw['original-policy'] : undefined,\n disposition:\n raw.disposition === 'enforce' || raw.disposition === 'report' ? raw.disposition : undefined,\n statusCode: typeof raw['status-code'] === 'number' ? raw['status-code'] : undefined,\n sourceFile: typeof raw['source-file'] === 'string' ? raw['source-file'] : undefined,\n lineNumber: typeof raw['line-number'] === 'number' ? raw['line-number'] : undefined,\n columnNumber: typeof raw['column-number'] === 'number' ? raw['column-number'] : undefined,\n }\n}\n\n/**\n * Map a `reports+json` entry to the internal shape. Returns `null` if\n * the entry lacks a usable `body` object (EC-2).\n */\nexport function normalizeNew(entry: unknown): CspViolation | null {\n if (!entry || typeof entry !== 'object') return null\n const body = (entry as { body?: unknown }).body\n if (!body || typeof body !== 'object') return null\n const b = body as Record<string, unknown>\n return {\n blockedUrl: toStringSafe(b.blockedURL),\n documentUrl: toStringSafe(b.documentURL),\n violatedDirective: toStringSafe(b.violatedDirective),\n effectiveDirective: typeof b.effectiveDirective === 'string' ? b.effectiveDirective : undefined,\n originalPolicy: typeof b.originalPolicy === 'string' ? b.originalPolicy : undefined,\n disposition:\n b.disposition === 'enforce' || b.disposition === 'report' ? b.disposition : undefined,\n statusCode: typeof b.statusCode === 'number' ? b.statusCode : undefined,\n sourceFile: typeof b.sourceFile === 'string' ? b.sourceFile : undefined,\n lineNumber: typeof b.lineNumber === 'number' ? b.lineNumber : undefined,\n columnNumber: typeof b.columnNumber === 'number' ? b.columnNumber : undefined,\n }\n}\n\nasync function readBody(req: IncomingMessage, maxBytes: number): Promise<string> {\n return await new Promise<string>((resolve, reject) => {\n const chunks: Buffer[] = []\n let total = 0\n req.on('data', (chunk: Buffer) => {\n total += chunk.length\n if (total > maxBytes) {\n reject(new Error('body too large'))\n req.destroy()\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => {\n resolve(Buffer.concat(chunks).toString('utf8'))\n })\n req.on('error', reject)\n })\n}\n\nexport async function handleCspReport(\n req: IncomingMessage,\n res: ServerResponse,\n opts: CspReportHandlerOptions,\n): Promise<void> {\n const ctHeader = req.headers['content-type']\n const ct = pickHeader(ctHeader)\n\n let raw: string\n try {\n raw = await readBody(req, MAX_BODY)\n } catch {\n res.statusCode = 413\n res.end()\n return\n }\n\n let violations: CspViolation[]\n try {\n if (ct.startsWith('application/csp-report')) {\n // EC-2: browsers MAY POST {\"csp-report\": null} or {} on\n // disposition='report' policies. Guard against null/undefined/non-object.\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const inner = parsed['csp-report']\n if (!inner || typeof inner !== 'object') {\n res.statusCode = 204\n res.end()\n return\n }\n violations = [normalizeLegacy(inner as Record<string, unknown>)]\n } else if (ct.startsWith('application/reports+json')) {\n // EC-2: filter out entries lacking `body` BEFORE normalizing.\n const parsed: unknown = JSON.parse(raw)\n const entries = Array.isArray(parsed) ? parsed : []\n violations = entries.map((e) => normalizeNew(e)).filter((v): v is CspViolation => v !== null)\n } else {\n res.statusCode = 415\n res.end()\n return\n }\n } catch {\n res.statusCode = 400\n res.end()\n return\n }\n\n for (const v of violations) {\n safeAudit(opts.auditLogger, {\n action: 'csp.violation',\n metadata: v as unknown as Record<string, unknown>,\n })\n try {\n opts.devtoolsDispatcher?.onCspViolation?.(v)\n } catch {\n // dispatcher errors are isolated from the request\n }\n try {\n opts.onViolation?.(v)\n } catch {\n // user hook throws are swallowed — never crash the request\n }\n }\n\n res.statusCode = 204\n res.end()\n}\n\n/**\n * T5a.2 Phase B slice 4/6 — Web-Standards CSP report handler.\n *\n * Mirror of `handleCspReport(req: IncomingMessage, res: ServerResponse,\n * opts): Promise<void>` for the Web `Request` shape. Returns\n * `Response` directly instead of mutating `res`.\n *\n * Same content-type dispatch (legacy `application/csp-report` vs new\n * `application/reports+json`), same normalizers (`normalizeLegacy`,\n * `normalizeNew`), same side-effect loop (safeAudit + devtools + user\n * hook). The body cap is enforced post-read because Web Request body\n * streaming doesn't have a portable mid-stream rejection primitive\n * across CF Workers / Bun / Deno; CSP reports are < 2 KB typical, well\n * under MAX_BODY (16 KB).\n *\n * Returns:\n * - 204 on accepted reports OR no-op empty payload\n * - 413 on body too large (post-read check)\n * - 415 on unsupported content-type\n * - 400 on malformed JSON\n */\nasync function readBodyFromRequest(request: Request, maxBytes: number): Promise<string | null> {\n const contentLengthHeader = request.headers.get('content-length')\n if (contentLengthHeader !== null) {\n const declared = Number.parseInt(contentLengthHeader, 10)\n if (Number.isFinite(declared) && declared > maxBytes) return null\n }\n const text = await request.text()\n if (text.length > maxBytes) return null\n return text\n}\n\nfunction dispatchViolations(violations: CspViolation[], opts: CspReportHandlerOptions): void {\n for (const v of violations) {\n safeAudit(opts.auditLogger, {\n action: 'csp.violation',\n metadata: v as unknown as Record<string, unknown>,\n })\n try {\n opts.devtoolsDispatcher?.onCspViolation?.(v)\n } catch {\n // dispatcher errors are isolated from the request\n }\n try {\n opts.onViolation?.(v)\n } catch {\n // user hook throws are swallowed — never crash the request\n }\n }\n}\n\nexport async function handleCspReportRequest(\n request: Request,\n opts: CspReportHandlerOptions,\n): Promise<Response> {\n const ct = request.headers.get('content-type') ?? ''\n\n const raw = await readBodyFromRequest(request, MAX_BODY)\n if (raw === null) {\n return new Response(null, { status: 413 })\n }\n\n let violations: CspViolation[]\n try {\n if (ct.startsWith('application/csp-report')) {\n const parsed = JSON.parse(raw) as Record<string, unknown>\n const inner = parsed['csp-report']\n if (!inner || typeof inner !== 'object') {\n return new Response(null, { status: 204 })\n }\n violations = [normalizeLegacy(inner as Record<string, unknown>)]\n } else if (ct.startsWith('application/reports+json')) {\n const parsed: unknown = JSON.parse(raw)\n const entries = Array.isArray(parsed) ? parsed : []\n violations = entries.map((e) => normalizeNew(e)).filter((v): v is CspViolation => v !== null)\n } else {\n return new Response(null, { status: 415 })\n }\n } catch {\n return new Response(null, { status: 400 })\n }\n\n dispatchViolations(violations, opts)\n return new Response(null, { status: 204 })\n}\n","/**\n * T2.2 — `/__theo/csrf-readiness` endpoint.\n *\n * GET /__theo/csrf-readiness → 200 + JSON summary\n * POST /__theo/csrf-readiness/reset → 204; clears the store\n *\n * The reset endpoint enforces CSRF (own dog food) — requires\n * `X-Theo-Action: 1` AND a matching Origin header (EC-15). This avoids\n * the endpoint being weaponizable from a cross-origin page when the\n * endpoint is opt-in exposed in production.\n *\n * Mount opt-in: in dev mode, the host wires this in unconditionally. In\n * production, only mount when `config.security.csrfTelemetry.exposeReadinessEndpoint === true`.\n * EC-10 parallel: returns 404 (via boolean false return) when the URL\n * does not match — the caller continues normal request handling.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport type { CsrfReadinessStore } from './csrf-readiness-store.js'\n\nexport const CSRF_READINESS_PATH = '/__theo/csrf-readiness'\nexport const CSRF_READINESS_RESET_PATH = '/__theo/csrf-readiness/reset'\n\nfunction originMatchesHost(req: IncomingMessage): boolean {\n const origin = req.headers.origin\n if (typeof origin !== 'string') return false\n const host = req.headers.host\n if (typeof host !== 'string') return false\n try {\n const parsed = new URL(origin)\n return parsed.host === host\n } catch {\n return false\n }\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'content-type': 'application/json' })\n res.end(JSON.stringify(body))\n}\n\nfunction sendNoContent(res: ServerResponse): void {\n res.writeHead(204)\n res.end()\n}\n\nfunction sendError(res: ServerResponse, status: number, code: string, message: string): void {\n res.writeHead(status, { 'content-type': 'application/json' })\n res.end(JSON.stringify({ error: { code, message } }))\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async return for future telemetry hooks\nexport async function handleCsrfReadiness(\n req: IncomingMessage,\n res: ServerResponse,\n store: CsrfReadinessStore,\n): Promise<boolean> {\n const url = (req.url ?? '').split('?')[0]\n const method = req.method ?? 'GET'\n\n if (url === CSRF_READINESS_PATH) {\n if (method === 'GET') {\n sendJson(res, 200, store.summary())\n return true\n }\n sendError(res, 405, 'METHOD_NOT_ALLOWED', `Use GET on ${CSRF_READINESS_PATH}`)\n return true\n }\n\n if (url === CSRF_READINESS_RESET_PATH) {\n if (method !== 'POST') {\n sendError(res, 405, 'METHOD_NOT_ALLOWED', `Use POST on ${CSRF_READINESS_RESET_PATH}`)\n return true\n }\n // Enforce CSRF on our own endpoint (dog-food).\n const hasHeader = req.headers['x-theo-action'] === '1'\n if (!hasHeader || !originMatchesHost(req)) {\n sendError(res, 403, 'CSRF_INVALID', 'Reset requires X-Theo-Action: 1 + same-origin')\n return true\n }\n store.reset()\n sendNoContent(res)\n return true\n }\n\n return false\n}\n\n/**\n * T5a.2 Phase B slice 3/6 — Web-Standards-shaped CSRF readiness handler.\n *\n * Mirror of `handleCsrfReadiness(req: IncomingMessage, res: ServerResponse,\n * store): Promise<boolean>` for the Web `Request` shape. Returns\n * `Response | null` instead of mutating `res` and returning a boolean:\n * - `Response` → this handler claimed the URL; caller short-circuits.\n * - `null` → URL doesn't match our endpoint; caller continues normal dispatch.\n *\n * Same routes (GET `CSRF_READINESS_PATH`, POST `CSRF_READINESS_RESET_PATH`).\n * Same CSRF dog-food on reset (X-Theo-Action + same-origin).\n *\n * Wire into `executeWebRequest` integration via a future Phase B sub-slice\n * (consumer can also call this directly today via the\n * `theokit/server/security` sub-path).\n */\nfunction buildJsonResponse(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n })\n}\n\nfunction buildErrorResponse(status: number, code: string, message: string): Response {\n return buildJsonResponse(status, { error: { code, message } })\n}\n\n/**\n * Returns true when `Origin` header and request URL host match (RFC 6454\n * same-origin check). Web-Standards counterpart of `originMatchesHost`.\n */\nfunction originMatchesHostFromRequest(request: Request): boolean {\n const origin = request.headers.get('origin')\n if (origin === null || origin.length === 0) return false\n const host = request.headers.get('host')\n if (host === null || host.length === 0) {\n // Fallback: derive host from request.url (Web Request guarantees absolute URL)\n try {\n const reqHost = new URL(request.url).host\n const originHost = new URL(origin).host\n return originHost === reqHost\n } catch {\n return false\n }\n }\n try {\n return new URL(origin).host === host\n } catch {\n return false\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async return for future telemetry hooks\nexport async function handleCsrfReadinessRequest(\n request: Request,\n store: CsrfReadinessStore,\n): Promise<Response | null> {\n const url = new URL(request.url).pathname\n const method = request.method.toUpperCase()\n\n if (url === CSRF_READINESS_PATH) {\n if (method === 'GET') {\n return buildJsonResponse(200, store.summary())\n }\n return buildErrorResponse(405, 'METHOD_NOT_ALLOWED', `Use GET on ${CSRF_READINESS_PATH}`)\n }\n\n if (url === CSRF_READINESS_RESET_PATH) {\n if (method !== 'POST') {\n return buildErrorResponse(\n 405,\n 'METHOD_NOT_ALLOWED',\n `Use POST on ${CSRF_READINESS_RESET_PATH}`,\n )\n }\n // Enforce CSRF on our own endpoint (dog-food).\n const hasHeader = request.headers.get('x-theo-action') === '1'\n if (!hasHeader || !originMatchesHostFromRequest(request)) {\n return buildErrorResponse(\n 403,\n 'CSRF_INVALID',\n 'Reset requires X-Theo-Action: 1 + same-origin',\n )\n }\n store.reset()\n return new Response(null, { status: 204 })\n }\n\n return null\n}\n","/**\n * T2.2 — In-memory bounded counter for CSRF warn events.\n *\n * Aggregates `csrf.warn` payloads by `(method, path, reason)` triple.\n * Used by the `/__theo/csrf-readiness` endpoint to expose a summary the\n * developer (or devtools tab) can inspect, so users do NOT need to grep\n * stdout to know which endpoints will break under 0.3.0 strict CSRF.\n *\n * Bounded at 1000 distinct keys (EC-22). Eviction is LRU-by-insertion —\n * when the cap is hit, the oldest key is dropped and a re-record of an\n * evicted key starts fresh (count: 1).\n *\n * Single-threaded by virtue of the JS event loop; Map operations are\n * atomic. NOT shared across processes — each worker has its own store.\n */\n\nexport interface CsrfWarnRecord {\n method: string\n path: string\n reason: string\n}\n\nexport interface CsrfReadinessRouteSummary {\n method: string\n path: string\n reason: string\n count: number\n firstSeen: string\n lastSeen: string\n}\n\nexport interface CsrfReadinessSummary {\n generatedAt: string\n totalEvents: number\n routes: CsrfReadinessRouteSummary[]\n}\n\ninterface StoredEntry {\n count: number\n firstSeen: string\n lastSeen: string\n}\n\nexport class CsrfReadinessStore {\n static readonly MAX_ENTRIES = 1000\n private readonly entries = new Map<string, StoredEntry>()\n\n private keyFor(event: CsrfWarnRecord): string {\n return `${event.method}\u0000${event.path}\u0000${event.reason}`\n }\n\n record(event: CsrfWarnRecord): void {\n const key = this.keyFor(event)\n const now = new Date().toISOString()\n const existing = this.entries.get(key)\n if (existing) {\n existing.count++\n existing.lastSeen = now\n return\n }\n if (this.entries.size >= CsrfReadinessStore.MAX_ENTRIES) {\n const firstKey = this.entries.keys().next().value\n if (firstKey !== undefined) this.entries.delete(firstKey)\n }\n this.entries.set(key, { count: 1, firstSeen: now, lastSeen: now })\n }\n\n summary(): CsrfReadinessSummary {\n let total = 0\n const routes: CsrfReadinessRouteSummary[] = []\n for (const [key, entry] of this.entries) {\n const [method, path, reason] = key.split('\u0000')\n routes.push({\n method,\n path,\n reason,\n count: entry.count,\n firstSeen: entry.firstSeen,\n lastSeen: entry.lastSeen,\n })\n total += entry.count\n }\n return {\n generatedAt: new Date().toISOString(),\n totalEvents: total,\n routes,\n }\n }\n\n reset(): void {\n this.entries.clear()\n }\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAS,mBAAgC;AAEzC,SAAS,YAAY;AAErB,SAAS,wBAAwB,yBAAyB;AAyB1D,IAAM,yBAAyB,oBAAI,IAAI,CAAC,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAGzE,SAAS,oBAAoB,KAAuB;AAClD,QAAM,QAAkB,CAAC;AACzB,QAAM,OAAO,CAAC,YAA0B;AACtC,QAAI;AACJ,QAAI;AACF,gBAAU,YAAY,SAAS,EAAE,eAAe,KAAK,CAAC;AAAA,IACxD,QAAQ;AACN;AAAA,IACF;AACA,eAAW,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