theokit 0.70.1 → 0.71.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/{aws-lambda-OCJM5YGB.js → aws-lambda-MUGK4WNZ.js} +36 -7
- package/dist/aws-lambda-MUGK4WNZ.js.map +1 -0
- package/dist/{build-ZC46IAFI.js → build-KCIH3HI6.js} +2 -2
- package/dist/build-KCIH3HI6.js.map +1 -0
- package/dist/{bun-KRUAWYRW.js → bun-JWZ2UOLJ.js} +5 -104
- package/dist/bun-JWZ2UOLJ.js.map +1 -0
- package/dist/{chunk-XG6SQUEP.js → chunk-6AGXDYVE.js} +2 -2
- package/dist/{chunk-FFGP2LGQ.js → chunk-IGCOTLQI.js} +135 -1
- package/dist/chunk-IGCOTLQI.js.map +1 -0
- package/dist/{chunk-2XYKRS7Y.js → chunk-Q4NSUGMS.js} +3 -1
- package/dist/cli/index.js +2 -2
- package/dist/{cloudflare-GK4VD3EU.js → cloudflare-XO43ZIQF.js} +39 -10
- package/dist/cloudflare-XO43ZIQF.js.map +1 -0
- package/dist/{deno-deploy-WMNXRVGL.js → deno-deploy-EUQDK2RC.js} +39 -11
- package/dist/deno-deploy-EUQDK2RC.js.map +1 -0
- package/dist/{netlify-VOL54SC7.js → netlify-LEYEQZK6.js} +25 -3
- package/dist/netlify-LEYEQZK6.js.map +1 -0
- package/dist/{preview-TYLABTAE.js → preview-YDJSRJ2K.js} +2 -2
- package/dist/{registry-DDBXDHJ2.js → registry-4JHCZ6EF.js} +7 -7
- package/dist/router/element-scroll-restoration.js +25 -6
- package/dist/router/element-scroll-restoration.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +6 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/rate-limit/index.d.ts +12 -2
- package/dist/server/rate-limit/index.js +7 -3
- package/dist/{vercel-LZTDSDJF.js → vercel-HTAWCNAG.js} +51 -5
- package/dist/vercel-HTAWCNAG.js.map +1 -0
- package/package.json +3 -3
- package/dist/aws-lambda-OCJM5YGB.js.map +0 -1
- package/dist/build-ZC46IAFI.js.map +0 -1
- package/dist/bun-KRUAWYRW.js.map +0 -1
- package/dist/chunk-FFGP2LGQ.js.map +0 -1
- package/dist/cloudflare-GK4VD3EU.js.map +0 -1
- package/dist/deno-deploy-WMNXRVGL.js.map +0 -1
- package/dist/netlify-VOL54SC7.js.map +0 -1
- package/dist/vercel-LZTDSDJF.js.map +0 -1
- /package/dist/{chunk-XG6SQUEP.js.map → chunk-6AGXDYVE.js.map} +0 -0
- /package/dist/{chunk-2XYKRS7Y.js.map → chunk-Q4NSUGMS.js.map} +0 -0
- /package/dist/{preview-TYLABTAE.js.map → preview-YDJSRJ2K.js.map} +0 -0
- /package/dist/{registry-DDBXDHJ2.js.map → registry-4JHCZ6EF.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/deployed-agents.ts","../src/adapters/deployed-cors.ts","../src/adapters/deployed-csrf.ts","../src/adapters/security-headers.ts","../src/adapters/deployed-runtime-config.ts","../src/adapters/deployed-trace.ts"],"sourcesContent":["/**\n * Serving an agent from a generated deploy entry (usetheokit/theokit#367).\n *\n * ## The gap this closes\n *\n * `grep -rc \"agent\" packages/theo/src/adapters/*.ts` used to return nothing across 14 files. The\n * notion did not exist in this layer at all: every generated entry routes `/api/` exclusively\n * through `scanServerRoutes` + `executeRoute`, and an agent is a DIFFERENT scan served by a\n * DIFFERENT function — `scanAgents` + `mountAgent`. So `/api/agents/chat` matched no file route and\n * fell into `notFoundResponse()` on every target.\n *\n * For a framework whose stated reason to exist is \"the agent is a file, delivered by the same\n * pipeline that serves the page\", that is the gap which contradicts the sentence: the agent was\n * delivered by no pipeline at all outside a machine running `theokit start`.\n *\n * ## Why baking, and why `../../`\n *\n * A Worker has no filesystem to scan and no path to `import()`, which is the same reason routes are\n * baked (#369). The agent modules are resolved on the build machine and emitted as static imports,\n * relative to the entry's directory — every target that can do this writes two levels below the\n * project root, so the arithmetic is the one `renderBakedRoutes` already does.\n *\n * ## Which targets can do it\n *\n * Only the ones whose output is BUNDLED from the project: `cloudflare` (wrangler), `bun` and\n * `deno-deploy` resolve the emitted import against the app's own source tree. `vercel`, `netlify`\n * and `aws-lambda` receive a standalone function directory that never sees the app's modules, so\n * an agent cannot travel there by this road at all. Same split as plugins (#425), same cause.\n *\n * ## The table is keyed by NAME\n *\n * The URL carries the name, the access policy is judged under the name, and the run's spans are\n * labelled with it (#406). Keying by file path would make the lookup depend on the server's\n * directory layout — which changes per deploy, and which is exactly the value #406 removed from\n * telemetry for the same reason.\n */\n\n/** One agent, as `scanAgents` reports it. Structural, so the adapters need no `server/` import. */\nexport interface DeployedAgent {\n /** Path relative to the project root — the specifier the static import uses. */\n readonly filePath: string\n /** The URL the agent answers on. */\n readonly agentPath: string\n /** The agent's NAME — what the URL carries, the policy is judged under, and spans are labelled. */\n readonly name: string\n}\n\nexport interface DeployedAgentsFragment {\n /** Top-level imports of the agent modules. */\n readonly imports: string[]\n /** Module-scope declarations — the name→module table. */\n readonly declarations: string[]\n /** The request-handler branch, to be emitted before the file-route table is consulted. */\n readonly branch: string[]\n /**\n * SI-020 — the condition a host ANDs into its non-API early-return guard, so an agent card path\n * is not handed to static assets before this fragment's branch is reached.\n *\n * Empty string when the fragment emits nothing, so a host that interpolates it unconditionally\n * never references a name that was not declared.\n */\n readonly hostBypass: string\n}\n\nconst EMPTY: DeployedAgentsFragment = { imports: [], declarations: [], branch: [], hostBypass: '' }\n\n/**\n * How the host entry names the things this branch has to use.\n *\n * The fragment is generated code injected into three entries that do NOT agree on their own\n * vocabulary — Bun reads `pathname`, Cloudflare reads `url.pathname`; Deno calls `notFound()`,\n * Cloudflare calls `notFoundResponse()`; Cloudflare wraps each branch in the security baseline\n * while Bun and Deno wrap once at the caller; Deno resolves npm packages with an `npm:` prefix.\n *\n * Naming those differences is what keeps this ONE fragment. The alternative — three near-identical\n * branches, one per adapter — is the copy that `serveThroughPluginLifecycle` was extracted to undo\n * after it had drifted five ways (#405).\n */\n/**\n * How the target REACHES its agent modules — and the two answers are genuinely different, not a\n * copy waiting to be merged.\n *\n * A Worker has no filesystem: its agents must be resolved on the build machine and emitted as\n * static imports, which is what `renderBakedRoutes` already does for routes there. Bun and Deno DO\n * have a filesystem and already scan their routes at request time; making them bake would couple an\n * agent's existence to a rebuild for no gain. The split mirrors the one routes already have on\n * exactly these targets, which is the argument for keeping it.\n */\nexport type DeployedAgentsSource =\n | {\n readonly kind: 'baked'\n /** Scanned on the build machine, emitted as static imports. */\n readonly agents: readonly DeployedAgent[]\n /**\n * B-185 — the app's `server/context.ts`, as a specifier relative to the emitted entry, or\n * `undefined` when the app has none. A Worker has no filesystem on which to find it, so it is\n * baked like the agent modules beside it (ADR 0014). `undefined` is the ordinary case for an\n * app that declares no context, and emitting an import of a file that is not there would\n * fail the BUILD rather than the request — which is why `planDeployedPlugins` takes the same\n * road for plugins.\n */\n readonly contextModule?: string\n }\n | {\n readonly kind: 'scan'\n /** Expression yielding the project root at runtime. */\n readonly projectRoot: string\n /** Expression yielding the module loader the entry already builds. */\n readonly loadModule: string\n /**\n * A statement that guarantees `loadModule` is usable, for a host that builds its loader\n * lazily. Deno's `loaderCache` is created on the route path, which runs AFTER this branch —\n * so without this the agent branch would call `null`.\n */\n readonly ensureLoader?: string\n /** The configured agents directory as a quoted literal. Absent ⇒ `scanAgents` defaults to `agents`. */\n readonly agentsDirLiteral?: string\n /**\n * B-185 — an expression yielding the app's `server/` directory, which this host already\n * declares (`bun.ts:95`, `deno-deploy.ts:69`) and already hands to `executeRoute`. A host\n * with a filesystem locates its own `context.ts`, so it needs no baking (ADR 0014, and the\n * split `deployed-agents.ts` already argues for routes two docblocks above).\n */\n readonly serverDir?: string\n }\n\nexport interface DeployedAgentsHost {\n /** Expression yielding the request path inside the handler. Default `url.pathname`. */\n readonly pathname?: string\n /** Call producing the 404 response. Default `notFoundResponse()`. */\n readonly notFound?: string\n /** Whether THIS branch applies the security baseline, or the caller already does. */\n readonly wrapSecurityHeaders?: boolean\n /** Prefix for bare package specifiers. Deno needs `npm:`; the others need nothing. */\n readonly importPrefix?: string\n /**\n * Expression yielding the entry's plugin runner, or `undefined` when the app declared no plugins\n * and the build emitted no module to bind.\n *\n * `deployedRuntimeConfigFragment` already declares `const THEO_PLUGIN_RUNNER` at module scope and\n * spreads `pluginRunner: await THEO_PLUGIN_RUNNER` into `executeRoute`; an adapter passes that\n * same expression here rather than building a second runner, because a runner rebuilt per request\n * re-runs every plugin's `register` -- which is where a plugin allocates the state its hooks read.\n */\n readonly pluginRunnerExpr?: string\n}\n\n/**\n * The two `AuxRouteDeps` fields a deployed entry must supply to match what dev already does.\n *\n * Both dev callers pass them — `vite-plugin/agent-middleware.ts:161,164` and\n * `cli/commands/start/handlers.ts:226,229` — and a first draft of this fragment passed neither,\n * on a quotation from `serve-aux-routes.ts:83-85` that names three routes (\"card, approvals,\n * stream\") while the dispatcher serves six. Two reviewers measured the same two consequences:\n *\n * - `csrfMode` unset defaults to `'strict'` (`serve-aux-routes.ts:379`), so an app declaring\n * `security: { csrf: 'off' }` got `off` on `POST /api/agents/<name>` and `strict` on its `/mcp`\n * sibling one line away — verbatim the divergence `deployed-csrf.ts`'s own header exists to\n * record, re-created on a route this slice had just made reachable.\n * - `resolveApiKey` unset makes the thread follow-up answer a permanent 501 on every deploy\n * target (`serve-aux-routes.ts:359-365`), naming a framework-internal parameter to the caller.\n *\n * Both values are already in scope: `CSRF_CONFIG` is spread into `mountAgent` in the same emitted\n * function, and `resolveProvider` is already on its import line.\n */\nconst AUX_DEPS_PARITY = [\n ` ...CSRF_CONFIG,`,\n ` resolveApiKey: (model, plugins) => resolveProvider(model, { plugins }).apiKey,`,\n] as const\n\n/** The prefix the agent convention owns. Matches `handlers.ts`'s own `tryServeAgent`. */\nconst AGENT_PREFIX = '/api/agents/'\n\n/**\n * The second shape the aux dispatcher owns. `matchGetAuxRoute` serves M15's\n * `GET /.well-known/<name>/agent-card.json`, and a guard admitting only {@link AGENT_PREFIX} left\n * five of the dispatcher's six families reachable on a deploy target and excluded the sixth — by\n * the guard, not by a decision, and silently.\n *\n * A prefix rather than the matcher's own `isAgentCardPath`: the guard exists to keep a url nobody\n * answers from paying for anything, and importing the matcher's predicate into every emitted entry\n * would buy a narrower pre-filter at the cost of a module the branch already declines without.\n */\nconst WELL_KNOWN_PREFIX = '/.well-known/'\n\n/**\n * What a deployed entry needs in order to serve the app's agents.\n *\n * @param agents - the agents scanned on the build machine. Empty emits nothing at all.\n */\n/**\n * The scan source every filesystem host with a lazily-created loader shares.\n *\n * Four adapters — `netlify`, `vercel`, `aws-lambda`, `deno-deploy` — emit an entry that resolves\n * `serverDir` itself, caches its loader in `loaderCache`, and creates that cache on first use.\n * They therefore hand this fragment the SAME six fields, and writing them out four times is the\n * copy `serveThroughPluginLifecycle` was extracted to undo after it had drifted five ways (#405).\n *\n * B-235 is what made it four: wiring three more targets duplicated the block three more times, and\n * the duplication gate on new code is what said so — 4.2% against a 3% ceiling. The gate was right\n * and the fix is the one it implies, not a threshold.\n *\n * `bun` is deliberately NOT a caller. It names its loader `loadModule` and creates it eagerly, so\n * it has no `ensureLoader` — a parameter to cover that difference would make this function a\n * switch over its callers, which is the shape that drifts.\n */\nexport function scannedFromLoaderCache(agentsDirLiteral?: string): DeployedAgentsSource {\n return {\n kind: 'scan',\n projectRoot: 'cwd',\n agentsDirLiteral,\n loadModule: 'loaderCache',\n serverDir: 'serverDir',\n ensureLoader: 'if (!loaderCache) loaderCache = createProductionLoader()',\n }\n}\n\n/**\n * The JSON 404 `vercel` and `aws-lambda` answer a routing miss with.\n *\n * An expression rather than a call, because the fragment interpolates `notFound` into a `return`\n * and neither host declares a helper for it.\n */\nexport const JSON_NOT_FOUND_RESPONSE = `new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), { status: 404, headers: { 'content-type': 'application/json' } })`\n\nexport function deployedAgentsFragment(\n source: DeployedAgentsSource | undefined,\n host: DeployedAgentsHost = {},\n): DeployedAgentsFragment {\n if (source === undefined) return EMPTY\n if (source.kind === 'baked' && source.agents.length === 0) return EMPTY\n\n const pathname = host.pathname ?? 'url.pathname'\n const notFound = host.notFound ?? 'notFoundResponse()'\n const prefix = host.importPrefix ?? ''\n\n const resolution =\n source.kind === 'baked'\n ? bakedResolution(source.agents, source.contextModule, host.pluginRunnerExpr)\n : scannedResolution({ ...source, pluginRunnerExpr: host.pluginRunnerExpr })\n\n return {\n hostBypass: ` && !__theoIsAgentCardPath(${pathname})`,\n imports: [\n // `theokit/adapters/agent-mount`, not `theokit/server`: `mount-agent` is deliberately not on\n // the app-facing surface (ADR 0041), and a generated entry is not an app. See that module.\n // B-185 — the identity entry differs by host: a filesystem host LOCATES its own\n // `context.ts`, a Worker is handed the baked factory (ADR 0014). `createWebShim` is not here\n // because all three entries already import it at module level.\n `import { mountAgent, resolveProvider, matchAgentAuxRoute, serveMatchedAuxRoute${resolution.identityImport}${source.kind === 'scan' ? ', scanAgents' : ''} } from '${prefix}theokit/adapters/agent-mount'`,\n ...resolution.imports,\n ],\n declarations: [\n ...resolution.declarations,\n // SI-020 — the host's `/api/` guard decides between the API surface and static assets, and it\n // runs BEFORE this branch. Widening the branch guard alone left the `.well-known` arm as dead\n // code on all three targets: present in the source, unreachable in the emitted program. The\n // host consults this predicate, so the card path escapes the asset branch and NOTHING else\n // under `/.well-known/` does — a blanket prefix bypass would route `/.well-known/security.txt`\n // away from assets, trading an unreachable card for a broken namespace.\n //\n // Same shape as `agent-card-handler.ts`'s own WELL_KNOWN. That is a COPY, not a shared\n // definition, and saying otherwise was the claim an inventory judge falsified: changing the\n // handler to serve `/agent.json` left every card test green, because this guard and that\n // matcher are checked separately and never against each other. The drift that matters here —\n // this guard narrowing while the matcher still serves the path — is caught by\n // `a-deployed-worker-reaches-the-agent-card.test.ts`, which drives a real request. The other\n // direction is not, and is the honest limit of this line.\n String.raw`const __theoIsAgentCardPath = (p) => /^\\/\\.well-known\\/[^/]+\\/agent-card\\.json$/.test(p)`,\n // B-185 — one factory, two call sites: the aux branch on a hit, and the run handler below.\n // Declared rather than inlined twice so the mechanism ADR 0014 decides has a single home.\n // `async` because the entry's plugin runner is a promise: `createPluginRunnerFromConfig` is\n // async, so the runtime-config fragment declares `const THEO_PLUGIN_RUNNER = createPluginRunnerFromConfig(...)`\n // WITHOUT awaiting it, and every consumer awaits at the point of use. `await` is a reserved\n // word everywhere in an ES module, so a non-async factory carrying that binding does not\n // merely misbehave -- the entry does not parse, and `tests/unit/adapter-entry-parses.test.ts`\n // is where that is caught. It went red at HEAD before this line existed, on a first version\n // of this fix whose own test asserted `toContain('await THEO_PLUGIN_RUNNER')`: the presence\n // of the token that breaks the parse. That test file's header says why, in its own words --\n // `toContain` does not care whether the string is a program.\n //\n // Laziness is unaffected. The shim was always built eagerly inside this factory; what ADR-1\n // refuses is paying for a url nobody answers, and neither call site is reached by one.\n `async function __theoResolveSubject(request) {`,\n ...resolution.identity,\n ` return resolveSubject`,\n `}`,\n ],\n branch: [\n ` // #367 — the agent convention owns this prefix. It is answered BEFORE the file-route`,\n ` // table because an agent matches no file route: falling through is how a deployed`,\n ` // \\`/api/agents/<name>\\` used to 404 on every target.`,\n ` if (`,\n ` ${pathname}.startsWith(${JSON.stringify(AGENT_PREFIX)}) ||`,\n ` ${pathname}.startsWith(${JSON.stringify(WELL_KNOWN_PREFIX)})`,\n ` ) {`,\n ...resolution.auxPrelude,\n ` // B-185 — the aux dispatcher is asked FIRST, and declining costs nothing: the matcher`,\n ` // reads the url and the scanned nodes, never a module (ADR-1). A miss falls through to`,\n ` // the run handler exactly as before, so this branch owns the sub-paths and nothing more.`,\n ` const auxRoute = await matchAgentAuxRoute(request.method, ${pathname}, auxDeps)`,\n ` if (auxRoute !== null) {`,\n ` // B-185 — identity is resolved only now. Building it costs a web shim and, where the`,\n ` // app declares one, a call into its own \\`createContext\\`; a url this dispatcher`,\n ` // merely declined must pay for neither (resolve-agent-subject.ts:93-96).`,\n ` const auxResponse = await serveMatchedAuxRoute(auxRoute, request, {`,\n ` ...auxDeps,`,\n ` resolveSubject: await __theoResolveSubject(request),`,\n ` })`,\n host.wrapSecurityHeaders === true\n ? ` return withSecurityHeaders(auxResponse, SECURITY_HEADERS)`\n : ` return auxResponse`,\n ` }`,\n ` // B-185 — only the agent prefix has a run handler behind it. A \\`.well-known\\` url the`,\n ` // dispatcher declined must NOT slice a prefix it does not carry: the name would be`,\n ` // garbage and mountAgent would answer 500 for what is a routing miss.`,\n ` if (!${pathname}.startsWith(${JSON.stringify(AGENT_PREFIX)})) return ${notFound}`,\n ` const agentName = ${pathname}.slice(${String(AGENT_PREFIX.length)}).split('/')[0]`,\n ...resolution.lookup,\n ` // A name nobody scanned is a 404, exactly like any other unknown path. Handing`,\n ` // \\`undefined\\` to mountAgent would surface as a 500 for what is a routing miss.`,\n ` if (mod === undefined) return ${notFound}`,\n ` const agentResponse = await mountAgent(mod, request, (model, plugins) => resolveProvider(model, { plugins }).apiKey, {`,\n ` agentName,`,\n ` // B-185 — mount-agent.ts:121 has accepted this since #365 and 0 of 23 adapters passed`,\n ` // one, so agent-access.ts:146 judged every deployed policy against \\`subject: null\\`.`,\n ` // A run is not a decline: it is about to do real work, so the shim this builds is not`,\n ` // the cost ADR-1 refuses.`,\n ` resolveSubject: await __theoResolveSubject(request),`,\n ` ...CSRF_CONFIG,`,\n ` })`,\n host.wrapSecurityHeaders === true\n ? ` return withSecurityHeaders(agentResponse, SECURITY_HEADERS)`\n : ` return agentResponse`,\n ` }`,\n ],\n }\n}\n\ninterface AgentResolution {\n imports: string[]\n declarations: string[]\n /** Lines that must leave `mod` bound to the agent's module, or `undefined`. */\n lookup: string[]\n /**\n * B-185 — lines that must leave `auxDeps` bound to an `AuxRouteDeps`, plus the expression for\n * its `agents`. They run BEFORE {@link AgentResolution.lookup} so a declined aux route performs\n * no module load, which is what ADR-1 buys and what a later ordering would spend.\n */\n auxPrelude: string[]\n /**\n * B-185 — lines that must leave `resolveSubject` bound to a resolver, or to `undefined`. Emitted\n * only where a match has already happened, because building one costs a web shim and\n * `resolve-agent-subject.ts:93-96` states that a declined url must never run the application's\n * `createContext`.\n */\n identity: string[]\n /**\n * B-185 — what {@link AgentResolution.identity} imports, appended to the `agent-mount` line, or\n * `''` where identity is not resolved at all.\n *\n * It lives HERE, beside the lines that CALL it, because a first draft decided it in a separate\n * `identityEntryFor` that switched the same discriminated union a second time. The two could not\n * disagree then — the conditions were identical — which is what made it latent rather than live.\n * A later drift would emit an entry that CALLS a symbol it never imported, and nothing catches\n * that: the stub-coverage guard derives its requirement FROM the imports, so a missing import\n * shrinks the requirement instead of failing, and `node --check` is syntax rather than\n * resolution. It would surface as a `ReferenceError` inside a deployed Worker.\n */\n identityImport: string\n}\n\n/** No filesystem: every agent module is a static import decided on the build machine. */\nfunction bakedResolution(\n agents: readonly DeployedAgent[],\n contextModule: string | undefined,\n pluginRunnerExpr: string | undefined,\n): AgentResolution {\n const varOf = (index: number): string => `__theoAgent${String(index)}`\n return {\n imports: [\n ...agents.map((agent, index) => `import * as ${varOf(index)} from '../../${agent.filePath}'`),\n // B-185 — the app's context module, baked exactly like the agents above it (ADR 0014).\n ...(contextModule === undefined\n ? []\n : [\n // SI-022 — DYNAMIC, not a top-level static import. B-185 added this import; before it\n // a Worker did not load the app's `server/context.ts` at all. A module-scope throw\n // there — the commonest shape being a required-env-var check — then went from costing\n // nothing to taking the ENTIRE target down: the import fails, the module never\n // evaluates, and every route dies rather than only the one that wanted an identity.\n //\n // That is strictly worse than what `resolve-agent-subject.ts:69-72` promises. It says\n // a throwing `createContext` reaches the branch's own error handler and becomes a 500,\n // which is a failure scoped to the request that needed identity. A throw at IMPORT\n // time reaches no handler at all.\n //\n // A relative `import()` is statically analysable, so wrangler bundles the module\n // exactly as it bundled the static form — the reason ADR 0014 bakes it is unaffected.\n // What changes is WHEN it evaluates, and therefore what a failure costs. It is only\n // a real improvement if the import stays inside the thunk; see the factory below.\n `const __theoContext = () => import('../../${contextModule}')`,\n ]),\n ],\n declarations: [\n `// #367 — the app's agents, keyed by NAME because that is what the URL carries, what the`,\n `// access policy is judged under, and what the run's spans are labelled with (#406).`,\n `const agents = {`,\n ...agents.map((agent, index) => ` ${JSON.stringify(agent.name)}: ${varOf(index)},`),\n `}`,\n `// B-185 — the node list the aux dispatcher matches a url against. There is deliberately NO`,\n `// second table keyed by file path: \\`test_the_table_is_keyed_by_agent_name_not_by_file_path\\``,\n `// forbids one, and the reason it gives is the right one — a path key makes a lookup depend on`,\n `// the server's directory layout. The loader below reaches the module THROUGH this list, so the`,\n `// layout appears once, here, and the module table above stays keyed by the name the URL, the`,\n `// access policy and the run's spans all carry (#406).`,\n `const agentNodes = [`,\n ...agents.map(\n (agent) =>\n ` { filePath: ${JSON.stringify(agent.filePath)}, agentPath: ${JSON.stringify(agent.agentPath)}, name: ${JSON.stringify(agent.name)} },`,\n ),\n `]`,\n ],\n lookup: [\n ` const mod = Object.prototype.hasOwnProperty.call(agents, agentName)`,\n ` ? agents[agentName]`,\n ` : undefined`,\n ],\n identityImport: contextModule === undefined ? '' : ', createSubjectResolverFromFactory',\n identity:\n contextModule === undefined\n ? [\n ` // B-185 — this app declares no \\`server/context.ts\\`, so there is no factory to`,\n ` // bake and an anonymous caller is the honest answer. A policy that admits`,\n ` // nobody is the correct outcome, not an error.`,\n ` const resolveSubject = undefined`,\n ]\n : [\n ` // B-185 — a Worker has no filesystem to find \\`context.ts\\` on, so the module is baked`,\n ` // and its factory handed straight to the resolver (ADR 0014).`,\n ` //`,\n ` // This function has TWO callers and is lazy on purpose. Both build a shim, and that is`,\n ` // correct at both: the aux branch calls it only AFTER a match, and the run handler is`,\n ` // about to do real work. What neither pays for is the app's own \\`createContext\\` on a`,\n ` // url nobody answers — the resolver is a thunk, and \\`agent-access.ts:146\\` returns early`,\n ` // for an absent or public policy without ever invoking it.`,\n ` const { req: __theoReq, res: __theoRes } = createWebShim(request)`,\n ` const resolveSubject = createSubjectResolverFromFactory(`,\n // The import happens HERE, inside the factory, and `createSubjectResolverFromFactory`\n // calls the factory inside the thunk it returns (`resolve-agent-subject.ts:127-133`).\n // A first version of this fix awaited the import as an ARGUMENT, which evaluated it\n // eagerly inside `__theoResolveSubject` — both call sites await that before\n // `agent-access.ts:145` returns early for an absent or `'public'` policy. The blast\n // radius was then every agent request rather than the one that wanted an identity,\n // and the laziness invariant the lines above assert was broken. Found by the\n // inventory judge while the change was still in the working tree.\n ` async (__theoArgs) => (await __theoContext()).createContext(__theoArgs),`,\n ` __theoReq,`,\n ` __theoRes,`,\n ` ${pluginRunnerExpr ?? 'undefined'},`,\n ` )`,\n ],\n auxPrelude: [\n ` // B-185 — the aux dispatcher needs nodes carrying \\`filePath\\` and a loader keyed by it.`,\n ` // The loader resolves the path to a NAME through the node list, then reads the same`,\n ` // name-keyed table the url lookup uses: one map, one layout mention, no filesystem`,\n ` // (ADR-2). A linear find over a handful of agents is not worth a second table that`,\n ` // \\`test_the_table_is_keyed_by_agent_name_not_by_file_path\\` exists to forbid.`,\n ` const auxDeps = {`,\n ` agents: agentNodes,`,\n ` loadModule: async (filePath) => {`,\n ` const node = agentNodes.find((a) => a.filePath === filePath)`,\n ` return node === undefined ? undefined : agents[node.name]`,\n ` },`,\n ` baseUrl: url.origin,`,\n ...AUX_DEPS_PARITY,\n ` }`,\n ],\n }\n}\n\n/** A filesystem: scan once and load on demand, exactly as this entry already treats its routes. */\nfunction scannedResolution(source: {\n projectRoot: string\n loadModule: string\n ensureLoader?: string\n agentsDirLiteral?: string\n serverDir?: string\n pluginRunnerExpr?: string\n}): AgentResolution {\n // The configured directory as a second argument, or nothing. `scanAgents` defaults the name to\n // `agents`, which is right for a project that never set one and wrong for every project that did.\n const agentsDirArg = source.agentsDirLiteral === undefined ? '' : `, ${source.agentsDirLiteral}`\n\n return {\n imports: [],\n declarations: [\n `// #367 — scanned on first use and cached, the same shape this entry already gives routes.`,\n `// Baking would tie an agent's existence to a rebuild on a target that has a filesystem.`,\n `let agentsCache = null`,\n ],\n lookup: [\n ` const agentNode = agentsCache.find((a) => a.name === agentName)`,\n ` const mod = agentNode === undefined ? undefined : await ${source.loadModule}(agentNode.filePath)`,\n ],\n identityImport: source.serverDir === undefined ? '' : ', createAgentSubjectResolver',\n identity:\n source.serverDir === undefined\n ? [` const resolveSubject = undefined`]\n : [\n ` // B-185 — this host HAS a filesystem, so it locates its own \\`context.ts\\` and the`,\n ` // existing resolver works unchanged; nothing is baked (ADR 0014). Lazy for the reason`,\n ` // the baked branch gives: both callers build a shim, and neither runs the app's own`,\n ` // \\`createContext\\` for a url nobody answers.`,\n ` const { req: __theoReq, res: __theoRes } = createWebShim(request)`,\n ` const resolveSubject = createAgentSubjectResolver({`,\n ` req: __theoReq,`,\n ` res: __theoRes,`,\n ` loadModule: ${source.loadModule},`,\n ` serverDir: ${source.serverDir},`,\n ` pluginRunner: ${source.pluginRunnerExpr ?? 'undefined'},`,\n ` })`,\n ],\n auxPrelude: [\n ...(source.ensureLoader === undefined ? [] : [` ${source.ensureLoader}`]),\n ` // B-185 — hoisted above the lookup so a declined aux route loads no module. The scan`,\n ` // LISTS agent files; it imports none, so moving it here costs a declined request`,\n ` // nothing it was not already paying.`,\n ` if (!agentsCache) agentsCache = scanAgents(${source.projectRoot}${agentsDirArg})`,\n ` const auxDeps = {`,\n ` agents: agentsCache,`,\n ` loadModule: ${source.loadModule},`,\n ` baseUrl: url.origin,`,\n ...AUX_DEPS_PARITY,\n ` }`,\n ],\n }\n}\n","/**\n * The CORS configuration a deployed entry carries, baked at build time.\n *\n * ## The defect this closes\n *\n * `security.cors` reached exactly one consumer: Vite's `configureServer` hook. So an app that\n * worked cross-origin under `theokit dev` stopped working the moment anything else served it —\n * `theokit start` (fixed separately) and all six Web deploy targets (usetheokit/theokit#409). Same\n * config, same code, no error and no warning; the failure surfaces in a browser as a blocked fetch\n * on the deployed URL, three layers from the key that had quietly stopped being read.\n *\n * The pure half was written twice and called once: `createCorsWebHandler` — the Web mirror — had no\n * caller anywhere in the repository. Nothing here reimplements it.\n *\n * ## A callback origin is REFUSED, not silently dropped\n *\n * `corsSchema.origins` accepts `z.function(...)` alongside the string / RegExp / array shapes. A\n * deployed function has no `theo.config.ts` to read, and there is no literal for a closure — so a\n * build that baked only the serialisable shapes would produce an app whose CORS silently allowed\n * nothing, which is the exact class of failure this issue reports.\n *\n * `rules/three-target-parity.md` § 3 is explicit about the alternative: \"a target that cannot serve\n * a capability refuses by name. Silent degradation is the failure mode this rule exists to\n * prevent.\" So the build throws, naming the target, the key and the two ways forward.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype CorsConfig = NonNullable<NonNullable<TheoConfig['security']>['cors']>\n\n/**\n * The CORS slice of an adapter's build options.\n *\n * Narrow and named once, matching how `securityHeaders` and `DeployedCsrfOptions` already reach the\n * emitters: each renderer receives what it uses, and six signatures name one type instead of six\n * inline shapes that can drift.\n */\nexport interface DeployedCorsOptions {\n cors?: CorsConfig\n}\n\n/**\n * Thrown at BUILD time when the declared CORS cannot be carried to a deployed target.\n *\n * A build error is the point: the alternative is a deploy that looks configured and refuses every\n * cross-origin request, discovered by a browser rather than by the build.\n */\nexport class UnserializableCorsOriginError extends Error {\n constructor(target: string) {\n super(\n `security.cors.origins is a function, and the \\`${target}\\` target cannot carry it: a deployed ` +\n `function has no theo.config.ts to read, and a callback cannot be written into the emitted ` +\n `entry. Replace it with the origin, a RegExp, or an array of either — all of which travel — ` +\n `or build for \\`node\\` and run \\`theokit start\\`, which evaluates the callback at runtime.`,\n )\n this.name = 'UnserializableCorsOriginError'\n }\n}\n\n/** Source text for one origin matcher: a RegExp as a literal, anything else as JSON. */\nfunction renderOrigin(origin: unknown, target: string): string {\n if (typeof origin === 'function') throw new UnserializableCorsOriginError(target)\n if (origin instanceof RegExp) return String(origin)\n if (Array.isArray(origin)) return `[${origin.map((o) => renderOrigin(o, target)).join(', ')}]`\n return JSON.stringify(origin)\n}\n\n/**\n * Source text for the CORS config, or `undefined` when the app declared none.\n *\n * RegExp entries are emitted as regex literals for the reason `deployed-csrf.ts` gives at length:\n * `JSON.stringify` renders a RegExp as `{}`, and `matchesOrigin` checks `instanceof RegExp`, so a\n * JSON-rendered origin would sit in the emitted file looking configured and matching nothing.\n *\n * @throws UnserializableCorsOriginError when `origins` is a callback\n */\nexport function renderDeployedCorsLiteral(cors: CorsConfig | undefined, target: string): string {\n if (cors === undefined) return 'undefined'\n\n const parts = [`origins: ${renderOrigin(cors.origins, target)}`]\n if (cors.methods !== undefined) parts.push(`methods: ${JSON.stringify(cors.methods)}`)\n if (cors.allowedHeaders !== undefined)\n parts.push(`allowedHeaders: ${JSON.stringify(cors.allowedHeaders)}`)\n if (cors.exposedHeaders !== undefined)\n parts.push(`exposedHeaders: ${JSON.stringify(cors.exposedHeaders)}`)\n // Both carry schema defaults, so they are always present and always emitted — unlike the\n // optional fields above, whose absence is a real answer the handler already has one for.\n parts.push(\n `credentials: ${JSON.stringify(cors.credentials)}`,\n `maxAge: ${JSON.stringify(cors.maxAge)}`,\n )\n\n return `{ ${parts.join(', ')} }`\n}\n\n/**\n * The lines that declare the CORS handler in a generated entry.\n *\n * `null` when nothing was declared, which is what \"no cors block\" meant before and still means: no\n * headers, not permissive ones.\n */\nexport function deployedCorsFragment(cors: CorsConfig | undefined, target: string): string[] {\n return [\n `// #409 — the CORS the app declared, carried as a literal because a deployed function has no`,\n `// theo.config.ts to read. \\`null\\` when the app declared none: no headers, not permissive ones.`,\n `const CORS_CONFIG = ${renderDeployedCorsLiteral(cors, target)}`,\n `const CORS_HANDLER = CORS_CONFIG === undefined ? null : createCorsWebHandler(CORS_CONFIG)`,\n ``,\n `/** Answer a preflight before routing — an OPTIONS the router handles never gets a CORS answer. */`,\n `function corsPreflight(request) {`,\n ` return CORS_HANDLER === null ? null : CORS_HANDLER.handlePreflightRequest(request)`,\n `}`,\n ``,\n `/** Put the headers on whatever the app answered, including its 404s — a browser reads a 404`,\n ` * without them as a CORS failure rather than as the 404 it is. */`,\n `function withCors(request, response) {`,\n ` if (CORS_HANDLER !== null) CORS_HANDLER.applyCorsHeaders(request, response.headers)`,\n ` return response`,\n `}`,\n ]\n}\n","/**\n * The CSRF configuration a deployed entry carries, baked at build time.\n *\n * ## The defect this closes\n *\n * The six Web-standards adapter entries built `executeRoute`'s context from an eight-field\n * literal, and neither `csrfMode` nor `disallowed` was among the eight (usetheokit/theokit#410).\n * `executeRoute` defaults an absent mode to `'strict'`, so an app declaring\n * `security: { csrf: 'off' }` — or `'warn'` — got `'strict'` on every deploy target: a `POST` that\n * works under `theokit dev` and `theokit start` answers `403 CSRF_INVALID` on Vercel, naming a\n * mechanism the operator had switched off. The config still validated and the build still\n * succeeded; the behaviour simply changed.\n *\n * The deployed function has no `theo.config.ts` to read, which is why the value is carried as a\n * literal — the same shape `security.headers` already uses (`renderSecurityHeadersConfigLiteral`).\n *\n * ## Why this is not `JSON.stringify`\n *\n * `disallowed.routes` accepts RegExp entries (`config/schemas/security.ts`), and `JSON.stringify`\n * renders a RegExp as `{}`. That is not a formatting problem: `matchDisallowed` checks\n * `p instanceof RegExp`, so a `{}` matches nothing while reading, in the emitted file, as a rule\n * that is present and configured. Reaching for JSON here would reproduce this issue's own defect —\n * configuration that survives validation and quietly stops applying — one layer further down.\n */\nimport type { TheoConfig } from '../config/schema.js'\n\ntype SecurityConfig = NonNullable<TheoConfig['security']>\n\n/**\n * The two slices of `security` that reach `executeRoute`'s context.\n *\n * Narrow rather than the whole block, matching how `securityHeaders` is already passed: each\n * renderer receives what it uses and nothing else, so a headers change cannot reach the CSRF\n * literal and vice versa.\n */\nexport interface DeployedCsrfOptions {\n csrf?: SecurityConfig['csrf']\n disallowed?: SecurityConfig['disallowed']\n}\n\n/**\n * Source text for one route pattern.\n *\n * A RegExp is emitted as a regex literal so it arrives as a RegExp; a string goes through\n * `JSON.stringify`, which is the correct escaper for a JS string literal (quotes, backslashes,\n * control characters, line separators).\n */\nfunction renderRoutePattern(pattern: string | RegExp): string {\n return pattern instanceof RegExp ? String(pattern) : JSON.stringify(pattern)\n}\n\n/**\n * Source text for the CSRF slice of `executeRoute`'s context.\n *\n * Absent values are OMITTED rather than defaulted. `executeRoute` already defaults an absent\n * `csrfMode` to `'strict'`, and writing `'strict'` here would put that default in a second place\n * where the two can disagree — which is the class of drift the whole issue is about.\n *\n * @param security - the declared csrf slices, or `undefined` when the app declared no security block\n */\nexport function renderDeployedCsrfLiteral(security: DeployedCsrfOptions | undefined): string {\n if (security === undefined) return '{}'\n\n const parts: string[] = []\n if (security.csrf !== undefined) parts.push(`csrfMode: ${JSON.stringify(security.csrf)}`)\n\n const { disallowed } = security\n if (disallowed !== undefined) {\n const routes = disallowed.routes.map(renderRoutePattern).join(', ')\n parts.push(\n `disallowed: { routes: [${routes}], behavior: ${JSON.stringify(disallowed.behavior)} }`,\n )\n }\n\n // `{}` and not `{ }` when nothing was declared: the emitted file is read by people, and the\n // two-space version reads as though something was meant to be there.\n return parts.length === 0 ? '{}' : `{ ${parts.join(', ')} }`\n}\n\n/**\n * The lines that declare `CSRF_CONFIG` in a generated entry.\n *\n * One function rather than the same six lines pasted into each of the six adapters: that\n * duplication is how the eight-field context literal came to be wrong in six places at once, and\n * repeating the fix in the same shape would leave the next field with the same six places to be\n * forgotten in. It also keeps the two largest emitters under the `max-lines-per-function` ceiling,\n * which `vercel.ts` already extracts fragments to respect.\n *\n * @param opts - the declared csrf slices, passed straight through from the adapter's build options\n * @param home - what the target has instead of a config file, for the comment's second sentence\n */\nexport function deployedCsrfFragment(\n opts: DeployedCsrfOptions,\n home = 'a deployed function',\n): string[] {\n return [\n `// #410 — the CSRF mode and per-route escalation the app declared. Carried as a`,\n `// literal for the same reason as the headers above: ${home} has no theo.config.ts`,\n `// to read. Absent keys stay absent so executeRoute's own default ('strict') applies,`,\n `// rather than this file becoming a second place it can drift.`,\n `const CSRF_CONFIG = ${renderDeployedCsrfLiteral(opts)}`,\n ]\n}\n","/**\n * The security headers a deployed target puts on its responses.\n *\n * `theokit start` applies the configured baseline to every response it writes\n * (`cli/commands/start/request-handler.ts`). None of the six Web-standards\n * deploy adapters applied any, so the same page carried a CSP,\n * `X-Frame-Options`, HSTS and `nosniff` under `theokit start` and none of them\n * once deployed (usetheokit/theokit#410, GHSA-87qq-fgcr-384x).\n *\n * This module is the seam that closes that half of the gap. It has two halves\n * and they live together on purpose: the code that writes the literal into a\n * generated entry and the code that reads it at request time have to agree on\n * one shape, and a shape stated in two files drifts.\n *\n * - **Build time** — {@link renderSecurityHeadersConfigLiteral} turns\n * `security.headers` into a JSON literal the adapter inlines. A deployed\n * runtime has no `theo.config.ts` to read, so the configuration travels as\n * data.\n * - **Request time** — the generated entry calls {@link buildSecurityHeaders}\n * on that literal and hands every response to {@link withSecurityHeaders}.\n * The same function `theokit start` calls, on the same input, so the two\n * cannot disagree about what the configuration means.\n *\n * ## The per-request nonce, and where it stops\n *\n * `buildSecurityHeaders` accepts a per-request `nonce` and substitutes it into\n * `script-src`. A nonce cannot survive a build-time literal — it is minted per\n * response — so a target reaches one only if it renders the HTML at request\n * time and can put the same value on the script tags it emits.\n *\n * Exactly one deploy path does: **Cloudflare with `ssrStreaming: true`**, whose\n * worker calls `renderStreamingWeb(request, { nonce })`, and that renderer\n * threads the value into `renderToReadableStream` and into the hydration script\n * (`router/entry-server.ts`). That branch mints a nonce per request and builds\n * its CSP from it. Everything else serves HTML written at build time, or no\n * HTML at all, and carries a **nonce-less CSP** — the same answer\n * `buildSecurityHeaders` already gives a prerendered route (EC-4), for the same\n * reason: a nonce in the header with no nonce on the tag blocks every inline\n * script.\n *\n * That asymmetry is real and is not smoothed over. It is stated in the emitted\n * entry, printed by the build through\n * {@link describeDeployedSecurityHeaders}, and written down in\n * `docs/surfaces/build-adapters.md`.\n */\nimport { generateNonce } from '../core/contracts/nonce.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { buildSecurityHeaders } from '../core/contracts/security-headers.js'\n\n/**\n * Re-exported so a generated entry has ONE import for the whole concern.\n *\n * Reaching it through `theokit/server/security` would work and would also drag\n * that barrel's CSRF surface into a Worker bundle, for a function that is forty\n * lines of string concatenation. It is defined in `core/contracts/`, which is\n * the module every target may import from — `adapters → server` is not an edge\n * in the DAG, and the header policy was never server code.\n */\nexport { buildSecurityHeaders }\n\n/**\n * Re-exported for the same reason, and so the streamed Cloudflare worker mints\n * its nonce with the identical primitive `theokit start` uses\n * (`cli/commands/start/request-handler.ts`) rather than a second, hand-rolled\n * one. It is already runtime-portable: Web Crypto first, with a named error\n * when the runtime has none.\n */\nexport { generateNonce }\n\n/**\n * The `security.headers` block, as a literal a generated entry can carry.\n *\n * `{}` when the app declares none — which is not the same as \"no headers\".\n * `buildSecurityHeaders({})` returns the full default baseline, and `{}` is\n * exactly what `theokit start` passes when `security.headers` is absent\n * (`cli/commands/start/index.ts`). An app with no security block gets the same\n * baseline deployed as it gets locally.\n */\n/**\n * The two declarations every deploy entry emits to carry the security baseline.\n *\n * Four adapters wrote these same two lines — `netlify`, `vercel`, `aws-lambda`, `deno-deploy` —\n * each under a comment naming its own host's static-asset boundary. The COMMENT differs and is\n * meant to; the declarations do not.\n *\n * Extracted after SonarCloud's duplication gate failed a PR at 4.0% against a 3% ceiling and named\n * this as the largest repeated block among the changed files. The gate was measuring something\n * real: a literal renderer and a builder call, copied four times, is four places to update when\n * either changes.\n *\n * Returns the lines rather than a joined string, because every caller splices them into an array\n * of emitted lines.\n */\nexport function securityHeadersDeclarations(config: SecurityHeadersConfig | undefined): string[] {\n return [\n `const SECURITY_HEADERS_CONFIG = ${renderSecurityHeadersConfigLiteral(config)}`,\n `const SECURITY_HEADERS = buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true })`,\n ]\n}\n\nexport function renderSecurityHeadersConfigLiteral(\n headers: SecurityHeadersConfig | undefined,\n): string {\n return JSON.stringify(headers ?? {})\n}\n\n/**\n * Put the headers on a response, without overruling the handler.\n *\n * `theokit start` sets the baseline BEFORE the route handler runs, so a handler\n * can override it with `res.setHeader` (last write wins, Node convention). On a\n * Web target the response arrives already built, so the equivalent of \"the\n * handler wins\" is to skip a header the response already carries: a route that\n * set its own `Content-Security-Policy` keeps it.\n *\n * Mutates and returns the same `Response` rather than constructing a\n * replacement, because these responses are handed to the runtime while their\n * body is still being written (#382) and re-wrapping the stream is exactly the\n * second buffering point that change removed.\n *\n * Mutation is safe for every response these entries produce: the Fetch spec\n * gives a locally constructed `Response` the `response` header guard, which\n * permits `set` for every name used here. The `immutable` guard belongs to\n * responses that came back from `fetch()`, and none of the six emitted handlers\n * returns one — each builds its response from `createWebShim`, from a `new\n * Response(...)`, or from the SSR renderer. The WebSocket upgrade, which is the\n * one response an adapter gets from its runtime rather than building, is\n * deliberately not routed through here.\n */\nexport function withSecurityHeaders(response: Response, headers: Record<string, string>): Response {\n for (const [key, value] of Object.entries(headers)) {\n if (!response.headers.has(key)) response.headers.set(key, value)\n }\n return response\n}\n\nexport interface DeployedSecurityHeaderLimits {\n target: string\n /** The app's `security.headers` block, or undefined when it declares none. */\n securityHeaders: SecurityHeadersConfig | undefined\n /**\n * Does the emitted handler render HTML at request time and mint a CSP nonce\n * for it? True only for Cloudflare with `ssrStreaming: true`.\n */\n mintsNonce: boolean\n /**\n * Is the HTML document served by a platform static host rather than by the\n * handler this build emits? True wherever the emitted handler answers\n * `/api/*` and returns 404 for everything else.\n */\n /**\n * Who puts the security headers on the HTML DOCUMENT — a different question from who serves it,\n * and the two used to be collapsed into one boolean (usetheokit/theokit#412).\n *\n * - `handler` — this target's own handler returns the document, so it carries the same baseline\n * every API response carries. No caveat.\n * - `platform-configured` — the platform's static host serves the document, AND this build emits\n * the configuration that puts the headers on it (`.vercel/output/config.json`, `netlify.toml`).\n * Still worth stating, because nothing here has seen a deployed response.\n * - `platform-unmanaged` — the platform serves it and this build owns no artifact that could\n * configure it. This is the real remaining gap, and it stays named.\n *\n * The two-value version reported `platform-configured` targets with the same message as\n * `platform-unmanaged` ones, telling an operator to go and do work the build had already done —\n * and a stale limitation reads exactly like a current one.\n */\n documentHeaders: 'handler' | 'platform-configured' | 'platform-unmanaged'\n}\n\n/**\n * What the build tells the operator, once, per target.\n *\n * Silent degradation is the failure mode `rules/three-target-parity.md` exists\n * to prevent. Two things degrade quietly here and both are named rather than\n * discovered in production: a CSP that refuses inline scripts on a deploy while\n * allowing them locally, and an HTML document that never passes through the\n * handler these headers are attached to.\n *\n * The header names are read from the map the entry will actually carry, not\n * from a list written next to it. A configuration that switches HSTS or the CSP\n * off would otherwise be announced as sending them.\n */\nexport function describeDeployedSecurityHeaders(limits: DeployedSecurityHeaderLimits): string {\n const headers = buildSecurityHeaders(limits.securityHeaders ?? {}, { production: true })\n const names = Object.keys(headers)\n if (names.length === 0) {\n return ` ! \\`${limits.target}\\` sends no security headers: the configuration switched every one of them off.`\n }\n\n const lines = [\n ` ✓ security headers on every response \\`${limits.target}\\` returns: ${names.join(', ')}.`,\n ]\n const sendsCsp = names.some((name) => name.startsWith('Content-Security-Policy'))\n if (sendsCsp && !limits.mintsNonce) {\n lines.push(\n ` - The CSP carries no nonce: this target serves HTML written at build time,`,\n ` so there is no per-request value to put on a script tag. An inline`,\n ` <script> is refused by \\`script-src 'self'\\` here, while the same page`,\n ` under \\`theokit start\\` gets a nonce and runs it. Move inline scripts to`,\n ` \\`<script src=\"...\">\\`, or set \\`security.headers.cspMode: 'report-only'\\``,\n ` while you migrate.`,\n )\n }\n if (limits.documentHeaders === 'platform-configured') {\n lines.push(\n ` - The HTML document is served by the platform's static host, and reaches`,\n ` the browser with these headers through config this build emits. That`,\n ` path is not verified by a deploy from here — the values come from the`,\n ` same function the handler uses, but no response has been read back.`,\n )\n }\n if (limits.documentHeaders === 'platform-unmanaged') {\n lines.push(\n ` - The HTML document does NOT pass through this handler — the platform's`,\n ` static host serves it — so these headers reach \\`/api/*\\` responses and`,\n ` not the page. This build emits no artifact that could configure it, so`,\n ` set the document's headers on the platform (usetheokit/theokit#412).`,\n )\n }\n return lines.join('\\n')\n}\n","/**\n * The configuration a deployed entry could not apply (usetheokit/theokit#425).\n *\n * ## Why this is not another literal renderer\n *\n * `deployed-csrf.ts` and `deployed-cors.ts` bake their values into the emitted source, which works\n * because `csrf` is an enum and `disallowed` is a `{ routes, behavior }` object — plain data, and a\n * deployed function has no `theo.config.ts` to read.\n *\n * The two concerns left over from #410 turn out to be different from each other, and the difference\n * is the whole design:\n *\n * - **`serialization` is plain data too.** The config field is `z.enum(['json', 'superjson'])`\n * (`config/schema.ts:147`) — a selector, not a transformer. `resolveTransformer` turns it into the\n * functions, and it already ships from `theokit/server`. So this half is a literal like the rest,\n * and the deployed entry resolves it exactly the way `theokit start` does\n * (`cli/commands/start/index.ts:108`), from the same string, through the same function.\n * - **`plugins` genuinely carries functions.** A plugin is constructed in `theo.config.ts` and there\n * is no literal for a closure, so this half needs the entry to import a module instead.\n *\n * ## Static import, not `import()` in the request path\n *\n * The tempting shortcut is `await import('../../theo.config.js')` inside the handler. It trades a\n * silent failure for a louder one on targets with no filesystem, and it moves configuration\n * resolution into every request on the targets that do have one.\n *\n * What this emits instead is a TOP-LEVEL import of a module the build already resolved and wrote\n * beside the entry — the same shape `renderBakedRoutes` uses for route modules (#369): decide on\n * the build machine, emit a static specifier. It is evaluated once at module load, the target's\n * bundler can see through it, and a plugin that needs an API the target lacks fails the build\n * rather than the first request.\n *\n * ## Why each half is optional\n *\n * An app that declares neither concern must produce the entry it produced before this existed.\n * Importing a module the build did not emit fails at load, and spreading an empty object costs an\n * allocation per request for nothing. So an empty request renders to nothing at all, and the\n * caller's `executeRoute` literal is unchanged.\n *\n * The halves are independent on purpose: an app that only picks `superjson` must not be made to\n * carry a plugins module, and an app with plugins and default JSON must not gain a transformer\n * lookup. Coupling them would have made the common case pay for the rare one.\n */\n\n/**\n * The option every Web-standards adapter grows to carry non-serialisable configuration.\n *\n * Composed into each adapter's option type the way `DeployedCsrfOptions` already is, so the six\n * targets cannot drift into six spellings of the same field.\n */\n/**\n * The project's `serverDir`, carried into every generated entrypoint (#RFC server-layout).\n *\n * Separate from the other option groups because it is not a runtime feature toggle: it is the\n * project's own layout, and an adapter that hardcodes `'server'` agrees with the default by\n * COINCIDENCE. The moment a project sets the option — the entire point of it existing — the\n * generated entrypoint resolves a directory that is not there, and only after deploy: the build\n * succeeds, the bundle is written, and routes 404 in production with nothing naming the cause.\n */\nexport interface DeployedServerDirOptions {\n /** Project-relative server directory. Absent ⇒ the schema default, `server`. */\n serverDir?: string\n}\n\n/**\n * The server directory as a quoted TypeScript literal, ready to interpolate into generated source.\n *\n * `JSON.stringify` rather than wrapping in quotes by hand: the value reaches this from user config,\n * so a directory containing a quote or a backslash would otherwise emit a syntax error into\n * somebody else's build — a worse failure than the one this fixes.\n */\nexport function serverDirLiteral(opts: DeployedServerDirOptions): string {\n return JSON.stringify(opts.serverDir ?? 'server')\n}\n\n/**\n * The agents directory, same shape and same reason as `serverDir` above.\n *\n * `scanAgents(projectRoot, agentsDirName = 'agents')` takes the name as its SECOND parameter\n * (`server/scan/agent-scan.ts:56`). Nine call sites pass the configured value; the generated\n * deploy entry was the only one that did not, so the default won and a project whose agents live\n * under the documented `core/agents` (`config/schema.ts:66`) served none of them — 404 per agent,\n * after deploy, with nothing naming the cause. Measured 2026-09-21 by executing `buildBun`\n * against a config carrying both directories and reading what it emitted.\n */\nexport interface DeployedAgentsDirOptions {\n /** Project-relative agents directory. Absent ⇒ the schema default, `agents`. */\n agentsDir?: string\n}\n\nexport function agentsDirLiteral(opts: DeployedAgentsDirOptions): string {\n return JSON.stringify(opts.agentsDir ?? 'agents')\n}\n\nexport interface DeployedRuntimeConfigOptions {\n /**\n * Specifier of the plugins module the build wrote beside the entry, or `undefined` when the app\n * declares no plugins and the build wrote none.\n */\n runtimeConfigModule?: string\n /**\n * The app's `serialization` selector, carried as a literal.\n *\n * `'json'` and `undefined` both mean the default, and neither emits anything: `executeRoute`\n * already falls back to `JSON.stringify`, and the `x-theo-transformer` header is deliberately\n * absent for the default so a client is told only when there is something to be told.\n */\n serialization?: 'json' | 'superjson'\n}\n\n/** The three places an entry has to grow to carry non-serialisable configuration. */\nexport interface DeployedRuntimeConfigFragment {\n /** Top-level imports. Empty when the build emitted no config module. */\n readonly imports: string[]\n /** Module-scope declarations — evaluated once, at load. Empty when there is nothing to carry. */\n readonly declarations: string[]\n /**\n * Spread into the entry's `executeRoute({ … })` literal, inside an async function.\n *\n * Empty string when there is nothing to carry, so the call site keeps the exact shape it had.\n */\n readonly executeRouteSpread: string\n}\n\nconst EMPTY: DeployedRuntimeConfigFragment = {\n imports: [],\n declarations: [],\n executeRouteSpread: '',\n}\n\n/**\n * What a deployed entry needs in order to apply `config.plugins` and `config.serialization`.\n *\n * @param moduleSpecifier - specifier of the runtime-config module the build emitted beside the\n * entry, or `undefined` when the app declared neither concern and the build emitted none.\n */\nexport function deployedRuntimeConfigFragment(\n options: DeployedRuntimeConfigOptions | undefined,\n): DeployedRuntimeConfigFragment {\n const pluginsModule = options?.runtimeConfigModule\n // 'json' is the default and emits nothing — see `serialization` above.\n const serialization = options?.serialization === 'superjson' ? 'superjson' : undefined\n if (pluginsModule === undefined && serialization === undefined) return EMPTY\n\n const imports: string[] = []\n const declarations: string[] = []\n const spread: string[] = []\n\n if (pluginsModule !== undefined) {\n imports.push(\n `import { createPluginRunnerFromConfig } from 'theokit/server'`,\n `// #425 — the app's own plugins, resolved on the build machine and written beside this entry.`,\n `// A closure has no literal, so this is an import rather than a baked value.`,\n `import theoRuntimeConfig from '${pluginsModule}'`,\n )\n declarations.push(\n `// Built ONCE, at module load. A runner rebuilt per request would re-run every plugin's`,\n `// \\`register\\`, which is where a plugin allocates the state its hooks then read.`,\n `const THEO_PLUGIN_RUNNER = createPluginRunnerFromConfig(theoRuntimeConfig.plugins)`,\n )\n // Awaited, not passed along: `createPluginRunnerFromConfig` is async because `register` is, and\n // a pending promise handed to `executeRoute` is a truthy object with none of the runner's\n // methods — every hook would silently not fire, which is this issue's own defect one layer in.\n spread.push(`pluginRunner: await THEO_PLUGIN_RUNNER`)\n }\n\n if (serialization !== undefined) {\n imports.push(`import { resolveTransformer } from 'theokit/server'`)\n declarations.push(\n `// #425 — a literal, because \\`config.serialization\\` is a SELECTOR and not a transformer.`,\n `// Same string, same function \\`theokit start\\` calls, so the deployed response and the local`,\n `// one cannot disagree about what the app asked for — including the \\`x-theo-transformer\\``,\n `// header, whose absence is what made this a data bug rather than a formatting one.`,\n `const THEO_TRANSFORMER = resolveTransformer('${serialization}')`,\n )\n spread.push(`transformer: THEO_TRANSFORMER`)\n }\n\n return { imports, declarations, executeRouteSpread: `${spread.join(', ')},` }\n}\n","/**\n * The request id a deployed entry uses, and the header it echoes back.\n *\n * ## The defect this closes\n *\n * Every generated entry minted a fresh `randomUUID()` per request and set no correlation header\n * at all on a success path (usetheokit/theokit#410). Both Node paths do the opposite: they resolve\n * an incoming `traceparent` / `x-request-id` through `extractTraceId` and echo the result under\n * both `x-request-id` and `x-trace-id` (`cli/commands/start/request-handler.ts`,\n * `vite-plugin/api-middleware.ts`).\n *\n * The consequence is that a trace crossing into a deployed function starts over. The caller's id\n * is discarded, and the response carries nothing to correlate against — so a request that fails in\n * production cannot be tied to the client that made it, which is the one situation the id exists\n * for.\n *\n * ## Why `setHeader` before the handler, rather than wrapping the response\n *\n * It is what the Node path does, and the shim reproduces Node's semantics exactly: `writeHead`\n * MERGES into the header map rather than replacing it (`web-shim.ts`), so a header set here\n * survives the handler's own `writeHead` and a handler that sets its own id still wins. Wrapping\n * the finished `Response` instead would have to mutate a response whose body is already streaming\n * (#382), and would miss the branches that return before the shim is built.\n */\n\n/**\n * Lines that resolve the request id and echo it, as generated source.\n *\n * @param requestVar - the name the entry gave the Web `Request` in scope\n * @param indent - leading whitespace, so the emitted file stays readable\n */\nexport function deployedTraceFragment(requestVar: string, indent: string): string[] {\n return [\n `${indent}// #410 — honour the caller's trace id instead of minting a new one, and echo it.`,\n `${indent}// \\`extractTraceIdFromRequest\\` validates the caller-controlled \\`x-request-id\\``,\n `${indent}// before trusting it, and falls back to a fresh UUID when neither header is present.`,\n `${indent}const requestId = extractTraceId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AAAA,IAClE,GAAG,MAAM;AAAA,IACT,GAAG,MAAM;AAAA,EACX;AACF;","names":["agentsDirLiteral","EMPTY"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/cloudflare.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Cloudflare deploy adapter. All write paths are under `cwd/.theokit/cloudflare/`\n * and `cwd/wrangler.toml`. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { findRootDiv } from '../core/contracts/find-root-div.js'\nimport { parseAssetsMap } from '../core/contracts/module-preloads.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, type DeployedAgent } from './deployed-agents.js'\nimport { deployedCorsFragment, type DeployedCorsOptions } from './deployed-cors.js'\nimport { deployedCsrfFragment, type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport {\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n type DeployedRuntimeConfigOptions,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders, securityHeadersDeclarations } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\n/**\n * T2.1 — Cloudflare adapter rewritten to consume `theokit/adapters/web-shim`\n * instead of emitting an inline plain-object Request/Response shim. Reduces\n * template from ~50 lines to ~25 and centralizes maintenance.\n */\n\n/**\n * The built `index.html` split into the part before `<div id=\"root\">` and the\n * part after it.\n *\n * Refuses by name when streaming is on and the template is missing, rather than\n * emitting a worker that serves a headless document. A build that cannot produce\n * a correct artifact should say so at build time; the alternative is a deploy\n * that looks successful and serves pages with no stylesheet.\n */\n/**\n * @internal Exported for tests only. Nothing re-exports this module, so this does not reach the\n * published surface — `findRootDiv`, exported for the same reason, appears 0 times in `dist/`.\n */\nexport function readDocumentShell(\n cwd: string,\n streaming: boolean,\n): { htmlHead?: string; htmlTail?: string } {\n if (!streaming) return {}\n\n const indexPath = resolve(cwd, '.theokit/client/index.html')\n if (!existsSync(indexPath)) {\n throw new Error(\n `[adapter-cloudflare] ssrStreaming is on but ${indexPath} does not exist, so the worker ` +\n `would serve a document with no <head> and no client entry. Run the client build first, ` +\n `or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n const indexHtml = readFileSync(indexPath, 'utf-8')\n const rootDiv = findRootDiv(indexHtml)\n if (rootDiv === undefined) {\n throw new Error(\n `[adapter-cloudflare] ${indexPath} has no <div id=\"root\">, so the streamed document has ` +\n `nowhere to put the app. Add one, or set ssrStreaming: false in theo.config.ts.`,\n )\n }\n\n return {\n htmlHead: indexHtml.slice(0, rootDiv.insertAt),\n htmlTail: indexHtml.slice(rootDiv.insertAt),\n }\n}\n\n/**\n * The routes, turned into source: static imports, a module map and a literal table (#369).\n *\n * Extracted so the worker renderer stays inside its length budget, and because this is the whole of\n * what changed about how a Worker finds a route — it reads as one idea rather than as three loops\n * inside a hundred lines of template.\n *\n * `../../` because the worker is written to `.theokit/cloudflare/worker.mjs` and `filePath` is\n * relative to the project root. The imports are static so Wrangler's bundler follows them:\n * `wrangler.toml` uploads `.theokit/client` and has never uploaded `server/`, so a module not\n * bundled INTO the worker is not on the platform at all.\n */\nfunction renderBakedRoutes(\n routes: readonly { filePath: string; routePath: string; methods?: readonly string[] }[],\n): { routeImports: string[]; routeModuleEntries: string[]; routeTableEntries: string[] } {\n const routeVar = (index: number): string => `__theoRoute${String(index)}`\n return {\n routeImports: routes.map(\n (route, index) => `import * as ${routeVar(index)} from '../../${route.filePath}'`,\n ),\n routeModuleEntries: routes.map(\n (route, index) => ` ${JSON.stringify(route.filePath)}: ${routeVar(index)},`,\n ),\n routeTableEntries: routes.map(\n (route) =>\n ` { filePath: ${JSON.stringify(route.filePath)}, routePath: ${JSON.stringify(route.routePath)}, ` +\n `methods: ${JSON.stringify([...(route.methods ?? [])])}, ` +\n `...compilePattern(${JSON.stringify(route.routePath)}) },`,\n ),\n }\n}\n\n/**\n * The route-resolution runtime the Worker gets instead of a directory scan (#369).\n *\n * A module map, the literal table, and a loader that refuses anything the build did not bake.\n * Emitted as its own block because it replaces one idea — \"find the routes\" — wholesale.\n */\nfunction routeRuntimeLines(moduleEntries: string[], tableEntries: string[]): string[] {\n return [\n `// #369 — the routes are baked at build time. The Worker used to reach for`,\n `// \\`scanServerRoutes\\` on the server directory — a readdirSync, in a runtime with no`,\n `// filesystem. The pattern is recompiled here from the same routePath the scanner`,\n `// used, so one function decides precedence on every target.`,\n `const ROUTE_MODULES = {`,\n ...moduleEntries,\n `}`,\n ``,\n `const routes = [`,\n ...tableEntries,\n `]`,\n ``,\n `// The executor asks for a module by the path the table names. Anything else was`,\n `// never bundled, and saying so beats returning undefined and failing later on a`,\n `// property access far from the cause.`,\n `async function loadModule(path) {`,\n ` const mod = ROUTE_MODULES[path]`,\n ` if (mod === undefined) {`,\n // No backticks in this message: it is emitted INTO a template literal, and a stray one closes\n // it. That is how #344 shipped a SyntaxError, and the emitted-entry parse gate caught this one\n // before it left the branch.\n \" throw new Error(`Route module '\" +\n '${path}' +\n \"' was not bundled into this Worker. \" +\n 'A Worker has no filesystem, so every route is imported at build time. ' +\n 'Re-run: theokit build --target cloudflare`)',\n ` }`,\n ` return mod`,\n `}`,\n ``,\n ]\n}\n\n/**\n * Read the map `theokit build` emitted, for baking into the worker (B-035).\n *\n * Returns `undefined` — never throws — for an absent or malformed file. A deploy that failed\n * because an optimisation was missing would turn a lost round trip into a broken build, and the\n * worker is correct without it.\n */\nexport function readAssetsMapForBake(path: string): Record<string, string[]> | undefined {\n try {\n return parseAssetsMap(readFileSync(path, 'utf8'))\n } catch {\n return undefined\n }\n}\n\n/**\n * The baked route-to-chunks map, as worker source (B-035).\n *\n * A literal and not a read, for the same reason the document shell is: a Worker has no filesystem\n * at request time. Emitted only when the build produced a map; otherwise the worker carries\n * nothing about preloads and behaves exactly as before.\n *\n * **It emits the DATA and no longer the code.** An earlier revision emitted a hand-written copy of\n * `injectModulePreloads`, justified by a claim that the worker could not import it. That claim was\n * false — `theokit/server` re-exports from `core/contracts/` and the generated worker already\n * imports that subpath — and the copy drifted within a day: a fix for proxy-form request targets\n * landed in the original and not in the duplicate. The worker now imports the real function, which\n * is the shape `adapters/security-headers.ts` established one directory over for exactly this\n * build-half/runtime-half pair.\n */\n/**\n * Whether this worker can preload at all (B-035).\n *\n * ONE predicate, read by the bake, the import and the call. Two conditions for one decision is\n * how the import came to be emitted for a worker that had no map to give it — found at review, in\n * the same change where a copy and its original had already drifted apart.\n *\n * Streaming is required because the other branch serves the document from `env.ASSETS` as a\n * static file and can inject nothing into it.\n */\nfunction preloadsApplyTo(opts: {\n ssrStreaming?: boolean\n assetsMap?: Record<string, string[]>\n}): boolean {\n return opts.ssrStreaming === true && opts.assetsMap !== undefined\n}\n\nfunction renderPreloadSupport(assetsMap: Record<string, string[]> | undefined): string {\n if (assetsMap === undefined) return ''\n return `const __THEO_ASSETS_MAP = ${JSON.stringify(assetsMap)}`\n}\n\n/**\n * The branch that answers a non-API request: streamed SSR, or the static asset the Worker\n * platform serves. Extracted at review — it is the one decision in this emitter with two whole\n * shapes behind it, and keeping it inline pushed the caller past its line budget.\n */\nfunction renderNonApiBranch(\n opts: NonNullable<Parameters<typeof renderCloudflareWorkerEntry>[0]>,\n preloadsApply: boolean,\n): string {\n return opts.ssrStreaming\n ? [\n ` // T2.3 — streaming SSR for non-API routes`,\n ` // The same primitive \\`theokit start\\` uses, not a second one:`,\n ` // 16 bytes of Web Crypto entropy, base64.`,\n ` const nonce = generateNonce()`,\n ` return withSecurityHeaders(`,\n ` await renderStreamingWeb(request, {`,\n !preloadsApply\n ? ` htmlHead: ${JSON.stringify(opts.htmlHead ?? '')},`\n : ` htmlHead: injectModulePreloads(${JSON.stringify(opts.htmlHead ?? '')}, __THEO_ASSETS_MAP, new URL(request.url).pathname),`,\n ` htmlTail: ${JSON.stringify(opts.htmlTail ?? '')},`,\n ` nonce,`,\n ` }),`,\n ` buildSecurityHeaders(SECURITY_HEADERS_CONFIG, { production: true }, { nonce }),`,\n ` )`,\n ].join('\\n')\n : [\n ` // #412 — the document, served by the worker so it carries the same baseline every`,\n ` // API response carries. It used to return 404 here while wrangler.toml declared a`,\n ` // \\`[site]\\` bucket nothing read, so the page was missing rather than unprotected.`,\n ` const assets = env?.ASSETS`,\n ` // A wrangler.toml that predates this binding has no ASSETS. Reading .fetch off`,\n ` // undefined would turn every page request into a 500; 404 is what this target`,\n ` // answered before, which is the honest fallback rather than a new failure.`,\n ` if (assets === undefined) return notFoundResponse()`,\n ` return withSecurityHeaders(await assets.fetch(request), SECURITY_HEADERS)`,\n ].join('\\n')\n}\n\nexport function renderCloudflareWorkerEntry(\n opts: {\n ssrStreaming?: boolean\n htmlHead?: string\n htmlTail?: string\n /**\n * B-035 — the route-to-chunks map, baked as a literal for the same reason the shell above\n * is: a Worker has no filesystem at request time. Absent when the build produced no map,\n * and then nothing about preloads is emitted at all.\n */\n assetsMap?: Record<string, string[]>\n securityHeaders?: SecurityHeadersConfig\n /**\n * The server routes, scanned on the BUILD machine (#369).\n *\n * A Worker has no filesystem, so the worker used to call `scanServerRoutes` — a `readdirSync` —\n * against a directory that does not exist there, and load each module through `import()` of a\n * file path. Both are baked here instead, which is the road this adapter already takes for the\n * document shell one function away.\n *\n * `filePath` is relative to the project root and is used for two things: the key the executor\n * looks a module up by, and the specifier the static import uses. Paths are emitted relative to\n * `.theokit/cloudflare/`, where the worker is written.\n */\n routes?: readonly { filePath: string; routePath: string; methods?: readonly string[] }[]\n /**\n * The two concerns #410 could not bake (#425), composed from one place so the six targets\n * cannot drift into six spellings. `serialization` is a literal like the security values above;\n * `plugins` is an import, because a closure has no literal.\n */\n runtimeConfigModule?: DeployedRuntimeConfigOptions['runtimeConfigModule']\n serialization?: DeployedRuntimeConfigOptions['serialization']\n /**\n * The app's agents, scanned on the build machine (#367).\n *\n * A different scan from `routes` and served by a different function — which is why a worker\n * that only consulted the route table answered every `/api/agents/<name>` with a 404.\n */\n agents?: readonly DeployedAgent[]\n /** B-185 — the app's `server/context.ts`, project-relative, or absent when it declares none. */\n contextModule?: string\n /** WebSocket route files, scanned on the build machine. Only their presence is used (#369). */\n wsRoutes?: readonly string[]\n } & DeployedServerDirOptions &\n DeployedCsrfOptions &\n DeployedCorsOptions = {},\n): string {\n const streamingImport = opts.ssrStreaming\n ? `import { renderStreamingWeb } from '/@theo/entry-server'`\n : `// (ssrStreaming off: renderStreamingWeb not imported)`\n // #343 — the document shell is inlined as a build-time literal because a Worker\n // has no filesystem to read `index.html` from at request time. Without it,\n // `renderStreamingWeb` falls back to its empty-string defaults and the response\n // is React output with no `<html>`, no `<head>`, no stylesheet and no client\n // entry — hydration data for a page that cannot hydrate. The streaming\n // assembly was fixed in the generated entry and this, its only caller, was\n // left passing nothing.\n //\n // `JSON.stringify` and not a template literal: the shell contains quotes,\n // angle brackets and a `</script>`, and embedding it naively produces a worker\n // that fails to parse at deploy time rather than here.\n //\n // #410 — this is also the ONE deploy path that renders HTML at request time,\n // so the one that can mint a per-request CSP nonce: `renderStreamingWeb`\n // threads `options.nonce` into `renderToReadableStream` and into the hydration\n // script (`router/entry-server.ts`). Every other response below carries the\n // nonce-less baseline, which is what `buildSecurityHeaders` already does for a\n // prerendered route (EC-4).\n // Only the streaming branch renders HTML at request time; the other serves the document from\n // `env.ASSETS` as a static file and can inject nothing. Baking the map for it would ship the whole\n // route table as dead weight — found at review, where the emitter was measured declaring it with\n // zero call sites.\n const preloadsApply = preloadsApplyTo(opts)\n const preloadSupport = preloadsApply ? renderPreloadSupport(opts.assetsMap) : ''\n\n const nonApiBranch = renderNonApiBranch(opts, preloadsApply)\n\n // CR-006: Workers lack `process.cwd()` and the `node:*` import surface\n // is brittle even under `nodejs_compat`. We use the Web Crypto\n // `crypto.randomUUID()` instead of `node:crypto.randomUUID`, and embed\n // the server directory as a build-time literal instead of resolving via\n // `node:path` at runtime.\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(\n opts.agents === undefined\n ? undefined\n : // B-185 — a Worker has no filesystem, so its identity module is baked exactly like its\n // agents and its routes (ADR 0014). `contextModule` is `undefined` for an app that\n // declares none, and the generator then emits no import for it.\n { kind: 'baked', agents: opts.agents, contextModule: opts.contextModule },\n {\n wrapSecurityHeaders: true,\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n },\n )\n\n return [\n `// Generated by Theo — Cloudflare Workers Adapter`,\n `//`,\n `// REQUIREMENTS (EC-3):`,\n `// - wrangler.toml MUST include compatibility_flags = [\"nodejs_compat\"]`,\n `// (still required for transitive theokit/server deps, e.g. busboy)`,\n `// - package.json MUST list \"theokit\" in dependencies (not devDependencies)`,\n `// so Wrangler bundles theokit and its transitive deps`,\n `// - Deploy: wrangler deploy`,\n ``,\n !preloadsApply\n ? `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`\n : `import { matchRoute, executeRoute, compilePattern, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'\\nimport { injectModulePreloads } from 'theokit/server/http'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n opts.ssrStreaming\n ? `import { buildSecurityHeaders, generateNonce, withSecurityHeaders } from 'theokit/adapters/security-headers'`\n : `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n `// T3.4 — WS bridge for Cloudflare Workers`,\n `import { createCloudflareWsBridge } from 'theokit/adapters/ws-shim'`,\n streamingImport,\n ``,\n ...runtimeConfig.imports,\n ...agentsFragment.imports,\n ...routeImports,\n ``,\n `// CR-006: server directory is a build-time literal — Workers cannot`,\n `// call process.cwd() and resolving paths at runtime returned '/server'.`,\n `const serverDir = ${serverDirLiteral(opts)}`,\n ``,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries),\n `// #410 — the security baseline \\`theokit start\\` puts on every response, carried`,\n `// here as a literal because a Worker has no theo.config.ts to read. Same`,\n `// function, same input, so the deployed page and the local one cannot`,\n `// disagree about what the configuration means.`,\n preloadSupport,\n ...securityHeadersDeclarations(opts.securityHeaders),\n ``,\n ...deployedCsrfFragment(opts, 'a Worker'),\n ``,\n ...runtimeConfig.declarations,\n ...agentsFragment.declarations,\n ...deployedCorsFragment(opts.cors, 'cloudflare'),\n `// #369 — whether this project declares a WebSocket route, decided at build time. It used`,\n `// to answer it with \\`scanWebSocketRoutes\\`, which is the same readdirSync.`,\n `const HAS_WS_ROUTES = ${String((opts.wsRoutes ?? []).length > 0)}`,\n ``,\n `function notFoundResponse() {`,\n ` return withSecurityHeaders(`,\n ` new Response(`,\n ` JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Route not found' } }),`,\n ` { status: 404, headers: { 'Content-Type': 'application/json' } },`,\n ` ),`,\n ` SECURITY_HEADERS,`,\n ` )`,\n `}`,\n ``,\n ...cloudflareHandleRequestFragment(\n nonApiBranch,\n runtimeConfig.executeRouteSpread,\n agentsFragment.branch,\n agentsFragment.hostBypass,\n ),\n ].join('\\n')\n}\n\n/**\n * The Worker's request handler, as generated source.\n *\n * Extracted for the reason `vercel.ts` extracts its own fragments: the emitter is one array\n * literal, so every line the entry gains counts against `max-lines-per-function`, and #410 added\n * the CSRF literal to an emitter already sitting exactly at the ceiling.\n *\n * @param nonApiBranch - what a non-`/api/` request gets, which differs with `ssrStreaming`\n */\nfunction cloudflareHandleRequestFragment(\n nonApiBranch: string,\n runtimeSpread: string,\n agentBranch: readonly string[],\n /** SI-020 — the condition that keeps an agent card path out of the static-asset branch. */\n hostBypass: string,\n): string[] {\n return [\n `async function handleRequest(request, url, env) {`,\n ` if (!url.pathname.startsWith('/api/')${hostBypass}) {`,\n nonApiBranch,\n ` }`,\n ``,\n ...agentBranch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ` if (!match) return notFoundResponse()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request, { trustedProxy: 'platform' })`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is NOT awaited before the Response is taken. toResponse()`,\n ` // settles as soon as status + headers are known and carries a live body, so`,\n ` // the Worker starts flushing while the handler is still writing. Awaiting`,\n ` // executeRoute() first would re-buffer the whole response here even though`,\n ` // the shim streams; awaiting toResponse() does not — it settles at the head.`,\n ` return withSecurityHeaders(await toResponse(executeRoute({`,\n ` route: match.route, method, params: match.params,`,\n ` req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` })), SECURITY_HEADERS)`,\n `}`,\n ``,\n `export default {`,\n ` async fetch(request, env, ctx) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` // T3.4 — Detect WebSocket upgrade and delegate to the CF bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!HAS_WS_ROUTES) return notFoundResponse()`,\n ` const cfWs = createCloudflareWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` })`,\n ` return cfWs.handle(request)`,\n ` }`,\n ``,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router handles`,\n ` // is an OPTIONS the browser never gets a CORS answer to. The WebSocket upgrade above is`,\n ` // deliberately upstream of it — a 101 is not a CORS-governed response.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ``,\n ` return withCors(request, await handleRequest(request, url, env))`,\n ` },`,\n `}`,\n ]\n}\n\nexport function renderWranglerToml(): string {\n return [\n `# Generated by Theo — Cloudflare Workers`,\n `name = \"theo-app\"`,\n `main = \".theokit/cloudflare/worker.mjs\"`,\n `compatibility_date = \"2025-09-01\"`,\n `compatibility_flags = [\"nodejs_compat\"]`,\n ``,\n `# #412 — \\`[assets]\\` with a BINDING, not the legacy \\`[site]\\` bucket.`,\n `#`,\n `# \\`[site]\\` uploads to KV and is read through \\`kv-asset-handler\\` and a`,\n `# \\`__STATIC_CONTENT\\` binding — neither of which this worker has ever had. So the`,\n `# bucket was declared, uploaded, and consumed by nothing: with ssrStreaming off, a`,\n `# deploy answered 404 for its own page. This binding is what the worker calls.`,\n `[assets]`,\n `directory = \".theokit/client\"`,\n `binding = \"ASSETS\"`,\n `# A client-routed app asks for /dashboard, which is no file. Without this the asset`,\n `# handler 404s a deep link and the SPA never boots.`,\n `not_found_handling = \"single-page-application\"`,\n ``,\n `# Environment variables are set via wrangler secret or dashboard`,\n `# Example: wrangler secret put DATABASE_URL`,\n ].join('\\n')\n}\n\nexport const cloudflareAdapter: DeployAdapter = {\n name: 'cloudflare',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied: the worker carries `security.headers` as a\n // literal and puts the built baseline on every response it returns, including\n // the streamed SSR document — with a per-request nonce, the only deploy path\n // that can mint one (`adapters/security-headers.ts`).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('cloudflare', readManifest(cwd))\n\n // 1. Run the standard Node build first (ctx forwarded so nodeAdapter has makeVitePlugins)\n await nodeAdapter.build(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/cloudflare')\n mkdirSync(outputDir, { recursive: true })\n\n // 2. Emit Worker entry (now uses the shared web-shim)\n //\n // The document shell is read HERE, after the Node build produced\n // `.theokit/client/index.html`, and inlined into the worker: a Worker has no\n // filesystem at request time. Split on the root div with the same helper the\n // Node server uses (`ssr-setup.ts`), so the two paths cannot disagree about\n // where the shell ends (#343).\n const shell = readDocumentShell(cwd, config.ssrStreaming)\n // B-035 — the route-to-chunks map, read HERE on the build machine for the same reason the\n // shell above is: a Worker has no filesystem at request time. `nodeAdapter.build` ran\n // first, so the map the Node build emitted is on disk by now. Absent map -> nothing about\n // preloads is emitted, and the worker behaves exactly as it did before.\n const assetsMap = readAssetsMapForBake(resolve(cwd, '.theokit', 'client', 'assets-map.json'))\n\n // #369 — the routes are resolved HERE, on the build machine, for the same reason the document\n // shell above is read here: a Worker has no filesystem at request time, and the worker used to\n // run the scan itself against a directory that does not exist there.\n //\n // The scanner is INJECTED rather than imported: importing it would add an `adapters → server`\n // edge, which is the layering inversion ADR-0001 v3 removed for `vite-plugin` and which\n // `adapters-may-only-depend-on-core-router-services` refuses. An absent scanner emits a worker\n // with no routes rather than falling back to a runtime scan — the fallback IS the defect.\n const scanned = ctx?.scanRoutes?.(config.serverDir) ?? {\n routes: [],\n wsRoutes: [],\n agents: [],\n // B-185 — no provider means no scan, and an app whose context nobody looked for is\n // indistinguishable here from one that has none. Both resolve an anonymous caller, which is\n // the honest answer rather than an invented subject.\n contextModule: undefined,\n }\n\n const pluginsPlan = planDeployedPlugins(config.plugins, 'cloudflare')\n if (pluginsPlan !== undefined) {\n // Beside the worker, so the emitted import is a sibling. Wrangler bundles from here, which is\n // what lets the static import reach the app's own module at all (#425).\n writeFileSync(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n\n writeFileSync(\n resolve(outputDir, 'worker.mjs'),\n renderCloudflareWorkerEntry({\n ssrStreaming: config.ssrStreaming,\n ...shell,\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n assetsMap,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n routes: scanned.routes,\n // #367 — a Worker has no filesystem, so its agents are decided here like its routes.\n agents: scanned.agents,\n // B-185 — rides beside the agents because it is decided by the same provider, for the same\n // reason: `build.ts` holds `serverDir` and a Worker cannot look for the module itself.\n contextModule: scanned.contextModule,\n wsRoutes: scanned.wsRoutes,\n }),\n )\n\n // 3. Emit wrangler.toml (with nodejs_compat enforced)\n writeFileSync(resolve(cwd, 'wrangler.toml'), renderWranglerToml())\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Cloudflare output → .theokit/cloudflare/ + wrangler.toml')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'cloudflare',\n securityHeaders: config.security?.headers,\n // Only the streaming worker renders HTML per request, so only it can put\n // the same nonce on the header and on the script tag it emits.\n mintsNonce: config.ssrStreaming,\n // #412 — either way the worker returns the document now: streamed by\n // `renderStreamingWeb`, or from the ASSETS binding it finally calls.\n documentHeaders: 'handler',\n })}\\n`,\n )\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AA0CjB,SAAS,kBACd,KACA,WAC0C;AAC1C,MAAI,CAAC,UAAW,QAAO,CAAC;AAExB,QAAM,YAAY,QAAQ,KAAK,4BAA4B;A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AAiB,OAAO,UAAU;AAAA;AAAA;AAAA,QAGlC,YAAY,OAAO;AAAA;AAAA;AAAA,QAGnB,iBAAiB;AAAA,MACnB,CAAC,CAAC;AAAA;AAAA,IACJ;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/deno-deploy.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Deno Deploy adapter. Writes to `cwd/.theokit/deno-deploy/`. Build-time.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport { deployedAgentsFragment, scannedFromLoaderCache } from './deployed-agents.js'\nimport { planDeployedPlugins } from './deployed-plugins-module.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport {\n agentsDirLiteral,\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter, DeployedEntryOptions } from './types.js'\n\nexport interface DenoBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeEntry?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n}\n\n/**\n * The framework imports this entry opens with, as `npm:` specifiers.\n *\n * Extracted from `renderDenoEntry` when adding the configured-directory literal pushed it past the\n * per-function line budget. A cohesive block — every line is one import of the same package family\n * — so lifting it keeps the budget a signal about the renderer rather than about its preamble.\n */\nconst FRAMEWORK_IMPORTS: readonly string[] = [\n `// Use npm: specifier so Deno resolves theokit from the user's package.json`,\n `// equivalent (works in both local 'deno run' and Deno Deploy).`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, scanWebSocketRoutes, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'npm:theokit/server'`,\n `import { createWebShim } from 'npm:theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'npm:theokit/adapters/security-headers'`,\n `// T3.3 — WS bridge for Deno runtime`,\n `import { createDenoWsBridge } from 'npm:theokit/adapters/ws-shim'`,\n]\n\nexport function renderDenoEntry(port: number, opts: DeployedEntryOptions = {}): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n const agentsFragment = deployedAgentsFragment(scannedFromLoaderCache(agentsDirLiteral(opts)), {\n notFound: 'notFound()',\n importPrefix: 'npm:',\n // B-185 — bound only when the runtime-config fragment declared the const, which is\n // exactly when a plugins module was emitted. Referencing it otherwise would emit an\n // identifier the entry never declares.\n pluginRunnerExpr:\n opts.runtimeConfigModule === undefined ? undefined : 'await THEO_PLUGIN_RUNNER',\n })\n return [\n `// Generated by Theo — Deno Deploy Adapter`,\n `// Deploy: deployctl deploy --project=<name> .theokit/deno/server.ts`,\n `// Requires Deno >= 1.40 (Deno.serve + npm: specifier support)`,\n ``,\n `// Runtime guard`,\n `if (typeof Deno === 'undefined') {`,\n ` throw new Error('TheoDenoDeployAdapter must run inside Deno.')`,\n `}`,\n ``,\n ...FRAMEWORK_IMPORTS,\n ``,\n `const port = Number(Deno.env.get('PORT') ?? '${port}')`,\n `const cwd = Deno.cwd()`,\n `const serverDir = cwd + '/' + ${serverDirLiteral(opts)}`,\n `let routesCache = null`,\n `let wsRoutesCache = null`,\n `let loaderCache = null`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed isolate has no`,\n `// theo.config.ts to read. Non-API paths 404 here and are served by Deno`,\n `// Deploy's static asset handler, so this covers the API and not the`,\n `// document (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, 'deno-deploy'),\n ``,\n `function notFound() {`,\n ` return new Response(JSON.stringify({ error: { code: 'NOT_FOUND' } }), {`,\n ` status: 404,`,\n ` headers: { 'Content-Type': 'application/json' },`,\n ` })`,\n `}`,\n ``,\n `Deno.serve({ port }, async (request) => {`,\n ` // T3.3 — Detect WebSocket upgrade and delegate to the Deno bridge.`,\n ` // A 101 carries no document and no script, so the security baseline does`,\n ` // not apply to it.`,\n ` if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {`,\n ` if (!wsRoutesCache) wsRoutesCache = scanWebSocketRoutes(serverDir)`,\n ` if (wsRoutesCache.length === 0) return notFound()`,\n ` const denoWs = createDenoWsBridge({`,\n ` onOpen: () => {},`,\n ` onMessage: (ws, data) => { ws.send(data) },`,\n ` onClose: () => {},`,\n ` }, Deno)`,\n ` return denoWs.handle(request)`,\n ` }`,\n ``,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n `})`,\n ``,\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ``,\n ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,\n ` // Static + SPA fallback are served by Deno Deploy's static asset handler.`,\n ` return notFound()`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ...agentsFragment.branch,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) return notFound()`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — not awaited: toResponse() settles at the headers and carries a`,\n ` // live body, so Deno.serve streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeConfig.executeRouteSpread} }))`,\n `}`,\n ``,\n `console.log('Theo (Deno Deploy) listening on :' + port)`,\n ].join('\\n')\n}\n\nexport async function buildDeno(\n config: TheoConfig,\n cwd: string,\n deps: DenoBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('deno-deploy', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const outputDir = resolve(cwd, '.theokit/deno')\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n ensureDir(outputDir)\n\n const pluginsPlan = planDeployedPlugins(config.plugins, denoDeployAdapter.name)\n const entry = renderDenoEntry(config.port, {\n securityHeaders: config.security?.headers,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n // #425 — the ONE concern that is not a literal. A closure cannot be baked, so a plugin\n // declared by module specifier is imported by the emitted module instead; a constructed one\n // is refused by name at build time rather than dropped in silence.\n runtimeConfigModule: pluginsPlan?.moduleSpecifier,\n // #95 — the configured directories, which `build.ts:210` already threads into the Vite\n // plugins. Without these two lines the literals above fall to their defaults and a project\n // with a custom dir deploys an entry that resolves a directory it does not have.\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })\n const write =\n deps.writeEntry ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n if (pluginsPlan !== undefined) {\n // Beside the entry, so the emitted import is a sibling. Written through the same seam as\n // the entry so a test that captures one captures both (#425).\n write(resolve(outputDir, 'theo.plugins.mjs'), pluginsPlan.source)\n }\n write(resolve(outputDir, 'server.ts'), entry)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Deno Deploy output → .theokit/deno/server.ts')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'deno-deploy',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-unmanaged',\n })}\\n`,\n )\n}\n\nexport const denoDeployAdapter: DeployAdapter = {\n name: 'deno-deploy',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this isolate returns. The\n // document comes from Deno Deploy's static asset handler and does not pass\n // through it (usetheokit/theokit#412).\n servesAgents: true,\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization', 'plugins'],\n build(config, cwd, ctx) {\n return buildDeno(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AA+BxB,IAAM,oBAAuC;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,gBAAgB,MAAc,OAA6B,CAAC,GAAW;AACrF,QAAM,gBAAgB,8BAA8B,IAAI;AACxD,QAAM,iBAAiB,uBAAuB,uBAAuB,iBAAiB,IAAI,CAAC,GAAG;AAAA,IAC5F,UAAU;AAAA,IACV,cAAc;AAAA;AAAA;AAAA;AAAA,IAId,kBACE,KAAK,wBAAwB,SAAY,SAAY;AAAA,EACzD,CAAC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG;AAAA,IACH;AAAA,IACA,gDAAgD,IAAI;AAAA,IACpD;AAAA,IACA,iCAAiC,iBAAiB,IAAI,CAAC;AAAA,IACvD;AAAA,IACA;AAAA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QAAQ,gBAAgB,OAAO,MAAM;AAAA,IACzC,iBAAiB,OAAO,UAAU;AAAA,IAClC,MAAM,OAAO,UAAU;AAAA,IACvB,YAAY,OAAO,UAAU;AAAA,IAC7B,MAAM,OAAO,UAAU;AAAA;AAAA,IAEvB,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA,IAItB,qBAAqB,aAAa;AAAA;AAAA;AAAA;AAAA,IAIlC,WAAW,OAAO;AAAA,IAClB,WAAW,OAAO;AAAA,EACpB,CAAC;AACD,QAAM,QACJ,KAAK,eACJ,CAAC,GAAG,MAAM;AACT,kBAAc,GAAG,CAAC;AAAA,EACpB;AACF,MAAI,gBAAgB,QAAW;AAG7B,UAAM,QAAQ,WAAW,kBAAkB,GAAG,YAAY,MAAM;AAAA,EAClE;AACA,QAAM,QAAQ,WAAW,WAAW,GAAG,KAAK;AAG5C,UAAQ,IAAI,8DAAoD;AAEhE,UAAQ;AAAA,IACN,GAAG,gCAAgC;AAAA,MACjC,QAAQ;AAAA,MACR,iBAAiB,OAAO,UAAU;AAAA,MAClC,YAAY;AAAA,MACZ,iBAAiB;AAAA,IACnB,CAAC,CAAC;AAAA;AAAA,EACJ;AACF;AAEO,IAAM,oBAAmC;AAAA,EAC9C,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,cAAc;AAAA,EACd,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,iBAAiB,SAAS;AAAA,EAC3F,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,UAAU,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EACvC;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/netlify.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Netlify deploy adapter. All paths derived from `cwd` and a fixed\n * `.theokit/netlify/` output layout. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport {\n deployedAgentsFragment,\n JSON_NOT_FOUND_RESPONSE,\n scannedFromLoaderCache,\n} from './deployed-agents.js'\nimport { type DeployedCorsOptions } from './deployed-cors.js'\nimport { type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport {\n agentsDirLiteral,\n type DeployedAgentsDirOptions,\n deployedRuntimeConfigFragment,\n type DeployedRuntimeConfigOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { buildSecurityHeaders, describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport class NetlifyConflictError extends Error {\n constructor(path: string, currentTo: string) {\n super(\n `netlify.toml has a conflicting redirect: \"${path}\" → \"${currentTo}\". ` +\n `Remove it manually or edit it to point to \"/.netlify/functions/theo\" ` +\n `before running the Netlify adapter again.`,\n )\n this.name = 'NetlifyConflictError'\n }\n}\n\nexport interface NetlifyBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeFile?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n readTomlIfExists?: () => string | null\n}\n\nexport function renderNetlifyFunction(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedAgentsDirOptions &\n DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedCorsOptions = {},\n): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n // B-235. Netlify's handler is `(request, context)` and already RECEIVES a Web `Request`, which\n // is the shape this branch needs — the item filed against it counted `new Request` occurrences\n // and concluded the opposite, measuring how the entry OBTAINS a request rather than whether it\n // has one. Deno is the model: same `loaderCache`, same filesystem `serverDir`, same guard.\n const agentsFragment = deployedAgentsFragment(scannedFromLoaderCache(agentsDirLiteral(opts)), {\n // Netlify answers its own 404 inline rather than through a helper, so the fragment is given\n // the expression instead of a call it would have to declare.\n notFound: `new Response('Not Found', { status: 404 })`,\n })\n return [\n `// Generated by Theo — Netlify Functions adapter`,\n `import { resolve } from 'node:path'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `const cwd = process.cwd()`,\n `const serverDir = resolve(cwd, 'server')`,\n `let routesCache = null`,\n `let loaderCache = null`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed function has no`,\n `// theo.config.ts to read. The netlify.toml redirect routes only /api/* here,`,\n `// so this covers the API and not the document Netlify's static host serves`,\n `// (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, 'netlify'),\n ``,\n `export default async (request, context) => {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n `}`,\n ``,\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,\n ` return new Response('Not Found', { status: 404 })`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n ...agentsFragment.branch,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) return ${JSON_NOT_FOUND_RESPONSE}`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is not awaited: toResponse() settles at the headers and`,\n ` // carries a live body, so Netlify streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeConfig.executeRouteSpread} }))`,\n `}`,\n ].join('\\n')\n}\n\nconst THEO_REDIRECT_FROM = '/api/*'\nconst THEO_REDIRECT_TO = '/.netlify/functions/theo'\n\n/**\n * TOML merge (EC-2) — non-destructive.\n *\n * We avoid adding a TOML parser dependency by working at the line level. The\n * supported subset is sufficient for the Netlify use case:\n * - detect existing `[[redirects]]` blocks\n * - find a block whose `from = \"...\"` matches our target\n * - error if such a block points elsewhere\n * - otherwise append our block\n *\n * Unknown sections (e.g. `[build]`, `[[headers]]`, `[context.production.environment]`)\n * are preserved as-is.\n */\ninterface NetlifyRedirectBlock {\n startLine: number\n endLine: number\n from?: string\n to?: string\n}\n\nfunction parseRedirectBlocks(lines: readonly string[]): NetlifyRedirectBlock[] {\n const blocks: NetlifyRedirectBlock[] = []\n let current: NetlifyRedirectBlock | null = null\n\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i].trim()\n if (trimmed === '[[redirects]]') {\n if (current) {\n current.endLine = i - 1\n blocks.push(current)\n }\n current = { startLine: i, endLine: i }\n continue\n }\n if (current && /^\\[(\\[|[^[])/.test(trimmed)) {\n // Entering another section — close current.\n current.endLine = i - 1\n blocks.push(current)\n current = null\n }\n if (current) {\n const fromMatch = /^from\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (fromMatch) current.from = fromMatch[1]\n const toMatch = /^to\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (toMatch) current.to = toMatch[1]\n current.endLine = i\n }\n }\n if (current) blocks.push(current)\n return blocks\n}\n\nconst THEO_REDIRECT_TARGET = [\n '[[redirects]]',\n ' from = \"/api/*\"',\n ' to = \"/.netlify/functions/theo\"',\n ' status = 200',\n ' force = true',\n].join('\\n')\n\n/**\n * Marks the block this build owns, so it can be REGENERATED rather than merely not duplicated.\n *\n * Idempotence alone would be the wrong contract here: the block carries configuration, so a\n * `security.headers` change has to reach the file. Leaving an existing block in place — which is\n * what the redirect above correctly does, because its content is fixed — would silently pin the\n * baseline to whatever the first build emitted.\n */\nconst THEO_HEADERS_MARKER = '# Generated by Theo — security baseline (usetheokit/theokit#412)'\n\n/**\n * The `[[headers]]` block telling Netlify's static host the baseline.\n *\n * The emitted function applies these to every response IT returns, and it never returns the HTML\n * document: the `[[redirects]]` block routes only `/api/*`, so the page comes from Netlify's static\n * host and carried none of them. The values come from `buildSecurityHeaders` — the same function\n * the handler calls — rather than being written out here, because two lists of headers that must\n * agree are two lists that eventually do not.\n */\nfunction renderHeadersBlock(securityHeaders: SecurityHeadersConfig | undefined): string {\n const values = buildSecurityHeaders(securityHeaders ?? {}, { production: true })\n return [\n THEO_HEADERS_MARKER,\n '[[headers]]',\n ' for = \"/*\"',\n ' [headers.values]',\n ...Object.entries(values).map(([k, v]) => ` ${k} = ${JSON.stringify(v)}`),\n ].join('\\n')\n}\n\n/**\n * Drop a previously generated block, so the next one replaces it.\n *\n * Bounded by the marker and the next top-level section at column 0 (or EOF) — the shape TOML gives\n * a block. A user's own `[[headers]]` is untouched because it does not carry the marker: their\n * file, their rules, and Netlify applies both.\n */\nfunction withoutGeneratedHeaders(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const start = lines.indexOf(THEO_HEADERS_MARKER)\n if (start < 0) return source\n\n const opensSection = (line: string | undefined): boolean => (line ?? '').startsWith('[')\n\n let end = start + 1\n while (end < lines.length && !opensSection(lines[end])) end += 1\n // The marker line itself opens the block, so `end` now sits on the NEXT section — but the block's\n // own `[[headers]]` is the first `[` after the marker, so step past it before scanning again.\n end += 1\n while (end < lines.length && !opensSection(lines[end])) end += 1\n\n return [...lines.slice(0, start), ...lines.slice(end)].join('\\n').replace(/\\n{3,}/gu, '\\n\\n')\n}\n\nexport function mergeNetlifyToml(\n existing: string | null,\n securityHeaders?: SecurityHeadersConfig,\n): string {\n const headersBlock = renderHeadersBlock(securityHeaders)\n\n if (existing === null || existing.trim().length === 0) {\n return `${THEO_REDIRECT_TARGET}\\n\\n${headersBlock}\\n`\n }\n\n existing = withoutGeneratedHeaders(existing)\n\n const blocks = parseRedirectBlocks(existing.split(/\\r?\\n/))\n\n // Detect conflict: every `/api/*` block must point at our function.\n for (const b of blocks) {\n if (b.from !== THEO_REDIRECT_FROM) continue\n if (b.to === THEO_REDIRECT_TO) {\n // The redirect is already there. The headers block is regenerated regardless, because it\n // carries configuration and the redirect does not.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return `${existing}${sep}\\n${headersBlock}\\n`\n }\n throw new NetlifyConflictError(b.from, b.to ?? '(unknown)')\n }\n\n // No conflict — append target block.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return `${existing}${sep}\\n${THEO_REDIRECT_TARGET}\\n\\n${headersBlock}\\n`\n}\n\nexport async function buildNetlify(\n config: TheoConfig,\n cwd: string,\n deps: NetlifyBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('netlify', readManifest(cwd))\n\n const runNodeBuild = deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter)\n await runNodeBuild(config, cwd, ctx)\n\n const ensureDir = deps.ensureDir ?? ((p: string) => mkdirSync(p, { recursive: true }))\n const writeFile =\n deps.writeFile ??\n ((p, c) => {\n writeFileSync(p, c)\n })\n const readTomlIfExists =\n deps.readTomlIfExists ??\n (() => {\n const p = resolve(cwd, 'netlify.toml')\n return existsSync(p) ? readFileSync(p, 'utf-8') : null\n })\n\n const fnDir = resolve(cwd, '.netlify/functions')\n ensureDir(fnDir)\n writeFile(\n resolve(fnDir, 'theo.mjs'),\n renderNetlifyFunction({\n securityHeaders: config.security?.headers,\n // B-235 — pillar (a): the option existed and no build passed it, so a project with a\n // configured agents directory got the default `agents` on this target. Same defect\n // B-185 fixed for bun and deno, one target over.\n agentsDir: config.agentsDir,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n }),\n )\n\n const existingToml = readTomlIfExists()\n const merged = mergeNetlifyToml(existingToml, config.security?.headers)\n writeFile(resolve(cwd, 'netlify.toml'), merged)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Netlify output → .netlify/functions/theo.mjs + netlify.toml')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'netlify',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-configured',\n })}\\n`,\n )\n}\n\nexport const netlifyAdapter: DeployAdapter = {\n name: 'netlify',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this function returns.\n // The document is served by Netlify's static host and does not pass through\n // it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n build(config, cwd, ctx) {\n return buildNetlify(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AAyBjB,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAAY,MAAc,WAAmB;AAC3C;AAAA,MACE,6CAA6C,IAAI,aAAQ,SAAS;AAAA,IAGpE;AACA,SAA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J,KAAK,qBACJ,MAAM;AACL,UAAM,IAAI,QAAQ,KAAK,cAAc;AACrC,WAAO,WAAW,CAAC,IAAI,aAAa,GAAG,OAAO,IAAI;AAAA,EACpD;AAEF,QAAM,QAAQ,QAAQ,KAAK,oBAAoB;AAC/C,YAAU,KAAK;AACf;AAAA,IACE,QAAQ,OAAO,UAAU;AAAA,IACzB,sBAAsB;AAAA,MACpB,iBAAiB,OAAO,UAAU;AAAA;AAAA;AAAA;AAAA,MAIlC,WAAW,OAAO;AAAA,MAClB,MAAM,OAAO,UAAU;AAAA,MACvB,YAAY,OAAO,UAAU;AAAA,MAC7B,MAAM,OAAO,UAAU;AAAA;AAAA,MAEvB,eAAe,OAAO;AAAA,IACxB,CAAC;AAAA,EACH;AAEA,QAAM,eAAe,iBAAiB;AACtC,QAAM,SAAS,iBAAiB,cAAc,OAAO,UAAU,OAAO;AACtE,YAAU,QAAQ,KAAK,cAAc,GAAG,MAAM;AAG9C,UAAQ,IAAI,6EAAmE;AAE/E,UAAQ;AAAA,IACN,GAAG,gCAAgC;AAAA,MACjC,QAAQ;AAAA,MACR,iBAAiB,OAAO,UAAU;AAAA,MAClC,YAAY;AAAA,MACZ,iBAAiB;AAAA,IACnB,CAAC,CAAC;AAAA;AAAA,EACJ;AACF;AAEO,IAAM,iBAAgC;AAAA,EAC3C,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,eAAe;AAAA,EAChF,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,aAAa,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EAC1C;AACF;","names":["sep"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/vercel.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Vercel deploy adapter. All paths derived from `cwd` and a fixed\n * `.theokit/vercel/` output layout. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, writeFileSync, cpSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport {\n deployedAgentsFragment,\n scannedFromLoaderCache,\n JSON_NOT_FOUND_RESPONSE,\n} from './deployed-agents.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport {\n agentsDirLiteral,\n deployedRuntimeConfigFragment,\n serverDirLiteral,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { buildSecurityHeaders, describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter, DeployedEntryOptions } from './types.js'\n\n/**\n * T2.2 — Vercel adapter rewritten to consume `theokit/adapters/web-shim`\n * instead of emitting an inline plain-object Request/Response shim and\n * lazy-importing internal `theo-server/` paths.\n */\n\n// Generated-code fragments — extracted so the parent emitter stays under the\n// max-lines-per-function ceiling.\n/** The exported function Vercel invokes: one security-header call, then the drain. */\nfunction vercelHandlerFragment(): string[] {\n return [\n `export default async function handler(nodeReq, nodeRes) {`,\n ` // #409 — CORS reads only the method and the \\`origin\\` / \\`access-control-request-method\\``,\n ` // headers, so this carries exactly those and no body. It is deliberately NOT the routing`,\n ` // Request: that one drains the request stream, and only after a route matched — building it`,\n ` // here would drain the body of every static path too.`,\n ` const corsHeaders = new Headers()`,\n ` for (const [k, v] of Object.entries(nodeReq.headers ?? {})) {`,\n ` if (typeof v === 'string') corsHeaders.set(k, v)`,\n ` }`,\n ` const corsRequest = new Request(`,\n ` new URL(nodeReq.url ?? '/', 'http://' + (nodeReq.headers?.host ?? 'localhost')),`,\n ` { method: (nodeReq.method ?? 'GET').toUpperCase(), headers: corsHeaders },`,\n ` )`,\n ``,\n ` // The preflight is answered BEFORE anything routes: an OPTIONS the router handles is an`,\n ` // OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(corsRequest)`,\n ` const webResponse = preflight !== null`,\n ` ? withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ` : withCors(corsRequest, withSecurityHeaders(await routeRequest(nodeReq), SECURITY_HEADERS))`,\n ``,\n ` // \\`outHeaders\\`, not \\`headers\\`: this used to live in the same scope as the`,\n ` // request-side \\`const headers\\` below, which made the whole module a`,\n ` // SyntaxError — every Vercel build between #382 and #411 emitted a function`,\n ` // that could not be loaded.`,\n ` const outHeaders = {}`,\n ` webResponse.headers.forEach((v, k) => { outHeaders[k] = v })`,\n ` nodeRes.writeHead(webResponse.status, outHeaders)`,\n ` if (typeof nodeRes.flushHeaders === 'function') nodeRes.flushHeaders()`,\n ``,\n ` // #382 — this used to materialize the entire body as a string and hand`,\n ` // it to a single end(), which re-buffered the whole response inside the`,\n ` // function even after the shim was fixed. Drain chunk by chunk instead,`,\n ` // honouring Node backpressure so a slow client cannot grow the queue.`,\n ` if (webResponse.body === null) {`,\n ` nodeRes.end()`,\n ` return`,\n ` }`,\n ` const reader = webResponse.body.getReader()`,\n ` try {`,\n ` for (;;) {`,\n ` const { done, value } = await reader.read()`,\n ` if (done) break`,\n ` if (nodeRes.write(value) === false) {`,\n ` await new Promise((resolveDrain) => {`,\n ` const finish = () => {`,\n ` nodeRes.off('drain', finish)`,\n ` nodeRes.off('close', finish)`,\n ` nodeRes.off('error', finish)`,\n ` resolveDrain()`,\n ` }`,\n ` nodeRes.once('drain', finish)`,\n ` nodeRes.once('close', finish)`,\n ` nodeRes.once('error', finish)`,\n ` })`,\n ` }`,\n ` }`,\n ` nodeRes.end()`,\n ` } catch (streamErr) {`,\n ` // The handler failed after the head went out. Destroying the socket is`,\n ` // the only signal left that the body is incomplete — ending normally`,\n ` // would report a truncated response as a complete one (ADR-0002).`,\n ` nodeRes.destroy(streamErr)`,\n ` } finally {`,\n ` reader.releaseLock()`,\n ` }`,\n `}`,\n ``,\n ]\n}\n\n// Generated-code fragments — extracted so the parent emitter stays under the\n// max-lines-per-function ceiling.\n/** Everything that decides WHAT the response is, as a Web Response for every outcome. */\nfunction vercelRouteRequestFragment(\n runtimeSpread: string,\n agentsBranch: readonly string[],\n agentsHostBypass: string,\n): string[] {\n return [\n `async function routeRequest(nodeReq) {`,\n ` const url = new URL(nodeReq.url ?? '/', 'http://' + (nodeReq.headers?.host ?? 'localhost'))`,\n ``,\n ` if (!url.pathname.startsWith('/api/')${agentsHostBypass}) {`,\n ` return new Response('Not Found', {`,\n ` status: 404,`,\n ` headers: { 'content-type': 'text/plain; charset=utf-8' },`,\n ` })`,\n ` }`,\n ``,\n ` if (!routesCache) routesCache = scanServerRoutes(serverDir)`,\n ` if (!loaderCache) loaderCache = createProductionLoader()`,\n ``,\n // B-235 — the Node-to-Web conversion is hoisted ABOVE the agents branch, which names\n // `request` like every other host's, and an agent path never reaches a route match. The\n // rename from `webRequest` is what lets this target share the one fragment instead of a\n // fourth near-copy of it.\n //\n // The body is therefore drained before `matchRoute` rather than after, so an unmatched POST\n // now has its body read. That is a real change and the safer direction: an unconsumed Node\n // request socket is what keeps a connection open, and the drain already happened for every\n // request that matched.\n ` // Convert Node-style req to a Web Request — for the agents branch and for the shim`,\n ` const headers = new Headers()`,\n ` for (const [k, v] of Object.entries(nodeReq.headers ?? {})) {`,\n ` if (typeof v === 'string') headers.set(k, v)`,\n ` }`,\n ` let body`,\n ` const method = (nodeReq.method ?? 'GET').toUpperCase()`,\n ` if (method !== 'GET' && method !== 'HEAD') {`,\n ` const chunks = []`,\n ` await new Promise((resolveProm, rejectProm) => {`,\n ` nodeReq.on('data', (c) => chunks.push(c))`,\n ` nodeReq.on('end', () => resolveProm())`,\n ` nodeReq.on('error', rejectProm)`,\n ` })`,\n ` body = Buffer.concat(chunks)`,\n ` }`,\n ` const request = new Request(url.toString(), { method, headers, body })`,\n ``,\n ...agentsBranch,\n ``,\n ` const match = matchRoute(url.pathname, routesCache)`,\n ` if (!match) return ${JSON_NOT_FOUND_RESPONSE}`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` // #382 — executeRoute() is NOT awaited before the Response is taken:`,\n ` // toResponse() settles at the headers and carries a live body.`,\n ` return toResponse(executeRoute({`,\n ` route: match.route, method, params: match.params,`,\n ` req, res, loadModule: loaderCache, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread}`,\n ` }))`,\n `}`,\n ]\n}\n\nexport function renderVercelFunctionEntry(opts: DeployedEntryOptions = {}): string {\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n // B-235. This is the target the item's evidence was right about in form and wrong about in\n // consequence: the handler IS Node-shaped, and it already converts to a Web `Request` before\n // handing anything to the shim. Threading `nodeReq` through twelve sites says how the entry\n // RECEIVES a request, not whether it can produce the one this branch needs.\n const agentsFragment = deployedAgentsFragment(scannedFromLoaderCache(agentsDirLiteral(opts)), {\n notFound: JSON_NOT_FOUND_RESPONSE,\n })\n return [\n `// Generated by Theo — Vercel Functions adapter`,\n `// Environment variables are resolved at RUNTIME, not build time.`,\n ``,\n `import { resolve } from 'node:path'`,\n `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server'`,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `// Cold-start cache`,\n `let routesCache = null`,\n `let loaderCache = null`,\n `const serverDir = resolve(process.cwd(), ${serverDirLiteral(opts)})`,\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed function has no`,\n `// theo.config.ts to read. config.json routes only /api/* here, so this`,\n `// covers the API and not the document Vercel's static host serves`,\n `// (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, 'vercel'),\n ``,\n `// Vercel Functions invoke this default export with a (req, res) pair`,\n `// (Node IncomingMessage-style). \\`routeRequest\\` produces a Web Response for`,\n `// every outcome — including the two 404s — so the security baseline is`,\n `// applied at ONE place and no branch can be added that skips it.`,\n ...vercelHandlerFragment(),\n ``,\n ...vercelRouteRequestFragment(\n runtimeConfig.executeRouteSpread,\n agentsFragment.branch,\n agentsFragment.hostBypass,\n ),\n ].join('\\n')\n}\n\nexport interface VercelRoutingRule {\n src?: string\n dest?: string\n handle?: string\n /** Build Output API v3 — response headers this rule adds. */\n headers?: Record<string, string>\n /**\n * Keep routing after this rule matches.\n *\n * Load-bearing for the header rule: without it a matching rule TERMINATES routing in Build\n * Output v3, so every request would receive the headers and no content.\n */\n continue?: boolean\n}\n\n/**\n * The routing table, plus the security baseline for the responses this build does NOT serve.\n *\n * The emitted function applies the baseline to every response IT returns — and it never returns the\n * HTML document: `{ handle: 'filesystem' }` hands the page to Vercel's static host, so the JSON was\n * protected and the page it renders in was not (usetheokit/theokit#412).\n *\n * The values come from `buildSecurityHeaders`, the same function the handler calls, rather than\n * being written out here. Two lists of headers that must agree are two lists that eventually do\n * not.\n *\n * Order matters twice: the header rule sits FIRST, because a rule after `handle: 'filesystem'`\n * never runs for a static file, and it carries `continue: true`, because a matching rule otherwise\n * ends routing and the request would get headers with no body.\n *\n * What this does NOT prove: that a deployed page carries them. That needs a deployment, and this\n * repository deploys to no Vercel project from CI. The emitted configuration is verifiable; the\n * platform honouring it is not, and the difference is stated rather than glossed.\n */\nexport function renderVercelConfigJson(securityHeaders?: SecurityHeadersConfig): {\n version: number\n routes: VercelRoutingRule[]\n} {\n return {\n version: 3,\n routes: [\n {\n src: '/(.*)',\n headers: buildSecurityHeaders(securityHeaders ?? {}, { production: true }),\n continue: true,\n },\n { src: '/api/(.*)', dest: '/api' },\n { handle: 'filesystem' },\n { src: '/(.*)', dest: '/index.html' },\n ],\n }\n}\n\nexport function renderVercelVcConfigJson(): {\n runtime: string\n handler: string\n launcherType: string\n shouldAddHelpers: boolean\n supportsResponseStreaming: boolean\n} {\n return {\n runtime: 'nodejs22.x',\n handler: 'index.mjs',\n launcherType: 'Nodejs',\n shouldAddHelpers: true,\n // #382 — Build Output API v3 opt-in. Without it the platform buffers the\n // function's response no matter how the handler writes it, so the emitted\n // chunk-by-chunk drain above would never reach the client. We cannot\n // verify the platform side from here; see the streaming note in\n // `adapters/web-shim.ts` and the adapter's `streamsResponses` flag.\n supportsResponseStreaming: true,\n }\n}\n\nexport const vercelAdapter: DeployAdapter = {\n name: 'vercel',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this function returns.\n // The document is served from `.vercel/output/static` and does not pass\n // through it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n\n async build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n // Per 2026-05-27 owner decision, polyglot is wired via `node` (local\n // docker-compose harness) + `theo-cloud` (Wave 3). Vercel adapter\n // wire-up is deferred to a fresh ADR with demand evidence.\n assertServicesUnsupported('vercel', readManifest(cwd))\n\n // 1. Run the standard Node build first (ctx forwarded so nodeAdapter has makeVitePlugins)\n await nodeAdapter.build(config, cwd, ctx)\n\n const clientDir = resolve(cwd, '.theokit/client')\n const outputDir = resolve(cwd, '.vercel/output')\n\n // 2. Create .vercel/output structure\n mkdirSync(resolve(outputDir, 'static'), { recursive: true })\n mkdirSync(resolve(outputDir, 'functions/api.func'), { recursive: true })\n\n // 3. Copy static assets\n if (existsSync(clientDir)) {\n cpSync(clientDir, resolve(outputDir, 'static'), { recursive: true })\n }\n\n // 4. Emit serverless function entry (now uses shared web-shim)\n writeFileSync(\n resolve(outputDir, 'functions/api.func/index.mjs'),\n renderVercelFunctionEntry({\n securityHeaders: config.security?.headers,\n // B-235 — pillar (a): the option existed and no build passed it, so a project with a\n // configured agents directory got the default `agents` on this target. Same defect\n // B-185 fixed for bun and deno, one target over.\n agentsDir: config.agentsDir,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n }),\n )\n\n // 5. Emit .vc-config.json\n writeFileSync(\n resolve(outputDir, 'functions/api.func/.vc-config.json'),\n JSON.stringify(renderVercelVcConfigJson(), null, 2),\n )\n\n // 6. Emit config.json (routing)\n writeFileSync(\n resolve(outputDir, 'config.json'),\n JSON.stringify(renderVercelConfigJson(config.security?.headers), null, 2),\n )\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log('\\n ✓ Vercel output → .vercel/output/')\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'vercel',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-configured',\n })}\\n`,\n )\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,eAAe,cAAc;AAC7D,SAAS,eAAe;AA+BxB,SAAS,wBAAkC;AACzC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;A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