theokit 0.37.0 → 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-6HQK5GHV.js → actions-virtual-module-H3LY5Q22.js} +3 -3
- package/dist/{actions-virtual-module-HYCFRMC3.js → actions-virtual-module-WLOT2SPR.js} +3 -3
- package/dist/{agent-PSJ77NJA.js → agent-VQMWM5BK.js} +2 -2
- package/dist/{app-typed-client-X2A6NMI2.js → app-typed-client-67GBLYD6.js} +113 -24
- package/dist/app-typed-client-67GBLYD6.js.map +1 -0
- package/dist/{app-typed-client-K3PXIZDZ.js → app-typed-client-SPFNGVZL.js} +113 -24
- package/dist/app-typed-client-SPFNGVZL.js.map +1 -0
- package/dist/{build-4HOXGMZV.js → build-3BFIACHN.js} +6 -6
- package/dist/{chunk-J5PK5FRN.js → chunk-2HKRQUWU.js} +2 -2
- package/dist/{chunk-PMBYKLLN.js → chunk-BKYFOEBK.js} +3 -1
- package/dist/{chunk-4FE56YQP.js → chunk-GW5H4KB4.js} +2 -2
- package/dist/{chunk-EZWFDHTI.js → chunk-IPSFSNEJ.js} +2 -2
- package/dist/{chunk-GNUXRXHI.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-XQPBWMC2.js → chunk-QCB7ZNR2.js} +91 -36
- package/dist/chunk-QCB7ZNR2.js.map +1 -0
- package/dist/{chunk-AXF3KYY5.js → chunk-QMV3R6D5.js} +88 -35
- 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-2WTL2GZO.js → chunk-QWBXUZAX.js} +2 -1
- 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-GA572OS7.js → dev-IBCZYFZZ.js} +8 -8
- package/dist/index.js +4 -4
- package/dist/{internal-api-N6JGTRMN.js → internal-api-MDCX7A7H.js} +8 -3
- package/dist/{internal-api-TV4CFQY2.js → internal-api-OLNM25HS.js} +7 -3
- package/dist/{mcp-Z3SZULLS.js → mcp-DKRODZAL.js} +2 -2
- package/dist/{registry-3NB7KOUI.js → registry-FKPH7XEL.js} +1 -1
- package/dist/server/http/index.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/{start-SWWCB36Q.js → start-WB7GYXEW.js} +3 -3
- package/dist/vite-plugin/index.js +4 -4
- package/dist/{vite-plugin-OY5ESFTR.js → vite-plugin-5Y3LDTXI.js} +5 -5
- package/package.json +2 -2
- package/dist/app-typed-client-K3PXIZDZ.js.map +0 -1
- package/dist/app-typed-client-X2A6NMI2.js.map +0 -1
- package/dist/chunk-AXF3KYY5.js.map +0 -1
- package/dist/chunk-CEHXC5NI.js.map +0 -1
- package/dist/chunk-GNUXRXHI.js.map +0 -1
- package/dist/chunk-VB2WWBIT.js +0 -1
- package/dist/chunk-XQPBWMC2.js.map +0 -1
- package/dist/vite-plugin-OY5ESFTR.js.map +0 -1
- /package/dist/{actions-virtual-module-6HQK5GHV.js.map → actions-virtual-module-H3LY5Q22.js.map} +0 -0
- /package/dist/{actions-virtual-module-HYCFRMC3.js.map → actions-virtual-module-WLOT2SPR.js.map} +0 -0
- /package/dist/{agent-PSJ77NJA.js.map → agent-VQMWM5BK.js.map} +0 -0
- /package/dist/{build-4HOXGMZV.js.map → build-3BFIACHN.js.map} +0 -0
- /package/dist/{chunk-J5PK5FRN.js.map → chunk-2HKRQUWU.js.map} +0 -0
- /package/dist/{chunk-PMBYKLLN.js.map → chunk-BKYFOEBK.js.map} +0 -0
- /package/dist/{chunk-4FE56YQP.js.map → chunk-GW5H4KB4.js.map} +0 -0
- /package/dist/{chunk-EZWFDHTI.js.map → chunk-IPSFSNEJ.js.map} +0 -0
- /package/dist/{chunk-2WTL2GZO.js.map → chunk-QWBXUZAX.js.map} +0 -0
- /package/dist/{dev-GA572OS7.js.map → dev-IBCZYFZZ.js.map} +0 -0
- /package/dist/{chunk-VB2WWBIT.js.map → internal-api-MDCX7A7H.js.map} +0 -0
- /package/dist/{internal-api-N6JGTRMN.js.map → internal-api-OLNM25HS.js.map} +0 -0
- /package/dist/{mcp-Z3SZULLS.js.map → mcp-DKRODZAL.js.map} +0 -0
- /package/dist/{registry-3NB7KOUI.js.map → registry-FKPH7XEL.js.map} +0 -0
- /package/dist/{start-SWWCB36Q.js.map → start-WB7GYXEW.js.map} +0 -0
- /package/dist/{internal-api-TV4CFQY2.js.map → vite-plugin-5Y3LDTXI.js.map} +0 -0
|
@@ -1423,6 +1423,7 @@ export {
|
|
|
1423
1423
|
extractUniversalIssues,
|
|
1424
1424
|
isActionError,
|
|
1425
1425
|
isInputError,
|
|
1426
|
+
dispatchCsrfWarn,
|
|
1426
1427
|
sendJson,
|
|
1427
1428
|
sendError,
|
|
1428
1429
|
isZodLike,
|
|
@@ -1447,4 +1448,4 @@ export {
|
|
|
1447
1448
|
extractTraceId,
|
|
1448
1449
|
extractTraceIdFromRequest
|
|
1449
1450
|
};
|
|
1450
|
-
//# sourceMappingURL=chunk-
|
|
1451
|
+
//# sourceMappingURL=chunk-QWBXUZAX.js.map
|
package/dist/cli/index.js
CHANGED
|
@@ -5,12 +5,12 @@ import "tsx/esm";
|
|
|
5
5
|
import cac from "cac";
|
|
6
6
|
var cli = cac("theokit");
|
|
7
7
|
cli.command("dev", "Start development server").option("--port <port>", "Port number").action(async (options) => {
|
|
8
|
-
const { devCommand } = await import("../dev-
|
|
8
|
+
const { devCommand } = await import("../dev-IBCZYFZZ.js");
|
|
9
9
|
await devCommand({ port: options.port ? Number(options.port) : void 0 });
|
|
10
10
|
});
|
|
11
11
|
cli.command("build", "Build for production").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
|
|
12
12
|
try {
|
|
13
|
-
const { buildCommand } = await import("../build-
|
|
13
|
+
const { buildCommand } = await import("../build-3BFIACHN.js");
|
|
14
14
|
await buildCommand({ target: options.target });
|
|
15
15
|
} catch (err) {
|
|
16
16
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -22,7 +22,7 @@ cli.command("build", "Build for production").option("--target <target>", "Deploy
|
|
|
22
22
|
});
|
|
23
23
|
cli.command("start", "Start production server").option("--port <port>", "Port number").action(async (options) => {
|
|
24
24
|
try {
|
|
25
|
-
const { startCommand } = await import("../start-
|
|
25
|
+
const { startCommand } = await import("../start-WB7GYXEW.js");
|
|
26
26
|
await startCommand({ port: options.port ? Number(options.port) : void 0 });
|
|
27
27
|
} catch (err) {
|
|
28
28
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -52,7 +52,7 @@ cli.command(
|
|
|
52
52
|
"Run an agent in the terminal (stream + tool calls + approval)"
|
|
53
53
|
).action(async (name, message) => {
|
|
54
54
|
try {
|
|
55
|
-
const { agentCommand } = await import("../agent-
|
|
55
|
+
const { agentCommand } = await import("../agent-VQMWM5BK.js");
|
|
56
56
|
const { sawError } = await agentCommand(name, message);
|
|
57
57
|
if (sawError) process.exit(1);
|
|
58
58
|
} catch (err) {
|
|
@@ -65,7 +65,7 @@ cli.command(
|
|
|
65
65
|
});
|
|
66
66
|
cli.command("mcp <agent>", "Serve an agent as an MCP server over stdio (for desktop MCP clients)").action(async (agent) => {
|
|
67
67
|
try {
|
|
68
|
-
const { mcpCommand } = await import("../mcp-
|
|
68
|
+
const { mcpCommand } = await import("../mcp-DKRODZAL.js");
|
|
69
69
|
await mcpCommand(agent);
|
|
70
70
|
} catch (err) {
|
|
71
71
|
const msg = err instanceof Error ? err.message : String(err);
|
package/dist/client/core.d.ts
CHANGED
|
@@ -46,7 +46,14 @@ type AgentTransport = ChatTransport<UIMessage> & {
|
|
|
46
46
|
type UseAgentStatus = 'idle' | 'streaming' | 'done' | 'error';
|
|
47
47
|
/** The observable state the store exposes (stable reference between emits — `useSyncExternalStore` contract). */
|
|
48
48
|
interface AgentClientState {
|
|
49
|
+
/** The CURRENT turn's assistant messages (per-turn; reset each `send`). Back-compat — unchanged since M41. */
|
|
49
50
|
messages: UIMessage[];
|
|
51
|
+
/**
|
|
52
|
+
* M46 — the full conversation: committed turns + the current turn's user message + in-flight assistant.
|
|
53
|
+
* Accumulated across sends (never reset except by `reset()`), with stable ids committed exactly once.
|
|
54
|
+
* Render this instead of hand-rolling a transcript from `messages`.
|
|
55
|
+
*/
|
|
56
|
+
thread: UIMessage[];
|
|
50
57
|
status: UseAgentStatus;
|
|
51
58
|
error: Error | undefined;
|
|
52
59
|
}
|
|
@@ -105,7 +112,11 @@ interface AgentClientHandle<TInput = unknown> {
|
|
|
105
112
|
reconnect(): void;
|
|
106
113
|
/** Subscribe to state changes; returns an unsubscribe fn. */
|
|
107
114
|
subscribe(listener: () => void): () => void;
|
|
108
|
-
/**
|
|
115
|
+
/**
|
|
116
|
+
* The current immutable snapshot: per-turn `messages` (back-compat) + the full conversation `thread`
|
|
117
|
+
* (M46 — committed history + in-flight, accumulated across sends) + `status` / `error`. A TUI / vanilla
|
|
118
|
+
* consumer renders `thread` directly without hand-rolling a transcript.
|
|
119
|
+
*/
|
|
109
120
|
getState(): AgentClientState;
|
|
110
121
|
/**
|
|
111
122
|
* Drive one turn and yield the assistant `UIMessage` as it streams (progressive snapshots); iteration
|
package/dist/client/core.js
CHANGED
package/dist/client/index.d.ts
CHANGED
|
@@ -118,8 +118,14 @@ interface Batcher {
|
|
|
118
118
|
declare function createBatcher(options: BatcherOptions): Batcher;
|
|
119
119
|
|
|
120
120
|
interface UseAgentReturn<TInput = unknown, TToolNames extends string = string> {
|
|
121
|
-
/**
|
|
121
|
+
/** The CURRENT turn's assistant messages (per-turn; reset each `send`). Back-compat since M41. */
|
|
122
122
|
messages: UIMessage[];
|
|
123
|
+
/**
|
|
124
|
+
* M46 — the full conversation to render: committed turns + the current turn's user + in-flight
|
|
125
|
+
* assistant, accumulated across sends with stable ids. Prefer this over hand-rolling a transcript
|
|
126
|
+
* from `messages`. Same shape on every surface (web/desktop/TUI) — it lives in the core store.
|
|
127
|
+
*/
|
|
128
|
+
thread: UIMessage[];
|
|
123
129
|
status: UseAgentStatus;
|
|
124
130
|
/** The last error, or `undefined`. */
|
|
125
131
|
error: Error | undefined;
|
package/dist/client/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
consumeUIMessageStream,
|
|
8
8
|
createAgentClient,
|
|
9
9
|
responseToChunkStream
|
|
10
|
-
} from "../chunk-
|
|
10
|
+
} from "../chunk-Q3C3KH3C.js";
|
|
11
11
|
import {
|
|
12
12
|
buildUseTheoQueryConfig,
|
|
13
13
|
stableQueryKey
|
|
@@ -418,6 +418,7 @@ function useAgent(pathOrTransport, options = {}) {
|
|
|
418
418
|
const state = useSyncExternalStore(client.subscribe, client.getSnapshot, client.getSnapshot);
|
|
419
419
|
return {
|
|
420
420
|
messages: state.messages,
|
|
421
|
+
thread: state.thread,
|
|
421
422
|
status: state.status,
|
|
422
423
|
error: state.error,
|
|
423
424
|
send: client.send,
|
package/dist/client/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/theo-fetch.ts","../../src/client/batch.ts","../../src/client/batch-transport.ts","../../src/client/app-client.ts","../../src/client/use-agent.ts","../../src/client/link.tsx","../../src/client/metadata.tsx","../../src/client/image.tsx","../../src/client/mcp-app-host.ts"],"sourcesContent":["import superjson from 'superjson'\nimport type { z } from 'zod'\n\nimport type { TheoErrorCode, TheoErrorEnvelope } from '../core/contracts/error-envelope.js'\n\nimport { getGlobalBatcher } from './batch-transport.js'\n\n// --- Transformer (T1.3) ---\n\n/**\n * Module-scoped flag preventing the transformer-mismatch warning from\n * firing more than once per session (EC-6).\n */\nlet mismatchWarned = false\n\n/** Test-only helper to reset the warned flag between assertions. */\nexport function __resetMismatchWarningForTests(): void {\n mismatchWarned = false\n}\n\n/**\n * Deserialize a fetch response body according to the negotiated transformer.\n *\n * `serverTransformerName` comes from the `x-theo-transformer` response header\n * (null when absent — server is using the default JSON path).\n * `clientTransformerName` is the transformer the client was built with\n * (typically injected via a Vite virtual module; falls back to `'json'`).\n *\n * Mismatch fires a single console.warn and falls back to JSON.parse (EC-5/EC-6).\n */\nexport function deserializeFetchResponse(\n raw: string,\n serverTransformerName: string | null,\n clientTransformerName: string,\n): unknown {\n // `raw` is typed `string`, but stay defensive: callers pass `await response.text()`\n // which can be empty.\n if (raw === '') {\n return null\n }\n\n const serverEffective = serverTransformerName ?? 'json'\n if (serverEffective !== clientTransformerName && !mismatchWarned) {\n mismatchWarned = true\n console.warn(\n `[theokit] transformer mismatch: server=${serverEffective}, client=${clientTransformerName}. Falling back to JSON.parse.`,\n )\n }\n\n if (serverEffective === 'superjson' && clientTransformerName === 'superjson') {\n const wrapped = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(wrapped)\n }\n\n // Default path (json) or mismatch fallback\n return JSON.parse(raw)\n}\n\n// --- Utility Types ---\n\n/** Infer the response type from a route's handler return */\nexport type InferResponse<T> = T extends { handler: (...args: never[]) => infer R }\n ? Awaited<R>\n : unknown\n\n/** Extract the query Zod schema type, handling optional properties */\ntype ExtractQuery<T> = T extends { query?: infer Q } ? (Q extends z.ZodType ? Q : never) : never\n\n/** Extract the body Zod schema type, handling optional properties */\ntype ExtractBody<T> = T extends { body?: infer B } ? (B extends z.ZodType ? B : never) : never\n\n/** Infer query type from a route's query Zod schema */\nexport type InferQuery<T> = [ExtractQuery<T>] extends [never]\n ? undefined\n : ExtractQuery<T> extends z.ZodUndefined\n ? undefined\n : z.infer<ExtractQuery<T>>\n\n/** Infer body type from a route's body Zod schema */\nexport type InferBody<T> = [ExtractBody<T>] extends [never]\n ? undefined\n : ExtractBody<T> extends z.ZodUndefined\n ? undefined\n : z.infer<ExtractBody<T>>\n\n/** Build the options type based on what schemas the route has */\nexport type TheoFetchOptions<T> = Omit<RequestInit, 'body' | 'method'> &\n (InferQuery<T> extends undefined ? { query?: never } : { query: InferQuery<T> }) &\n (InferBody<T> extends undefined ? { body?: never } : { body: InferBody<T> })\n\n// --- Error Class ---\n\n/**\n * G5 T2.1 — extract a TheoErrorEnvelope from a response body. Supports both\n * the new envelope-at-root shape (`{ code, message, ext?, ... }`, blueprint\n * Recommendations § concrete shape) and the legacy nested shape\n * (`{ error: { code, message, issues? } }`, G3 SerializedActionResult).\n *\n * Falls back to `INTERNAL_SERVER_ERROR` with a synthetic message when the\n * body shape is unrecognized. Pure; no I/O.\n */\nfunction extractEnvelope(status: number, body: unknown): TheoErrorEnvelope {\n if (!body || typeof body !== 'object') {\n return { code: 'INTERNAL_SERVER_ERROR', message: `HTTP ${String(status)}` }\n }\n const obj = body as Record<string, unknown>\n // New shape — envelope at root\n if (typeof obj.code === 'string' && typeof obj.message === 'string') {\n return {\n code: obj.code as TheoErrorCode,\n message: obj.message,\n cause: obj.cause,\n meta: obj.meta as Record<string, unknown> | undefined,\n ext: obj.ext,\n }\n }\n // Legacy shape — { error: { code, message, ... } }\n if (obj.error && typeof obj.error === 'object') {\n const nested = obj.error as Record<string, unknown>\n return {\n code:\n typeof nested.code === 'string' ? (nested.code as TheoErrorCode) : 'INTERNAL_SERVER_ERROR',\n message: typeof nested.message === 'string' ? nested.message : `HTTP ${String(status)}`,\n }\n }\n return { code: 'INTERNAL_SERVER_ERROR', message: `HTTP ${String(status)}` }\n}\n\n/**\n * Pull a single string field from an object, returning undefined if missing\n * or non-string. Helper for `extractLegacyFields` to stay under the\n * complexity ceiling.\n */\nfunction strField(obj: Record<string, unknown> | null, key: string): string | undefined {\n const v = obj?.[key]\n return typeof v === 'string' ? v : undefined\n}\n\n/**\n * Pull the canonical {message, code, issues} from either an envelope-at-root\n * body or the legacy { error: {...} } body. Pure.\n */\nfunction extractLegacyFields(\n status: number,\n body: unknown,\n): { message: string; code?: string; issues?: unknown[] } {\n if (!body || typeof body !== 'object') {\n return { message: `HTTP ${String(status)}` }\n }\n const obj = body as Record<string, unknown>\n const nested =\n obj.error && typeof obj.error === 'object' ? (obj.error as Record<string, unknown>) : null\n const issues = Array.isArray(nested?.issues) ? nested.issues : undefined\n return {\n message: strField(obj, 'message') ?? strField(nested, 'message') ?? `HTTP ${String(status)}`,\n code: strField(obj, 'code') ?? strField(nested, 'code'),\n issues,\n }\n}\n\nexport class TheoFetchError extends Error {\n status: number\n code?: string\n issues?: unknown[]\n /**\n * G5 T2.1 — canonical envelope view of the server-side error. Use this in\n * consumer code that wants to switch on a typed TheoErrorCode instead of\n * coupling to the legacy `.status` / `.code` flat fields.\n */\n readonly envelope: TheoErrorEnvelope\n\n constructor(status: number, body?: unknown) {\n const legacy = extractLegacyFields(status, body)\n super(legacy.message)\n this.name = 'TheoFetchError'\n this.status = status\n this.code = legacy.code\n this.issues = legacy.issues\n this.envelope = extractEnvelope(status, body)\n }\n}\n\n/**\n * Serialize a query-param value to a string. Handles primitives, dates,\n * and falls back to JSON for arrays/objects. Avoids the\n * `[object Object]` foot-gun that `no-base-to-string` warns against.\n */\nfunction stringifyQueryValue(value: unknown): string {\n if (value === null) return 'null'\n if (value instanceof Date) return value.toISOString()\n switch (typeof value) {\n case 'string':\n return value\n case 'number':\n case 'boolean':\n case 'bigint':\n return String(value)\n default:\n return JSON.stringify(value)\n }\n}\n\n// --- Main Function ---\n\ninterface TheoFetchInternalOptions {\n method?: string\n query?: Record<string, unknown>\n body?: unknown\n headers?: HeadersInit\n signal?: AbortSignal\n}\n\n/**\n * Resolve the request origin per the documented fallback hierarchy. Pure\n * helper extracted to keep `theoFetch` under the complexity ceiling.\n * 1. `globalThis.location.origin` (browser)\n * 2. `globalThis.__THEO_ORIGIN__` (build-time literal)\n * 3. `process.env.THEO_ORIGIN` (escape hatch)\n * 4. `http://localhost` (placeholder for URL parsing — the URL is built\n * relative so only pathname+search ever flows to the wire)\n */\nfunction resolveRequestOrigin(): string {\n const g = globalThis as { location?: { origin?: string }; __THEO_ORIGIN__?: string }\n const fromEnv = typeof process !== 'undefined' ? process.env.THEO_ORIGIN : undefined\n return g.location?.origin ?? g.__THEO_ORIGIN__ ?? fromEnv ?? 'http://localhost'\n}\n\nfunction buildFetchUrl(path: string, query: Record<string, unknown> | undefined): URL {\n const fetchUrl = new URL(path, resolveRequestOrigin())\n if (!query) return fetchUrl\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined) {\n fetchUrl.searchParams.set(k, stringifyQueryValue(v))\n }\n }\n return fetchUrl\n}\n\n/**\n * Normalize `HeadersInit` (Headers / `[string, string][]` / Record) into a\n * single plain `Record<string, string>`. Plain-object output is required\n * by callers that introspect headers via index access (test fixtures use\n * `(init.headers as Record<string, string>)['Content-Type']`).\n */\nfunction normalizeHeaders(input: HeadersInit | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n if (!input) return out\n if (input instanceof Headers) {\n input.forEach((value, key) => {\n out[key] = value\n })\n return out\n }\n if (Array.isArray(input)) {\n for (const [key, value] of input) out[key] = value\n return out\n }\n for (const [key, value] of Object.entries(input)) {\n out[key] = value\n }\n return out\n}\n\nfunction buildRequestInit(opts: TheoFetchInternalOptions): RequestInit {\n const init: RequestInit = {}\n if (opts.method !== undefined) init.method = opts.method\n if (opts.signal !== undefined) init.signal = opts.signal\n\n const headers = normalizeHeaders(opts.headers)\n init.headers = headers\n\n if (opts.body !== undefined) {\n init.body = JSON.stringify(opts.body)\n headers['Content-Type'] = 'application/json'\n }\n\n // Phase 5 — Auto-attach `X-Theo-Action: 1` for state-mutating methods so\n // the framework's CSRF check passes when servers run in `strict` mode.\n // Safe methods (GET/HEAD/OPTIONS) skip the header to keep them cacheable.\n const method = (opts.method ?? 'GET').toUpperCase()\n if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') {\n headers['X-Theo-Action'] = '1'\n }\n return init\n}\n\nasync function tryBatcher(\n url: string,\n options: TheoFetchInternalOptions,\n): Promise<{ matched: true; result: unknown } | { matched: false }> {\n const batcher = getGlobalBatcher()\n if (!batcher) return { matched: false }\n try {\n const result = await batcher.dispatch({\n path: url,\n method: options.method ?? 'GET',\n query: options.query,\n body: options.body,\n })\n return { matched: true, result }\n } catch {\n // Batcher failure: fall through to direct fetch (graceful degrade).\n return { matched: false }\n }\n}\n\nexport async function theoFetch<T>(\n url: string,\n options?: TheoFetchOptions<T>,\n): Promise<InferResponse<T>> {\n const internal = (options ?? {}) as unknown as TheoFetchInternalOptions\n\n // T1.5 — Transparent batching when globalThis.__THEO_BATCHING__ is truthy.\n const batchAttempt = await tryBatcher(url, internal)\n if (batchAttempt.matched) {\n return batchAttempt.result as InferResponse<T>\n }\n\n const fetchUrl = buildFetchUrl(url, internal.query)\n const init = buildRequestInit(internal)\n const response = await fetch(fetchUrl.toString(), init)\n\n if (!response.ok) {\n let errorBody: unknown\n try {\n errorBody = await response.json()\n } catch {\n // Non-JSON error response\n }\n throw new TheoFetchError(response.status, errorBody)\n }\n\n // Handle 204 No Content (EC-1)\n if (response.status === 204) {\n return null as InferResponse<T>\n }\n\n // Check for empty body\n const contentLength = response.headers.get('content-length')\n if (contentLength === '0') {\n return null as InferResponse<T>\n }\n\n // T1.3 — transformer-aware deserialization\n const serverTransformerName = response.headers.get('x-theo-transformer')\n const clientTransformerName = resolveClientTransformerName()\n const text = await response.text()\n return deserializeFetchResponse(\n text,\n serverTransformerName,\n clientTransformerName,\n ) as InferResponse<T>\n}\n\n/**\n * Read the client-configured transformer name. Default `'json'`.\n *\n * In a Vite build, this is overridden by virtual module\n * `/@theo/runtime-config` which sets `globalThis.__THEO_TRANSFORMER__`.\n * Outside Vite (Node SSR, tests) the default applies.\n */\nfunction resolveClientTransformerName(): string {\n const g = globalThis as { __THEO_TRANSFORMER__?: string }\n return g.__THEO_TRANSFORMER__ ?? 'json'\n}\n","/**\n * T5.1 — client-side microtask batching.\n *\n * Collects all `dispatch` calls within the same microtask and sends them as a\n * single HTTP POST to the configured transport. Each caller's promise resolves\n * with its own result; one failed item does not break the others (per-item\n * error isolation).\n *\n * Designed as a transport-agnostic primitive so unit tests do not require\n * network access. The default transport (fetch to `/api/__theo_batch__`)\n * lives alongside this module but is created by the consumer (e.g., theoFetch).\n */\n\nexport interface BatchRequest {\n path: string\n method: string\n query?: Record<string, unknown>\n body?: unknown\n headers?: Record<string, string>\n}\n\nexport type BatchResponse =\n | { index: number; data: unknown }\n | { index: number; error: { message: string; code?: string } }\n\nexport type BatchTransport = (requests: BatchRequest[]) => Promise<BatchResponse[]>\n\nexport interface BatcherOptions {\n transport: BatchTransport\n /** Maximum batch size before flushing into multiple parallel batches. */\n max?: number\n}\n\nexport interface Batcher {\n dispatch(req: BatchRequest): Promise<unknown>\n}\n\ninterface PendingCall {\n req: BatchRequest\n resolve: (value: unknown) => void\n reject: (reason: unknown) => void\n}\n\nexport function createBatcher(options: BatcherOptions): Batcher {\n const max = options.max ?? 32\n let queue: PendingCall[] = []\n let flushScheduled = false\n\n function flush(): void {\n flushScheduled = false\n const current = queue\n queue = []\n if (current.length === 0) return\n\n // Split into chunks respecting max\n const chunks: PendingCall[][] = []\n for (let i = 0; i < current.length; i += max) {\n chunks.push(current.slice(i, i + max))\n }\n\n for (const chunk of chunks) {\n const payload: BatchRequest[] = chunk.map((p) => p.req)\n options\n .transport(payload)\n .then((results) => {\n for (let i = 0; i < chunk.length; i++) {\n // `results[i]` could be undefined at runtime when the transport\n // returns fewer entries than the chunk; TypeScript's strict\n // typing without `noUncheckedIndexedAccess` does not surface\n // this, so we hand-narrow.\n const result = results.length > i ? results[i] : undefined\n if (result === undefined) {\n chunk[i].reject(new Error(`Batch transport returned no result for index ${i}`))\n continue\n }\n if ('error' in result) {\n const err = new Error(result.error.message)\n ;(err as { code?: string }).code = result.error.code\n chunk[i].reject(err)\n } else {\n chunk[i].resolve(result.data)\n }\n }\n })\n .catch((err: unknown) => {\n for (const item of chunk) item.reject(err)\n })\n }\n }\n\n return {\n dispatch(req: BatchRequest): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n queue.push({ req, resolve, reject })\n if (!flushScheduled) {\n flushScheduled = true\n queueMicrotask(flush)\n }\n })\n },\n }\n}\n","/**\n * T1.5 — Default HTTP transport for the client batcher.\n *\n * Wraps `fetch` to POST `/api/__theo_batch__` with the collected requests\n * and return the array of per-item results.\n */\n\nimport {\n createBatcher,\n type BatchTransport,\n type Batcher,\n type BatchRequest,\n type BatchResponse,\n} from './batch.js'\n\nconst BATCH_ENDPOINT = '/api/__theo_batch__'\n\nexport interface CreateBatchTransportOptions {\n /** Override fetch (default: globalThis.fetch). Used by tests. */\n fetchImpl?: typeof fetch\n /** Override endpoint (default '/api/__theo_batch__'). */\n endpoint?: string\n}\n\nexport function createBatchTransport(options: CreateBatchTransportOptions = {}): BatchTransport {\n const fetchImpl = options.fetchImpl ?? fetch\n const endpoint = options.endpoint ?? BATCH_ENDPOINT\n return async (requests: BatchRequest[]): Promise<BatchResponse[]> => {\n const response = await fetchImpl(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ requests }),\n })\n if (!response.ok) {\n throw new Error(`Batch transport returned ${response.status}`)\n }\n const payload = (await response.json()) as { results?: BatchResponse[] }\n if (!Array.isArray(payload.results)) {\n throw new Error('Batch response missing results array')\n }\n // Map results to indexed BatchResponse shape (server already returns the right form)\n return payload.results.map((item, index) => {\n if ('error' in item) {\n return { index, error: (item as { error: { message: string; code?: string } }).error }\n }\n return { index, data: (item as { data: unknown }).data }\n })\n }\n}\n\n// --- EC-7: singleton batcher per page, lazy-instantiated ---\n\nlet globalBatcher: Batcher | undefined\n\n/** Test-only — reset the module-scope singleton between assertions. */\nexport function __resetGlobalBatcherForTests(): void {\n globalBatcher = undefined\n}\n\n/**\n * Returns the global batcher singleton when `globalThis.__THEO_BATCHING__` is\n * truthy; undefined otherwise. Lazy-instantiated on first call.\n */\nexport function getGlobalBatcher(): Batcher | undefined {\n const g = globalThis as { __THEO_BATCHING__?: boolean }\n if (!g.__THEO_BATCHING__) return undefined\n globalBatcher ??= createBatcher({ transport: createBatchTransport() })\n return globalBatcher\n}\n","/**\n * Phase 3 of G1 (g1-client-codegen-plan.md):\n *\n * `createAppClient(baseUrl?, fetchImpl?)` returns a Proxy that walks property\n * access (`client.posts.id.get(...)`) into a `theoFetch` invocation against\n * `{baseUrl}/posts/{params.id}` with method `GET`.\n *\n * Type safety is delivered by the `.d.ts` file emitted in Phase 2 — this\n * runtime is structurally untyped. Power users may use `theoFetch` directly\n * when they need to escape the Proxy facade.\n *\n * Edge cases absorbed:\n * - EC-1 (thenable trap): `then` / `catch` / `finally` / `toJSON` / `Symbol.*`\n * return `undefined` so that accidental `await client.posts` resolves to a\n * plain Proxy value (it is NOT thenable) instead of looping.\n * - EC-7 (abort signal): `opts.signal` is spread through to the underlying\n * fetchImpl unchanged — verified in unit tests.\n *\n * Bundle target: ≤ 2KB gzipped.\n */\n\nimport { theoFetch, TheoFetchError } from './theo-fetch.js'\nimport type { TheoFetchOptions } from './theo-fetch.js'\nimport { HTTP_METHOD_LOWERCASE } from '../core/contracts/http-methods.js'\n\nconst HTTP_METHODS_SET = new Set(HTTP_METHOD_LOWERCASE)\n\n/**\n * Keys that JavaScript runtime / inspectors / Promise resolution probe\n * unconditionally. Returning `undefined` for these keeps the Proxy from\n * pretending to be a thenable / iterable / serializable thing.\n */\nconst NON_INTERCEPT_KEYS = new Set([\n 'then',\n 'catch',\n 'finally',\n 'toJSON',\n 'toString',\n 'valueOf',\n 'constructor',\n 'prototype',\n])\n\ntype FetchImpl = typeof theoFetch\n\ninterface CallOptions {\n params?: Record<string, string | number>\n query?: Record<string, unknown>\n body?: unknown\n signal?: AbortSignal\n headers?: HeadersInit\n // arbitrary RequestInit fields (mode, credentials, cache, etc.)\n [k: string]: unknown\n}\n\nfunction injectParams(path: string, params?: Record<string, string | number>): string {\n if (!params) {\n if (/:(?:\\.\\.\\.)?[A-Za-z_]/.test(path)) {\n throw new TheoFetchError(0, {\n error: {\n code: 'MISSING_PARAM',\n message: `Route ${path} requires params but none were provided. Pass them via opts.params, e.g. client.posts.get({ params: { id: '123' } }).`,\n },\n })\n }\n return path\n }\n return path.replace(/:(?:\\.\\.\\.)?([A-Za-z_][A-Za-z0-9_]*)/g, (_match, key: string) => {\n const value = params[key]\n if (value === undefined || value === null || value === '') {\n throw new TheoFetchError(0, {\n error: {\n code: 'MISSING_PARAM',\n message: `Param '${key}' is required for path '${path}' but was missing/empty.`,\n },\n })\n }\n return encodeURIComponent(String(value))\n })\n}\n\ninterface ProxyContext {\n segments: string[]\n baseUrl: string\n fetchImpl: FetchImpl\n}\n\nfunction makeProxy(ctx: ProxyContext): unknown {\n const handler: ProxyHandler<() => void> = {\n get(_target, key) {\n if (typeof key !== 'string') return undefined\n if (NON_INTERCEPT_KEYS.has(key)) return undefined\n if (HTTP_METHODS_SET.has(key)) {\n return async (opts?: CallOptions) => {\n if (ctx.segments.length === 0) {\n throw new TheoFetchError(0, {\n error: {\n code: 'INVALID_PATH',\n message: `client.${key}() called without a route segment. Use client.<resource>.${key}(...) instead.`,\n },\n })\n }\n let finalPath = `${ctx.baseUrl}/${ctx.segments.join('/')}`\n if (opts?.params) {\n // Build a path with `:name` placeholders re-inserted from segments\n // whose name matches a key in opts.params (treat as dynamic).\n const segmentsWithDynamic = ctx.segments.map((seg) =>\n Object.prototype.hasOwnProperty.call(opts.params, seg) ? `:${seg}` : seg,\n )\n finalPath = injectParams(\n `${ctx.baseUrl}/${segmentsWithDynamic.join('/')}`,\n opts.params,\n )\n }\n const { params: _ignored, ...rest } = opts ?? {}\n const init = { method: key.toUpperCase(), ...rest } as unknown as TheoFetchOptions<unknown>\n return ctx.fetchImpl(finalPath, init)\n }\n }\n // Continue traversal — append segment to the path.\n return makeProxy({ ...ctx, segments: [...ctx.segments, key] })\n },\n apply() {\n return Promise.reject(\n new TheoFetchError(0, {\n error: {\n code: 'INVALID_CALL',\n message:\n 'client(...) is not callable. Use client.<resource>.<method>(opts?) — e.g. client.posts.get().',\n },\n }),\n )\n },\n }\n return new Proxy(() => undefined, handler)\n}\n\nexport interface CreateAppClientOptions {\n /** Base URL for the API. Defaults to `/api`. */\n baseUrl?: string\n /** Test-only fetch override. Production callers should not pass this. */\n fetchImpl?: FetchImpl\n}\n\nexport function createAppClient<TAppClient = unknown>(\n baseUrlOrOptions?: string | CreateAppClientOptions,\n legacyFetchImpl?: FetchImpl,\n): TAppClient {\n let baseUrl = '/api'\n let fetchImpl: FetchImpl = theoFetch\n if (typeof baseUrlOrOptions === 'string') {\n baseUrl = baseUrlOrOptions || '/api'\n } else if (baseUrlOrOptions && typeof baseUrlOrOptions === 'object') {\n if (baseUrlOrOptions.baseUrl) baseUrl = baseUrlOrOptions.baseUrl\n if (baseUrlOrOptions.fetchImpl) fetchImpl = baseUrlOrOptions.fetchImpl\n }\n // Legacy 2nd-arg fetchImpl overrides regardless of 1st-arg shape (test seam).\n if (legacyFetchImpl) fetchImpl = legacyFetchImpl\n // Strip trailing slash for predictable joining.\n if (baseUrl.length > 1 && baseUrl.endsWith('/')) baseUrl = baseUrl.slice(0, -1)\n return makeProxy({ segments: [], baseUrl, fetchImpl }) as TAppClient\n}\n","import type { UIMessage } from 'ai'\nimport { useMemo, useRef, useSyncExternalStore } from 'react'\n\nimport { AgentClient, type UseAgentStatus } from './agent-client.js'\nimport { HttpTransport } from './http-transport.js'\nimport type { AgentTransport, ApprovalDecision, RequestContext } from './transport.js'\n\n/**\n * M2 (theokit-ai-first) / M41 (ADR-0050) — `useAgent`, the ONE typed client hook for the\n * `agents/*.ts` convention, unified across surfaces.\n *\n * Pass an endpoint path (web) OR an {@link AgentTransport} (terminal/desktop). A string is wrapped in\n * an {@link HttpTransport} (exact back-compat with the pre-M41 fetch+SSE hook); an `InProcessTransport`\n * drives the SAME hook in a single process. The hook is a thin binding over the framework-agnostic\n * {@link AgentClient} store via React's native `useSyncExternalStore` (no test-DOM dependency). The\n * generated `@theo/agents` module types `send` to the agent's `input` schema — inferred end-to-end\n * from the server `defineAgent({ input })` with ZERO manual wiring.\n */\nexport type { UseAgentStatus }\n\nexport interface UseAgentReturn<TInput = unknown, TToolNames extends string = string> {\n /** Reconstructed assistant messages so far (ai `UIMessage[]`). */\n messages: UIMessage[]\n status: UseAgentStatus\n /** The last error, or `undefined`. */\n error: Error | undefined\n /** Send a request; opens a new stream. Typed to the agent's `input` schema. */\n send: (input: TInput) => void\n /** Abort an in-flight stream. */\n abort: () => void\n /** Clear messages + error, back to idle. */\n reset: () => void\n /** Settle a paused HITL approval (HTTP `POST /approve/<id>` for web; the inline callback in-process). */\n approve: (approvalId: string, decision: ApprovalDecision) => Promise<void>\n /** Resume an interrupted stream (M37 durable transport for web; a no-op in-process). */\n reconnect: () => void\n /**\n * The union of tool names this agent can emit (M8), carried end-to-end from the `agent()` builder's\n * accumulated tool-name type through the generated `@theo/agents` client. Type-only witness (never\n * populated at runtime). Resolves to the literal union for builder agents, `string` otherwise.\n */\n readonly __toolNames?: TToolNames\n}\n\nexport interface UseAgentOptions {\n /**\n * Extra request headers (e.g., auth) — applied when a string path builds an `HttpTransport`. Read on\n * EVERY request, so a value that changes across renders (a rotating JWT) is never sent stale.\n */\n headers?: Record<string, string>\n /** Override fetch (primarily for tests) — captured when a string path builds an `HttpTransport`. */\n fetch?: typeof fetch\n /**\n * M43 — per-request context attached uniformly to EVERY transport (`headers` → HTTP request headers;\n * `metadata` → the in-process runner / Tauri invoke). A value OR a resolver evaluated on every\n * send/reconnect, so a rotating token/tenant is never stale.\n */\n context?: RequestContext | (() => RequestContext | undefined)\n}\n\n/**\n * Bind to an agent by endpoint path (`/api/agents/<name>`) or by an explicit {@link AgentTransport}.\n * Prefer the generated `useAgent` from `@theo/agents` (typed by agent name); this base accepts a path\n * or a transport. The store is created once per binding identity — memoize a transport before passing it.\n */\nexport function useAgent<TInput = unknown>(\n pathOrTransport: string | AgentTransport,\n options: UseAgentOptions = {},\n): UseAgentReturn<TInput> {\n // Track the latest options so the built HttpTransport reads current headers per request (dynamic\n // auth is never stale) without rebuilding the store — which would drop in-flight messages.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const client = useMemo(\n () =>\n new AgentClient<TInput>(\n typeof pathOrTransport === 'string'\n ? new HttpTransport({\n api: pathOrTransport,\n headers: () => optionsRef.current.headers,\n fetch: optionsRef.current.fetch,\n })\n : pathOrTransport,\n // M43 — resolve context live from the ref each send/reconnect (never stale). A value or a resolver.\n () => {\n const ctx = optionsRef.current.context\n return typeof ctx === 'function' ? ctx() : ctx\n },\n ),\n // Identity is the binding; headers/context are resolved live via optionsRef, fetch captured at creation.\n [pathOrTransport],\n )\n\n const state = useSyncExternalStore(client.subscribe, client.getSnapshot, client.getSnapshot)\n\n return {\n messages: state.messages,\n status: state.status,\n error: state.error,\n send: client.send,\n abort: client.abort,\n reset: client.reset,\n approve: client.approve,\n reconnect: client.reconnect,\n }\n}\n","/**\n * <Link> — React Router Link with route prefetching.\n *\n * Wraps react-router's <Link> with prefetch behavior:\n * - `intent` (default): prefetch on hover + focus (~200ms before click)\n * - `viewport`: prefetch when visible (IntersectionObserver)\n * - `none`: no prefetch (same as plain react-router Link)\n *\n * Uses `<link rel=\"prefetch\">` (not modulepreload) because route paths\n * can be prefetched directly — no Vite manifest resolution needed (EC-1).\n */\nimport {\n Link as RouterLink,\n type LinkProps as RouterLinkProps,\n} from 'react-router'\nimport { useRef, useCallback, useEffect } from 'react'\n\nexport type PrefetchBehavior = 'none' | 'intent' | 'viewport'\n\nexport interface LinkProps extends RouterLinkProps {\n /** Prefetch strategy. Default: 'intent' (on hover + focus). */\n prefetch?: PrefetchBehavior\n}\n\n/** Deduplication — each URL prefetched at most once per session. */\nconst prefetched = new Set<string>()\n\nfunction injectPrefetch(href: string): void {\n // EC-2: SSR guard — document unavailable on server\n if (typeof document === 'undefined') return\n if (prefetched.has(href)) return\n prefetched.add(href)\n\n const link = document.createElement('link')\n link.rel = 'prefetch'\n link.href = href\n document.head.appendChild(link)\n}\n\nfunction resolveTo(to: LinkProps['to']): string {\n if (typeof to === 'string') return to\n return to?.pathname ?? ''\n}\n\n/**\n * TheoKit Link — drop-in replacement for react-router Link with prefetch.\n *\n * @example\n * ```tsx\n * import { Link } from 'theokit/client'\n *\n * <Link to=\"/contacts\">Contacts</Link>\n * <Link to=\"/dashboard\" prefetch=\"viewport\">Dashboard</Link>\n * <Link to=\"/settings\" prefetch=\"none\">Settings</Link>\n * ```\n */\nexport function Link({ prefetch = 'intent', to, onMouseEnter, onFocus, ...rest }: LinkProps) {\n const ref = useRef<HTMLAnchorElement>(null)\n\n const handleIntent = useCallback(\n (event: React.MouseEvent<HTMLAnchorElement> | React.FocusEvent<HTMLAnchorElement>) => {\n if (prefetch === 'intent') {\n injectPrefetch(resolveTo(to))\n }\n // Forward original handlers\n if (event.type === 'mouseenter' && onMouseEnter) {\n ;(onMouseEnter as React.MouseEventHandler<HTMLAnchorElement>)(event as React.MouseEvent<HTMLAnchorElement>)\n }\n if (event.type === 'focus' && onFocus) {\n ;(onFocus as React.FocusEventHandler<HTMLAnchorElement>)(event as React.FocusEvent<HTMLAnchorElement>)\n }\n },\n [prefetch, to, onMouseEnter, onFocus],\n )\n\n // Viewport mode: IntersectionObserver\n useEffect(() => {\n if (prefetch !== 'viewport' || !ref.current) return\n if (typeof IntersectionObserver === 'undefined') return // SSR guard\n\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) {\n injectPrefetch(resolveTo(to))\n observer.disconnect()\n }\n },\n { rootMargin: '200px' }, // prefetch slightly before visible\n )\n observer.observe(ref.current)\n return () => observer.disconnect()\n }, [prefetch, to])\n\n return (\n <RouterLink\n ref={ref}\n to={to}\n onMouseEnter={handleIntent}\n onFocus={handleIntent}\n {...rest}\n />\n )\n}\n","/**\n * <Metadata> — SEO-ready head tags from a single component.\n *\n * Uses React 19's native <title>/<meta>/<link> hoisting to <head>.\n * No build-time extraction needed — works in SSR and client.\n *\n * @example\n * ```tsx\n * import { Metadata } from 'theokit/client'\n *\n * export default function ContactsPage() {\n * return (\n * <>\n * <Metadata\n * title=\"Contacts | My CRM\"\n * description=\"Manage your contacts\"\n * ogImage=\"/og/contacts.png\"\n * canonical=\"https://mycrm.com/contacts\"\n * />\n * <h1>Contacts</h1>\n * </>\n * )\n * }\n * ```\n */\n\nexport interface MetadataProps {\n title?: string\n description?: string\n canonical?: string\n ogTitle?: string\n ogDescription?: string\n ogImage?: string\n ogType?: string\n ogUrl?: string\n twitterCard?: 'summary' | 'summary_large_image'\n /** Custom meta tags rendered as children */\n children?: React.ReactNode\n}\n\nexport function Metadata(props: MetadataProps) {\n const ogTitle = props.ogTitle ?? props.title\n const ogDesc = props.ogDescription ?? props.description\n\n return (\n <>\n {props.title && <title>{props.title}</title>}\n {props.description && <meta name=\"description\" content={props.description} />}\n {props.canonical && <link rel=\"canonical\" href={props.canonical} />}\n {ogTitle && <meta property=\"og:title\" content={ogTitle} />}\n {ogDesc && <meta property=\"og:description\" content={ogDesc} />}\n {props.ogImage && <meta property=\"og:image\" content={props.ogImage} />}\n {props.ogType && <meta property=\"og:type\" content={props.ogType} />}\n {props.ogUrl && <meta property=\"og:url\" content={props.ogUrl} />}\n {props.twitterCard && <meta name=\"twitter:card\" content={props.twitterCard} />}\n {props.children}\n </>\n )\n}\n","/**\n * <Image> — optimized image component with lazy loading.\n *\n * Renders a standard <img> with:\n * - loading=\"lazy\" by default (eager with priority={true})\n * - decoding=\"async\" for non-blocking decode\n * - width/height for CLS prevention\n * - srcSet/sizes forwarded for responsive images\n *\n * No CDN, no Sharp, no build-time optimization — pure HTML attributes\n * that deliver 80% of the performance value at zero complexity.\n *\n * @example\n * ```tsx\n * import { Image } from 'theokit/client'\n *\n * <Image src=\"/team.jpg\" alt=\"Team photo\" width={800} height={600} />\n * <Image src=\"/hero.jpg\" alt=\"Hero\" priority />\n * <Image\n * src=\"/product.jpg\"\n * alt=\"Product\"\n * width={400}\n * height={300}\n * srcSet=\"/product-400.jpg 400w, /product-800.jpg 800w\"\n * sizes=\"(max-width: 768px) 100vw, 400px\"\n * />\n * ```\n */\n\nexport interface ImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {\n /** Image source URL (required). */\n src: string\n /** Alt text for accessibility (required). */\n alt: string\n /** If true, loading=\"eager\" — use for above-the-fold images. */\n priority?: boolean\n}\n\nexport function Image({ priority, loading, decoding, ...props }: ImageProps) {\n return (\n <img\n loading={loading ?? (priority ? 'eager' : 'lazy')}\n decoding={decoding ?? 'async'}\n {...props}\n />\n )\n}\n","/**\n * M30 (ADR-0041) — client host for MCP App `ui://` resources.\n *\n * Renders a tool's `ui://` HTML in a SANDBOXED iframe and bridges a capability-scoped guest API over\n * `postMessage`. Security is load-bearing:\n * - the iframe is `sandbox=\"allow-scripts\"` ONLY — NOT `allow-same-origin`, so the guest runs at a\n * null origin and cannot touch the parent DOM, cookies, or storage;\n * - the host only honors messages whose `source` is the iframe's own `contentWindow`;\n * - the guest API is a fixed, capability-scoped vocabulary (`callServerTool`, `sendMessage`) — any\n * other message type is ignored.\n */\n\n/** The guest → host message vocabulary (capability-scoped). */\nexport type GuestMessage =\n | { type: 'callServerTool'; id: string; tool: string; args?: unknown }\n | { type: 'sendMessage'; text: string }\n\n/** Callbacks the host wires for the guest API. */\nexport interface McpAppHostOptions {\n /** Guest asked to call a server tool — return its result (posted back to the guest by id). */\n onCallServerTool: (tool: string, args: unknown) => unknown\n /** Guest emitted a chat message to the host app. */\n onSendMessage?: (text: string) => void\n}\n\n/**\n * Pure bridge: interpret one guest message and (for `callServerTool`) post the result back via\n * `post`. Exported for unit testing without a DOM. Unknown message shapes are ignored — the guest\n * API is capability-scoped, not an open RPC surface.\n */\nexport function createGuestMessageHandler(\n opts: McpAppHostOptions,\n post: (message: unknown) => void,\n): (data: unknown) => Promise<void> {\n return async (data: unknown): Promise<void> => {\n if (typeof data !== 'object' || data === null) return\n const msg = data as Partial<GuestMessage> & { type?: string }\n if (\n msg.type === 'callServerTool' &&\n typeof msg.id === 'string' &&\n typeof msg.tool === 'string'\n ) {\n const result = await opts.onCallServerTool(msg.tool, msg.args)\n post({ type: 'callServerTool:result', id: msg.id, result })\n return\n }\n if (msg.type === 'sendMessage' && typeof (msg as { text?: unknown }).text === 'string') {\n opts.onSendMessage?.((msg as { text: string }).text)\n }\n }\n}\n\n/** Handle returned by {@link mountMcpApp}. */\nexport interface McpAppHandle {\n iframe: HTMLIFrameElement\n /** Remove the message listener and the iframe. */\n dispose: () => void\n}\n\n/** The sandbox tokens the guest iframe is allowed — scripts only, NEVER `allow-same-origin`. */\nexport const MCP_APP_SANDBOX = 'allow-scripts'\n\n/**\n * Mount an MCP App resource's HTML in a sandboxed iframe inside `container`, wiring the guest API.\n * The HTML comes from `resources/read` (see `mcp-app-resources.ts`). Returns a handle to dispose.\n */\nexport function mountMcpApp(\n container: HTMLElement,\n resource: { html: string },\n opts: McpAppHostOptions,\n): McpAppHandle {\n const iframe = container.ownerDocument.createElement('iframe')\n // Security: scripts only, null origin. Do NOT add allow-same-origin.\n iframe.setAttribute('sandbox', MCP_APP_SANDBOX)\n iframe.srcdoc = resource.html\n container.appendChild(iframe)\n\n const post = (message: unknown): void => {\n // The guest is a sandboxed srcdoc iframe (allow-scripts, NO allow-same-origin) → its origin is\n // the opaque string \"null\", which cannot be used as a reliable targetOrigin. '*' is the only\n // valid target for a null-origin sandboxed guest; the sandbox (no navigation, no same-origin)\n // is what prevents a cross-origin leak, not the targetOrigin string.\n // eslint-disable-next-line sonarjs/post-message -- sandboxed null-origin iframe: '*' is correct\n iframe.contentWindow?.postMessage(message, '*')\n }\n const handle = createGuestMessageHandler(opts, post)\n\n const onMessage = (event: MessageEvent): void => {\n // Only trust messages from THIS iframe's guest window.\n if (event.source !== iframe.contentWindow) return\n void handle(event.data)\n }\n const view = container.ownerDocument.defaultView\n view?.addEventListener('message', onMessage)\n\n return {\n iframe,\n dispose: () => {\n view?.removeEventListener('message', onMessage)\n iframe.remove()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,eAAe;;;AC2Cf,SAAS,cAAc,SAAkC;AAC9D,QAAM,MAAM,QAAQ,OAAO;AAC3B,MAAI,QAAuB,CAAC;AAC5B,MAAI,iBAAiB;AAErB,WAAS,QAAc;AACrB,qBAAiB;AACjB,UAAM,UAAU;AAChB,YAAQ,CAAC;AACT,QAAI,QAAQ,WAAW,EAAG;AAG1B,UAAM,SAA0B,CAAC;AACjC,aAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK,KAAK;AAC5C,aAAO,KAAK,QAAQ,MAAM,GAAG,IAAI,GAAG,CAAC;AAAA,IACvC;AAEA,eAAW,SAAS,QAAQ;AAC1B,YAAM,UAA0B,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG;AACtD,cACG,UAAU,OAAO,EACjB,KAAK,CAAC,YAAY;AACjB,iBAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AAKrC,gBAAM,SAAS,QAAQ,SAAS,IAAI,QAAQ,CAAC,IAAI;AACjD,cAAI,WAAW,QAAW;AACxB,kBAAM,CAAC,EAAE,OAAO,IAAI,MAAM,gDAAgD,CAAC,EAAE,CAAC;AAC9E;AAAA,UACF;AACA,cAAI,WAAW,QAAQ;AACrB,kBAAM,MAAM,IAAI,MAAM,OAAO,MAAM,OAAO;AACzC,YAAC,IAA0B,OAAO,OAAO,MAAM;AAChD,kBAAM,CAAC,EAAE,OAAO,GAAG;AAAA,UACrB,OAAO;AACL,kBAAM,CAAC,EAAE,QAAQ,OAAO,IAAI;AAAA,UAC9B;AAAA,QACF;AAAA,MACF,CAAC,EACA,MAAM,CAAC,QAAiB;AACvB,mBAAW,QAAQ,MAAO,MAAK,OAAO,GAAG;AAAA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AAMxB,SAAS,YACd,WACA,UACA,MACc;AACd,QAAM,SAAS,UAAU,cAAc,cAAc,QAAQ;AAE7D,SAAO,aAAa,WAAW,eAAe;AAC9C,SAAO,SAAS,SAAS;AACzB,YAAU,YAAY,MAAM;AAE5B,QAAM,OAAO,CAAC,YAA2B;AAMvC,WAAO,eAAe,YAAY,SAAS,GAAG;AAAA,EAChD;AACA,QAAM,SAAS,0BAA0B,MAAM,IAAI;AAEnD,QAAM,YAAY,CAAC,UAA8B;AAE/C,QAAI,MAAM,WAAW,OAAO,cAAe;AAC3C,SAAK,OAAO,MAAM,IAAI;AAAA,EACxB;AACA,QAAM,OAAO,UAAU,cAAc;AACrC,QAAM,iBAAiB,WAAW,SAAS;AAE3C,SAAO;AAAA,IACL;AAAA,IACA,SAAS,MAAM;AACb,YAAM,oBAAoB,WAAW,SAAS;AAC9C,aAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF;","names":["useRef","jsx","jsx"]}
|
|
1
|
+
{"version":3,"sources":["../../src/client/theo-fetch.ts","../../src/client/batch.ts","../../src/client/batch-transport.ts","../../src/client/app-client.ts","../../src/client/use-agent.ts","../../src/client/link.tsx","../../src/client/metadata.tsx","../../src/client/image.tsx","../../src/client/mcp-app-host.ts"],"sourcesContent":["import superjson from 'superjson'\nimport type { z } from 'zod'\n\nimport type { TheoErrorCode, TheoErrorEnvelope } from '../core/contracts/error-envelope.js'\n\nimport { getGlobalBatcher } from './batch-transport.js'\n\n// --- Transformer (T1.3) ---\n\n/**\n * Module-scoped flag preventing the transformer-mismatch warning from\n * firing more than once per session (EC-6).\n */\nlet mismatchWarned = false\n\n/** Test-only helper to reset the warned flag between assertions. */\nexport function __resetMismatchWarningForTests(): void {\n mismatchWarned = false\n}\n\n/**\n * Deserialize a fetch response body according to the negotiated transformer.\n *\n * `serverTransformerName` comes from the `x-theo-transformer` response header\n * (null when absent — server is using the default JSON path).\n * `clientTransformerName` is the transformer the client was built with\n * (typically injected via a Vite virtual module; falls back to `'json'`).\n *\n * Mismatch fires a single console.warn and falls back to JSON.parse (EC-5/EC-6).\n */\nexport function deserializeFetchResponse(\n raw: string,\n serverTransformerName: string | null,\n clientTransformerName: string,\n): unknown {\n // `raw` is typed `string`, but stay defensive: callers pass `await response.text()`\n // which can be empty.\n if (raw === '') {\n return null\n }\n\n const serverEffective = serverTransformerName ?? 'json'\n if (serverEffective !== clientTransformerName && !mismatchWarned) {\n mismatchWarned = true\n console.warn(\n `[theokit] transformer mismatch: server=${serverEffective}, client=${clientTransformerName}. Falling back to JSON.parse.`,\n )\n }\n\n if (serverEffective === 'superjson' && clientTransformerName === 'superjson') {\n const wrapped = JSON.parse(raw) as Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize(wrapped)\n }\n\n // Default path (json) or mismatch fallback\n return JSON.parse(raw)\n}\n\n// --- Utility Types ---\n\n/** Infer the response type from a route's handler return */\nexport type InferResponse<T> = T extends { handler: (...args: never[]) => infer R }\n ? Awaited<R>\n : unknown\n\n/** Extract the query Zod schema type, handling optional properties */\ntype ExtractQuery<T> = T extends { query?: infer Q } ? (Q extends z.ZodType ? Q : never) : never\n\n/** Extract the body Zod schema type, handling optional properties */\ntype ExtractBody<T> = T extends { body?: infer B } ? (B extends z.ZodType ? B : never) : never\n\n/** Infer query type from a route's query Zod schema */\nexport type InferQuery<T> = [ExtractQuery<T>] extends [never]\n ? undefined\n : ExtractQuery<T> extends z.ZodUndefined\n ? undefined\n : z.infer<ExtractQuery<T>>\n\n/** Infer body type from a route's body Zod schema */\nexport type InferBody<T> = [ExtractBody<T>] extends [never]\n ? undefined\n : ExtractBody<T> extends z.ZodUndefined\n ? undefined\n : z.infer<ExtractBody<T>>\n\n/** Build the options type based on what schemas the route has */\nexport type TheoFetchOptions<T> = Omit<RequestInit, 'body' | 'method'> &\n (InferQuery<T> extends undefined ? { query?: never } : { query: InferQuery<T> }) &\n (InferBody<T> extends undefined ? { body?: never } : { body: InferBody<T> })\n\n// --- Error Class ---\n\n/**\n * G5 T2.1 — extract a TheoErrorEnvelope from a response body. Supports both\n * the new envelope-at-root shape (`{ code, message, ext?, ... }`, blueprint\n * Recommendations § concrete shape) and the legacy nested shape\n * (`{ error: { code, message, issues? } }`, G3 SerializedActionResult).\n *\n * Falls back to `INTERNAL_SERVER_ERROR` with a synthetic message when the\n * body shape is unrecognized. Pure; no I/O.\n */\nfunction extractEnvelope(status: number, body: unknown): TheoErrorEnvelope {\n if (!body || typeof body !== 'object') {\n return { code: 'INTERNAL_SERVER_ERROR', message: `HTTP ${String(status)}` }\n }\n const obj = body as Record<string, unknown>\n // New shape — envelope at root\n if (typeof obj.code === 'string' && typeof obj.message === 'string') {\n return {\n code: obj.code as TheoErrorCode,\n message: obj.message,\n cause: obj.cause,\n meta: obj.meta as Record<string, unknown> | undefined,\n ext: obj.ext,\n }\n }\n // Legacy shape — { error: { code, message, ... } }\n if (obj.error && typeof obj.error === 'object') {\n const nested = obj.error as Record<string, unknown>\n return {\n code:\n typeof nested.code === 'string' ? (nested.code as TheoErrorCode) : 'INTERNAL_SERVER_ERROR',\n message: typeof nested.message === 'string' ? nested.message : `HTTP ${String(status)}`,\n }\n }\n return { code: 'INTERNAL_SERVER_ERROR', message: `HTTP ${String(status)}` }\n}\n\n/**\n * Pull a single string field from an object, returning undefined if missing\n * or non-string. Helper for `extractLegacyFields` to stay under the\n * complexity ceiling.\n */\nfunction strField(obj: Record<string, unknown> | null, key: string): string | undefined {\n const v = obj?.[key]\n return typeof v === 'string' ? v : undefined\n}\n\n/**\n * Pull the canonical {message, code, issues} from either an envelope-at-root\n * body or the legacy { error: {...} } body. Pure.\n */\nfunction extractLegacyFields(\n status: number,\n body: unknown,\n): { message: string; code?: string; issues?: unknown[] } {\n if (!body || typeof body !== 'object') {\n return { message: `HTTP ${String(status)}` }\n }\n const obj = body as Record<string, unknown>\n const nested =\n obj.error && typeof obj.error === 'object' ? (obj.error as Record<string, unknown>) : null\n const issues = Array.isArray(nested?.issues) ? nested.issues : undefined\n return {\n message: strField(obj, 'message') ?? strField(nested, 'message') ?? `HTTP ${String(status)}`,\n code: strField(obj, 'code') ?? strField(nested, 'code'),\n issues,\n }\n}\n\nexport class TheoFetchError extends Error {\n status: number\n code?: string\n issues?: unknown[]\n /**\n * G5 T2.1 — canonical envelope view of the server-side error. Use this in\n * consumer code that wants to switch on a typed TheoErrorCode instead of\n * coupling to the legacy `.status` / `.code` flat fields.\n */\n readonly envelope: TheoErrorEnvelope\n\n constructor(status: number, body?: unknown) {\n const legacy = extractLegacyFields(status, body)\n super(legacy.message)\n this.name = 'TheoFetchError'\n this.status = status\n this.code = legacy.code\n this.issues = legacy.issues\n this.envelope = extractEnvelope(status, body)\n }\n}\n\n/**\n * Serialize a query-param value to a string. Handles primitives, dates,\n * and falls back to JSON for arrays/objects. Avoids the\n * `[object Object]` foot-gun that `no-base-to-string` warns against.\n */\nfunction stringifyQueryValue(value: unknown): string {\n if (value === null) return 'null'\n if (value instanceof Date) return value.toISOString()\n switch (typeof value) {\n case 'string':\n return value\n case 'number':\n case 'boolean':\n case 'bigint':\n return String(value)\n default:\n return JSON.stringify(value)\n }\n}\n\n// --- Main Function ---\n\ninterface TheoFetchInternalOptions {\n method?: string\n query?: Record<string, unknown>\n body?: unknown\n headers?: HeadersInit\n signal?: AbortSignal\n}\n\n/**\n * Resolve the request origin per the documented fallback hierarchy. Pure\n * helper extracted to keep `theoFetch` under the complexity ceiling.\n * 1. `globalThis.location.origin` (browser)\n * 2. `globalThis.__THEO_ORIGIN__` (build-time literal)\n * 3. `process.env.THEO_ORIGIN` (escape hatch)\n * 4. `http://localhost` (placeholder for URL parsing — the URL is built\n * relative so only pathname+search ever flows to the wire)\n */\nfunction resolveRequestOrigin(): string {\n const g = globalThis as { location?: { origin?: string }; __THEO_ORIGIN__?: string }\n const fromEnv = typeof process !== 'undefined' ? process.env.THEO_ORIGIN : undefined\n return g.location?.origin ?? g.__THEO_ORIGIN__ ?? fromEnv ?? 'http://localhost'\n}\n\nfunction buildFetchUrl(path: string, query: Record<string, unknown> | undefined): URL {\n const fetchUrl = new URL(path, resolveRequestOrigin())\n if (!query) return fetchUrl\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined) {\n fetchUrl.searchParams.set(k, stringifyQueryValue(v))\n }\n }\n return fetchUrl\n}\n\n/**\n * Normalize `HeadersInit` (Headers / `[string, string][]` / Record) into a\n * single plain `Record<string, string>`. Plain-object output is required\n * by callers that introspect headers via index access (test fixtures use\n * `(init.headers as Record<string, string>)['Content-Type']`).\n */\nfunction normalizeHeaders(input: HeadersInit | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n if (!input) return out\n if (input instanceof Headers) {\n input.forEach((value, key) => {\n out[key] = value\n })\n return out\n }\n if (Array.isArray(input)) {\n for (const [key, value] of input) out[key] = value\n return out\n }\n for (const [key, value] of Object.entries(input)) {\n out[key] = value\n }\n return out\n}\n\nfunction buildRequestInit(opts: TheoFetchInternalOptions): RequestInit {\n const init: RequestInit = {}\n if (opts.method !== undefined) init.method = opts.method\n if (opts.signal !== undefined) init.signal = opts.signal\n\n const headers = normalizeHeaders(opts.headers)\n init.headers = headers\n\n if (opts.body !== undefined) {\n init.body = JSON.stringify(opts.body)\n headers['Content-Type'] = 'application/json'\n }\n\n // Phase 5 — Auto-attach `X-Theo-Action: 1` for state-mutating methods so\n // the framework's CSRF check passes when servers run in `strict` mode.\n // Safe methods (GET/HEAD/OPTIONS) skip the header to keep them cacheable.\n const method = (opts.method ?? 'GET').toUpperCase()\n if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') {\n headers['X-Theo-Action'] = '1'\n }\n return init\n}\n\nasync function tryBatcher(\n url: string,\n options: TheoFetchInternalOptions,\n): Promise<{ matched: true; result: unknown } | { matched: false }> {\n const batcher = getGlobalBatcher()\n if (!batcher) return { matched: false }\n try {\n const result = await batcher.dispatch({\n path: url,\n method: options.method ?? 'GET',\n query: options.query,\n body: options.body,\n })\n return { matched: true, result }\n } catch {\n // Batcher failure: fall through to direct fetch (graceful degrade).\n return { matched: false }\n }\n}\n\nexport async function theoFetch<T>(\n url: string,\n options?: TheoFetchOptions<T>,\n): Promise<InferResponse<T>> {\n const internal = (options ?? {}) as unknown as TheoFetchInternalOptions\n\n // T1.5 — Transparent batching when globalThis.__THEO_BATCHING__ is truthy.\n const batchAttempt = await tryBatcher(url, internal)\n if (batchAttempt.matched) {\n return batchAttempt.result as InferResponse<T>\n }\n\n const fetchUrl = buildFetchUrl(url, internal.query)\n const init = buildRequestInit(internal)\n const response = await fetch(fetchUrl.toString(), init)\n\n if (!response.ok) {\n let errorBody: unknown\n try {\n errorBody = await response.json()\n } catch {\n // Non-JSON error response\n }\n throw new TheoFetchError(response.status, errorBody)\n }\n\n // Handle 204 No Content (EC-1)\n if (response.status === 204) {\n return null as InferResponse<T>\n }\n\n // Check for empty body\n const contentLength = response.headers.get('content-length')\n if (contentLength === '0') {\n return null as InferResponse<T>\n }\n\n // T1.3 — transformer-aware deserialization\n const serverTransformerName = response.headers.get('x-theo-transformer')\n const clientTransformerName = resolveClientTransformerName()\n const text = await response.text()\n return deserializeFetchResponse(\n text,\n serverTransformerName,\n clientTransformerName,\n ) as InferResponse<T>\n}\n\n/**\n * Read the client-configured transformer name. Default `'json'`.\n *\n * In a Vite build, this is overridden by virtual module\n * `/@theo/runtime-config` which sets `globalThis.__THEO_TRANSFORMER__`.\n * Outside Vite (Node SSR, tests) the default applies.\n */\nfunction resolveClientTransformerName(): string {\n const g = globalThis as { __THEO_TRANSFORMER__?: string }\n return g.__THEO_TRANSFORMER__ ?? 'json'\n}\n","/**\n * T5.1 — client-side microtask batching.\n *\n * Collects all `dispatch` calls within the same microtask and sends them as a\n * single HTTP POST to the configured transport. Each caller's promise resolves\n * with its own result; one failed item does not break the others (per-item\n * error isolation).\n *\n * Designed as a transport-agnostic primitive so unit tests do not require\n * network access. The default transport (fetch to `/api/__theo_batch__`)\n * lives alongside this module but is created by the consumer (e.g., theoFetch).\n */\n\nexport interface BatchRequest {\n path: string\n method: string\n query?: Record<string, unknown>\n body?: unknown\n headers?: Record<string, string>\n}\n\nexport type BatchResponse =\n | { index: number; data: unknown }\n | { index: number; error: { message: string; code?: string } }\n\nexport type BatchTransport = (requests: BatchRequest[]) => Promise<BatchResponse[]>\n\nexport interface BatcherOptions {\n transport: BatchTransport\n /** Maximum batch size before flushing into multiple parallel batches. */\n max?: number\n}\n\nexport interface Batcher {\n dispatch(req: BatchRequest): Promise<unknown>\n}\n\ninterface PendingCall {\n req: BatchRequest\n resolve: (value: unknown) => void\n reject: (reason: unknown) => void\n}\n\nexport function createBatcher(options: BatcherOptions): Batcher {\n const max = options.max ?? 32\n let queue: PendingCall[] = []\n let flushScheduled = false\n\n function flush(): void {\n flushScheduled = false\n const current = queue\n queue = []\n if (current.length === 0) return\n\n // Split into chunks respecting max\n const chunks: PendingCall[][] = []\n for (let i = 0; i < current.length; i += max) {\n chunks.push(current.slice(i, i + max))\n }\n\n for (const chunk of chunks) {\n const payload: BatchRequest[] = chunk.map((p) => p.req)\n options\n .transport(payload)\n .then((results) => {\n for (let i = 0; i < chunk.length; i++) {\n // `results[i]` could be undefined at runtime when the transport\n // returns fewer entries than the chunk; TypeScript's strict\n // typing without `noUncheckedIndexedAccess` does not surface\n // this, so we hand-narrow.\n const result = results.length > i ? results[i] : undefined\n if (result === undefined) {\n chunk[i].reject(new Error(`Batch transport returned no result for index ${i}`))\n continue\n }\n if ('error' in result) {\n const err = new Error(result.error.message)\n ;(err as { code?: string }).code = result.error.code\n chunk[i].reject(err)\n } else {\n chunk[i].resolve(result.data)\n }\n }\n })\n .catch((err: unknown) => {\n for (const item of chunk) item.reject(err)\n })\n }\n }\n\n return {\n dispatch(req: BatchRequest): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n queue.push({ req, resolve, reject })\n if (!flushScheduled) {\n flushScheduled = true\n queueMicrotask(flush)\n }\n })\n },\n }\n}\n","/**\n * T1.5 — Default HTTP transport for the client batcher.\n *\n * Wraps `fetch` to POST `/api/__theo_batch__` with the collected requests\n * and return the array of per-item results.\n */\n\nimport {\n createBatcher,\n type BatchTransport,\n type Batcher,\n type BatchRequest,\n type BatchResponse,\n} from './batch.js'\n\nconst BATCH_ENDPOINT = '/api/__theo_batch__'\n\nexport interface CreateBatchTransportOptions {\n /** Override fetch (default: globalThis.fetch). Used by tests. */\n fetchImpl?: typeof fetch\n /** Override endpoint (default '/api/__theo_batch__'). */\n endpoint?: string\n}\n\nexport function createBatchTransport(options: CreateBatchTransportOptions = {}): BatchTransport {\n const fetchImpl = options.fetchImpl ?? fetch\n const endpoint = options.endpoint ?? BATCH_ENDPOINT\n return async (requests: BatchRequest[]): Promise<BatchResponse[]> => {\n const response = await fetchImpl(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ requests }),\n })\n if (!response.ok) {\n throw new Error(`Batch transport returned ${response.status}`)\n }\n const payload = (await response.json()) as { results?: BatchResponse[] }\n if (!Array.isArray(payload.results)) {\n throw new Error('Batch response missing results array')\n }\n // Map results to indexed BatchResponse shape (server already returns the right form)\n return payload.results.map((item, index) => {\n if ('error' in item) {\n return { index, error: (item as { error: { message: string; code?: string } }).error }\n }\n return { index, data: (item as { data: unknown }).data }\n })\n }\n}\n\n// --- EC-7: singleton batcher per page, lazy-instantiated ---\n\nlet globalBatcher: Batcher | undefined\n\n/** Test-only — reset the module-scope singleton between assertions. */\nexport function __resetGlobalBatcherForTests(): void {\n globalBatcher = undefined\n}\n\n/**\n * Returns the global batcher singleton when `globalThis.__THEO_BATCHING__` is\n * truthy; undefined otherwise. Lazy-instantiated on first call.\n */\nexport function getGlobalBatcher(): Batcher | undefined {\n const g = globalThis as { __THEO_BATCHING__?: boolean }\n if (!g.__THEO_BATCHING__) return undefined\n globalBatcher ??= createBatcher({ transport: createBatchTransport() })\n return globalBatcher\n}\n","/**\n * Phase 3 of G1 (g1-client-codegen-plan.md):\n *\n * `createAppClient(baseUrl?, fetchImpl?)` returns a Proxy that walks property\n * access (`client.posts.id.get(...)`) into a `theoFetch` invocation against\n * `{baseUrl}/posts/{params.id}` with method `GET`.\n *\n * Type safety is delivered by the `.d.ts` file emitted in Phase 2 — this\n * runtime is structurally untyped. Power users may use `theoFetch` directly\n * when they need to escape the Proxy facade.\n *\n * Edge cases absorbed:\n * - EC-1 (thenable trap): `then` / `catch` / `finally` / `toJSON` / `Symbol.*`\n * return `undefined` so that accidental `await client.posts` resolves to a\n * plain Proxy value (it is NOT thenable) instead of looping.\n * - EC-7 (abort signal): `opts.signal` is spread through to the underlying\n * fetchImpl unchanged — verified in unit tests.\n *\n * Bundle target: ≤ 2KB gzipped.\n */\n\nimport { theoFetch, TheoFetchError } from './theo-fetch.js'\nimport type { TheoFetchOptions } from './theo-fetch.js'\nimport { HTTP_METHOD_LOWERCASE } from '../core/contracts/http-methods.js'\n\nconst HTTP_METHODS_SET = new Set(HTTP_METHOD_LOWERCASE)\n\n/**\n * Keys that JavaScript runtime / inspectors / Promise resolution probe\n * unconditionally. Returning `undefined` for these keeps the Proxy from\n * pretending to be a thenable / iterable / serializable thing.\n */\nconst NON_INTERCEPT_KEYS = new Set([\n 'then',\n 'catch',\n 'finally',\n 'toJSON',\n 'toString',\n 'valueOf',\n 'constructor',\n 'prototype',\n])\n\ntype FetchImpl = typeof theoFetch\n\ninterface CallOptions {\n params?: Record<string, string | number>\n query?: Record<string, unknown>\n body?: unknown\n signal?: AbortSignal\n headers?: HeadersInit\n // arbitrary RequestInit fields (mode, credentials, cache, etc.)\n [k: string]: unknown\n}\n\nfunction injectParams(path: string, params?: Record<string, string | number>): string {\n if (!params) {\n if (/:(?:\\.\\.\\.)?[A-Za-z_]/.test(path)) {\n throw new TheoFetchError(0, {\n error: {\n code: 'MISSING_PARAM',\n message: `Route ${path} requires params but none were provided. Pass them via opts.params, e.g. client.posts.get({ params: { id: '123' } }).`,\n },\n })\n }\n return path\n }\n return path.replace(/:(?:\\.\\.\\.)?([A-Za-z_][A-Za-z0-9_]*)/g, (_match, key: string) => {\n const value = params[key]\n if (value === undefined || value === null || value === '') {\n throw new TheoFetchError(0, {\n error: {\n code: 'MISSING_PARAM',\n message: `Param '${key}' is required for path '${path}' but was missing/empty.`,\n },\n })\n }\n return encodeURIComponent(String(value))\n })\n}\n\ninterface ProxyContext {\n segments: string[]\n baseUrl: string\n fetchImpl: FetchImpl\n}\n\nfunction makeProxy(ctx: ProxyContext): unknown {\n const handler: ProxyHandler<() => void> = {\n get(_target, key) {\n if (typeof key !== 'string') return undefined\n if (NON_INTERCEPT_KEYS.has(key)) return undefined\n if (HTTP_METHODS_SET.has(key)) {\n return async (opts?: CallOptions) => {\n if (ctx.segments.length === 0) {\n throw new TheoFetchError(0, {\n error: {\n code: 'INVALID_PATH',\n message: `client.${key}() called without a route segment. Use client.<resource>.${key}(...) instead.`,\n },\n })\n }\n let finalPath = `${ctx.baseUrl}/${ctx.segments.join('/')}`\n if (opts?.params) {\n // Build a path with `:name` placeholders re-inserted from segments\n // whose name matches a key in opts.params (treat as dynamic).\n const segmentsWithDynamic = ctx.segments.map((seg) =>\n Object.prototype.hasOwnProperty.call(opts.params, seg) ? `:${seg}` : seg,\n )\n finalPath = injectParams(\n `${ctx.baseUrl}/${segmentsWithDynamic.join('/')}`,\n opts.params,\n )\n }\n const { params: _ignored, ...rest } = opts ?? {}\n const init = { method: key.toUpperCase(), ...rest } as unknown as TheoFetchOptions<unknown>\n return ctx.fetchImpl(finalPath, init)\n }\n }\n // Continue traversal — append segment to the path.\n return makeProxy({ ...ctx, segments: [...ctx.segments, key] })\n },\n apply() {\n return Promise.reject(\n new TheoFetchError(0, {\n error: {\n code: 'INVALID_CALL',\n message:\n 'client(...) is not callable. Use client.<resource>.<method>(opts?) — e.g. client.posts.get().',\n },\n }),\n )\n },\n }\n return new Proxy(() => undefined, handler)\n}\n\nexport interface CreateAppClientOptions {\n /** Base URL for the API. Defaults to `/api`. */\n baseUrl?: string\n /** Test-only fetch override. Production callers should not pass this. */\n fetchImpl?: FetchImpl\n}\n\nexport function createAppClient<TAppClient = unknown>(\n baseUrlOrOptions?: string | CreateAppClientOptions,\n legacyFetchImpl?: FetchImpl,\n): TAppClient {\n let baseUrl = '/api'\n let fetchImpl: FetchImpl = theoFetch\n if (typeof baseUrlOrOptions === 'string') {\n baseUrl = baseUrlOrOptions || '/api'\n } else if (baseUrlOrOptions && typeof baseUrlOrOptions === 'object') {\n if (baseUrlOrOptions.baseUrl) baseUrl = baseUrlOrOptions.baseUrl\n if (baseUrlOrOptions.fetchImpl) fetchImpl = baseUrlOrOptions.fetchImpl\n }\n // Legacy 2nd-arg fetchImpl overrides regardless of 1st-arg shape (test seam).\n if (legacyFetchImpl) fetchImpl = legacyFetchImpl\n // Strip trailing slash for predictable joining.\n if (baseUrl.length > 1 && baseUrl.endsWith('/')) baseUrl = baseUrl.slice(0, -1)\n return makeProxy({ segments: [], baseUrl, fetchImpl }) as TAppClient\n}\n","import type { UIMessage } from 'ai'\nimport { useMemo, useRef, useSyncExternalStore } from 'react'\n\nimport { AgentClient, type UseAgentStatus } from './agent-client.js'\nimport { HttpTransport } from './http-transport.js'\nimport type { AgentTransport, ApprovalDecision, RequestContext } from './transport.js'\n\n/**\n * M2 (theokit-ai-first) / M41 (ADR-0050) — `useAgent`, the ONE typed client hook for the\n * `agents/*.ts` convention, unified across surfaces.\n *\n * Pass an endpoint path (web) OR an {@link AgentTransport} (terminal/desktop). A string is wrapped in\n * an {@link HttpTransport} (exact back-compat with the pre-M41 fetch+SSE hook); an `InProcessTransport`\n * drives the SAME hook in a single process. The hook is a thin binding over the framework-agnostic\n * {@link AgentClient} store via React's native `useSyncExternalStore` (no test-DOM dependency). The\n * generated `@theo/agents` module types `send` to the agent's `input` schema — inferred end-to-end\n * from the server `defineAgent({ input })` with ZERO manual wiring.\n */\nexport type { UseAgentStatus }\n\nexport interface UseAgentReturn<TInput = unknown, TToolNames extends string = string> {\n /** The CURRENT turn's assistant messages (per-turn; reset each `send`). Back-compat since M41. */\n messages: UIMessage[]\n /**\n * M46 — the full conversation to render: committed turns + the current turn's user + in-flight\n * assistant, accumulated across sends with stable ids. Prefer this over hand-rolling a transcript\n * from `messages`. Same shape on every surface (web/desktop/TUI) — it lives in the core store.\n */\n thread: UIMessage[]\n status: UseAgentStatus\n /** The last error, or `undefined`. */\n error: Error | undefined\n /** Send a request; opens a new stream. Typed to the agent's `input` schema. */\n send: (input: TInput) => void\n /** Abort an in-flight stream. */\n abort: () => void\n /** Clear messages + error, back to idle. */\n reset: () => void\n /** Settle a paused HITL approval (HTTP `POST /approve/<id>` for web; the inline callback in-process). */\n approve: (approvalId: string, decision: ApprovalDecision) => Promise<void>\n /** Resume an interrupted stream (M37 durable transport for web; a no-op in-process). */\n reconnect: () => void\n /**\n * The union of tool names this agent can emit (M8), carried end-to-end from the `agent()` builder's\n * accumulated tool-name type through the generated `@theo/agents` client. Type-only witness (never\n * populated at runtime). Resolves to the literal union for builder agents, `string` otherwise.\n */\n readonly __toolNames?: TToolNames\n}\n\nexport interface UseAgentOptions {\n /**\n * Extra request headers (e.g., auth) — applied when a string path builds an `HttpTransport`. Read on\n * EVERY request, so a value that changes across renders (a rotating JWT) is never sent stale.\n */\n headers?: Record<string, string>\n /** Override fetch (primarily for tests) — captured when a string path builds an `HttpTransport`. */\n fetch?: typeof fetch\n /**\n * M43 — per-request context attached uniformly to EVERY transport (`headers` → HTTP request headers;\n * `metadata` → the in-process runner / Tauri invoke). A value OR a resolver evaluated on every\n * send/reconnect, so a rotating token/tenant is never stale.\n */\n context?: RequestContext | (() => RequestContext | undefined)\n}\n\n/**\n * Bind to an agent by endpoint path (`/api/agents/<name>`) or by an explicit {@link AgentTransport}.\n * Prefer the generated `useAgent` from `@theo/agents` (typed by agent name); this base accepts a path\n * or a transport. The store is created once per binding identity — memoize a transport before passing it.\n */\nexport function useAgent<TInput = unknown>(\n pathOrTransport: string | AgentTransport,\n options: UseAgentOptions = {},\n): UseAgentReturn<TInput> {\n // Track the latest options so the built HttpTransport reads current headers per request (dynamic\n // auth is never stale) without rebuilding the store — which would drop in-flight messages.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const client = useMemo(\n () =>\n new AgentClient<TInput>(\n typeof pathOrTransport === 'string'\n ? new HttpTransport({\n api: pathOrTransport,\n headers: () => optionsRef.current.headers,\n fetch: optionsRef.current.fetch,\n })\n : pathOrTransport,\n // M43 — resolve context live from the ref each send/reconnect (never stale). A value or a resolver.\n () => {\n const ctx = optionsRef.current.context\n return typeof ctx === 'function' ? ctx() : ctx\n },\n ),\n // Identity is the binding; headers/context are resolved live via optionsRef, fetch captured at creation.\n [pathOrTransport],\n )\n\n const state = useSyncExternalStore(client.subscribe, client.getSnapshot, client.getSnapshot)\n\n return {\n messages: state.messages,\n thread: state.thread,\n status: state.status,\n error: state.error,\n send: client.send,\n abort: client.abort,\n reset: client.reset,\n approve: client.approve,\n reconnect: client.reconnect,\n }\n}\n","/**\n * <Link> — React Router Link with route prefetching.\n *\n * Wraps react-router's <Link> with prefetch behavior:\n * - `intent` (default): prefetch on hover + focus (~200ms before click)\n * - `viewport`: prefetch when visible (IntersectionObserver)\n * - `none`: no prefetch (same as plain react-router Link)\n *\n * Uses `<link rel=\"prefetch\">` (not modulepreload) because route paths\n * can be prefetched directly — no Vite manifest resolution needed (EC-1).\n */\nimport {\n Link as RouterLink,\n type LinkProps as RouterLinkProps,\n} from 'react-router'\nimport { useRef, useCallback, useEffect } from 'react'\n\nexport type PrefetchBehavior = 'none' | 'intent' | 'viewport'\n\nexport interface LinkProps extends RouterLinkProps {\n /** Prefetch strategy. Default: 'intent' (on hover + focus). */\n prefetch?: PrefetchBehavior\n}\n\n/** Deduplication — each URL prefetched at most once per session. */\nconst prefetched = new Set<string>()\n\nfunction injectPrefetch(href: string): void {\n // EC-2: SSR guard — document unavailable on server\n if (typeof document === 'undefined') return\n if (prefetched.has(href)) return\n prefetched.add(href)\n\n const link = document.createElement('link')\n link.rel = 'prefetch'\n link.href = href\n document.head.appendChild(link)\n}\n\nfunction resolveTo(to: LinkProps['to']): string {\n if (typeof to === 'string') return to\n return to?.pathname ?? ''\n}\n\n/**\n * TheoKit Link — drop-in replacement for react-router Link with prefetch.\n *\n * @example\n * ```tsx\n * import { Link } from 'theokit/client'\n *\n * <Link to=\"/contacts\">Contacts</Link>\n * <Link to=\"/dashboard\" prefetch=\"viewport\">Dashboard</Link>\n * <Link to=\"/settings\" prefetch=\"none\">Settings</Link>\n * ```\n */\nexport function Link({ prefetch = 'intent', to, onMouseEnter, onFocus, ...rest }: LinkProps) {\n const ref = useRef<HTMLAnchorElement>(null)\n\n const handleIntent = useCallback(\n (event: React.MouseEvent<HTMLAnchorElement> | React.FocusEvent<HTMLAnchorElement>) => {\n if (prefetch === 'intent') {\n injectPrefetch(resolveTo(to))\n }\n // Forward original handlers\n if (event.type === 'mouseenter' && onMouseEnter) {\n ;(onMouseEnter as React.MouseEventHandler<HTMLAnchorElement>)(event as React.MouseEvent<HTMLAnchorElement>)\n }\n if (event.type === 'focus' && onFocus) {\n ;(onFocus as React.FocusEventHandler<HTMLAnchorElement>)(event as React.FocusEvent<HTMLAnchorElement>)\n }\n },\n [prefetch, to, onMouseEnter, onFocus],\n )\n\n // Viewport mode: IntersectionObserver\n useEffect(() => {\n if (prefetch !== 'viewport' || !ref.current) return\n if (typeof IntersectionObserver === 'undefined') return // SSR guard\n\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (entry.isIntersecting) {\n injectPrefetch(resolveTo(to))\n observer.disconnect()\n }\n },\n { rootMargin: '200px' }, // prefetch slightly before visible\n )\n observer.observe(ref.current)\n return () => observer.disconnect()\n }, [prefetch, to])\n\n return (\n <RouterLink\n ref={ref}\n to={to}\n onMouseEnter={handleIntent}\n onFocus={handleIntent}\n {...rest}\n />\n )\n}\n","/**\n * <Metadata> — SEO-ready head tags from a single component.\n *\n * Uses React 19's native <title>/<meta>/<link> hoisting to <head>.\n * No build-time extraction needed — works in SSR and client.\n *\n * @example\n * ```tsx\n * import { Metadata } from 'theokit/client'\n *\n * export default function ContactsPage() {\n * return (\n * <>\n * <Metadata\n * title=\"Contacts | My CRM\"\n * description=\"Manage your contacts\"\n * ogImage=\"/og/contacts.png\"\n * canonical=\"https://mycrm.com/contacts\"\n * />\n * <h1>Contacts</h1>\n * </>\n * )\n * }\n * ```\n */\n\nexport interface MetadataProps {\n title?: string\n description?: string\n canonical?: string\n ogTitle?: string\n ogDescription?: string\n ogImage?: string\n ogType?: string\n ogUrl?: string\n twitterCard?: 'summary' | 'summary_large_image'\n /** Custom meta tags rendered as children */\n children?: React.ReactNode\n}\n\nexport function Metadata(props: MetadataProps) {\n const ogTitle = props.ogTitle ?? props.title\n const ogDesc = props.ogDescription ?? props.description\n\n return (\n <>\n {props.title && <title>{props.title}</title>}\n {props.description && <meta name=\"description\" content={props.description} />}\n {props.canonical && <link rel=\"canonical\" href={props.canonical} />}\n {ogTitle && <meta property=\"og:title\" content={ogTitle} />}\n {ogDesc && <meta property=\"og:description\" content={ogDesc} />}\n {props.ogImage && <meta property=\"og:image\" content={props.ogImage} />}\n {props.ogType && <meta property=\"og:type\" content={props.ogType} />}\n {props.ogUrl && <meta property=\"og:url\" content={props.ogUrl} />}\n {props.twitterCard && <meta name=\"twitter:card\" content={props.twitterCard} />}\n {props.children}\n </>\n )\n}\n","/**\n * <Image> — optimized image component with lazy loading.\n *\n * Renders a standard <img> with:\n * - loading=\"lazy\" by default (eager with priority={true})\n * - decoding=\"async\" for non-blocking decode\n * - width/height for CLS prevention\n * - srcSet/sizes forwarded for responsive images\n *\n * No CDN, no Sharp, no build-time optimization — pure HTML attributes\n * that deliver 80% of the performance value at zero complexity.\n *\n * @example\n * ```tsx\n * import { Image } from 'theokit/client'\n *\n * <Image src=\"/team.jpg\" alt=\"Team photo\" width={800} height={600} />\n * <Image src=\"/hero.jpg\" alt=\"Hero\" priority />\n * <Image\n * src=\"/product.jpg\"\n * alt=\"Product\"\n * width={400}\n * height={300}\n * srcSet=\"/product-400.jpg 400w, /product-800.jpg 800w\"\n * sizes=\"(max-width: 768px) 100vw, 400px\"\n * />\n * ```\n */\n\nexport interface ImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {\n /** Image source URL (required). */\n src: string\n /** Alt text for accessibility (required). */\n alt: string\n /** If true, loading=\"eager\" — use for above-the-fold images. */\n priority?: boolean\n}\n\nexport function Image({ priority, loading, decoding, ...props }: ImageProps) {\n return (\n <img\n loading={loading ?? (priority ? 'eager' : 'lazy')}\n decoding={decoding ?? 'async'}\n {...props}\n />\n )\n}\n","/**\n * M30 (ADR-0041) — client host for MCP App `ui://` resources.\n *\n * Renders a tool's `ui://` HTML in a SANDBOXED iframe and bridges a capability-scoped guest API over\n * `postMessage`. Security is load-bearing:\n * - the iframe is `sandbox=\"allow-scripts\"` ONLY — NOT `allow-same-origin`, so the guest runs at a\n * null origin and cannot touch the parent DOM, cookies, or storage;\n * - the host only honors messages whose `source` is the iframe's own `contentWindow`;\n * - the guest API is a fixed, capability-scoped vocabulary (`callServerTool`, `sendMessage`) — any\n * other message type is ignored.\n */\n\n/** The guest → host message vocabulary (capability-scoped). */\nexport type GuestMessage =\n | { type: 'callServerTool'; id: string; tool: string; args?: unknown }\n | { type: 'sendMessage'; text: string }\n\n/** Callbacks the host wires for the guest API. */\nexport interface McpAppHostOptions {\n /** Guest asked to call a server tool — return its result (posted back to the guest by id). */\n onCallServerTool: (tool: string, args: unknown) => unknown\n /** Guest emitted a chat message to the host app. */\n onSendMessage?: (text: string) => void\n}\n\n/**\n * Pure bridge: interpret one guest message and (for `callServerTool`) post the result back via\n * `post`. Exported for unit testing without a DOM. Unknown message shapes are ignored — the guest\n * API is capability-scoped, not an open RPC surface.\n */\nexport function createGuestMessageHandler(\n opts: McpAppHostOptions,\n post: (message: unknown) => void,\n): (data: unknown) => Promise<void> {\n return async (data: unknown): Promise<void> => {\n if (typeof data !== 'object' || data === null) return\n const msg = data as Partial<GuestMessage> & { type?: string }\n if (\n msg.type === 'callServerTool' &&\n typeof msg.id === 'string' &&\n typeof msg.tool === 'string'\n ) {\n const result = await opts.onCallServerTool(msg.tool, msg.args)\n post({ type: 'callServerTool:result', id: msg.id, result })\n return\n }\n if (msg.type === 'sendMessage' && typeof (msg as { text?: unknown }).text === 'string') {\n opts.onSendMessage?.((msg as { text: string }).text)\n }\n }\n}\n\n/** Handle returned by {@link mountMcpApp}. */\nexport interface McpAppHandle {\n iframe: HTMLIFrameElement\n /** Remove the message listener and the iframe. */\n dispose: () => void\n}\n\n/** The sandbox tokens the guest iframe is allowed — scripts only, NEVER `allow-same-origin`. */\nexport const MCP_APP_SANDBOX = 'allow-scripts'\n\n/**\n * Mount an MCP App resource's HTML in a sandboxed iframe inside `container`, wiring the guest API.\n * The HTML comes from `resources/read` (see `mcp-app-resources.ts`). Returns a handle to dispose.\n */\nexport function mountMcpApp(\n container: HTMLElement,\n resource: { html: string },\n opts: McpAppHostOptions,\n): McpAppHandle {\n const iframe = container.ownerDocument.createElement('iframe')\n // Security: scripts only, null origin. Do NOT add allow-same-origin.\n iframe.setAttribute('sandbox', MCP_APP_SANDBOX)\n iframe.srcdoc = resource.html\n container.appendChild(iframe)\n\n const post = (message: unknown): void => {\n // The guest is a sandboxed srcdoc iframe (allow-scripts, NO allow-same-origin) → its origin is\n // the opaque string \"null\", which cannot be used as a reliable targetOrigin. '*' is the only\n // valid target for a null-origin sandboxed guest; the sandbox (no navigation, no same-origin)\n // is what prevents a cross-origin leak, not the targetOrigin string.\n // eslint-disable-next-line sonarjs/post-message -- sandboxed null-origin iframe: '*' is correct\n iframe.contentWindow?.postMessage(message, '*')\n }\n const handle = createGuestMessageHandler(opts, post)\n\n const onMessage = (event: MessageEvent): void => {\n // Only trust messages from THIS iframe's guest window.\n if (event.source !== iframe.contentWindow) return\n void handle(event.data)\n }\n const view = container.ownerDocument.defaultView\n view?.addEventListener('message', onMessage)\n\n return {\n iframe,\n dispose: () => {\n view?.removeEventListener('message', onMessage)\n iframe.remove()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,eAAe;;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,CAAC,YAA2B;AAMvC,WAAO,eAAe,YAAY,SAAS,GAAG;AAAA,EAChD;AACA,QAAM,SAAS,0BAA0B,MAAM,IAAI;AAEnD,QAAM,YAAY,CAAC,UAA8B;AAE/C,QAAI,MAAM,WAAW,OAAO,cAAe;AAC3C,SAAK,OAAO,MAAM,IAAI;AAAA,EACxB;AACA,QAAM,OAAO,UAAU,cAAc;AACrC,QAAM,iBAAiB,WAAW,SAAS;AAE3C,SAAO;AAAA,IACL;AAAA,IACA,SAAS,MAAM;AACb,YAAM,oBAAoB,WAAW,SAAS;AAC9C,aAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF;","names":["useRef","jsx","jsx"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import "./chunk-DGUM43GV.js";
|
|
2
|
+
|
|
3
|
+
// src/vite-plugin/controller-swc-transform.ts
|
|
4
|
+
import { resolve } from "path";
|
|
5
|
+
import { transformControllerSource } from "@theokit/http";
|
|
6
|
+
function toPosix(p) {
|
|
7
|
+
return p.replace(/\\/g, "/");
|
|
8
|
+
}
|
|
9
|
+
function controllerSwcTransformPlugin(options) {
|
|
10
|
+
const controllersDir = toPosix(resolve(options.serverDir, "controllers")) + "/";
|
|
11
|
+
return {
|
|
12
|
+
name: "theo:controller-swc-transform",
|
|
13
|
+
enforce: "pre",
|
|
14
|
+
async transform(code, id) {
|
|
15
|
+
const cleanId = toPosix(id.split("?")[0]);
|
|
16
|
+
if (!cleanId.startsWith(controllersDir) || !cleanId.endsWith(".ts")) {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
const transformed = await transformControllerSource(code, cleanId, options.loadSwcCore);
|
|
20
|
+
return { code: transformed, map: null };
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export {
|
|
25
|
+
controllerSwcTransformPlugin
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=controller-swc-transform-URELVCBM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vite-plugin/controller-swc-transform.ts"],"sourcesContent":["import { resolve } from 'node:path'\n\nimport { transformControllerSource, type SwcCore } from '@theokit/http'\nimport type { Plugin } from 'vite'\n\n/** Vite normalizes module ids to POSIX `/` on every OS; normalize the prefix to match. */\nfunction toPosix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n\n/**\n * Vite plugin that compiles `<serverDir>/controllers/**` through @theokit/http's\n * swc transform so parameter decorators (`@Body`, `@Param`, `@Query`) emit the\n * `design:paramtypes` metadata esbuild silently drops. Without it, controller\n * dispatch (Task 1.2) cannot validate `@Body` or bind `@Param`.\n *\n * Scope discipline (ADR-4): the transform is a strict no-op for every file\n * outside `controllers/`, so file-based `route()` compilation is byte-for-byte\n * unchanged. `enforce: 'pre'` runs it before esbuild would mangle the decorators.\n *\n * The swc-loader is REUSED, never reimplemented (ADR-1 / Rule 9 / G12): the swc\n * option block lives once in `@theokit/http`.\n */\nexport interface ControllerSwcTransformOptions {\n /** Absolute backend root (config `serverDir`). Only `controllers/` under it is transformed. */\n serverDir: string\n /**\n * Injectable `@swc/core` loader — test seam only. Defaults to the loader\n * inside `transformControllerSource`, which resolves + caches @swc/core.\n */\n loadSwcCore?: () => Promise<SwcCore | null>\n}\n\nexport function controllerSwcTransformPlugin(options: ControllerSwcTransformOptions): Plugin {\n // Trailing `/` so `server/controllers-ui/` cannot false-match `server/controllers`.\n // POSIX-normalized so the prefix compares against Vite's `/`-separated ids on Windows too.\n const controllersDir = toPosix(resolve(options.serverDir, 'controllers')) + '/'\n\n return {\n name: 'theo:controller-swc-transform',\n enforce: 'pre',\n async transform(code: string, id: string) {\n // Strip Vite's query suffix (`?t=...`, `?worker`, etc.) + normalize separators.\n const cleanId = toPosix(id.split('?')[0])\n if (!cleanId.startsWith(controllersDir) || !cleanId.endsWith('.ts')) {\n return null\n }\n const transformed = await transformControllerSource(code, cleanId, options.loadSwcCore)\n return { code: transformed, map: null }\n },\n }\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AAExB,SAAS,iCAA+C;AAIxD,SAAS,QAAQ,GAAmB;AAClC,SAAO,EAAE,QAAQ,OAAO,GAAG;AAC7B;AAyBO,SAAS,6BAA6B,SAAgD;AAG3F,QAAM,iBAAiB,QAAQ,QAAQ,QAAQ,WAAW,aAAa,CAAC,IAAI;AAE5E,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM,UAAU,MAAc,IAAY;AAExC,YAAM,UAAU,QAAQ,GAAG,MAAM,GAAG,EAAE,CAAC,CAAC;AACxC,UAAI,CAAC,QAAQ,WAAW,cAAc,KAAK,CAAC,QAAQ,SAAS,KAAK,GAAG;AACnE,eAAO;AAAA,MACT;AACA,YAAM,cAAc,MAAM,0BAA0B,MAAM,SAAS,QAAQ,WAAW;AACtF,aAAO,EAAE,MAAM,aAAa,KAAK,KAAK;AAAA,IACxC;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "tsx/esm";
|
|
3
|
+
|
|
4
|
+
// src/vite-plugin/controller-swc-transform.ts
|
|
5
|
+
import { resolve } from "path";
|
|
6
|
+
import { transformControllerSource } from "@theokit/http";
|
|
7
|
+
function toPosix(p) {
|
|
8
|
+
return p.replace(/\\/g, "/");
|
|
9
|
+
}
|
|
10
|
+
function controllerSwcTransformPlugin(options) {
|
|
11
|
+
const controllersDir = toPosix(resolve(options.serverDir, "controllers")) + "/";
|
|
12
|
+
return {
|
|
13
|
+
name: "theo:controller-swc-transform",
|
|
14
|
+
enforce: "pre",
|
|
15
|
+
async transform(code, id) {
|
|
16
|
+
const cleanId = toPosix(id.split("?")[0]);
|
|
17
|
+
if (!cleanId.startsWith(controllersDir) || !cleanId.endsWith(".ts")) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
const transformed = await transformControllerSource(code, cleanId, options.loadSwcCore);
|
|
21
|
+
return { code: transformed, map: null };
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
controllerSwcTransformPlugin
|
|
27
|
+
};
|
|
28
|
+
//# sourceMappingURL=controller-swc-transform-XV3ETSE3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/vite-plugin/controller-swc-transform.ts"],"sourcesContent":["import { resolve } from 'node:path'\n\nimport { transformControllerSource, type SwcCore } from '@theokit/http'\nimport type { Plugin } from 'vite'\n\n/** Vite normalizes module ids to POSIX `/` on every OS; normalize the prefix to match. */\nfunction toPosix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n\n/**\n * Vite plugin that compiles `<serverDir>/controllers/**` through @theokit/http's\n * swc transform so parameter decorators (`@Body`, `@Param`, `@Query`) emit the\n * `design:paramtypes` metadata esbuild silently drops. Without it, controller\n * dispatch (Task 1.2) cannot validate `@Body` or bind `@Param`.\n *\n * Scope discipline (ADR-4): the transform is a strict no-op for every file\n * outside `controllers/`, so file-based `route()` compilation is byte-for-byte\n * unchanged. `enforce: 'pre'` runs it before esbuild would mangle the decorators.\n *\n * The swc-loader is REUSED, never reimplemented (ADR-1 / Rule 9 / G12): the swc\n * option block lives once in `@theokit/http`.\n */\nexport interface ControllerSwcTransformOptions {\n /** Absolute backend root (config `serverDir`). Only `controllers/` under it is transformed. */\n serverDir: string\n /**\n * Injectable `@swc/core` loader — test seam only. Defaults to the loader\n * inside `transformControllerSource`, which resolves + caches @swc/core.\n */\n loadSwcCore?: () => Promise<SwcCore | null>\n}\n\nexport function controllerSwcTransformPlugin(options: ControllerSwcTransformOptions): Plugin {\n // Trailing `/` so `server/controllers-ui/` cannot false-match `server/controllers`.\n // POSIX-normalized so the prefix compares against Vite's `/`-separated ids on Windows too.\n const controllersDir = toPosix(resolve(options.serverDir, 'controllers')) + '/'\n\n return {\n name: 'theo:controller-swc-transform',\n enforce: 'pre',\n async transform(code: string, id: string) {\n // Strip Vite's query suffix (`?t=...`, `?worker`, etc.) + normalize separators.\n const cleanId = toPosix(id.split('?')[0])\n if (!cleanId.startsWith(controllersDir) || !cleanId.endsWith('.ts')) {\n return null\n }\n const transformed = await transformControllerSource(code, cleanId, options.loadSwcCore)\n return { code: transformed, map: null }\n },\n }\n}\n"],"mappings":";;;;AAAA,SAAS,eAAe;AAExB,SAAS,iCAA+C;AAIxD,SAAS,QAAQ,GAAmB;AAClC,SAAO,EAAE,QAAQ,OAAO,GAAG;AAC7B;AAyBO,SAAS,6BAA6B,SAAgD;AAG3F,QAAM,iBAAiB,QAAQ,QAAQ,QAAQ,WAAW,aAAa,CAAC,IAAI;AAE5E,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MAAM,UAAU,MAAc,IAAY;AAExC,YAAM,UAAU,QAAQ,GAAG,MAAM,GAAG,EAAE,CAAC,CAAC;AACxC,UAAI,CAAC,QAAQ,WAAW,cAAc,KAAK,CAAC,QAAQ,SAAS,KAAK,GAAG;AACnE,eAAO;AAAA,MACT;AACA,YAAM,cAAc,MAAM,0BAA0B,MAAM,SAAS,QAAQ,WAAW;AACtF,aAAO,EAAE,MAAM,aAAa,KAAK,KAAK;AAAA,IACxC;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import "tsx/esm";
|
|
3
|
-
import {
|
|
4
|
-
validateProjectStructure
|
|
5
|
-
} from "./chunk-GEQJAFSV.js";
|
|
6
3
|
import {
|
|
7
4
|
preflightNodeAndBindings
|
|
8
5
|
} from "./chunk-HNBWZKIQ.js";
|
|
6
|
+
import {
|
|
7
|
+
validateProjectStructure
|
|
8
|
+
} from "./chunk-GEQJAFSV.js";
|
|
9
9
|
import {
|
|
10
10
|
theoPluginAsync
|
|
11
|
-
} from "./chunk-
|
|
12
|
-
import "./chunk-
|
|
11
|
+
} from "./chunk-QMV3R6D5.js";
|
|
12
|
+
import "./chunk-2HKRQUWU.js";
|
|
13
13
|
import "./chunk-2CVV6CNN.js";
|
|
14
14
|
import "./chunk-M6NMS5LR.js";
|
|
15
15
|
import "./chunk-IEES3CHD.js";
|
|
@@ -24,8 +24,8 @@ import {
|
|
|
24
24
|
orchestrateDev
|
|
25
25
|
} from "./chunk-45C3WUQ7.js";
|
|
26
26
|
import "./chunk-5ODOE6EF.js";
|
|
27
|
-
import "./chunk-
|
|
28
|
-
import "./chunk-
|
|
27
|
+
import "./chunk-OLZLYLOE.js";
|
|
28
|
+
import "./chunk-BKYFOEBK.js";
|
|
29
29
|
import "./chunk-NQRNDPZJ.js";
|
|
30
30
|
import "./chunk-L4GCEMNW.js";
|
|
31
31
|
import "./chunk-FRUEDJFX.js";
|
|
@@ -111,4 +111,4 @@ export {
|
|
|
111
111
|
devCommand,
|
|
112
112
|
startDevServer
|
|
113
113
|
};
|
|
114
|
-
//# sourceMappingURL=dev-
|
|
114
|
+
//# sourceMappingURL=dev-IBCZYFZZ.js.map
|
package/dist/index.js
CHANGED
|
@@ -8,12 +8,12 @@ import {
|
|
|
8
8
|
scanRoutes,
|
|
9
9
|
theoConfigSchema,
|
|
10
10
|
theoPlugin
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-QCB7ZNR2.js";
|
|
12
12
|
import "./chunk-D7ZH7DTG.js";
|
|
13
13
|
import "./chunk-7BIM27LV.js";
|
|
14
|
-
import "./chunk-
|
|
15
|
-
import "./chunk-
|
|
16
|
-
import "./chunk-
|
|
14
|
+
import "./chunk-QNFVYST4.js";
|
|
15
|
+
import "./chunk-GW5H4KB4.js";
|
|
16
|
+
import "./chunk-QWBXUZAX.js";
|
|
17
17
|
import "./chunk-GY5Q27BJ.js";
|
|
18
18
|
import "./chunk-5QW7IQQU.js";
|
|
19
19
|
import "./chunk-WFNLNIJX.js";
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import
|
|
1
|
+
import {
|
|
2
|
+
createControllerDispatcher,
|
|
3
|
+
dispatchControllerRequest
|
|
4
|
+
} from "./chunk-QNFVYST4.js";
|
|
2
5
|
import {
|
|
3
6
|
BATCH_PATH,
|
|
4
7
|
TRACE_HEADER,
|
|
@@ -9,7 +12,7 @@ import {
|
|
|
9
12
|
handleBatchRequest,
|
|
10
13
|
incomingMessageToHandlerRequest,
|
|
11
14
|
sendError
|
|
12
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-QWBXUZAX.js";
|
|
13
16
|
import "./chunk-GY5Q27BJ.js";
|
|
14
17
|
import {
|
|
15
18
|
findSuggestion
|
|
@@ -59,10 +62,12 @@ export {
|
|
|
59
62
|
CsrfReadinessStore,
|
|
60
63
|
TRACE_HEADER,
|
|
61
64
|
applySecurityHeaders,
|
|
65
|
+
createControllerDispatcher,
|
|
62
66
|
createCorsHandler,
|
|
63
67
|
createPluginRunnerFromConfig,
|
|
64
68
|
createRateLimiter,
|
|
65
69
|
createViteLoader,
|
|
70
|
+
dispatchControllerRequest,
|
|
66
71
|
executeAction,
|
|
67
72
|
executeRoute,
|
|
68
73
|
extractTraceId,
|
|
@@ -82,4 +87,4 @@ export {
|
|
|
82
87
|
scanWebSocketRoutes,
|
|
83
88
|
sendError
|
|
84
89
|
};
|
|
85
|
-
//# sourceMappingURL=internal-api-
|
|
90
|
+
//# sourceMappingURL=internal-api-MDCX7A7H.js.map
|
|
@@ -5,12 +5,14 @@ import {
|
|
|
5
5
|
CSP_REPORT_PATH,
|
|
6
6
|
CsrfReadinessStore,
|
|
7
7
|
TRACE_HEADER,
|
|
8
|
+
createControllerDispatcher,
|
|
8
9
|
createCorsHandler,
|
|
10
|
+
dispatchControllerRequest,
|
|
9
11
|
extractTraceId,
|
|
10
12
|
handleBatchRequest,
|
|
11
13
|
handleCspReport,
|
|
12
14
|
handleCsrfReadiness
|
|
13
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-OLZLYLOE.js";
|
|
14
16
|
import {
|
|
15
17
|
applySecurityHeaders,
|
|
16
18
|
createPluginRunnerFromConfig,
|
|
@@ -23,7 +25,7 @@ import {
|
|
|
23
25
|
incomingMessageToHandlerRequest,
|
|
24
26
|
logRequest,
|
|
25
27
|
sendError
|
|
26
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-BKYFOEBK.js";
|
|
27
29
|
import {
|
|
28
30
|
generateManifest
|
|
29
31
|
} from "./chunk-NQRNDPZJ.js";
|
|
@@ -45,10 +47,12 @@ export {
|
|
|
45
47
|
CsrfReadinessStore,
|
|
46
48
|
TRACE_HEADER,
|
|
47
49
|
applySecurityHeaders,
|
|
50
|
+
createControllerDispatcher,
|
|
48
51
|
createCorsHandler,
|
|
49
52
|
createPluginRunnerFromConfig,
|
|
50
53
|
createRateLimiter,
|
|
51
54
|
createViteLoader,
|
|
55
|
+
dispatchControllerRequest,
|
|
52
56
|
executeAction,
|
|
53
57
|
executeRoute,
|
|
54
58
|
extractTraceId,
|
|
@@ -68,4 +72,4 @@ export {
|
|
|
68
72
|
scanWebSocketRoutes,
|
|
69
73
|
sendError
|
|
70
74
|
};
|
|
71
|
-
//# sourceMappingURL=internal-api-
|
|
75
|
+
//# sourceMappingURL=internal-api-OLNM25HS.js.map
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
4
|
createAgentSsrLoader
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-IPSFSNEJ.js";
|
|
6
6
|
import {
|
|
7
7
|
extractAppResources,
|
|
8
8
|
handleMcpJsonRpc
|
|
@@ -75,4 +75,4 @@ async function mcpCommand(name, deps = {}) {
|
|
|
75
75
|
export {
|
|
76
76
|
mcpCommand
|
|
77
77
|
};
|
|
78
|
-
//# sourceMappingURL=mcp-
|
|
78
|
+
//# sourceMappingURL=mcp-DKRODZAL.js.map
|