@guren/plugin-cloudflare 0.12.3 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/commands.js CHANGED
@@ -1,5 +1,1777 @@
1
- import { a as printBundleReport, c as buildCloudflareOutput, s as reportBundleSize } from "./bundle-size-CUn3w_nY.js";
1
+ import { A as readPackageJson, C as workerName, D as readLocalMigrations, E as migrationDirArgs, O as detectCloudflareBackend, S as readWranglerConfig, T as fingerprintMigrations, b as readResolvedResources, c as reportBundleSize, d as assembleCloudflareOutput, f as assertAgentsPluginUsable, g as durableObjectStorage, h as durableObjectBindings, k as isRecord, l as OAUTH_KV_BINDING, m as configScopes, o as printBundleReport, p as buildCloudflareOutput, r as assertSizeReportable, u as asArray, v as isPlaceholderId, w as decideLayout, x as readWorkerManifest, y as readAgentRegistry } from "./bundle-size-CcXTKLKq.js";
2
+ import { a as WRANGLER_OUTPUT_DIR, i as WRANGLER_DEPLOY_CONFIG_FILE, n as D1_MIGRATIONS_DIR, o as outputDirFor, r as WORKER_MANIFEST_FILE, s as resourceName } from "./worker-manifest-16SJawlX.js";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, writeSync } from "node:fs";
4
+ import { dirname, isAbsolute, join, resolve } from "node:path";
5
+ import { ALLOW_DESTRUCTIVE_ENV, judgePendingMigrations, readEnvFileKeys, readRequiredDeployEnv } from "@guren/core/internal/deploy-plan";
2
6
  import { defineCommand } from "citty";
7
+ import { createInterface } from "node:readline/promises";
8
+ //#region src/versions.ts
9
+ /**
10
+ * The versions the cf backend is verified against (RFC 0035 §7, Appendix C): what
11
+ * `cloudflare:init` raises package.json to and what `cloudflare:deploy`'s preflight checks.
12
+ */
13
+ /** cf refuses to load cloudflare.config.ts on older Node (Appendix C row 10). */
14
+ const CF_NODE_FLOOR = "22.18.0";
15
+ /** The Wrangler cf delegates the bundle to (Appendix C row 17). */
16
+ const CF_WRANGLER_FLOOR = "4.136.0";
17
+ /** The cf release the backend's argv contract is pinned to. */
18
+ const CF_VERSION = "1.0.0-beta.18";
19
+ //#endregion
20
+ //#region src/deploy/cf-cli.ts
21
+ /**
22
+ * Every account operation `cloudflare:deploy` performs goes through the app's own
23
+ * `cf` (RFC 0035 §7). The argv here is the contract with a beta CLI, pinned by
24
+ * `cf-cli.test.ts` and checked against the real one by the GUREN_TEST_CF probe.
25
+ * A result that does not parse is `unreadable`, never an empty listing: an empty
26
+ * listing would make the plan create a resource that already exists.
27
+ */
28
+ /** `cf` prints a listing's `result` and drops `result_info`, so a full page is the only sign of another. */
29
+ const PAGE_SIZE = 100;
30
+ const MAX_PAGES = 50;
31
+ /**
32
+ * The app's `cf` or `wrangler`, run by the `node` on PATH (cf loads cloudflare.config.ts
33
+ * with it). No stdin and CI=1, so no prompt waits and none writes wrangler.jsonc.
34
+ */
35
+ function appCliRunner(root, bin) {
36
+ return (args) => {
37
+ const result = Bun.spawnSync({
38
+ cmd: [
39
+ "node",
40
+ bin,
41
+ ...args
42
+ ],
43
+ cwd: root,
44
+ env: {
45
+ ...process.env,
46
+ CI: "1"
47
+ },
48
+ stdin: "ignore",
49
+ stdout: "pipe",
50
+ stderr: "pipe"
51
+ });
52
+ return {
53
+ exitCode: result.exitCode,
54
+ stdout: result.stdout.toString(),
55
+ stderr: result.stderr.toString()
56
+ };
57
+ };
58
+ }
59
+ function listD1Databases(cf) {
60
+ return listPages(cf, ["d1", "list"], "cf d1 list", "uuid", "name");
61
+ }
62
+ function listKvNamespaces(cf) {
63
+ return listPages(cf, [
64
+ "kv",
65
+ "namespaces",
66
+ "list"
67
+ ], "cf kv namespaces list", "id", "title");
68
+ }
69
+ /** `cf auth whoami` exits 0 when logged out too, printing `{ "authenticated": false, "error": … }`. */
70
+ function checkAuth(cf) {
71
+ const result = cf(["auth", "whoami"]);
72
+ if (result.exitCode !== 0) return {
73
+ ok: false,
74
+ reason: `cf auth whoami failed: ${failureText(result)}`
75
+ };
76
+ const status = parseJson(result.stdout);
77
+ if (!isRecord(status) || !("authenticated" in status)) return {
78
+ ok: false,
79
+ reason: "cf auth whoami printed no \"authenticated\" field"
80
+ };
81
+ if (status.authenticated !== true) return {
82
+ ok: false,
83
+ reason: typeof status.error === "string" ? status.error : "not authenticated"
84
+ };
85
+ return {
86
+ ok: true,
87
+ value: true
88
+ };
89
+ }
90
+ /**
91
+ * The names `d1_migrations` records, in apply order, or `null` when the table does not
92
+ * exist yet (nothing applied). Any other failure is unreadable: guessing "nothing
93
+ * applied" would replay the whole history against live data.
94
+ */
95
+ function readMigrationTracker(cf, databaseId) {
96
+ return trackerRows(cf([
97
+ "d1",
98
+ "query",
99
+ databaseId,
100
+ "--sql",
101
+ trackerQuery(DEFAULT_TRACKER)
102
+ ]), "cf d1 query", DEFAULT_TRACKER);
103
+ }
104
+ /** The table both CLIs record applied migrations in, unless wrangler.jsonc names another (`migrations_table`). */
105
+ const DEFAULT_TRACKER = "d1_migrations";
106
+ function trackerQuery(table) {
107
+ return `select name from ${/^[A-Za-z_][A-Za-z0-9_]*$/.test(table) ? table : `"${table.replaceAll("\"", "\"\"")}"`} order by id`;
108
+ }
109
+ /** A tracker query's result: the API answers `[{ results: [...], success, meta }]`, with or without the envelope. */
110
+ function trackerRows(result, label, table) {
111
+ if (result.exitCode !== 0) {
112
+ if (failureText(result).toLowerCase().includes(`no such table: ${table.toLowerCase()}`)) return {
113
+ ok: true,
114
+ value: null
115
+ };
116
+ return {
117
+ ok: false,
118
+ reason: `${label} on the migrations table failed: ${failureText(result)}`
119
+ };
120
+ }
121
+ const statements = resultArray(parseJson(result.stdout));
122
+ const rows = names(statements?.[0] !== void 0 && isRecord(statements[0]) ? statements[0].results : void 0);
123
+ return rows ? {
124
+ ok: true,
125
+ value: rows
126
+ } : {
127
+ ok: false,
128
+ reason: `${label} printed no \`results\` rows with a \`name\` for the migrations table`
129
+ };
130
+ }
131
+ /** The secret names a deployed Worker has. Fails on a Worker that does not exist yet, too. */
132
+ function listWorkerSecrets(cf, worker) {
133
+ const result = cf([
134
+ "workers",
135
+ "secrets",
136
+ "list",
137
+ "--worker",
138
+ worker
139
+ ]);
140
+ if (result.exitCode !== 0) return {
141
+ ok: false,
142
+ reason: `cf workers secrets list failed: ${failureText(result)}`
143
+ };
144
+ const secrets = names(resultArray(parseJson(result.stdout)));
145
+ return secrets ? {
146
+ ok: true,
147
+ value: secrets
148
+ } : {
149
+ ok: false,
150
+ reason: "cf workers secrets list printed no list of named secrets"
151
+ };
152
+ }
153
+ /** The R2 API's page ceiling; a full page could hide the exact match behind it. */
154
+ const R2_PAGE_SIZE = 1e3;
155
+ /**
156
+ * The buckets named exactly as `bucketNames`, as `{ id: name, name }` since R2 has no id. Looked up
157
+ * by `--name-contains`, because a listing pages by a cursor that cf may not print.
158
+ */
159
+ function listR2Buckets(cf, bucketNames) {
160
+ const found = [];
161
+ for (const name of new Set(bucketNames)) {
162
+ const result = cf([
163
+ "r2",
164
+ "buckets",
165
+ "list",
166
+ "--name-contains",
167
+ name,
168
+ "--per-page",
169
+ String(R2_PAGE_SIZE)
170
+ ]);
171
+ if (result.exitCode !== 0) return {
172
+ ok: false,
173
+ reason: `cf r2 buckets list failed: ${failureText(result)}`
174
+ };
175
+ const value = parseJson(result.stdout);
176
+ const buckets = Array.isArray(value) ? value : resultObject(value)?.buckets;
177
+ if (!Array.isArray(buckets)) return {
178
+ ok: false,
179
+ reason: "cf r2 buckets list printed no list of buckets"
180
+ };
181
+ if (buckets.length >= R2_PAGE_SIZE) return {
182
+ ok: false,
183
+ reason: `cf r2 buckets list matched ${R2_PAGE_SIZE} or more buckets containing "${name}"`
184
+ };
185
+ const listed = names(buckets);
186
+ if (!listed) return {
187
+ ok: false,
188
+ reason: "cf r2 buckets list returned a bucket with no name"
189
+ };
190
+ if (listed.includes(name)) found.push({
191
+ id: name,
192
+ name
193
+ });
194
+ }
195
+ return {
196
+ ok: true,
197
+ value: found
198
+ };
199
+ }
200
+ /** `cf r2 buckets create`: a bucket's name is its id. */
201
+ function createR2Bucket(cf, name) {
202
+ const result = cf([
203
+ "r2",
204
+ "buckets",
205
+ "create",
206
+ "--name",
207
+ name
208
+ ]);
209
+ return result.exitCode === 0 ? {
210
+ ok: true,
211
+ value: name
212
+ } : {
213
+ ok: false,
214
+ reason: `cf r2 buckets create failed: ${failureText(result)}`
215
+ };
216
+ }
217
+ /** `cf d1 create`: the new database's id, read from `uuid`. Unparseable output is a failure, though the database may exist. */
218
+ function createD1Database(cf, name) {
219
+ return readField(cf, [
220
+ "d1",
221
+ "create",
222
+ "--name",
223
+ name
224
+ ], "cf d1 create", "uuid");
225
+ }
226
+ /** `cf kv namespaces create`: the new namespace's id. */
227
+ function createKvNamespace(cf, title) {
228
+ return readField(cf, [
229
+ "kv",
230
+ "namespaces",
231
+ "create",
232
+ "--title",
233
+ title
234
+ ], "cf kv namespaces create", "id");
235
+ }
236
+ /** The Time Travel bookmark a restore would return the database to. */
237
+ function getBookmark(cf, databaseId) {
238
+ return readField(cf, [
239
+ "d1",
240
+ "time-travel",
241
+ "get-bookmark",
242
+ databaseId
243
+ ], "cf d1 time-travel get-bookmark", "bookmark");
244
+ }
245
+ function applyMigrations(cf, databaseId, dirArgs) {
246
+ const result = cf([
247
+ "d1",
248
+ "migrations",
249
+ "apply",
250
+ databaseId,
251
+ ...dirArgs
252
+ ]);
253
+ return result.exitCode === 0 ? {
254
+ ok: true,
255
+ value: result.stdout
256
+ } : {
257
+ ok: false,
258
+ reason: `cf d1 migrations apply failed: ${failureText(result)}`
259
+ };
260
+ }
261
+ /** Stage 7: the build already evaluated, and no resource created behind the plan's back (RFC 0035 §4). */
262
+ function deployPrebuilt(cf, secretsFile) {
263
+ const result = cf([
264
+ "deploy",
265
+ "--prebuilt",
266
+ "--no-provision",
267
+ ...secretsFile ? ["--secrets-file", secretsFile] : []
268
+ ]);
269
+ return result.exitCode === 0 ? {
270
+ ok: true,
271
+ value: `${result.stdout}${result.stderr}`
272
+ } : {
273
+ ok: false,
274
+ reason: `cf deploy failed: ${failureText(result)}`
275
+ };
276
+ }
277
+ /** One string field of a single result the CLI prints. */
278
+ function readField(cf, args, label, key) {
279
+ const result = cf(args);
280
+ if (result.exitCode !== 0) return {
281
+ ok: false,
282
+ reason: `${label} failed: ${failureText(result)}`
283
+ };
284
+ const value = resultObject(parseJson(result.stdout))?.[key];
285
+ return typeof value === "string" ? {
286
+ ok: true,
287
+ value
288
+ } : {
289
+ ok: false,
290
+ reason: `${label} printed no ${key}`
291
+ };
292
+ }
293
+ /** `build` through cf's implementation protocol: evaluates cloudflare.config.ts and writes the build output the plan reads. */
294
+ function cfBuild(cf) {
295
+ const result = cf(["build"]);
296
+ return result.exitCode === 0 ? {
297
+ ok: true,
298
+ value: true
299
+ } : {
300
+ ok: false,
301
+ reason: failureText(result)
302
+ };
303
+ }
304
+ function listPages(cf, command, label, idKey, nameKey) {
305
+ const all = [];
306
+ for (let page = 1; page <= MAX_PAGES; page++) {
307
+ const listed = parseResources(cf([
308
+ ...command,
309
+ "--page",
310
+ String(page),
311
+ "--per-page",
312
+ String(PAGE_SIZE)
313
+ ]), label, idKey, nameKey);
314
+ if (!listed.ok) return listed;
315
+ all.push(...listed.value);
316
+ if (listed.value.length < PAGE_SIZE) return {
317
+ ok: true,
318
+ value: all
319
+ };
320
+ }
321
+ return {
322
+ ok: false,
323
+ reason: `${label} still had results after ${MAX_PAGES} pages of ${PAGE_SIZE}`
324
+ };
325
+ }
326
+ /** One listing's entries, each read as `{ id, name }` from the keys the resource type uses. */
327
+ function parseResources(result, label, idKey, nameKey) {
328
+ if (result.exitCode !== 0) return {
329
+ ok: false,
330
+ reason: `${label} failed: ${failureText(result)}`
331
+ };
332
+ const entries = resultArray(parseJson(result.stdout));
333
+ if (!entries) return {
334
+ ok: false,
335
+ reason: `${label} printed no JSON list`
336
+ };
337
+ const resources = [];
338
+ for (const entry of entries) {
339
+ const id = isRecord(entry) ? entry[idKey] : void 0;
340
+ const name = isRecord(entry) ? entry[nameKey] : void 0;
341
+ if (typeof id !== "string" || typeof name !== "string") return {
342
+ ok: false,
343
+ reason: `${label} returned an entry of an unexpected shape: ${JSON.stringify(entry)}`
344
+ };
345
+ resources.push({
346
+ id,
347
+ name
348
+ });
349
+ }
350
+ return {
351
+ ok: true,
352
+ value: resources
353
+ };
354
+ }
355
+ /** A listing as `cf` prints it: the `result` array alone, or the API envelope around it. */
356
+ function resultArray(value) {
357
+ if (Array.isArray(value)) return value;
358
+ return isRecord(value) && Array.isArray(value.result) ? value.result : void 0;
359
+ }
360
+ /** A single result as `cf` prints it: the object alone, or the API envelope around it. */
361
+ function resultObject(value) {
362
+ if (isRecord(value) && isRecord(value.result)) return value.result;
363
+ return isRecord(value) ? value : void 0;
364
+ }
365
+ /** Every entry's string `name`, or nothing when any entry has none. */
366
+ function names(entries) {
367
+ if (!Array.isArray(entries)) return void 0;
368
+ const read = entries.map((entry) => isRecord(entry) && typeof entry.name === "string" ? entry.name : void 0);
369
+ return read.every((name) => name !== void 0) ? read : void 0;
370
+ }
371
+ /** The JSON a command printed, past any line the CLI writes ahead of it (an update notice). */
372
+ function parseJson(text) {
373
+ const whole = tryParse(text);
374
+ if (whole !== void 0) return whole;
375
+ const start = text.search(/^[[{]/m);
376
+ return start === -1 ? void 0 : tryParse(text.slice(start));
377
+ }
378
+ function tryParse(text) {
379
+ try {
380
+ return JSON.parse(text);
381
+ } catch {
382
+ return;
383
+ }
384
+ }
385
+ function failureText(result) {
386
+ const text = `${result.stderr}${result.stdout}`.trim();
387
+ return text === "" ? `exit code ${result.exitCode}` : text;
388
+ }
389
+ //#endregion
390
+ //#region src/deploy/words.ts
391
+ /** The rendered config holds the resolved ids, so a placeholder id in wrangler.jsonc never stands in. */
392
+ const DEPLOY_CONFIG = `-c ${WRANGLER_OUTPUT_DIR}/${WRANGLER_DEPLOY_CONFIG_FILE}`;
393
+ const BACKEND_WORDS = {
394
+ cf: {
395
+ cli: "cf",
396
+ config: "cloudflare.config.ts",
397
+ setSecret: (name, worker) => `bunx cf workers secrets update ${name} --worker ${worker}`,
398
+ applyMigrations: (args) => `cf d1 migrations apply <DB id> ${args}`,
399
+ rollback: (worker) => `Roll back with \`bunx cf workers deployments list --worker ${worker}\` and a redeploy of an earlier version.`,
400
+ restore: (database, bookmark) => `bunx cf d1 time-travel restore ${database.id} --bookmark ${bookmark}`,
401
+ delete: (resource) => resource.type === "d1" ? `bunx cf d1 delete ${resource.id}` : resource.type === "kv" ? `bunx cf kv namespaces delete ${resource.id}` : `bunx cf r2 buckets delete ${resource.name}`,
402
+ addR2: (binding) => `gurenWorker() binds ${binding} from the build; an env entry after the spread in cloudflare.config.ts replaced it. Remove that entry, or bind ${binding} with bindings.r2().`,
403
+ addD1: (binding) => `gurenWorker() binds the database as DB. Pass binding: 'DB' to createD1Database() in config/database.ts, or bind ${binding} in cloudflare.config.ts.`
404
+ },
405
+ wrangler: {
406
+ cli: "wrangler",
407
+ config: "wrangler.jsonc",
408
+ setSecret: (name, worker) => `bunx wrangler secret put ${name} --name ${worker}`,
409
+ applyMigrations: (args) => `wrangler d1 migrations apply <DB binding> ${args}`,
410
+ rollback: (worker) => `Roll back to the previous version with \`bunx wrangler rollback --name ${worker}\`, or pass it an earlier version id.`,
411
+ restore: (database, bookmark) => `bunx wrangler d1 time-travel restore ${database.binding} --bookmark ${bookmark} ${DEPLOY_CONFIG}`,
412
+ delete: (resource) => resource.type === "d1" ? `bunx wrangler d1 delete ${resource.binding} ${DEPLOY_CONFIG}` : resource.type === "kv" ? `bunx wrangler kv namespace delete --namespace-id ${resource.id}` : `bunx wrangler r2 bucket delete ${resource.name}`,
413
+ addR2: (binding, bucket) => `Add it to wrangler.jsonc: "r2_buckets": [{ "binding": "${binding}", "bucket_name": "${bucket}" }].`,
414
+ addD1: (binding) => `Add a d1_databases entry with "binding": "${binding}" to wrangler.jsonc, or name the existing binding in config/database.ts.`
415
+ }
416
+ };
417
+ //#endregion
418
+ //#region src/deploy/plan.ts
419
+ const UNREAD_SOURCES = ["the deployed Worker's bindings (RFC 0035 Open Question 9); the deploy's strict inheritance covers them"];
420
+ /** The concurrency group `guren deploy --target cloudflare` writes for a Worker; @guren/cli's template spells it too. */
421
+ function deployConcurrencyGroup(worker) {
422
+ return `cloudflare-deploy-${worker}`;
423
+ }
424
+ /** A top-level `concurrency` that queues a second run rather than cancelling the first. */
425
+ function serializesRuns(workflow) {
426
+ let parsed;
427
+ try {
428
+ parsed = Bun.YAML.parse(workflow);
429
+ } catch {
430
+ return false;
431
+ }
432
+ const concurrency = typeof parsed === "object" && parsed !== null ? parsed.concurrency : void 0;
433
+ if (typeof concurrency === "string") return concurrency.trim() !== "";
434
+ if (typeof concurrency !== "object" || concurrency === null) return false;
435
+ const { group, "cancel-in-progress": cancel } = concurrency;
436
+ return typeof group === "string" && group.trim() !== "" && cancel !== true;
437
+ }
438
+ function buildPlan(context) {
439
+ const { backend } = context;
440
+ const words = BACKEND_WORDS[backend];
441
+ const findings = [];
442
+ const bindings = [];
443
+ for (const [binding, entry] of Object.entries(context.worker.env)) {
444
+ const type = entry.type;
445
+ if (!(type in RESOURCES) || !listingFor(context, type)) continue;
446
+ bindings.push(planBinding(context, binding, entry, type, findings, words));
447
+ }
448
+ for (const planned of bindings) {
449
+ const problem = planned.configured ? void 0 : RESOURCES[planned.type].nameProblem?.(planned.name);
450
+ if (problem) findings.push(blocker("resource-name", planned.binding, `"${planned.name}" is not a valid ${RESOURCES[planned.type].label} name: ${problem}.`, `Name it in config/cloudflare.ts (resourceNames: { ${planned.binding}: '<name>' }), or correct the name ${words.config} gives it, which comes first.`));
451
+ }
452
+ for (const binding of Object.keys(context.manifest.resourceNames ?? {})) {
453
+ const bound = context.worker.env[binding];
454
+ if (bound && bound.type in RESOURCES) continue;
455
+ findings.push({
456
+ check: "resource-name",
457
+ severity: "warning",
458
+ binding,
459
+ message: bound ? `config/cloudflare.ts names a resource for ${binding}, a ${bound.type} binding, which has no resource to name, so the name is not used.` : `config/cloudflare.ts names a resource for ${binding}, which the Worker does not bind, so the name is not used.`,
460
+ fix: `Check the binding's spelling: the Worker binds ${Object.keys(context.worker.env).join(", ") || "nothing"}.`
461
+ });
462
+ }
463
+ const unread = [...UNREAD_SOURCES, ...planInference(context, findings, words)];
464
+ for (const type of Object.keys(RESOURCES)) {
465
+ const listing = listingFor(context, type);
466
+ if (listing && !listing.ok && bindings.some((planned) => planned.type === type)) findings.push(blocker("source-unreadable", void 0, `${listing.reason}. Without the listing the plan cannot tell an existing resource from a missing one.`, `Rerun once \`${words.cli}\` can reach the account.`));
467
+ }
468
+ if (context.workflow && !(context.workflow.ok && serializesRuns(context.workflow.value))) findings.push({
469
+ check: "serialization",
470
+ severity: "warning",
471
+ message: context.workflow.ok ? "This GitHub Actions workflow has no top-level concurrency group that waits for a running deploy, so two deploys of this Worker can overlap, or one can be cancelled midway through a migration." : `The running workflow could not be read (${context.workflow.reason}), so whether deploys of this Worker run one at a time is unknown.`,
472
+ fix: `Add \`concurrency: { group: ${deployConcurrencyGroup(context.worker.name)}, cancel-in-progress: false }\` at the top of the workflow, as \`guren deploy --target cloudflare\` writes it.`
473
+ });
474
+ if (context.scheduleUnreadable && !context.worker.scheduled) findings.push(blocker("schedule-unreadable", void 0, `${context.scheduleUnreadable}, so whether the Worker needs a cron trigger is unknown, and deploying without one would remove a trigger it may already have.`, "Fix the kernel so `bunx guren schedule:list` reads it, or set `triggers` yourself in cloudflare.config.ts."));
475
+ const migrations = context.migrations ? planMigrations(context.migrations, findings, words) : void 0;
476
+ const missingSecrets = context.secrets ? planSecrets(context.secrets, context.worker.name, findings, words) : void 0;
477
+ return {
478
+ backend,
479
+ worker: context.worker.name,
480
+ bindings,
481
+ findings,
482
+ ...migrations ? { migrations } : {},
483
+ ...missingSecrets ? { missingSecrets } : {},
484
+ unread
485
+ };
486
+ }
487
+ /** The bindings the app names but the Worker lacks, and what could not be inferred (RFC 0035 §2). */
488
+ function planInference(context, findings, words) {
489
+ const { inference, worker } = context;
490
+ if (!inference) return [];
491
+ const unread = [];
492
+ if (inference.unread) unread.push(`the bindings the app names (R2 disks, the D1 binding): ${inference.unread}`);
493
+ if (inference.opaqueDisks?.length) unread.push(`the disks ${inference.opaqueDisks.join(", ")}, registered with a bare factory; register an R2 disk with r2Disk() so the deploy sees its bucket`);
494
+ for (const binding of inference.r2Buckets) {
495
+ if (worker.env[binding]?.type === "r2") continue;
496
+ const bucket = resourceName(worker.name, binding, context.manifest.resourceNames);
497
+ findings.push(blocker("resource-missing", binding, `A storage disk reads the R2 bucket binding ${binding}, which the Worker does not bind, so its first file operation would throw.`, words.addR2(binding, bucket)));
498
+ }
499
+ const database = inference.databaseBinding;
500
+ const bound = database ? worker.env[database] : void 0;
501
+ if (database && bound?.type !== "d1") findings.push(blocker(bound ? "binding-conflict" : "resource-missing", database, bound ? `config/database.ts reads the D1 binding ${database}, which the Worker binds as ${bound.type}.` : `config/database.ts reads the D1 binding ${database}, which the Worker does not bind.`, words.addD1(database)));
502
+ return unread;
503
+ }
504
+ function planMigrations(input, findings, words) {
505
+ if (input.status === "unreadable") {
506
+ findings.push(blocker("source-unreadable", void 0, `${input.reason}. Without the tracker the plan cannot tell which migrations are pending.`, `Rerun once \`${words.cli}\` can query the database.`));
507
+ return;
508
+ }
509
+ if (input.status === "unassigned") {
510
+ findings.push(blocker("tracker-layout", void 0, `${input.reason}.`, `Set "migrations_dir": ".cloudflare/d1-migrations" on that binding in ${words.config}.`));
511
+ return;
512
+ }
513
+ if (input.status === "layout-unsupported") {
514
+ findings.push(blocker("tracker-layout", void 0, `d1_migrations records drizzle's nested names (${input.nested.slice(0, 3).join(", ")}), which only the cf backend applies. ${words.cli} applies the flattened copy, so it would run the whole history again.`, "Deploy with the cf backend (`bunx guren cloudflare:init`), or rename the rows to `<folder>.sql` with a guarded UPDATE on d1_migrations."));
515
+ return;
516
+ }
517
+ if (input.status === "layout-conflict") {
518
+ findings.push(blocker("tracker-layout", void 0, `d1_migrations records both flattened names (${input.flat.slice(0, 3).join(", ")}) and nested ones (${input.nested.slice(0, 3).join(", ")}), so no layout applies only what is pending.`, "Rename the rows to one form with a guarded UPDATE on d1_migrations, then plan again."));
519
+ return;
520
+ }
521
+ const destructive = [...input.verdict.unacknowledged, ...input.unjudged.map((file) => input.layout === "nested" ? `db/migrations/${file}: a plain .sql file, which the nested layout never applies` : `db/migrations/${file}: a plain .sql file, which the destructive-migration guard does not read`)];
522
+ if (destructive.length > 0) findings.push({
523
+ check: "destructive-migration",
524
+ severity: input.allowDestructive ? "warning" : "blocker",
525
+ message: `${destructive.length} pending statement(s) no migration acknowledges:\n ${destructive.join("\n ")}`,
526
+ fix: "Review each one. Put `-- guren:allow-destructive: <reason>` on the first line of its migration.sql, or pass --allow-destructive for this run."
527
+ });
528
+ return {
529
+ layout: input.layout,
530
+ pending: input.pending,
531
+ applyArgs: input.applyArgs,
532
+ acknowledged: input.verdict.acknowledged,
533
+ fingerprint: input.fingerprint
534
+ };
535
+ }
536
+ function planSecrets(input, worker, findings, words) {
537
+ if (input.required.status === "unreadable") {
538
+ findings.push(blocker("source-unreadable", void 0, `${input.required.message}. Without it the plan cannot tell which secrets the worker needs.`, "Fix config/env.ts so it imports, then plan again."));
539
+ return;
540
+ }
541
+ if (input.required.status === "absent") return void 0;
542
+ const have = /* @__PURE__ */ new Set([...input.provided, ...input.deployed.ok ? input.deployed.value : []]);
543
+ const missing = input.required.required.filter((name) => !have.has(name));
544
+ if (missing.length === 0) return missing;
545
+ findings.push(blocker("secrets", void 0, input.deployed.ok ? `${worker} has no value for ${missing.join(", ")}, which config/env.ts requires in production.` : `config/env.ts requires ${missing.join(", ")} in production, and the deployed secrets could not be read (${input.deployed.reason}), as on a first deploy.`, input.deployed.ok ? missing.map((name) => words.setSecret(name, worker)).join("; ") : `List them in a dotenv file passed as --secrets-file${input.secretsFile ? ` (${input.secretsFile} lacks them)` : ""}; only the names are read here.`));
546
+ return missing;
547
+ }
548
+ /** The identity a binding carries for its resource: the id, or for an id-less type (R2) the name. */
549
+ function boundIdentity(entry) {
550
+ return entry && entry.type in RESOURCES && !RESOURCES[entry.type].hasId ? entry.name : entry?.id;
551
+ }
552
+ function hasBlocker(plan) {
553
+ return plan.findings.some((finding) => finding.severity === "blocker");
554
+ }
555
+ /** What differs per resource type. R2 has no id: a bucket's name is its identity (`{ id: name, name }`). */
556
+ const RESOURCES = {
557
+ d1: {
558
+ label: "D1 database",
559
+ hasId: true,
560
+ carriesName: true
561
+ },
562
+ kv: {
563
+ label: "KV namespace",
564
+ hasId: true,
565
+ carriesName: false
566
+ },
567
+ r2: {
568
+ label: "R2 bucket",
569
+ hasId: false,
570
+ carriesName: true,
571
+ nameProblem: (name) => /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(name) ? void 0 : "3 to 63 lowercase letters, digits and hyphens, starting and ending with a letter or digit"
572
+ }
573
+ };
574
+ /** A type's account listing; absent for one the backend cannot list, which leaves its bindings to the deploy. */
575
+ function listingFor(context, type) {
576
+ return type === "d1" ? context.d1 : type === "kv" ? context.kv : context.r2;
577
+ }
578
+ function planBinding(context, binding, entry, type, findings, words) {
579
+ const resource = RESOURCES[type];
580
+ const name = resourceName(context.worker.name, binding, context.manifest.resourceNames, resource.carriesName ? entry.name : void 0);
581
+ const resolvedId = context.manifest.resolved[binding]?.id;
582
+ const configuredId = resource.hasId && entry.id !== void 0 && entry.id !== resolvedId ? entry.id : void 0;
583
+ const listing = listingFor(context, type);
584
+ if (!listing.ok) return {
585
+ binding,
586
+ type,
587
+ action: "unknown",
588
+ name,
589
+ ...configuredId ? { id: configuredId } : {}
590
+ };
591
+ const resources = listing.value;
592
+ const byName = resources.filter((resource) => resource.name === name);
593
+ const { label } = resource;
594
+ if (configuredId !== void 0) {
595
+ const missing = !resources.some((resource) => resource.id === configuredId);
596
+ if (missing) findings.push(blocker("resource-missing", binding, `${binding} names the ${label} ${configuredId} in ${words.config}, and the account has none with that id.`, `Correct the id, or remove it so the deploy uses the ${label} named "${name}".`));
597
+ const other = byName.find((resource) => resource.id !== configuredId);
598
+ if (other) findings.push(blocker("binding-conflict", binding, `${binding} names the ${label} ${configuredId} in ${words.config}, while the ${label} "${name}" it would otherwise resolve to is ${other.id}.`, `Keep one: remove the id from ${words.config}, or give the binding another name.`));
599
+ return {
600
+ binding,
601
+ type,
602
+ action: missing ? "unknown" : "existing",
603
+ name,
604
+ id: configuredId,
605
+ configured: true
606
+ };
607
+ }
608
+ const settled = resolvedId === void 0 || !resource.hasId && resolvedId !== name ? void 0 : resources.find((candidate) => candidate.id === resolvedId);
609
+ if (settled) {
610
+ const requested = context.manifest.resourceNames?.[binding];
611
+ if (requested !== void 0 && requested !== settled.name) {
612
+ findings.push(blocker("binding-conflict", binding, `config/cloudflare.ts names ${binding}'s ${label} "${requested}", but an earlier deploy bound it to "${settled.name}" (${settled.id}), which the next deploy would keep.`, `To move the binding, delete ${binding} from "resolved" in .guren/cloudflare/guren-worker.json and plan again; to stay, set the name back to "${settled.name}".`));
613
+ return {
614
+ binding,
615
+ type,
616
+ action: "unknown",
617
+ name: requested,
618
+ id: settled.id
619
+ };
620
+ }
621
+ const other = byName.find((resource) => resource.id !== resolvedId);
622
+ if (other && !byName.some((resource) => resource.id === resolvedId)) findings.push(blocker("binding-conflict", binding, `${binding} is bound to the ${label} ${resolvedId} by an earlier deploy, while the ${label} "${name}" is ${other.id}.`, `Put the intended id in ${words.config}, or rename one of the ${label}s.`));
623
+ return {
624
+ binding,
625
+ type,
626
+ action: "existing",
627
+ name,
628
+ id: resolvedId
629
+ };
630
+ }
631
+ if (byName.length > 1) {
632
+ findings.push(blocker("binding-conflict", binding, `The account has ${byName.length} ${label}s named "${name}" (${byName.map((resource) => resource.id).join(", ")}), so the name does not decide which one ${binding} binds.`, `Put the intended id in ${words.config}.`));
633
+ return {
634
+ binding,
635
+ type,
636
+ action: "unknown",
637
+ name
638
+ };
639
+ }
640
+ const found = byName[0];
641
+ if (found) return {
642
+ binding,
643
+ type,
644
+ action: found.id === resolvedId ? "existing" : "adopt",
645
+ name,
646
+ id: found.id
647
+ };
648
+ if (!context.mayCreate) findings.push(blocker("resource-missing", binding, `No ${label} named "${name}" exists, and this run may not create one.`, "Pass --provision to let a CI run create it, or create it beforehand."));
649
+ return {
650
+ binding,
651
+ type,
652
+ action: "create",
653
+ name
654
+ };
655
+ }
656
+ function blocker(check, binding, message, fix) {
657
+ return {
658
+ check,
659
+ severity: "blocker",
660
+ ...binding ? { binding } : {},
661
+ message,
662
+ fix
663
+ };
664
+ }
665
+ //#endregion
666
+ //#region src/deploy/wrangler-cli.ts
667
+ /**
668
+ * The Wrangler backend's account operations (RFC 0035 §7, Appendix B), against
669
+ * Wrangler 4.129 or later. Every command naming a database, the secrets listing and
670
+ * the deploy take the rendered deploy config (`-c`), so a database is found by its
671
+ * binding there and never through a placeholder id in wrangler.jsonc. `d1 execute`
672
+ * and `d1 migrations apply` default to the local database, so both pass `--remote`.
673
+ */
674
+ /** `whoami --json` exits non-zero when nobody is logged in. */
675
+ function checkWranglerAuth(wrangler) {
676
+ const result = wrangler(["whoami", "--json"]);
677
+ return result.exitCode === 0 ? {
678
+ ok: true,
679
+ value: true
680
+ } : {
681
+ ok: false,
682
+ reason: failureText(result)
683
+ };
684
+ }
685
+ /** Wrangler pages through the whole account itself. */
686
+ function listWranglerD1(wrangler) {
687
+ return parseResources(wrangler([
688
+ "d1",
689
+ "list",
690
+ "--json"
691
+ ]), "wrangler d1 list", "uuid", "name");
692
+ }
693
+ /** Prints JSON with no flag (Appendix B row 7). */
694
+ function listWranglerKv(wrangler) {
695
+ return parseResources(wrangler([
696
+ "kv",
697
+ "namespace",
698
+ "list"
699
+ ]), "wrangler kv namespace list", "id", "title");
700
+ }
701
+ /**
702
+ * `--update-config=false` answers the "add it to your config?" prompt before it is
703
+ * asked. Create prints no JSON, so the id is read back from the listing by name.
704
+ */
705
+ function createWranglerResource(wrangler, type, name) {
706
+ const args = type === "d1" ? [
707
+ "d1",
708
+ "create",
709
+ name,
710
+ "--update-config=false"
711
+ ] : [
712
+ "kv",
713
+ "namespace",
714
+ "create",
715
+ name,
716
+ "--update-config=false"
717
+ ];
718
+ const label = `wrangler ${args.slice(0, type === "d1" ? 2 : 3).join(" ")}`;
719
+ const result = wrangler(args);
720
+ if (result.exitCode !== 0) return {
721
+ ok: false,
722
+ reason: `${label} failed: ${failureText(result)}`
723
+ };
724
+ const listing = type === "d1" ? listWranglerD1(wrangler) : listWranglerKv(wrangler);
725
+ if (!listing.ok) return {
726
+ ok: false,
727
+ reason: `${label} succeeded, but ${listing.reason}`
728
+ };
729
+ const found = listing.value.filter((resource) => resource.name === name);
730
+ return found.length === 1 && found[0] ? {
731
+ ok: true,
732
+ value: found[0].id
733
+ } : {
734
+ ok: false,
735
+ reason: `${label} succeeded, but the listing has ${found.length} named "${name}"`
736
+ };
737
+ }
738
+ /** The names the binding's tracker table records, or `null` when the table does not exist yet. */
739
+ function readWranglerTracker(wrangler, binding, table, configArgs) {
740
+ return trackerRows(wrangler([
741
+ "d1",
742
+ "execute",
743
+ binding,
744
+ "--remote",
745
+ "--json",
746
+ "--command",
747
+ trackerQuery(table),
748
+ ...configArgs
749
+ ]), "wrangler d1 execute", table);
750
+ }
751
+ function getWranglerBookmark(wrangler, binding, configArgs) {
752
+ return readField(wrangler, [
753
+ "d1",
754
+ "time-travel",
755
+ "info",
756
+ binding,
757
+ "--json",
758
+ ...configArgs
759
+ ], "wrangler d1 time-travel info", "bookmark");
760
+ }
761
+ /** Applies from the `migrations_dir` the deploy config gives the binding; non-interactive, so unprompted. */
762
+ function applyWranglerMigrations(wrangler, binding, applyArgs) {
763
+ const result = wrangler([
764
+ "d1",
765
+ "migrations",
766
+ "apply",
767
+ binding,
768
+ ...applyArgs
769
+ ]);
770
+ return result.exitCode === 0 ? {
771
+ ok: true,
772
+ value: result.stdout
773
+ } : {
774
+ ok: false,
775
+ reason: `wrangler d1 migrations apply failed: ${failureText(result)}`
776
+ };
777
+ }
778
+ /** Fails on a Worker that does not exist yet, as on a first deploy. */
779
+ function listWranglerSecrets(wrangler, worker, configArgs) {
780
+ const result = wrangler([
781
+ "secret",
782
+ "list",
783
+ "--name",
784
+ worker,
785
+ "--format",
786
+ "json",
787
+ ...configArgs
788
+ ]);
789
+ if (result.exitCode !== 0) return {
790
+ ok: false,
791
+ reason: `wrangler secret list failed: ${failureText(result)}`
792
+ };
793
+ const secrets = names(resultArray(parseJson(result.stdout)));
794
+ return secrets ? {
795
+ ok: true,
796
+ value: secrets
797
+ } : {
798
+ ok: false,
799
+ reason: "wrangler secret list printed no list of named secrets"
800
+ };
801
+ }
802
+ /** Stage 7 with provisioning off, so a binding that does not resolve fails the upload (RFC 0035 §4). */
803
+ function deployWithWrangler(wrangler, configArgs, secretsFile) {
804
+ const result = wrangler([
805
+ "deploy",
806
+ ...configArgs,
807
+ "--x-provision=false",
808
+ ...secretsFile ? ["--secrets-file", secretsFile] : []
809
+ ]);
810
+ return result.exitCode === 0 ? {
811
+ ok: true,
812
+ value: `${result.stdout}${result.stderr}`
813
+ } : {
814
+ ok: false,
815
+ reason: `wrangler deploy failed: ${failureText(result)}`
816
+ };
817
+ }
818
+ //#endregion
819
+ //#region src/deploy/wrangler-config.ts
820
+ /**
821
+ * The Wrangler backend's view of `wrangler.jsonc` (RFC 0035 §7): read as the
822
+ * evaluated Worker the plan resolves, and rendered into `<out>/wrangler.deploy.json`
823
+ * with the resolved ids filled in. wrangler.jsonc itself is never written. Only the
824
+ * top level is deployed; named environments come in a later phase.
825
+ */
826
+ /** The plan's view of the top level: a placeholder id reads as no id, as `wrangler deploy` would not bind it. */
827
+ function evaluateWranglerConfig(config) {
828
+ if (typeof config.name !== "string" || config.name === "") throw new Error("Cloudflare deploy: wrangler.jsonc has no \"name\", so there is no Worker to deploy.");
829
+ const env = {};
830
+ for (const entry of asArray(config.d1_databases)) {
831
+ if (!isRecord(entry) || typeof entry.binding !== "string") continue;
832
+ env[entry.binding] = {
833
+ type: "d1",
834
+ ...realId(entry.database_id) ? { id: entry.database_id } : {},
835
+ ...typeof entry.database_name === "string" ? { name: entry.database_name } : {}
836
+ };
837
+ }
838
+ for (const entry of asArray(config.kv_namespaces)) {
839
+ if (!isRecord(entry) || typeof entry.binding !== "string") continue;
840
+ env[entry.binding] = {
841
+ type: "kv",
842
+ ...realId(entry.id) ? { id: entry.id } : {}
843
+ };
844
+ }
845
+ for (const entry of asArray(config.r2_buckets)) {
846
+ if (!isRecord(entry) || typeof entry.binding !== "string") continue;
847
+ env[entry.binding] = {
848
+ type: "r2",
849
+ ...typeof entry.bucket_name === "string" ? { name: entry.bucket_name } : {}
850
+ };
851
+ }
852
+ for (const [name, value] of Object.entries(isRecord(config.vars) ? config.vars : {})) env[name] = { type: typeof value === "string" ? "text" : "json" };
853
+ const crons = isRecord(config.triggers) ? asArray(config.triggers.crons) : [];
854
+ return {
855
+ name: config.name,
856
+ env,
857
+ scheduled: crons.length > 0
858
+ };
859
+ }
860
+ function realId(id) {
861
+ return typeof id === "string" && id !== "" && !isPlaceholderId(id);
862
+ }
863
+ /**
864
+ * The D1 binding `db/migrations` belongs to: the one whose `migrations_dir` is the
865
+ * build's flattened copy, else the only D1 binding, else none can be told apart.
866
+ */
867
+ function wranglerMigrationsBinding(config, root, flatDir) {
868
+ const databases = asArray(config.d1_databases).filter((entry) => isRecord(entry) && typeof entry.binding === "string");
869
+ const pointing = databases.filter((entry) => typeof entry.migrations_dir === "string" && resolve(root, entry.migrations_dir) === flatDir);
870
+ if (pointing.length === 1 && pointing[0]) return {
871
+ ok: true,
872
+ value: pointing[0].binding
873
+ };
874
+ if (pointing.length > 1) return {
875
+ ok: false,
876
+ reason: `wrangler.jsonc gives ${pointing.map((entry) => entry.binding).join(" and ")} the same migrations_dir, so which database db/migrations belongs to is unknown`
877
+ };
878
+ if (databases.length === 0) return {
879
+ ok: true,
880
+ value: void 0
881
+ };
882
+ const only = databases.length === 1 ? databases[0] : void 0;
883
+ if (only && only.migrations_dir === void 0) return {
884
+ ok: true,
885
+ value: only.binding
886
+ };
887
+ return {
888
+ ok: false,
889
+ reason: `no D1 binding in wrangler.jsonc sets migrations_dir to ${flatDir}, where the build flattens db/migrations, so which database they belong to is unknown`
890
+ };
891
+ }
892
+ /** The table `wrangler d1 migrations apply` records into for a binding (`migrations_table`). */
893
+ function wranglerMigrationsTable(config, binding) {
894
+ const entry = asArray(config.d1_databases).find((candidate) => isRecord(candidate) && candidate.binding === binding);
895
+ return isRecord(entry) && typeof entry.migrations_table === "string" && entry.migrations_table !== "" ? entry.migrations_table : void 0;
896
+ }
897
+ /** Keys holding a path wrangler resolves against the config file's directory. */
898
+ const PATH_KEYS = [
899
+ "main",
900
+ "tsconfig",
901
+ "base_dir"
902
+ ];
903
+ const PATH_MAPS = [
904
+ "wasm_modules",
905
+ "text_blobs",
906
+ "data_blobs"
907
+ ];
908
+ /**
909
+ * wrangler.jsonc with every path absolute (the file sits in the output directory, not
910
+ * the app root), the resolved ids filled in on the top level, and the migrations
911
+ * binding pointed at the flattened copy.
912
+ */
913
+ function renderWranglerDeployConfig(input) {
914
+ const { root } = input;
915
+ const config = structuredClone(input.config);
916
+ const absolute = (value) => typeof value === "string" && value !== "" && !isAbsolute(value) ? resolve(root, value) : value;
917
+ for (const { config: scope } of configScopes(config)) {
918
+ for (const key of PATH_KEYS) if (key in scope) scope[key] = absolute(scope[key]);
919
+ for (const key of PATH_MAPS) {
920
+ const map = scope[key];
921
+ if (isRecord(map)) for (const name of Object.keys(map)) map[name] = absolute(map[name]);
922
+ }
923
+ if (isRecord(scope.assets)) scope.assets.directory = absolute(scope.assets.directory);
924
+ if (isRecord(scope.site)) scope.site.bucket = absolute(scope.site.bucket);
925
+ if (isRecord(scope.build)) {
926
+ scope.build.cwd = absolute(scope.build.cwd ?? ".");
927
+ const watch = scope.build.watch_dir;
928
+ scope.build.watch_dir = Array.isArray(watch) ? watch.map(absolute) : absolute(watch);
929
+ }
930
+ if (isRecord(scope.alias)) {
931
+ for (const [name, target] of Object.entries(scope.alias)) if (typeof target === "string" && target.startsWith(".")) scope.alias[name] = resolve(root, target);
932
+ }
933
+ for (const entry of asArray(scope.d1_databases)) if (isRecord(entry) && "migrations_dir" in entry) entry.migrations_dir = absolute(entry.migrations_dir);
934
+ for (const container of asArray(scope.containers)) {
935
+ if (!isRecord(container)) continue;
936
+ if (typeof container.image === "string" && existsSync(resolve(root, container.image))) container.image = absolute(container.image);
937
+ if ("image_build_context" in container) container.image_build_context = absolute(container.image_build_context);
938
+ }
939
+ }
940
+ for (const entry of asArray(config.d1_databases)) {
941
+ if (!isRecord(entry) || typeof entry.binding !== "string") continue;
942
+ const id = input.resolved[entry.binding]?.id;
943
+ if (id) entry.database_id = id;
944
+ if (entry.binding === input.migrationsBinding) entry.migrations_dir = input.flatDir;
945
+ }
946
+ for (const entry of asArray(config.kv_namespaces)) {
947
+ if (!isRecord(entry) || typeof entry.binding !== "string") continue;
948
+ const id = input.resolved[entry.binding]?.id;
949
+ if (id) entry.id = id;
950
+ }
951
+ return config;
952
+ }
953
+ //#endregion
954
+ //#region src/deploy/backends.ts
955
+ /**
956
+ * The backend interface `cloudflare:deploy` runs its stages against (RFC 0035 §7).
957
+ * Every operation on the account or a CLI goes through one of these, so the stages
958
+ * in `deploy.ts` are written once. Which backend runs is `detectCloudflareBackend()`'s.
959
+ */
960
+ /** Where the cf build writes the evaluated Worker configuration. */
961
+ const EVALUATED_CONFIG = ".cloudflare/output/v0/workers/default/worker.config.json";
962
+ function cfDeployBackend(options) {
963
+ const { root } = options;
964
+ const cfPackage = resolvePackageFile(root, "cf/package.json");
965
+ const cf = options.cf ?? appCliRunner(root, packageBin(root, "cf", "cf", cfPackage));
966
+ const nodeVersion = options.nodeVersion ?? nodeOnPathVersion;
967
+ const buildEntry = packageBin(root, "wrangler", CF_WRANGLER_BUILD_ENTRY);
968
+ const buildLabel = `the cf build (\`${CF_WRANGLER_BUILD_ENTRY} build\`)`;
969
+ const builder = options.cf ?? appCliRunner(root, buildEntry);
970
+ const build = () => {
971
+ rmSync(join(root, EVALUATED_CONFIG), { force: true });
972
+ return cfBuild(builder);
973
+ };
974
+ return {
975
+ kind: "cf",
976
+ outputDir: outputDirFor("cf"),
977
+ appliesNested: true,
978
+ preflight() {
979
+ const problems = [];
980
+ if (!cfPackage) problems.push("cf is declared but not installed. Run `bun install`.");
981
+ const node = nodeVersion();
982
+ if (!node || !Bun.semver.satisfies(node, `>=22.18.0`)) problems.push(`cf loads cloudflare.config.ts with the node on PATH, which needs Node ${CF_NODE_FLOOR} or later; found ${node ?? "no node"}.`);
983
+ const wrangler = installedVersion(root, "wrangler");
984
+ if (!wrangler || !Bun.semver.satisfies(wrangler, `>=4.136.0-0`)) problems.push(`cf bundles through the app's Wrangler, which needs ${CF_WRANGLER_FLOOR} or later; found ${wrangler ?? "none"}. Run \`bun add -d wrangler@latest\`.`);
985
+ else if (!existsSync(buildEntry)) problems.push(`The app's Wrangler ${wrangler} has no bin/${CF_WRANGLER_BUILD_ENTRY}, the build cf runs for a Worker. Run \`bun add -d wrangler@latest\`.`);
986
+ if (problems.length === 0) {
987
+ const auth = checkAuth(cf);
988
+ if (!auth.ok) problems.push(`cf is not logged in (${auth.reason}). Run \`bunx cf auth login\`, or set CLOUDFLARE_API_TOKEN in CI.`);
989
+ }
990
+ return problems;
991
+ },
992
+ evaluate() {
993
+ const built = build();
994
+ if (!built.ok) throw new Error(`Cloudflare deploy: ${buildLabel} failed, so cloudflare.config.ts could not be evaluated:\n${built.reason}`);
995
+ return readEvaluatedWorker(root);
996
+ },
997
+ migrationsBinding() {
998
+ return {
999
+ ok: true,
1000
+ value: readWorkerManifest(join(root, outputDirFor("cf"))).d1?.binding
1001
+ };
1002
+ },
1003
+ prepareReads() {},
1004
+ list: (type) => type === "d1" ? listD1Databases(cf) : listKvNamespaces(cf),
1005
+ create: (type, name) => type === "d1" ? createD1Database(cf, name) : createKvNamespace(cf, name),
1006
+ r2: {
1007
+ list: (names) => listR2Buckets(cf, names),
1008
+ create: (name) => createR2Bucket(cf, name)
1009
+ },
1010
+ rebuild(resolved) {
1011
+ const rebuilt = build();
1012
+ if (!rebuilt.ok) return {
1013
+ ok: false,
1014
+ reason: `${buildLabel} failed after the resources were settled:\n${rebuilt.reason}`
1015
+ };
1016
+ const worker = readEvaluatedWorker(root);
1017
+ const drift = Object.entries(resolved).filter(([binding, resource]) => boundIdentity(worker.env[binding]) !== resource.id).map(([binding]) => binding);
1018
+ return drift.length > 0 ? {
1019
+ ok: false,
1020
+ reason: `cloudflare.config.ts binds ${drift.join(", ")} to another resource than the plan resolved. Remove the id it sets after the gurenWorker() spread, then plan again.`
1021
+ } : {
1022
+ ok: true,
1023
+ value: true
1024
+ };
1025
+ },
1026
+ applyArgs: (layout) => migrationDirArgs(layout, `${outputDirFor("cf")}/${D1_MIGRATIONS_DIR}`),
1027
+ readTracker: (database) => readMigrationTracker(cf, database.id),
1028
+ bookmark: (database) => getBookmark(cf, database.id),
1029
+ applyMigrations: (database, applyArgs) => applyMigrations(cf, database.id, applyArgs),
1030
+ listSecrets: (worker) => listWorkerSecrets(cf, worker),
1031
+ deploy: (secretsFile) => deployPrebuilt(cf, secretsFile)
1032
+ };
1033
+ }
1034
+ /** The Wrangler Appendix B's commands were verified against; `-0` admits its pre-releases. */
1035
+ const WRANGLER_FLOOR = "4.129.0";
1036
+ /**
1037
+ * For apps on `wrangler.jsonc` (RFC 0035 §7). wrangler.jsonc stays the developer's:
1038
+ * the deploy reads it, and renders `.cloudflare/wrangler.deploy.json` with the
1039
+ * resolved ids for every command that needs a database or the upload.
1040
+ */
1041
+ function wranglerDeployBackend(options) {
1042
+ const { root } = options;
1043
+ const wranglerPackage = resolvePackageFile(root, "wrangler/package.json");
1044
+ const wrangler = options.wrangler ?? appCliRunner(root, packageBin(root, "wrangler", "wrangler.js", wranglerPackage));
1045
+ const nodeVersion = options.nodeVersion ?? nodeOnPathVersion;
1046
+ const outputDir = outputDirFor("wrangler");
1047
+ const outDir = join(root, outputDir);
1048
+ const flatDir = join(outDir, D1_MIGRATIONS_DIR);
1049
+ const configArgs = ["-c", `${outputDir}/${WRANGLER_DEPLOY_CONFIG_FILE}`];
1050
+ let config;
1051
+ let chosen;
1052
+ const developerConfig = () => {
1053
+ config ??= readWranglerConfig(join(root, "wrangler.jsonc"));
1054
+ if (!config) throw new Error(`Cloudflare deploy: ${join(root, "wrangler.jsonc")} is missing or not valid JSONC, so the bindings could not be read.`);
1055
+ return config;
1056
+ };
1057
+ const migrationsBinding = () => chosen ??= wranglerMigrationsBinding(developerConfig(), root, flatDir);
1058
+ const render = (resolved) => {
1059
+ const binding = migrationsBinding();
1060
+ const rendered = renderWranglerDeployConfig({
1061
+ root,
1062
+ config: developerConfig(),
1063
+ resolved,
1064
+ migrationsBinding: binding.ok ? binding.value : void 0,
1065
+ flatDir
1066
+ });
1067
+ writeFileSync(join(outDir, WRANGLER_DEPLOY_CONFIG_FILE), `${JSON.stringify(rendered, null, 2)}\n`);
1068
+ };
1069
+ return {
1070
+ kind: "wrangler",
1071
+ outputDir,
1072
+ appliesNested: false,
1073
+ preflight() {
1074
+ const problems = [];
1075
+ const manifest = wranglerPackage ? readJson(wranglerPackage) : void 0;
1076
+ const version = isRecord(manifest) && typeof manifest.version === "string" ? manifest.version : void 0;
1077
+ if (!version || !Bun.semver.satisfies(version, `>=${WRANGLER_FLOOR}-0`)) problems.push(`The deploy runs the app's Wrangler, which needs ${WRANGLER_FLOOR} or later; found ${version ?? "none"}. Run \`bun add -d wrangler@latest\`.`);
1078
+ const nodeRange = isRecord(manifest) && isRecord(manifest.engines) && typeof manifest.engines.node === "string" ? manifest.engines.node : void 0;
1079
+ const node = nodeRange ? nodeVersion() : void 0;
1080
+ if (nodeRange && (!node || !Bun.semver.satisfies(node, nodeRange))) problems.push(`Wrangler runs on the node on PATH, and this one needs Node ${nodeRange}; found ${node ?? "no node"}.`);
1081
+ if (problems.length === 0) {
1082
+ const auth = checkWranglerAuth(wrangler);
1083
+ if (!auth.ok) problems.push(`Wrangler is not logged in (${auth.reason}). Run \`bunx wrangler login\`, or set CLOUDFLARE_API_TOKEN in CI.`);
1084
+ }
1085
+ return problems;
1086
+ },
1087
+ evaluate: () => evaluateWranglerConfig(developerConfig()),
1088
+ migrationsBinding,
1089
+ prepareReads(bindings) {
1090
+ const ids = {};
1091
+ for (const binding of bindings) if (binding.id) ids[binding.binding] = { id: binding.id };
1092
+ render(ids);
1093
+ },
1094
+ list: (type) => type === "d1" ? listWranglerD1(wrangler) : listWranglerKv(wrangler),
1095
+ create: (type, name) => createWranglerResource(wrangler, type, name),
1096
+ rebuild(resolved) {
1097
+ render(resolved);
1098
+ return {
1099
+ ok: true,
1100
+ value: true
1101
+ };
1102
+ },
1103
+ applyArgs: () => ["--remote", ...configArgs],
1104
+ readTracker: (database) => readWranglerTracker(wrangler, database.binding, wranglerMigrationsTable(developerConfig(), database.binding) ?? "d1_migrations", configArgs),
1105
+ bookmark: (database) => getWranglerBookmark(wrangler, database.binding, configArgs),
1106
+ applyMigrations: (database, applyArgs) => applyWranglerMigrations(wrangler, database.binding, applyArgs),
1107
+ listSecrets: (worker) => listWranglerSecrets(wrangler, worker, configArgs),
1108
+ deploy: (secretsFile) => deployWithWrangler(wrangler, configArgs, secretsFile)
1109
+ };
1110
+ }
1111
+ function readEvaluatedWorker(root) {
1112
+ const path = join(root, EVALUATED_CONFIG);
1113
+ const config = readJson(path);
1114
+ if (!isRecord(config) || typeof config.name !== "string" || config.env !== void 0 && !isRecord(config.env)) throw new Error(`Cloudflare deploy: ${path} is missing or not the shape the cf build writes, so the bindings could not be read.`);
1115
+ const env = {};
1116
+ for (const [binding, entry] of Object.entries(config.env ?? {})) if (isRecord(entry) && typeof entry.type === "string") env[binding] = {
1117
+ type: entry.type,
1118
+ ...typeof entry.id === "string" ? { id: entry.id } : {},
1119
+ ...typeof entry.name === "string" ? { name: entry.name } : {}
1120
+ };
1121
+ const triggers = Array.isArray(config.triggers) ? config.triggers : [];
1122
+ return {
1123
+ name: config.name,
1124
+ env,
1125
+ scheduled: triggers.some((trigger) => isRecord(trigger) && trigger.type === "scheduled")
1126
+ };
1127
+ }
1128
+ /** The entry cf spawns for `build` when it picks the Wrangler implementation (wrangler 4.136+). */
1129
+ const CF_WRANGLER_BUILD_ENTRY = "cf-wrangler.js";
1130
+ /** A file under an installed package's `bin/`, from its resolved `package.json` when the caller has it. */
1131
+ function packageBin(root, name, file, manifest = resolvePackageFile(root, `${name}/package.json`)) {
1132
+ return join(dirname(manifest ?? join(root, "node_modules", name, "package.json")), "bin", file);
1133
+ }
1134
+ /** Resolved the way Node resolves it from the app, so a hoisted workspace install is found. */
1135
+ function resolvePackageFile(root, specifier) {
1136
+ try {
1137
+ return Bun.resolveSync(specifier, root);
1138
+ } catch {
1139
+ return;
1140
+ }
1141
+ }
1142
+ function installedVersion(root, name) {
1143
+ const path = resolvePackageFile(root, `${name}/package.json`);
1144
+ const manifest = path ? readJson(path) : void 0;
1145
+ return isRecord(manifest) && typeof manifest.version === "string" ? manifest.version : void 0;
1146
+ }
1147
+ function nodeOnPathVersion() {
1148
+ try {
1149
+ const result = Bun.spawnSync({
1150
+ cmd: ["node", "--version"],
1151
+ stdout: "pipe",
1152
+ stderr: "pipe"
1153
+ });
1154
+ return result.exitCode === 0 ? result.stdout.toString().trim() : void 0;
1155
+ } catch {
1156
+ return;
1157
+ }
1158
+ }
1159
+ function readJson(path) {
1160
+ try {
1161
+ return parseJson(readFileSync(path, "utf8"));
1162
+ } catch {
1163
+ return;
1164
+ }
1165
+ }
1166
+ //#endregion
1167
+ //#region src/deploy/report.ts
1168
+ const ACTION_LABELS = {
1169
+ existing: "existing",
1170
+ adopt: "adopt (found by name; check it is this app's)",
1171
+ create: "create on deploy",
1172
+ unknown: "unknown"
1173
+ };
1174
+ /** The plan as text, the form a person reads before anything is written. */
1175
+ function formatPlan(plan) {
1176
+ const lines = [`Cloudflare deploy plan for ${plan.worker}:`];
1177
+ if (plan.bindings.length === 0) lines.push(" No D1, KV or R2 bindings.");
1178
+ for (const binding of plan.bindings) {
1179
+ const id = binding.id ? ` ${binding.id}` : "";
1180
+ lines.push(` ${binding.binding} (${binding.type}) "${binding.name}"${id}: ${ACTION_LABELS[binding.action]}`);
1181
+ }
1182
+ if (plan.migrations) {
1183
+ const { pending, layout, applyArgs } = plan.migrations;
1184
+ lines.push(pending.length === 0 ? ` Migrations: none pending (${layout} layout).` : ` Migrations: ${pending.length} pending (${layout} layout): ${pending.join(", ")}`);
1185
+ const args = applyArgs.map((arg) => arg.includes("*") ? `'${arg}'` : arg).join(" ");
1186
+ if (pending.length > 0) lines.push(` Applied with: ${BACKEND_WORDS[plan.backend].applyMigrations(args)}`);
1187
+ for (const { migration, reason } of plan.migrations.acknowledged) lines.push(` ${migration}: destructive, acknowledged${reason ? ` (${reason})` : ""}`);
1188
+ }
1189
+ if (plan.missingSecrets?.length === 0) lines.push(" Secrets: every required variable is provided.");
1190
+ for (const source of plan.unread) lines.push(` Not read: ${source}.`);
1191
+ for (const finding of plan.findings) {
1192
+ const where = finding.binding ? ` ${finding.binding}` : "";
1193
+ lines.push(`${finding.severity === "blocker" ? "Blocker" : "Warning"} [${finding.check}]${where}: ${finding.message}`);
1194
+ if (finding.fix) lines.push(` Fix: ${finding.fix}`);
1195
+ }
1196
+ return lines.join("\n");
1197
+ }
1198
+ /** The whole run: the plan, then what was created, migrated and deployed, or where it stopped. */
1199
+ function formatResult(result) {
1200
+ const lines = result.confirmed ? [] : [formatPlan(result.plan)];
1201
+ if (result.stopped === "blocked") lines.push("Nothing was written: resolve the blockers above, then run again.");
1202
+ if (result.stopped === "declined") lines.push("Nothing was written.");
1203
+ for (const resource of result.created) lines.push(`Created ${resource.binding} (${resource.type}) "${resource.name}" ${resource.id}`);
1204
+ if (result.migrated) {
1205
+ lines.push(`Applied ${result.migrated.applied.length} migration(s): ${result.migrated.applied.join(", ")}`);
1206
+ lines.push(` Time Travel bookmark before them: ${result.migrated.bookmark}`);
1207
+ }
1208
+ if (result.deployment) {
1209
+ lines.push(result.deployment.output.trimEnd());
1210
+ lines.push(result.url ? `Deployed: ${result.url}` : `Deployed. ${BACKEND_WORDS[result.plan.backend].cli} printed no workers.dev URL; see its output above.`);
1211
+ lines.push(`${BACKEND_WORDS[result.plan.backend].rollback(result.plan.worker)} A rollback does not revert migrations.`);
1212
+ }
1213
+ if (result.failure) {
1214
+ lines.push(`Failed at ${result.failure.stage}: ${result.failure.message}`);
1215
+ if (result.failure.cleanup.length > 0) lines.push("Nothing was deleted. To undo what this run did:", ...result.failure.cleanup.map((command) => ` ${command}`));
1216
+ }
1217
+ return lines.join("\n");
1218
+ }
1219
+ //#endregion
1220
+ //#region src/deploy/deploy.ts
1221
+ /**
1222
+ * `guren cloudflare:deploy` (RFC 0035 §1): preflight, assemble and plan, then,
1223
+ * unless `--plan`, create, rebuild, migrate, deploy and report. Nothing is written
1224
+ * to the account before the plan has no blocker and the run is confirmed, and
1225
+ * nothing is ever deleted: a failure reports what this run created instead.
1226
+ */
1227
+ async function planCloudflareDeploy(options) {
1228
+ return (await prepare({
1229
+ ...options,
1230
+ plan: true
1231
+ })).plan;
1232
+ }
1233
+ async function prepare(options) {
1234
+ const root = resolve(options.root);
1235
+ const backend = detectCloudflareBackend(root) === "cf" ? cfDeployBackend({
1236
+ root,
1237
+ cf: options.cf,
1238
+ nodeVersion: options.nodeVersion
1239
+ }) : wranglerDeployBackend({
1240
+ root,
1241
+ wrangler: options.wrangler,
1242
+ nodeVersion: options.nodeVersion
1243
+ });
1244
+ const problems = backend.preflight();
1245
+ if (problems.length > 0) throw new Error(`Cloudflare deploy: preflight failed, before anything was built:\n ${problems.join("\n ")}`);
1246
+ const { inference } = await withStdoutLogs(options.logToStderr === true, () => assembleCloudflareOutput({
1247
+ rootDir: root,
1248
+ skipAppBuild: options.skipAppBuild,
1249
+ mcpOAuth: options.mcpOAuth,
1250
+ ...options.mcpPath ? { mcpPath: options.mcpPath } : {},
1251
+ appBuildToStderr: options.logToStderr
1252
+ }));
1253
+ const interactive = options.interactive ?? Boolean(process.stdin.isTTY);
1254
+ const worker = backend.evaluate();
1255
+ const uses = (type) => Object.values(worker.env).some((entry) => entry.type === type);
1256
+ const unlisted = {
1257
+ ok: true,
1258
+ value: []
1259
+ };
1260
+ const outDir = join(root, backend.outputDir);
1261
+ const previous = readWorkerManifest(outDir);
1262
+ const resourceNames = isRecord(previous.resourceNames) ? previous.resourceNames : void 0;
1263
+ const r2Names = Object.entries(worker.env).filter(([, entry]) => entry.type === "r2").map(([binding, entry]) => resourceName(worker.name, binding, resourceNames, entry.name));
1264
+ const context = {
1265
+ backend: backend.kind,
1266
+ worker,
1267
+ manifest: {
1268
+ resolved: readResolvedResources(outDir),
1269
+ ...resourceNames ? { resourceNames } : {}
1270
+ },
1271
+ d1: uses("d1") ? backend.list("d1") : unlisted,
1272
+ kv: uses("kv") ? backend.list("kv") : unlisted,
1273
+ ...backend.r2 ? { r2: r2Names.length > 0 ? backend.r2.list(r2Names) : unlisted } : {},
1274
+ inference,
1275
+ mayCreate: Boolean(options.provision) || !options.ci && (interactive || Boolean(options.yes))
1276
+ };
1277
+ const bindings = buildPlan(context).bindings;
1278
+ const chosen = backend.migrationsBinding();
1279
+ backend.prepareReads(bindings);
1280
+ const databaseBinding = chosen.ok ? chosen.value : void 0;
1281
+ const database = bindings.find((binding) => binding.binding === databaseBinding);
1282
+ return {
1283
+ plan: buildPlan({
1284
+ ...context,
1285
+ ...process.env.GITHUB_ACTIONS === "true" ? { workflow: readRunningWorkflow(root) } : {},
1286
+ ...typeof previous.scheduleUnreadable === "string" ? { scheduleUnreadable: previous.scheduleUnreadable } : {},
1287
+ migrations: options.skipMigrations ? void 0 : !chosen.ok ? unchosenDatabase(root, chosen.reason) : database ? readMigrations(root, backend, database, options) : void 0,
1288
+ secrets: await readSecrets(backend, worker, options.secretsFile, root)
1289
+ }),
1290
+ interactive,
1291
+ root,
1292
+ backend,
1293
+ databaseBinding
1294
+ };
1295
+ }
1296
+ /** No D1 binding could be picked for `db/migrations`: a blocker only when there is something to apply. */
1297
+ function unchosenDatabase(root, reason) {
1298
+ const local = readLocalMigrations(join(root, "db", "migrations"));
1299
+ return local.folders.length === 0 && local.files.length === 0 ? void 0 : {
1300
+ status: "unassigned",
1301
+ reason
1302
+ };
1303
+ }
1304
+ /** Every stage of RFC 0035 §1. Throws only before stage 4; after it, failures are reported with what to clean up. */
1305
+ async function runCloudflareDeploy(input) {
1306
+ const options = {
1307
+ ...input,
1308
+ interactive: input.interactive ?? Boolean(process.stdin.isTTY)
1309
+ };
1310
+ if (!options.plan && !options.yes && !options.ci && !options.interactive) throw new Error("Cloudflare deploy: no terminal to confirm the plan on. Pass --yes to deploy it, --ci to deploy without creating anything, or --plan to only plan.");
1311
+ const prepared = await prepare(options);
1312
+ const { plan } = prepared;
1313
+ if (options.plan) return {
1314
+ plan,
1315
+ stopped: "plan",
1316
+ created: []
1317
+ };
1318
+ if (hasBlocker(plan)) return {
1319
+ plan,
1320
+ stopped: "blocked",
1321
+ created: []
1322
+ };
1323
+ if (prepared.interactive && !options.yes) {
1324
+ if (!await (options.confirm ?? confirmOnTerminal)(plan)) return {
1325
+ plan,
1326
+ stopped: "declined",
1327
+ created: []
1328
+ };
1329
+ return {
1330
+ ...await applyPlan(prepared, options),
1331
+ confirmed: true
1332
+ };
1333
+ }
1334
+ return applyPlan(prepared, options);
1335
+ }
1336
+ async function confirmOnTerminal(plan) {
1337
+ console.error(formatPlan(plan));
1338
+ const prompt = createInterface({
1339
+ input: process.stdin,
1340
+ output: process.stderr
1341
+ });
1342
+ try {
1343
+ return /^y(es)?$/i.test((await prompt.question("Apply this plan to the account? [y/N] ")).trim());
1344
+ } finally {
1345
+ prompt.close();
1346
+ }
1347
+ }
1348
+ async function applyPlan(prepared, options) {
1349
+ const { plan, root, backend, databaseBinding } = prepared;
1350
+ const result = {
1351
+ plan,
1352
+ created: []
1353
+ };
1354
+ const fail = (stage, message, bookmark) => ({
1355
+ ...result,
1356
+ failure: {
1357
+ stage,
1358
+ message,
1359
+ cleanup: [...bookmark ? [BACKEND_WORDS[backend.kind].restore(bookmark, bookmark.value)] : [], ...result.created.map((resource) => BACKEND_WORDS[backend.kind].delete(resource))]
1360
+ }
1361
+ });
1362
+ const resolved = {};
1363
+ for (const binding of plan.bindings) {
1364
+ let id = binding.id;
1365
+ if (binding.action === "create") {
1366
+ const created = binding.type === "r2" ? backend.r2.create(binding.name) : backend.create(binding.type, binding.name);
1367
+ if (!created.ok) return fail("provision", `${created.reason}. If the resource was created anyway, the next plan finds it by name and adopts it.`);
1368
+ id = created.value;
1369
+ result.created.push({
1370
+ binding: binding.binding,
1371
+ type: binding.type,
1372
+ name: binding.name,
1373
+ id
1374
+ });
1375
+ }
1376
+ if (id && !binding.configured) resolved[binding.binding] = binding.type === "kv" ? { id } : {
1377
+ id,
1378
+ name: binding.name
1379
+ };
1380
+ }
1381
+ const outDir = join(root, backend.outputDir);
1382
+ const previous = readResolvedResources(outDir);
1383
+ const merged = {
1384
+ ...previous,
1385
+ ...resolved
1386
+ };
1387
+ for (const binding of plan.bindings) if (binding.configured) delete merged[binding.binding];
1388
+ if (!sameResolution(previous, merged)) {
1389
+ if (!writeResolved(outDir, merged)) return fail("provision", `${join(outDir, WORKER_MANIFEST_FILE)} could not be read back, so the resolved ids were not recorded. Run cloudflare:build, then deploy again.`);
1390
+ const rebuilt = backend.rebuild(resolved);
1391
+ if (!rebuilt.ok) return fail("build", rebuilt.reason);
1392
+ }
1393
+ const migrations = plan.migrations;
1394
+ const planned = plan.bindings.find((binding) => binding.binding === databaseBinding);
1395
+ const databaseId = databaseBinding ? resolved[databaseBinding]?.id ?? planned?.id : void 0;
1396
+ let restore;
1397
+ if (!options.skipMigrations && migrations && migrations.pending.length > 0 && planned && databaseId) {
1398
+ const database = {
1399
+ ...planned,
1400
+ action: "existing",
1401
+ id: databaseId
1402
+ };
1403
+ const bookmark = backend.bookmark(database);
1404
+ if (!bookmark.ok) return fail("migrate", `${bookmark.reason}. No migration was applied without a point to restore to.`);
1405
+ const now = readMigrations(root, backend, database, options);
1406
+ if (now?.status !== "ready" || now.layout !== migrations.layout || now.fingerprint !== migrations.fingerprint) return fail("migrate", now?.status === "unreadable" ? `${now.reason}. Nothing was applied.` : "The pending migrations changed since the plan judged them, by another run or an edit. Nothing was applied; plan again.");
1407
+ restore = {
1408
+ binding: planned.binding,
1409
+ id: databaseId,
1410
+ name: planned.name,
1411
+ value: bookmark.value
1412
+ };
1413
+ const applied = backend.applyMigrations(database, migrations.applyArgs);
1414
+ if (!applied.ok) return fail("migrate", applied.reason, restore);
1415
+ result.migrated = {
1416
+ applied: migrations.pending,
1417
+ bookmark: bookmark.value
1418
+ };
1419
+ }
1420
+ const deployed = backend.deploy(options.secretsFile ? resolve(options.secretsFile) : void 0);
1421
+ if (!deployed.ok) return fail("deploy", deployed.reason, restore);
1422
+ result.deployment = { output: deployed.value };
1423
+ const url = /https:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/.exec(deployed.value)?.[0];
1424
+ return url ? {
1425
+ ...result,
1426
+ url
1427
+ } : result;
1428
+ }
1429
+ function sameResolution(before, after) {
1430
+ return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].every((key) => before[key]?.id === after[key]?.id && before[key]?.name === after[key]?.name);
1431
+ }
1432
+ /** Replaces only `resolved`, keeping the rest of what the build wrote; false when there is no manifest to keep. */
1433
+ function writeResolved(outDir, resolved) {
1434
+ const manifest = readWorkerManifest(outDir);
1435
+ if (manifest.version === void 0) return false;
1436
+ writeFileSync(join(outDir, WORKER_MANIFEST_FILE), `${JSON.stringify({
1437
+ ...manifest,
1438
+ resolved
1439
+ }, null, 2)}\n`);
1440
+ return true;
1441
+ }
1442
+ /** GITHUB_WORKFLOW_REF is `owner/repo/.github/workflows/<file>@<ref>`; the file is read from the checkout. */
1443
+ function readRunningWorkflow(root) {
1444
+ const ref = process.env.GITHUB_WORKFLOW_REF ?? "";
1445
+ const path = /\/(\.github\/workflows\/[^@]+)@/.exec(ref)?.[1];
1446
+ if (!path) return {
1447
+ ok: false,
1448
+ reason: "GITHUB_WORKFLOW_REF names no workflow file"
1449
+ };
1450
+ try {
1451
+ return {
1452
+ ok: true,
1453
+ value: readFileSync(resolve(process.env.GITHUB_WORKSPACE ?? root, path), "utf8")
1454
+ };
1455
+ } catch (error) {
1456
+ return {
1457
+ ok: false,
1458
+ reason: error instanceof Error ? error.message : String(error)
1459
+ };
1460
+ }
1461
+ }
1462
+ function readMigrations(root, backend, database, options) {
1463
+ const migrationsDir = join(root, "db", "migrations");
1464
+ const local = readLocalMigrations(migrationsDir);
1465
+ if (local.folders.length === 0 && local.files.length === 0) return void 0;
1466
+ if (database.action === "unknown") return void 0;
1467
+ let tracker = null;
1468
+ if (database.action !== "create" && database.id) {
1469
+ const read = backend.readTracker({
1470
+ ...database,
1471
+ id: database.id
1472
+ });
1473
+ if (!read.ok) return {
1474
+ status: "unreadable",
1475
+ reason: read.reason
1476
+ };
1477
+ tracker = read.value;
1478
+ }
1479
+ const decision = decideLayout(local, tracker, backend.appliesNested);
1480
+ if (!decision.ok) return "unsupported" in decision ? {
1481
+ status: "layout-unsupported",
1482
+ nested: decision.nested
1483
+ } : {
1484
+ status: "layout-conflict",
1485
+ nested: decision.nested,
1486
+ flat: decision.flat
1487
+ };
1488
+ let verdict;
1489
+ try {
1490
+ verdict = judgePendingMigrations(migrationsDir, decision.pendingFolders, "db/migrations");
1491
+ } catch (error) {
1492
+ return {
1493
+ status: "unreadable",
1494
+ reason: error instanceof Error ? error.message : String(error)
1495
+ };
1496
+ }
1497
+ return {
1498
+ status: "ready",
1499
+ layout: decision.layout,
1500
+ applyArgs: backend.applyArgs(decision.layout),
1501
+ pending: decision.pending,
1502
+ unjudged: decision.pendingFiles,
1503
+ verdict,
1504
+ fingerprint: fingerprintMigrations(migrationsDir, decision.pending),
1505
+ allowDestructive: options.allowDestructive === true || process.env[ALLOW_DESTRUCTIVE_ENV] === "1"
1506
+ };
1507
+ }
1508
+ /** Binding types whose value the config itself provides. A `secret` binding only declares one. */
1509
+ const VALUE_BINDING_TYPES = /* @__PURE__ */ new Set(["text", "json"]);
1510
+ async function readSecrets(backend, worker, secretsFile, root) {
1511
+ const provided = Object.entries(worker.env).filter(([, entry]) => VALUE_BINDING_TYPES.has(entry.type)).map(([name]) => name);
1512
+ if (secretsFile) {
1513
+ let content;
1514
+ try {
1515
+ content = readFileSync(resolve(secretsFile), "utf8");
1516
+ } catch (error) {
1517
+ throw new Error(`Cloudflare deploy: --secrets-file ${secretsFile} could not be read (${error instanceof Error ? error.message : String(error)}).`);
1518
+ }
1519
+ const keys = await readEnvFileKeys(content);
1520
+ if (typeof keys === "string") throw new Error(`Cloudflare deploy: --secrets-file could not be read: ${keys}.`);
1521
+ provided.push(...keys);
1522
+ }
1523
+ const required = await readRequiredDeployEnv(root);
1524
+ return {
1525
+ required,
1526
+ deployed: required.status === "loaded" && required.required.some((name) => !provided.includes(name)) ? backend.listSecrets(worker.name) : {
1527
+ ok: true,
1528
+ value: []
1529
+ },
1530
+ provided,
1531
+ ...secretsFile ? { secretsFile } : {}
1532
+ };
1533
+ }
1534
+ async function withStdoutLogs(toStderr, run) {
1535
+ if (!toStderr) return run();
1536
+ const log = console.log;
1537
+ console.log = console.error;
1538
+ try {
1539
+ return await run();
1540
+ } finally {
1541
+ console.log = log;
1542
+ }
1543
+ }
1544
+ //#endregion
1545
+ //#region src/init.ts
1546
+ /**
1547
+ * `guren cloudflare:init` (RFC 0035 §3): moves an app onto the `cf` backend by
1548
+ * writing `cloudflare.config.ts`, `wrangler.config.ts` and `config/cloudflare.ts`.
1549
+ * It installs nothing, raises `cf` and `wrangler` in package.json, and skips a file that
1550
+ * exists unless forced. From a `wrangler.jsonc` it carries over what decides which
1551
+ * resources the Worker binds, and names every setting it leaves behind.
1552
+ */
1553
+ /** The build's D1 binding (`WorkerManifest.d1.binding`). */
1554
+ const DATABASE_BINDING = "DB";
1555
+ const FILES = [
1556
+ "cloudflare.config.ts",
1557
+ "wrangler.config.ts",
1558
+ "config/cloudflare.ts"
1559
+ ];
1560
+ /** wrangler.jsonc keys the build owns or init carries over; the rest are named as left behind. */
1561
+ const HANDLED_KEYS = /* @__PURE__ */ new Set([
1562
+ "$schema",
1563
+ "name",
1564
+ "main",
1565
+ "compatibility_date",
1566
+ "compatibility_flags",
1567
+ "alias",
1568
+ "define",
1569
+ "assets",
1570
+ "d1_databases",
1571
+ "kv_namespaces",
1572
+ "durable_objects",
1573
+ "migrations",
1574
+ "vars"
1575
+ ]);
1576
+ async function initCloudflare(options) {
1577
+ const root = resolve(options.rootDir);
1578
+ const wrangler = readWranglerConfig(resolve(root, "wrangler.jsonc"));
1579
+ const defaultName = workerName(readPackageJson(root).name);
1580
+ const worker = typeof wrangler?.name === "string" ? wrangler.name : defaultName;
1581
+ const databaseName = wrangler ? bindingEntry(wrangler.d1_databases, DATABASE_BINDING)?.database_name : void 0;
1582
+ const oauthKv = wrangler ? bindingEntry(wrangler.kv_namespaces, OAUTH_KV_BINDING) : void 0;
1583
+ const carried = {
1584
+ worker,
1585
+ compatibilityDate: options.compatibilityDate ?? (typeof wrangler?.compatibility_date === "string" ? wrangler.compatibility_date : (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)),
1586
+ ...typeof databaseName === "string" && databaseName !== worker ? { databaseName } : {},
1587
+ ...typeof oauthKv?.id === "string" && !isPlaceholderId(oauthKv.id) ? { oauthKvId: oauthKv.id } : {}
1588
+ };
1589
+ const contents = {
1590
+ "cloudflare.config.ts": cloudflareConfigSource(carried),
1591
+ "wrangler.config.ts": WRANGLER_CONFIG_SOURCE,
1592
+ "config/cloudflare.ts": deployConfigSource(oauthKv !== void 0, carried.databaseName)
1593
+ };
1594
+ const written = [];
1595
+ const skipped = [];
1596
+ for (const file of FILES) {
1597
+ const path = resolve(root, file);
1598
+ mkdirSync(dirname(path), { recursive: true });
1599
+ try {
1600
+ writeFileSync(path, contents[file], { flag: options.force ? "w" : "wx" });
1601
+ } catch (error) {
1602
+ if (error.code !== "EEXIST") throw error;
1603
+ skipped.push(file);
1604
+ continue;
1605
+ }
1606
+ written.push(file);
1607
+ }
1608
+ ignoreCfOutput(root);
1609
+ return {
1610
+ written,
1611
+ skipped,
1612
+ carried: wrangler ? describeCarried(carried, oauthKv !== void 0) : [],
1613
+ warnings: wrangler ? [...leftBehind(wrangler), ...await durableObjectWarnings(root, wrangler)] : [],
1614
+ dependencies: raiseCfDependencies(root)
1615
+ };
1616
+ }
1617
+ function bindingEntry(entries, binding) {
1618
+ return asArray(entries).find((entry) => isRecord(entry) && entry.binding === binding);
1619
+ }
1620
+ function describeCarried(carried, mcpOAuth) {
1621
+ return [
1622
+ `the Worker name "${carried.worker}" and compatibility date ${carried.compatibilityDate}`,
1623
+ ...carried.databaseName ? [`the D1 database "${carried.databaseName}" (resourceNames.DB)`] : [],
1624
+ ...mcpOAuth ? [`the OAUTH_KV binding (mcpOAuth: true${carried.oauthKvId ? `, its namespace id in cloudflare.config.ts` : ""})`] : []
1625
+ ];
1626
+ }
1627
+ /** Settings cf does not read, so the first cf deploy would drop them unannounced. */
1628
+ function leftBehind(wrangler) {
1629
+ const warnings = [];
1630
+ const keys = Object.keys(wrangler).filter((key) => !HANDLED_KEYS.has(key));
1631
+ const flags = asArray(wrangler.compatibility_flags).filter((flag) => flag !== "nodejs_compat");
1632
+ const vars = isRecord(wrangler.vars) ? Object.keys(wrangler.vars).filter((key) => key !== "NODE_ENV") : [];
1633
+ const extraBindings = [...asArray(wrangler.d1_databases), ...asArray(wrangler.kv_namespaces)].filter(isRecord).filter((entry) => entry.binding !== DATABASE_BINDING && entry.binding !== "OAUTH_KV").map((entry) => String(entry.binding));
1634
+ const notCarried = [
1635
+ ...keys,
1636
+ ...flags.map((flag) => `compatibility_flags ${String(flag)}`),
1637
+ ...vars.map((key) => `vars.${key}`),
1638
+ ...extraBindings.map((binding) => `the ${binding} binding`)
1639
+ ];
1640
+ if (notCarried.length > 0) warnings.push(`wrangler.jsonc sets ${notCarried.join(", ")}, which cf does not read. Add them to cloudflare.config.ts after the gurenWorker() spread before deploying.`);
1641
+ return warnings;
1642
+ }
1643
+ /**
1644
+ * gurenWorker() declares the agents config/agents.ts registers as cf `exports`, and the generated
1645
+ * worker exports only those classes. Any other live class, or a binding to another Worker, has no
1646
+ * declaration on cf, so the first deploy could drop its storage; each is named.
1647
+ */
1648
+ async function durableObjectWarnings(root, wrangler) {
1649
+ if (!declaresDurableObjects(wrangler)) return [];
1650
+ const warnings = ["wrangler.jsonc declares Durable Objects through `migrations`; on cf, gurenWorker() declares the registered agents as `exports`. Whether a deployed class keeps its storage across that move is unconfirmed (RFC 0035 Open Question 5), so try it on a staging Worker first."];
1651
+ let agents;
1652
+ try {
1653
+ agents = await agentClasses(root);
1654
+ } catch (error) {
1655
+ return [...warnings, `config/agents.ts could not be read (${error instanceof Error ? error.message : String(error)}), so which Durable Objects are agents is unknown; check every class before deploying.`];
1656
+ }
1657
+ const unregistered = [...new Set(configScopes(wrangler).flatMap(({ config }) => [...durableObjectStorage(config).keys()]))].filter((name) => !agents.has(name));
1658
+ if (unregistered.length > 0) warnings.push(`The Durable Object class ${unregistered.join(", ")} is not an agent in config/agents.ts. The worker cloudflare:build generates exports only registered agents, so on cf nothing declares it: register it as an agent, or export it from the worker and declare it with exports.durableObject().`);
1659
+ const remote = configScopes(wrangler).flatMap(({ config }) => durableObjectBindings(config).filter((entry) => entry.scriptName !== void 0).map((entry) => entry.name));
1660
+ if (remote.length > 0) warnings.push(`The Durable Object binding ${remote.join(", ")} points at another Worker; bind it in cloudflare.config.ts with bindings.durableObject().`);
1661
+ if (asArray(wrangler.migrations).some((step) => isRecord(step) && [
1662
+ "renamed_classes",
1663
+ "deleted_classes",
1664
+ "transferred_classes"
1665
+ ].some((key) => asArray(step[key]).length > 0))) warnings.push("wrangler.jsonc migrations rename, delete or transfer a Durable Object class; declare those steps with exports.durableObject({ state }) in cloudflare.config.ts.");
1666
+ return warnings;
1667
+ }
1668
+ /** The agent classes gurenWorker() hosts from config/agents.ts, the registry the build reads. */
1669
+ async function agentClasses(root) {
1670
+ if (!existsSync(resolve(root, "config/agents.ts"))) return /* @__PURE__ */ new Set();
1671
+ assertAgentsPluginUsable(root);
1672
+ return new Set((await readAgentRegistry(root)).exports.map((agent) => agent.export));
1673
+ }
1674
+ /**
1675
+ * Raises what the cf backend needs in package.json (RFC 0035 §7): `cf` and `wrangler` when absent
1676
+ * or when the declared range starts below the verified version. A range it cannot read (`latest`,
1677
+ * `catalog:`, `workspace:*`) is left as it is: the preflight checks what is installed.
1678
+ */
1679
+ function raiseCfDependencies(root) {
1680
+ const path = resolve(root, "package.json");
1681
+ let text;
1682
+ let manifest;
1683
+ try {
1684
+ text = readFileSync(path, "utf8");
1685
+ manifest = JSON.parse(text);
1686
+ } catch {
1687
+ return [];
1688
+ }
1689
+ if (!isRecord(manifest)) return [];
1690
+ const dependencies = isRecord(manifest.dependencies) ? { ...manifest.dependencies } : void 0;
1691
+ const devDependencies = isRecord(manifest.devDependencies) ? { ...manifest.devDependencies } : {};
1692
+ const raised = {};
1693
+ for (const [name, floor, range] of [[
1694
+ "cf",
1695
+ CF_VERSION,
1696
+ CF_VERSION
1697
+ ], [
1698
+ "wrangler",
1699
+ CF_WRANGLER_FLOOR,
1700
+ `^${CF_WRANGLER_FLOOR}`
1701
+ ]]) {
1702
+ const declared = dependencies?.[name] ?? devDependencies[name];
1703
+ if (declared === void 0 || startsBelow(declared, floor)) raised[name] = range;
1704
+ }
1705
+ if (Object.keys(raised).length === 0) return [];
1706
+ for (const [name, range] of Object.entries(raised)) if (dependencies && name in dependencies) dependencies[name] = range;
1707
+ else devDependencies[name] = range;
1708
+ const indent = /^(\s+)"/m.exec(text)?.[1] ?? " ";
1709
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
1710
+ const json = JSON.stringify({
1711
+ ...manifest,
1712
+ ...dependencies ? { dependencies } : {},
1713
+ devDependencies
1714
+ }, null, indent);
1715
+ writeFileSync(path, `${json.replaceAll("\n", eol)}${eol}`);
1716
+ return Object.entries(raised).map(([name, range]) => `${name}@${range}`);
1717
+ }
1718
+ /** Whether a range's lowest version (`^4.140`, `>=4.129.0 <5`, `1.0.0-beta.10`) is below `floor`; false when there is none to read. */
1719
+ function startsBelow(range, floor) {
1720
+ const match = typeof range === "string" ? /(\d+)(?:\.(\d+))?(?:\.(\d+))?(-[\w.]+)?/.exec(range) : null;
1721
+ if (!match) return false;
1722
+ const lowest = `${match[1]}.${match[2] ?? 0}.${match[3] ?? 0}${match[4] ?? ""}`;
1723
+ return !Bun.semver.satisfies(lowest, `>=${floor}${floor.includes("-") ? "" : "-0"}`);
1724
+ }
1725
+ function declaresDurableObjects(wrangler) {
1726
+ return configScopes(wrangler).some(({ config }) => {
1727
+ const bindings = isRecord(config.durable_objects) ? config.durable_objects.bindings : void 0;
1728
+ return asArray(bindings).length > 0 || asArray(config.migrations).length > 0;
1729
+ });
1730
+ }
1731
+ /** `cf build` writes `.cloudflare/`, which is output; the build's own `.guren/cloudflare/` ignores itself. */
1732
+ function ignoreCfOutput(root) {
1733
+ const fd = openSync(resolve(root, ".gitignore"), "a+");
1734
+ try {
1735
+ const current = readFileSync(fd, "utf8");
1736
+ if (/^\/?\.cloudflare\/?\r?$/m.test(current)) return;
1737
+ writeSync(fd, `${current === "" || current.endsWith("\n") ? "" : "\n"}.cloudflare/\n`);
1738
+ } finally {
1739
+ closeSync(fd);
1740
+ }
1741
+ }
1742
+ function cloudflareConfigSource(carried) {
1743
+ const env = carried.oauthKvId ? `
1744
+ env: { ...worker.env, OAUTH_KV: bindings.kv({ id: ${JSON.stringify(carried.oauthKvId)} }) },` : "";
1745
+ return `import { ${carried.oauthKvId ? "bindings, " : ""}defineConfig } from 'cf/config'
1746
+ import { gurenWorker } from '@guren/plugin-cloudflare/config'
1747
+
1748
+ export default defineConfig(async () => {
1749
+ const worker = await gurenWorker({ name: ${JSON.stringify(carried.worker)} })
1750
+ return {
1751
+ worker: {
1752
+ ...worker,
1753
+ compatibilityDate: ${JSON.stringify(carried.compatibilityDate)},${env}
1754
+ },
1755
+ }
1756
+ })
1757
+ `;
1758
+ }
1759
+ const WRANGLER_CONFIG_SOURCE = `import { defineWranglerConfig } from 'wrangler/experimental-config'
1760
+ import { gurenWranglerBundle } from '@guren/plugin-cloudflare/config'
1761
+
1762
+ export default defineWranglerConfig(gurenWranglerBundle())
1763
+ `;
1764
+ function deployConfigSource(mcpOAuth, databaseName) {
1765
+ const lines = [` mcpOAuth: ${mcpOAuth},`];
1766
+ if (databaseName) lines.push(` resourceNames: { DB: ${JSON.stringify(databaseName)} },`);
1767
+ return `import { defineCloudflareConfig } from '@guren/plugin-cloudflare/config'
1768
+
1769
+ export default defineCloudflareConfig({
1770
+ ${lines.join("\n")}
1771
+ })
1772
+ `;
1773
+ }
1774
+ //#endregion
3
1775
  //#region src/commands.ts
4
1776
  const rootArg = {
5
1777
  type: "string",
@@ -13,62 +1785,181 @@ function topOf(value) {
13
1785
  const parsed = Number.parseInt(value ?? "", 10);
14
1786
  return Number.isInteger(parsed) && parsed > 0 ? parsed : void 0;
15
1787
  }
1788
+ const cloudflareBuild = defineCommand({
1789
+ meta: {
1790
+ name: "cloudflare:build",
1791
+ description: "Assemble a Cloudflare Workers deployment from the app build (.cloudflare/, or .guren/cloudflare/ on the cf backend)"
1792
+ },
1793
+ args: {
1794
+ root: rootArg,
1795
+ "skip-app-build": {
1796
+ type: "boolean",
1797
+ description: "Skip running the app's build script before assembling output"
1798
+ },
1799
+ "mcp-oauth": {
1800
+ type: "boolean",
1801
+ description: "Front the App MCP endpoint with @cloudflare/workers-oauth-provider, scaffold the consent flow, and make the OAUTH_KV binding build-owned (requires @guren/plugin-mcp)"
1802
+ },
1803
+ "mcp-path": {
1804
+ type: "string",
1805
+ description: "Path the App MCP endpoint is mounted at, protected as the OAuth apiRoute (default /mcp; must match mcpPlugin({ path }))"
1806
+ },
1807
+ "report-size": {
1808
+ type: "boolean",
1809
+ description: "After assembling, run wrangler's dry run and print the bundle size with its largest sources (what cloudflare:size prints)"
1810
+ },
1811
+ top: topArg
1812
+ },
1813
+ async run({ args }) {
1814
+ const rootDir = args.root || process.cwd();
1815
+ if (args["report-size"]) assertSizeReportable(rootDir, "Cloudflare build --report-size");
1816
+ await buildCloudflareOutput({
1817
+ rootDir,
1818
+ skipAppBuild: Boolean(args["skip-app-build"]),
1819
+ mcpOAuth: Boolean(args["mcp-oauth"]),
1820
+ ...args["mcp-path"] ? { mcpPath: args["mcp-path"] } : {}
1821
+ });
1822
+ if (args["report-size"]) printBundleReport(reportBundleSize({
1823
+ root: rootDir,
1824
+ top: topOf(args.top)
1825
+ }));
1826
+ }
1827
+ });
1828
+ const cloudflareSize = defineCommand({
1829
+ meta: {
1830
+ name: "cloudflare:size",
1831
+ description: "Measure the worker bundle wrangler would upload from .cloudflare/ and attribute it to its largest sources"
1832
+ },
1833
+ args: {
1834
+ root: rootArg,
1835
+ top: topArg
1836
+ },
1837
+ run({ args }) {
1838
+ printBundleReport(reportBundleSize({
1839
+ root: args.root || process.cwd(),
1840
+ top: topOf(args.top)
1841
+ }));
1842
+ }
1843
+ });
1844
+ const cloudflareDeploy = defineCommand({
1845
+ meta: {
1846
+ name: "cloudflare:deploy",
1847
+ description: "Deploy through the cf CLI, or Wrangler for an app on wrangler.jsonc (RFC 0035): build, plan every D1/KV binding, migration and secret against the account, then create, migrate and deploy after one confirmation"
1848
+ },
1849
+ args: {
1850
+ root: rootArg,
1851
+ plan: {
1852
+ type: "boolean",
1853
+ description: "Stop after the plan, writing nothing to the account"
1854
+ },
1855
+ yes: {
1856
+ type: "boolean",
1857
+ description: "Apply the plan without asking; a run with no terminal needs this or --ci"
1858
+ },
1859
+ "skip-migrations": {
1860
+ type: "boolean",
1861
+ description: "Deploy without applying the pending migrations"
1862
+ },
1863
+ ci: {
1864
+ type: "boolean",
1865
+ description: "Never create a missing resource unless --provision is passed"
1866
+ },
1867
+ provision: {
1868
+ type: "boolean",
1869
+ description: "Allow creating missing resources even under --ci or without a terminal"
1870
+ },
1871
+ json: {
1872
+ type: "boolean",
1873
+ description: "Print { plan, created, migrated, deployment, url } as one JSON object"
1874
+ },
1875
+ "mcp-oauth": {
1876
+ type: "boolean",
1877
+ description: "Build with --mcp-oauth, which binds OAUTH_KV (the plan rebuilds the deployable output, so pass what cloudflare:build gets)"
1878
+ },
1879
+ "mcp-path": {
1880
+ type: "string",
1881
+ description: "Path the App MCP endpoint is mounted at, as for cloudflare:build --mcp-path"
1882
+ },
1883
+ "skip-app-build": {
1884
+ type: "boolean",
1885
+ description: "Skip running the app's build script"
1886
+ },
1887
+ "allow-destructive": {
1888
+ type: "boolean",
1889
+ description: "Accept pending destructive migration statements no -- guren:allow-destructive marker covers (still listed)"
1890
+ },
1891
+ "secrets-file": {
1892
+ type: "string",
1893
+ description: "A dotenv file of secrets for the deploy; the plan reads only the names it assigns"
1894
+ }
1895
+ },
1896
+ async run({ args }) {
1897
+ const result = await runCloudflareDeploy({
1898
+ root: args.root || process.cwd(),
1899
+ plan: Boolean(args.plan),
1900
+ yes: Boolean(args.yes),
1901
+ skipMigrations: Boolean(args["skip-migrations"]),
1902
+ ci: Boolean(args.ci),
1903
+ provision: Boolean(args.provision),
1904
+ mcpOAuth: Boolean(args["mcp-oauth"]),
1905
+ ...args["mcp-path"] ? { mcpPath: args["mcp-path"] } : {},
1906
+ skipAppBuild: Boolean(args["skip-app-build"]),
1907
+ allowDestructive: Boolean(args["allow-destructive"]),
1908
+ ...args["secrets-file"] ? { secretsFile: args["secrets-file"] } : {},
1909
+ logToStderr: Boolean(args.json)
1910
+ });
1911
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatResult(result));
1912
+ if (result.stopped === "blocked" || result.stopped === "declined" || result.failure) process.exitCode = 1;
1913
+ }
1914
+ });
16
1915
  var commands_default = {
17
- "cloudflare:build": defineCommand({
1916
+ "cloudflare:init": defineCommand({
18
1917
  meta: {
19
- name: "cloudflare:build",
20
- description: "Assemble a Cloudflare Workers deployment (.cloudflare/) from the app build"
1918
+ name: "cloudflare:init",
1919
+ description: "Move the app onto the cf CLI: write cloudflare.config.ts, wrangler.config.ts and config/cloudflare.ts, carrying over what wrangler.jsonc decided"
21
1920
  },
22
1921
  args: {
23
1922
  root: rootArg,
24
- "skip-app-build": {
1923
+ force: {
25
1924
  type: "boolean",
26
- description: "Skip running the app's build script before assembling output"
1925
+ description: "Rewrite those files when they exist (otherwise they are left as they are)"
27
1926
  },
28
- "mcp-oauth": {
1927
+ plan: {
29
1928
  type: "boolean",
30
- description: "Front the App MCP endpoint with @cloudflare/workers-oauth-provider, scaffold the consent flow, and make the OAUTH_KV binding build-owned (requires @guren/plugin-mcp)"
31
- },
32
- "mcp-path": {
33
- type: "string",
34
- description: "Path the App MCP endpoint is mounted at, protected as the OAuth apiRoute (default /mcp; must match mcpPlugin({ path }))"
35
- },
36
- "report-size": {
37
- type: "boolean",
38
- description: "After assembling, run wrangler's dry run and print the bundle size with its largest sources (what cloudflare:size prints)"
39
- },
40
- top: topArg
1929
+ description: "Then plan a deploy on the cf backend, which should show nothing to create (needs the dependencies installed)"
1930
+ }
41
1931
  },
42
1932
  async run({ args }) {
43
1933
  const rootDir = args.root || process.cwd();
44
- await buildCloudflareOutput({
1934
+ const result = await initCloudflare({
45
1935
  rootDir,
46
- skipAppBuild: Boolean(args["skip-app-build"]),
47
- mcpOAuth: Boolean(args["mcp-oauth"]),
48
- ...args["mcp-path"] ? { mcpPath: args["mcp-path"] } : {}
1936
+ force: Boolean(args.force)
49
1937
  });
50
- if (args["report-size"]) printBundleReport(reportBundleSize({
51
- root: rootDir,
52
- top: topOf(args.top)
53
- }));
1938
+ if (result.written.length > 0) console.log(`Cloudflare init: wrote ${result.written.join(", ")}.`);
1939
+ if (result.skipped.length > 0) console.log(`Cloudflare init: left ${result.skipped.join(", ")} as they are; --force rewrites them.`);
1940
+ if (result.dependencies.length > 0) console.log(`Cloudflare init: raised ${result.dependencies.join(", ")} in package.json; run \`bun install\`.`);
1941
+ for (const carried of result.carried) console.log(` Carried over from wrangler.jsonc: ${carried}.`);
1942
+ for (const warning of result.warnings) console.warn(` ${warning}`);
1943
+ if (!args.plan || result.dependencies.length > 0) {
1944
+ if (args.plan) console.log("Cloudflare init: not planning until the raised dependencies are installed.");
1945
+ console.log([
1946
+ "Next:",
1947
+ ...result.dependencies.length > 0 ? [" bun install"] : [],
1948
+ " bunx guren cloudflare:deploy --plan # needs Node 22.18+ as the node on PATH, and `bunx cf auth login`"
1949
+ ].join("\n"));
1950
+ return;
1951
+ }
1952
+ try {
1953
+ console.log(formatPlan(await planCloudflareDeploy({ root: rootDir })));
1954
+ } catch (error) {
1955
+ console.error(`Cloudflare init: the files are written, but the plan could not run: ${error instanceof Error ? error.message : String(error)}`);
1956
+ process.exitCode = 1;
1957
+ }
54
1958
  }
55
1959
  }),
56
- "cloudflare:size": defineCommand({
57
- meta: {
58
- name: "cloudflare:size",
59
- description: "Measure the worker bundle wrangler would upload from .cloudflare/ and attribute it to its largest sources"
60
- },
61
- args: {
62
- root: rootArg,
63
- top: topArg
64
- },
65
- run({ args }) {
66
- printBundleReport(reportBundleSize({
67
- root: args.root || process.cwd(),
68
- top: topOf(args.top)
69
- }));
70
- }
71
- })
1960
+ "cloudflare:build": cloudflareBuild,
1961
+ "cloudflare:size": cloudflareSize,
1962
+ "cloudflare:deploy": cloudflareDeploy
72
1963
  };
73
1964
  //#endregion
74
1965
  export { commands_default as default };