@moku-labs/worker 0.9.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,34 +1,765 @@
1
- import { a as kvPlugin, c as d1Plugin, d as createCore, f as createPlugin$1, i as queuesPlugin, l as bindingsPlugin, n as deployPlugin, o as durableObjectsPlugin, p as stagePlugin, r as storagePlugin, s as defineDurableObject, t as cliPlugin, u as coreConfig } from "./cli--EPl98vG.mjs";
2
- import { envPlugin, logPlugin } from "@moku-labs/common";
3
- //#region src/env-provider.ts
1
+ import { envPlugin, envPlugin as envPlugin$1, logPlugin, logPlugin as logPlugin$1 } from "@moku-labs/common";
2
+ import { createCoreConfig, createCorePlugin } from "@moku-labs/core";
3
+ import { brandedSink, createBrandConsole, createBrandPrompts } from "@moku-labs/common/cli";
4
+ import { access, readdir, stat, writeFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { spawn } from "node:child_process";
7
+ import { existsSync, readFileSync, watch } from "node:fs";
4
8
  /**
5
- * Build the default env provider: a shallow copy of `process.env` when a `process` global exists,
6
- * else an empty record. Safe to evaluate at Worker cold start — it never throws on a missing
7
- * `process` (typeof of an undeclared identifier is the string "undefined", not a ReferenceError).
9
+ * stage core plugin deployment-stage / dev-mode detection, flat-injected on
10
+ * every regular plugin's context as `ctx.stage` (spec/02 §6). No state, no
11
+ * events, no depends, no lifecycle hooks.
8
12
  *
9
- * @returns An {@link EnvProvider} named `worker-process-env`.
13
+ * @see README.md
14
+ * @example
15
+ * ```typescript
16
+ * // Inside any regular plugin's api factory:
17
+ * api: (ctx) => ({
18
+ * errorBody: (e: Error) =>
19
+ * ctx.stage.isDev() ? e.stack ?? e.message : "Internal Error",
20
+ * })
21
+ * ```
22
+ */
23
+ const stagePlugin = createCorePlugin("stage", {
24
+ config: { stage: "production" },
25
+ /**
26
+ * Builds the stage accessor surface from the resolved stage.
27
+ *
28
+ * @param ctx - Core plugin context (spec/02 §6 — `{ config, state }` only;
29
+ * no `global`, `emit`, or `require`). `state` is unused by this plugin.
30
+ * @param ctx.config - The resolved plugin config containing the deployment stage.
31
+ * @returns The `ctx.stage` API: `isDev`, `isProduction`, `current`.
32
+ * @example
33
+ * ```typescript
34
+ * const api = stagePlugin.spec.api({ config: { stage: "development" }, state: {} });
35
+ * api.isDev(); // true
36
+ * ```
37
+ */
38
+ api: ({ config }) => ({
39
+ /**
40
+ * Whether this Worker runs in the development stage.
41
+ *
42
+ * @returns True iff `stage === "development"`.
43
+ * @example
44
+ * ```typescript
45
+ * if (ctx.stage.isDev()) return Response.json({ stack: err.stack });
46
+ * ```
47
+ */
48
+ isDev: () => config.stage === "development",
49
+ /**
50
+ * Whether this Worker runs in the production stage. Note: false in "test".
51
+ *
52
+ * @returns True iff `stage === "production"`.
53
+ * @example
54
+ * ```typescript
55
+ * const cc = ctx.stage.isProduction() ? "public, max-age=31536000" : "no-store";
56
+ * ```
57
+ */
58
+ isProduction: () => config.stage === "production",
59
+ /**
60
+ * The raw deployment stage, as the literal union (not `string`).
61
+ *
62
+ * @returns The resolved stage.
63
+ * @example
64
+ * ```typescript
65
+ * ctx.log.info("startup", { stage: ctx.stage.current() });
66
+ * ```
67
+ */
68
+ current: () => config.stage
69
+ })
70
+ });
71
+ const coreConfig = createCoreConfig("moku-worker", {
72
+ config: {
73
+ stage: "production",
74
+ name: "moku-worker",
75
+ compatibilityDate: ""
76
+ },
77
+ plugins: [
78
+ logPlugin$1,
79
+ envPlugin$1,
80
+ stagePlugin
81
+ ]
82
+ });
83
+ const { createPlugin: createPlugin$1, createCore } = coreConfig;
84
+ //#endregion
85
+ //#region src/plugins/bindings/api.ts
86
+ /**
87
+ * Checks whether a value read from an env object is nullish (null or undefined).
88
+ * Cloudflare supplies either form when a binding is absent, so both must be caught.
89
+ *
90
+ * @param value - The value read from the env object.
91
+ * @returns True when the value is null or undefined.
92
+ * @example
93
+ * ```typescript
94
+ * isNullish(undefined); // true
95
+ * isNullish(0); // false — falsy but bound
96
+ * ```
97
+ */
98
+ const isNullish = (value) => value === void 0 || value === null;
99
+ /**
100
+ * Resolves binding `name` off a request-supplied env object, narrowed to T.
101
+ * Throws a `[moku-worker]`-prefixed error when the binding is nullish.
102
+ * The env argument is read but never retained.
103
+ *
104
+ * @param env - The Cloudflare request env object passed to fetch/scheduled/queue.
105
+ * @param name - The binding name to resolve.
106
+ * @returns The binding value narrowed to T.
107
+ * @throws {Error} With a `[moku-worker]` prefix when the binding is null or undefined.
108
+ * @example
109
+ * ```typescript
110
+ * const kv = requireBinding<KVNamespace>(env, "MY_KV");
111
+ * ```
112
+ */
113
+ const requireBinding = (env, name) => {
114
+ const value = env[name];
115
+ if (isNullish(value)) throw new Error(`[moku-worker] binding "${name}" is not bound.\n Declare it in wrangler config and pass it in via the request env.`);
116
+ return value;
117
+ };
118
+ /**
119
+ * Returns true when `name` resolves to a non-nullish value on the request env.
120
+ * Never throws. Use for optional-binding branching without forcing an error.
121
+ *
122
+ * @param env - The Cloudflare request env object passed to fetch/scheduled/queue.
123
+ * @param name - The binding name to check.
124
+ * @returns Whether the binding is present and non-nullish.
125
+ * @example
126
+ * ```typescript
127
+ * const ok = hasBinding(env, "DB"); // false if DB is not bound
128
+ * ```
129
+ */
130
+ const hasBinding = (env, name) => !isNullish(env[name]);
131
+ /**
132
+ * Builds the app.bindings API surface. The factory receives a context but does
133
+ * not use it — bindings holds no state (F4) and all resolution is argument-local.
134
+ *
135
+ * @param _ctx - Plugin context (unused; bindings is stateless — F4).
136
+ * @returns BindingsApi with `require` and `has` methods.
137
+ * @example
138
+ * ```typescript
139
+ * const api = createBindingsApi(ctx);
140
+ * const kv = api.require<KVNamespace>(env, "MY_KV");
141
+ * ```
142
+ */
143
+ const createBindingsApi = (_ctx) => ({
144
+ require: requireBinding,
145
+ has: hasBinding
146
+ });
147
+ /**
148
+ * Standard-tier stateless resolver — the binding-family dependency root.
149
+ *
150
+ * Exposes `require<T>(env, name)` and `has(env, name)` off a per-request env
151
+ * object. Regular plugin so downstream binding plugins can declare
152
+ * `depends: [bindingsPlugin]` and reach it via `ctx.require(bindingsPlugin)`.
153
+ *
154
+ * @see README.md
155
+ */
156
+ const bindingsPlugin = createPlugin$1("bindings", {
157
+ config: { required: [] },
158
+ api: createBindingsApi
159
+ });
160
+ //#endregion
161
+ //#region src/plugins/bindings/instances.ts
162
+ /**
163
+ * Resolve the default instance key from a keyed-map config: the sole entry, or the one flagged
164
+ * `default: true`. Throws a branded error when there are no instances, or several without (or with
165
+ * more than one) `default: true`.
166
+ *
167
+ * @param instances - The keyed-map config (`Record<key, instance>`).
168
+ * @param kind - The resource kind, for the error message (e.g. "kv", "d1").
169
+ * @returns The default instance's key.
170
+ * @throws {Error} With a `[moku-worker]` prefix when no single default can be resolved.
10
171
  * @example
11
172
  * ```ts
12
- * // wired by createApp so `ctx.env.get("CLOUDFLARE_API_TOKEN")` resolves under Bun/Node
13
- * const provider = workerSafeProcessEnv();
14
- * provider.load().CLOUDFLARE_API_TOKEN;
173
+ * defaultInstanceKey({ main: { name: "db", binding: "DB" } }, "d1"); // "main"
15
174
  * ```
16
175
  */
17
- const workerSafeProcessEnv = () => ({
18
- name: "worker-process-env",
176
+ const defaultInstanceKey = (instances, kind) => {
177
+ const keys = Object.keys(instances);
178
+ if (keys.length === 0) throw new Error(`[moku-worker] No ${kind} instance is configured.`);
179
+ if (keys.length === 1) return keys[0];
180
+ const flagged = keys.filter((key) => instances[key]?.default === true);
181
+ if (flagged.length === 1) return flagged[0];
182
+ throw new Error(`[moku-worker] ${kind} has ${String(keys.length)} instances — mark exactly one with \`default: true\`.`);
183
+ };
184
+ /**
185
+ * Look up a resource instance by key, with a branded error listing the configured keys when absent.
186
+ *
187
+ * @param instances - The keyed-map config (`Record<key, instance>`).
188
+ * @param key - The instance key to resolve (the `use(key)` selector).
189
+ * @param kind - The resource kind, for the error message.
190
+ * @returns The instance at `key`.
191
+ * @throws {Error} With a `[moku-worker]` prefix when `key` is not configured.
192
+ * @example
193
+ * ```ts
194
+ * pickInstance(cfg, "analytics", "d1");
195
+ * ```
196
+ */
197
+ const pickInstance = (instances, key, kind) => {
198
+ const instance = instances[key];
199
+ if (instance === void 0) {
200
+ const configured = Object.keys(instances).join(", ") || "(none)";
201
+ throw new Error(`[moku-worker] No ${kind} instance "${key}". Configured: ${configured}.`);
202
+ }
203
+ return instance;
204
+ };
205
+ //#endregion
206
+ //#region src/plugins/d1/api.ts
207
+ /**
208
+ * Create the d1 api over a keyed map of database instances. The default-database methods and
209
+ * `use(key)` both resolve the `D1Database` off the REQUEST-SUPPLIED env on every call — env is
210
+ * threaded, never stored (SB4), so concurrent requests stay isolated — and the instance key is
211
+ * resolved lazily by binding-getter so an unconfigured-but-present plugin only errors when actually
212
+ * called.
213
+ *
214
+ * The return is intentionally NOT annotated `: Api`. Annotating it would
215
+ * collapse the per-method call-site generic `<T>` on `query`/`first` to
216
+ * `unknown`; instead the implementation forwards `<T>` to `all<T>()` /
217
+ * `first<T>()` and `types.ts#Api` remains the public-surface source of truth.
218
+ *
219
+ * @param {D1Ctx} ctx - Plugin context (keyed-map config + require).
220
+ * @returns {object} The d1 public api (query, first, run, batch, prepare, use, deployManifest).
221
+ * @example
222
+ * ```typescript
223
+ * const api = createD1Api(ctx);
224
+ * const { results } = await api.query<Product>(env, "SELECT * FROM products");
225
+ * await api.use("analytics").run(env, "INSERT INTO events (name) VALUES (?)", "click");
226
+ * ```
227
+ */
228
+ const createD1Api = (ctx) => {
229
+ const bindings = ctx.require(bindingsPlugin);
230
+ const surface = (binding) => {
231
+ const db = (env) => bindings.require(env, binding());
232
+ return {
233
+ /**
234
+ * Run a statement against this database and return all rows.
235
+ *
236
+ * @param env - The per-request Cloudflare env.
237
+ * @param sql - SQL with `?` placeholders.
238
+ * @param params - Bind parameters for the placeholders.
239
+ * @returns All rows in a D1 result.
240
+ * @example
241
+ * ```typescript
242
+ * const { results } = await api.query<Product>(env, "SELECT * FROM products");
243
+ * ```
244
+ */
245
+ query: (env, sql, ...params) => db(env).prepare(sql).bind(...params).all(),
246
+ /**
247
+ * Run a statement against this database and return the first row, or null when none.
248
+ *
249
+ * @param env - The per-request Cloudflare env.
250
+ * @param sql - SQL with `?` placeholders.
251
+ * @param params - Bind parameters for the placeholders.
252
+ * @returns The first row, or null if none.
253
+ * @example
254
+ * ```typescript
255
+ * const product = await api.first<Product>(env, "SELECT * FROM products WHERE id = ?", 1);
256
+ * ```
257
+ */
258
+ first: (env, sql, ...params) => db(env).prepare(sql).bind(...params).first(),
259
+ /**
260
+ * Run a write/DDL statement against this database and return its result meta.
261
+ *
262
+ * @param env - The per-request Cloudflare env.
263
+ * @param sql - SQL with `?` placeholders.
264
+ * @param params - Bind parameters for the placeholders.
265
+ * @returns Result carrying `.meta`.
266
+ * @example
267
+ * ```typescript
268
+ * await api.run(env, "INSERT INTO events (name) VALUES (?)", "click");
269
+ * ```
270
+ */
271
+ run: (env, sql, ...params) => db(env).prepare(sql).bind(...params).run(),
272
+ /**
273
+ * Execute caller-built prepared statements atomically in one round-trip.
274
+ *
275
+ * @param env - The per-request Cloudflare env.
276
+ * @param stmts - Caller-built prepared statements.
277
+ * @returns One result per statement, order preserved.
278
+ * @example
279
+ * ```typescript
280
+ * await api.batch(env, [api.prepare(env).prepare("INSERT INTO t (id) VALUES (1)")]);
281
+ * ```
282
+ */
283
+ batch: (env, stmts) => db(env).batch(stmts),
284
+ /**
285
+ * Resolve the request `D1Database` so callers can build statements for `batch()`.
286
+ *
287
+ * @param env - The per-request Cloudflare env.
288
+ * @returns The request-resolved database handle.
289
+ * @example
290
+ * ```typescript
291
+ * const stmt = api.prepare(env).prepare("SELECT * FROM products");
292
+ * ```
293
+ */
294
+ prepare: (env) => db(env)
295
+ };
296
+ };
297
+ const defaultBinding = () => pickInstance(ctx.config, defaultInstanceKey(ctx.config, "d1"), "d1").binding;
298
+ return {
299
+ ...surface(defaultBinding),
300
+ /**
301
+ * Select a specific D1 database instance by its config key.
302
+ *
303
+ * @param key - The instance key (as configured under `pluginConfigs.d1`).
304
+ * @returns The SQL surface bound to that database.
305
+ * @example
306
+ * ```typescript
307
+ * await api.use("analytics").run(env, "INSERT INTO events (name) VALUES (?)", "click");
308
+ * ```
309
+ */
310
+ use: (key) => surface(() => pickInstance(ctx.config, key, "d1").binding),
311
+ /**
312
+ * Return this plugin's deploy metadata — one descriptor per configured database.
313
+ *
314
+ * @returns One d1 deploy descriptor per instance.
315
+ * @example
316
+ * ```typescript
317
+ * const manifest = api.deployManifest(); // [{ kind: "d1", name: "tracker-db", binding: "DB" }]
318
+ * ```
319
+ */
320
+ deployManifest: () => Object.values(ctx.config).map((instance) => {
321
+ const entry = {
322
+ kind: "d1",
323
+ name: instance.name,
324
+ binding: instance.binding
325
+ };
326
+ if (instance.migrations !== void 0) entry.migrations = instance.migrations;
327
+ return entry;
328
+ })
329
+ };
330
+ };
331
+ /**
332
+ * Standard tier — Cloudflare D1 SQL access (thin typed wrappers, not an ORM).
333
+ *
334
+ * Exposes `query`, `first`, `run`, `batch`, `prepare`, and `deployManifest`.
335
+ * Resolves the D1 binding off the per-request `env` via the bindings plugin.
336
+ * No state, no events, no lifecycle hooks (request-scoped, spec/06 §3).
337
+ *
338
+ * @see README.md
339
+ */
340
+ const d1Plugin = createPlugin$1("d1", {
341
+ depends: [bindingsPlugin],
342
+ config: {},
343
+ api: (ctx) => createD1Api(ctx)
344
+ });
345
+ //#endregion
346
+ //#region src/plugins/durable-objects/api.ts
347
+ /**
348
+ * Builds the `app.durableObjects` API surface — `get` and `deployManifest`.
349
+ *
350
+ * All namespace resolution uses the per-call `env` argument: `env` is threaded, never
351
+ * stored (SB4 / design §1a). The keyed-map config is frozen and read-only. No state
352
+ * is held on the plugin between calls (stateless — `Record<string, never>`).
353
+ *
354
+ * @param ctx - Plugin context with the keyed-map `config`, `require(bindingsPlugin)`, and core APIs.
355
+ * @returns The durableObjects API: `{ get, deployManifest }`.
356
+ * @example
357
+ * ```typescript
358
+ * const api = createDoApi(ctx);
359
+ * const stub = api.get(env, "board", "room-42");
360
+ * const manifest = api.deployManifest(); // [{ kind: "do", binding: "BOARD", className: "BoardChannel" }]
361
+ * ```
362
+ */
363
+ const createDoApi = (ctx) => ({
19
364
  /**
20
- * Read a shallow copy of `process.env`, or `{}` when there is no `process` global (workerd
21
- * without nodejs_compat). Never throws at cold start.
365
+ * Resolves a `DurableObjectStub` off the per-request env.
22
366
  *
23
- * @returns The current environment as a flat record (empty when `process` is absent).
367
+ * Selects the configured instance by `logicalName` (the config key) via `pickInstance`, resolves
368
+ * its `binding` off `env`, derives a deterministic id via `namespace.idFromName(idName)`, and
369
+ * returns the addressed stub. Synchronous — returns a stub, not a Promise. Throws (branded) when
370
+ * `logicalName` is not configured, or (via the bindings resolver) when the binding is not present
371
+ * on `env`.
372
+ *
373
+ * @param env - Per-request Cloudflare bindings object (Worker fetch/queue/scheduled env).
374
+ * @param logicalName - Logical DO key (selects the configured instance, e.g. `"board"`).
375
+ * @param idName - Stable id name passed to `idFromName` (e.g. `"room-42"`).
376
+ * @returns The addressed `DurableObjectStub`.
377
+ * @throws {Error} With `[moku-worker]` prefix when `logicalName` is not configured, or when the
378
+ * binding is not bound on `env`.
24
379
  * @example
25
- * ```ts
26
- * workerSafeProcessEnv().load();
380
+ * ```typescript
381
+ * const stub = app.durableObjects.get(env, "board", "room-42");
382
+ * const res = await stub.fetch("https://do/increment");
27
383
  * ```
28
384
  */
29
- load() {
30
- return typeof process === "undefined" ? {} : { ...process.env };
385
+ get: (env, logicalName, idName) => {
386
+ const binding = pickInstance(ctx.config, logicalName, "durableObjects").binding;
387
+ const ns = ctx.require(bindingsPlugin).require(env, binding);
388
+ return ns.get(ns.idFromName(idName));
389
+ },
390
+ /**
391
+ * Returns this plugin's deploy metadata — one entry per configured instance, read by the `deploy`
392
+ * plugin via `ctx.require(durableObjectsPlugin)`. Never reads sibling `pluginConfigs` (F6;
393
+ * spec/08 §5, §7). Pure synchronous read of `ctx.config`.
394
+ *
395
+ * @returns One `{ kind: "do", binding, className }` per configured instance.
396
+ * @example
397
+ * ```typescript
398
+ * const manifest = app.durableObjects.deployManifest();
399
+ * // → [{ kind: "do", binding: "BOARD", className: "BoardChannel" }]
400
+ * ```
401
+ */
402
+ deployManifest: () => Object.values(ctx.config).map((instance) => ({
403
+ kind: "do",
404
+ binding: instance.binding,
405
+ className: instance.className
406
+ }))
407
+ });
408
+ //#endregion
409
+ //#region src/plugins/durable-objects/helpers.ts
410
+ /**
411
+ * Returns a base class the consumer extends and exports from `worker.ts`.
412
+ *
413
+ * PURE (spec/03 §1): takes no `ctx`, has no side effects, and may be called before
414
+ * `createApp`. The static `doName` property captures `name` for diagnostics and
415
+ * binding correlation. The constructor stores `(state, env)` as `this.ctx` / `this.env`,
416
+ * satisfying the Cloudflare Durable Object constructor contract. The plugin NEVER
417
+ * generates the final exported class — the consumer owns that class.
418
+ *
419
+ * @param name - Logical DO name; captured as `static doName` for diagnostics.
420
+ * @returns A base class (constructor) the consumer extends.
421
+ * @example
422
+ * ```typescript
423
+ * // src/counter.ts
424
+ * import { defineDurableObject } from "@moku-labs/worker";
425
+ *
426
+ * export class Counter extends defineDurableObject("Counter") {
427
+ * async fetch(): Promise<Response> {
428
+ * const n = ((await this.ctx.storage.get<number>("n")) ?? 0) + 1;
429
+ * await this.ctx.storage.put("n", n);
430
+ * return Response.json({ n });
431
+ * }
432
+ * }
433
+ * ```
434
+ */
435
+ const defineDurableObject = (name) => {
436
+ /**
437
+ * Base implementation of the Cloudflare Durable Object constructor contract.
438
+ * Stores `(ctx, env)` as readonly properties for consumer subclasses to use.
439
+ */
440
+ class DurableObjectBaseImpl {
441
+ /**
442
+ * Cloudflare per-object storage/alarm context (DurableObjectState).
443
+ * Use `this.ctx.storage` to read/write durable storage and `this.ctx.id` to inspect the DO id.
444
+ */
445
+ ctx;
446
+ /**
447
+ * Per-object Cloudflare bindings (per-request WorkerEnv).
448
+ * Mirrors the env passed at construction time; never cached across requests.
449
+ */
450
+ env;
451
+ /**
452
+ * Logical DO name captured from `defineDurableObject(name)`.
453
+ * Used for diagnostics and binding correlation.
454
+ */
455
+ static doName = name;
456
+ /**
457
+ * Constructs the base Durable Object with Cloudflare's required signature.
458
+ *
459
+ * @param ctx - Cloudflare DurableObjectState (storage, id, blockConcurrencyWhile, …).
460
+ * @param env - Per-request Cloudflare bindings object (WorkerEnv).
461
+ * @example
462
+ * ```typescript
463
+ * class Counter extends Base {
464
+ * constructor(ctx: DurableObjectState, env: WorkerEnv) { super(ctx, env); }
465
+ * }
466
+ * ```
467
+ */
468
+ constructor(ctx, env) {
469
+ this.ctx = ctx;
470
+ this.env = env;
471
+ }
31
472
  }
473
+ return DurableObjectBaseImpl;
474
+ };
475
+ /**
476
+ * Cloudflare Durable Objects plugin — Standard tier.
477
+ *
478
+ * Exposes `get(env, logicalName, idName)` (synchronous stub accessor, threaded env) and
479
+ * `deployManifest()` (build-time metadata, one entry per configured instance). Depends on
480
+ * `bindingsPlugin` for namespace resolution. The `defineDurableObject` helper is mounted under
481
+ * `helpers` and re-exported at the top level for consumer use.
482
+ *
483
+ * @example
484
+ * ```typescript
485
+ * // Consumer endpoint handler:
486
+ * const stub = app.durableObjects.get(env, "board", params.room!);
487
+ * const res = await stub.fetch("https://do/increment");
488
+ * // Consumer DO class (the EXPORTED className referenced by the "board" instance):
489
+ * export class BoardChannel extends defineDurableObject("BoardChannel") {
490
+ * async fetch(): Promise<Response> { return new Response("ok"); }
491
+ * }
492
+ * ```
493
+ * @see README.md
494
+ */
495
+ const durableObjectsPlugin = createPlugin$1("durableObjects", {
496
+ depends: [bindingsPlugin],
497
+ config: {},
498
+ api: createDoApi,
499
+ helpers: { defineDurableObject }
500
+ });
501
+ //#endregion
502
+ //#region src/plugins/kv/api.ts
503
+ /**
504
+ * Builds the app.kv.* api over a keyed map of namespace instances. The default-namespace methods and
505
+ * `use(key)` both resolve the namespace off the REQUEST-SUPPLIED env on every call — env is threaded,
506
+ * never stored (design §1a / SB4) — and the instance key is resolved lazily so an unconfigured-but-
507
+ * present plugin only errors when actually called.
508
+ *
509
+ * @param ctx - The kv plugin context (keyed-map config + merged events).
510
+ * @returns The app.kv api: get / put / delete / list / use / deployManifest.
511
+ * @example
512
+ * ```typescript
513
+ * const api = createKvApi(ctx);
514
+ * const value = await api.get(env, "key");
515
+ * await api.use("sessions").put(env, "s:1", "data");
516
+ * ```
517
+ */
518
+ const createKvApi = (ctx) => {
519
+ const bindings = ctx.require(bindingsPlugin);
520
+ const surface = (binding) => {
521
+ const ns = (env) => bindings.require(env, binding());
522
+ return {
523
+ /**
524
+ * Read a value by key from this namespace. Returns null when absent.
525
+ *
526
+ * @param env - The per-request Cloudflare env.
527
+ * @param key - The key to read.
528
+ * @returns The stored value, or null when absent.
529
+ * @example
530
+ * ```typescript
531
+ * const value = await api.get(env, "feature-flags");
532
+ * ```
533
+ */
534
+ get: async (env, key) => ns(env).get(key),
535
+ /**
536
+ * Write a string value under a key, optionally with KV put options.
537
+ *
538
+ * @param env - The per-request Cloudflare env.
539
+ * @param key - The key to write.
540
+ * @param value - The string value to store.
541
+ * @param opts - Optional expiration / metadata.
542
+ * @returns Resolves once the write is acknowledged.
543
+ * @example
544
+ * ```typescript
545
+ * await api.put(env, "session:1", "data", { expirationTtl: 3600 });
546
+ * ```
547
+ */
548
+ put: async (env, key, value, opts) => ns(env).put(key, value, opts),
549
+ /**
550
+ * Remove a key from this namespace (no-op if absent).
551
+ *
552
+ * @param env - The per-request Cloudflare env.
553
+ * @param key - The key to delete.
554
+ * @returns Resolves once the delete is acknowledged.
555
+ * @example
556
+ * ```typescript
557
+ * await api.delete(env, "session:expired");
558
+ * ```
559
+ */
560
+ delete: async (env, key) => ns(env).delete(key),
561
+ /**
562
+ * List keys in this namespace, optionally filtered/paginated.
563
+ *
564
+ * @param env - The per-request Cloudflare env.
565
+ * @param opts - Optional prefix / cursor / limit.
566
+ * @returns The list result.
567
+ * @example
568
+ * ```typescript
569
+ * const { keys } = await api.list(env, { prefix: "session:" });
570
+ * ```
571
+ */
572
+ list: async (env, opts) => ns(env).list(opts)
573
+ };
574
+ };
575
+ const defaultBinding = () => pickInstance(ctx.config, defaultInstanceKey(ctx.config, "kv"), "kv").binding;
576
+ return {
577
+ ...surface(defaultBinding),
578
+ /**
579
+ * Select a specific KV namespace instance by its config key.
580
+ *
581
+ * @param key - The instance key (as configured under `pluginConfigs.kv`).
582
+ * @returns The key/value surface bound to that namespace.
583
+ * @example
584
+ * ```typescript
585
+ * await api.use("sessions").get(env, "s:1");
586
+ * ```
587
+ */
588
+ use: (key) => surface(() => pickInstance(ctx.config, key, "kv").binding),
589
+ /**
590
+ * Return this plugin's deploy metadata — one descriptor per configured namespace.
591
+ *
592
+ * @returns One kv deploy descriptor per instance.
593
+ * @example
594
+ * ```typescript
595
+ * const manifest = api.deployManifest(); // [{ kind: "kv", name: "tracker-cache", binding: "CACHE" }]
596
+ * ```
597
+ */
598
+ deployManifest: () => Object.values(ctx.config).map((instance) => ({
599
+ kind: "kv",
600
+ name: instance.name,
601
+ binding: instance.binding
602
+ }))
603
+ };
604
+ };
605
+ /**
606
+ * Micro tier — thin env-first wrapper over a Cloudflare KV namespace.
607
+ *
608
+ * Resolves the KV namespace per request via `ctx.require(bindingsPlugin)`;
609
+ * never stores env in state (design §1a / SB4). No lifecycle hooks —
610
+ * request-scoped; nothing to open or close.
611
+ *
612
+ * @see README.md
613
+ */
614
+ const kvPlugin = createPlugin$1("kv", {
615
+ depends: [bindingsPlugin],
616
+ config: {},
617
+ api: createKvApi
618
+ });
619
+ //#endregion
620
+ //#region src/plugins/queues/api.ts
621
+ /**
622
+ * Resolve the instance a consumed batch belongs to. With a single instance, that instance always
623
+ * matches. With several, match the instance whose `name` equals `batch.queue` OR whose stage-suffixed
624
+ * form (`${name}-`) prefixes it (tolerant of the deploy stage suffix, e.g. `tracker-activity-dev`);
625
+ * fall back to the default instance when nothing matches.
626
+ *
627
+ * @param config - The keyed-map queues config.
628
+ * @param queueName - The CF queue name from `batch.queue`.
629
+ * @returns The matched `QueueInstance` (its `onMessage` is what `consume` awaits).
630
+ * @example
631
+ * ```ts
632
+ * routeInstance(cfg, "tracker-activity-dev"); // → the `activity` instance
633
+ * ```
634
+ */
635
+ const routeInstance = (config, queueName) => {
636
+ const keys = Object.keys(config);
637
+ if (keys.length === 1) return pickInstance(config, keys[0], "queues");
638
+ return Object.values(config).find((instance) => instance.name === queueName || queueName.startsWith(`${instance.name}-`)) ?? pickInstance(config, defaultInstanceKey(config, "queues"), "queues");
639
+ };
640
+ /**
641
+ * Builds app.queues.* over a keyed map of Queue instances — read by worker.ts queue() delegation
642
+ * (design §1d; spec/02 §7). The default-instance producer methods and `use(key)` both resolve the
643
+ * Queue off the REQUEST-SUPPLIED env on every call (env is threaded, never stored — SB4); the
644
+ * instance key is resolved lazily. Emits `queue:message` for observability after each consumed
645
+ * message (F8).
646
+ *
647
+ * @param ctx - Plugin context (keyed-map config + require + emit).
648
+ * @returns The queues API surface: send, sendBatch, use, consume, deployManifest.
649
+ * @example
650
+ * ```ts
651
+ * const api = createQueuesApi(ctx);
652
+ * await api.send(env, { orderId: "1" }); // default instance
653
+ * await api.use("activity").send(env, { id: 2 }); // a named instance
654
+ * // Worker entry (design §1d): queue: (b, e, c) => app.queues.consume(b, e, c)
655
+ * ```
656
+ */
657
+ const createQueuesApi = (ctx) => {
658
+ const bindings = ctx.require(bindingsPlugin);
659
+ const surface = (binding) => {
660
+ const queue = (env) => bindings.require(env, binding());
661
+ return {
662
+ /**
663
+ * Enqueue a single message onto this instance's queue.
664
+ *
665
+ * @param env - The per-request Cloudflare env.
666
+ * @param body - The message body to enqueue.
667
+ * @returns Resolves once the message is enqueued.
668
+ * @example
669
+ * ```typescript
670
+ * await api.send(env, { userId: "u1" });
671
+ * ```
672
+ */
673
+ send: async (env, body) => {
674
+ await queue(env).send(body);
675
+ },
676
+ /**
677
+ * Enqueue many messages onto this instance's queue; each element becomes one message.
678
+ *
679
+ * @param env - The per-request Cloudflare env.
680
+ * @param bodies - Array of message bodies; each becomes one message.
681
+ * @returns Resolves once all messages are enqueued.
682
+ * @example
683
+ * ```typescript
684
+ * await api.sendBatch(env, [{ id: 1 }, { id: 2 }]);
685
+ * ```
686
+ */
687
+ sendBatch: async (env, bodies) => {
688
+ await queue(env).sendBatch(bodies.map((body) => ({ body })));
689
+ }
690
+ };
691
+ };
692
+ const defaultBinding = () => pickInstance(ctx.config, defaultInstanceKey(ctx.config, "queues"), "queues").binding;
693
+ return {
694
+ ...surface(defaultBinding),
695
+ /**
696
+ * Select a specific Queue instance by its config key.
697
+ *
698
+ * @param key - The instance key (as configured under `pluginConfigs.queues`).
699
+ * @returns The producer surface bound to that instance.
700
+ * @example
701
+ * ```typescript
702
+ * await api.use("activity").send(env, { id: 2 });
703
+ * ```
704
+ */
705
+ use: (key) => surface(() => pickInstance(ctx.config, key, "queues").binding),
706
+ /**
707
+ * Consumer dispatch — the Worker's `queue()` export delegates here. Routes the batch to the
708
+ * matching instance's `onMessage` and emits `queue:message` per message.
709
+ *
710
+ * @param batch - The incoming message batch.
711
+ * @param env - The per-request Cloudflare env.
712
+ * @param _ctx - The execution context (waitUntil / passThroughOnException); unused.
713
+ * @returns Resolves after all messages settle.
714
+ * @example
715
+ * ```typescript
716
+ * // Worker entry (design §1d): queue: (b, e, c) => app.queues.consume(b, e, c)
717
+ * ```
718
+ */
719
+ consume: async (batch, env, _ctx) => {
720
+ const instance = routeInstance(ctx.config, batch.queue);
721
+ for (const m of batch.messages) {
722
+ if (instance.onMessage) await instance.onMessage(m, env);
723
+ ctx.emit("queue:message", {
724
+ queue: batch.queue,
725
+ messageId: m.id
726
+ });
727
+ }
728
+ },
729
+ /**
730
+ * Return this plugin's deploy metadata — one descriptor per configured instance.
731
+ *
732
+ * @returns One queue deploy descriptor per instance.
733
+ * @example
734
+ * ```typescript
735
+ * const manifest = api.deployManifest(); // [{ kind: "queue", name: "tracker-activity", binding: "ACTIVITY" }]
736
+ * ```
737
+ */
738
+ deployManifest: () => Object.values(ctx.config).map((instance) => ({
739
+ kind: "queue",
740
+ name: instance.name,
741
+ binding: instance.binding,
742
+ ...instance.onMessage ? { consumer: true } : {},
743
+ ...instance.maxBatchTimeout === void 0 ? {} : { maxBatchTimeout: instance.maxBatchTimeout }
744
+ }))
745
+ };
746
+ };
747
+ /**
748
+ * Standard tier — Cloudflare Queues producer + per-instance consumer dispatch over a keyed map of
749
+ * instances.
750
+ *
751
+ * `events` is declared first and via `register.map<QueueEvents>` so the plugin's own events infer
752
+ * into the factory context; the api wiring is therefore arrow-wrapped (contextually typed).
753
+ *
754
+ * Emits the plugin-local `queue:message` event after each consumed message.
755
+ *
756
+ * @see README.md
757
+ */
758
+ const queuesPlugin = createPlugin$1("queues", {
759
+ events: (register) => register.map({ "queue:message": "A queue message was processed" }),
760
+ depends: [bindingsPlugin],
761
+ config: {},
762
+ api: (ctx) => createQueuesApi(ctx)
32
763
  });
33
764
  //#endregion
34
765
  //#region src/plugins/server/api.ts
@@ -513,6 +1244,3618 @@ const serverPlugin = createPlugin$1("server", {
513
1244
  helpers: { endpoint }
514
1245
  });
515
1246
  //#endregion
1247
+ //#region src/plugins/storage/providers/r2.ts
1248
+ /**
1249
+ * Build a StorageProvider backed by the real R2Bucket resolved off the
1250
+ * per-request env via the bindings plugin. The bucket is resolved fresh on
1251
+ * EVERY method call — never cached, so concurrent requests stay isolated
1252
+ * (worker-api-design SB4; spec/08 §6).
1253
+ *
1254
+ * Each method is `async` so that synchronous throws from `bindings.require`
1255
+ * (e.g. missing binding) are automatically wrapped in rejected Promises —
1256
+ * callers can always use `await` / `.catch` instead of `try/catch`.
1257
+ *
1258
+ * @param bindings - The bindings plugin API (provides `require<T>`).
1259
+ * @param env - The per-request Cloudflare bindings object.
1260
+ * @param bucket - The R2 bucket binding name (e.g. "ASSETS").
1261
+ * @returns {StorageProvider} A provider that delegates to the resolved R2Bucket.
1262
+ * @example
1263
+ * ```typescript
1264
+ * const provider = resolveR2Provider(ctx.require(bindingsPlugin), env, ctx.config.bucket);
1265
+ * const body = await provider.get("my-object");
1266
+ * ```
1267
+ */
1268
+ const resolveR2Provider = (bindings, env, bucket) => {
1269
+ /**
1270
+ * Resolve the R2Bucket for this request's env. Throws on missing binding.
1271
+ *
1272
+ * @returns {R2Bucket} The resolved R2Bucket binding.
1273
+ * @example
1274
+ * ```typescript
1275
+ * const bucket = b();
1276
+ * ```
1277
+ */
1278
+ const b = () => bindings.require(env, bucket);
1279
+ return {
1280
+ /**
1281
+ * Read an object from the bucket.
1282
+ *
1283
+ * @param key - The object key.
1284
+ * @returns {Promise<R2ObjectBody | null>} The R2ObjectBody, or null if the key is absent.
1285
+ * @example
1286
+ * ```typescript
1287
+ * const body = await provider.get("assets/logo.png");
1288
+ * ```
1289
+ */
1290
+ async get(key) {
1291
+ return b().get(key);
1292
+ },
1293
+ /**
1294
+ * Write an object to the bucket.
1295
+ *
1296
+ * @param key - The object key.
1297
+ * @param value - The object contents (any R2-accepted type).
1298
+ * @returns {Promise<R2Object>} The R2Object metadata for the written object.
1299
+ * @example
1300
+ * ```typescript
1301
+ * const obj = await provider.put("assets/logo.png", buffer);
1302
+ * ```
1303
+ */
1304
+ async put(key, value) {
1305
+ return b().put(key, value);
1306
+ },
1307
+ /**
1308
+ * Remove one or more objects from the bucket. No-op when a key is absent.
1309
+ *
1310
+ * @param key - A single key or array of keys to remove.
1311
+ * @returns {Promise<void>} Resolves once removed.
1312
+ * @example
1313
+ * ```typescript
1314
+ * await provider.delete("assets/old.png");
1315
+ * ```
1316
+ */
1317
+ async delete(key) {
1318
+ return b().delete(key);
1319
+ },
1320
+ /**
1321
+ * List objects, optionally filtered by R2ListOptions.
1322
+ *
1323
+ * @param opts - Optional list options (prefix, limit, cursor, delimiter).
1324
+ * @returns {Promise<R2Objects>} The R2Objects list result.
1325
+ * @example
1326
+ * ```typescript
1327
+ * const { objects } = await provider.list({ prefix: "images/" });
1328
+ * ```
1329
+ */
1330
+ async list(opts) {
1331
+ return b().list(opts);
1332
+ }
1333
+ };
1334
+ };
1335
+ //#endregion
1336
+ //#region src/plugins/storage/api.ts
1337
+ /**
1338
+ * Build the app.storage.* api over a keyed map of R2 bucket instances. The default-bucket methods and
1339
+ * `use(key)` both resolve the bucket off the REQUEST-SUPPLIED env on every call — env is threaded,
1340
+ * never stored (worker-api-design SB4; spec/08 §6,§7) — and the instance key is resolved lazily so an
1341
+ * unconfigured-but-present plugin only errors when actually called.
1342
+ *
1343
+ * The `deployManifest()` method is build-time only: it reads from `ctx.config`
1344
+ * and never touches `env` or R2.
1345
+ *
1346
+ * @param ctx - Plugin context (keyed-map config + require for bindings resolution).
1347
+ * @returns {StorageApi} The app.storage api: get / put / delete / list / use / deployManifest.
1348
+ * @example
1349
+ * ```typescript
1350
+ * const api = createStorageApi(ctx);
1351
+ * const body = await api.get(env, "my-object");
1352
+ * await api.use("uploads").put(env, "avatar.png", buffer);
1353
+ * ```
1354
+ */
1355
+ const createStorageApi = (ctx) => {
1356
+ const bindings = ctx.require(bindingsPlugin);
1357
+ const surface = (binding) => {
1358
+ const provider = (env) => resolveR2Provider(bindings, env, binding());
1359
+ return {
1360
+ /**
1361
+ * Read an object from this bucket; resolves null when the key is absent.
1362
+ *
1363
+ * @param env - The per-request Cloudflare env.
1364
+ * @param key - The object key to read.
1365
+ * @returns The object body, or null.
1366
+ * @example
1367
+ * ```typescript
1368
+ * const body = await api.get(env, "assets/logo.png");
1369
+ * ```
1370
+ */
1371
+ get: (env, key) => provider(env).get(key),
1372
+ /**
1373
+ * Write an object to this bucket.
1374
+ *
1375
+ * @param env - The per-request Cloudflare env.
1376
+ * @param key - The object key to write.
1377
+ * @param value - The object contents.
1378
+ * @returns The written object metadata.
1379
+ * @example
1380
+ * ```typescript
1381
+ * await api.put(env, "avatar.png", buffer);
1382
+ * ```
1383
+ */
1384
+ put: (env, key, value) => provider(env).put(key, value),
1385
+ /**
1386
+ * Remove an object (or keys) from this bucket. No-op when absent.
1387
+ *
1388
+ * @param env - The per-request Cloudflare env.
1389
+ * @param key - The object key or keys to delete.
1390
+ * @returns Resolves once removed.
1391
+ * @example
1392
+ * ```typescript
1393
+ * await api.delete(env, "assets/old-logo.png");
1394
+ * ```
1395
+ */
1396
+ delete: (env, key) => provider(env).delete(key),
1397
+ /**
1398
+ * List objects in this bucket, optionally filtered by R2ListOptions.
1399
+ *
1400
+ * @param env - The per-request Cloudflare env.
1401
+ * @param opts - Optional prefix / limit / cursor / delimiter.
1402
+ * @returns The list result.
1403
+ * @example
1404
+ * ```typescript
1405
+ * const { objects } = await api.list(env, { prefix: "assets/" });
1406
+ * ```
1407
+ */
1408
+ list: (env, opts) => provider(env).list(opts)
1409
+ };
1410
+ };
1411
+ const defaultBinding = () => pickInstance(ctx.config, defaultInstanceKey(ctx.config, "r2"), "r2").binding;
1412
+ return {
1413
+ ...surface(defaultBinding),
1414
+ /**
1415
+ * Select a specific R2 bucket instance by its config key.
1416
+ *
1417
+ * @param key - The instance key (as configured under `pluginConfigs.storage`).
1418
+ * @returns The object surface bound to that bucket.
1419
+ * @example
1420
+ * ```typescript
1421
+ * await api.use("uploads").put(env, "avatar.png", buffer);
1422
+ * ```
1423
+ */
1424
+ use: (key) => surface(() => pickInstance(ctx.config, key, "r2").binding),
1425
+ /**
1426
+ * Return this plugin's deploy metadata — one descriptor per configured bucket.
1427
+ *
1428
+ * @returns One r2 deploy descriptor per instance.
1429
+ * @example
1430
+ * ```typescript
1431
+ * const manifest = api.deployManifest(); // [{ kind: "r2", name: "tracker-files", binding: "FILES" }]
1432
+ * ```
1433
+ */
1434
+ deployManifest: () => Object.values(ctx.config).map((instance) => ({
1435
+ kind: "r2",
1436
+ name: instance.name,
1437
+ binding: instance.binding,
1438
+ ...instance.upload === void 0 ? {} : { upload: instance.upload }
1439
+ }))
1440
+ };
1441
+ };
1442
+ /**
1443
+ * Complex tier — Cloudflare R2 object storage behind a provider adapter seam.
1444
+ *
1445
+ * Exposes `get`, `put`, `delete`, `list` (all env-first) and `deployManifest()`
1446
+ * (build-time). Depends on `bindingsPlugin` to resolve the `R2Bucket` binding
1447
+ * per request. No state, no events, no lifecycle hooks.
1448
+ *
1449
+ * @see README.md
1450
+ */
1451
+ const storagePlugin = createPlugin$1("storage", {
1452
+ depends: [bindingsPlugin],
1453
+ config: {},
1454
+ api: createStorageApi
1455
+ });
1456
+ //#endregion
1457
+ //#region src/plugins/stage/env-provider.ts
1458
+ /**
1459
+ * Build the default env provider: a shallow copy of `process.env` when a `process` global exists,
1460
+ * else an empty record. Safe to evaluate at Worker cold start — it never throws on a missing
1461
+ * `process` (typeof of an undeclared identifier is the string "undefined", not a ReferenceError).
1462
+ *
1463
+ * @returns An {@link EnvProvider} named `worker-process-env`.
1464
+ * @example
1465
+ * ```ts
1466
+ * // wired by createApp so `ctx.env.get("CLOUDFLARE_API_TOKEN")` resolves under Bun/Node
1467
+ * const provider = workerSafeProcessEnv();
1468
+ * provider.load().CLOUDFLARE_API_TOKEN;
1469
+ * ```
1470
+ */
1471
+ const workerSafeProcessEnv = () => ({
1472
+ name: "worker-process-env",
1473
+ /**
1474
+ * Read a shallow copy of `process.env`, or `{}` when there is no `process` global (workerd
1475
+ * without nodejs_compat). Never throws at cold start.
1476
+ *
1477
+ * @returns The current environment as a flat record (empty when `process` is absent).
1478
+ * @example
1479
+ * ```ts
1480
+ * workerSafeProcessEnv().load();
1481
+ * ```
1482
+ */
1483
+ load() {
1484
+ return typeof process === "undefined" ? {} : { ...process.env };
1485
+ }
1486
+ });
1487
+ //#endregion
1488
+ //#region src/plugins/deploy/auth/env-file.ts
1489
+ /**
1490
+ * @file deploy plugin — `.env.local` scaffolder (node:fs).
1491
+ *
1492
+ * Writes a ready-to-fill `.env.local` so the guided deploy can hand the user a real file to paste
1493
+ * their Cloudflare token into — NEVER clobbering an existing one (it may already hold real secrets).
1494
+ * Node-only; never imported by the runtime Worker bundle.
1495
+ */
1496
+ /**
1497
+ * Create `<dir>/.env.local` with the given contents, unless it already exists. Existing files are
1498
+ * left untouched (they may hold real secrets) — the caller tells the user to fill that one in.
1499
+ *
1500
+ * @param dir - Directory to create the file in (usually `process.cwd()`).
1501
+ * @param content - The file contents to write when absent (e.g. `envLocalScaffold(manifest)`).
1502
+ * @returns Whether the file was created (false when it already existed) and its path.
1503
+ * @example
1504
+ * ```ts
1505
+ * const { created, path } = await ensureEnvLocal(process.cwd(), envLocalScaffold(manifest));
1506
+ * ```
1507
+ */
1508
+ const ensureEnvLocal = async (dir, content) => {
1509
+ const filePath = path.join(dir, ".env.local");
1510
+ try {
1511
+ await access(filePath);
1512
+ return {
1513
+ created: false,
1514
+ path: filePath
1515
+ };
1516
+ } catch {
1517
+ await writeFile(filePath, content, "utf8");
1518
+ return {
1519
+ created: true,
1520
+ path: filePath
1521
+ };
1522
+ }
1523
+ };
1524
+ //#endregion
1525
+ //#region src/plugins/deploy/auth/permissions.ts
1526
+ /** Permission groups every deploy needs, regardless of resources. */
1527
+ const ALWAYS = [{
1528
+ group: "Account · Workers Scripts",
1529
+ scope: "Edit",
1530
+ reason: "deploy",
1531
+ inBaseTemplate: true
1532
+ }, {
1533
+ group: "Account · Account Settings",
1534
+ scope: "Read",
1535
+ reason: "account",
1536
+ inBaseTemplate: true
1537
+ }];
1538
+ /**
1539
+ * Per-resource-kind permission group. `do` needs nothing extra (Durable Objects ship with the
1540
+ * Worker script, covered by Workers Scripts · Edit). `d1`/`queue` are NOT in the stock template.
1541
+ */
1542
+ const BY_KIND = {
1543
+ kv: {
1544
+ group: "Account · Workers KV Storage",
1545
+ scope: "Edit",
1546
+ reason: "kv",
1547
+ inBaseTemplate: true
1548
+ },
1549
+ r2: {
1550
+ group: "Account · Workers R2 Storage",
1551
+ scope: "Edit",
1552
+ reason: "r2",
1553
+ inBaseTemplate: true
1554
+ },
1555
+ d1: {
1556
+ group: "Account · D1",
1557
+ scope: "Edit",
1558
+ reason: "d1",
1559
+ inBaseTemplate: false
1560
+ },
1561
+ queue: {
1562
+ group: "Account · Queues",
1563
+ scope: "Edit",
1564
+ reason: "queue",
1565
+ inBaseTemplate: false
1566
+ },
1567
+ do: void 0
1568
+ };
1569
+ /**
1570
+ * Derive the Cloudflare API token requirement from an app manifest: the full permission set plus
1571
+ * the subset that must be ADDED to the stock "Edit Cloudflare Workers" template.
1572
+ *
1573
+ * @param manifest - The assembled deploy manifest.
1574
+ * @returns The token requirement (base template, full required set, and groups to add).
1575
+ * @example
1576
+ * ```ts
1577
+ * const { toAdd } = requiredToken({ name: "w", compatibilityDate: "…", resources: [{ kind: "d1", binding: "DB" }] });
1578
+ * // toAdd → [{ group: "Account · D1", scope: "Edit", … }]
1579
+ * ```
1580
+ */
1581
+ const requiredToken = (manifest) => {
1582
+ const required = [...ALWAYS];
1583
+ const seen = new Set(required.map((permission) => permission.group));
1584
+ for (const resource of manifest.resources) {
1585
+ const permission = BY_KIND[resource.kind];
1586
+ if (permission !== void 0 && !seen.has(permission.group)) {
1587
+ required.push(permission);
1588
+ seen.add(permission.group);
1589
+ }
1590
+ }
1591
+ return {
1592
+ base: "Edit Cloudflare Workers",
1593
+ required,
1594
+ toAdd: required.filter((permission) => !permission.inBaseTemplate)
1595
+ };
1596
+ };
1597
+ /** Permission every CI/automation redeploy needs: ship the Worker script. */
1598
+ const CI_ALWAYS = [{
1599
+ group: "Account · Workers Scripts",
1600
+ scope: "Edit",
1601
+ reason: "deploy",
1602
+ inBaseTemplate: true
1603
+ }];
1604
+ /**
1605
+ * Per-resource-kind permission for the CI/automation token. After a first LOCAL deploy has
1606
+ * provisioned everything, CI only needs to LIST existing infra (the idempotent preflight) and
1607
+ * ship — so data resources drop to `Read`; R2 stays `Edit` because asset upload writes objects.
1608
+ */
1609
+ const CI_BY_KIND = {
1610
+ kv: {
1611
+ group: "Account · Workers KV Storage",
1612
+ scope: "Read",
1613
+ reason: "kv (preflight)",
1614
+ inBaseTemplate: true
1615
+ },
1616
+ r2: {
1617
+ group: "Account · Workers R2 Storage",
1618
+ scope: "Edit",
1619
+ reason: "r2 (asset upload)",
1620
+ inBaseTemplate: true
1621
+ },
1622
+ d1: {
1623
+ group: "Account · D1",
1624
+ scope: "Read",
1625
+ reason: "d1 (preflight)",
1626
+ inBaseTemplate: false
1627
+ },
1628
+ queue: {
1629
+ group: "Account · Queues",
1630
+ scope: "Read",
1631
+ reason: "queue (preflight)",
1632
+ inBaseTemplate: false
1633
+ },
1634
+ do: void 0
1635
+ };
1636
+ /**
1637
+ * Derive the REDUCED Cloudflare API token for CI/automation redeploys, from the same manifest.
1638
+ * Assumes a prior LOCAL deploy already provisioned the infra, so CI never creates: data resources
1639
+ * need only `Read` (the idempotent preflight lists them), R2 keeps `Edit` for asset upload, and no
1640
+ * `Account Settings · Read` is needed because CI pins `CLOUDFLARE_ACCOUNT_ID`. Pure: no network.
1641
+ *
1642
+ * @param manifest - The assembled deploy manifest.
1643
+ * @returns The minimum permission groups for a CI redeploy token (deduped, manifest-scoped).
1644
+ * @example
1645
+ * ```ts
1646
+ * const groups = ciToken({ name: "w", compatibilityDate: "…", resources: [{ kind: "d1", binding: "DB" }] });
1647
+ * // → [Workers Scripts·Edit, D1·Read]
1648
+ * ```
1649
+ */
1650
+ const ciToken = (manifest) => {
1651
+ const groups = [...CI_ALWAYS];
1652
+ const seen = new Set(groups.map((permission) => permission.group));
1653
+ for (const resource of manifest.resources) {
1654
+ const permission = CI_BY_KIND[resource.kind];
1655
+ if (permission !== void 0 && !seen.has(permission.group)) {
1656
+ groups.push(permission);
1657
+ seen.add(permission.group);
1658
+ }
1659
+ }
1660
+ return groups;
1661
+ };
1662
+ //#endregion
1663
+ //#region src/plugins/deploy/auth/render.ts
1664
+ /** Cloudflare's dashboard path for creating API tokens. */
1665
+ const TOKENS_URL$1 = "https://dash.cloudflare.com/profile/api-tokens";
1666
+ /**
1667
+ * Render one permission as a framed row. With the template flag on (the LOCAL panel) a green `✓`
1668
+ * marks a permission the stock template already includes and a pink `+ ← add to template` marks one
1669
+ * the user must add; with it off (the CI panel) every row is a neutral bullet. Scope bold, reason dim.
1670
+ *
1671
+ * @param ui - The branded console (for its palette).
1672
+ * @param permission - The permission group to render.
1673
+ * @param showTemplateFlag - Whether to mark template-vs-add (LOCAL) or use a neutral bullet (CI).
1674
+ * @returns The rendered (colorized) row, ready to drop into a box.
1675
+ * @example
1676
+ * ```ts
1677
+ * permissionRow(ui, { group: "Account · D1", scope: "Edit", reason: "d1", inBaseTemplate: false }, true);
1678
+ * ```
1679
+ */
1680
+ const permissionRow = (ui, permission, showTemplateFlag) => {
1681
+ const { palette } = ui;
1682
+ const templateMark = permission.inBaseTemplate ? palette.green("✓") : palette.pink("+");
1683
+ const mark = showTemplateFlag ? templateMark : palette.dim("•");
1684
+ const flag = showTemplateFlag && !permission.inBaseTemplate ? palette.pink(" ← add to template") : "";
1685
+ const reason = palette.dim(`(${permission.reason})`);
1686
+ return `${mark} ${permission.group} : ${palette.bold(permission.scope)} ${reason}${flag}`;
1687
+ };
1688
+ /**
1689
+ * Render the LOCAL (first deploy) token panel: the full permission set with template/add markers,
1690
+ * then the numbered create-token steps (URL cyan, template + `.env.local` bold).
1691
+ *
1692
+ * @param ui - The branded console to render through.
1693
+ * @param requirement - The LOCAL token requirement (from requiredToken()).
1694
+ * @example
1695
+ * ```ts
1696
+ * localPanel(ui, requiredToken(manifest));
1697
+ * ```
1698
+ */
1699
+ const localPanel = (ui, requirement) => {
1700
+ const { palette } = ui;
1701
+ const adds = requirement.toAdd.map((permission) => `${permission.group.replace("Account · ", "")} → ${permission.scope}`).join(", ");
1702
+ const coversAll = palette.dim(`The "${requirement.base}" template covers everything.`);
1703
+ const addStep = requirement.toAdd.length > 0 ? ` 3. ADD ${palette.pink(adds)}` : ` 3. ${coversAll}`;
1704
+ const template = palette.bold(`"${requirement.base}"`);
1705
+ ui.box([
1706
+ palette.bold("LOCAL — first deploy (creates your infra)"),
1707
+ "",
1708
+ ...requirement.required.map((permission) => permissionRow(ui, permission, true)),
1709
+ "",
1710
+ ` 1. ${palette.cyan(TOKENS_URL$1)}`,
1711
+ ` 2. Create Token → start from the ${template} template.`,
1712
+ addStep,
1713
+ " 4. Account Resources → Include → your account.",
1714
+ ` 5. Create it, copy it, then paste into ${palette.bold(".env.local")} (below).`
1715
+ ]);
1716
+ };
1717
+ /**
1718
+ * Render the compact CI (automation redeploy) token panel: the reduced, read-mostly permission set
1719
+ * for a later Custom Token. No template markers — CI builds a token from scratch, not the template.
1720
+ *
1721
+ * @param ui - The branded console to render through.
1722
+ * @param groups - The CI token permission groups (from ciToken()).
1723
+ * @example
1724
+ * ```ts
1725
+ * ciPanel(ui, ciToken(manifest));
1726
+ * ```
1727
+ */
1728
+ const ciPanel = (ui, groups) => {
1729
+ const { palette } = ui;
1730
+ ui.box([
1731
+ palette.bold("CI — automation redeploy (optional, later)"),
1732
+ "",
1733
+ ...groups.map((permission) => permissionRow(ui, permission, false)),
1734
+ "",
1735
+ palette.dim("Create a Custom Token with exactly these (Read, not Edit, on data)."),
1736
+ palette.dim("Store as the CLOUDFLARE_API_TOKEN secret; pin CLOUDFLARE_ACCOUNT_ID.")
1737
+ ]);
1738
+ };
1739
+ /**
1740
+ * Render the full branded `auth setup` guidance: a heading, the LOCAL token panel (what to create
1741
+ * now), and — when `opts.ci` is supplied — the compact CI panel; otherwise a one-line pointer to
1742
+ * `auth setup` for the CI token (so the guided deploy stays focused on the immediate next step).
1743
+ *
1744
+ * @param ui - The branded console to render through.
1745
+ * @param requirement - The LOCAL token requirement (from requiredToken()).
1746
+ * @param opts - Optional rendering options.
1747
+ * @param opts.ci - The CI token permission groups (from ciToken()); omit to show a pointer instead.
1748
+ * @example
1749
+ * ```ts
1750
+ * renderAuthSetup(ui, requiredToken(manifest)); // guided deploy (LOCAL only)
1751
+ * renderAuthSetup(ui, requiredToken(manifest), { ci: ciToken(m) }); // `auth setup` (LOCAL + CI)
1752
+ * ```
1753
+ */
1754
+ const renderAuthSetup = (ui, requirement, opts) => {
1755
+ ui.heading("Cloudflare API token");
1756
+ localPanel(ui, requirement);
1757
+ if (opts?.ci) ciPanel(ui, opts.ci);
1758
+ else ui.line(ui.palette.dim(" Need a CI token later? Run `auth setup` for the reduced set."));
1759
+ };
1760
+ //#endregion
1761
+ //#region src/plugins/deploy/auth/setup.ts
1762
+ /** Cloudflare's dashboard path for creating API tokens. */
1763
+ const TOKENS_URL = "https://dash.cloudflare.com/profile/api-tokens";
1764
+ /**
1765
+ * Render the FULL local-first token section (the deploy that provisions everything): the permission
1766
+ * table flagging template-missing rows, the template + "add these" steps, and the `.env.local` lines.
1767
+ *
1768
+ * @param requirement - The full token requirement (from requiredToken()).
1769
+ * @returns The local-first section lines.
1770
+ * @example
1771
+ * ```ts
1772
+ * const lines = localSection(requiredToken(manifest));
1773
+ * ```
1774
+ */
1775
+ const localSection = (requirement) => {
1776
+ const permissionRows = requirement.required.map((permission) => {
1777
+ const flag = permission.inBaseTemplate ? "" : " <- add to template";
1778
+ return ` - ${permission.group} : ${permission.scope} (${permission.reason})${flag}`;
1779
+ });
1780
+ const step3 = requirement.toAdd.length > 0 ? [` 3. Under Permissions, ADD: ${requirement.toAdd.map((permission) => `${permission.group.replace("Account · ", "")} -> ${permission.scope}`).join(", ")}`, " (the template omits these; everything else is already included)"] : [` 3. The "${requirement.base}" template covers everything — no changes needed.`];
1781
+ return [
1782
+ "LOCAL — first deploy (provisions infra). A Cloudflare API token with these permissions:",
1783
+ "",
1784
+ ...permissionRows,
1785
+ "",
1786
+ "Fastest path:",
1787
+ ` 1. ${TOKENS_URL} -> Create Token`,
1788
+ ` 2. Start from the "${requirement.base}" template.`,
1789
+ ...step3,
1790
+ " 4. Account Resources -> Include -> your account.",
1791
+ " 5. Create the token, copy it, then add it to .env.local:",
1792
+ " CLOUDFLARE_API_TOKEN=<paste your token>",
1793
+ " CLOUDFLARE_ACCOUNT_ID=<your account id>",
1794
+ " 6. Verify it with `auth` (app.deploy.verifyAuth())."
1795
+ ];
1796
+ };
1797
+ /**
1798
+ * Render the REDUCED CI/automation token section (redeploy-only): the scoped permission table plus
1799
+ * the CI-secret + account-pin steps.
1800
+ *
1801
+ * @param groups - The CI permission groups (from ciToken()).
1802
+ * @returns The CI section lines.
1803
+ * @example
1804
+ * ```ts
1805
+ * const lines = ciSection(ciToken(manifest));
1806
+ * ```
1807
+ */
1808
+ const ciSection = (groups) => {
1809
+ return [
1810
+ "CI — automation redeploy (infra already provisioned by a local deploy). A SCOPED token with:",
1811
+ "",
1812
+ ...groups.map((permission) => ` - ${permission.group} : ${permission.scope} (${permission.reason})`),
1813
+ "",
1814
+ ` 1. ${TOKENS_URL} -> Create Token -> Create Custom Token.`,
1815
+ " 2. Add exactly the permissions above (Read, not Edit, on data resources — CI never creates).",
1816
+ " 3. Account Resources -> Include -> your account.",
1817
+ " 4. Store it as the CLOUDFLARE_API_TOKEN secret in CI, and PIN the account so no account",
1818
+ " lookup (and no Account Settings -> Read) is needed:",
1819
+ " CLOUDFLARE_ACCOUNT_ID=<your account id>",
1820
+ " CI reuses the same idempotent pipeline — it lists existing infra and ships. To let CI also",
1821
+ " CREATE missing infra (self-heal), give it the LOCAL token above instead."
1822
+ ];
1823
+ };
1824
+ /**
1825
+ * Render the `auth setup` instructions from the app manifest: the FULL local-first token (provisions
1826
+ * everything) followed by the REDUCED CI/automation token (redeploy-only).
1827
+ *
1828
+ * @param manifest - The assembled deploy manifest.
1829
+ * @returns A multi-line instruction string covering both tokens.
1830
+ * @example
1831
+ * ```ts
1832
+ * const text = tokenInstructions(manifest);
1833
+ * ```
1834
+ */
1835
+ const tokenInstructions = (manifest) => [
1836
+ ...localSection(requiredToken(manifest)),
1837
+ "",
1838
+ ...ciSection(ciToken(manifest))
1839
+ ].join("\n");
1840
+ /**
1841
+ * Render a ready-to-fill `.env.local` for the guided deploy: the two Cloudflare credential keys
1842
+ * (left blank to paste into) preceded by a comment block derived from the manifest — where to
1843
+ * create the token, which template to start from, exactly which permissions to add, and how to find
1844
+ * the account id. The same guidance {@link tokenInstructions} prints, but PERSISTED in the file the
1845
+ * user edits (so it survives the terminal scrolling away). Pure: no fs, no network.
1846
+ *
1847
+ * @param manifest - The assembled deploy manifest.
1848
+ * @returns The `.env.local` file contents (trailing newline included).
1849
+ * @example
1850
+ * ```ts
1851
+ * await writeFile(".env.local", envLocalScaffold(manifest));
1852
+ * ```
1853
+ */
1854
+ const envLocalScaffold = (manifest) => {
1855
+ const requirement = requiredToken(manifest);
1856
+ const addStep = requirement.toAdd.length > 0 ? `# 3. Under Permissions, ADD: ${requirement.toAdd.map((permission) => `${permission.group.replace("Account · ", "")} -> ${permission.scope}`).join(", ")}` : `# 3. The "${requirement.base}" template covers everything — no changes needed.`;
1857
+ return `${[
1858
+ "# Cloudflare credentials for the moku deploy — fill in the two values below, then re-run deploy.",
1859
+ "# Local-only: keep this file out of git (.env.local is gitignored by convention).",
1860
+ "#",
1861
+ "# Create the API token:",
1862
+ `# 1. ${TOKENS_URL} -> Create Token`,
1863
+ `# 2. Start from the "${requirement.base}" template.`,
1864
+ addStep,
1865
+ "# 4. Account Resources -> Include -> your account.",
1866
+ "# 5. Create the token, copy it, and paste it after CLOUDFLARE_API_TOKEN= below.",
1867
+ "#",
1868
+ "# Account id: open https://dash.cloudflare.com — it is the id in the URL",
1869
+ "# (dash.cloudflare.com/<account-id>) or in the right sidebar of any domain's overview.",
1870
+ "",
1871
+ "CLOUDFLARE_API_TOKEN=",
1872
+ "CLOUDFLARE_ACCOUNT_ID="
1873
+ ].join("\n")}\n`;
1874
+ };
1875
+ //#endregion
1876
+ //#region src/plugins/deploy/infra/cloudflare.ts
1877
+ /**
1878
+ * @file deploy plugin — Cloudflare REST discovery client (infra preflight).
1879
+ *
1880
+ * Lists what already exists in a Cloudflare account so the deploy pipeline can create only the
1881
+ * missing resources (idempotent provisioning) and recover real ids for existing kv/d1 bindings.
1882
+ * Authenticated with the `.env` API token (CLOUDFLARE_API_TOKEN) — never an interactive login.
1883
+ * Uses the global `fetch`; node-only, never imported by the runtime Worker bundle.
1884
+ */
1885
+ const API_BASE = "https://api.cloudflare.com/client/v4";
1886
+ /**
1887
+ * GET a Cloudflare API path with the bearer token and unwrap the `result`.
1888
+ *
1889
+ * @param token - The Cloudflare API token (CLOUDFLARE_API_TOKEN).
1890
+ * @param path - API path beneath the v4 base (e.g. "/accounts").
1891
+ * @returns The unwrapped `result` payload, typed by the caller.
1892
+ * @throws {Error} When the HTTP request fails or the API reports `success: false`.
1893
+ * @example
1894
+ * ```ts
1895
+ * const accounts = await cfGet<Array<{ id: string }>>(token, "/accounts");
1896
+ * ```
1897
+ */
1898
+ const cfGet = async (token, path) => {
1899
+ const response = await fetch(`${API_BASE}${path}`, { headers: {
1900
+ Authorization: `Bearer ${token}`,
1901
+ "Content-Type": "application/json"
1902
+ } });
1903
+ const body = await response.json();
1904
+ if (!response.ok || !body.success) {
1905
+ const detail = body.errors?.map((error) => error.message).join("; ") || `HTTP ${response.status}`;
1906
+ throw new Error(`[moku-worker] Cloudflare API request failed (${path}): ${detail}`);
1907
+ }
1908
+ return body.result;
1909
+ };
1910
+ /**
1911
+ * Resolve the Cloudflare account (id + display name) accessible to the token. Used when the
1912
+ * consumer did not pin CLOUDFLARE_ACCOUNT_ID; the first accessible account is chosen.
1913
+ *
1914
+ * @param token - The Cloudflare API token.
1915
+ * @returns The resolved account id and name.
1916
+ * @throws {Error} When the token can access no account.
1917
+ * @example
1918
+ * ```ts
1919
+ * const { id, name } = await resolveAccount(token);
1920
+ * ```
1921
+ */
1922
+ const resolveAccount = async (token) => {
1923
+ const first = (await cfGet(token, "/accounts"))[0];
1924
+ if (!first) throw new Error("[moku-worker] No Cloudflare account is accessible with this API token.");
1925
+ return {
1926
+ id: first.id,
1927
+ name: first.name
1928
+ };
1929
+ };
1930
+ /**
1931
+ * Verify a Cloudflare API token via `GET /user/tokens/verify`. Returns its status (`"active"` for
1932
+ * a usable token); throws (via cfGet) when the token is rejected outright (401/invalid).
1933
+ *
1934
+ * @param token - The Cloudflare API token to verify.
1935
+ * @returns The token status string reported by Cloudflare.
1936
+ * @throws {Error} When the verify request fails (invalid/expired token).
1937
+ * @example
1938
+ * ```ts
1939
+ * const { status } = await verifyToken(token); // status === "active"
1940
+ * ```
1941
+ */
1942
+ const verifyToken = async (token) => {
1943
+ return { status: (await cfGet(token, "/user/tokens/verify")).status };
1944
+ };
1945
+ /**
1946
+ * List the resources that already exist in the account, querying ONLY the kinds the app declares
1947
+ * (one request per declared kind, in parallel), indexed for the preflight diff. Scoping to the
1948
+ * declared kinds keeps the API token minimal — an app with only KV never lists (and so never needs
1949
+ * read permission on) D1, R2, or Queues.
1950
+ *
1951
+ * @param token - The Cloudflare API token.
1952
+ * @param accountId - The Cloudflare account id to scope the listings to.
1953
+ * @param kinds - The resource kinds present in the manifest (the only kinds queried).
1954
+ * @returns The existing resources, indexed by kind (un-queried kinds resolve empty).
1955
+ * @throws {Error} When any listing request fails.
1956
+ * @example
1957
+ * ```ts
1958
+ * const existing = await listExisting(token, accountId, new Set(["kv", "d1"]));
1959
+ * if (existing.kv.has("SESSIONS")) { ... }
1960
+ * ```
1961
+ */
1962
+ const listExisting = async (token, accountId, kinds) => {
1963
+ const base = `/accounts/${accountId}`;
1964
+ const [kv, d1, r2, queues] = await Promise.all([
1965
+ kinds.has("kv") ? cfGet(token, `${base}/storage/kv/namespaces`) : Promise.resolve([]),
1966
+ kinds.has("d1") ? cfGet(token, `${base}/d1/database`) : Promise.resolve([]),
1967
+ kinds.has("r2") ? cfGet(token, `${base}/r2/buckets`) : Promise.resolve({}),
1968
+ kinds.has("queue") ? cfGet(token, `${base}/queues`) : Promise.resolve([])
1969
+ ]);
1970
+ return {
1971
+ kv: new Map(kv.map((namespace) => [namespace.title, namespace.id])),
1972
+ d1: new Map(d1.map((database) => [database.name, database.uuid])),
1973
+ r2: new Set((r2.buckets ?? []).map((bucket) => bucket.name)),
1974
+ queue: new Set(queues.map((queue) => queue.queue_name))
1975
+ };
1976
+ };
1977
+ //#endregion
1978
+ //#region src/plugins/deploy/auth/verify.ts
1979
+ /**
1980
+ * @file deploy plugin — `.env` token verification + account resolution.
1981
+ *
1982
+ * Reads CLOUDFLARE_API_TOKEN via ctx.env, verifies it is active against the Cloudflare API, and
1983
+ * resolves the account. Emits auth:verified. Throws a branded, actionable error (pointing at
1984
+ * `auth setup`) when the token is absent, invalid, or inactive — never an interactive login.
1985
+ * Node-only; never imported by the runtime Worker bundle.
1986
+ */
1987
+ /** Branded hint appended to every auth failure so the user knows the next step. */
1988
+ const SETUP_HINT = "Run `auth setup` for the exact token to create.";
1989
+ /**
1990
+ * Verify the `.env` Cloudflare API token and resolve its account.
1991
+ *
1992
+ * @param ctx - The deploy plugin context (env + emit).
1993
+ * @returns The verified auth status (account + id).
1994
+ * @throws {Error} When the token is absent, invalid/expired, or not active.
1995
+ * @example
1996
+ * ```ts
1997
+ * const { account, accountId } = await verifyAuth(ctx);
1998
+ * ```
1999
+ */
2000
+ const verifyAuth = async (ctx) => {
2001
+ const token = ctx.env.get("CLOUDFLARE_API_TOKEN");
2002
+ if (token === void 0 || token === "") throw new Error(`[moku-worker] CLOUDFLARE_API_TOKEN is not set. ${SETUP_HINT}`);
2003
+ let status;
2004
+ try {
2005
+ ({status} = await verifyToken(token));
2006
+ } catch (error) {
2007
+ throw new Error(`[moku-worker] Cloudflare API token is invalid or expired. ${SETUP_HINT}`, { cause: error });
2008
+ }
2009
+ if (status !== "active") throw new Error(`[moku-worker] Cloudflare API token is "${status}", not active. ${SETUP_HINT}`);
2010
+ const pinnedAccountId = ctx.env.get("CLOUDFLARE_ACCOUNT_ID");
2011
+ const account = pinnedAccountId === void 0 || pinnedAccountId === "" ? await resolveAccount(token) : {
2012
+ id: pinnedAccountId,
2013
+ name: pinnedAccountId
2014
+ };
2015
+ ctx.emit("auth:verified", {
2016
+ account: account.name,
2017
+ accountId: account.id,
2018
+ scopes: []
2019
+ });
2020
+ return {
2021
+ ok: true,
2022
+ account: account.name,
2023
+ accountId: account.id,
2024
+ scopes: []
2025
+ };
2026
+ };
2027
+ //#endregion
2028
+ //#region src/plugins/deploy/infra/render.ts
2029
+ /**
2030
+ * Derive a human-readable name from a resource descriptor: the Cloudflare resource `name` for the
2031
+ * provisioned kinds (kv/r2/d1/queue), or the exported `className` for a Durable Object (which has no
2032
+ * provisioned name). Used in both the provision events and the branded panels so the two agree.
2033
+ *
2034
+ * @param resource - The resource descriptor.
2035
+ * @returns A short name identifying the resource.
2036
+ * @example
2037
+ * ```ts
2038
+ * resourceName({ kind: "kv", name: "tracker-cache", binding: "CACHE" }); // "tracker-cache"
2039
+ * ```
2040
+ */
2041
+ const resourceName = (resource) => resource.kind === "do" ? resource.className : resource.name;
2042
+ /**
2043
+ * Format a `kind name` cell, padding the kind so the names line up in a column.
2044
+ *
2045
+ * @param kind - The resource kind (kv / r2 / d1 / queue / do).
2046
+ * @param name - The resource name.
2047
+ * @returns The aligned `kind name` cell.
2048
+ * @example
2049
+ * ```ts
2050
+ * cell("kv", "CACHE"); // "kv CACHE"
2051
+ * ```
2052
+ */
2053
+ const cell = (kind, name) => `${kind.padEnd(6)}${name}`;
2054
+ /**
2055
+ * Row tag for a Durable Object — it ships with the Worker (`wrangler deploy` creates the namespace),
2056
+ * so it is NEVER labelled `(exists)` (the planner never queried the account for it). Shared by the
2057
+ * plan and provision-result panels so the two always read the same.
2058
+ */
2059
+ const SHIPS_WITH_WORKER = "(ships with worker)";
2060
+ /**
2061
+ * ANSI SGR matcher — built from `String.fromCharCode(27)` (the ESC byte) so no control character
2062
+ * appears in a regex literal (which both linters reject).
2063
+ */
2064
+ const ANSI_SGR = new RegExp(String.raw`${String.fromCodePoint(27)}\[[0-9;]*m`, "gu");
2065
+ /**
2066
+ * Strip ANSI SGR escape sequences so a captured (colorized) error renders as plain, readable text.
2067
+ *
2068
+ * @param text - The (possibly colorized) text.
2069
+ * @returns The text with ANSI color codes removed.
2070
+ * @example
2071
+ * ```ts
2072
+ * stripAnsi(`${String.fromCharCode(27)}[31mX${String.fromCharCode(27)}[0m`); // "X"
2073
+ * ```
2074
+ */
2075
+ const stripAnsi = (text) => text.replaceAll(ANSI_SGR, "");
2076
+ /**
2077
+ * Clean a captured (colorized, multi-line, wrapper-wrapped) provision error down to its meaningful
2078
+ * text: strip ANSI, drop the wrapper lines (the branded prefix, wrangler's log-file pointer), strip
2079
+ * each `✘ [ERROR]` marker, and join what's left. Returns the FULL message (the caller word-wraps it)
2080
+ * so the user reads the actual reason — never a truncated `…`.
2081
+ *
2082
+ * @param message - The captured error message.
2083
+ * @returns The full, plain failure reason.
2084
+ * @example
2085
+ * ```ts
2086
+ * cleanError("[moku-worker] wrangler exited…\n ✘ [ERROR] The bucket name is invalid.");
2087
+ * // "The bucket name is invalid."
2088
+ * ```
2089
+ */
2090
+ const cleanError = (message) => {
2091
+ const cleaned = stripAnsi(message).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).filter((line) => !/^\[moku-worker\]/u.test(line)).filter((line) => !/logs were written to/iu.test(line)).map((line) => line.replace(/^✘\s*/u, "").replace(/^\[error\]\s*/iu, "")).join(" ");
2092
+ return cleaned.length > 0 ? cleaned : stripAnsi(message).trim();
2093
+ };
2094
+ /**
2095
+ * Word-wrap text to `width` columns (never splitting inside a word), so a long failure reason reads
2096
+ * as a tidy indented block instead of forcing the box wide or scrolling off the edge.
2097
+ *
2098
+ * @param text - The text to wrap.
2099
+ * @param width - The maximum column width per line.
2100
+ * @returns The wrapped lines.
2101
+ * @example
2102
+ * ```ts
2103
+ * wrapText("a long sentence to wrap", 10); // ["a long", "sentence", "to wrap"]
2104
+ * ```
2105
+ */
2106
+ const wrapText = (text, width) => {
2107
+ const lines = [];
2108
+ let line = "";
2109
+ for (const word of text.split(/\s+/u).filter(Boolean)) if (line.length === 0) line = word;
2110
+ else if (line.length + 1 + word.length <= width) line += ` ${word}`;
2111
+ else {
2112
+ lines.push(line);
2113
+ line = word;
2114
+ }
2115
+ if (line.length > 0) lines.push(line);
2116
+ return lines;
2117
+ };
2118
+ /**
2119
+ * Render the infra preflight plan as a branded panel: a dim summary line (counts + account) then one
2120
+ * row per declared resource — a pink `+` for those to create, a dim `~ (exists)` for those already
2121
+ * present, and a dim `~ (ships with worker)` for Durable Objects (created by `wrangler deploy`, never
2122
+ * pre-provisioned). When nothing needs creating it still renders, so the user sees the full picture.
2123
+ *
2124
+ * @param ui - The branded console to render through.
2125
+ * @param plan - The infra plan (existing vs missing vs ships-with-Worker) from checkInfra()/planInfra().
2126
+ * @example
2127
+ * ```ts
2128
+ * renderPlan(ui, await planInfra(ctx, manifest));
2129
+ * ```
2130
+ */
2131
+ const renderPlan = (ui, plan) => {
2132
+ const { palette } = ui;
2133
+ const counts = [`${String(plan.missing.length)} to create`, `${String(plan.exists.length)} exist`];
2134
+ if (plan.ships.length > 0) counts.push(`${String(plan.ships.length)} with worker`);
2135
+ const summary = palette.dim(`${counts.join(" · ")} · ${plan.account}`);
2136
+ const createRows = plan.missing.map((resource) => `${palette.pink("+")} ${cell(resource.kind, resourceName(resource))}`);
2137
+ const existsRows = plan.exists.map((ref) => `${palette.dim("~")} ${cell(ref.resource.kind, resourceName(ref.resource))} ${palette.dim("(exists)")}`);
2138
+ const shipsRows = plan.ships.map((resource) => `${palette.dim("~")} ${cell(resource.kind, resourceName(resource))} ${palette.dim(SHIPS_WITH_WORKER)}`);
2139
+ ui.heading("Infra plan");
2140
+ ui.box([
2141
+ summary,
2142
+ "",
2143
+ ...createRows,
2144
+ ...existsRows,
2145
+ ...shipsRows
2146
+ ]);
2147
+ };
2148
+ /**
2149
+ * Render the provision result as a branded panel — a green `✓` per created resource, a dim `~` per
2150
+ * skipped, a dim `~ (ships with worker)` per Durable Object, a red `✗` per failure, then a summary
2151
+ * line (failed count red when non-zero) — followed, when anything failed, by a detail block printing
2152
+ * each failure's FULL reason (ANSI-stripped and word-wrapped) so it is actually readable instead of
2153
+ * truncated inside the box.
2154
+ *
2155
+ * @param ui - The branded console to render through.
2156
+ * @param result - The provision result from provisionInfra()/the deploy pipeline.
2157
+ * @example
2158
+ * ```ts
2159
+ * renderProvisionResult(ui, await provisionInfra(plan));
2160
+ * ```
2161
+ */
2162
+ const renderProvisionResult = (ui, result) => {
2163
+ const { palette } = ui;
2164
+ const createdRows = result.created.map((ref) => `${palette.green("✓")} ${cell(ref.resource.kind, resourceName(ref.resource))}`);
2165
+ const skippedRows = result.skipped.map((ref) => `${palette.dim("~")} ${cell(ref.resource.kind, resourceName(ref.resource))} ${palette.dim("(exists)")}`);
2166
+ const bundledRows = result.bundled.map((resource) => `${palette.dim("~")} ${cell(resource.kind, resourceName(resource))} ${palette.dim(SHIPS_WITH_WORKER)}`);
2167
+ const failedRows = result.failed.map((failure) => `${palette.red("✗")} ${cell(failure.resource.kind, resourceName(failure.resource))}`);
2168
+ const failedCount = result.failed.length > 0 ? palette.red(`${String(result.failed.length)} failed`) : "0 failed";
2169
+ const counts = [`${String(result.created.length)} created`, `${String(result.skipped.length)} exist`];
2170
+ if (result.bundled.length > 0) counts.push(`${String(result.bundled.length)} with worker`);
2171
+ const summary = `${counts.join(" · ")} · ${failedCount}`;
2172
+ ui.heading("Provisioned");
2173
+ ui.box([
2174
+ ...createdRows,
2175
+ ...skippedRows,
2176
+ ...bundledRows,
2177
+ ...failedRows,
2178
+ "",
2179
+ summary
2180
+ ]);
2181
+ if (result.failed.length > 0) {
2182
+ ui.line();
2183
+ for (const failure of result.failed) {
2184
+ ui.line(` ${palette.red("✗")} ${cell(failure.resource.kind, resourceName(failure.resource))}`);
2185
+ for (const wrapped of wrapText(cleanError(failure.error), ui.width - 4)) ui.line(palette.dim(` ${wrapped}`));
2186
+ }
2187
+ }
2188
+ };
2189
+ /**
2190
+ * Format an elapsed duration compactly: sub-second as `820ms`, otherwise one-decimal seconds (`4.2s`),
2191
+ * and minutes once it crosses 60s (`1m04s`) so a long deploy stays readable.
2192
+ *
2193
+ * @param ms - The elapsed milliseconds.
2194
+ * @returns The compact duration string.
2195
+ * @example
2196
+ * ```ts
2197
+ * formatDuration(4234); // "4.2s"
2198
+ * ```
2199
+ */
2200
+ const formatDuration = (ms) => {
2201
+ if (ms < 1e3) return `${String(ms)}ms`;
2202
+ const seconds = ms / 1e3;
2203
+ if (seconds < 60) return `${seconds.toFixed(1)}s`;
2204
+ const whole = Math.floor(seconds);
2205
+ return `${String(Math.floor(whole / 60))}m${String(whole % 60).padStart(2, "0")}s`;
2206
+ };
2207
+ /**
2208
+ * Render the terminal deploy summary as a branded panel — the headline the user actually wants. The
2209
+ * live URL leads on its own line (pink, so it is the first thing the eye lands on), then a dim
2210
+ * key/value block: the target stage, the resource tally (with a red `failed` count when non-zero),
2211
+ * and the wall-clock time the whole deploy took. Replaces the prior single `deployed → url` line.
2212
+ *
2213
+ * @param ui - The branded console to render through.
2214
+ * @param summary - The deploy summary fields.
2215
+ * @param summary.url - The live deployed URL (the panel headline).
2216
+ * @param summary.stage - The target stage the worker deployed to.
2217
+ * @param summary.created - How many resources were created this run.
2218
+ * @param summary.exists - How many resources already existed (skipped).
2219
+ * @param summary.bundled - How many Durable Objects shipped with the Worker.
2220
+ * @param summary.failed - How many resources failed to provision.
2221
+ * @param summary.elapsedMs - The wall-clock deploy duration in milliseconds.
2222
+ * @example
2223
+ * ```ts
2224
+ * renderDeploySummary(ui, { url, stage: "production", created: 0, exists: 5, bundled: 1, failed: 0, elapsedMs: 4234 });
2225
+ * ```
2226
+ */
2227
+ const renderDeploySummary = (ui, summary) => {
2228
+ const { palette } = ui;
2229
+ const parts = [`${String(summary.exists)} exist`, `${String(summary.created)} created`];
2230
+ if (summary.bundled > 0) parts.push(`${String(summary.bundled)} with worker`);
2231
+ const tally = parts.join(" · ");
2232
+ const failedLabel = palette.red(`${String(summary.failed)} failed`);
2233
+ const resources = summary.failed > 0 ? `${tally} · ${failedLabel}` : tally;
2234
+ ui.heading("Deployed");
2235
+ ui.box([
2236
+ palette.pink(summary.url),
2237
+ "",
2238
+ `${palette.dim("stage".padEnd(10))}${summary.stage}`,
2239
+ `${palette.dim("resources".padEnd(10))}${resources}`,
2240
+ `${palette.dim("took".padEnd(10))}${formatDuration(summary.elapsedMs)}`
2241
+ ]);
2242
+ };
2243
+ /**
2244
+ * Render the D1 migration outcome as a branded panel — the readable replacement for wrangler's raw
2245
+ * `d1 migrations apply` TUI. One row per database: the `d1 <binding>` cell plus a pink `N applied`
2246
+ * count (or a dim `up to date` when nothing was pending), with each applied migration filename listed
2247
+ * beneath as a green `✓`. A dim scope footer (`remote` / `local`) names which database was touched.
2248
+ * The caller renders this only when at least one database actually ran migrations.
2249
+ *
2250
+ * @param ui - The branded console to render through.
2251
+ * @param outcomes - The per-database migration outcomes (one per d1 instance that declares migrations).
2252
+ * @param scope - Which database the migrations ran against: `remote` (Cloudflare) or `local` (dev).
2253
+ * @example
2254
+ * ```ts
2255
+ * renderMigrateSummary(ui, [{ binding: "DB", applied: ["0003_x.sql"], upToDate: false }], "remote");
2256
+ * ```
2257
+ */
2258
+ const renderMigrateSummary = (ui, outcomes, scope) => {
2259
+ const { palette } = ui;
2260
+ const rows = [];
2261
+ for (const outcome of outcomes) {
2262
+ const count = outcome.applied.length;
2263
+ const appliedLabel = palette.pink(count > 0 ? `${String(count)} applied` : "applied");
2264
+ const status = outcome.upToDate ? palette.dim("up to date") : appliedLabel;
2265
+ rows.push(`${cell("d1", outcome.binding)} ${status}`);
2266
+ for (const name of outcome.applied) rows.push(` ${palette.green("✓")} ${palette.dim(name)}`);
2267
+ }
2268
+ ui.heading("Migrated");
2269
+ ui.box([
2270
+ ...rows,
2271
+ "",
2272
+ palette.dim(scope)
2273
+ ]);
2274
+ };
2275
+ /**
2276
+ * Render the seed outcome as a branded panel — the readable replacement for wrangler's raw
2277
+ * `d1 execute` / `kv key delete` TUI. Leads with the loaded `file → binding` (pink file), an optional
2278
+ * dim stats line (rows written / statements, only the parts wrangler reported), then — when the seed
2279
+ * cleared cached KV keys — a `KV reset` block listing each `~ binding key` so the user sees exactly
2280
+ * what was dropped. A dim scope footer (`remote` / `local`) names which database was seeded.
2281
+ *
2282
+ * @param ui - The branded console to render through.
2283
+ * @param outcome - The seed outcome (file, target binding, best-effort counts, the KV keys reset).
2284
+ * @param scope - Which database the seed ran against: `remote` (Cloudflare) or `local` (dev).
2285
+ * @example
2286
+ * ```ts
2287
+ * renderSeedSummary(ui, { file: "db/seed.sql", binding: "DB", rowsWritten: 18, resetKv: [] }, "remote");
2288
+ * ```
2289
+ */
2290
+ const renderSeedSummary = (ui, outcome, scope) => {
2291
+ const { palette } = ui;
2292
+ const lines = [`${palette.pink(outcome.file)} ${palette.dim("→")} ${outcome.binding}`];
2293
+ const stats = [];
2294
+ if (outcome.rowsWritten !== void 0) stats.push(`${String(outcome.rowsWritten)} rows written`);
2295
+ if (outcome.statements !== void 0) stats.push(`${String(outcome.statements)} statements`);
2296
+ if (stats.length > 0) lines.push(palette.dim(stats.join(" · ")));
2297
+ if (outcome.resetKv.length > 0) {
2298
+ lines.push("", palette.dim("KV reset"));
2299
+ for (const entry of outcome.resetKv) lines.push(`${palette.dim("~")} ${entry.binding} ${palette.dim(entry.key)}`);
2300
+ }
2301
+ ui.heading("Seeded");
2302
+ ui.box([
2303
+ ...lines,
2304
+ "",
2305
+ palette.dim(scope)
2306
+ ]);
2307
+ };
2308
+ //#endregion
2309
+ //#region src/plugins/deploy/runner.ts
2310
+ /**
2311
+ * @file deploy plugin — wrangler subprocess wrapper (node:child_process).
2312
+ *
2313
+ * Spawns `wrangler` with the given args and resolves the deployed URL
2314
+ * (extracted from stdout for `wrangler deploy`), or the full stdout for other verbs.
2315
+ * This module is node-only; never imported by the runtime Worker bundle.
2316
+ */
2317
+ /**
2318
+ * Extract the deployed URL from `wrangler deploy` stdout.
2319
+ * Wrangler prints a line like: "Published my-worker (1.23 sec) https://..."
2320
+ * or "Deployed my-worker (1.23 sec) https://...".
2321
+ *
2322
+ * @param output - The combined stdout from wrangler deploy.
2323
+ * @returns The deployed URL, or empty string when not found.
2324
+ * @example
2325
+ * ```ts
2326
+ * extractDeployedUrl("Deployed my-worker (0.5 sec) https://my-worker.workers.dev");
2327
+ * // "https://my-worker.workers.dev"
2328
+ * ```
2329
+ */
2330
+ const extractDeployedUrl = (output) => {
2331
+ return /https:\/\/[^\s]+\.workers\.dev[^\s]*/u.exec(output)?.[0] ?? "";
2332
+ };
2333
+ /**
2334
+ * Spawn `wrangler` with the given args and resolve the output string.
2335
+ * For `wrangler deploy`, the resolved value is the deployed URL parsed from stdout.
2336
+ * For all other verbs (dev, kv namespace create, etc.), the resolved value is stdout.
2337
+ *
2338
+ * @param args - Wrangler CLI arguments (e.g. ["deploy", "--config", "wrangler.jsonc"]).
2339
+ * @returns Resolves with the deployed URL (deploy verb) or full stdout (other verbs).
2340
+ * @throws {Error} When wrangler exits with a non-zero code.
2341
+ * @example
2342
+ * ```ts
2343
+ * const url = await runWrangler(["deploy", "--config", "wrangler.jsonc"]);
2344
+ * await runWrangler(["kv", "namespace", "create", "CACHE"]);
2345
+ * ```
2346
+ */
2347
+ const runWrangler = (args) => new Promise((resolve, reject) => {
2348
+ const chunks = [];
2349
+ const errChunks = [];
2350
+ const child = spawn("wrangler", args, {
2351
+ env: { ...process.env },
2352
+ stdio: [
2353
+ "ignore",
2354
+ "pipe",
2355
+ "pipe"
2356
+ ]
2357
+ });
2358
+ child.stdout.on("data", (chunk) => {
2359
+ chunks.push(chunk);
2360
+ });
2361
+ child.stderr.on("data", (chunk) => {
2362
+ errChunks.push(chunk);
2363
+ });
2364
+ child.on("error", (err) => {
2365
+ reject(/* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${err.message}`));
2366
+ });
2367
+ child.on("close", (code) => {
2368
+ const stdout = Buffer.concat(chunks).toString("utf8");
2369
+ const stderr = Buffer.concat(errChunks).toString("utf8");
2370
+ if (code !== 0) {
2371
+ reject(/* @__PURE__ */ new Error(`[moku-worker] wrangler exited with code ${String(code)}.\n ${stderr || stdout}`));
2372
+ return;
2373
+ }
2374
+ resolve(args[0] === "deploy" ? extractDeployedUrl(stdout) : stdout);
2375
+ });
2376
+ });
2377
+ /**
2378
+ * Spawn `wrangler` with the given args, inheriting stdio so its output streams live to the user's
2379
+ * terminal (used by the generic passthrough and long-lived commands like `tail`).
2380
+ *
2381
+ * @param args - Wrangler CLI arguments (e.g. ["kv", "namespace", "list"]).
2382
+ * @returns Resolves once wrangler exits successfully.
2383
+ * @throws {Error} When wrangler cannot be spawned or exits non-zero.
2384
+ * @example
2385
+ * ```ts
2386
+ * await runWranglerInherit(["kv", "namespace", "list"]);
2387
+ * ```
2388
+ */
2389
+ const runWranglerInherit = (args) => {
2390
+ return new Promise((resolve, reject) => {
2391
+ const child = spawn("wrangler", args, { stdio: "inherit" });
2392
+ child.on("error", (error) => {
2393
+ reject(/* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${error.message}`));
2394
+ });
2395
+ child.on("close", (code) => {
2396
+ if (code === 0) {
2397
+ resolve();
2398
+ return;
2399
+ }
2400
+ reject(/* @__PURE__ */ new Error(`[moku-worker] wrangler exited with code ${String(code)}.`));
2401
+ });
2402
+ });
2403
+ };
2404
+ //#endregion
2405
+ //#region src/plugins/deploy/seed.ts
2406
+ /**
2407
+ * @file deploy plugin — shared D1 seed helpers (resolve the target db, run a configured seed).
2408
+ *
2409
+ * Pure orchestration over an INJECTED wrangler runner, so the post-deploy REMOTE seed (api.ts) and
2410
+ * the dev-session LOCAL seed (dev/runner.ts) stay in lockstep — same file, same KV-reset semantics,
2411
+ * differing only in the `--remote` / `--local` scope. Migrations are NOT applied here: each caller
2412
+ * applies the schema first (the deploy's migration step / dev's local-migrate step), then seeds.
2413
+ * Node-only; never imported by the runtime Worker bundle.
2414
+ */
2415
+ /**
2416
+ * Parse the best-effort row/statement counts from wrangler's `d1 execute` output so the branded seed
2417
+ * panel can report them — degrading gracefully (each field simply omitted) when wrangler's format
2418
+ * differs or the runner streamed instead of captured. Wrangler prints lines like "🚣 18 commands
2419
+ * executed" and a rows-written total; both are matched loosely (case-insensitive).
2420
+ *
2421
+ * @param output - The captured stdout from `wrangler d1 execute` (empty when the runner streamed).
2422
+ * @returns The parsed counts — each field present only when found.
2423
+ * @example
2424
+ * ```ts
2425
+ * parseSeedStats("🚣 18 commands executed (30 rows written)"); // { statements: 18, rowsWritten: 30 }
2426
+ * ```
2427
+ */
2428
+ const parseSeedStats = (output) => {
2429
+ const rows = /(\d{1,12}) rows? written/iu.exec(output);
2430
+ const commands = /(\d{1,12}) commands? executed/iu.exec(output) ?? /executed (\d{1,12}) commands?/iu.exec(output);
2431
+ const result = {};
2432
+ if (commands?.[1] !== void 0) result.statements = Number(commands[1]);
2433
+ if (rows?.[1] !== void 0) result.rowsWritten = Number(rows[1]);
2434
+ return result;
2435
+ };
2436
+ /**
2437
+ * Parse which migrations wrangler applied from its captured `d1 migrations apply` output, so the
2438
+ * branded migrate panel can name them instead of dumping wrangler's raw migration TUI. `upToDate` is
2439
+ * true when wrangler reported nothing pending ("No migrations to apply"); otherwise every
2440
+ * `NNNN_name.sql` filename token in the output is collected in order (de-duplicated). Degrades
2441
+ * safely — an unrecognized format yields no names, and the panel falls back to a generic "applied".
2442
+ * Lives here (not in api.ts) so both the deploy path and the dev path parse it without a cycle.
2443
+ *
2444
+ * @param output - The captured stdout from `wrangler d1 migrations apply`.
2445
+ * @returns The applied migration filenames and whether the database was already up to date.
2446
+ * @example
2447
+ * ```ts
2448
+ * parseMigrationsApplied("Applied 0003_x.sql\n0004_y.sql"); // { applied: ["0003_x.sql", "0004_y.sql"], upToDate: false }
2449
+ * ```
2450
+ */
2451
+ const parseMigrationsApplied = (output) => {
2452
+ if (/no migrations to apply/iu.test(output)) return {
2453
+ applied: [],
2454
+ upToDate: true
2455
+ };
2456
+ const applied = [];
2457
+ const seen = /* @__PURE__ */ new Set();
2458
+ for (const match of output.matchAll(/\b\d{3,}_[A-Za-z0-9_-]+\.sql\b/gu)) {
2459
+ const name = match[0];
2460
+ if (!seen.has(name)) {
2461
+ seen.add(name);
2462
+ applied.push(name);
2463
+ }
2464
+ }
2465
+ return {
2466
+ applied,
2467
+ upToDate: false
2468
+ };
2469
+ };
2470
+ /**
2471
+ * Resolve the single configured d1 database (or the one bound to `binding` when several exist) from
2472
+ * the d1 plugin's manifest. The shared resolver behind `seed()`, the post-deploy seed, and the dev
2473
+ * seed; throws a branded error when the choice is ambiguous (none/several, no binding) or unknown.
2474
+ *
2475
+ * @param ctx - The deploy plugin context.
2476
+ * @param binding - The d1 binding to target when more than one is configured; the sole one otherwise.
2477
+ * @returns The resolved d1 resource descriptor (its binding + optional migrations dir).
2478
+ * @throws {Error} When no single database resolves (none/several without a binding, or unknown binding).
2479
+ * @example
2480
+ * ```ts
2481
+ * const db = resolveD1(ctx, "DB");
2482
+ * ```
2483
+ */
2484
+ const resolveD1 = (ctx, binding) => {
2485
+ const databases = ctx.require(d1Plugin).deployManifest();
2486
+ const matched = binding === void 0 ? databases : databases.filter((db) => db.binding === binding);
2487
+ const target = matched.length === 1 ? matched[0] : void 0;
2488
+ if (target === void 0) throw new Error(binding === void 0 ? `[moku-worker] seed: ${String(databases.length)} d1 databases configured — pass { binding } to choose one.` : `[moku-worker] seed: no d1 database is bound to "${binding}".`);
2489
+ return target;
2490
+ };
2491
+ /**
2492
+ * Run a configured seed against one scope: execute the seed SQL against the d1 database, then delete
2493
+ * each configured cached KV key so the next read rebuilds it from the freshly-seeded rows. The
2494
+ * schema is assumed to exist (the caller applies migrations first), so this never migrates. The
2495
+ * wrangler runner is injected so the same orchestration serves the streamed deploy path and the
2496
+ * injectable dev path.
2497
+ *
2498
+ * @param ctx - The deploy plugin context.
2499
+ * @param run - The wrangler runner to execute each command through (a CAPTURING runner lets the
2500
+ * returned outcome report row/statement counts; a streaming one still works, just without them).
2501
+ * @param seed - The resolved seed config (SQL file, optional binding, KV keys to reset).
2502
+ * @param scope - The wrangler scope: `--remote` (deploy) or `--local` (dev).
2503
+ * @returns The seed outcome (file, target binding, best-effort counts, and the KV keys that were reset).
2504
+ * @throws {Error} When no d1 database is configured, or the seed's binding cannot be resolved.
2505
+ * @example
2506
+ * ```ts
2507
+ * const outcome = await runConfiguredSeed(ctx, runWrangler, ctx.config.seed, "--remote");
2508
+ * ```
2509
+ */
2510
+ const runConfiguredSeed = async (ctx, run, seed, scope) => {
2511
+ if (!ctx.has("d1")) throw new Error("[moku-worker] seed: no d1 database is configured.");
2512
+ const database = resolveD1(ctx, seed.binding);
2513
+ const executed = await run([
2514
+ "d1",
2515
+ "execute",
2516
+ database.binding,
2517
+ scope,
2518
+ "--file",
2519
+ seed.file
2520
+ ]);
2521
+ const resetKv = seed.resetKv ?? [];
2522
+ for (const entry of resetKv) await run([
2523
+ "kv",
2524
+ "key",
2525
+ "delete",
2526
+ entry.key,
2527
+ "--binding",
2528
+ entry.binding,
2529
+ scope
2530
+ ]);
2531
+ return {
2532
+ file: seed.file,
2533
+ binding: database.binding,
2534
+ resetKv,
2535
+ ...parseSeedStats(typeof executed === "string" ? executed : "")
2536
+ };
2537
+ };
2538
+ //#endregion
2539
+ //#region src/plugins/deploy/dev/build.ts
2540
+ /**
2541
+ * @file deploy plugin — dev site-rebuild resolution.
2542
+ *
2543
+ * Resolves HOW to rebuild the Moku web site on change: the in-process `webBuild` hook (preferred,
2544
+ * fast, typed — passed call-time from the consumer's script or set as a config default) → a
2545
+ * `buildCommand` shell string → an auto-detected `scripts/build.ts`. When nothing is configured,
2546
+ * dev serves the worker only and says so. Subprocesses inherit the parent env by default.
2547
+ * Node-only; never imported by the runtime Worker bundle.
2548
+ */
2549
+ /** Convention build script auto-detected when no webBuild/buildCommand is configured. */
2550
+ const AUTO_DETECT = "scripts/build.ts";
2551
+ /**
2552
+ * Opportunistically read a numeric `files` count off an arbitrary web build result. A real web
2553
+ * build returns its own summary shape (the worker framework cannot know it), so anything without a
2554
+ * numeric `files` field reports 0.
2555
+ *
2556
+ * @param result - The resolved value of a {@link WebBuild} hook (any shape).
2557
+ * @returns The `files` count when present and numeric, else 0.
2558
+ * @example
2559
+ * ```ts
2560
+ * fileCountOf({ files: 12 }); // 12
2561
+ * fileCountOf({ outDir: "dist", pageCount: 4 }); // 0
2562
+ * ```
2563
+ */
2564
+ const fileCountOf = (result) => {
2565
+ if (typeof result === "object" && result !== null && "files" in result) {
2566
+ const { files } = result;
2567
+ return typeof files === "number" ? files : 0;
2568
+ }
2569
+ return 0;
2570
+ };
2571
+ /**
2572
+ * Run a shell build command, resolving on a zero exit and rejecting otherwise.
2573
+ *
2574
+ * @param command - The shell command to run (the consumer's own configured build).
2575
+ * @returns Resolves once the command exits successfully.
2576
+ * @throws {Error} When the command fails to start or exits non-zero.
2577
+ * @example
2578
+ * ```ts
2579
+ * await runShellBuild("bun run scripts/build.ts");
2580
+ * ```
2581
+ */
2582
+ const runShellBuild = (command) => {
2583
+ return new Promise((resolve, reject) => {
2584
+ const child = spawn(command, {
2585
+ shell: true,
2586
+ stdio: "inherit"
2587
+ });
2588
+ child.on("error", (error) => {
2589
+ reject(/* @__PURE__ */ new Error(`[moku-worker] site build failed to start.\n ${error.message}`));
2590
+ });
2591
+ child.on("close", (code) => {
2592
+ if (code === 0) {
2593
+ resolve();
2594
+ return;
2595
+ }
2596
+ reject(/* @__PURE__ */ new Error(`[moku-worker] site build exited with code ${String(code)}.`));
2597
+ });
2598
+ });
2599
+ };
2600
+ /**
2601
+ * Rebuild the Moku web site using the resolved strategy: the call-time `webBuild` hook (the
2602
+ * script-driven path), else the `webBuild` config default, else the `buildCommand` shell string,
2603
+ * else an auto-detected `scripts/build.ts`. A hook's result is normalized to a `{ files }` count
2604
+ * (0 when the hook reports none, and for the shell path where it is unknown).
2605
+ *
2606
+ * @param ctx - The deploy plugin context (config + emit).
2607
+ * @param webBuild - Optional call-time web build hook (takes precedence over `ctx.config.webBuild`).
2608
+ * @returns The rebuilt file count (0 for the shell path / a countless hook).
2609
+ * @throws {Error} When the resolved shell build fails.
2610
+ * @example
2611
+ * ```ts
2612
+ * const { files } = await buildSite(ctx, () => web.cli.build());
2613
+ * ```
2614
+ */
2615
+ const buildSite = async (ctx, webBuild) => {
2616
+ const hook = webBuild ?? ctx.config.webBuild;
2617
+ if (hook !== void 0) return { files: fileCountOf(await hook()) };
2618
+ const command = ctx.config.buildCommand || (existsSync(AUTO_DETECT) ? `bun run ${AUTO_DETECT}` : "");
2619
+ if (command === "") {
2620
+ ctx.emit("dev:error", { message: "No site build configured (pass webBuild or set buildCommand); serving worker only." });
2621
+ return { files: 0 };
2622
+ }
2623
+ await runShellBuild(command);
2624
+ return { files: 0 };
2625
+ };
2626
+ //#endregion
2627
+ //#region src/plugins/deploy/dev/watch.ts
2628
+ /**
2629
+ * @file deploy plugin — debounced filesystem watcher for dev.
2630
+ *
2631
+ * Watches the top-level directories implied by the config globs (recursive) and fires a debounced
2632
+ * change callback with the SET of paths changed in the window (so a burst of edits coalesces into
2633
+ * one rebuild that knows every changed file). Uses node:fs.watch — no extra dependency.
2634
+ * Node-only; never imported by the runtime Worker bundle.
2635
+ */
2636
+ /**
2637
+ * Derive the set of top-level directories to watch from glob patterns.
2638
+ *
2639
+ * @param globs - Watch globs (e.g. ["src/**\/*.ts", "public/**\/*"]).
2640
+ * @returns The distinct top-level directories (e.g. ["src", "public"]).
2641
+ * @example
2642
+ * ```ts
2643
+ * watchDirectories(["src/**\/*.ts", "public/**\/*"]); // ["src", "public"]
2644
+ * ```
2645
+ */
2646
+ const watchDirectories = (globs) => {
2647
+ const directories = /* @__PURE__ */ new Set();
2648
+ for (const glob of globs) {
2649
+ const globStart = glob.search(/[*?[{]/u);
2650
+ const top = (globStart === -1 ? path.dirname(glob) : glob.slice(0, globStart)).split(/[/\\]/u).find((segment) => segment !== "") ?? ".";
2651
+ directories.add(top);
2652
+ }
2653
+ return [...directories];
2654
+ };
2655
+ /**
2656
+ * Watch the directories implied by `globs` and fire `onChange` (debounced by `debounceMs`) with the
2657
+ * distinct set of paths changed within the window. Missing directories are skipped silently.
2658
+ *
2659
+ * @param globs - Watch globs.
2660
+ * @param debounceMs - Coalesce rapid changes into one callback within this window.
2661
+ * @param onChange - Called with the changed paths (snapshot of the window) after the debounce settles.
2662
+ * @returns A handle whose close() stops all watchers and cancels any pending callback.
2663
+ * @example
2664
+ * ```ts
2665
+ * const handle = watchPaths(["src/**\/*.ts"], 120, paths => rebuild(paths));
2666
+ * handle.close();
2667
+ * ```
2668
+ */
2669
+ const watchPaths = (globs, debounceMs, onChange) => {
2670
+ let timer;
2671
+ const changed = /* @__PURE__ */ new Set();
2672
+ const fire = (changedPath) => {
2673
+ changed.add(changedPath);
2674
+ if (timer !== void 0) clearTimeout(timer);
2675
+ timer = setTimeout(() => {
2676
+ const batch = [...changed];
2677
+ changed.clear();
2678
+ onChange(batch);
2679
+ }, debounceMs);
2680
+ };
2681
+ const watchers = [];
2682
+ for (const directory of watchDirectories(globs)) {
2683
+ if (!existsSync(directory)) continue;
2684
+ watchers.push(watch(directory, { recursive: true }, (_event, filename) => {
2685
+ if (filename !== null) fire(path.join(directory, filename.toString()));
2686
+ }));
2687
+ }
2688
+ return { close: () => {
2689
+ if (timer !== void 0) clearTimeout(timer);
2690
+ for (const watcher of watchers) watcher.close();
2691
+ } };
2692
+ };
2693
+ //#endregion
2694
+ //#region src/plugins/deploy/dev/runner.ts
2695
+ /**
2696
+ * @file deploy plugin — dev watch/recompile orchestrator.
2697
+ *
2698
+ * One long-lived session: cold-build the Moku site, optionally apply local D1 migrations, spawn
2699
+ * `wrangler dev --live-reload` ONCE, then watch the site sources and rebuild on change (wrangler's
2700
+ * asset server live-reloads the browser). Build failures keep the session serving the last good
2701
+ * build. Tears down cleanly on SIGINT. Side-effecting work is injected via DevDeps so the
2702
+ * orchestration is unit-testable without real processes, watchers, or signals.
2703
+ * Node-only; never imported by the runtime Worker bundle.
2704
+ */
2705
+ /** Grace period (ms) before escalating a hung `wrangler dev` shutdown from SIGINT to SIGKILL. */
2706
+ const STOP_GRACE_MS = 4e3;
2707
+ /**
2708
+ * Spawn the long-lived `wrangler dev` child (inherits the parent env; non-blocking).
2709
+ *
2710
+ * `whenExited` settles when the child exits OR fails to spawn — the `error` listener is essential:
2711
+ * a missing/unexecutable wrangler emits `error` (not `exit`), which is otherwise unhandled (crashes
2712
+ * the process) and would leave `whenExited` pending forever, hanging `stop()`. `stop()` shuts
2713
+ * wrangler down the way its own Ctrl+C does — a graceful SIGINT, then a SIGKILL escalation if it has
2714
+ * not exited within {@link STOP_GRACE_MS} — resolving only once it is gone; a spawn failure is
2715
+ * surfaced as a thrown branded error so the caller can render it. Without the wait, the
2716
+ * inherited-stdio child can keep the parent alive after the watcher closes ("stuck on stopping").
2717
+ *
2718
+ * @param args - The `wrangler dev …` arguments.
2719
+ * @returns A handle: `whenExited` (settles on exit/spawn-failure) and `stop()` (resolves once gone).
2720
+ * @example
2721
+ * ```ts
2722
+ * const child = spawnWranglerDev(["dev", "--port", "8787"]);
2723
+ * await Promise.race([untilSignal(), child.whenExited]);
2724
+ * await child.stop();
2725
+ * ```
2726
+ */
2727
+ const spawnWranglerDev = (args) => {
2728
+ const child = spawn("wrangler", args, { stdio: "inherit" });
2729
+ let spawnError;
2730
+ const whenExited = new Promise((resolve) => {
2731
+ child.once("exit", () => {
2732
+ resolve();
2733
+ });
2734
+ child.once("error", (error) => {
2735
+ spawnError = /* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${error.message}`);
2736
+ resolve();
2737
+ });
2738
+ });
2739
+ const stop = async () => {
2740
+ if (spawnError !== void 0) throw spawnError;
2741
+ if (child.exitCode !== null || child.signalCode !== null || child.pid === void 0) return;
2742
+ child.kill("SIGINT");
2743
+ const forceKill = setTimeout(() => child.kill("SIGKILL"), STOP_GRACE_MS);
2744
+ await whenExited;
2745
+ clearTimeout(forceKill);
2746
+ };
2747
+ return {
2748
+ stop,
2749
+ whenExited
2750
+ };
2751
+ };
2752
+ /**
2753
+ * Resolve when the user first interrupts the dev session (SIGINT).
2754
+ *
2755
+ * @returns A promise that settles on the first SIGINT.
2756
+ * @example
2757
+ * ```ts
2758
+ * await waitForSigint();
2759
+ * ```
2760
+ */
2761
+ const waitForSigint = () => {
2762
+ return new Promise((resolve) => {
2763
+ process.once("SIGINT", () => {
2764
+ resolve();
2765
+ });
2766
+ });
2767
+ };
2768
+ /**
2769
+ * Wall-clock timestamp in ms (extracted so realDevDeps holds only named references).
2770
+ *
2771
+ * @returns The current time in milliseconds.
2772
+ * @example
2773
+ * ```ts
2774
+ * const t = nowMs();
2775
+ * ```
2776
+ */
2777
+ const nowMs = () => Date.now();
2778
+ /**
2779
+ * Build the real (side-effecting) dev deps used by api.dev(). Subprocesses inherit the parent env.
2780
+ *
2781
+ * @returns The production DevDeps (real spawn / fs.watch / SIGINT / Date.now).
2782
+ * @example
2783
+ * ```ts
2784
+ * await runDev(ctx, opts, realDevDeps());
2785
+ * ```
2786
+ */
2787
+ const realDevDeps = () => ({
2788
+ build: buildSite,
2789
+ runWrangler,
2790
+ spawnDev: spawnWranglerDev,
2791
+ watch: watchPaths,
2792
+ untilSignal: waitForSigint,
2793
+ now: nowMs
2794
+ });
2795
+ /**
2796
+ * The d1 bindings to migrate locally — one per configured d1 instance that declares a migrations
2797
+ * directory (empty when no d1 plugin is present, or none declares migrations).
2798
+ *
2799
+ * @param ctx - The deploy plugin context.
2800
+ * @returns The d1 binding names with migrations (e.g. `["DB"]`).
2801
+ * @example
2802
+ * ```ts
2803
+ * const bindings = d1MigrationBindings(ctx); // ["DB"]
2804
+ * ```
2805
+ */
2806
+ const d1MigrationBindings = (ctx) => ctx.has("d1") ? ctx.require(d1Plugin).deployManifest().filter((manifest) => manifest.migrations !== void 0).map((manifest) => manifest.binding) : [];
2807
+ /**
2808
+ * One-line description of a changed-path batch for the `dev:phase rebuild` detail: the single path,
2809
+ * or the first path plus a `(+N more)` tail. Empty batches (defensive) read as "site".
2810
+ *
2811
+ * @param paths - The changed paths the watcher coalesced for this rebuild.
2812
+ * @returns The detail string for the rebuild phase event.
2813
+ * @example
2814
+ * ```ts
2815
+ * describeChanges(["src/a.ts", "src/b.css"]); // "src/a.ts (+1 more)"
2816
+ * ```
2817
+ */
2818
+ const describeChanges = (paths) => {
2819
+ const [first, ...rest] = paths;
2820
+ if (first === void 0) return "site";
2821
+ return rest.length === 0 ? first : `${first} (+${String(rest.length)} more)`;
2822
+ };
2823
+ /**
2824
+ * Rebuild the site once for a changed-path batch and announce the result. The FAST path is the
2825
+ * incremental `onChange(changedPaths)` hook (e.g. `web.cli.update`) when wired; otherwise it falls
2826
+ * back to a full `webBuild()` rebuild (via deps.build) — the prior behavior. A failed rebuild keeps
2827
+ * the session alive (it just emits dev:error and serves the last good build). Both paths share one
2828
+ * `dev:phase rebuild` → `dev:rebuilt`/`dev:error` envelope so the branded dev TUI is identical.
2829
+ *
2830
+ * @param ctx - The deploy plugin context.
2831
+ * @param deps - The injected dev deps.
2832
+ * @param changedPaths - The paths that triggered the rebuild (the watcher's debounced set).
2833
+ * @param hooks - The consumer rebuild hooks.
2834
+ * @param hooks.webBuild - Full rebuild (used when `onChange` is absent — the prior behavior).
2835
+ * @param hooks.onChange - Incremental rebuild for the changed set (the fast path when wired).
2836
+ * @returns Resolves once the rebuild attempt completes.
2837
+ * @example
2838
+ * ```ts
2839
+ * await rebuild(ctx, deps, ["src/app.tsx"], { onChange: c => web.cli.update(c) });
2840
+ * ```
2841
+ */
2842
+ const rebuild = async (ctx, deps, changedPaths, hooks) => {
2843
+ ctx.emit("dev:phase", {
2844
+ phase: "rebuild",
2845
+ detail: describeChanges(changedPaths)
2846
+ });
2847
+ const started = deps.now();
2848
+ try {
2849
+ let files;
2850
+ if (hooks.onChange) files = fileCountOf(await hooks.onChange(changedPaths));
2851
+ else files = (await deps.build(ctx, hooks.webBuild)).files;
2852
+ ctx.emit("dev:rebuilt", {
2853
+ files,
2854
+ ms: deps.now() - started
2855
+ });
2856
+ } catch (error) {
2857
+ ctx.emit("dev:error", { message: error instanceof Error ? error.message : String(error) });
2858
+ }
2859
+ };
2860
+ /**
2861
+ * Load the configured seed into the LOCAL D1 for a `dev --seed` session: execute the SQL file, then
2862
+ * clear the configured cached KV keys so the app rebuilds them from the freshly-seeded rows. The
2863
+ * schema already exists (the migrate step above runs first), so this never migrates — the local
2864
+ * analogue of the deploy's remote seed, over the same `pluginConfigs.deploy.seed` config.
2865
+ *
2866
+ * @param ctx - The deploy plugin context.
2867
+ * @param deps - The injected dev deps (for the wrangler runner).
2868
+ * @returns Resolves once the seed file has executed and every cached KV key is cleared.
2869
+ * @throws {Error} When `--seed` is set but no seed is configured under `pluginConfigs.deploy.seed`.
2870
+ * @example
2871
+ * ```ts
2872
+ * await seedLocal(ctx, realDevDeps());
2873
+ * ```
2874
+ */
2875
+ const seedLocal = async (ctx, deps) => {
2876
+ const config = ctx.config.seed;
2877
+ if (config === void 0) throw new Error("[moku-worker] dev({ seed: true }) but no seed is configured — set pluginConfigs.deploy.seed.");
2878
+ ctx.emit("dev:phase", {
2879
+ phase: "seed",
2880
+ detail: config.file
2881
+ });
2882
+ const outcome = await runConfiguredSeed(ctx, deps.runWrangler, config, "--local");
2883
+ renderSeedSummary(createBrandConsole(), outcome, "local");
2884
+ };
2885
+ /**
2886
+ * Run a long-lived dev session: cold build → (local d1 migrate) → (local seed) → spawn `wrangler
2887
+ * dev` → watch + rebuild on change → teardown on signal.
2888
+ *
2889
+ * @param ctx - The deploy plugin context (config + emit + require/has).
2890
+ * @param opts - Optional options.
2891
+ * @param opts.port - Local dev port (default 8787).
2892
+ * @param opts.webBuild - Cold-build hook (also the per-change rebuild when `onChange` is omitted).
2893
+ * @param opts.onChange - Incremental per-change rebuild hook (e.g. `c => web.cli.update(c)`); when
2894
+ * set, each debounced change rebuilds only the changed paths instead of a full `webBuild()`.
2895
+ * @param opts.seed - Load the configured seed into the LOCAL D1 (+ reset its KV keys) before serving.
2896
+ * @param deps - Injected side effects (real ones from realDevDeps in production).
2897
+ * @returns Resolves when the session ends (SIGINT).
2898
+ * @example
2899
+ * ```ts
2900
+ * await runDev(ctx, { port: 8787, seed: true, webBuild: () => web.cli.build() }, realDevDeps());
2901
+ * ```
2902
+ */
2903
+ const runDev = async (ctx, opts, deps) => {
2904
+ const port = opts?.port ?? 8787;
2905
+ const webBuild = opts?.webBuild;
2906
+ const onChange = opts?.onChange;
2907
+ const seed = opts?.seed === true;
2908
+ ctx.emit("dev:phase", {
2909
+ phase: "build",
2910
+ detail: "site"
2911
+ });
2912
+ await deps.build(ctx, webBuild);
2913
+ const migrationBindings = ctx.config.migrateLocal || seed ? d1MigrationBindings(ctx) : [];
2914
+ if (migrationBindings.length > 0) {
2915
+ ctx.emit("dev:phase", {
2916
+ phase: "migrate",
2917
+ detail: "d1 (local)"
2918
+ });
2919
+ const outcomes = [];
2920
+ for (const binding of migrationBindings) {
2921
+ const output = await deps.runWrangler([
2922
+ "d1",
2923
+ "migrations",
2924
+ "apply",
2925
+ binding,
2926
+ "--local"
2927
+ ]);
2928
+ outcomes.push({
2929
+ binding,
2930
+ ...parseMigrationsApplied(output)
2931
+ });
2932
+ }
2933
+ renderMigrateSummary(createBrandConsole(), outcomes, "local");
2934
+ }
2935
+ if (seed) await seedLocal(ctx, deps);
2936
+ ctx.emit("dev:phase", {
2937
+ phase: "serve",
2938
+ detail: `http://localhost:${String(port)}`
2939
+ });
2940
+ const child = deps.spawnDev([
2941
+ "dev",
2942
+ "--port",
2943
+ String(port),
2944
+ "--config",
2945
+ ctx.config.configFile,
2946
+ "--live-reload"
2947
+ ]);
2948
+ const watcher = deps.watch(ctx.config.watch, ctx.config.debounceMs, (changedPaths) => rebuild(ctx, deps, changedPaths, {
2949
+ webBuild,
2950
+ onChange
2951
+ }));
2952
+ await Promise.race([deps.untilSignal(), child.whenExited]);
2953
+ ctx.emit("dev:phase", { phase: "stopping" });
2954
+ watcher.close();
2955
+ await child.stop();
2956
+ };
2957
+ //#endregion
2958
+ //#region src/plugins/deploy/infra/plan.ts
2959
+ /**
2960
+ * Decide whether a single API-provisioned resource already exists in the account, recovering its id
2961
+ * (kv/d1) when it does. Durable Objects are NOT handled here — they ship with the Worker (`wrangler
2962
+ * deploy` + the auto-derived DO migration create the namespace), are never provisioned via the API,
2963
+ * and are partitioned into the plan's `ships` bucket by {@link planInfra} before this is ever called.
2964
+ *
2965
+ * @param resource - The declared (provisionable) resource descriptor.
2966
+ * @param existing - The indexed set of resources already in the account.
2967
+ * @returns Whether it exists, plus the captured id for kv/d1.
2968
+ * @example
2969
+ * ```ts
2970
+ * checkExisting({ kind: "kv", binding: "SESSIONS" }, existing); // { exists: true, id: "ns123" }
2971
+ * ```
2972
+ */
2973
+ const checkExisting = (resource, existing) => {
2974
+ switch (resource.kind) {
2975
+ case "kv": {
2976
+ const id = existing.kv.get(resource.name);
2977
+ return id === void 0 ? { exists: false } : {
2978
+ exists: true,
2979
+ id
2980
+ };
2981
+ }
2982
+ case "d1": {
2983
+ const id = existing.d1.get(resource.name);
2984
+ return id === void 0 ? { exists: false } : {
2985
+ exists: true,
2986
+ id
2987
+ };
2988
+ }
2989
+ case "r2": return { exists: existing.r2.has(resource.name) };
2990
+ case "queue": return { exists: existing.queue.has(resource.name) };
2991
+ }
2992
+ };
2993
+ /**
2994
+ * Run the read-only infra preflight: resolve the account, list existing resources, diff against
2995
+ * the manifest, emit `provision:plan`, and return the plan. Writes nothing.
2996
+ *
2997
+ * @param ctx - The deploy plugin context (env + emit).
2998
+ * @param manifest - The assembled (or caller-supplied) deploy manifest.
2999
+ * @returns The infra plan: existing (with ids) vs missing vs ships-with-Worker (Durable Objects).
3000
+ * @throws {Error} When the token is absent/invalid or a Cloudflare listing fails.
3001
+ * @example
3002
+ * ```ts
3003
+ * const plan = await planInfra(ctx, manifest);
3004
+ * ```
3005
+ */
3006
+ const planInfra = async (ctx, manifest) => {
3007
+ const token = ctx.env.require("CLOUDFLARE_API_TOKEN");
3008
+ const pinnedAccountId = ctx.env.get("CLOUDFLARE_ACCOUNT_ID");
3009
+ const account = pinnedAccountId ? {
3010
+ id: pinnedAccountId,
3011
+ name: pinnedAccountId
3012
+ } : await resolveAccount(token);
3013
+ const kinds = /* @__PURE__ */ new Set();
3014
+ for (const resource of manifest.resources) if (resource.kind !== "do") kinds.add(resource.kind);
3015
+ const existing = await listExisting(token, account.id, kinds);
3016
+ const exists = [];
3017
+ const missing = [];
3018
+ const ships = [];
3019
+ for (const resource of manifest.resources) {
3020
+ if (resource.kind === "do") {
3021
+ ships.push(resource);
3022
+ continue;
3023
+ }
3024
+ const check = checkExisting(resource, existing);
3025
+ if (check.exists) exists.push(check.id === void 0 ? { resource } : {
3026
+ resource,
3027
+ id: check.id
3028
+ });
3029
+ else missing.push(resource);
3030
+ }
3031
+ ctx.emit("provision:plan", {
3032
+ exists: exists.length,
3033
+ missing: missing.length,
3034
+ ships: ships.length,
3035
+ account: account.name
3036
+ });
3037
+ return {
3038
+ account: account.name,
3039
+ accountId: account.id,
3040
+ exists,
3041
+ missing,
3042
+ ships
3043
+ };
3044
+ };
3045
+ //#endregion
3046
+ //#region src/plugins/deploy/naming.ts
3047
+ /**
3048
+ * @file deploy plugin — stage-aware resource naming.
3049
+ *
3050
+ * One source of truth for turning a base Cloudflare resource name into its stage variant, so the
3051
+ * worker name, the provisioners, the infra existence diff, and the generated wrangler config all
3052
+ * agree. Production keeps the base name; every other stage gets a `-${stage}` suffix. Node-only;
3053
+ * never imported by the runtime Worker bundle.
3054
+ */
3055
+ /**
3056
+ * Apply the deploy stage to a base Cloudflare resource name: the base name in `production`, else
3057
+ * `${base}-${stage}` (e.g. dev → `tracker-db-dev`). Env bindings + DO class names never get the
3058
+ * suffix — only provisioned resource names (and the worker name) are stage-qualified.
3059
+ *
3060
+ * @param base - The base resource name (e.g. "tracker-db").
3061
+ * @param stage - The deploy stage (e.g. "production", "development", "dev").
3062
+ * @returns The stage-qualified name.
3063
+ * @example
3064
+ * ```ts
3065
+ * stageName("tracker-db", "production"); // "tracker-db"
3066
+ * stageName("tracker-db", "dev"); // "tracker-db-dev"
3067
+ * ```
3068
+ */
3069
+ const stageName = (base, stage) => stage === "production" ? base : `${base}-${stage}`;
3070
+ //#endregion
3071
+ //#region src/plugins/deploy/providers/d1.ts
3072
+ /**
3073
+ * @file deploy plugin — D1 provisioning adapter.
3074
+ *
3075
+ * Creates a Cloudflare D1 database via `wrangler d1 create <binding>`, captures the created
3076
+ * database id from wrangler's output (so writeWranglerConfig can write a real `database_id`
3077
+ * instead of an empty placeholder), and applies migrations when declared.
3078
+ * Node-only; never imported by the runtime Worker bundle.
3079
+ */
3080
+ /**
3081
+ * Parse the created D1 database id from `wrangler d1 create` output.
3082
+ * Wrangler prints the new binding as JSON (`"database_id": "..."`) or TOML
3083
+ * (`database_id = "..."`); the leading boundary keeps the match anchored to the field name.
3084
+ *
3085
+ * @param output - Raw stdout from the wrangler create command.
3086
+ * @returns The database id, or undefined when none is found.
3087
+ * @example
3088
+ * ```ts
3089
+ * parseD1DatabaseId('{ "database_id": "uuid-1234" }'); // "uuid-1234"
3090
+ * ```
3091
+ */
3092
+ const parseD1DatabaseId = (output) => {
3093
+ return /(?:^|[\s,{])"?database_id"?\s*[:=]\s*"([^"]+)"/m.exec(output)?.[1];
3094
+ };
3095
+ /**
3096
+ * Provision a D1 database via `wrangler d1 create`, capture its id, and apply migrations.
3097
+ *
3098
+ * @param manifest - The D1 resource descriptor.
3099
+ * @param _ci - Whether running non-interactively.
3100
+ * @returns The captured database id when wrangler reported one, else an empty outcome.
3101
+ * @example
3102
+ * ```ts
3103
+ * const { id } = await provisionD1({ kind: "d1", binding: "DB", migrations: "./migrations" }, false);
3104
+ * ```
3105
+ */
3106
+ const provisionD1 = async (manifest, _ci) => {
3107
+ const id = parseD1DatabaseId(await runWrangler([
3108
+ "d1",
3109
+ "create",
3110
+ manifest.name
3111
+ ]));
3112
+ if (manifest.migrations) await runWrangler([
3113
+ "d1",
3114
+ "migrations",
3115
+ "apply",
3116
+ manifest.name,
3117
+ "--local"
3118
+ ]);
3119
+ return id ? { id } : {};
3120
+ };
3121
+ //#endregion
3122
+ //#region src/plugins/deploy/providers/do.ts
3123
+ /**
3124
+ * Provision Durable Object bindings. DOs are config-driven (no `wrangler do create` command
3125
+ * exists) — the actual binding entries are written by writeWranglerConfig. This function is
3126
+ * a resolved no-op for the dispatch step.
3127
+ *
3128
+ * @param _manifest - The Durable Objects resource descriptor.
3129
+ * @param _ci - Whether running non-interactively.
3130
+ * @returns Resolves immediately (DOs are config-only provisioning).
3131
+ * @example
3132
+ * ```ts
3133
+ * await provisionDurableObject({ kind: "do", bindings: { counter: "COUNTER" } }, false);
3134
+ * ```
3135
+ */
3136
+ const provisionDurableObject = async (_manifest, _ci) => {};
3137
+ //#endregion
3138
+ //#region src/plugins/deploy/providers/kv.ts
3139
+ /**
3140
+ * @file deploy plugin — KV provisioning adapter.
3141
+ *
3142
+ * Creates a Cloudflare KV namespace via `wrangler kv namespace create <binding>` and captures
3143
+ * the created namespace id from wrangler's output, so writeWranglerConfig can write a real `id`
3144
+ * (not an empty placeholder) into the generated wrangler config — otherwise the binding resolves
3145
+ * to nothing at runtime. Node-only; never imported by the runtime Worker bundle.
3146
+ */
3147
+ /**
3148
+ * Parse the created KV namespace id from `wrangler kv namespace create` output.
3149
+ * Wrangler prints the new binding as JSON (`"id": "..."`) or TOML (`id = "..."`); the leading
3150
+ * boundary (start / whitespace / `{` / `,`) keeps the match off a longer identifier such as
3151
+ * `kv_namespace_id`.
3152
+ *
3153
+ * @param output - Raw stdout from the wrangler create command.
3154
+ * @returns The namespace id, or undefined when none is found.
3155
+ * @example
3156
+ * ```ts
3157
+ * parseKvNamespaceId('{ "id": "abc123" }'); // "abc123"
3158
+ * ```
3159
+ */
3160
+ const parseKvNamespaceId = (output) => {
3161
+ return /(?:^|[\s,{])"?id"?\s*[:=]\s*"([^"]+)"/m.exec(output)?.[1];
3162
+ };
3163
+ /**
3164
+ * Provision a KV namespace via `wrangler kv namespace create` and capture its id.
3165
+ *
3166
+ * @param manifest - The KV resource descriptor.
3167
+ * @param _ci - Whether running non-interactively (passed through; wrangler respects env vars).
3168
+ * @returns The captured namespace id when wrangler reported one, else an empty outcome.
3169
+ * @example
3170
+ * ```ts
3171
+ * const { id } = await provisionKv({ kind: "kv", binding: "CACHE" }, false);
3172
+ * ```
3173
+ */
3174
+ const provisionKv = async (manifest, _ci) => {
3175
+ const id = parseKvNamespaceId(await runWrangler([
3176
+ "kv",
3177
+ "namespace",
3178
+ "create",
3179
+ manifest.name
3180
+ ]));
3181
+ return id ? { id } : {};
3182
+ };
3183
+ //#endregion
3184
+ //#region src/plugins/deploy/providers/queues.ts
3185
+ /**
3186
+ * @file deploy plugin — Queues provisioning adapter.
3187
+ *
3188
+ * Creates one Cloudflare Queue via `wrangler queues create <name>` per queue instance.
3189
+ * Node-only; never imported by the runtime Worker bundle.
3190
+ */
3191
+ /**
3192
+ * Provision the queue via `wrangler queues create <name>`.
3193
+ *
3194
+ * @param manifest - The queue resource descriptor.
3195
+ * @param _ci - Whether running non-interactively.
3196
+ * @returns Resolves once the queue is created.
3197
+ * @example
3198
+ * ```ts
3199
+ * await provisionQueue({ kind: "queue", name: "tracker-activity", binding: "ACTIVITY" }, false);
3200
+ * ```
3201
+ */
3202
+ const provisionQueue = async (manifest, _ci) => {
3203
+ await runWrangler([
3204
+ "queues",
3205
+ "create",
3206
+ manifest.name
3207
+ ]);
3208
+ };
3209
+ //#endregion
3210
+ //#region src/plugins/deploy/providers/r2.ts
3211
+ /**
3212
+ * @file deploy plugin — R2 provisioning + asset upload adapter.
3213
+ *
3214
+ * Provides two exports:
3215
+ * - `provisionR2`: creates an R2 bucket via `wrangler r2 bucket create`.
3216
+ * - `uploadDirToR2`: walks a directory recursively and uploads each file via
3217
+ * `wrangler r2 object put`, returning the uploaded file count.
3218
+ *
3219
+ * Node-only; never imported by the runtime Worker bundle.
3220
+ */
3221
+ /**
3222
+ * Provision an R2 bucket via `wrangler r2 bucket create`.
3223
+ *
3224
+ * @param manifest - The R2 resource descriptor.
3225
+ * @param _ci - Whether running non-interactively.
3226
+ * @returns Resolves once the bucket is created.
3227
+ * @example
3228
+ * ```ts
3229
+ * await provisionR2({ kind: "r2", name: "tracker-files", binding: "FILES" }, false);
3230
+ * ```
3231
+ */
3232
+ const provisionR2 = async (manifest, _ci) => {
3233
+ await runWrangler([
3234
+ "r2",
3235
+ "bucket",
3236
+ "create",
3237
+ manifest.name
3238
+ ]);
3239
+ };
3240
+ /**
3241
+ * Walk a directory recursively and return all file paths (absolute).
3242
+ *
3243
+ * @param directory - Directory path to walk.
3244
+ * @returns All file paths found under the directory.
3245
+ * @example
3246
+ * ```ts
3247
+ * const files = await walkDir("./public");
3248
+ * ```
3249
+ */
3250
+ const walkDir = async (directory) => {
3251
+ const entries = await readdir(directory);
3252
+ const results = [];
3253
+ for (const entry of entries) {
3254
+ const fullPath = path.join(directory, entry);
3255
+ if ((await stat(fullPath)).isDirectory()) {
3256
+ const nested = await walkDir(fullPath);
3257
+ results.push(...nested);
3258
+ } else results.push(fullPath);
3259
+ }
3260
+ return results;
3261
+ };
3262
+ /**
3263
+ * Upload a directory to an R2 bucket and return the uploaded file count.
3264
+ * Each file is uploaded via `wrangler r2 object put <bucket>/<key> --file <path>`.
3265
+ *
3266
+ * @param bucket - The R2 bucket binding name.
3267
+ * @param directory - The directory to upload.
3268
+ * @returns The number of files uploaded.
3269
+ * @example
3270
+ * ```ts
3271
+ * const count = await uploadDirToR2("ASSETS", "./public");
3272
+ * ```
3273
+ */
3274
+ const uploadDirToR2 = async (bucket, directory) => {
3275
+ const files = await walkDir(directory);
3276
+ for (const filePath of files) await runWrangler([
3277
+ "r2",
3278
+ "object",
3279
+ "put",
3280
+ `${bucket}/${path.relative(directory, filePath)}`,
3281
+ "--file",
3282
+ filePath
3283
+ ]);
3284
+ return files.length;
3285
+ };
3286
+ //#endregion
3287
+ //#region src/plugins/deploy/providers/index.ts
3288
+ /**
3289
+ * Dispatch a resource descriptor to the matching provider's provisioning routine.
3290
+ *
3291
+ * @param resource - The resource descriptor to provision.
3292
+ * @param ci - Whether running non-interactively.
3293
+ * @returns The provisioning outcome — `{ id }` for kv/d1, `{}` for r2/queue/do.
3294
+ * @example
3295
+ * ```ts
3296
+ * const { id } = await provisionResource({ kind: "kv", binding: "CACHE" }, false);
3297
+ * await provisionResource({ kind: "r2", bucket: "ASSETS" }, false); // {}
3298
+ * ```
3299
+ */
3300
+ const provisionResource = async (resource, ci) => {
3301
+ switch (resource.kind) {
3302
+ case "kv": return provisionKv(resource, ci);
3303
+ case "d1": return provisionD1(resource, ci);
3304
+ case "r2":
3305
+ await provisionR2(resource, ci);
3306
+ return {};
3307
+ case "queue":
3308
+ await provisionQueue(resource, ci);
3309
+ return {};
3310
+ case "do":
3311
+ await provisionDurableObject(resource, ci);
3312
+ return {};
3313
+ }
3314
+ };
3315
+ //#endregion
3316
+ //#region src/plugins/deploy/tty.ts
3317
+ /**
3318
+ * @file deploy plugin — TTY detection (isolated so the guided flow is testable).
3319
+ *
3320
+ * The guided deploy only prompts on an interactive terminal; in a pipe or CI it must never block
3321
+ * on stdin. Kept in its own module so tests can mock it without stubbing `process.stdout`.
3322
+ * Node-only; never imported by the runtime Worker bundle.
3323
+ */
3324
+ /**
3325
+ * Whether stdout is an interactive TTY (so prompts are safe to show).
3326
+ *
3327
+ * @returns True when stdout is a terminal.
3328
+ * @example
3329
+ * ```ts
3330
+ * if (stdoutIsTty()) await prompts.confirm("Deploy?");
3331
+ * ```
3332
+ */
3333
+ const stdoutIsTty = () => process.stdout.isTTY === true;
3334
+ //#endregion
3335
+ //#region src/plugins/deploy/wrangler-config.ts
3336
+ /**
3337
+ * @file deploy plugin — wrangler config generation + scaffold.
3338
+ *
3339
+ * Provides two exports:
3340
+ * - `writeWranglerConfig`: generates/updates a wrangler.jsonc file from an ExternalManifest.
3341
+ * Non-destructive: preserves existing top-level keys not managed by deploy.
3342
+ * - `scaffoldWranglerAndCi`: creates a minimal starter wrangler config when the file does not
3343
+ * exist yet; idempotent (leaves existing files untouched).
3344
+ *
3345
+ * Node-only; never imported by the runtime Worker bundle.
3346
+ */
3347
+ /**
3348
+ * Strip JSONC line- and block-comments, then JSON.parse the result.
3349
+ *
3350
+ * @param source - Raw JSONC file contents.
3351
+ * @returns The parsed object.
3352
+ * @example
3353
+ * ```ts
3354
+ * const cfg = parseJsonc('{ "name": "w" } // trailing comment');
3355
+ * ```
3356
+ */
3357
+ const parseJsonc = (source) => {
3358
+ const stripped = source.replaceAll(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/gu, "");
3359
+ return JSON.parse(stripped);
3360
+ };
3361
+ /**
3362
+ * Build the wrangler `kv_namespaces` array from the manifest's kv resources.
3363
+ *
3364
+ * @param resources - All resource descriptors from the manifest.
3365
+ * @param ids - Captured Cloudflare ids keyed by binding; the entry's `id` is filled from here.
3366
+ * @returns One wrangler KV namespace entry per kv resource — real `id` when known, omitted otherwise
3367
+ * (wrangler rejects an empty `id`, but a local-dev / freshly-generated config validates without one).
3368
+ * @example
3369
+ * ```ts
3370
+ * const kv = buildKvNamespaces([{ kind: "kv", binding: "CACHE" }], { CACHE: "ns123" });
3371
+ * ```
3372
+ */
3373
+ const buildKvNamespaces = (resources, ids) => resources.filter((resource) => resource.kind === "kv").map((resource) => {
3374
+ const id = ids[resource.binding];
3375
+ return id ? {
3376
+ binding: resource.binding,
3377
+ id
3378
+ } : { binding: resource.binding };
3379
+ });
3380
+ /**
3381
+ * Build the wrangler `r2_buckets` array from the manifest's r2 resources.
3382
+ *
3383
+ * @param resources - All resource descriptors from the manifest.
3384
+ * @returns One wrangler R2 bucket entry per r2 resource.
3385
+ * @example
3386
+ * ```ts
3387
+ * const r2 = buildR2Buckets([{ kind: "r2", name: "tracker-files", binding: "FILES" }]);
3388
+ * ```
3389
+ */
3390
+ const buildR2Buckets = (resources) => resources.filter((resource) => resource.kind === "r2").map((resource) => ({
3391
+ binding: resource.binding,
3392
+ bucket_name: resource.name
3393
+ }));
3394
+ /**
3395
+ * Build the wrangler `d1_databases` array from the manifest's d1 resources.
3396
+ *
3397
+ * @param resources - All resource descriptors from the manifest.
3398
+ * @param ids - Captured Cloudflare ids keyed by binding; the entry's `database_id` is filled from here.
3399
+ * @returns One wrangler D1 database entry per d1 resource (migrations_dir set when present).
3400
+ * @example
3401
+ * ```ts
3402
+ * const d1 = buildD1Databases([{ kind: "d1", name: "tracker-db", binding: "DB" }], { DB: "uuid-1234" });
3403
+ * ```
3404
+ */
3405
+ const buildD1Databases = (resources, ids) => resources.filter((resource) => resource.kind === "d1").map((resource) => {
3406
+ const databaseId = ids[resource.binding];
3407
+ const entry = {
3408
+ binding: resource.binding,
3409
+ database_name: resource.name
3410
+ };
3411
+ if (databaseId) entry.database_id = databaseId;
3412
+ if (resource.migrations) entry.migrations_dir = resource.migrations;
3413
+ return entry;
3414
+ });
3415
+ /**
3416
+ * Build the wrangler `queues` section (producers + consumers) from the manifest's queue resources.
3417
+ * Every queue is a `producer`; a queue flagged `consumer: true` (it declares an `onMessage` handler)
3418
+ * is ALSO registered as a `consumer` so wrangler delivers its messages to this Worker's queue()
3419
+ * handler — both locally under `wrangler dev` and in production. Without the consumer entry the
3420
+ * handler never runs (the bug that silently drops a queue-driven activity feed). A consumer that
3421
+ * sets `maxBatchTimeout` carries it through as wrangler's `max_batch_timeout` (lower delivery latency).
3422
+ *
3423
+ * @param resources - All resource descriptors from the manifest.
3424
+ * @returns The queues section (producers, plus consumers when any), or undefined when there are none.
3425
+ * @example
3426
+ * ```ts
3427
+ * const q = buildQueues([{ kind: "queue", name: "tracker-activity", binding: "ACTIVITY", consumer: true, maxBatchTimeout: 1 }]);
3428
+ * ```
3429
+ */
3430
+ const buildQueues = (resources) => {
3431
+ const queueResources = resources.filter((resource) => resource.kind === "queue");
3432
+ if (queueResources.length === 0) return void 0;
3433
+ const producers = queueResources.map((resource) => ({
3434
+ queue: resource.name,
3435
+ binding: resource.binding
3436
+ }));
3437
+ const consumers = queueResources.filter((resource) => resource.consumer === true).map((resource) => {
3438
+ const entry = { queue: resource.name };
3439
+ if (resource.maxBatchTimeout !== void 0) entry.max_batch_timeout = resource.maxBatchTimeout;
3440
+ return entry;
3441
+ });
3442
+ return consumers.length > 0 ? {
3443
+ producers,
3444
+ consumers
3445
+ } : { producers };
3446
+ };
3447
+ /**
3448
+ * Build the wrangler `durable_objects` bindings section from the manifest's do resources.
3449
+ *
3450
+ * @param resources - All resource descriptors from the manifest.
3451
+ * @returns The durable_objects section, or undefined when there are no do resources.
3452
+ * @example
3453
+ * ```ts
3454
+ * const dobj = buildDurableObjects([{ kind: "do", binding: "COUNTER", className: "Counter" }]);
3455
+ * ```
3456
+ */
3457
+ const buildDurableObjects = (resources) => {
3458
+ const doResources = resources.filter((resource) => resource.kind === "do");
3459
+ if (doResources.length === 0) return void 0;
3460
+ return { bindings: doResources.map((resource) => ({
3461
+ name: resource.binding,
3462
+ class_name: resource.className
3463
+ })) };
3464
+ };
3465
+ /**
3466
+ * Build the auto Durable Object `migrations` from the manifest's do classes. wrangler REQUIRES a
3467
+ * migration for every DO class, so this derives a single `v1` migration registering each class as
3468
+ * SQLite-backed (the modern default) — the exact section wrangler prompts for when it is missing.
3469
+ *
3470
+ * @param resources - All resource descriptors from the manifest.
3471
+ * @returns A single-entry migrations array, or undefined when there are no do resources.
3472
+ * @example
3473
+ * ```ts
3474
+ * buildMigrations([{ kind: "do", binding: "BOARD", className: "BoardChannel" }]);
3475
+ * // [{ tag: "v1", new_sqlite_classes: ["BoardChannel"] }]
3476
+ * ```
3477
+ */
3478
+ const buildMigrations = (resources) => {
3479
+ const classes = resources.filter((resource) => resource.kind === "do").map((resource) => resource.className);
3480
+ return classes.length > 0 ? [{
3481
+ tag: "v1",
3482
+ new_sqlite_classes: classes
3483
+ }] : void 0;
3484
+ };
3485
+ /**
3486
+ * Extract the already-captured Cloudflare ids (kv namespace `id`, d1 `database_id`) from an existing
3487
+ * parsed wrangler config, keyed by binding — so a regeneration (e.g. on `dev`) can preserve ids it
3488
+ * isn't handed. Tolerant of a malformed/hand-edited file (skips non-object / non-string entries).
3489
+ *
3490
+ * @param existing - The parsed existing wrangler config (or `{}`).
3491
+ * @returns A binding → id map (empty when the file has none).
3492
+ * @example
3493
+ * ```ts
3494
+ * extractExistingIds({ kv_namespaces: [{ binding: "CACHE", id: "ns1" }] }); // { CACHE: "ns1" }
3495
+ * ```
3496
+ */
3497
+ const extractExistingIds = (existing) => {
3498
+ const ids = {};
3499
+ const collect = (list, idKey) => {
3500
+ if (!Array.isArray(list)) return;
3501
+ for (const raw of list) {
3502
+ if (raw === null || typeof raw !== "object") continue;
3503
+ const entry = raw;
3504
+ const binding = entry.binding;
3505
+ const id = entry[idKey];
3506
+ if (typeof binding === "string" && typeof id === "string" && id.length > 0) ids[binding] = id;
3507
+ }
3508
+ };
3509
+ collect(existing.kv_namespaces, "id");
3510
+ collect(existing.d1_databases, "database_id");
3511
+ return ids;
3512
+ };
3513
+ /**
3514
+ * Build the extra top-level wrangler keys from the typed deploy config: `entry` → `main`,
3515
+ * `nodeCompat` → `compatibility_flags: ["nodejs_compat"]`, `assets` → the wrangler `assets` block
3516
+ * (SPA fallback when `spa`), then the raw `wrangler` passthrough last (the escape hatch wins / adds
3517
+ * anything else). Pass the result as the `extra` argument to {@link writeWranglerConfig}.
3518
+ *
3519
+ * @param config - The deploy plugin config.
3520
+ * @returns The merged extra wrangler keys.
3521
+ * @example
3522
+ * ```ts
3523
+ * await writeWranglerConfig(file, manifest, ids, wranglerExtra(ctx.config));
3524
+ * ```
3525
+ */
3526
+ const wranglerExtra = (config) => {
3527
+ const extra = {};
3528
+ if (config.entry !== void 0) extra.main = config.entry;
3529
+ if (config.nodeCompat === true) extra.compatibility_flags = ["nodejs_compat"];
3530
+ if (config.assets !== void 0) extra.assets = {
3531
+ directory: config.assets.directory,
3532
+ binding: config.assets.binding,
3533
+ ...config.assets.spa === true ? { not_found_handling: "single-page-application" } : {}
3534
+ };
3535
+ return {
3536
+ ...extra,
3537
+ ...config.wrangler
3538
+ };
3539
+ };
3540
+ /**
3541
+ * Generate/update the wrangler config file from a manifest (non-destructive merge).
3542
+ *
3543
+ * Layering (last wins): existing file keys → the `extra` passthrough (the app's `wrangler` config:
3544
+ * `main`, `compatibility_flags`, `assets`, `vars`, …) → the deploy-managed keys (name,
3545
+ * compatibility_date, kv_namespaces, r2_buckets, d1_databases, queues, durable_objects). So the
3546
+ * framework always owns the resource sections, the app supplies what the manifest can't derive, and
3547
+ * any other hand-written keys survive. Durable Object `migrations` are auto-derived for every DO
3548
+ * class (the section wrangler requires) UNLESS the file/passthrough already defines `migrations`.
3549
+ *
3550
+ * @param configFile - Path to the wrangler config file.
3551
+ * @param manifest - The assembled deploy manifest.
3552
+ * @param ids - Captured Cloudflare ids keyed by binding (kv namespace id, d1 database id). Defaults
3553
+ * to an empty map, in which case `id`/`database_id` are OMITTED (not "") so the generated config
3554
+ * still validates for local `dev` (wrangler rejects an empty id); a deploy fills the real ids.
3555
+ * @param extra - Extra top-level wrangler keys to merge in (the app's `deploy.wrangler` config).
3556
+ * @returns Resolves once the file is written.
3557
+ * @example
3558
+ * ```ts
3559
+ * await writeWranglerConfig("wrangler.jsonc", manifest, { CACHE: "ns123" }, {
3560
+ * main: "src/cloudflare/worker.ts",
3561
+ * compatibility_flags: ["nodejs_compat"],
3562
+ * assets: { directory: "dist/client", binding: "ASSETS" }
3563
+ * });
3564
+ * ```
3565
+ */
3566
+ const writeWranglerConfig = async (configFile, manifest, ids = {}, extra = {}) => {
3567
+ let existing = {};
3568
+ if (existsSync(configFile)) try {
3569
+ existing = parseJsonc(readFileSync(configFile, "utf8"));
3570
+ } catch {
3571
+ existing = {};
3572
+ }
3573
+ const effectiveIds = {
3574
+ ...extractExistingIds(existing),
3575
+ ...ids
3576
+ };
3577
+ const kvNamespaces = buildKvNamespaces(manifest.resources, effectiveIds);
3578
+ const r2Buckets = buildR2Buckets(manifest.resources);
3579
+ const d1Databases = buildD1Databases(manifest.resources, effectiveIds);
3580
+ const queues = buildQueues(manifest.resources);
3581
+ const durableObjects = buildDurableObjects(manifest.resources);
3582
+ const updated = {
3583
+ ...existing,
3584
+ ...extra,
3585
+ name: manifest.name,
3586
+ compatibility_date: manifest.compatibilityDate
3587
+ };
3588
+ if (kvNamespaces.length > 0) updated.kv_namespaces = kvNamespaces;
3589
+ if (r2Buckets.length > 0) updated.r2_buckets = r2Buckets;
3590
+ if (d1Databases.length > 0) updated.d1_databases = d1Databases;
3591
+ if (queues !== void 0) updated.queues = queues;
3592
+ if (durableObjects !== void 0) updated.durable_objects = durableObjects;
3593
+ const migrations = buildMigrations(manifest.resources);
3594
+ if (migrations !== void 0 && updated.migrations === void 0) updated.migrations = migrations;
3595
+ await writeFile(configFile, JSON.stringify(updated, void 0, 2));
3596
+ };
3597
+ /**
3598
+ * Scaffold a starting wrangler config and, when ci is set, CI workflow files.
3599
+ * Idempotent: an existing config file is left completely untouched.
3600
+ *
3601
+ * @param configFile - Path to the wrangler config file.
3602
+ * @param _ci - Whether to also scaffold CI workflow files.
3603
+ * @returns Resolves once scaffolding is written.
3604
+ * @example
3605
+ * ```ts
3606
+ * await scaffoldWranglerAndCi("wrangler.jsonc", true);
3607
+ * ```
3608
+ */
3609
+ const scaffoldWranglerAndCi = async (configFile, _ci) => {
3610
+ if (existsSync(configFile)) return;
3611
+ const starter = {
3612
+ name: "my-worker",
3613
+ main: "src/worker.ts",
3614
+ compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
3615
+ };
3616
+ await writeFile(configFile, JSON.stringify(starter, void 0, 2));
3617
+ };
3618
+ //#endregion
3619
+ //#region src/plugins/deploy/api.ts
3620
+ /**
3621
+ * @file deploy plugin — API factory (run, dev, init, checkInfra, provisionInfra).
3622
+ *
3623
+ * Pure ctx-taking factory. Assembles the deploy manifest from each resource plugin's own
3624
+ * deployManifest() api (never sibling pluginConfigs — design F6), runs an infra preflight
3625
+ * (check-before-create + capture real ids), generates/updates the wrangler config, uploads the
3626
+ * R2 upload dir, and runs wrangler deploy. Emits only global events: deploy:phase,
3627
+ * deploy:complete, provision:resource, provision:plan, provision:skip.
3628
+ *
3629
+ * Node-only: uses node:child_process (via runner.ts), node:fs (via wrangler-config.ts), and the
3630
+ * Cloudflare REST API (via infra/). Never called in the deployed Worker runtime.
3631
+ */
3632
+ /**
3633
+ * Assemble the deploy manifest from each present resource plugin's OWN deployManifest() api (each
3634
+ * returns one entry PER configured instance), gated by ctx.has(name) so absent plugins are skipped —
3635
+ * never sibling pluginConfigs (F6). The single place the deploy stage is baked into names: the worker
3636
+ * name and every provisioned resource `name` are run through {@link stageName} (bindings/DO class
3637
+ * names are never suffixed), so provisioning, the existence diff, and the generated config all agree.
3638
+ *
3639
+ * @param ctx - The deploy plugin context.
3640
+ * @param stage - The deploy stage (e.g. "production", "dev") applied to every resource name.
3641
+ * @returns The assembled manifest (stage-qualified name, compatibilityDate, per-instance resources).
3642
+ * @example
3643
+ * ```ts
3644
+ * const manifest = assembleManifest(ctx, "production");
3645
+ * ```
3646
+ */
3647
+ const assembleManifest = (ctx, stage) => {
3648
+ const resources = [
3649
+ ctx.has("storage") ? ctx.require(storagePlugin).deployManifest() : [],
3650
+ ctx.has("kv") ? ctx.require(kvPlugin).deployManifest() : [],
3651
+ ctx.has("d1") ? ctx.require(d1Plugin).deployManifest() : [],
3652
+ ctx.has("queues") ? ctx.require(queuesPlugin).deployManifest() : [],
3653
+ ctx.has("durableObjects") ? ctx.require(durableObjectsPlugin).deployManifest() : []
3654
+ ].flat();
3655
+ return {
3656
+ name: stageName(ctx.global.name, stage),
3657
+ compatibilityDate: ctx.global.compatibilityDate,
3658
+ resources: resources.map((resource) => "name" in resource ? {
3659
+ ...resource,
3660
+ name: stageName(resource.name, stage)
3661
+ } : resource)
3662
+ };
3663
+ };
3664
+ /**
3665
+ * Create the still-missing resources one at a time: provision each, fold its captured id (kv/d1) into
3666
+ * the shared `ids` map, and announce it via provision:resource. Resilient — a single failure is
3667
+ * CAPTURED (not thrown), so one bad resource never aborts the rest. Extracted from {@link applyPlan}
3668
+ * so that orchestrator stays flat (skip existing, skip DOs, create missing).
3669
+ *
3670
+ * @param ctx - The deploy plugin context.
3671
+ * @param missing - The resources the plan flagged as not-yet-existing.
3672
+ * @param ci - Whether provisioning runs non-interactively (forwarded to each provider).
3673
+ * @param ids - The binding → Cloudflare id map, mutated in place with each created kv/d1 id.
3674
+ * @returns The created refs and any captured per-resource failures.
3675
+ * @example
3676
+ * ```ts
3677
+ * const { created, failed } = await provisionMissing(ctx, plan.missing, false, ids);
3678
+ * ```
3679
+ */
3680
+ const provisionMissing = async (ctx, missing, ci, ids) => {
3681
+ const created = [];
3682
+ const failed = [];
3683
+ for (const resource of missing) try {
3684
+ const { id } = await provisionResource(resource, ci);
3685
+ if (id !== void 0 && (resource.kind === "kv" || resource.kind === "d1")) ids[resource.binding] = id;
3686
+ created.push(id === void 0 ? { resource } : {
3687
+ resource,
3688
+ id
3689
+ });
3690
+ ctx.emit("provision:resource", {
3691
+ kind: resource.kind,
3692
+ name: resourceName(resource)
3693
+ });
3694
+ } catch (error) {
3695
+ failed.push({
3696
+ resource,
3697
+ error: error instanceof Error ? error.message : String(error)
3698
+ });
3699
+ }
3700
+ return {
3701
+ created,
3702
+ failed
3703
+ };
3704
+ };
3705
+ /**
3706
+ * Act on an infra plan: skip the resources that already exist (reusing their ids), skip the Durable
3707
+ * Objects that ship with the Worker, create the missing ones (capturing each new id), and announce
3708
+ * each via provision:skip / :resource. Resilient — a single resource that fails to create is CAPTURED
3709
+ * in `failed` (not thrown), so one bad resource (e.g. an invalid bucket name) never aborts the whole
3710
+ * run and the caller can report a clear result.
3711
+ *
3712
+ * @param ctx - The deploy plugin context.
3713
+ * @param plan - The infra plan from planInfra (existing vs missing vs ships-with-Worker).
3714
+ * @param ci - Whether provisioning runs non-interactively (forwarded to each provider).
3715
+ * @returns The provisioning result: created, skipped, bundled, failed, and the merged binding → id map.
3716
+ * @example
3717
+ * ```ts
3718
+ * const { created, failed } = await applyPlan(ctx, plan, false);
3719
+ * ```
3720
+ */
3721
+ const applyPlan = async (ctx, plan, ci) => {
3722
+ const ids = {};
3723
+ for (const ref of plan.exists) {
3724
+ if (ref.id !== void 0 && (ref.resource.kind === "kv" || ref.resource.kind === "d1")) ids[ref.resource.binding] = ref.id;
3725
+ ctx.emit("provision:skip", {
3726
+ kind: ref.resource.kind,
3727
+ name: resourceName(ref.resource)
3728
+ });
3729
+ }
3730
+ for (const resource of plan.ships) ctx.emit("provision:skip", {
3731
+ kind: resource.kind,
3732
+ name: resourceName(resource)
3733
+ });
3734
+ const { created, failed } = await provisionMissing(ctx, plan.missing, ci, ids);
3735
+ return {
3736
+ created,
3737
+ skipped: plan.exists,
3738
+ bundled: plan.ships,
3739
+ failed,
3740
+ ids
3741
+ };
3742
+ };
3743
+ /**
3744
+ * Sentinel a guided helper resolves to when the user declined recovery — a clean abort the caller
3745
+ * turns into a `deploy:phase aborted` + early return, never a thrown (and re-rendered) error.
3746
+ */
3747
+ const ABORTED = Symbol("deploy:aborted");
3748
+ /** Retry guidance shown beneath each step's failure, before the "Retry?" prompt. */
3749
+ const HINTS = {
3750
+ build: "Web build failed — fix the error above, then retry.",
3751
+ provision: "Verify your token's account scopes and Cloudflare's status, then retry.",
3752
+ upload: "R2 upload failed — check the bucket and your token's R2 scope, then retry.",
3753
+ deploy: "wrangler deploy failed — review the output above, then retry."
3754
+ };
3755
+ /**
3756
+ * Emit the terminal `aborted` phase AND build the matching {@link DeployReport} — the single exit
3757
+ * every guided gate/retry funnels through when the user stops the deploy (or auth was never set up).
3758
+ * Centralizing it keeps every abort path emitting one consistent line and returning the same shaped
3759
+ * report: `status: "aborted"`, both post-steps `"skipped"`, no errors — so a calling script sees a
3760
+ * clean stop, never a half-filled success, and the remote-DB migration/seed are guaranteed unrun.
3761
+ *
3762
+ * @param ctx - The deploy plugin context.
3763
+ * @param stage - The resolved deploy stage (echoed into the report).
3764
+ * @param startedAt - The run's start timestamp, for the elapsed field.
3765
+ * @returns The aborted deploy report.
3766
+ * @example
3767
+ * ```ts
3768
+ * if (declined) return aborted(ctx, stage, startedAt);
3769
+ * ```
3770
+ */
3771
+ const aborted = (ctx, stage, startedAt) => {
3772
+ ctx.emit("deploy:phase", { phase: "aborted" });
3773
+ return {
3774
+ ok: false,
3775
+ status: "aborted",
3776
+ stage,
3777
+ migration: "skipped",
3778
+ seed: "skipped",
3779
+ elapsedMs: Date.now() - startedAt,
3780
+ errors: []
3781
+ };
3782
+ };
3783
+ /**
3784
+ * The full guided token setup shown after an auth failure on a TTY. Offers to walk the user through
3785
+ * it, and when accepted: prints WHERE to create the Cloudflare token (dashboard URL, which template,
3786
+ * the exact permissions to add) AND scaffolds a ready-to-fill `.env.local` — the same guidance baked
3787
+ * in as comments — for the user to paste the token + account id into (never clobbering an existing
3788
+ * file). Always ends pointing at the re-run.
3789
+ *
3790
+ * @param ctx - The deploy plugin context.
3791
+ * @param ui - The branded console to render the guidance through.
3792
+ * @param confirm - The yes/no prompt.
3793
+ * @returns Resolves once the guidance (and optional `.env.local` scaffold) has been rendered.
3794
+ * @example
3795
+ * ```ts
3796
+ * await guidedTokenSetup(ctx, createBrandConsole(), confirm);
3797
+ * ```
3798
+ */
3799
+ const guidedTokenSetup = async (ctx, ui, confirm) => {
3800
+ if (!await confirm("Set up Cloudflare credentials now? (guided)")) {
3801
+ ui.info("Set CLOUDFLARE_API_TOKEN in .env.local, then run `deploy` again.");
3802
+ return;
3803
+ }
3804
+ const manifest = assembleManifest(ctx, ctx.global.stage);
3805
+ renderAuthSetup(ui, requiredToken(manifest));
3806
+ const { created, path } = await ensureEnvLocal(process.cwd(), envLocalScaffold(manifest));
3807
+ ui.info(created ? `Created ${path} — paste your token + account id there, then run \`deploy\` again.` : `${path} already exists — fill in CLOUDFLARE_API_TOKEN there, then run \`deploy\` again.`);
3808
+ };
3809
+ /**
3810
+ * Verify the `.env` token, turning a missing/invalid token into a guided recovery on a TTY: surface
3811
+ * WHY auth failed, then walk the user through {@link guidedTokenSetup} (where to create the token +
3812
+ * scaffold a `.env.local`). The env is snapshotted at app start, so a freshly-pasted token only
3813
+ * takes effect on a NEW run. In CI/pipes the branded error re-throws (fail-fast).
3814
+ *
3815
+ * @param ctx - The deploy plugin context.
3816
+ * @param deps - Interactivity + the confirm prompt.
3817
+ * @returns True when the token verified; false when the user must set it up and re-run.
3818
+ * @throws {Error} Re-throws the branded auth error in CI / non-interactive runs.
3819
+ * @example
3820
+ * ```ts
3821
+ * if (!(await guidedAuth(ctx, { interactive, confirm }))) return;
3822
+ * ```
3823
+ */
3824
+ const guidedAuth = async (ctx, deps) => {
3825
+ try {
3826
+ await verifyAuth(ctx);
3827
+ return true;
3828
+ } catch (error) {
3829
+ if (!deps.interactive) throw error;
3830
+ const ui = createBrandConsole();
3831
+ ui.error(error instanceof Error ? error.message : String(error));
3832
+ await guidedTokenSetup(ctx, ui, deps.confirm);
3833
+ return false;
3834
+ }
3835
+ };
3836
+ /**
3837
+ * Run one external pipeline step with interactive recovery: on failure, render the branded error +
3838
+ * an actionable hint, then offer to retry — looping until the step succeeds or the user declines.
3839
+ * A decline resolves to {@link ABORTED} (a clean abort the caller surfaces), so the error is shown
3840
+ * once, not re-rendered downstream. In CI/pipes the first failure re-throws (fail-fast). The step
3841
+ * MUST be safe to re-run (idempotent).
3842
+ *
3843
+ * @param step - The async step to run (e.g. the web build, the R2 upload, `wrangler deploy`).
3844
+ * @param hint - One-line guidance shown beneath the error before the retry prompt.
3845
+ * @param deps - Interactivity + the confirm prompt.
3846
+ * @returns The step's resolved value once it succeeds, or {@link ABORTED} when a retry is declined.
3847
+ * @throws {Error} Re-throws the step's error in CI / non-interactive runs.
3848
+ * @example
3849
+ * ```ts
3850
+ * const url = await guidedStep(() => runWrangler(args), "wrangler deploy failed …", deps);
3851
+ * if (url === ABORTED) return;
3852
+ * ```
3853
+ */
3854
+ const guidedStep = async (step, hint, deps) => {
3855
+ for (;;) try {
3856
+ return await step();
3857
+ } catch (error) {
3858
+ if (!deps.interactive) throw error;
3859
+ const ui = createBrandConsole();
3860
+ ui.error(error instanceof Error ? error.message : String(error));
3861
+ ui.info(hint);
3862
+ if (!await deps.confirm("Retry?")) return ABORTED;
3863
+ }
3864
+ };
3865
+ /**
3866
+ * Run the read-only infra preflight with interactive recovery: a network/scope failure fails fast in
3867
+ * CI, or (on a TTY) renders the error + hint and offers a retry. Resolves the plan, or {@link ABORTED}
3868
+ * when the user declines the retry.
3869
+ *
3870
+ * @param ctx - The deploy plugin context.
3871
+ * @param manifest - The assembled (or caller-supplied) deploy manifest.
3872
+ * @param deps - Interactivity + the confirm prompt.
3873
+ * @returns The infra plan, or {@link ABORTED} when a preflight retry is declined.
3874
+ * @throws {Error} Re-throws the preflight error in CI / non-interactive runs.
3875
+ * @example
3876
+ * ```ts
3877
+ * const plan = await guidedPlan(ctx, manifest, deps);
3878
+ * if (plan === ABORTED) return;
3879
+ * ```
3880
+ */
3881
+ const guidedPlan = async (ctx, manifest, deps) => {
3882
+ for (;;) try {
3883
+ return await planInfra(ctx, manifest);
3884
+ } catch (error) {
3885
+ if (!deps.interactive) throw error;
3886
+ const ui = createBrandConsole();
3887
+ ui.error(error instanceof Error ? error.message : String(error));
3888
+ ui.info(HINTS.provision);
3889
+ if (!await deps.confirm("Retry?")) return ABORTED;
3890
+ }
3891
+ };
3892
+ /**
3893
+ * Plan + provision the infra with branded panels and interactive recovery. Each attempt RE-PLANS
3894
+ * (a resource created by a prior attempt is seen as existing and skipped — retries stay idempotent),
3895
+ * renders the plan panel (what will be created vs already exists), confirms the create gate, creates
3896
+ * the resources, then renders the result panel (created / skipped / failed). When some resources
3897
+ * FAIL it offers to retry just those (interactive) or fails fast (CI). Resolves to {@link ABORTED}
3898
+ * when the user declines the gate or a retry.
3899
+ *
3900
+ * @param ctx - The deploy plugin context.
3901
+ * @param manifest - The assembled (or caller-supplied) deploy manifest.
3902
+ * @param ci - Whether provisioning runs non-interactively (forwarded to each provider).
3903
+ * @param deps - Interactivity + the confirm prompt.
3904
+ * @returns The provisioning result (all created/skipped), or {@link ABORTED} when the user declined.
3905
+ * @throws {Error} Re-throws a plan error, or throws on a provision failure, in CI / non-interactive runs.
3906
+ * @example
3907
+ * ```ts
3908
+ * const provisioned = await guidedProvision(ctx, manifest, ci, deps);
3909
+ * if (provisioned === ABORTED) return;
3910
+ * ```
3911
+ */
3912
+ const guidedProvision = async (ctx, manifest, ci, deps) => {
3913
+ for (;;) {
3914
+ const plan = await guidedPlan(ctx, manifest, deps);
3915
+ if (plan === ABORTED) return ABORTED;
3916
+ const ui = createBrandConsole();
3917
+ renderPlan(ui, plan);
3918
+ if (plan.missing.length > 0 && !await deps.confirm(`Create ${String(plan.missing.length)} missing resource(s) in "${plan.account}"?`)) return ABORTED;
3919
+ const result = await applyPlan(ctx, plan, ci);
3920
+ renderProvisionResult(ui, result);
3921
+ if (result.failed.length === 0) return result;
3922
+ if (!deps.interactive) throw new Error(`[moku-worker] ${String(result.failed.length)} resource(s) failed to provision.`);
3923
+ if (!await deps.confirm("Retry the failed resource(s)?")) return ABORTED;
3924
+ }
3925
+ };
3926
+ /**
3927
+ * Build the web site first (when a hook is wired in), so its assets exist before the R2 upload and
3928
+ * `wrangler deploy`. Emits the `build · web` phase, then runs the build with interactive retry.
3929
+ *
3930
+ * @param ctx - The deploy plugin context.
3931
+ * @param webBuild - The web build hook, or undefined when none is wired (then this is a no-op).
3932
+ * @param deps - Interactivity + the confirm prompt.
3933
+ * @returns True to continue the pipeline; false when the user declined a build retry (abort).
3934
+ * @example
3935
+ * ```ts
3936
+ * if (!(await guidedWebBuild(ctx, webBuild, deps))) return emitAborted(ctx);
3937
+ * ```
3938
+ */
3939
+ const guidedWebBuild = async (ctx, webBuild, deps) => {
3940
+ if (webBuild === void 0) return true;
3941
+ ctx.emit("deploy:phase", {
3942
+ phase: "build",
3943
+ detail: "web"
3944
+ });
3945
+ return await guidedStep(() => webBuild(), HINTS.build, deps) !== ABORTED;
3946
+ };
3947
+ /**
3948
+ * Upload the R2 directory when a bucket declares an upload source, with interactive retry. Emits the
3949
+ * `upload · N files` phase on success; a no-op (and emits nothing) when no bucket declares an upload.
3950
+ *
3951
+ * @param ctx - The deploy plugin context.
3952
+ * @param manifest - The assembled (or caller-supplied) deploy manifest.
3953
+ * @param deps - Interactivity + the confirm prompt.
3954
+ * @returns True to continue the pipeline; false when the user declined an upload retry (abort).
3955
+ * @example
3956
+ * ```ts
3957
+ * if (!(await guidedUpload(ctx, manifest, deps))) return emitAborted(ctx);
3958
+ * ```
3959
+ */
3960
+ const guidedUpload = async (ctx, manifest, deps) => {
3961
+ const r2 = manifest.resources.find((resource) => resource.kind === "r2");
3962
+ if (!r2?.upload) return true;
3963
+ const bucket = r2.name;
3964
+ const uploadDir = r2.upload;
3965
+ const count = await guidedStep(() => uploadDirToR2(bucket, uploadDir), HINTS.upload, deps);
3966
+ if (count === ABORTED) return false;
3967
+ ctx.emit("deploy:phase", {
3968
+ phase: "upload",
3969
+ detail: `${String(count)} files`
3970
+ });
3971
+ return true;
3972
+ };
3973
+ /**
3974
+ * The final deploy step: confirm the target (guided only), run `wrangler deploy` with interactive
3975
+ * retry, then emit deploy:complete. Returns the deployed URL, or undefined when the target gate or a
3976
+ * deploy retry is declined (so the caller renders the summary panel only on a real success).
3977
+ *
3978
+ * @param ctx - The deploy plugin context.
3979
+ * @param manifest - The assembled (or caller-supplied) deploy manifest.
3980
+ * @param stage - The resolved deploy stage (for the confirm prompt).
3981
+ * @param deps - Interactivity + the confirm prompt.
3982
+ * @returns The deployed URL once live; undefined when the user declined the gate or a retry (abort).
3983
+ * @example
3984
+ * ```ts
3985
+ * const url = await guidedDeployStep(ctx, manifest, stage, deps);
3986
+ * if (url === undefined) return emitAborted(ctx);
3987
+ * ```
3988
+ */
3989
+ const guidedDeployStep = async (ctx, manifest, stage, deps) => {
3990
+ if (!await deps.confirm(`Deploy "${manifest.name}" to ${stage}?`)) return void 0;
3991
+ ctx.emit("deploy:phase", { phase: "deploy" });
3992
+ const url = await guidedStep(() => runWrangler([
3993
+ "deploy",
3994
+ "--config",
3995
+ ctx.config.configFile
3996
+ ]), HINTS.deploy, deps);
3997
+ if (url === ABORTED) return void 0;
3998
+ ctx.emit("deploy:complete", { url });
3999
+ return url;
4000
+ };
4001
+ /**
4002
+ * Apply pending D1 migrations to the REMOTE database for every configured d1 instance that ships a
4003
+ * migrations dir — the generic, deploy-owned analogue of `wrangler d1 migrations apply <binding>
4004
+ * --remote`. The wrangler config was written earlier in the pipeline, so each binding resolves. The
4005
+ * caller runs this only AFTER a successful deploy, so a deploy that never happened never migrates a
4006
+ * remote DB. CAPTURES wrangler's output (the raw TUI is hidden; {@link parseMigrationsApplied} turns
4007
+ * it into the branded panel's facts); throws on the first non-zero exit (the caller folds it into the
4008
+ * report, where the captured error is still surfaced).
4009
+ *
4010
+ * @param ctx - The deploy plugin context.
4011
+ * @returns The per-database migration outcomes (one per d1 instance that declares migrations).
4012
+ * @example
4013
+ * ```ts
4014
+ * const outcomes = await applyRemoteMigrations(ctx);
4015
+ * ```
4016
+ */
4017
+ const applyRemoteMigrations = async (ctx) => {
4018
+ if (!ctx.has("d1")) return [];
4019
+ const outcomes = [];
4020
+ for (const database of ctx.require(d1Plugin).deployManifest()) if (database.migrations !== void 0) {
4021
+ const output = await runWrangler([
4022
+ "d1",
4023
+ "migrations",
4024
+ "apply",
4025
+ database.binding,
4026
+ "--remote"
4027
+ ]);
4028
+ outcomes.push({
4029
+ binding: database.binding,
4030
+ ...parseMigrationsApplied(output)
4031
+ });
4032
+ }
4033
+ return outcomes;
4034
+ };
4035
+ /**
4036
+ * Render a post-deploy step's failure as a branded line and capture its message into `errors` —
4037
+ * folding the failure into the report instead of throwing, so a deploy that already went live still
4038
+ * yields a complete, honest report when a later remote step (migration/seed) fails.
4039
+ *
4040
+ * @param ui - The branded console to render the error through.
4041
+ * @param errors - The accumulator the captured message is pushed into.
4042
+ * @param error - The thrown error (or value) to brand and capture.
4043
+ * @returns The captured (branded) message.
4044
+ * @example
4045
+ * ```ts
4046
+ * captureFailure(ui, errors, new Error("[moku-worker] seed failed"));
4047
+ * ```
4048
+ */
4049
+ const captureFailure = (ui, errors, error) => {
4050
+ const message = error instanceof Error ? error.message : String(error);
4051
+ ui.error(message);
4052
+ errors.push(message);
4053
+ return message;
4054
+ };
4055
+ /**
4056
+ * Run the post-deploy remote steps — REACHED ONLY ON A SUCCESSFUL DEPLOY (every gate in `run` returns
4057
+ * early before here), so a deploy that never happened never touches a remote DB. Applies remote D1
4058
+ * migrations (when requested), then loads the configured seed (when requested) — but skips the seed
4059
+ * if the migration it depends on failed. Each step's failure is RENDERED inline and CAPTURED in
4060
+ * `errors` (never thrown), so one failed step still yields a complete, honest report.
4061
+ *
4062
+ * @param ctx - The deploy plugin context.
4063
+ * @param want - Which post-steps the caller requested.
4064
+ * @param want.migration - Whether to apply pending remote D1 migrations.
4065
+ * @param want.seed - Whether to load the configured remote seed (and reset its KV keys).
4066
+ * @returns The migration + seed outcomes and any captured branded errors.
4067
+ * @example
4068
+ * ```ts
4069
+ * const post = await runPostDeploy(ctx, { migration: true, seed: true });
4070
+ * ```
4071
+ */
4072
+ const runPostDeploy = async (ctx, want) => {
4073
+ const ui = createBrandConsole();
4074
+ const errors = [];
4075
+ let migration = "skipped";
4076
+ if (want.migration) try {
4077
+ ctx.emit("deploy:phase", {
4078
+ phase: "migrate",
4079
+ detail: "remote D1"
4080
+ });
4081
+ const outcomes = await applyRemoteMigrations(ctx);
4082
+ migration = "applied";
4083
+ if (outcomes.length > 0) renderMigrateSummary(ui, outcomes, "remote");
4084
+ } catch (error) {
4085
+ migration = "failed";
4086
+ captureFailure(ui, errors, error);
4087
+ }
4088
+ let seed = "skipped";
4089
+ if (want.seed && migration === "failed") {
4090
+ seed = "failed";
4091
+ captureFailure(ui, errors, /* @__PURE__ */ new Error("[moku-worker] seed skipped — the remote migration it depends on failed."));
4092
+ } else if (want.seed) {
4093
+ const config = ctx.config.seed;
4094
+ if (config === void 0) {
4095
+ seed = "failed";
4096
+ captureFailure(ui, errors, /* @__PURE__ */ new Error("[moku-worker] deploy({ seed: true }) but no seed is configured — set pluginConfigs.deploy.seed."));
4097
+ } else try {
4098
+ ctx.emit("deploy:phase", {
4099
+ phase: "seed",
4100
+ detail: config.file
4101
+ });
4102
+ const outcome = await runConfiguredSeed(ctx, runWrangler, config, "--remote");
4103
+ seed = "applied";
4104
+ renderSeedSummary(ui, outcome, "remote");
4105
+ } catch (error) {
4106
+ seed = "failed";
4107
+ captureFailure(ui, errors, error);
4108
+ }
4109
+ }
4110
+ return {
4111
+ migration,
4112
+ seed,
4113
+ errors
4114
+ };
4115
+ };
4116
+ /**
4117
+ * Create the deploy api. Assembles the manifest from each resource plugin's own deployManifest(),
4118
+ * runs an infra preflight (check-before-create + id capture), generates config, uploads, and runs
4119
+ * `wrangler deploy`, emitting global deploy events along the way.
4120
+ *
4121
+ * @param ctx - Plugin context (own config + require + has + emit + global + env).
4122
+ * @returns The app.deploy api: run / dev / init / checkInfra / provisionInfra.
4123
+ * @example
4124
+ * ```ts
4125
+ * const api = createDeployApi(ctx);
4126
+ * await api.run();
4127
+ * ```
4128
+ */
4129
+ const createDeployApi = (ctx) => ({
4130
+ /**
4131
+ * Run the full deploy pipeline: detect → preflight (check-before-create) → provision (only the
4132
+ * missing) → wrangler-config (with real ids) → upload → deploy, then — ONLY on a successful
4133
+ * deploy — the requested post-deploy remote steps (migration, seed). When opts.manifest is
4134
+ * supplied it is used verbatim (universal path).
4135
+ *
4136
+ * On a TTY the run is GUIDED end to end: each gate is confirmed, and every failure is recovered
4137
+ * interactively rather than thrown — a missing/invalid token offers a `.env.local` scaffold, and
4138
+ * the build, infra, upload, and `wrangler deploy` steps offer a retry. In CI/pipes it fails fast
4139
+ * (no prompt, the first error propagates to the branded CLI handler).
4140
+ *
4141
+ * Resolves to a {@link DeployReport}. Every abort path (a declined gate, or auth never set up)
4142
+ * returns `status: "aborted"` BEFORE the post-deploy steps, so `migration`/`seed` run only when
4143
+ * the worker actually went live — a first `deploy --seed` with no token aborts cleanly instead of
4144
+ * falling through to a raw `wrangler … --remote` auth error.
4145
+ *
4146
+ * @param opts - Optional run options.
4147
+ * @param opts.ci - CI/automated mode: never prompts, auto-confirms every gate, fails fast. When
4148
+ * false (the default) and stdout is a TTY, the deploy is guided — each gate is confirmed and
4149
+ * failures are recovered interactively. Falls back to ctx.config.ci when omitted.
4150
+ * @param opts.stage - Target stage; suffixes resource names (`production` = bare). Falls back to the app stage.
4151
+ * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
4152
+ * @param opts.manifest - Caller-supplied manifest (bypasses deployManifest() assembly).
4153
+ * @param opts.migration - After a successful deploy, apply pending remote D1 migrations for every
4154
+ * configured d1 instance that ships migrations. Skipped (not attempted) on an aborted deploy.
4155
+ * @param opts.seed - After a successful deploy (+ migration), load the seed configured under
4156
+ * `pluginConfigs.deploy.seed` into the remote D1 and reset its cached KV keys. Skipped on abort.
4157
+ * @returns The deploy report (status, url, resource tally, migration/seed outcome, errors).
4158
+ * @example
4159
+ * ```ts
4160
+ * const report = await api.run({ webBuild: () => web.cli.build(), migration: true, seed: true });
4161
+ * if (!report.ok) process.exitCode = 1; // aborted or a post-step failed
4162
+ * ```
4163
+ */
4164
+ async run(opts) {
4165
+ const ci = opts?.ci ?? ctx.config.ci;
4166
+ const stage = opts?.stage ?? ctx.global.stage;
4167
+ const interactive = !ci && stdoutIsTty();
4168
+ const deps = {
4169
+ interactive,
4170
+ confirm: interactive ? createBrandPrompts().confirm : async (_question) => true
4171
+ };
4172
+ const startedAt = Date.now();
4173
+ ctx.emit("deploy:phase", { phase: "auth" });
4174
+ if (!await guidedAuth(ctx, deps)) return aborted(ctx, stage, startedAt);
4175
+ if (!await guidedWebBuild(ctx, opts?.webBuild ?? ctx.config.webBuild, deps)) return aborted(ctx, stage, startedAt);
4176
+ ctx.emit("deploy:phase", { phase: "detect" });
4177
+ const manifest = opts?.manifest ?? assembleManifest(ctx, stage);
4178
+ ctx.emit("deploy:phase", { phase: "provision" });
4179
+ const provisioned = await guidedProvision(ctx, manifest, ci, deps);
4180
+ if (provisioned === ABORTED) return aborted(ctx, stage, startedAt);
4181
+ ctx.emit("deploy:phase", { phase: "wrangler-config" });
4182
+ await writeWranglerConfig(ctx.config.configFile, manifest, provisioned.ids, wranglerExtra(ctx.config));
4183
+ if (!await guidedUpload(ctx, manifest, deps)) return aborted(ctx, stage, startedAt);
4184
+ const url = await guidedDeployStep(ctx, manifest, stage, deps);
4185
+ if (url === void 0) return aborted(ctx, stage, startedAt);
4186
+ const resources = {
4187
+ created: provisioned.created.length,
4188
+ exists: provisioned.skipped.length,
4189
+ bundled: provisioned.bundled.length,
4190
+ failed: provisioned.failed.length
4191
+ };
4192
+ renderDeploySummary(createBrandConsole(), {
4193
+ url,
4194
+ stage,
4195
+ ...resources,
4196
+ elapsedMs: Date.now() - startedAt
4197
+ });
4198
+ const post = await runPostDeploy(ctx, {
4199
+ migration: opts?.migration === true,
4200
+ seed: opts?.seed === true
4201
+ });
4202
+ return {
4203
+ ok: post.errors.length === 0,
4204
+ status: post.errors.length === 0 ? "deployed" : "failed",
4205
+ stage,
4206
+ url,
4207
+ resources,
4208
+ migration: post.migration,
4209
+ seed: post.seed,
4210
+ elapsedMs: Date.now() - startedAt,
4211
+ errors: post.errors
4212
+ };
4213
+ },
4214
+ /**
4215
+ * Start a long-lived local dev session: cold-build the Moku site, spawn `wrangler dev
4216
+ * --live-reload`, and watch the site sources — rebuilding on change (wrangler live-reloads the
4217
+ * browser). Resolves on SIGINT.
4218
+ *
4219
+ * @param opts - Optional options.
4220
+ * @param opts.port - Local dev port (default 8787).
4221
+ * @param opts.stage - Stage for the generated config's resource names (defaults to the app stage).
4222
+ * @param opts.webBuild - Cold-build the web site (e.g. `() => webApp.cli.build()`); also the
4223
+ * per-change rebuild when `onChange` is omitted.
4224
+ * @param opts.onChange - Incremental per-change rebuild (e.g. `changes => webApp.cli.update(changes)`).
4225
+ * @param opts.seed - Load the configured seed (`pluginConfigs.deploy.seed`) into the LOCAL D1 and
4226
+ * reset its cached KV keys before serving — the local analogue of `deploy({ seed: true })`.
4227
+ * @returns Resolves when the dev session ends.
4228
+ * @example
4229
+ * ```ts
4230
+ * await api.dev({ port: 8787, seed: true, webBuild: () => web.cli.build(), onChange: c => web.cli.update(c) });
4231
+ * ```
4232
+ */
4233
+ async dev(opts) {
4234
+ const manifest = assembleManifest(ctx, opts?.stage ?? ctx.global.stage);
4235
+ await writeWranglerConfig(ctx.config.configFile, manifest, {}, wranglerExtra(ctx.config));
4236
+ await runDev(ctx, opts, realDevDeps());
4237
+ },
4238
+ /**
4239
+ * Execute a SQL file against a configured D1 database via `wrangler d1 execute` — for seeding dev
4240
+ * data. Local by default (applies that database's migrations first so the file's tables exist);
4241
+ * `opts.remote` seeds Cloudflare (schema is applied by `deploy`). Generates the wrangler config up
4242
+ * front so the binding resolves even on a first run. CAPTURES wrangler's output and renders a
4243
+ * branded "Migrated" / "Seeded" summary (the raw migration/execute TUI is hidden) so the command
4244
+ * reads the same as the rest of the deploy UX; a failure still surfaces the real wrangler error.
4245
+ *
4246
+ * @param sqlFile - Path to the SQL file to execute (e.g. "db/seed.sql").
4247
+ * @param opts - Optional options.
4248
+ * @param opts.stage - Stage for the generated config's resource names (defaults to the app stage).
4249
+ * @param opts.binding - The d1 binding to target when more than one is configured (e.g. "DB").
4250
+ * @param opts.remote - Seed the remote (Cloudflare) D1 instead of the local one.
4251
+ * @returns Resolves once wrangler finishes executing the file and the summary is rendered.
4252
+ * @example
4253
+ * ```ts
4254
+ * await api.seed("db/seed.sql"); // local default d1 (migrate, then execute)
4255
+ * await api.seed("db/seed.sql", { remote: true }); // remote d1
4256
+ * ```
4257
+ */
4258
+ async seed(sqlFile, opts) {
4259
+ if (!ctx.has("d1")) throw new Error("[moku-worker] seed: no d1 database is configured.");
4260
+ const stage = opts?.stage ?? ctx.global.stage;
4261
+ await writeWranglerConfig(ctx.config.configFile, assembleManifest(ctx, stage), {}, wranglerExtra(ctx.config));
4262
+ const target = resolveD1(ctx, opts?.binding);
4263
+ const scope = opts?.remote === true ? "--remote" : "--local";
4264
+ const where = opts?.remote === true ? "remote" : "local";
4265
+ const ui = createBrandConsole();
4266
+ if (scope === "--local" && target.migrations !== void 0) {
4267
+ const migrated = await runWrangler([
4268
+ "d1",
4269
+ "migrations",
4270
+ "apply",
4271
+ target.binding,
4272
+ "--local"
4273
+ ]);
4274
+ renderMigrateSummary(ui, [{
4275
+ binding: target.binding,
4276
+ ...parseMigrationsApplied(migrated)
4277
+ }], where);
4278
+ }
4279
+ const executed = await runWrangler([
4280
+ "d1",
4281
+ "execute",
4282
+ target.binding,
4283
+ scope,
4284
+ "--file",
4285
+ sqlFile
4286
+ ]);
4287
+ renderSeedSummary(ui, {
4288
+ file: sqlFile,
4289
+ binding: target.binding,
4290
+ resetKv: [],
4291
+ ...parseSeedStats(executed)
4292
+ }, where);
4293
+ },
4294
+ /**
4295
+ * Scaffold a starting wrangler config (and CI files when ci is set).
4296
+ * Idempotent: an existing config file is left untouched.
4297
+ *
4298
+ * @param opts - Optional options.
4299
+ * @param opts.ci - Also scaffold CI workflow files.
4300
+ * @returns Resolves once scaffolding is written.
4301
+ * @example
4302
+ * ```ts
4303
+ * await api.init({ ci: true });
4304
+ * ```
4305
+ */
4306
+ init: async (opts) => {
4307
+ await scaffoldWranglerAndCi(ctx.config.configFile, opts?.ci ?? ctx.config.ci);
4308
+ },
4309
+ /**
4310
+ * Read-only infra preflight: assemble the manifest, resolve the account, list what exists in
4311
+ * Cloudflare, diff, emit provision:plan, and return the plan. Writes nothing.
4312
+ *
4313
+ * @returns The infra plan (existing vs missing resources, with captured ids).
4314
+ * @example
4315
+ * ```ts
4316
+ * const plan = await api.checkInfra();
4317
+ * ```
4318
+ */
4319
+ checkInfra: () => planInfra(ctx, assembleManifest(ctx, ctx.global.stage)),
4320
+ /**
4321
+ * Create only the resources missing from the plan (skipping existing), capturing each id.
4322
+ *
4323
+ * @param plan - A plan produced by checkInfra().
4324
+ * @returns The provisioning result: created, skipped, and the merged id map.
4325
+ * @example
4326
+ * ```ts
4327
+ * const { created } = await api.provisionInfra(await api.checkInfra());
4328
+ * ```
4329
+ */
4330
+ provisionInfra: (plan) => applyPlan(ctx, plan, ctx.config.ci),
4331
+ /**
4332
+ * Verify the `.env` Cloudflare API token (must be active) and resolve its account; emits
4333
+ * auth:verified. Throws a branded error pointing at `auth setup` when absent/invalid/inactive.
4334
+ *
4335
+ * @returns The verified auth status (account + id).
4336
+ * @example
4337
+ * ```ts
4338
+ * const { account } = await api.verifyAuth();
4339
+ * ```
4340
+ */
4341
+ verifyAuth: () => verifyAuth(ctx),
4342
+ /**
4343
+ * Derive the minimum Cloudflare API token this app needs from its manifest (pure, no network).
4344
+ *
4345
+ * @returns The token requirement (full set + groups to add to the stock template).
4346
+ * @example
4347
+ * ```ts
4348
+ * const { toAdd } = api.requiredToken();
4349
+ * ```
4350
+ */
4351
+ requiredToken: () => requiredToken(assembleManifest(ctx, ctx.global.stage)),
4352
+ /**
4353
+ * Derive the REDUCED CI/automation redeploy token permission groups from the manifest (pure, no
4354
+ * network). Used by the branded `auth setup` renderer to show the scoped CI token alongside the
4355
+ * full LOCAL one.
4356
+ *
4357
+ * @returns The CI token permission groups (read-mostly, manifest-scoped).
4358
+ * @example
4359
+ * ```ts
4360
+ * const groups = api.ciToken();
4361
+ * ```
4362
+ */
4363
+ ciToken: () => ciToken(assembleManifest(ctx, ctx.global.stage)),
4364
+ /**
4365
+ * Render the `auth setup` guidance from the derived token requirement (pure, no network).
4366
+ *
4367
+ * @returns The rendered instruction text.
4368
+ * @example
4369
+ * ```ts
4370
+ * const text = api.tokenInstructions();
4371
+ * ```
4372
+ */
4373
+ tokenInstructions: () => tokenInstructions(assembleManifest(ctx, ctx.global.stage)),
4374
+ /**
4375
+ * Run an arbitrary wrangler command, streaming its output (the branded CLI escape hatch).
4376
+ *
4377
+ * @param args - The wrangler arguments.
4378
+ * @returns Resolves once wrangler exits.
4379
+ * @example
4380
+ * ```ts
4381
+ * await api.wrangler(["kv", "namespace", "list"]);
4382
+ * ```
4383
+ */
4384
+ wrangler: (args) => runWranglerInherit(args)
4385
+ });
4386
+ /**
4387
+ * Complex tier (node-only) — build-time deploy orchestrator over the five resource plugins.
4388
+ *
4389
+ * Assembles each resource plugin's deployManifest() via ctx.require, provisions resources,
4390
+ * generates/updates wrangler config, uploads the R2 upload dir, and runs wrangler deploy.
4391
+ * Also supports a universal path: run({ manifest }) uses a caller-supplied manifest verbatim.
4392
+ *
4393
+ * Emits only the global events `deploy:phase`, `deploy:complete`, and `provision:resource`
4394
+ * (declared in WorkerEvents — no per-plugin events block).
4395
+ *
4396
+ * @see README.md
4397
+ */
4398
+ const deployPlugin = createPlugin$1("deploy", {
4399
+ config: {
4400
+ configFile: "wrangler.jsonc",
4401
+ ci: false,
4402
+ watch: ["src/**/*.{ts,tsx,css}", "public/**/*"],
4403
+ buildCommand: "",
4404
+ migrateLocal: true,
4405
+ debounceMs: 120
4406
+ },
4407
+ depends: [
4408
+ storagePlugin,
4409
+ kvPlugin,
4410
+ d1Plugin,
4411
+ queuesPlugin,
4412
+ durableObjectsPlugin
4413
+ ],
4414
+ api: (ctx) => createDeployApi(ctx)
4415
+ });
4416
+ //#endregion
4417
+ //#region src/plugins/cli/args.ts
4418
+ /**
4419
+ * @file cli plugin — argv parsing helpers (isolated so they unit-test without a real process).
4420
+ *
4421
+ * `deploy`/`dev` resolve the target stage from the command line (`--stage dev`) so a consumer never
4422
+ * hardcodes it. The dev PORT is not parsed here — it comes only from the `dev()` argument (no hidden
4423
+ * argv/config resolution). Pure: takes an argv array, reads no globals. Node-only tooling.
4424
+ */
4425
+ /**
4426
+ * Extract a `--stage` value from a single token (and the token after it, for the spaced form).
4427
+ *
4428
+ * @param token - The current argv token.
4429
+ * @param next - The following argv token (the value, for the `--stage dev` spaced form).
4430
+ * @returns The raw string value when this token is a stage flag, else undefined.
4431
+ * @example
4432
+ * ```ts
4433
+ * stageValueFrom("--stage=dev", undefined); // "dev"
4434
+ * stageValueFrom("--stage", "dev"); // "dev"
4435
+ * stageValueFrom("--other", "x"); // undefined
4436
+ * ```
4437
+ */
4438
+ const stageValueFrom = (token, next) => {
4439
+ const inline = /^--stage=(.+)$/u.exec(token);
4440
+ if (inline) return inline[1];
4441
+ if (token === "--stage") return next;
4442
+ };
4443
+ /**
4444
+ * Parse a `--stage <name>` / `--stage=<name>` flag out of an argv array — the deploy/dev stage that
4445
+ * drives the resource-name suffix (e.g. `tracker-db-dev`). Returns the first non-empty value, or
4446
+ * undefined so the caller can fall back to the app's configured stage.
4447
+ *
4448
+ * @param argv - The argv array to scan (the caller passes the process argv).
4449
+ * @returns The parsed stage string, or undefined when no `--stage` flag is present.
4450
+ * @example
4451
+ * ```ts
4452
+ * parseStageArg(["bun", "scripts/deploy.ts", "--stage", "dev"]); // "dev"
4453
+ * parseStageArg(["bun", "scripts/deploy.ts"]); // undefined
4454
+ * ```
4455
+ */
4456
+ const parseStageArg = (argv) => {
4457
+ for (let index = 0; index < argv.length; index++) {
4458
+ const token = argv[index];
4459
+ if (token === void 0) continue;
4460
+ const raw = stageValueFrom(token, argv[index + 1]);
4461
+ if (raw !== void 0 && raw.length > 0) return raw;
4462
+ }
4463
+ };
4464
+ //#endregion
4465
+ //#region src/plugins/cli/api.ts
4466
+ /**
4467
+ * @file cli plugin — API factory (dev, deploy, auth, doctor).
4468
+ */
4469
+ /**
4470
+ * Builds app.cli.* over the deploy plugin (via ctx.require(deployPlugin)). `dev`/`deploy` resolve
4471
+ * their args (port from `--port`; guided unless `ci`) then delegate, catching any failure into a
4472
+ * branded `✗` line + non-zero exit; the read-only verbs (auth/doctor/whoami) render in Moku style.
4473
+ *
4474
+ * @param ctx - CLI plugin context (own config + typed require to deployPlugin).
4475
+ * @returns The cli API object (dev, deploy, auth, doctor, whoami, wrangler).
4476
+ * @example
4477
+ * ```ts
4478
+ * const api = createCliApi(ctx);
4479
+ * await api.dev({ webBuild: () => web.cli.build() }); // → deploy.dev({ port })
4480
+ * await api.deploy({ ci: true }); // → deploy.run({ ci: true })
4481
+ * ```
4482
+ */
4483
+ const createCliApi = (ctx) => ({
4484
+ /**
4485
+ * Run the Worker locally. The dev port comes ONLY from `opts.port` — the consumer passes it (e.g.
4486
+ * parsed from its own CLI flags in scripts/dev.ts); when omitted it defaults to wrangler's 8787.
4487
+ * There is no hidden argv/config port resolution. Prints a branded dev-session banner, then
4488
+ * delegates to deploy.dev; a `webBuild` hook (e.g. `() => webApp.cli.build()`) wires the web build
4489
+ * into the dev loop so the site recompiles on change. A failure renders a branded `✗` line +
4490
+ * non-zero exit, not a stack.
4491
+ *
4492
+ * @param opts - Optional local dev options.
4493
+ * @param opts.port - Local dev port to bind. Defaults to 8787 when omitted.
4494
+ * @param opts.stage - Stage for the generated wrangler config; falls back to `--stage` then the app stage.
4495
+ * @param opts.webBuild - Cold-build the web site (e.g. `() => webApp.cli.build()`); also the
4496
+ * per-change rebuild when `onChange` is omitted.
4497
+ * @param opts.onChange - Incremental per-change rebuild (e.g. `changes => webApp.cli.update(changes)`),
4498
+ * so each change rebuilds only the changed paths instead of a full `webBuild()`.
4499
+ * @param opts.seed - Load the configured seed (`pluginConfigs.deploy.seed`) into the LOCAL D1 and
4500
+ * reset its cached KV keys before serving — the local analogue of `deploy({ seed: true })`.
4501
+ * @returns Resolves when the dev session ends.
4502
+ * @example
4503
+ * ```ts
4504
+ * await api.dev({ port: 7878, seed: true, webBuild: () => web.cli.build(), onChange: c => web.cli.update(c) });
4505
+ * ```
4506
+ */
4507
+ async dev(opts) {
4508
+ const ui = createBrandConsole();
4509
+ ui.lockup({
4510
+ wordmark: "moku worker",
4511
+ label: "dev session"
4512
+ });
4513
+ const stage = opts?.stage ?? parseStageArg(process.argv);
4514
+ try {
4515
+ await ctx.require(deployPlugin).dev({
4516
+ ...opts?.port === void 0 ? {} : { port: opts.port },
4517
+ ...stage === void 0 ? {} : { stage },
4518
+ ...opts?.webBuild ? { webBuild: opts.webBuild } : {},
4519
+ ...opts?.onChange ? { onChange: opts.onChange } : {},
4520
+ ...opts?.seed ? { seed: opts.seed } : {}
4521
+ });
4522
+ ui.check(true, "dev session stopped cleanly");
4523
+ } catch (error) {
4524
+ ui.error(error instanceof Error ? error.message : String(error));
4525
+ process.exitCode = 1;
4526
+ }
4527
+ },
4528
+ /**
4529
+ * One-command Cloudflare deploy; forwards opts verbatim to deploy.run, then — only on a successful
4530
+ * deploy — the requested post-deploy migration/seed. Guided/interactive by default; `{ ci: true }`
4531
+ * runs the automated path (CI). A `webBuild` hook builds the web site first (before `wrangler
4532
+ * deploy`). RETURNS the structured {@link DeployReport}; on a failure it also renders a branded `✗`
4533
+ * line + sets a non-zero exit code (matching cli.auth/doctor), never a raw stack trace.
4534
+ *
4535
+ * @param opts - Optional deploy options.
4536
+ * @param opts.ci - Automated mode: never prompts, auto-confirms. Omit/false → guided on a TTY.
4537
+ * @param opts.stage - Target stage (resource-name suffix); falls back to `--stage` then the app stage.
4538
+ * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
4539
+ * @param opts.migration - Apply pending remote D1 migrations after a successful deploy (skipped on abort).
4540
+ * @param opts.seed - Load the configured remote seed (`pluginConfigs.deploy.seed`) after a
4541
+ * successful deploy (+ migration); skipped on an aborted deploy.
4542
+ * @returns The deploy report (status, url, resource tally, migration/seed outcome, errors).
4543
+ * @example
4544
+ * ```ts
4545
+ * const report = await api.deploy({ webBuild: () => web.cli.build(), migration: true, seed: true });
4546
+ * if (report.status === "aborted") return; // creds not set up yet — nothing shipped
4547
+ * ```
4548
+ */
4549
+ async deploy(opts) {
4550
+ const stage = opts?.stage ?? parseStageArg(process.argv);
4551
+ try {
4552
+ const report = await ctx.require(deployPlugin).run({
4553
+ ...opts,
4554
+ ...stage === void 0 ? {} : { stage }
4555
+ });
4556
+ if (report.status === "failed") process.exitCode = 1;
4557
+ return report;
4558
+ } catch (error) {
4559
+ const message = error instanceof Error ? error.message : String(error);
4560
+ createBrandConsole().error(message);
4561
+ process.exitCode = 1;
4562
+ return {
4563
+ ok: false,
4564
+ status: "failed",
4565
+ stage: stage ?? "production",
4566
+ migration: "skipped",
4567
+ seed: "skipped",
4568
+ elapsedMs: 0,
4569
+ errors: [message]
4570
+ };
4571
+ }
4572
+ },
4573
+ /**
4574
+ * Seed a configured D1 database from a SQL file (delegates to deploy.seed). Local by default;
4575
+ * `opts.remote` seeds Cloudflare. The stage is resolved from a `--stage <name>` CLI flag (so
4576
+ * `bun run dev --seed --stage dev` seeds the dev database). A failure renders a branded `✗` line
4577
+ * and sets a non-zero exit code rather than throwing.
4578
+ *
4579
+ * @param sqlFile - Path to the SQL file to execute (e.g. "db/seed.sql").
4580
+ * @param opts - Optional options.
4581
+ * @param opts.binding - The d1 binding to target when more than one is configured (e.g. "DB").
4582
+ * @param opts.remote - Seed the remote (Cloudflare) D1 instead of the local one.
4583
+ * @returns Resolves once the seed completes (or after a failure is rendered).
4584
+ * @example
4585
+ * ```ts
4586
+ * await app.cli.seed("db/seed.sql"); // before app.cli.dev(...)
4587
+ * ```
4588
+ */
4589
+ async seed(sqlFile, opts) {
4590
+ const ui = createBrandConsole();
4591
+ ui.lockup({
4592
+ wordmark: "moku worker",
4593
+ label: "seed"
4594
+ });
4595
+ const stage = parseStageArg(process.argv);
4596
+ try {
4597
+ await ctx.require(deployPlugin).seed(sqlFile, {
4598
+ ...opts,
4599
+ ...stage === void 0 ? {} : { stage }
4600
+ });
4601
+ ui.check(true, "seeded", sqlFile);
4602
+ } catch (error) {
4603
+ ui.error(error instanceof Error ? error.message : String(error));
4604
+ process.exitCode = 1;
4605
+ }
4606
+ },
4607
+ /**
4608
+ * Verify the `.env` token (no sub) or print the config-derived token guidance (`"setup"`),
4609
+ * rendered in Moku style. `setup` works without a token; verify reports the resolved account.
4610
+ *
4611
+ * @param sub - Pass "setup" to print guidance; omit to verify the current token.
4612
+ * @returns Resolves once the check or guidance render completes.
4613
+ * @example
4614
+ * ```ts
4615
+ * await api.auth("setup"); // print what token to create
4616
+ * await api.auth(); // verify the current token
4617
+ * ```
4618
+ */
4619
+ async auth(sub) {
4620
+ const deploy = ctx.require(deployPlugin);
4621
+ const ui = createBrandConsole();
4622
+ if (sub === "setup") {
4623
+ renderAuthSetup(ui, deploy.requiredToken(), { ci: deploy.ciToken() });
4624
+ return;
4625
+ }
4626
+ try {
4627
+ const status = await deploy.verifyAuth();
4628
+ ui.check(true, "token valid", `account "${status.account}" (${status.accountId})`);
4629
+ } catch (error) {
4630
+ ui.error(error instanceof Error ? error.message : String(error));
4631
+ }
4632
+ },
4633
+ /**
4634
+ * One-shot preflight report: token + account (verifyAuth) then infra drift (checkInfra),
4635
+ * each as a branded check line. Stops after the token check when auth fails.
4636
+ *
4637
+ * @returns Resolves once the report is printed.
4638
+ * @example
4639
+ * ```ts
4640
+ * await api.doctor();
4641
+ * ```
4642
+ */
4643
+ async doctor() {
4644
+ const deploy = ctx.require(deployPlugin);
4645
+ const ui = createBrandConsole();
4646
+ ui.heading("doctor");
4647
+ let tokenOk = false;
4648
+ try {
4649
+ const status = await deploy.verifyAuth();
4650
+ tokenOk = true;
4651
+ ui.check(true, "token", `valid · account "${status.account}" (${status.accountId})`);
4652
+ } catch (error) {
4653
+ ui.check(false, "token", error instanceof Error ? error.message : String(error));
4654
+ }
4655
+ if (!tokenOk) {
4656
+ ui.line("Run `auth setup` for the exact token to create.");
4657
+ return;
4658
+ }
4659
+ try {
4660
+ const plan = await deploy.checkInfra();
4661
+ ui.check(true, "infra", `${plan.exists.length} exist, ${plan.missing.length} to create in "${plan.account}"`);
4662
+ } catch (error) {
4663
+ ui.check(false, "infra", error instanceof Error ? error.message : String(error));
4664
+ }
4665
+ },
4666
+ /**
4667
+ * Print the resolved Cloudflare account for the current `.env` token.
4668
+ *
4669
+ * @returns Resolves once the account summary is printed.
4670
+ * @example
4671
+ * ```ts
4672
+ * await api.whoami();
4673
+ * ```
4674
+ */
4675
+ async whoami() {
4676
+ const ui = createBrandConsole();
4677
+ try {
4678
+ const status = await ctx.require(deployPlugin).verifyAuth();
4679
+ ui.check(true, "account", `${status.account} (${status.accountId})`);
4680
+ } catch (error) {
4681
+ ui.error(error instanceof Error ? error.message : String(error));
4682
+ }
4683
+ },
4684
+ /**
4685
+ * Run an arbitrary wrangler command through the branded CLI (escape hatch). Streams its output.
4686
+ *
4687
+ * @param args - The wrangler arguments.
4688
+ * @returns Resolves once wrangler exits.
4689
+ * @example
4690
+ * ```ts
4691
+ * await api.wrangler(["kv", "namespace", "list"]);
4692
+ * ```
4693
+ */
4694
+ async wrangler(args) {
4695
+ createBrandConsole().heading(`wrangler ${args.join(" ")}`);
4696
+ await ctx.require(deployPlugin).wrangler(args);
4697
+ }
4698
+ });
4699
+ //#endregion
4700
+ //#region src/plugins/cli/handlers.ts
4701
+ /** Divider drawn before the native `wrangler dev` TUI so the moku preamble reads as one section. */
4702
+ const WRANGLER_DIVIDER = ` ── wrangler ${"─".repeat(48)}`;
4703
+ /** Deploy phases that are a slow, opaque wait (captured output) — worth a live spinner on a TTY. */
4704
+ const SPINNER_PHASES = new Set(["upload", "deploy"]);
4705
+ /** Braille spinner glyphs; advance one per tick. */
4706
+ const SPINNER_FRAMES = [
4707
+ "⠋",
4708
+ "⠙",
4709
+ "⠹",
4710
+ "⠸",
4711
+ "⠼",
4712
+ "⠴",
4713
+ "⠦",
4714
+ "⠧",
4715
+ "⠇",
4716
+ "⠏"
4717
+ ];
4718
+ /** Spinner tick interval (ms). */
4719
+ const SPINNER_TICK_MS = 80;
4720
+ /** Carriage-return + blanks + carriage-return that wipes the transient spinner line before settling. */
4721
+ const SPINNER_CLEAR = `\r${" ".repeat(72)}\r`;
4722
+ /**
4723
+ * Builds the hook handlers that turn global deploy events into a live progress TUI.
4724
+ * Each logs a clean, prefix-free message via `ctx.log`; the branded log sink (installed
4725
+ * by the cli plugin's onInit from `@moku-labs/common/cli`) adds the `›` marker, brand
4726
+ * color, and stderr routing. Pure observers — print and return; never mutate state,
4727
+ * never block the deploy pipeline (fire-and-forget, spec/07 §3,§4).
4728
+ *
4729
+ * @param ctx - CLI plugin context with injected log core API.
4730
+ * @returns Hook map for the deploy/dev phase + completion events (provision detail is panel-rendered).
4731
+ * @example
4732
+ * ```ts
4733
+ * const hooks = createCliHooks(ctx);
4734
+ * hooks["deploy:phase"]({ phase: "detect" }); // logs "detect" → renders " › detect"
4735
+ * hooks["dev:phase"]({ phase: "serve", detail: "http://localhost:8787" }); // "serve · …"
4736
+ * hooks["deploy:complete"](); // settles the deploy spinner; the "Deployed" panel renders separately
4737
+ * ```
4738
+ */
4739
+ const createCliHooks = (ctx) => {
4740
+ const ui = createBrandConsole();
4741
+ const { palette } = ui;
4742
+ let spinnerTimer;
4743
+ let spinnerLabel;
4744
+ const stopSpinner = () => {
4745
+ if (spinnerTimer !== void 0) {
4746
+ clearInterval(spinnerTimer);
4747
+ spinnerTimer = void 0;
4748
+ }
4749
+ if (spinnerLabel !== void 0) {
4750
+ process.stdout.write(SPINNER_CLEAR);
4751
+ ctx.log.info(spinnerLabel);
4752
+ spinnerLabel = void 0;
4753
+ }
4754
+ };
4755
+ const startSpinner = (label) => {
4756
+ spinnerLabel = label;
4757
+ let frame = 0;
4758
+ const text = `${label} …`;
4759
+ spinnerTimer = setInterval(() => {
4760
+ const glyph = SPINNER_FRAMES[frame % SPINNER_FRAMES.length] ?? SPINNER_FRAMES[0];
4761
+ frame += 1;
4762
+ process.stdout.write(`\r ${palette.pink(glyph)} ${palette.dim(text)}`);
4763
+ }, SPINNER_TICK_MS);
4764
+ };
4765
+ return {
4766
+ /**
4767
+ * Render one pipeline phase. Quick phases print a clean line ("phase" / "phase · detail"); the
4768
+ * slow opaque waits (upload / deploy) animate a branded spinner on a TTY, settling to a line when
4769
+ * the next phase or completion arrives. Off a TTY every phase is a plain line (unchanged).
4770
+ *
4771
+ * @param p - The deploy:phase event payload.
4772
+ * @example
4773
+ * ```ts
4774
+ * handler({ phase: "detect" }); // "detect"
4775
+ * handler({ phase: "deploy" }); // spins on a TTY, else "deploy"
4776
+ * ```
4777
+ */
4778
+ "deploy:phase"(p) {
4779
+ stopSpinner();
4780
+ const label = p.detail ? `${p.phase} · ${p.detail}` : p.phase;
4781
+ if (process.stdout.isTTY === true && SPINNER_PHASES.has(p.phase)) startSpinner(label);
4782
+ else ctx.log.info(label);
4783
+ },
4784
+ /**
4785
+ * Log one dev-session phase: "phase" or "phase · detail".
4786
+ *
4787
+ * @param p - The dev:phase event payload.
4788
+ * @example
4789
+ * ```ts
4790
+ * handler({ phase: "serve", detail: "http://localhost:8787" }); // "serve · http://localhost:8787"
4791
+ * ```
4792
+ */
4793
+ "dev:phase"(p) {
4794
+ ctx.log.info(p.detail ? `${p.phase} · ${p.detail}` : p.phase);
4795
+ if (p.phase === "serve") ui.line(WRANGLER_DIVIDER);
4796
+ },
4797
+ /**
4798
+ * Log the site rebuild result: "site <n> files · <ms>ms" (omits the count when unknown).
4799
+ *
4800
+ * @param p - The dev:rebuilt event payload.
4801
+ * @example
4802
+ * ```ts
4803
+ * handler({ files: 12, ms: 240 }); // "site 12 files · 240ms"
4804
+ * handler({ files: 0, ms: 240 }); // "site · 240ms"
4805
+ * ```
4806
+ */
4807
+ "dev:rebuilt"(p) {
4808
+ ctx.log.info(p.files > 0 ? `site ${String(p.files)} files · ${String(p.ms)}ms` : `site · ${String(p.ms)}ms`);
4809
+ },
4810
+ /**
4811
+ * Log a non-fatal dev build failure via warn (the session keeps serving the last good build).
4812
+ *
4813
+ * @param p - The dev:error event payload.
4814
+ * @example
4815
+ * ```ts
4816
+ * handler({ message: "build failed" }); // warn "build failed"
4817
+ * ```
4818
+ */
4819
+ "dev:error"(p) {
4820
+ ctx.log.warn(p.message);
4821
+ },
4822
+ /**
4823
+ * Settle the final deploy spinner. The deployed URL + summary now render as a branded panel (the
4824
+ * deploy plugin's renderDeploySummary), so the cli no longer logs a duplicate `deployed → url`.
4825
+ *
4826
+ * @example
4827
+ * ```ts
4828
+ * handler(); // clears the `deploy` spinner; the "Deployed" panel follows from the deploy plugin
4829
+ * ```
4830
+ */
4831
+ "deploy:complete"() {
4832
+ stopSpinner();
4833
+ }
4834
+ };
4835
+ };
4836
+ /**
4837
+ * Standard tier (node-only) — developer-facing CLI surface.
4838
+ *
4839
+ * Mounts `app.cli.dev()` and `app.cli.deploy()` as thin passthroughs to deployPlugin.
4840
+ * Hooks subscribe to the global deploy:phase / provision:resource / deploy:complete events
4841
+ * and print a live progress TUI via the injected ctx.log core API.
4842
+ *
4843
+ * Inline lambdas on `api`/`hooks` preserve event-name inference so the hook map keys
4844
+ * are constrained to `WorkerEvents` keys (spec/15 §5).
4845
+ *
4846
+ * @see README.md
4847
+ */
4848
+ const cliPlugin = createPlugin$1("cli", {
4849
+ depends: [deployPlugin],
4850
+ config: {},
4851
+ onInit: (ctx) => {
4852
+ ctx.log.clearSinks();
4853
+ ctx.log.addSink(brandedSink("info"));
4854
+ },
4855
+ api: (ctx) => createCliApi(ctx),
4856
+ hooks: (ctx) => createCliHooks(ctx)
4857
+ });
4858
+ //#endregion
516
4859
  //#region src/index.ts
517
4860
  const framework = createCore(coreConfig, { plugins: [bindingsPlugin, serverPlugin] });
518
4861
  const { createPlugin } = framework;