@guren/plugin-cloudflare 0.5.0 → 0.7.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.
@@ -0,0 +1,950 @@
1
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { join, relative, resolve, sep } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { AGENTS_CONFIG_FILE, DEV_ONLY_MODULES, DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS, MCP_PLUGIN_PACKAGE, MCP_TRANSPORT_SPECIFIER, SQL_CLIENT_MODULES, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, stageStaticAssets, stubbableDevOnlyModules } from "@guren/core/internal/deploy-build";
5
+ //#region src/templates.ts
6
+ /**
7
+ * The OAuth consent flow this plugin scaffolds, shipped as real sources under
8
+ * `templates/mcp-oauth/` (published, outside `dist/`, so the URL below climbs one
9
+ * level from `dist/` and `src/` alike). A template's path relative to that tree
10
+ * is exactly its path in the app, so the relative import from `routes/` into
11
+ * `app/Http/Controllers/` resolves in both; the root `tsconfig` typechecks them.
12
+ */
13
+ const templateDir = fileURLToPath(new URL("../templates/mcp-oauth", import.meta.url));
14
+ /** The routes template, named once — the scaffold reports on it specifically. */
15
+ const MCP_OAUTH_ROUTES_FILE = "routes/mcp-oauth.ts";
16
+ /**
17
+ * Every file the consent-flow scaffold writes, in the order it writes them. A
18
+ * list rather than a directory walk: a walk would silently start writing
19
+ * anything that landed in the template tree, a stray `.d.ts` included.
20
+ */
21
+ const MCP_OAUTH_TEMPLATE_FILES = [
22
+ "app/View/McpOAuthConsentPage.tsx",
23
+ "app/View/McpOAuthErrorPage.tsx",
24
+ "app/Http/Controllers/McpOAuthController.ts",
25
+ MCP_OAUTH_ROUTES_FILE
26
+ ];
27
+ /**
28
+ * The registrar the routes template exports. Named here because two places spell
29
+ * it — the template and the wiring instruction the scaffold prints — and a
30
+ * rename updating only one would print an import of a missing function.
31
+ */
32
+ const MCP_OAUTH_REGISTRAR = "registerMcpOAuthRoutes";
33
+ /** Read one shipped template, `path` in POSIX form and relative to the tree. */
34
+ function loadMcpOAuthTemplate(path) {
35
+ return readFileSync(join(templateDir, ...path.split("/")), "utf8");
36
+ }
37
+ //#endregion
38
+ //#region src/build.ts
39
+ /**
40
+ * Assemble a deployable Cloudflare Workers directory (`.cloudflare/`) from a
41
+ * built Guren app: a generated worker entry that statically wires the SSR
42
+ * bundle, static assets for Workers Static Assets, and a one-time
43
+ * `wrangler.jsonc` scaffold. Deploy with `wrangler deploy`.
44
+ */
45
+ async function buildCloudflareOutput(options = {}) {
46
+ const root = resolvePathLike(options.rootDir ?? process.cwd());
47
+ const out = resolvePathLike(options.outputDir ?? resolve(root, ".cloudflare"));
48
+ const appEntry = resolvePathLike(options.appEntry ?? resolve(root, "src/app.ts"));
49
+ const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
50
+ const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
51
+ const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
52
+ const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
53
+ assertOutputDirOutsideRoot(out, root, "Cloudflare build");
54
+ assertWranglerJsoncIsAuthoritative(root);
55
+ const packageJson = readPackageJson(root);
56
+ const mcpPlugin = appUsesMcpPlugin(root);
57
+ const mcpOAuth = options.mcpOAuth === true;
58
+ const mcpPath = options.mcpPath ?? DEFAULT_MCP_PATH;
59
+ assertMcpTransportNotAliased(root, mcpPlugin);
60
+ if (mcpOAuth) {
61
+ assertMcpOAuthUsable(root, mcpPlugin);
62
+ assertOAuthKvBound(root);
63
+ }
64
+ const hostsAgents = existsSync(resolve(root, AGENTS_CONFIG_FILE));
65
+ if (hostsAgents) assertAgentsPluginUsable(root);
66
+ const agents = hostsAgents ? await readAgentRegistry(root) : NO_AGENTS;
67
+ const agentBindings = assertAgentDurableObjects(root, agents.exports);
68
+ warnUnroutedAgents(agents);
69
+ if (!options.skipAppBuild) runAppBuild(root, packageJson.scripts ?? {});
70
+ if (!existsSync(appEntry)) throw new Error(`Cloudflare build: app entry not found at ${appEntry}. Pass "appEntry" if your Application lives elsewhere.`);
71
+ const ssrImport = await resolveSsrImport(ssrDir, ssrEntryKey);
72
+ const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Cloudflare build");
73
+ const viteManifest = clientManifestJson(publicDir);
74
+ resetOutputDir(out, root, "Cloudflare build");
75
+ stageStaticAssets(publicDir, resolve(out, "assets"));
76
+ writeAssetHeaders(resolve(out, "assets"));
77
+ const workerEnv = renderWorkerEnvModule({
78
+ assetEnv,
79
+ viteManifest
80
+ });
81
+ if (workerEnv) writeFileSync(resolve(out, "worker-env.js"), workerEnv);
82
+ writeFileSync(resolve(out, "worker.js"), renderWorkerModule({
83
+ out,
84
+ appEntry,
85
+ ssrImport,
86
+ hasEnvModule: workerEnv !== void 0,
87
+ mcpOAuth,
88
+ mcpPath,
89
+ root,
90
+ agents: agents.exports,
91
+ agentBindings
92
+ }));
93
+ flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, "d1-migrations"));
94
+ writeDevOnlyStubs(out);
95
+ if (mcpOAuth) scaffoldConsentFlow(root);
96
+ scaffoldWranglerConfig(root, out, packageJson.name, mcpPlugin, mcpOAuth, agents.exports);
97
+ }
98
+ const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on Cloudflare Workers — it generates files on disk.";
99
+ /** `mcpPlugin()`'s own default mount path — see `BuildCloudflareOutputOptions.mcpPath`. */
100
+ const DEFAULT_MCP_PATH = "/mcp";
101
+ /** The OAuth provider package the generated worker imports, installed by the app. */
102
+ const OAUTH_PROVIDER_PACKAGE = "@cloudflare/workers-oauth-provider";
103
+ /** The subpath of `@guren/plugin-mcp` carrying the principal seam. */
104
+ const MCP_OAUTH_SEAM_SPECIFIER = "@guren/plugin-mcp/oauth";
105
+ /** The KV binding name `OAuthProvider` requires, fixed by the provider. */
106
+ const OAUTH_KV_BINDING = "OAUTH_KV";
107
+ /** The three endpoints the provider owns or hands back, in one place. */
108
+ const OAUTH_ENDPOINTS = {
109
+ authorize: "/oauth/authorize",
110
+ token: "/oauth/token",
111
+ register: "/oauth/register"
112
+ };
113
+ /**
114
+ * Refuse `--mcp-oauth` on an app that cannot serve it, before anything is built.
115
+ * Both prerequisites are the app's own `dependencies`: `@guren/plugin-mcp` (else
116
+ * there is no endpoint to front and the seam module is not installed) and
117
+ * `@cloudflare/workers-oauth-provider`, which wrangler resolves from the *app's*
118
+ * `node_modules` at `wrangler deploy`, from a production install — not devDeps.
119
+ */
120
+ function assertMcpOAuthUsable(root, mcpPlugin) {
121
+ if (!mcpPlugin) throw new Error(`Cloudflare build: --mcp-oauth fronts the App MCP endpoint with an OAuth provider, but this app does not depend on ${MCP_PLUGIN_PACKAGE}, so it serves no such endpoint. Install and mount the plugin first:\n bun add ${MCP_PLUGIN_PACKAGE}\n # then add mcpPlugin() to createApp({ providers })
122
+ Or drop --mcp-oauth to build the worker without the OAuth wrapping.`);
123
+ if (!appDependsOn(root, OAUTH_PROVIDER_PACKAGE)) throw new Error(`Cloudflare build: --mcp-oauth generates a worker that imports ${OAUTH_PROVIDER_PACKAGE}, which this app does not depend on. Install it:\n bun add ${OAUTH_PROVIDER_PACKAGE}\nIt is not a dependency of @guren/plugin-cloudflare on purpose — only apps fronting the MCP endpoint with OAuth need it. A devDependency will not do: wrangler resolves the import at deploy time, from a production install.`);
124
+ }
125
+ /**
126
+ * `OAuthProvider` stores clients, grants and tokens in a KV namespace bound as
127
+ * `OAUTH_KV`, with no default: unbound, the worker deploys and fails on its
128
+ * first authorize request. Checked only while the flag is on. A fresh scaffold
129
+ * gets the entry written; an existing `wrangler.jsonc` fails rather than warns,
130
+ * since the fix is exact JSON. Unparseable configs: {@link warnMissingBuildOwnedKeys}.
131
+ */
132
+ function assertOAuthKvBound(root) {
133
+ const configPath = resolve(root, "wrangler.jsonc");
134
+ const config = readWranglerConfig(configPath);
135
+ if (!config) return;
136
+ const bound = oauthKvBinding(config);
137
+ if (bound) {
138
+ if (bound.id === oauthKvNamespace().id) console.warn(`Cloudflare build: ${configPath} still has the scaffolded placeholder id for the ${OAUTH_KV_BINDING} binding, so a real deploy will be rejected. Create the namespace and paste its id in:\n wrangler kv namespace create ${OAUTH_KV_BINDING}`);
139
+ return;
140
+ }
141
+ throw new Error(`Cloudflare build: --mcp-oauth needs a KV namespace bound as ${OAUTH_KV_BINDING} — the OAuth provider stores its clients, grants and tokens there — and ${configPath} has none. Create one and add this entry, alongside whatever the file already has:\n "kv_namespaces": [\n ${JSON.stringify(oauthKvNamespace(), null, 2).split("\n").join("\n ")}\n ]\nGet the id from: wrangler kv namespace create ${OAUTH_KV_BINDING}`);
142
+ }
143
+ /**
144
+ * The KV namespace a parsed config binds under the provider's name, or
145
+ * `undefined`. Returns the entry rather than a boolean because callers ask both
146
+ * "is it bound" and "is its id still the placeholder" of the same match.
147
+ */
148
+ function oauthKvBinding(config) {
149
+ const namespaces = config.kv_namespaces;
150
+ if (!Array.isArray(namespaces)) return;
151
+ return namespaces.find((entry) => isRecord(entry) && entry.binding === OAUTH_KV_BINDING);
152
+ }
153
+ /** The binding entry, spelled once — the scaffold writes it, the guard quotes it. */
154
+ function oauthKvNamespace() {
155
+ return {
156
+ binding: OAUTH_KV_BINDING,
157
+ id: `TODO: wrangler kv namespace create ${OAUTH_KV_BINDING}`
158
+ };
159
+ }
160
+ /**
161
+ * Whether the app declares `name` under `dependencies`. Same answer-shape as
162
+ * `appUsesMcpPlugin` in `@guren/core/internal/deploy-build`: an absent,
163
+ * unreadable or malformed manifest answers `false`.
164
+ */
165
+ function appDependsOn(root, name) {
166
+ try {
167
+ const dependencies = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).dependencies;
168
+ return typeof dependencies === "object" && dependencies !== null && name in dependencies;
169
+ } catch {
170
+ return false;
171
+ }
172
+ }
173
+ /** The package the generated worker imports the agent runtime and router from. */
174
+ const AGENTS_PLUGIN_PACKAGE = "@guren/plugin-agents";
175
+ /** Its two subpaths: the boot seam, and the workerd-only routing half. */
176
+ const AGENTS_RUNTIME_SPECIFIER = `${AGENTS_PLUGIN_PACKAGE}/runtime`;
177
+ const AGENTS_ROUTER_SPECIFIER = `${AGENTS_PLUGIN_PACKAGE}/agent`;
178
+ const NO_AGENTS = {
179
+ exports: [],
180
+ routing: false
181
+ };
182
+ /**
183
+ * Read `config/agents.ts` by evaluating it, the way `guren dev` does. RFC 0017
184
+ * §3's static grammar is what makes that safe here: literal strings, nothing
185
+ * imported from `agents` or `cloudflare:workers`, so it evaluates on Bun.
186
+ * Duck-typed rather than typed against the plugin, which this package
187
+ * deliberately does not depend on.
188
+ */
189
+ async function readAgentRegistry(root) {
190
+ const configPath = resolve(root, AGENTS_CONFIG_FILE);
191
+ let module;
192
+ try {
193
+ module = await import(pathToFileURL(configPath).href);
194
+ } catch (error) {
195
+ throw new Error(`Cloudflare build: could not evaluate ${AGENTS_CONFIG_FILE} on Bun: ${error instanceof Error ? error.message : String(error)}\nThe registry is evaluated outside workerd, so nothing it imports may exist only there (\`agents\`, \`cloudflare:workers\`). Keep the agent classes in their own modules and name them by path.`, { cause: error });
196
+ }
197
+ const config = module.default;
198
+ if (!isRecord(config) || !isRecord(config.agents)) throw new Error(`Cloudflare build: ${AGENTS_CONFIG_FILE} does not default-export a config with an "agents" object, so this build cannot tell which classes are Durable Objects. Write it as:\n export default defineAgentsConfig({ agents: { triager: { module: 'app/Agents/Triager.ts', export: 'Triager', scopes: ['tools:read'] } } })`);
199
+ const exports = [];
200
+ const claimed = /* @__PURE__ */ new Map();
201
+ const claimedBindings = /* @__PURE__ */ new Map();
202
+ for (const [agent, registration] of Object.entries(config.agents)) {
203
+ const fields = isRecord(registration) ? registration : {};
204
+ const modulePath = fields.module;
205
+ const exportName = fields.export;
206
+ if (typeof modulePath !== "string" || modulePath.trim() === "") throw new Error(agentRegistrationError(agent, "has no `module`", "module: 'app/Agents/Triager.ts'"));
207
+ if (typeof exportName !== "string" || !IDENTIFIER_PATTERN.test(exportName) || exportName === "default") throw new Error(agentRegistrationError(agent, `names the export ${JSON.stringify(exportName)}, which is not a usable class name — the generated worker writes it into an \`export { … }\` line`, "export: 'Triager'"));
208
+ const file = resolve(root, modulePath);
209
+ if (!isInside(root, file) || !existsSync(file)) throw new Error(agentRegistrationError(agent, `names the module "${modulePath}", which is not a file inside this app`, "module: 'app/Agents/Triager.ts'"));
210
+ const claimedBy = claimed.get(exportName);
211
+ if (claimedBy !== void 0) throw new Error(`Cloudflare build: ${AGENTS_CONFIG_FILE} registers the export "${exportName}" for both "${claimedBy}" and "${agent}". One class is one agent: the generated worker exports each name once, and a Durable Object binding names exactly one class.`);
212
+ claimed.set(exportName, agent);
213
+ const binding = durableObjectBindingName(exportName);
214
+ const bindingClaimedBy = claimedBindings.get(binding);
215
+ if (bindingClaimedBy !== void 0) throw new Error(`Cloudflare build: ${AGENTS_CONFIG_FILE} registers the exports "${bindingClaimedBy}" and "${exportName}", which both scaffold the Durable Object binding "${binding}". Rename one so each class gets a binding of its own.`);
216
+ claimedBindings.set(binding, exportName);
217
+ exports.push({
218
+ agent,
219
+ module: modulePath,
220
+ export: exportName
221
+ });
222
+ }
223
+ return {
224
+ exports,
225
+ routing: hasRouting(config)
226
+ };
227
+ }
228
+ /**
229
+ * `routing` is absent or an object with a callable `authorize`. Anything else
230
+ * (`routing: {}`, `authorize: true`) would be refused at request time as
231
+ * unconfigured while the build stayed silent — the one diagnostic this
232
+ * feature offers, defeated by a typo.
233
+ */
234
+ function hasRouting(config) {
235
+ const routing = config.routing;
236
+ if (routing === void 0) return false;
237
+ if (isRecord(routing) && typeof routing.authorize === "function") return true;
238
+ throw new Error(`Cloudflare build: ${AGENTS_CONFIG_FILE} declares "routing" without a callable "authorize", so it neither opens /agents/* nor reads as the deny-all default. Write \`routing: { authorize: (request, target) => … }\`, or remove "routing" to keep every request refused.`);
239
+ }
240
+ /** What a JavaScript `export { … }` clause will accept as a name. */
241
+ const IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
242
+ function agentRegistrationError(agent, problem, fix) {
243
+ return `Cloudflare build: the agent "${agent}" in ${AGENTS_CONFIG_FILE} ${problem}. The generated worker needs both a module and an export name to write \`export { Class } from '…'\`, or the Durable Object binding points at nothing. Fix: \`${fix}\`.`;
244
+ }
245
+ /** Whether `target` is the directory `root` or something under it. */
246
+ function isInside(root, target) {
247
+ const rel = relative(root, target);
248
+ return rel !== "" && !rel.startsWith("..") && !rel.startsWith(`..${sep}`);
249
+ }
250
+ function isRecord(value) {
251
+ return typeof value === "object" && value !== null && !Array.isArray(value);
252
+ }
253
+ /**
254
+ * Refuse an app hosting agents that did not install the plugin, before anything
255
+ * is built. Same shape as {@link assertMcpOAuthUsable}: wrangler resolves the
256
+ * generated worker's imports at deploy time, from a *production* install, so a
257
+ * devDependency does not answer.
258
+ */
259
+ function assertAgentsPluginUsable(root) {
260
+ if (appDependsOn(root, AGENTS_PLUGIN_PACKAGE)) return;
261
+ throw new Error(`Cloudflare build: ${AGENTS_CONFIG_FILE} registers durable agents, so the generated worker imports ${AGENTS_PLUGIN_PACKAGE} — which this app does not depend on. Install it:\n bun add ${AGENTS_PLUGIN_PACKAGE}\n # then add agentsPlugin(agents) to createApp({ providers })\nA devDependency will not do: wrangler resolves the import at deploy time, from a production install. Or delete ${AGENTS_CONFIG_FILE} to build a worker without agents.`);
262
+ }
263
+ /**
264
+ * Say once, at build time, that the mount the worker just gained refuses
265
+ * everything. Nothing else reports it: the deploy succeeds, the agents run on
266
+ * their alarms, and only an inbound request meets the 403.
267
+ */
268
+ function warnUnroutedAgents(agents) {
269
+ if (agents.exports.length === 0 || agents.routing) return;
270
+ console.warn(`Cloudflare build: ${AGENTS_CONFIG_FILE} declares no "routing", so /agents/* on the generated worker refuses every request with 403 and no Durable Object is constructed. That is the default on purpose (RFC 0017 §6). To let callers in, add:\n routing: { authorize: (request, target) => /* your check */ false }`);
271
+ }
272
+ /**
273
+ * Verify the committed config hosts every registered agent, before the app
274
+ * build, and return the binding names that host them — the generated worker's
275
+ * routing allowlist. Both halves are required: a class with no `durable_objects`
276
+ * binding is unreachable, and one that is not SQLite-backed cannot host an
277
+ * `Agent` (the SDK keeps state, schedules and bookkeeping in Durable Object SQLite).
278
+ */
279
+ function assertAgentDurableObjects(root, agents) {
280
+ if (agents.length === 0) return [];
281
+ const configPath = resolve(root, "wrangler.jsonc");
282
+ if (!existsSync(configPath)) return agents.map((agent) => durableObjectBindingName(agent.export));
283
+ const config = readWranglerConfig(configPath);
284
+ if (!config) {
285
+ console.warn(`Cloudflare build: could not parse ${configPath}, so the Durable Object configuration for the registered agents went unchecked. An agent with no binding deploys and then answers nothing, and /agents/* will refuse every binding.`);
286
+ return [];
287
+ }
288
+ const bindings = /* @__PURE__ */ new Set();
289
+ for (const scope of configScopes(config)) {
290
+ assertAgentScopeHosts(configPath, scope, config, agents);
291
+ for (const binding of registeredBindings(scope.config, agents)) bindings.add(binding.name);
292
+ }
293
+ return [...bindings];
294
+ }
295
+ function configScopes(config) {
296
+ const scopes = [{
297
+ label: "",
298
+ config
299
+ }];
300
+ if (isRecord(config.env)) {
301
+ for (const [name, environment] of Object.entries(config.env)) if (isRecord(environment)) scopes.push({
302
+ label: ` (env.${name})`,
303
+ config: environment
304
+ });
305
+ }
306
+ return scopes;
307
+ }
308
+ /** One scope's verdict: mangling refused, every registered class bound and SQLite-backed. */
309
+ function assertAgentScopeHosts(configPath, scope, topLevel, agents) {
310
+ const where = `${configPath}${scope.label}`;
311
+ if ((scope.config.minify ?? topLevel.minify) === true) throw new Error(`Cloudflare build: ${where} sets "minify": true, and this app hosts agents. wrangler's minifier renames identifiers, and an agent class is looked up by its runtime name — mangled, every tool call fails with "is not registered" after a deploy that looked fine. Remove "minify" from the config.`);
312
+ const bound = new Set(registeredBindings(scope.config, agents).map((binding) => binding.class_name));
313
+ const sqlite = sqliteBackedClasses(Array.isArray(scope.config.migrations) || isRecord(scope.config.exports) ? scope.config : topLevel);
314
+ const unbound = agents.filter((agent) => !bound.has(agent.export));
315
+ const unbacked = agents.filter((agent) => !sqlite.has(agent.export));
316
+ if (unbound.length === 0 && unbacked.length === 0) return;
317
+ const fixes = [];
318
+ if (unbound.length > 0) {
319
+ const bindings = unbound.map((agent) => ({
320
+ name: durableObjectBindingName(agent.export),
321
+ class_name: agent.export
322
+ }));
323
+ fixes.push(indentJson({ durable_objects: { bindings } }));
324
+ }
325
+ if (unbacked.length > 0) {
326
+ const classes = unbacked.map((agent) => agent.export);
327
+ fixes.push(indentJson({ migrations: [{
328
+ tag: nextMigrationTag(topLevel),
329
+ new_sqlite_classes: classes
330
+ }] }));
331
+ }
332
+ const names = [...new Set([...unbound, ...unbacked].map((agent) => agent.export))].join(", ");
333
+ throw new Error(`Cloudflare build: ${where} does not host the registered agent(s) ${names} as SQLite-backed Durable Objects. Add these entries, alongside whatever the file already has under the same keys:\n${fixes.join("\n")}\nThe declarative form is accepted too — \`"exports": { "Triager": { "type": "durable-object", "storage": "sqlite" } }\` — but wrangler treats it as mutually exclusive with "migrations", so use one or the other.`);
334
+ }
335
+ /** `Triager` → `TRIAGER`, `TriagerAgent` → `TRIAGER_AGENT`. */
336
+ function durableObjectBindingName(exportName) {
337
+ return exportName.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
338
+ }
339
+ function indentJson(value) {
340
+ return ` ${JSON.stringify(value, null, 2).slice(1, -1).trim()}`.replace(/\n/g, "\n ");
341
+ }
342
+ /**
343
+ * The bindings in one scope whose class is a registered agent. A binding with a
344
+ * `script_name` points at another Worker's class, not at the export this build
345
+ * generates, so it is neither hosting nor routable here.
346
+ */
347
+ function registeredBindings(config, agents) {
348
+ const registered = new Set(agents.map((agent) => agent.export));
349
+ const durableObjects = config.durable_objects;
350
+ const hosting = [];
351
+ for (const entry of asArray(isRecord(durableObjects) ? durableObjects.bindings : void 0)) {
352
+ if (!isRecord(entry)) continue;
353
+ const { name, class_name: className, script_name: scriptName } = entry;
354
+ if (scriptName !== void 0) continue;
355
+ if (typeof name !== "string" || typeof className !== "string") continue;
356
+ if (!registered.has(className)) continue;
357
+ hosting.push({
358
+ name,
359
+ class_name: className
360
+ });
361
+ }
362
+ return hosting;
363
+ }
364
+ /**
365
+ * Classes wrangler will give a SQLite storage backend, in either form. The
366
+ * `migrations` list is *history*, folded in order: a class created in `v1` and
367
+ * deleted in `v2` is gone, a rename carries the backend to the new name. A
368
+ * declarative `exports` entry counts while it is live — `created` (the default)
369
+ * or `expecting-transfer` — and `deleted`/`renamed` declare the class gone.
370
+ */
371
+ function sqliteBackedClasses(config) {
372
+ const classes = /* @__PURE__ */ new Set();
373
+ for (const migration of asArray(config.migrations)) {
374
+ if (!isRecord(migration)) continue;
375
+ for (const name of strings(migration.new_sqlite_classes)) classes.add(name);
376
+ for (const rename of asArray(migration.renamed_classes)) {
377
+ if (!isRecord(rename) || typeof rename.from !== "string" || typeof rename.to !== "string") continue;
378
+ if (classes.delete(rename.from)) classes.add(rename.to);
379
+ }
380
+ for (const name of strings(migration.deleted_classes)) classes.delete(name);
381
+ }
382
+ const exported = config.exports;
383
+ if (isRecord(exported)) for (const [name, entry] of Object.entries(exported)) {
384
+ if (!isRecord(entry)) continue;
385
+ const live = entry.state === void 0 || entry.state === "created" || entry.state === "expecting-transfer";
386
+ if (entry.type === "durable-object" && entry.storage === "sqlite" && live) classes.add(name);
387
+ }
388
+ return classes;
389
+ }
390
+ function asArray(value) {
391
+ return Array.isArray(value) ? value : [];
392
+ }
393
+ function strings(value) {
394
+ return asArray(value).filter((entry) => typeof entry === "string");
395
+ }
396
+ /** The tag after the highest `v<n>` already in the file, or `v1`. */
397
+ function nextMigrationTag(config) {
398
+ const migrations = Array.isArray(config.migrations) ? config.migrations : [];
399
+ let highest = 0;
400
+ for (const migration of migrations) {
401
+ const tag = isRecord(migration) ? migration.tag : void 0;
402
+ const match = typeof tag === "string" ? /^v(\d+)$/.exec(tag) : null;
403
+ if (match) highest = Math.max(highest, Number(match[1]));
404
+ }
405
+ return `v${highest + 1}`;
406
+ }
407
+ /**
408
+ * Both lists: on Workers the SQL clients are as unreachable as the dev-only
409
+ * modules, because D1 is the only database the platform has.
410
+ */
411
+ const STUBBED_MODULES = [...DEV_ONLY_MODULES, ...SQL_CLIENT_MODULES];
412
+ /**
413
+ * Why the stubbed modules cannot run here, worded for this platform: each
414
+ * names the Workers-appropriate replacement.
415
+ */
416
+ const UNAVAILABLE_ON_WORKERS = {
417
+ sqlite: "bun:sqlite is unavailable on Cloudflare Workers — use createD1Database().",
418
+ vite: "The Vite dev server is unavailable on Cloudflare Workers — assets are served by Workers Static Assets.",
419
+ mcp: MCP_UNAVAILABLE,
420
+ "sql-driver": "This database client is unavailable on Cloudflare Workers — use createD1Database(). It is stubbed because @guren/orm names it in a dynamic import that bundlers follow even when the branch cannot be taken."
421
+ };
422
+ /**
423
+ * Wrangler resolves an `alias` to a path on disk, so each stub needs a file of
424
+ * its own. The names are hand-written rather than derived: they are baked into
425
+ * every app's committed `wrangler.jsonc`, which the scaffold never overwrites.
426
+ * Keyed on `DevOnlySpecifier`, so a new `DEV_ONLY_MODULES` entry is a compile
427
+ * error here until it gets a filename.
428
+ */
429
+ const STUB_FILES = {
430
+ "bun:sqlite": "stub-bun-sqlite.js",
431
+ vite: "stub-vite.js",
432
+ "@guren/cli": "stub-guren-cli.js",
433
+ "@modelcontextprotocol/sdk/server/mcp.js": "stub-mcp-server.js",
434
+ "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js": "stub-mcp-transport.js",
435
+ postgres: "stub-postgres.js",
436
+ mysql2: "stub-mysql2.js",
437
+ "mysql2/promise": "stub-mysql2-promise.js",
438
+ "@aws-sdk/client-rds-data": "stub-rds-data.js"
439
+ };
440
+ function writeDevOnlyStubs(out) {
441
+ for (const module of STUBBED_MODULES) writeFileSync(resolve(out, STUB_FILES[module.specifier]), renderDevOnlyStub(module, UNAVAILABLE_ON_WORKERS[module.kind]));
442
+ }
443
+ /**
444
+ * A package-name alias does not cover subpaths and wrangler cannot match a
445
+ * prefix, so every stubbed specifier needs its own entry (an SDK subpath added
446
+ * upstream needs a new `DEV_ONLY_MODULES` entry). `mcpPlugin` drops only the App
447
+ * MCP transport's alias (RFC 0016 §7; the adapter is workerd-compatible). Stub
448
+ * *files* are written unconditionally, so a config still pointing at one keeps finding it.
449
+ */
450
+ function devOnlyAliases(outRelative, mcpPlugin) {
451
+ const stubbed = [...stubbableDevOnlyModules({ mcpPlugin }), ...SQL_CLIENT_MODULES];
452
+ return Object.fromEntries(stubbed.map((module) => [module.specifier, `./${outRelative}/${STUB_FILES[module.specifier]}`]));
453
+ }
454
+ /**
455
+ * Fail rather than deploy an app declaring `@guren/plugin-mcp` while its committed
456
+ * `wrangler.jsonc` aliases the App MCP transport to a stub *this build generated*:
457
+ * the endpoint stays compiled shut with every gate green. The *value* decides
458
+ * (another target is a deliberate override), matched on the last path segment of
459
+ * either separator against `STUB_FILES`; `parseJsonc` keeps comments from matching.
460
+ */
461
+ function assertMcpTransportNotAliased(root, mcpPlugin) {
462
+ if (!mcpPlugin) return;
463
+ const configPath = resolve(root, "wrangler.jsonc");
464
+ const alias = readWranglerConfig(configPath)?.alias;
465
+ if (!isRecord(alias)) return;
466
+ const target = alias[MCP_TRANSPORT_SPECIFIER];
467
+ if (typeof target !== "string" || target.split(/[\\/]/).pop() !== STUB_FILES[MCP_TRANSPORT_SPECIFIER]) return;
468
+ throw new Error(`Cloudflare build: ${configPath} aliases the App MCP transport to a stub, but this app depends on ${MCP_PLUGIN_PACKAGE} — the endpoint would deploy compiled shut. Delete this one line from "alias":\n ${JSON.stringify(MCP_TRANSPORT_SPECIFIER)}: ${JSON.stringify(target)}\nLeave every other alias entry in place; ${JSON.stringify("@modelcontextprotocol/sdk/server/mcp.js")} in particular must stay stubbed — that is the dev-only MCP server, which generates files on disk.`);
469
+ }
470
+ /**
471
+ * Wrangler's `migrations_dir` only discovers flat `*.sql` files, but drizzle-kit
472
+ * (1.x) emits one `<timestamp>_<name>/migration.sql` folder per migration.
473
+ * Flatten each folder into `<folder-name>.sql` (plain `*.sql` files pass
474
+ * through, `meta/` is skipped) so `wrangler d1 migrations apply` sees them in
475
+ * filename order. Regenerated on every build — run `cloudflare:build` after adding one.
476
+ */
477
+ function flattenD1Migrations(migrationsDir, outDir) {
478
+ if (!existsSync(migrationsDir)) return;
479
+ const entries = readdirSync(migrationsDir, { withFileTypes: true });
480
+ const copies = [];
481
+ for (const entry of entries) {
482
+ if (entry.isFile() && entry.name.endsWith(".sql")) {
483
+ copies.push({
484
+ from: resolve(migrationsDir, entry.name),
485
+ to: entry.name
486
+ });
487
+ continue;
488
+ }
489
+ if (entry.isDirectory() && entry.name !== "meta") {
490
+ const nested = resolve(migrationsDir, entry.name, "migration.sql");
491
+ if (existsSync(nested)) copies.push({
492
+ from: nested,
493
+ to: `${entry.name}.sql`
494
+ });
495
+ }
496
+ }
497
+ const seen = /* @__PURE__ */ new Map();
498
+ for (const copy of copies) {
499
+ const clash = seen.get(copy.to);
500
+ if (clash) throw new Error(`Cloudflare build: migrations "${clash}" and "${copy.from}" both flatten to "${copy.to}". Rename one so wrangler sees a stable order.`);
501
+ seen.set(copy.to, copy.from);
502
+ }
503
+ if (existsSync(outDir)) rmSync(outDir, {
504
+ recursive: true,
505
+ force: true
506
+ });
507
+ if (copies.length === 0) return;
508
+ mkdirSync(outDir, { recursive: true });
509
+ for (const copy of copies) cpSync(copy.from, resolve(outDir, copy.to));
510
+ }
511
+ /**
512
+ * Neutralize the document types staged under `assets/` with a `_headers` file:
513
+ * Static Assets answer before the worker runs, so `guardStaticDocument` never
514
+ * sees one and an SVG would render inline, script and all, on the app's origin.
515
+ * One splat per pattern: /*.svg matches at any depth, and a second splat is a
516
+ * parse error the platform reports by *dropping the rule*.
517
+ */
518
+ function renderAssetHeaders(assetsOut) {
519
+ const headerLines = Object.entries(DOCUMENT_ASSET_HEADERS).map(([name, value]) => ` ${name}: ${value}`);
520
+ return [
521
+ "# Generated by `guren cloudflare:build`. Do not edit — regenerate instead.",
522
+ ...[...DOCUMENT_ASSET_EXTENSIONS.map((extension) => `/*.${extension}`), ...oddlyCasedDocumentPaths(assetsOut)].flatMap((pattern) => [
523
+ "",
524
+ pattern,
525
+ ...headerLines
526
+ ]),
527
+ ""
528
+ ].join("\n");
529
+ }
530
+ /**
531
+ * Staged document files whose extension is not already lowercase, as exact
532
+ * patterns: the one hole the `/*.<ext>` globs cannot reach. `getMimeType`
533
+ * lowercases before its lookup while Cloudflare compiles a `_headers` pattern
534
+ * case-sensitively (measured), and `.svg` alone has eight spellings at one splat
535
+ * per rule. Exact rules are complete: the asset set is closed at build time.
536
+ */
537
+ function oddlyCasedDocumentPaths(assetsOut) {
538
+ const documents = new Set(DOCUMENT_ASSET_EXTENSIONS);
539
+ const paths = [];
540
+ const walk = (dir, prefix) => {
541
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
542
+ if (entry.isDirectory()) {
543
+ walk(resolve(dir, entry.name), `${prefix}/${entry.name}`);
544
+ continue;
545
+ }
546
+ const dot = entry.name.lastIndexOf(".");
547
+ const extension = dot === -1 ? "" : entry.name.slice(dot + 1);
548
+ if (extension && extension !== extension.toLowerCase() && documents.has(extension.toLowerCase())) paths.push(`${prefix}/${entry.name}`);
549
+ }
550
+ };
551
+ walk(assetsOut, "");
552
+ return paths.sort();
553
+ }
554
+ /**
555
+ * An app may ship its own `_headers` under `public/`, already copied here by
556
+ * `stageStaticAssets`. Prepend rather than append: only the *first* rule naming
557
+ * a header sets it and a later one appends, so going second would turn an app's
558
+ * own `Content-Disposition` into "inline, attachment". The cost, warned about
559
+ * rather than resolved: these rules push the app's own toward the 100-rule cap.
560
+ */
561
+ function writeAssetHeaders(assetsOut) {
562
+ const headersFile = resolve(assetsOut, "_headers");
563
+ let existing = "";
564
+ try {
565
+ existing = readFileSync(headersFile, "utf8");
566
+ } catch (error) {
567
+ if (error.code !== "ENOENT") throw error;
568
+ }
569
+ const generated = renderAssetHeaders(assetsOut);
570
+ const merged = existing ? `${generated}\n${existing}` : generated;
571
+ warnHeaderRuleBudget(merged, existing);
572
+ writeFileSync(headersFile, merged);
573
+ }
574
+ /** What the platform parses before it stops. */
575
+ const HEADER_RULE_LIMIT = 100;
576
+ /**
577
+ * Say so when the rules added here push an app's own past what the platform
578
+ * reads: Cloudflare parses at most 100 rules and *stops* at the hundredth
579
+ * silently, so going first — which the set-versus-append reasoning above
580
+ * requires — drops the app's last rules. Counted, not resolved: app rules first
581
+ * would let its `Content-Disposition` turn ours into "inline, attachment".
582
+ */
583
+ function warnHeaderRuleBudget(merged, existing) {
584
+ if (!existing) return;
585
+ const rules = merged.split("\n").filter((line) => line.startsWith("/")).length;
586
+ if (rules <= HEADER_RULE_LIMIT) return;
587
+ console.warn(`Cloudflare build: the merged _headers has ${rules} rules and the platform reads only ${HEADER_RULE_LIMIT}, so the last ${rules - HEADER_RULE_LIMIT} of your app's own rules are dropped without an error. The generated document rules are placed first deliberately — the platform lets a later rule only append to a header an earlier one set, so going second would turn your own Content-Disposition into "inline, attachment". Trim public/_headers to fit.`);
588
+ }
589
+ function readPackageJson(root) {
590
+ const packageJsonPath = resolve(root, "package.json");
591
+ if (!existsSync(packageJsonPath)) return {};
592
+ try {
593
+ return JSON.parse(readFileSync(packageJsonPath, "utf8"));
594
+ } catch {
595
+ return {};
596
+ }
597
+ }
598
+ function runAppBuild(root, scripts) {
599
+ if (!scripts.build) throw new Error("Cloudflare build: no \"build\" script found in package.json. Add one (codegen + vite build + vite build --ssr) or pass --skip-app-build after building manually.");
600
+ if (Bun.spawnSync({
601
+ cmd: [
602
+ "bun",
603
+ "run",
604
+ "build"
605
+ ],
606
+ cwd: root,
607
+ stdout: "inherit",
608
+ stderr: "inherit"
609
+ }).exitCode !== 0) throw new Error("Cloudflare build: the app \"build\" script failed.");
610
+ }
611
+ async function resolveSsrImport(ssrDir, ssrEntryKey) {
612
+ const file = resolveSsrEntryFile(ssrDir, ssrEntryKey, "Cloudflare build");
613
+ if (!file) {
614
+ console.warn(`Cloudflare build: no SSR manifest entry for "${ssrEntryKey}" under ${ssrDir}; generating a CSR-only worker.`);
615
+ return;
616
+ }
617
+ const module = await import(pathToFileURL(file).href);
618
+ const rendererExport = ["render", "default"].find((name) => typeof module[name] === "function");
619
+ if (!rendererExport) throw new Error(`Cloudflare build: SSR entry ${file} does not export a renderer (expected a named "render" or default export).`);
620
+ return {
621
+ file,
622
+ rendererExport
623
+ };
624
+ }
625
+ /**
626
+ * Statements assigning the build-derived environment, emitted as their own module
627
+ * because worker.js imports it *first*, the only ordering ESM import hoisting
628
+ * cannot defeat. A statement in the worker body runs after the app's module graph
629
+ * evaluated, so a module-scope `viteAsset()` call would see no manifest and throw
630
+ * before the worker could start.
631
+ */
632
+ function renderWorkerEnvModule(input) {
633
+ const lines = [];
634
+ if (input.assetEnv.entry) lines.push(`process.env.GUREN_INERTIA_ENTRY = ${JSON.stringify(input.assetEnv.entry)}`);
635
+ if (input.assetEnv.styles) lines.push(`process.env.GUREN_INERTIA_STYLES = ${JSON.stringify(input.assetEnv.styles)}`);
636
+ if (input.viteManifest) lines.push(`process.env.GUREN_VITE_MANIFEST = ${JSON.stringify(input.viteManifest)}`);
637
+ if (lines.length === 0) return;
638
+ return [
639
+ "// Generated by `guren cloudflare:build`. Do not edit — regenerate instead.",
640
+ ...lines,
641
+ ""
642
+ ].join("\n");
643
+ }
644
+ function renderWorkerModule(input) {
645
+ const hasAgents = input.agents.length > 0;
646
+ const lines = ["// Generated by `guren cloudflare:build`. Do not edit — regenerate instead."];
647
+ if (input.hasEnvModule) lines.push("import './worker-env.js'");
648
+ lines.push("import { createWorkersHandler } from '@guren/plugin-cloudflare'");
649
+ if (hasAgents) lines.push(`import { configureAgentRuntime } from ${JSON.stringify(AGENTS_RUNTIME_SPECIFIER)}`, `import { routeGuardedAgentRequest } from ${JSON.stringify(AGENTS_ROUTER_SPECIFIER)}`, `import agentsConfig from ${quotedImport(input.out, resolve(input.root, AGENTS_CONFIG_FILE))}`);
650
+ if (input.mcpOAuth) lines.push(`import { OAuthProvider } from ${JSON.stringify(OAUTH_PROVIDER_PACKAGE)}`, `import { mcpOAuthPropsToAuth, presentExternalMcpAuth } from ${JSON.stringify(MCP_OAUTH_SEAM_SPECIFIER)}`);
651
+ if (input.ssrImport) lines.push("import { setInertiaSsrRenderer } from '@guren/core'", `import * as ssrModule from ${quotedImport(input.out, input.ssrImport.file)}`);
652
+ lines.push(`import app from ${quotedImport(input.out, input.appEntry)}`, "");
653
+ if (input.ssrImport) lines.push(`setInertiaSsrRenderer(ssrModule.${input.ssrImport.rendererExport})`, "");
654
+ if (!input.mcpOAuth && !hasAgents) {
655
+ lines.push("export default createWorkersHandler(app)", "");
656
+ return lines.join("\n");
657
+ }
658
+ lines.push("const handler = createWorkersHandler(app)", "");
659
+ if (hasAgents) lines.push(renderAgentWiring(input.out, input.root, input.agents, input.agentBindings), "");
660
+ const entry = hasAgents ? "agentEntry" : "handler";
661
+ lines.push(input.mcpOAuth ? renderOAuthWorker(input.mcpPath, entry) : `export default ${entry}`, "");
662
+ return lines.join("\n");
663
+ }
664
+ /** An import specifier for the generated worker, relative to it and quoted. */
665
+ function quotedImport(out, target) {
666
+ return JSON.stringify(importSpecifier(out, target, "Cloudflare build"));
667
+ }
668
+ /**
669
+ * The agent half of the generated program: the boot seam, the Durable Object
670
+ * exports, and the guarded `/agents/*` mount. The resolver returns nothing on
671
+ * purpose — `agentsPlugin`'s own boot publishes the runtime, and returning it
672
+ * here would make the generated worker read its own latch back (RFC 0017 §6).
673
+ */
674
+ function renderAgentWiring(out, root, agents, bindings) {
675
+ return `// An alarm can wake an agent before any request has booted the app, so the
676
+ // runtime latch is handed the boot rather than a runtime.
677
+ configureAgentRuntime((env) => handler.boot(env))
678
+
679
+ ${agents.map((agent) => `export { ${agent.export} } from ${quotedImport(out, resolve(root, agent.module))}`).join("\n")}
680
+
681
+ // The Durable Object bindings wrangler.jsonc gives the registered agents. The
682
+ // SDK's router would otherwise reach every Durable Object in env.
683
+ const agentBindings = ${JSON.stringify(bindings)}
684
+
685
+ const agentEntry = {
686
+ async fetch(request, env, ctx) {
687
+ // Booted before routing, so an authorizer may read getWorkersEnv().
688
+ await handler.boot(env)
689
+ // /agents/* is deny-all until config/agents.ts declares routing.authorize.
690
+ const routed = await routeGuardedAgentRequest(request, env, agentsConfig.routing, agentBindings)
691
+ if (routed) return routed
692
+ return handler.fetch(request, env, ctx)
693
+ },
694
+ }`;
695
+ }
696
+ /**
697
+ * wrangler resolves its config as `wrangler.json` ?? `wrangler.jsonc` ??
698
+ * `wrangler.toml`, first match winning silently (workers-sdk config-helpers.ts).
699
+ * This plugin manages `wrangler.jsonc`, so a `wrangler.json` outranks everything
700
+ * it scaffolds or checks, and scaffolding beside a lone `wrangler.toml` stops
701
+ * wrangler reading the user's config. Name the migration before the app build runs.
702
+ */
703
+ function assertWranglerJsoncIsAuthoritative(root) {
704
+ if (wranglerConfigExists(resolve(root, "wrangler.json"))) throw new Error("Cloudflare build: found wrangler.json. wrangler reads it before the wrangler.jsonc this plugin manages, so the build-owned keys would never reach a deploy. Rename it to wrangler.jsonc — every JSON file is already valid JSONC.");
705
+ if (!wranglerConfigExists(resolve(root, "wrangler.toml"))) return;
706
+ if (wranglerConfigExists(resolve(root, "wrangler.jsonc"))) {
707
+ console.warn("Cloudflare build: wrangler.toml is dead weight — wrangler reads wrangler.jsonc first. Port anything still missing into wrangler.jsonc, then delete wrangler.toml so edits to it stop looking like configuration.");
708
+ return;
709
+ }
710
+ throw new Error("Cloudflare build: found wrangler.toml, but this plugin manages wrangler.jsonc — it cannot read TOML to check the build-owned keys, and scaffolding wrangler.jsonc beside it would make wrangler silently ignore wrangler.toml. Move wrangler.toml aside, rerun the build to scaffold a reference wrangler.jsonc, then port your settings into it.");
711
+ }
712
+ /**
713
+ * `existsSync` folds an unreadable entry into "absent", and absent is the
714
+ * branch that scaffolds a config file beside it — only ENOENT may mean no.
715
+ */
716
+ function wranglerConfigExists(path) {
717
+ try {
718
+ statSync(path);
719
+ return true;
720
+ } catch (error) {
721
+ if (error.code === "ENOENT") return false;
722
+ throw error;
723
+ }
724
+ }
725
+ /**
726
+ * Serve a staged `.html` file at its own path and nowhere else. The platform
727
+ * default, `auto-trailing-slash`, serves `public/page.html` at `/page` and
728
+ * *redirects* `/page.html` there (measured), which lands the /*.html `_headers`
729
+ * rule only on the redirect and lets a file under `public/` shadow the app's
730
+ * route of that name, since assets answer first. A miss falls through to the worker.
731
+ */
732
+ const HTML_HANDLING = "none";
733
+ /**
734
+ * The OAuth-fronted export: the module's one handler threaded through both
735
+ * halves of the provider. The grant travels through the seam, not a header:
736
+ * `ctx.props` is what the provider decrypted from the access token it validated.
737
+ * @param defaultEntry What unprotected paths reach — the agent-routing entry
738
+ * when this app hosts agents, so `/agents/*` stays mounted and guarded.
739
+ */
740
+ function renderOAuthWorker(mcpPath, defaultEntry) {
741
+ return `export default new OAuthProvider({
742
+ apiRoute: ${JSON.stringify(mcpPath)},
743
+ apiHandler: {
744
+ fetch(request, env, ctx) {
745
+ // ctx.props is the grant the provider decrypted from the access
746
+ // token it has already validated. A shape the endpoint cannot read
747
+ // is refused here, never forwarded as a partial principal.
748
+ const auth = mcpOAuthPropsToAuth(ctx.props)
749
+ if (!auth) {
750
+ return new Response(
751
+ JSON.stringify({
752
+ error: 'unauthorized',
753
+ message: 'This access token carries no readable grant. Re-authorize the client.',
754
+ }),
755
+ { status: 401, headers: { 'Content-Type': 'application/json' } },
756
+ )
757
+ }
758
+ // The seam is keyed on this exact Request object — dispatch the one
759
+ // presentExternalMcpAuth returns, never a copy of it.
760
+ return handler.fetch(presentExternalMcpAuth(request, auth), env, ctx)
761
+ },
762
+ },
763
+ defaultHandler: ${defaultEntry},
764
+ authorizeEndpoint: ${JSON.stringify(OAUTH_ENDPOINTS.authorize)},
765
+ tokenEndpoint: ${JSON.stringify(OAUTH_ENDPOINTS.token)},
766
+ // Dynamic client registration (RFC 7591). Deprecated in the MCP
767
+ // 2026-07-28 line in favour of Client ID Metadata Documents, but it is
768
+ // what shipping MCP SDK 1.x clients use to register themselves today.
769
+ clientRegistrationEndpoint: ${JSON.stringify(OAUTH_ENDPOINTS.register)},
770
+ })`;
771
+ }
772
+ function scaffoldWranglerConfig(root, out, packageName, mcpPlugin, mcpOAuth, agents) {
773
+ const configPath = resolve(root, "wrangler.jsonc");
774
+ const appName = (packageName ?? "guren-app").replace(/^@[^/]+\//, "");
775
+ const outRelative = relative(root, out).split(sep).join("/");
776
+ const config = {
777
+ name: appName,
778
+ main: `${outRelative}/worker.js`,
779
+ compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
780
+ compatibility_flags: ["nodejs_compat"],
781
+ alias: devOnlyAliases(outRelative, mcpPlugin),
782
+ define: {
783
+ "process.env.NODE_ENV": "\"production\"",
784
+ "import.meta.url": "\"file:///worker.js\""
785
+ },
786
+ assets: {
787
+ directory: `${outRelative}/assets`,
788
+ html_handling: HTML_HANDLING
789
+ },
790
+ d1_databases: [{
791
+ binding: "DB",
792
+ database_name: appName,
793
+ database_id: "TODO: wrangler d1 create",
794
+ migrations_dir: `${outRelative}/d1-migrations`
795
+ }],
796
+ ...mcpOAuth ? { kv_namespaces: [oauthKvNamespace()] } : {},
797
+ ...agents.length > 0 ? {
798
+ durable_objects: { bindings: agents.map((agent) => ({
799
+ name: durableObjectBindingName(agent.export),
800
+ class_name: agent.export
801
+ })) },
802
+ migrations: [{
803
+ tag: "v1",
804
+ new_sqlite_classes: agents.map((agent) => agent.export)
805
+ }]
806
+ } : {},
807
+ vars: { NODE_ENV: "production" }
808
+ };
809
+ try {
810
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { flag: "wx" });
811
+ } catch (error) {
812
+ if (error.code === "EEXIST") {
813
+ warnMissingBuildOwnedKeys(configPath, outRelative, mcpPlugin, mcpOAuth);
814
+ return;
815
+ }
816
+ throw error;
817
+ }
818
+ const notes = ["fill in d1_databases[0].database_id"];
819
+ if (mcpOAuth) notes.push(`create the ${OAUTH_KV_BINDING} namespace (wrangler kv namespace create ${OAUTH_KV_BINDING}) and fill in its id`);
820
+ console.log(`Cloudflare build: scaffolded ${configPath} — ${notes.join(", and ")} before deploying.`);
821
+ }
822
+ /**
823
+ * The consent flow, written once into the app and never overwritten, on the same
824
+ * contract as `wrangler.jsonc`: these are the developer's files from the moment
825
+ * they exist. Only reached with `--mcp-oauth` on.
826
+ */
827
+ function scaffoldConsentFlow(root) {
828
+ const written = [];
829
+ for (const path of MCP_OAUTH_TEMPLATE_FILES) {
830
+ const target = resolve(root, ...path.split("/"));
831
+ mkdirSync(resolve(target, ".."), { recursive: true });
832
+ try {
833
+ writeFileSync(target, loadMcpOAuthTemplate(path), { flag: "wx" });
834
+ written.push(path);
835
+ } catch (error) {
836
+ if (error.code !== "EEXIST") throw error;
837
+ }
838
+ }
839
+ if (written.length === 0) return;
840
+ console.log(`Cloudflare build: scaffolded the OAuth consent flow — ${written.join(", ")}.`);
841
+ if (written.includes("routes/mcp-oauth.ts")) console.log(` Nothing mounts ${MCP_OAUTH_ROUTES_FILE} yet. Add these two lines to your routes entry (routes/web.ts):\n import { ${MCP_OAUTH_REGISTRAR} } from './mcp-oauth'\n ${MCP_OAUTH_REGISTRAR}(router) // inside your registrar, with its router parameter`);
842
+ }
843
+ /**
844
+ * The committed config, parsed — `undefined` when it is absent or malformed.
845
+ * Callers that must tell those apart check `existsSync` first; the rest treat
846
+ * both as nothing to read.
847
+ */
848
+ function readWranglerConfig(configPath) {
849
+ try {
850
+ return parseJsonc(readFileSync(configPath, "utf8"));
851
+ } catch {
852
+ return;
853
+ }
854
+ }
855
+ /**
856
+ * `wrangler.jsonc` carries comments in any app that has edited it, and
857
+ * `JSON.parse` rejects the first one. Only comments and trailing commas are
858
+ * stripped, the whole of what wrangler accepts beyond JSON. The scan tracks
859
+ * string literals rather than pattern-matching, because `define` holds
860
+ * `"\"file:///worker.js\""` — a `//` inside a string, with escaped quotes around it.
861
+ */
862
+ function parseJsonc(text) {
863
+ const out = [];
864
+ let index = 0;
865
+ while (index < text.length) {
866
+ const char = text[index];
867
+ if (char === "\"") {
868
+ const start = index;
869
+ index += 1;
870
+ while (index < text.length) {
871
+ if (text[index] === "\\") {
872
+ index += 2;
873
+ continue;
874
+ }
875
+ if (text[index] === "\"") {
876
+ index += 1;
877
+ break;
878
+ }
879
+ index += 1;
880
+ }
881
+ out.push(text.slice(start, index));
882
+ continue;
883
+ }
884
+ if (char === "/" && text[index + 1] === "/") {
885
+ while (index < text.length && text[index] !== "\n") index += 1;
886
+ continue;
887
+ }
888
+ if (char === "/" && text[index + 1] === "*") {
889
+ const end = text.indexOf("*/", index + 2);
890
+ index = end === -1 ? text.length : end + 2;
891
+ continue;
892
+ }
893
+ if (char === "}" || char === "]") {
894
+ let back = out.length - 1;
895
+ while (back >= 0 && /^\s+$/.test(out[back])) back -= 1;
896
+ if (back >= 0 && out[back] === ",") out.splice(back, 1);
897
+ }
898
+ out.push(char);
899
+ index += 1;
900
+ }
901
+ return JSON.parse(out.join(""));
902
+ }
903
+ /**
904
+ * The scaffold never overwrites an existing config, but `alias`, `define` and
905
+ * `migrations_dir` are build-owned invariants pointing into the output directory:
906
+ * an app scaffolded before they existed deploys a worker that cannot resolve
907
+ * `bun:sqlite` or never applies its migrations. Named per entry, never as a whole
908
+ * `"alias"`/`"define"` object, which reads as one to paste over the app's own entries.
909
+ */
910
+ function warnMissingBuildOwnedKeys(configPath, outRelative, mcpPlugin, mcpOAuth) {
911
+ const config = readWranglerConfig(configPath);
912
+ if (!config) {
913
+ console.warn(`Cloudflare build: could not parse ${configPath}, so its build-owned keys went unchecked. Fix the file, or compare it against a config scaffolded in an empty directory.`);
914
+ return;
915
+ }
916
+ const missing = [];
917
+ const alias = isRecord(config.alias) ? config.alias : {};
918
+ for (const [specifier, target] of Object.entries(devOnlyAliases(outRelative, mcpPlugin))) if (!(specifier in alias)) missing.push(`${JSON.stringify(specifier)}: ${JSON.stringify(target)} (inside "alias")`);
919
+ if (!config.define?.["process.env.NODE_ENV"]) missing.push("\"process.env.NODE_ENV\": \"\\\"production\\\"\" (inside \"define\")");
920
+ const d1 = config.d1_databases?.[0];
921
+ if (d1 && d1.migrations_dir !== `${outRelative}/d1-migrations`) missing.push(`"migrations_dir": "${outRelative}/d1-migrations" (inside d1_databases[0])`);
922
+ if (missing.length > 0) console.warn(`Cloudflare build: ${configPath} predates this plugin version. Add these entries, alongside whatever the file already has under the same keys, or the worker will fail to start or skip migrations:\n ${missing.join("\n ")}`);
923
+ warnMissingHtmlHandling(configPath, config);
924
+ warnOAuthDrift(configPath, config, mcpOAuth);
925
+ }
926
+ /**
927
+ * Kept out of `warnMissingBuildOwnedKeys`: that list's shared sentence ends "the
928
+ * worker will fail to start or skip migrations", which is not true here — adding
929
+ * this key *changes* how the app's own HTML is served, and needs saying. Warned
930
+ * only when the key is absent: any other value is a decision an app typed, and a
931
+ * config with no `assets` serves no static files for `_headers` to protect.
932
+ */
933
+ function warnMissingHtmlHandling(configPath, config) {
934
+ const assets = config.assets;
935
+ if (!assets || assets.html_handling !== void 0) return;
936
+ console.warn(`Cloudflare build: ${configPath} does not set "html_handling" under "assets", so a document staged from public/ is still served at its extensionless path — where the /*.html rule in _headers does not reach it, and where it shadows any route of that name in your app. Add "html_handling": "${HTML_HANDLING}" to close both. Note this changes how those files are served: public/about.html stops answering at /about.`);
937
+ }
938
+ /**
939
+ * The drift `--mcp-oauth` leaves detectable in the other direction: a config
940
+ * scaffolded *with* the flag (carrying `OAUTH_KV`) while today's build omitted
941
+ * it, so the replacing worker has no `OAuthProvider`, `/oauth/token` answers 404
942
+ * and every authorized client stops working with no build output mentioning
943
+ * OAuth. A warning: a non-OAuth worker from the same repository is legitimate.
944
+ */
945
+ function warnOAuthDrift(configPath, config, mcpOAuth) {
946
+ if (mcpOAuth || !oauthKvBinding(config)) return;
947
+ console.warn(`Cloudflare build: ${configPath} binds ${OAUTH_KV_BINDING}, which only an OAuth-fronted worker uses, but this build ran without --mcp-oauth. The worker it produced has no OAuth provider in it: ${OAUTH_ENDPOINTS.token} and ${OAUTH_ENDPOINTS.register} will 404 and already-authorized clients will stop working. Pass --mcp-oauth, or remove the binding if this app no longer fronts its MCP endpoint with OAuth.`);
948
+ }
949
+ //#endregion
950
+ export { flattenD1Migrations as n, buildCloudflareOutput as t };