@moku-labs/worker 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2988 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let _moku_labs_common = require("@moku-labs/common");
24
+ let _moku_labs_core = require("@moku-labs/core");
25
+ let _moku_labs_common_cli = require("@moku-labs/common/cli");
26
+ let node_child_process = require("node:child_process");
27
+ let node_fs = require("node:fs");
28
+ let node_path = require("node:path");
29
+ node_path = __toESM(node_path, 1);
30
+ let node_fs_promises = require("node:fs/promises");
31
+ /**
32
+ * stage core plugin — deployment-stage / dev-mode detection, flat-injected on
33
+ * every regular plugin's context as `ctx.stage` (spec/02 §6). No state, no
34
+ * events, no depends, no lifecycle hooks.
35
+ *
36
+ * @see README.md
37
+ * @example
38
+ * ```typescript
39
+ * // Inside any regular plugin's api factory:
40
+ * api: (ctx) => ({
41
+ * errorBody: (e: Error) =>
42
+ * ctx.stage.isDev() ? e.stack ?? e.message : "Internal Error",
43
+ * })
44
+ * ```
45
+ */
46
+ const stagePlugin = (0, _moku_labs_core.createCorePlugin)("stage", {
47
+ config: { stage: "production" },
48
+ /**
49
+ * Builds the stage accessor surface from the resolved stage.
50
+ *
51
+ * @param ctx - Core plugin context (spec/02 §6 — `{ config, state }` only;
52
+ * no `global`, `emit`, or `require`). `state` is unused by this plugin.
53
+ * @param ctx.config - The resolved plugin config containing the deployment stage.
54
+ * @returns The `ctx.stage` API: `isDev`, `isProduction`, `current`.
55
+ * @example
56
+ * ```typescript
57
+ * const api = stagePlugin.spec.api({ config: { stage: "development" }, state: {} });
58
+ * api.isDev(); // true
59
+ * ```
60
+ */
61
+ api: ({ config }) => ({
62
+ /**
63
+ * Whether this Worker runs in the development stage.
64
+ *
65
+ * @returns True iff `stage === "development"`.
66
+ * @example
67
+ * ```typescript
68
+ * if (ctx.stage.isDev()) return Response.json({ stack: err.stack });
69
+ * ```
70
+ */
71
+ isDev: () => config.stage === "development",
72
+ /**
73
+ * Whether this Worker runs in the production stage. Note: false in "test".
74
+ *
75
+ * @returns True iff `stage === "production"`.
76
+ * @example
77
+ * ```typescript
78
+ * const cc = ctx.stage.isProduction() ? "public, max-age=31536000" : "no-store";
79
+ * ```
80
+ */
81
+ isProduction: () => config.stage === "production",
82
+ /**
83
+ * The raw deployment stage, as the literal union (not `string`).
84
+ *
85
+ * @returns The resolved stage.
86
+ * @example
87
+ * ```typescript
88
+ * ctx.log.info("startup", { stage: ctx.stage.current() });
89
+ * ```
90
+ */
91
+ current: () => config.stage
92
+ })
93
+ });
94
+ const coreConfig = (0, _moku_labs_core.createCoreConfig)("moku-worker", {
95
+ config: {
96
+ stage: "production",
97
+ name: "moku-worker",
98
+ compatibilityDate: ""
99
+ },
100
+ plugins: [
101
+ _moku_labs_common.logPlugin,
102
+ _moku_labs_common.envPlugin,
103
+ stagePlugin
104
+ ]
105
+ });
106
+ const { createPlugin, createCore } = coreConfig;
107
+ //#endregion
108
+ //#region src/plugins/bindings/api.ts
109
+ /**
110
+ * Checks whether a value read from an env object is nullish (null or undefined).
111
+ * Cloudflare supplies either form when a binding is absent, so both must be caught.
112
+ *
113
+ * @param value - The value read from the env object.
114
+ * @returns True when the value is null or undefined.
115
+ * @example
116
+ * ```typescript
117
+ * isNullish(undefined); // true
118
+ * isNullish(0); // false — falsy but bound
119
+ * ```
120
+ */
121
+ const isNullish = (value) => value === void 0 || value === null;
122
+ /**
123
+ * Resolves binding `name` off a request-supplied env object, narrowed to T.
124
+ * Throws a `[moku-worker]`-prefixed error when the binding is nullish.
125
+ * The env argument is read but never retained.
126
+ *
127
+ * @param env - The Cloudflare request env object passed to fetch/scheduled/queue.
128
+ * @param name - The binding name to resolve.
129
+ * @returns The binding value narrowed to T.
130
+ * @throws {Error} With a `[moku-worker]` prefix when the binding is null or undefined.
131
+ * @example
132
+ * ```typescript
133
+ * const kv = requireBinding<KVNamespace>(env, "MY_KV");
134
+ * ```
135
+ */
136
+ const requireBinding = (env, name) => {
137
+ const value = env[name];
138
+ 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.`);
139
+ return value;
140
+ };
141
+ /**
142
+ * Returns true when `name` resolves to a non-nullish value on the request env.
143
+ * Never throws. Use for optional-binding branching without forcing an error.
144
+ *
145
+ * @param env - The Cloudflare request env object passed to fetch/scheduled/queue.
146
+ * @param name - The binding name to check.
147
+ * @returns Whether the binding is present and non-nullish.
148
+ * @example
149
+ * ```typescript
150
+ * const ok = hasBinding(env, "DB"); // false if DB is not bound
151
+ * ```
152
+ */
153
+ const hasBinding = (env, name) => !isNullish(env[name]);
154
+ /**
155
+ * Builds the app.bindings API surface. The factory receives a context but does
156
+ * not use it — bindings holds no state (F4) and all resolution is argument-local.
157
+ *
158
+ * @param _ctx - Plugin context (unused; bindings is stateless — F4).
159
+ * @returns BindingsApi with `require` and `has` methods.
160
+ * @example
161
+ * ```typescript
162
+ * const api = createBindingsApi(ctx);
163
+ * const kv = api.require<KVNamespace>(env, "MY_KV");
164
+ * ```
165
+ */
166
+ const createBindingsApi = (_ctx) => ({
167
+ require: requireBinding,
168
+ has: hasBinding
169
+ });
170
+ /**
171
+ * Standard-tier stateless resolver — the binding-family dependency root.
172
+ *
173
+ * Exposes `require<T>(env, name)` and `has(env, name)` off a per-request env
174
+ * object. Regular plugin so downstream binding plugins can declare
175
+ * `depends: [bindingsPlugin]` and reach it via `ctx.require(bindingsPlugin)`.
176
+ *
177
+ * @see README.md
178
+ */
179
+ const bindingsPlugin = createPlugin("bindings", {
180
+ config: { required: [] },
181
+ api: createBindingsApi
182
+ });
183
+ //#endregion
184
+ //#region src/plugins/d1/api.ts
185
+ /**
186
+ * Create the d1 api. Each method resolves the D1Database off the request
187
+ * `env` via the bindings plugin, then forwards to the native D1 call. The
188
+ * binding is never cached, so concurrent requests stay isolated (SB4).
189
+ *
190
+ * The return is intentionally NOT annotated `: Api`. Annotating it would
191
+ * collapse the per-method call-site generic `<T>` on `query`/`first` to
192
+ * `unknown`; instead the implementation forwards `<T>` to `all<T>()` /
193
+ * `first<T>()` and `types.ts#Api` remains the public-surface source of truth.
194
+ *
195
+ * @param {D1Ctx} ctx - Plugin context (own config + require).
196
+ * @returns {object} The d1 public api (query, first, run, batch, prepare, deployManifest).
197
+ * @example
198
+ * ```typescript
199
+ * const api = createD1Api(ctx);
200
+ * const { results } = await api.query<Product>(env, "SELECT * FROM products");
201
+ * ```
202
+ */
203
+ const createD1Api = (ctx) => {
204
+ const db = (env) => ctx.require(bindingsPlugin).require(env, ctx.config.binding);
205
+ return {
206
+ /**
207
+ * Run a statement and return all rows. Forwards the call-site generic to
208
+ * `all<T>()` so the result type is not widened to `unknown`.
209
+ *
210
+ * @param {WorkerEnv} env - Per-request Cloudflare bindings object.
211
+ * @param {string} sql - SQL text with `?` placeholders.
212
+ * @param {unknown[]} params - Bind parameters, in placeholder order.
213
+ * @returns {Promise<D1Result<T>>} All rows (`.results` is `T[]`).
214
+ * @example
215
+ * ```typescript
216
+ * const { results } = await api.query<Product>(env, "SELECT * FROM products WHERE active = ?", 1);
217
+ * ```
218
+ */
219
+ query: (env, sql, ...params) => db(env).prepare(sql).bind(...params).all(),
220
+ /**
221
+ * Run a statement and return the first row, or `null` if there are none.
222
+ * Forwards the call-site generic to `first<T>()`.
223
+ *
224
+ * @param {WorkerEnv} env - Per-request Cloudflare bindings object.
225
+ * @param {string} sql - SQL text with `?` placeholders.
226
+ * @param {unknown[]} params - Bind parameters, in placeholder order.
227
+ * @returns {Promise<T | null>} The first row, or `null` if none matched.
228
+ * @example
229
+ * ```typescript
230
+ * const row = await api.first<Product>(env, "SELECT * FROM products WHERE id = ?", id);
231
+ * ```
232
+ */
233
+ first: (env, sql, ...params) => db(env).prepare(sql).bind(...params).first(),
234
+ /**
235
+ * Run a write/DDL statement (INSERT/UPDATE/DELETE/DDL) and return the
236
+ * D1 result carrying `.meta` (e.g. `rows_written`, `last_row_id`).
237
+ *
238
+ * @param {WorkerEnv} env - Per-request Cloudflare bindings object.
239
+ * @param {string} sql - SQL text with `?` placeholders.
240
+ * @param {unknown[]} params - Bind parameters, in placeholder order.
241
+ * @returns {Promise<D1Result>} Result carrying `.meta`.
242
+ * @example
243
+ * ```typescript
244
+ * const res = await api.run(env, "INSERT INTO products (name) VALUES (?)", name);
245
+ * const id = res.meta.last_row_id;
246
+ * ```
247
+ */
248
+ run: (env, sql, ...params) => db(env).prepare(sql).bind(...params).run(),
249
+ /**
250
+ * Execute caller-built prepared statements atomically in one round-trip,
251
+ * returning one result per statement in order.
252
+ *
253
+ * @param {WorkerEnv} env - Per-request Cloudflare bindings object.
254
+ * @param {D1PreparedStatement[]} stmts - Statements built from prepare(env).
255
+ * @returns {Promise<D1Result[]>} One result per statement, order preserved.
256
+ * @example
257
+ * ```typescript
258
+ * const handle = api.prepare(env);
259
+ * await api.batch(env, [handle.prepare("INSERT INTO a VALUES (1)").bind()]);
260
+ * ```
261
+ */
262
+ batch: (env, stmts) => db(env).batch(stmts),
263
+ /**
264
+ * Resolve the request-scoped D1Database so callers can build prepared
265
+ * statements for batch(). Issues no query itself.
266
+ *
267
+ * @param {WorkerEnv} env - Per-request Cloudflare bindings object.
268
+ * @returns {D1Database} The request-resolved database handle.
269
+ * @example
270
+ * ```typescript
271
+ * const handle = api.prepare(env);
272
+ * const stmt = handle.prepare("SELECT * FROM t").bind();
273
+ * ```
274
+ */
275
+ prepare: (env) => db(env),
276
+ /**
277
+ * Return this plugin's deploy metadata for the deploy plugin to read.
278
+ * Build-time only — takes no `env`. The return is typed `DeployManifest`
279
+ * (from types.ts), which pins `kind` to the literal `"d1"` without an
280
+ * inline `as` assertion.
281
+ *
282
+ * @returns {DeployManifest} Deploy manifest entry `{ kind: "d1", binding, migrations }`.
283
+ * @example
284
+ * ```typescript
285
+ * const m = api.deployManifest();
286
+ * // => { kind: "d1", binding: "DB", migrations: "./migrations" }
287
+ * ```
288
+ */
289
+ deployManifest: () => ({
290
+ kind: "d1",
291
+ binding: ctx.config.binding,
292
+ migrations: ctx.config.migrations
293
+ })
294
+ };
295
+ };
296
+ /**
297
+ * Standard tier — Cloudflare D1 SQL access (thin typed wrappers, not an ORM).
298
+ *
299
+ * Exposes `query`, `first`, `run`, `batch`, `prepare`, and `deployManifest`.
300
+ * Resolves the D1 binding off the per-request `env` via the bindings plugin.
301
+ * No state, no events, no lifecycle hooks (request-scoped, spec/06 §3).
302
+ *
303
+ * @see README.md
304
+ */
305
+ const d1Plugin = createPlugin("d1", {
306
+ depends: [bindingsPlugin],
307
+ config: {
308
+ binding: "DB",
309
+ migrations: ""
310
+ },
311
+ api: (ctx) => createD1Api(ctx)
312
+ });
313
+ //#endregion
314
+ //#region src/plugins/durable-objects/api.ts
315
+ /**
316
+ * Builds the `app.durableObjects` API surface — `get` and `deployManifest`.
317
+ *
318
+ * All namespace resolution uses the per-call `env` argument: `env` is threaded, never
319
+ * stored (SB4 / design §1a). The config bindings map is frozen and read-only. No state
320
+ * is held on the plugin between calls (stateless — `Record<string, never>`).
321
+ *
322
+ * @param ctx - Plugin context with `config.bindings`, `require(bindingsPlugin)`, and core APIs.
323
+ * @returns The durableObjects API: `{ get, deployManifest }`.
324
+ * @example
325
+ * ```typescript
326
+ * const api = createDoApi(ctx);
327
+ * const stub = api.get(env, "counter", "room-42");
328
+ * const manifest = api.deployManifest(); // { kind: "do", bindings: { counter: "COUNTER" } }
329
+ * ```
330
+ */
331
+ const createDoApi = (ctx) => ({
332
+ /**
333
+ * Resolves a `DurableObjectStub` off the per-request env.
334
+ *
335
+ * Maps `logicalName` → `config.bindings[logicalName]` (falling back to `logicalName`
336
+ * itself when unmapped), derives a deterministic id via `namespace.idFromName(idName)`,
337
+ * and returns the addressed stub. Synchronous — returns a stub, not a Promise.
338
+ * Throws (via the bindings resolver) when the binding is not present on `env`.
339
+ *
340
+ * @param env - Per-request Cloudflare bindings object (Worker fetch/queue/scheduled env).
341
+ * @param logicalName - Logical DO name used in code (e.g. `"counter"`).
342
+ * @param idName - Stable id name passed to `idFromName` (e.g. `"room-42"`).
343
+ * @returns The addressed `DurableObjectStub`.
344
+ * @throws {Error} With `[moku-worker]` prefix when the binding is not bound on `env`.
345
+ * @example
346
+ * ```typescript
347
+ * const stub = app.durableObjects.get(env, "counter", "room-42");
348
+ * const res = await stub.fetch("https://do/increment");
349
+ * ```
350
+ */
351
+ get: (env, logicalName, idName) => {
352
+ const binding = ctx.config.bindings[logicalName] ?? logicalName;
353
+ const ns = ctx.require(bindingsPlugin).require(env, binding);
354
+ return ns.get(ns.idFromName(idName));
355
+ },
356
+ /**
357
+ * Returns this plugin's deploy metadata — read by the `deploy` plugin via
358
+ * `ctx.require(durableObjectsPlugin)`. Never reads sibling `pluginConfigs` (F6;
359
+ * spec/08 §5, §7). Pure synchronous read of `ctx.config.bindings`.
360
+ *
361
+ * @returns `{ kind: "do", bindings }` reflecting the frozen plugin config.
362
+ * @example
363
+ * ```typescript
364
+ * const manifest = app.durableObjects.deployManifest();
365
+ * // → { kind: "do", bindings: { counter: "COUNTER" } }
366
+ * ```
367
+ */
368
+ deployManifest: () => ({
369
+ kind: "do",
370
+ bindings: ctx.config.bindings
371
+ })
372
+ });
373
+ //#endregion
374
+ //#region src/plugins/durable-objects/helpers.ts
375
+ /**
376
+ * Returns a base class the consumer extends and exports from `worker.ts`.
377
+ *
378
+ * PURE (spec/03 §1): takes no `ctx`, has no side effects, and may be called before
379
+ * `createApp`. The static `doName` property captures `name` for diagnostics and
380
+ * binding correlation. The constructor stores `(state, env)` as `this.ctx` / `this.env`,
381
+ * satisfying the Cloudflare Durable Object constructor contract. The plugin NEVER
382
+ * generates the final exported class — the consumer owns that class.
383
+ *
384
+ * @param name - Logical DO name; captured as `static doName` for diagnostics.
385
+ * @returns A base class (constructor) the consumer extends.
386
+ * @example
387
+ * ```typescript
388
+ * // src/counter.ts
389
+ * import { defineDurableObject } from "@moku-labs/worker";
390
+ *
391
+ * export class Counter extends defineDurableObject("Counter") {
392
+ * async fetch(): Promise<Response> {
393
+ * const n = ((await this.ctx.storage.get<number>("n")) ?? 0) + 1;
394
+ * await this.ctx.storage.put("n", n);
395
+ * return Response.json({ n });
396
+ * }
397
+ * }
398
+ * ```
399
+ */
400
+ const defineDurableObject = (name) => {
401
+ /**
402
+ * Base implementation of the Cloudflare Durable Object constructor contract.
403
+ * Stores `(ctx, env)` as readonly properties for consumer subclasses to use.
404
+ */
405
+ class DurableObjectBaseImpl {
406
+ /**
407
+ * Cloudflare per-object storage/alarm context (DurableObjectState).
408
+ * Use `this.ctx.storage` to read/write durable storage and `this.ctx.id` to inspect the DO id.
409
+ */
410
+ ctx;
411
+ /**
412
+ * Per-object Cloudflare bindings (per-request WorkerEnv).
413
+ * Mirrors the env passed at construction time; never cached across requests.
414
+ */
415
+ env;
416
+ /**
417
+ * Logical DO name captured from `defineDurableObject(name)`.
418
+ * Used for diagnostics and binding correlation.
419
+ */
420
+ static doName = name;
421
+ /**
422
+ * Constructs the base Durable Object with Cloudflare's required signature.
423
+ *
424
+ * @param ctx - Cloudflare DurableObjectState (storage, id, blockConcurrencyWhile, …).
425
+ * @param env - Per-request Cloudflare bindings object (WorkerEnv).
426
+ * @example
427
+ * ```typescript
428
+ * class Counter extends Base {
429
+ * constructor(ctx: DurableObjectState, env: WorkerEnv) { super(ctx, env); }
430
+ * }
431
+ * ```
432
+ */
433
+ constructor(ctx, env) {
434
+ this.ctx = ctx;
435
+ this.env = env;
436
+ }
437
+ }
438
+ return DurableObjectBaseImpl;
439
+ };
440
+ /**
441
+ * Cloudflare Durable Objects plugin — Standard tier.
442
+ *
443
+ * Exposes `get(env, logicalName, idName)` (synchronous stub accessor, threaded env) and
444
+ * `deployManifest()` (build-time metadata). Depends on `bindingsPlugin` for namespace
445
+ * resolution. The `defineDurableObject` helper is mounted under `helpers` and re-exported
446
+ * at the top level for consumer use.
447
+ *
448
+ * @example
449
+ * ```typescript
450
+ * // Consumer endpoint handler:
451
+ * const stub = app.durableObjects.get(env, "counter", params.room!);
452
+ * const res = await stub.fetch("https://do/increment");
453
+ * // Consumer DO class:
454
+ * export class Counter extends defineDurableObject("Counter") {
455
+ * async fetch(): Promise<Response> { return new Response("ok"); }
456
+ * }
457
+ * ```
458
+ * @see README.md
459
+ */
460
+ const durableObjectsPlugin = createPlugin("durableObjects", {
461
+ depends: [bindingsPlugin],
462
+ config: { bindings: {} },
463
+ api: createDoApi,
464
+ helpers: { defineDurableObject }
465
+ });
466
+ //#endregion
467
+ //#region src/plugins/kv/api.ts
468
+ /**
469
+ * Builds the app.kv.* api. Resolves the KV namespace off the REQUEST-SUPPLIED env
470
+ * on every call — env is threaded, never stored (design §1a / SB4).
471
+ *
472
+ * @param ctx - The kv plugin context (own config + merged events).
473
+ * @returns The app.kv api: get / put / delete / list / deployManifest.
474
+ * @example
475
+ * ```typescript
476
+ * const api = createKvApi(ctx);
477
+ * const value = await api.get(env, "key");
478
+ * ```
479
+ */
480
+ const createKvApi = (ctx) => {
481
+ const ns = (env) => ctx.require(bindingsPlugin).require(env, ctx.config.binding);
482
+ return {
483
+ /**
484
+ * Reads a value by key from the KV namespace. Returns null when absent.
485
+ *
486
+ * @param env - The per-request Cloudflare env (threaded, never stored).
487
+ * @param key - The key to read.
488
+ * @returns The stored value, or null when absent.
489
+ * @example
490
+ * ```typescript
491
+ * const value = await api.get(env, "feature-flags");
492
+ * ```
493
+ */
494
+ get: async (env, key) => ns(env).get(key),
495
+ /**
496
+ * Writes a string value under a key, optionally with KV put options.
497
+ *
498
+ * @param env - The per-request Cloudflare env.
499
+ * @param key - The key to write.
500
+ * @param value - The string value to store.
501
+ * @param opts - Optional expiration / metadata.
502
+ * @returns Resolves once the write is acknowledged.
503
+ * @example
504
+ * ```typescript
505
+ * await api.put(env, "session:1", "data", { expirationTtl: 3600 });
506
+ * ```
507
+ */
508
+ put: async (env, key, value, opts) => ns(env).put(key, value, opts),
509
+ /**
510
+ * Removes a key from the namespace (no-op if absent).
511
+ *
512
+ * @param env - The per-request Cloudflare env.
513
+ * @param key - The key to delete.
514
+ * @returns Resolves once the delete is acknowledged.
515
+ * @example
516
+ * ```typescript
517
+ * await api.delete(env, "session:expired");
518
+ * ```
519
+ */
520
+ delete: async (env, key) => ns(env).delete(key),
521
+ /**
522
+ * Lists keys in the namespace, optionally filtered/paginated via opts.
523
+ *
524
+ * @param env - The per-request Cloudflare env.
525
+ * @param opts - Optional prefix / cursor / limit.
526
+ * @returns The list result from the KV namespace.
527
+ * @example
528
+ * ```typescript
529
+ * const { keys } = await api.list(env, { prefix: "session:" });
530
+ * ```
531
+ */
532
+ list: async (env, opts) => ns(env).list(opts),
533
+ /**
534
+ * Returns this plugin's own deploy metadata, read by the deploy plugin via
535
+ * require (design §6 / F6). Build-time only — takes no env.
536
+ *
537
+ * @returns The kv deploy descriptor with kind literal and binding name.
538
+ * @example
539
+ * ```typescript
540
+ * const manifest = api.deployManifest(); // { kind: "kv", binding: "KV" }
541
+ * ```
542
+ */
543
+ deployManifest: () => ({
544
+ kind: "kv",
545
+ binding: ctx.config.binding
546
+ })
547
+ };
548
+ };
549
+ /**
550
+ * Micro tier — thin env-first wrapper over a Cloudflare KV namespace.
551
+ *
552
+ * Resolves the KV namespace per request via `ctx.require(bindingsPlugin)`;
553
+ * never stores env in state (design §1a / SB4). No lifecycle hooks —
554
+ * request-scoped; nothing to open or close.
555
+ *
556
+ * @see README.md
557
+ */
558
+ const kvPlugin = createPlugin("kv", {
559
+ depends: [bindingsPlugin],
560
+ config: { binding: "KV" },
561
+ api: createKvApi
562
+ });
563
+ //#endregion
564
+ //#region src/plugins/queues/api.ts
565
+ /**
566
+ * @file queues plugin — API factory (send, sendBatch, consume, deployManifest).
567
+ *
568
+ * All binding-resolving methods take the per-request `env` as the first argument
569
+ * and resolve the `Queue` via `ctx.require(bindingsPlugin).require<Queue>(env, name)`.
570
+ * The `env` is never stored (SB4 / design §1a) — resolved fresh on every call.
571
+ */
572
+ /**
573
+ * Builds app.queues.* — read by worker.ts queue() delegation (design §1d; spec/02 §7).
574
+ *
575
+ * Resolves Queue bindings off the request env per call (never stored — SB4).
576
+ * Emits `queue:message` for observability after each consumed message (F8).
577
+ *
578
+ * @param ctx - Plugin context (own config + require + emit).
579
+ * @returns The queues API surface: send, sendBatch, consume, deployManifest.
580
+ * @example
581
+ * ```ts
582
+ * // Worker entry (design §1d)
583
+ * export default {
584
+ * queue: (b, e, c) => app.queues.consume(b, e, c),
585
+ * };
586
+ * ```
587
+ */
588
+ const createQueuesApi = (ctx) => {
589
+ /**
590
+ * Resolves a named Queue binding from the per-request env.
591
+ * Throws a [moku-worker]-prefixed error when the binding is absent.
592
+ *
593
+ * @param env - Per-request Cloudflare bindings.
594
+ * @param name - Queue binding name.
595
+ * @returns The resolved Queue instance.
596
+ * @example
597
+ * ```ts
598
+ * const q = queue(env, "ORDERS");
599
+ * ```
600
+ */
601
+ const queue = (env, name) => ctx.require(bindingsPlugin).require(env, name);
602
+ return {
603
+ /**
604
+ * Enqueue a single message onto the named queue.
605
+ *
606
+ * Resolves the Queue binding fresh from `env` on every call (SB4).
607
+ * Request/response work → api method, never emit (F8).
608
+ *
609
+ * @param env - Per-request Cloudflare bindings object.
610
+ * @param q - Target queue binding name in `env`.
611
+ * @param body - Message body to enqueue.
612
+ * @returns Resolves once the message is enqueued.
613
+ * @throws {Error} With a `[moku-worker]` prefix if the binding is missing.
614
+ * @example
615
+ * ```ts
616
+ * await app.queues.send(env, "ORDERS", { orderId: "123" });
617
+ * ```
618
+ */
619
+ send: async (env, q, body) => {
620
+ await queue(env, q).send(body);
621
+ },
622
+ /**
623
+ * Enqueue many messages in one call; each element becomes one message.
624
+ *
625
+ * Maps each body to `{ body }` before calling `Queue.sendBatch` (design §4.3).
626
+ *
627
+ * @param env - Per-request Cloudflare bindings object.
628
+ * @param q - Target queue binding name in `env`.
629
+ * @param bodies - Array of message bodies; each becomes one message.
630
+ * @returns Resolves once all messages are enqueued.
631
+ * @throws {Error} With a `[moku-worker]` prefix if the binding is missing.
632
+ * @example
633
+ * ```ts
634
+ * await app.queues.sendBatch(env, "ORDERS", orders);
635
+ * ```
636
+ */
637
+ sendBatch: async (env, q, bodies) => {
638
+ await queue(env, q).sendBatch(bodies.map((body) => ({ body })));
639
+ },
640
+ /**
641
+ * Consumer dispatch — the Worker's `queue()` export delegates here.
642
+ *
643
+ * Iterates `batch.messages`, **awaits** `config.onMessage(message, env)` per message
644
+ * (so Cloudflare gets a settled promise and the handler controls ack/retry; F8,
645
+ * spec/07 §3 — never emit for awaited work), then fire-and-forget emits `queue:message`
646
+ * for observability. Returns a promise the Worker **must** await so the isolate is not
647
+ * killed mid-batch.
648
+ *
649
+ * @param batch - The incoming message batch from Cloudflare.
650
+ * @param env - Per-request Cloudflare bindings object.
651
+ * @param _exec - waitUntil / passThroughOnException (reserved for future use).
652
+ * @returns Resolves after all messages in the batch are processed.
653
+ * @throws {Error} Re-throws any error from `config.onMessage` so Cloudflare can retry.
654
+ * @example
655
+ * ```ts
656
+ * // Worker entry
657
+ * queue: (b, e, c) => app.queues.consume(b, e, c),
658
+ * ```
659
+ */
660
+ consume: async (batch, env, _exec) => {
661
+ for (const m of batch.messages) {
662
+ await ctx.config.onMessage(m, env);
663
+ ctx.emit("queue:message", {
664
+ queue: batch.queue,
665
+ messageId: m.id
666
+ });
667
+ }
668
+ },
669
+ /**
670
+ * Returns this plugin's deploy metadata, read by the deploy plugin via
671
+ * `ctx.require(queuesPlugin).deployManifest()` (F6 — never reads sibling config).
672
+ *
673
+ * @returns Deploy manifest entry `{ kind: "queue", producers }`.
674
+ * @example
675
+ * ```ts
676
+ * const manifest = ctx.require(queuesPlugin).deployManifest();
677
+ * // → { kind: "queue", producers: ["orders"] }
678
+ * ```
679
+ */
680
+ deployManifest: () => ({
681
+ kind: "queue",
682
+ producers: ctx.config.producers
683
+ })
684
+ };
685
+ };
686
+ /**
687
+ * Standard tier — Cloudflare Queues producer + consumer dispatch.
688
+ *
689
+ * `events` is declared first and via `register.map<QueueEvents>` so the plugin's own events infer
690
+ * into the factory context; the api wiring is therefore arrow-wrapped (contextually typed).
691
+ *
692
+ * Emits the plugin-local `queue:message` event after each consumed message.
693
+ *
694
+ * @see README.md
695
+ */
696
+ const queuesPlugin = createPlugin("queues", {
697
+ events: (register) => register.map({ "queue:message": "A queue message was processed" }),
698
+ depends: [bindingsPlugin],
699
+ config: {
700
+ producers: [],
701
+ onMessage: async () => {}
702
+ },
703
+ api: (ctx) => createQueuesApi(ctx)
704
+ });
705
+ //#endregion
706
+ //#region src/plugins/storage/providers/r2.ts
707
+ /**
708
+ * Build a StorageProvider backed by the real R2Bucket resolved off the
709
+ * per-request env via the bindings plugin. The bucket is resolved fresh on
710
+ * EVERY method call — never cached, so concurrent requests stay isolated
711
+ * (worker-api-design SB4; spec/08 §6).
712
+ *
713
+ * Each method is `async` so that synchronous throws from `bindings.require`
714
+ * (e.g. missing binding) are automatically wrapped in rejected Promises —
715
+ * callers can always use `await` / `.catch` instead of `try/catch`.
716
+ *
717
+ * @param bindings - The bindings plugin API (provides `require<T>`).
718
+ * @param env - The per-request Cloudflare bindings object.
719
+ * @param bucket - The R2 bucket binding name (e.g. "ASSETS").
720
+ * @returns {StorageProvider} A provider that delegates to the resolved R2Bucket.
721
+ * @example
722
+ * ```typescript
723
+ * const provider = resolveR2Provider(ctx.require(bindingsPlugin), env, ctx.config.bucket);
724
+ * const body = await provider.get("my-object");
725
+ * ```
726
+ */
727
+ const resolveR2Provider = (bindings, env, bucket) => {
728
+ /**
729
+ * Resolve the R2Bucket for this request's env. Throws on missing binding.
730
+ *
731
+ * @returns {R2Bucket} The resolved R2Bucket binding.
732
+ * @example
733
+ * ```typescript
734
+ * const bucket = b();
735
+ * ```
736
+ */
737
+ const b = () => bindings.require(env, bucket);
738
+ return {
739
+ /**
740
+ * Read an object from the bucket.
741
+ *
742
+ * @param key - The object key.
743
+ * @returns {Promise<R2ObjectBody | null>} The R2ObjectBody, or null if the key is absent.
744
+ * @example
745
+ * ```typescript
746
+ * const body = await provider.get("assets/logo.png");
747
+ * ```
748
+ */
749
+ async get(key) {
750
+ return b().get(key);
751
+ },
752
+ /**
753
+ * Write an object to the bucket.
754
+ *
755
+ * @param key - The object key.
756
+ * @param value - The object contents (any R2-accepted type).
757
+ * @returns {Promise<R2Object>} The R2Object metadata for the written object.
758
+ * @example
759
+ * ```typescript
760
+ * const obj = await provider.put("assets/logo.png", buffer);
761
+ * ```
762
+ */
763
+ async put(key, value) {
764
+ return b().put(key, value);
765
+ },
766
+ /**
767
+ * Remove one or more objects from the bucket. No-op when a key is absent.
768
+ *
769
+ * @param key - A single key or array of keys to remove.
770
+ * @returns {Promise<void>} Resolves once removed.
771
+ * @example
772
+ * ```typescript
773
+ * await provider.delete("assets/old.png");
774
+ * ```
775
+ */
776
+ async delete(key) {
777
+ return b().delete(key);
778
+ },
779
+ /**
780
+ * List objects, optionally filtered by R2ListOptions.
781
+ *
782
+ * @param opts - Optional list options (prefix, limit, cursor, delimiter).
783
+ * @returns {Promise<R2Objects>} The R2Objects list result.
784
+ * @example
785
+ * ```typescript
786
+ * const { objects } = await provider.list({ prefix: "images/" });
787
+ * ```
788
+ */
789
+ async list(opts) {
790
+ return b().list(opts);
791
+ }
792
+ };
793
+ };
794
+ //#endregion
795
+ //#region src/plugins/storage/api.ts
796
+ /**
797
+ * Build the env-first storage API. Each runtime method resolves the bucket
798
+ * provider fresh from the per-request `env` — nothing is stored, so concurrent
799
+ * requests stay isolated (worker-api-design SB4; spec/08 §6,§7).
800
+ *
801
+ * The `deployManifest()` method is build-time only: it reads from `ctx.config`
802
+ * and never touches `env` or R2.
803
+ *
804
+ * @param ctx - Plugin context (config + require for bindings resolution).
805
+ * @returns {StorageApi} The env-first storage API surface.
806
+ * @example
807
+ * ```typescript
808
+ * const api = createStorageApi(ctx);
809
+ * const body = await api.get(env, "my-object");
810
+ * ```
811
+ */
812
+ const createStorageApi = (ctx) => {
813
+ /**
814
+ * Resolve the StorageProvider for the given per-request env. Called on every
815
+ * method invocation — the bucket binding is never cached across calls.
816
+ *
817
+ * @param env - The per-request Cloudflare bindings object.
818
+ * @returns {StorageProvider} A StorageProvider delegating to the resolved R2Bucket.
819
+ * @example
820
+ * ```typescript
821
+ * const p = provider(env);
822
+ * const body = await p.get("key");
823
+ * ```
824
+ */
825
+ const provider = (env) => resolveR2Provider(ctx.require(bindingsPlugin), env, ctx.config.bucket);
826
+ return {
827
+ /**
828
+ * Read an object from the bucket; resolves null when the key is absent.
829
+ *
830
+ * @param env - Per-request Cloudflare bindings.
831
+ * @param key - Object key.
832
+ * @returns {Promise<R2ObjectBody | null>} The R2ObjectBody, or null.
833
+ * @example
834
+ * ```typescript
835
+ * const body = await api.get(env, "assets/logo.png");
836
+ * ```
837
+ */
838
+ get: (env, key) => provider(env).get(key),
839
+ /**
840
+ * Write an object to the bucket.
841
+ *
842
+ * @param env - Per-request Cloudflare bindings.
843
+ * @param key - Object key.
844
+ * @param value - Object contents (ReadableStream | ArrayBuffer | ArrayBufferView | string | Blob | null).
845
+ * @returns {Promise<R2Object>} The R2Object metadata for the written object.
846
+ * @example
847
+ * ```typescript
848
+ * const obj = await api.put(env, "assets/logo.png", buffer);
849
+ * ```
850
+ */
851
+ put: (env, key, value) => provider(env).put(key, value),
852
+ /**
853
+ * Remove an object (or array of keys) from the bucket. No-op when absent.
854
+ *
855
+ * @param env - Per-request Cloudflare bindings.
856
+ * @param key - Object key or array of keys.
857
+ * @returns {Promise<void>} Resolves once removed.
858
+ * @example
859
+ * ```typescript
860
+ * await api.delete(env, "assets/old.png");
861
+ * ```
862
+ */
863
+ delete: (env, key) => provider(env).delete(key),
864
+ /**
865
+ * List objects, optionally filtered by R2ListOptions.
866
+ *
867
+ * @param env - Per-request Cloudflare bindings.
868
+ * @param opts - Optional R2ListOptions (prefix, limit, cursor, delimiter).
869
+ * @returns {Promise<R2Objects>} The R2Objects list result.
870
+ * @example
871
+ * ```typescript
872
+ * const { objects } = await api.list(env, { prefix: "images/" });
873
+ * ```
874
+ */
875
+ list: (env, opts) => provider(env).list(opts),
876
+ /**
877
+ * Return this plugin's deploy metadata. Build-time only — does not touch
878
+ * `env` or R2. The deploy plugin reads this via `ctx.require(storagePlugin).deployManifest()`.
879
+ *
880
+ * @returns {StorageManifest} Deploy manifest entry `{ kind: "r2", bucket, upload }`.
881
+ * @example
882
+ * ```typescript
883
+ * const manifest = api.deployManifest();
884
+ * // { kind: "r2", bucket: "ASSETS", upload: "./public" }
885
+ * ```
886
+ */
887
+ deployManifest: () => ({
888
+ kind: "r2",
889
+ bucket: ctx.config.bucket,
890
+ upload: ctx.config.upload
891
+ })
892
+ };
893
+ };
894
+ /**
895
+ * Complex tier — Cloudflare R2 object storage behind a provider adapter seam.
896
+ *
897
+ * Exposes `get`, `put`, `delete`, `list` (all env-first) and `deployManifest()`
898
+ * (build-time). Depends on `bindingsPlugin` to resolve the `R2Bucket` binding
899
+ * per request. No state, no events, no lifecycle hooks.
900
+ *
901
+ * @see README.md
902
+ */
903
+ const storagePlugin = createPlugin("storage", {
904
+ depends: [bindingsPlugin],
905
+ config: {
906
+ upload: "",
907
+ bucket: "ASSETS"
908
+ },
909
+ api: createStorageApi
910
+ });
911
+ //#endregion
912
+ //#region src/plugins/deploy/auth/permissions.ts
913
+ /** Permission groups every deploy needs, regardless of resources. */
914
+ const ALWAYS = [{
915
+ group: "Account · Workers Scripts",
916
+ scope: "Edit",
917
+ reason: "deploy",
918
+ inBaseTemplate: true
919
+ }, {
920
+ group: "Account · Account Settings",
921
+ scope: "Read",
922
+ reason: "account",
923
+ inBaseTemplate: true
924
+ }];
925
+ /**
926
+ * Per-resource-kind permission group. `do` needs nothing extra (Durable Objects ship with the
927
+ * Worker script, covered by Workers Scripts · Edit). `d1`/`queue` are NOT in the stock template.
928
+ */
929
+ const BY_KIND = {
930
+ kv: {
931
+ group: "Account · Workers KV Storage",
932
+ scope: "Edit",
933
+ reason: "kv",
934
+ inBaseTemplate: true
935
+ },
936
+ r2: {
937
+ group: "Account · Workers R2 Storage",
938
+ scope: "Edit",
939
+ reason: "r2",
940
+ inBaseTemplate: true
941
+ },
942
+ d1: {
943
+ group: "Account · D1",
944
+ scope: "Edit",
945
+ reason: "d1",
946
+ inBaseTemplate: false
947
+ },
948
+ queue: {
949
+ group: "Account · Queues",
950
+ scope: "Edit",
951
+ reason: "queue",
952
+ inBaseTemplate: false
953
+ },
954
+ do: void 0
955
+ };
956
+ /**
957
+ * Derive the Cloudflare API token requirement from an app manifest: the full permission set plus
958
+ * the subset that must be ADDED to the stock "Edit Cloudflare Workers" template.
959
+ *
960
+ * @param manifest - The assembled deploy manifest.
961
+ * @returns The token requirement (base template, full required set, and groups to add).
962
+ * @example
963
+ * ```ts
964
+ * const { toAdd } = requiredToken({ name: "w", compatibilityDate: "…", resources: [{ kind: "d1", binding: "DB" }] });
965
+ * // toAdd → [{ group: "Account · D1", scope: "Edit", … }]
966
+ * ```
967
+ */
968
+ const requiredToken = (manifest) => {
969
+ const required = [...ALWAYS];
970
+ const seen = new Set(required.map((permission) => permission.group));
971
+ for (const resource of manifest.resources) {
972
+ const permission = BY_KIND[resource.kind];
973
+ if (permission !== void 0 && !seen.has(permission.group)) {
974
+ required.push(permission);
975
+ seen.add(permission.group);
976
+ }
977
+ }
978
+ return {
979
+ base: "Edit Cloudflare Workers",
980
+ required,
981
+ toAdd: required.filter((permission) => !permission.inBaseTemplate)
982
+ };
983
+ };
984
+ /** Permission every CI/automation redeploy needs: ship the Worker script. */
985
+ const CI_ALWAYS = [{
986
+ group: "Account · Workers Scripts",
987
+ scope: "Edit",
988
+ reason: "deploy",
989
+ inBaseTemplate: true
990
+ }];
991
+ /**
992
+ * Per-resource-kind permission for the CI/automation token. After a first LOCAL deploy has
993
+ * provisioned everything, CI only needs to LIST existing infra (the idempotent preflight) and
994
+ * ship — so data resources drop to `Read`; R2 stays `Edit` because asset upload writes objects.
995
+ */
996
+ const CI_BY_KIND = {
997
+ kv: {
998
+ group: "Account · Workers KV Storage",
999
+ scope: "Read",
1000
+ reason: "kv (preflight)",
1001
+ inBaseTemplate: true
1002
+ },
1003
+ r2: {
1004
+ group: "Account · Workers R2 Storage",
1005
+ scope: "Edit",
1006
+ reason: "r2 (asset upload)",
1007
+ inBaseTemplate: true
1008
+ },
1009
+ d1: {
1010
+ group: "Account · D1",
1011
+ scope: "Read",
1012
+ reason: "d1 (preflight)",
1013
+ inBaseTemplate: false
1014
+ },
1015
+ queue: {
1016
+ group: "Account · Queues",
1017
+ scope: "Read",
1018
+ reason: "queue (preflight)",
1019
+ inBaseTemplate: false
1020
+ },
1021
+ do: void 0
1022
+ };
1023
+ /**
1024
+ * Derive the REDUCED Cloudflare API token for CI/automation redeploys, from the same manifest.
1025
+ * Assumes a prior LOCAL deploy already provisioned the infra, so CI never creates: data resources
1026
+ * need only `Read` (the idempotent preflight lists them), R2 keeps `Edit` for asset upload, and no
1027
+ * `Account Settings · Read` is needed because CI pins `CLOUDFLARE_ACCOUNT_ID`. Pure: no network.
1028
+ *
1029
+ * @param manifest - The assembled deploy manifest.
1030
+ * @returns The minimum permission groups for a CI redeploy token (deduped, manifest-scoped).
1031
+ * @example
1032
+ * ```ts
1033
+ * const groups = ciToken({ name: "w", compatibilityDate: "…", resources: [{ kind: "d1", binding: "DB" }] });
1034
+ * // → [Workers Scripts·Edit, D1·Read]
1035
+ * ```
1036
+ */
1037
+ const ciToken = (manifest) => {
1038
+ const groups = [...CI_ALWAYS];
1039
+ const seen = new Set(groups.map((permission) => permission.group));
1040
+ for (const resource of manifest.resources) {
1041
+ const permission = CI_BY_KIND[resource.kind];
1042
+ if (permission !== void 0 && !seen.has(permission.group)) {
1043
+ groups.push(permission);
1044
+ seen.add(permission.group);
1045
+ }
1046
+ }
1047
+ return groups;
1048
+ };
1049
+ //#endregion
1050
+ //#region src/plugins/deploy/auth/setup.ts
1051
+ /** Cloudflare's dashboard path for creating API tokens. */
1052
+ const TOKENS_URL = "https://dash.cloudflare.com/profile/api-tokens";
1053
+ /**
1054
+ * Render the FULL local-first token section (the deploy that provisions everything): the permission
1055
+ * table flagging template-missing rows, the template + "add these" steps, and the `.env.local` lines.
1056
+ *
1057
+ * @param requirement - The full token requirement (from requiredToken()).
1058
+ * @returns The local-first section lines.
1059
+ * @example
1060
+ * ```ts
1061
+ * const lines = localSection(requiredToken(manifest));
1062
+ * ```
1063
+ */
1064
+ const localSection = (requirement) => {
1065
+ const permissionRows = requirement.required.map((permission) => {
1066
+ const flag = permission.inBaseTemplate ? "" : " <- add to template";
1067
+ return ` - ${permission.group} : ${permission.scope} (${permission.reason})${flag}`;
1068
+ });
1069
+ 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.`];
1070
+ return [
1071
+ "LOCAL — first deploy (provisions infra). A Cloudflare API token with these permissions:",
1072
+ "",
1073
+ ...permissionRows,
1074
+ "",
1075
+ "Fastest path:",
1076
+ ` 1. ${TOKENS_URL} -> Create Token`,
1077
+ ` 2. Start from the "${requirement.base}" template.`,
1078
+ ...step3,
1079
+ " 4. Account Resources -> Include -> your account.",
1080
+ " 5. Create the token, copy it, then add it to .env.local:",
1081
+ " CLOUDFLARE_API_TOKEN=<paste your token>",
1082
+ " CLOUDFLARE_ACCOUNT_ID=<your account id>",
1083
+ " 6. Verify it with `auth` (app.deploy.verifyAuth())."
1084
+ ];
1085
+ };
1086
+ /**
1087
+ * Render the REDUCED CI/automation token section (redeploy-only): the scoped permission table plus
1088
+ * the CI-secret + account-pin steps.
1089
+ *
1090
+ * @param groups - The CI permission groups (from ciToken()).
1091
+ * @returns The CI section lines.
1092
+ * @example
1093
+ * ```ts
1094
+ * const lines = ciSection(ciToken(manifest));
1095
+ * ```
1096
+ */
1097
+ const ciSection = (groups) => {
1098
+ return [
1099
+ "CI — automation redeploy (infra already provisioned by a local deploy). A SCOPED token with:",
1100
+ "",
1101
+ ...groups.map((permission) => ` - ${permission.group} : ${permission.scope} (${permission.reason})`),
1102
+ "",
1103
+ ` 1. ${TOKENS_URL} -> Create Token -> Create Custom Token.`,
1104
+ " 2. Add exactly the permissions above (Read, not Edit, on data resources — CI never creates).",
1105
+ " 3. Account Resources -> Include -> your account.",
1106
+ " 4. Store it as the CLOUDFLARE_API_TOKEN secret in CI, and PIN the account so no account",
1107
+ " lookup (and no Account Settings -> Read) is needed:",
1108
+ " CLOUDFLARE_ACCOUNT_ID=<your account id>",
1109
+ " CI reuses the same idempotent pipeline — it lists existing infra and ships. To let CI also",
1110
+ " CREATE missing infra (self-heal), give it the LOCAL token above instead."
1111
+ ];
1112
+ };
1113
+ /**
1114
+ * Render the `auth setup` instructions from the app manifest: the FULL local-first token (provisions
1115
+ * everything) followed by the REDUCED CI/automation token (redeploy-only).
1116
+ *
1117
+ * @param manifest - The assembled deploy manifest.
1118
+ * @returns A multi-line instruction string covering both tokens.
1119
+ * @example
1120
+ * ```ts
1121
+ * const text = tokenInstructions(manifest);
1122
+ * ```
1123
+ */
1124
+ const tokenInstructions = (manifest) => [
1125
+ ...localSection(requiredToken(manifest)),
1126
+ "",
1127
+ ...ciSection(ciToken(manifest))
1128
+ ].join("\n");
1129
+ //#endregion
1130
+ //#region src/plugins/deploy/infra/cloudflare.ts
1131
+ /**
1132
+ * @file deploy plugin — Cloudflare REST discovery client (infra preflight).
1133
+ *
1134
+ * Lists what already exists in a Cloudflare account so the deploy pipeline can create only the
1135
+ * missing resources (idempotent provisioning) and recover real ids for existing kv/d1 bindings.
1136
+ * Authenticated with the `.env` API token (CLOUDFLARE_API_TOKEN) — never an interactive login.
1137
+ * Uses the global `fetch`; node-only, never imported by the runtime Worker bundle.
1138
+ */
1139
+ const API_BASE = "https://api.cloudflare.com/client/v4";
1140
+ /**
1141
+ * GET a Cloudflare API path with the bearer token and unwrap the `result`.
1142
+ *
1143
+ * @param token - The Cloudflare API token (CLOUDFLARE_API_TOKEN).
1144
+ * @param path - API path beneath the v4 base (e.g. "/accounts").
1145
+ * @returns The unwrapped `result` payload, typed by the caller.
1146
+ * @throws {Error} When the HTTP request fails or the API reports `success: false`.
1147
+ * @example
1148
+ * ```ts
1149
+ * const accounts = await cfGet<Array<{ id: string }>>(token, "/accounts");
1150
+ * ```
1151
+ */
1152
+ const cfGet = async (token, path) => {
1153
+ const response = await fetch(`${API_BASE}${path}`, { headers: {
1154
+ Authorization: `Bearer ${token}`,
1155
+ "Content-Type": "application/json"
1156
+ } });
1157
+ const body = await response.json();
1158
+ if (!response.ok || !body.success) {
1159
+ const detail = body.errors?.map((error) => error.message).join("; ") || `HTTP ${response.status}`;
1160
+ throw new Error(`[moku-worker] Cloudflare API request failed (${path}): ${detail}`);
1161
+ }
1162
+ return body.result;
1163
+ };
1164
+ /**
1165
+ * Resolve the Cloudflare account (id + display name) accessible to the token. Used when the
1166
+ * consumer did not pin CLOUDFLARE_ACCOUNT_ID; the first accessible account is chosen.
1167
+ *
1168
+ * @param token - The Cloudflare API token.
1169
+ * @returns The resolved account id and name.
1170
+ * @throws {Error} When the token can access no account.
1171
+ * @example
1172
+ * ```ts
1173
+ * const { id, name } = await resolveAccount(token);
1174
+ * ```
1175
+ */
1176
+ const resolveAccount = async (token) => {
1177
+ const first = (await cfGet(token, "/accounts"))[0];
1178
+ if (!first) throw new Error("[moku-worker] No Cloudflare account is accessible with this API token.");
1179
+ return {
1180
+ id: first.id,
1181
+ name: first.name
1182
+ };
1183
+ };
1184
+ /**
1185
+ * Verify a Cloudflare API token via `GET /user/tokens/verify`. Returns its status (`"active"` for
1186
+ * a usable token); throws (via cfGet) when the token is rejected outright (401/invalid).
1187
+ *
1188
+ * @param token - The Cloudflare API token to verify.
1189
+ * @returns The token status string reported by Cloudflare.
1190
+ * @throws {Error} When the verify request fails (invalid/expired token).
1191
+ * @example
1192
+ * ```ts
1193
+ * const { status } = await verifyToken(token); // status === "active"
1194
+ * ```
1195
+ */
1196
+ const verifyToken = async (token) => {
1197
+ return { status: (await cfGet(token, "/user/tokens/verify")).status };
1198
+ };
1199
+ /**
1200
+ * List the resources that already exist in the account, querying ONLY the kinds the app declares
1201
+ * (one request per declared kind, in parallel), indexed for the preflight diff. Scoping to the
1202
+ * declared kinds keeps the API token minimal — an app with only KV never lists (and so never needs
1203
+ * read permission on) D1, R2, or Queues.
1204
+ *
1205
+ * @param token - The Cloudflare API token.
1206
+ * @param accountId - The Cloudflare account id to scope the listings to.
1207
+ * @param kinds - The resource kinds present in the manifest (the only kinds queried).
1208
+ * @returns The existing resources, indexed by kind (un-queried kinds resolve empty).
1209
+ * @throws {Error} When any listing request fails.
1210
+ * @example
1211
+ * ```ts
1212
+ * const existing = await listExisting(token, accountId, new Set(["kv", "d1"]));
1213
+ * if (existing.kv.has("SESSIONS")) { ... }
1214
+ * ```
1215
+ */
1216
+ const listExisting = async (token, accountId, kinds) => {
1217
+ const base = `/accounts/${accountId}`;
1218
+ const [kv, d1, r2, queues] = await Promise.all([
1219
+ kinds.has("kv") ? cfGet(token, `${base}/storage/kv/namespaces`) : Promise.resolve([]),
1220
+ kinds.has("d1") ? cfGet(token, `${base}/d1/database`) : Promise.resolve([]),
1221
+ kinds.has("r2") ? cfGet(token, `${base}/r2/buckets`) : Promise.resolve({}),
1222
+ kinds.has("queue") ? cfGet(token, `${base}/queues`) : Promise.resolve([])
1223
+ ]);
1224
+ return {
1225
+ kv: new Map(kv.map((namespace) => [namespace.title, namespace.id])),
1226
+ d1: new Map(d1.map((database) => [database.name, database.uuid])),
1227
+ r2: new Set((r2.buckets ?? []).map((bucket) => bucket.name)),
1228
+ queue: new Set(queues.map((queue) => queue.queue_name))
1229
+ };
1230
+ };
1231
+ //#endregion
1232
+ //#region src/plugins/deploy/auth/verify.ts
1233
+ /**
1234
+ * @file deploy plugin — `.env` token verification + account resolution.
1235
+ *
1236
+ * Reads CLOUDFLARE_API_TOKEN via ctx.env, verifies it is active against the Cloudflare API, and
1237
+ * resolves the account. Emits auth:verified. Throws a branded, actionable error (pointing at
1238
+ * `auth setup`) when the token is absent, invalid, or inactive — never an interactive login.
1239
+ * Node-only; never imported by the runtime Worker bundle.
1240
+ */
1241
+ /** Branded hint appended to every auth failure so the user knows the next step. */
1242
+ const SETUP_HINT = "Run `auth setup` for the exact token to create.";
1243
+ /**
1244
+ * Verify the `.env` Cloudflare API token and resolve its account.
1245
+ *
1246
+ * @param ctx - The deploy plugin context (env + emit).
1247
+ * @returns The verified auth status (account + id).
1248
+ * @throws {Error} When the token is absent, invalid/expired, or not active.
1249
+ * @example
1250
+ * ```ts
1251
+ * const { account, accountId } = await verifyAuth(ctx);
1252
+ * ```
1253
+ */
1254
+ const verifyAuth = async (ctx) => {
1255
+ const token = ctx.env.get("CLOUDFLARE_API_TOKEN");
1256
+ if (token === void 0 || token === "") throw new Error(`[moku-worker] CLOUDFLARE_API_TOKEN is not set. ${SETUP_HINT}`);
1257
+ let status;
1258
+ try {
1259
+ ({status} = await verifyToken(token));
1260
+ } catch (error) {
1261
+ throw new Error(`[moku-worker] Cloudflare API token is invalid or expired. ${SETUP_HINT}`, { cause: error });
1262
+ }
1263
+ if (status !== "active") throw new Error(`[moku-worker] Cloudflare API token is "${status}", not active. ${SETUP_HINT}`);
1264
+ const pinnedAccountId = ctx.env.get("CLOUDFLARE_ACCOUNT_ID");
1265
+ const account = pinnedAccountId === void 0 || pinnedAccountId === "" ? await resolveAccount(token) : {
1266
+ id: pinnedAccountId,
1267
+ name: pinnedAccountId
1268
+ };
1269
+ ctx.emit("auth:verified", {
1270
+ account: account.name,
1271
+ accountId: account.id,
1272
+ scopes: []
1273
+ });
1274
+ return {
1275
+ ok: true,
1276
+ account: account.name,
1277
+ accountId: account.id,
1278
+ scopes: []
1279
+ };
1280
+ };
1281
+ //#endregion
1282
+ //#region src/plugins/deploy/runner.ts
1283
+ /**
1284
+ * @file deploy plugin — wrangler subprocess wrapper (node:child_process).
1285
+ *
1286
+ * Spawns `wrangler` with the given args and resolves the deployed URL
1287
+ * (extracted from stdout for `wrangler deploy`), or the full stdout for other verbs.
1288
+ * This module is node-only; never imported by the runtime Worker bundle.
1289
+ */
1290
+ /**
1291
+ * Extract the deployed URL from `wrangler deploy` stdout.
1292
+ * Wrangler prints a line like: "Published my-worker (1.23 sec) https://..."
1293
+ * or "Deployed my-worker (1.23 sec) https://...".
1294
+ *
1295
+ * @param output - The combined stdout from wrangler deploy.
1296
+ * @returns The deployed URL, or empty string when not found.
1297
+ * @example
1298
+ * ```ts
1299
+ * extractDeployedUrl("Deployed my-worker (0.5 sec) https://my-worker.workers.dev");
1300
+ * // "https://my-worker.workers.dev"
1301
+ * ```
1302
+ */
1303
+ const extractDeployedUrl = (output) => {
1304
+ return /https:\/\/[^\s]+\.workers\.dev[^\s]*/u.exec(output)?.[0] ?? "";
1305
+ };
1306
+ /**
1307
+ * Spawn `wrangler` with the given args and resolve the output string.
1308
+ * For `wrangler deploy`, the resolved value is the deployed URL parsed from stdout.
1309
+ * For all other verbs (dev, kv namespace create, etc.), the resolved value is stdout.
1310
+ *
1311
+ * @param args - Wrangler CLI arguments (e.g. ["deploy", "--config", "wrangler.jsonc"]).
1312
+ * @returns Resolves with the deployed URL (deploy verb) or full stdout (other verbs).
1313
+ * @throws {Error} When wrangler exits with a non-zero code.
1314
+ * @example
1315
+ * ```ts
1316
+ * const url = await runWrangler(["deploy", "--config", "wrangler.jsonc"]);
1317
+ * await runWrangler(["kv", "namespace", "create", "CACHE"]);
1318
+ * ```
1319
+ */
1320
+ const runWrangler = (args) => new Promise((resolve, reject) => {
1321
+ const chunks = [];
1322
+ const errChunks = [];
1323
+ const child = (0, node_child_process.spawn)("wrangler", args, {
1324
+ env: { ...process.env },
1325
+ stdio: [
1326
+ "ignore",
1327
+ "pipe",
1328
+ "pipe"
1329
+ ]
1330
+ });
1331
+ child.stdout.on("data", (chunk) => {
1332
+ chunks.push(chunk);
1333
+ });
1334
+ child.stderr.on("data", (chunk) => {
1335
+ errChunks.push(chunk);
1336
+ });
1337
+ child.on("error", (err) => {
1338
+ reject(/* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${err.message}`));
1339
+ });
1340
+ child.on("close", (code) => {
1341
+ const stdout = Buffer.concat(chunks).toString("utf8");
1342
+ const stderr = Buffer.concat(errChunks).toString("utf8");
1343
+ if (code !== 0) {
1344
+ reject(/* @__PURE__ */ new Error(`[moku-worker] wrangler exited with code ${String(code)}.\n ${stderr || stdout}`));
1345
+ return;
1346
+ }
1347
+ resolve(args[0] === "deploy" ? extractDeployedUrl(stdout) : stdout);
1348
+ });
1349
+ });
1350
+ /**
1351
+ * Spawn `wrangler` with the given args, inheriting stdio so its output streams live to the user's
1352
+ * terminal (used by the generic passthrough and long-lived commands like `tail`).
1353
+ *
1354
+ * @param args - Wrangler CLI arguments (e.g. ["kv", "namespace", "list"]).
1355
+ * @returns Resolves once wrangler exits successfully.
1356
+ * @throws {Error} When wrangler cannot be spawned or exits non-zero.
1357
+ * @example
1358
+ * ```ts
1359
+ * await runWranglerInherit(["kv", "namespace", "list"]);
1360
+ * ```
1361
+ */
1362
+ const runWranglerInherit = (args) => {
1363
+ return new Promise((resolve, reject) => {
1364
+ const child = (0, node_child_process.spawn)("wrangler", args, { stdio: "inherit" });
1365
+ child.on("error", (error) => {
1366
+ reject(/* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${error.message}`));
1367
+ });
1368
+ child.on("close", (code) => {
1369
+ if (code === 0) {
1370
+ resolve();
1371
+ return;
1372
+ }
1373
+ reject(/* @__PURE__ */ new Error(`[moku-worker] wrangler exited with code ${String(code)}.`));
1374
+ });
1375
+ });
1376
+ };
1377
+ //#endregion
1378
+ //#region src/plugins/deploy/dev/build.ts
1379
+ /**
1380
+ * @file deploy plugin — dev site-rebuild resolution.
1381
+ *
1382
+ * Resolves HOW to rebuild the Moku web site on change: the in-process `webBuild` hook (preferred,
1383
+ * fast, typed — passed call-time from the consumer's script or set as a config default) → a
1384
+ * `buildCommand` shell string → an auto-detected `scripts/build.ts`. When nothing is configured,
1385
+ * dev serves the worker only and says so. Subprocesses inherit the parent env by default.
1386
+ * Node-only; never imported by the runtime Worker bundle.
1387
+ */
1388
+ /** Convention build script auto-detected when no webBuild/buildCommand is configured. */
1389
+ const AUTO_DETECT = "scripts/build.ts";
1390
+ /**
1391
+ * Opportunistically read a numeric `files` count off an arbitrary web build result. A real web
1392
+ * build returns its own summary shape (the worker framework cannot know it), so anything without a
1393
+ * numeric `files` field reports 0.
1394
+ *
1395
+ * @param result - The resolved value of a {@link WebBuild} hook (any shape).
1396
+ * @returns The `files` count when present and numeric, else 0.
1397
+ * @example
1398
+ * ```ts
1399
+ * fileCountOf({ files: 12 }); // 12
1400
+ * fileCountOf({ outDir: "dist", pageCount: 4 }); // 0
1401
+ * ```
1402
+ */
1403
+ const fileCountOf = (result) => {
1404
+ if (typeof result === "object" && result !== null && "files" in result) {
1405
+ const { files } = result;
1406
+ return typeof files === "number" ? files : 0;
1407
+ }
1408
+ return 0;
1409
+ };
1410
+ /**
1411
+ * Run a shell build command, resolving on a zero exit and rejecting otherwise.
1412
+ *
1413
+ * @param command - The shell command to run (the consumer's own configured build).
1414
+ * @returns Resolves once the command exits successfully.
1415
+ * @throws {Error} When the command fails to start or exits non-zero.
1416
+ * @example
1417
+ * ```ts
1418
+ * await runShellBuild("bun run scripts/build.ts");
1419
+ * ```
1420
+ */
1421
+ const runShellBuild = (command) => {
1422
+ return new Promise((resolve, reject) => {
1423
+ const child = (0, node_child_process.spawn)(command, {
1424
+ shell: true,
1425
+ stdio: "inherit"
1426
+ });
1427
+ child.on("error", (error) => {
1428
+ reject(/* @__PURE__ */ new Error(`[moku-worker] site build failed to start.\n ${error.message}`));
1429
+ });
1430
+ child.on("close", (code) => {
1431
+ if (code === 0) {
1432
+ resolve();
1433
+ return;
1434
+ }
1435
+ reject(/* @__PURE__ */ new Error(`[moku-worker] site build exited with code ${String(code)}.`));
1436
+ });
1437
+ });
1438
+ };
1439
+ /**
1440
+ * Rebuild the Moku web site using the resolved strategy: the call-time `webBuild` hook (the
1441
+ * script-driven path), else the `webBuild` config default, else the `buildCommand` shell string,
1442
+ * else an auto-detected `scripts/build.ts`. A hook's result is normalized to a `{ files }` count
1443
+ * (0 when the hook reports none, and for the shell path where it is unknown).
1444
+ *
1445
+ * @param ctx - The deploy plugin context (config + emit).
1446
+ * @param webBuild - Optional call-time web build hook (takes precedence over `ctx.config.webBuild`).
1447
+ * @returns The rebuilt file count (0 for the shell path / a countless hook).
1448
+ * @throws {Error} When the resolved shell build fails.
1449
+ * @example
1450
+ * ```ts
1451
+ * const { files } = await buildSite(ctx, () => web.cli.build());
1452
+ * ```
1453
+ */
1454
+ const buildSite = async (ctx, webBuild) => {
1455
+ const hook = webBuild ?? ctx.config.webBuild;
1456
+ if (hook !== void 0) return { files: fileCountOf(await hook()) };
1457
+ const command = ctx.config.buildCommand || ((0, node_fs.existsSync)(AUTO_DETECT) ? `bun run ${AUTO_DETECT}` : "");
1458
+ if (command === "") {
1459
+ ctx.emit("dev:error", { message: "No site build configured (pass webBuild or set buildCommand); serving worker only." });
1460
+ return { files: 0 };
1461
+ }
1462
+ await runShellBuild(command);
1463
+ return { files: 0 };
1464
+ };
1465
+ //#endregion
1466
+ //#region src/plugins/deploy/dev/watch.ts
1467
+ /**
1468
+ * @file deploy plugin — debounced filesystem watcher for dev.
1469
+ *
1470
+ * Watches the top-level directories implied by the config globs (recursive) and fires a debounced
1471
+ * change callback with the last changed path. Uses node:fs.watch — no extra dependency.
1472
+ * Node-only; never imported by the runtime Worker bundle.
1473
+ */
1474
+ /**
1475
+ * Derive the set of top-level directories to watch from glob patterns.
1476
+ *
1477
+ * @param globs - Watch globs (e.g. ["src/**\/*.ts", "public/**\/*"]).
1478
+ * @returns The distinct top-level directories (e.g. ["src", "public"]).
1479
+ * @example
1480
+ * ```ts
1481
+ * watchDirectories(["src/**\/*.ts", "public/**\/*"]); // ["src", "public"]
1482
+ * ```
1483
+ */
1484
+ const watchDirectories = (globs) => {
1485
+ const directories = /* @__PURE__ */ new Set();
1486
+ for (const glob of globs) {
1487
+ const globStart = glob.search(/[*?[{]/u);
1488
+ const top = (globStart === -1 ? node_path.default.dirname(glob) : glob.slice(0, globStart)).split(/[/\\]/u).find((segment) => segment !== "") ?? ".";
1489
+ directories.add(top);
1490
+ }
1491
+ return [...directories];
1492
+ };
1493
+ /**
1494
+ * Watch the directories implied by `globs` and fire `onChange` (debounced by `debounceMs`) with
1495
+ * the last changed path. Missing directories are skipped silently.
1496
+ *
1497
+ * @param globs - Watch globs.
1498
+ * @param debounceMs - Coalesce rapid changes into one callback within this window.
1499
+ * @param onChange - Called with the last changed path after the debounce settles.
1500
+ * @returns A handle whose close() stops all watchers and cancels any pending callback.
1501
+ * @example
1502
+ * ```ts
1503
+ * const handle = watchPaths(["src/**\/*.ts"], 120, p => rebuild(p));
1504
+ * handle.close();
1505
+ * ```
1506
+ */
1507
+ const watchPaths = (globs, debounceMs, onChange) => {
1508
+ let timer;
1509
+ let lastPath = "";
1510
+ const fire = (changedPath) => {
1511
+ lastPath = changedPath;
1512
+ if (timer !== void 0) clearTimeout(timer);
1513
+ timer = setTimeout(() => {
1514
+ onChange(lastPath);
1515
+ }, debounceMs);
1516
+ };
1517
+ const watchers = [];
1518
+ for (const directory of watchDirectories(globs)) {
1519
+ if (!(0, node_fs.existsSync)(directory)) continue;
1520
+ watchers.push((0, node_fs.watch)(directory, { recursive: true }, (_event, filename) => {
1521
+ if (filename !== null) fire(node_path.default.join(directory, filename.toString()));
1522
+ }));
1523
+ }
1524
+ return { close: () => {
1525
+ if (timer !== void 0) clearTimeout(timer);
1526
+ for (const watcher of watchers) watcher.close();
1527
+ } };
1528
+ };
1529
+ //#endregion
1530
+ //#region src/plugins/deploy/dev/runner.ts
1531
+ /**
1532
+ * @file deploy plugin — dev watch/recompile orchestrator.
1533
+ *
1534
+ * One long-lived session: cold-build the Moku site, optionally apply local D1 migrations, spawn
1535
+ * `wrangler dev --live-reload` ONCE, then watch the site sources and rebuild on change (wrangler's
1536
+ * asset server live-reloads the browser). Build failures keep the session serving the last good
1537
+ * build. Tears down cleanly on SIGINT. Side-effecting work is injected via DevDeps so the
1538
+ * orchestration is unit-testable without real processes, watchers, or signals.
1539
+ * Node-only; never imported by the runtime Worker bundle.
1540
+ */
1541
+ /** Grace period (ms) before escalating a hung `wrangler dev` shutdown from SIGINT to SIGKILL. */
1542
+ const STOP_GRACE_MS = 4e3;
1543
+ /**
1544
+ * Spawn the long-lived `wrangler dev` child (inherits the parent env; non-blocking).
1545
+ *
1546
+ * `whenExited` settles when the child exits OR fails to spawn — the `error` listener is essential:
1547
+ * a missing/unexecutable wrangler emits `error` (not `exit`), which is otherwise unhandled (crashes
1548
+ * the process) and would leave `whenExited` pending forever, hanging `stop()`. `stop()` shuts
1549
+ * wrangler down the way its own Ctrl+C does — a graceful SIGINT, then a SIGKILL escalation if it has
1550
+ * not exited within {@link STOP_GRACE_MS} — resolving only once it is gone; a spawn failure is
1551
+ * surfaced as a thrown branded error so the caller can render it. Without the wait, the
1552
+ * inherited-stdio child can keep the parent alive after the watcher closes ("stuck on stopping").
1553
+ *
1554
+ * @param args - The `wrangler dev …` arguments.
1555
+ * @returns A handle: `whenExited` (settles on exit/spawn-failure) and `stop()` (resolves once gone).
1556
+ * @example
1557
+ * ```ts
1558
+ * const child = spawnWranglerDev(["dev", "--port", "8787"]);
1559
+ * await Promise.race([untilSignal(), child.whenExited]);
1560
+ * await child.stop();
1561
+ * ```
1562
+ */
1563
+ const spawnWranglerDev = (args) => {
1564
+ const child = (0, node_child_process.spawn)("wrangler", args, { stdio: "inherit" });
1565
+ let spawnError;
1566
+ const whenExited = new Promise((resolve) => {
1567
+ child.once("exit", () => {
1568
+ resolve();
1569
+ });
1570
+ child.once("error", (error) => {
1571
+ spawnError = /* @__PURE__ */ new Error(`[moku-worker] Failed to spawn wrangler.\n ${error.message}`);
1572
+ resolve();
1573
+ });
1574
+ });
1575
+ const stop = async () => {
1576
+ if (spawnError !== void 0) throw spawnError;
1577
+ if (child.exitCode !== null || child.signalCode !== null || child.pid === void 0) return;
1578
+ child.kill("SIGINT");
1579
+ const forceKill = setTimeout(() => child.kill("SIGKILL"), STOP_GRACE_MS);
1580
+ await whenExited;
1581
+ clearTimeout(forceKill);
1582
+ };
1583
+ return {
1584
+ stop,
1585
+ whenExited
1586
+ };
1587
+ };
1588
+ /**
1589
+ * Resolve when the user first interrupts the dev session (SIGINT).
1590
+ *
1591
+ * @returns A promise that settles on the first SIGINT.
1592
+ * @example
1593
+ * ```ts
1594
+ * await waitForSigint();
1595
+ * ```
1596
+ */
1597
+ const waitForSigint = () => {
1598
+ return new Promise((resolve) => {
1599
+ process.once("SIGINT", () => {
1600
+ resolve();
1601
+ });
1602
+ });
1603
+ };
1604
+ /**
1605
+ * Wall-clock timestamp in ms (extracted so realDevDeps holds only named references).
1606
+ *
1607
+ * @returns The current time in milliseconds.
1608
+ * @example
1609
+ * ```ts
1610
+ * const t = nowMs();
1611
+ * ```
1612
+ */
1613
+ const nowMs = () => Date.now();
1614
+ /**
1615
+ * Build the real (side-effecting) dev deps used by api.dev(). Subprocesses inherit the parent env.
1616
+ *
1617
+ * @returns The production DevDeps (real spawn / fs.watch / SIGINT / Date.now).
1618
+ * @example
1619
+ * ```ts
1620
+ * await runDev(ctx, opts, realDevDeps());
1621
+ * ```
1622
+ */
1623
+ const realDevDeps = () => ({
1624
+ build: buildSite,
1625
+ runWrangler,
1626
+ spawnDev: spawnWranglerDev,
1627
+ watch: watchPaths,
1628
+ untilSignal: waitForSigint,
1629
+ now: nowMs
1630
+ });
1631
+ /**
1632
+ * The d1 binding to migrate locally, when a d1 plugin is present in the app.
1633
+ *
1634
+ * @param ctx - The deploy plugin context.
1635
+ * @returns The d1 binding name, or undefined when no d1 plugin is present.
1636
+ * @example
1637
+ * ```ts
1638
+ * const binding = d1Binding(ctx); // "DB" | undefined
1639
+ * ```
1640
+ */
1641
+ const d1Binding = (ctx) => ctx.has("d1") ? ctx.require(d1Plugin).deployManifest().binding : void 0;
1642
+ /**
1643
+ * Rebuild the site once and announce the result. A failed build keeps the session alive (it just
1644
+ * emits dev:error and serves the last good build).
1645
+ *
1646
+ * @param ctx - The deploy plugin context.
1647
+ * @param deps - The injected dev deps.
1648
+ * @param changedPath - The path that triggered the rebuild.
1649
+ * @param webBuild - Optional call-time web build hook threaded into the rebuild.
1650
+ * @returns Resolves once the rebuild attempt completes.
1651
+ * @example
1652
+ * ```ts
1653
+ * await rebuild(ctx, deps, "src/app.tsx", () => web.cli.build());
1654
+ * ```
1655
+ */
1656
+ const rebuild = async (ctx, deps, changedPath, webBuild) => {
1657
+ ctx.emit("dev:phase", {
1658
+ phase: "rebuild",
1659
+ detail: changedPath
1660
+ });
1661
+ const started = deps.now();
1662
+ try {
1663
+ const { files } = await deps.build(ctx, webBuild);
1664
+ ctx.emit("dev:rebuilt", {
1665
+ files,
1666
+ ms: deps.now() - started
1667
+ });
1668
+ } catch (error) {
1669
+ ctx.emit("dev:error", { message: error instanceof Error ? error.message : String(error) });
1670
+ }
1671
+ };
1672
+ /**
1673
+ * Run a long-lived dev session: cold build → (local d1 migrate) → spawn `wrangler dev` →
1674
+ * watch + rebuild on change → teardown on signal.
1675
+ *
1676
+ * @param ctx - The deploy plugin context (config + emit + require/has).
1677
+ * @param opts - Optional options.
1678
+ * @param opts.port - Local dev port (default 8787).
1679
+ * @param opts.webBuild - Web build hook (re)run on cold build + each change (e.g. `() => web.cli.build()`).
1680
+ * @param deps - Injected side effects (real ones from realDevDeps in production).
1681
+ * @returns Resolves when the session ends (SIGINT).
1682
+ * @example
1683
+ * ```ts
1684
+ * await runDev(ctx, { port: 8787, webBuild: () => web.cli.build() }, realDevDeps());
1685
+ * ```
1686
+ */
1687
+ const runDev = async (ctx, opts, deps) => {
1688
+ const port = opts?.port ?? 8787;
1689
+ const webBuild = opts?.webBuild;
1690
+ ctx.emit("dev:phase", {
1691
+ phase: "build",
1692
+ detail: "site"
1693
+ });
1694
+ await deps.build(ctx, webBuild);
1695
+ const binding = d1Binding(ctx);
1696
+ if (ctx.config.migrateLocal && binding !== void 0) {
1697
+ ctx.emit("dev:phase", {
1698
+ phase: "migrate",
1699
+ detail: "d1 (local)"
1700
+ });
1701
+ await deps.runWrangler([
1702
+ "d1",
1703
+ "migrations",
1704
+ "apply",
1705
+ binding,
1706
+ "--local"
1707
+ ]);
1708
+ }
1709
+ ctx.emit("dev:phase", {
1710
+ phase: "serve",
1711
+ detail: `http://localhost:${String(port)}`
1712
+ });
1713
+ const child = deps.spawnDev([
1714
+ "dev",
1715
+ "--port",
1716
+ String(port),
1717
+ "--config",
1718
+ ctx.config.configFile,
1719
+ "--live-reload"
1720
+ ]);
1721
+ const watcher = deps.watch(ctx.config.watch, ctx.config.debounceMs, (changedPath) => rebuild(ctx, deps, changedPath, webBuild));
1722
+ await Promise.race([deps.untilSignal(), child.whenExited]);
1723
+ ctx.emit("dev:phase", { phase: "stopping" });
1724
+ watcher.close();
1725
+ await child.stop();
1726
+ };
1727
+ //#endregion
1728
+ //#region src/plugins/deploy/infra/plan.ts
1729
+ /**
1730
+ * Decide whether a single declared resource already exists in the account, recovering its id
1731
+ * (kv/d1) when it does. Durable Objects are config-only (they ship with the script), so they are
1732
+ * always treated as "missing" — provisioning them is a no-op that just records the binding.
1733
+ *
1734
+ * @param resource - The declared resource descriptor.
1735
+ * @param existing - The indexed set of resources already in the account.
1736
+ * @returns Whether it exists, plus the captured id for kv/d1.
1737
+ * @example
1738
+ * ```ts
1739
+ * checkExisting({ kind: "kv", binding: "SESSIONS" }, existing); // { exists: true, id: "ns123" }
1740
+ * ```
1741
+ */
1742
+ const checkExisting = (resource, existing) => {
1743
+ switch (resource.kind) {
1744
+ case "kv": {
1745
+ const id = existing.kv.get(resource.binding);
1746
+ return id === void 0 ? { exists: false } : {
1747
+ exists: true,
1748
+ id
1749
+ };
1750
+ }
1751
+ case "d1": {
1752
+ const id = existing.d1.get(resource.binding);
1753
+ return id === void 0 ? { exists: false } : {
1754
+ exists: true,
1755
+ id
1756
+ };
1757
+ }
1758
+ case "r2": return { exists: existing.r2.has(resource.bucket) };
1759
+ case "queue": return { exists: resource.producers.every((producer) => existing.queue.has(producer)) };
1760
+ case "do": return { exists: false };
1761
+ }
1762
+ };
1763
+ /**
1764
+ * Run the read-only infra preflight: resolve the account, list existing resources, diff against
1765
+ * the manifest, emit `provision:plan`, and return the plan. Writes nothing.
1766
+ *
1767
+ * @param ctx - The deploy plugin context (env + emit).
1768
+ * @param manifest - The assembled (or caller-supplied) deploy manifest.
1769
+ * @returns The infra plan: existing (with ids) vs missing resources.
1770
+ * @throws {Error} When the token is absent/invalid or a Cloudflare listing fails.
1771
+ * @example
1772
+ * ```ts
1773
+ * const plan = await planInfra(ctx, manifest);
1774
+ * ```
1775
+ */
1776
+ const planInfra = async (ctx, manifest) => {
1777
+ const token = ctx.env.require("CLOUDFLARE_API_TOKEN");
1778
+ const pinnedAccountId = ctx.env.get("CLOUDFLARE_ACCOUNT_ID");
1779
+ const account = pinnedAccountId ? {
1780
+ id: pinnedAccountId,
1781
+ name: pinnedAccountId
1782
+ } : await resolveAccount(token);
1783
+ const kinds = /* @__PURE__ */ new Set();
1784
+ for (const resource of manifest.resources) if (resource.kind !== "do") kinds.add(resource.kind);
1785
+ const existing = await listExisting(token, account.id, kinds);
1786
+ const exists = [];
1787
+ const missing = [];
1788
+ for (const resource of manifest.resources) {
1789
+ const check = checkExisting(resource, existing);
1790
+ if (check.exists) exists.push(check.id === void 0 ? { resource } : {
1791
+ resource,
1792
+ id: check.id
1793
+ });
1794
+ else missing.push(resource);
1795
+ }
1796
+ ctx.emit("provision:plan", {
1797
+ exists: exists.length,
1798
+ missing: missing.length,
1799
+ account: account.name
1800
+ });
1801
+ return {
1802
+ account: account.name,
1803
+ accountId: account.id,
1804
+ exists,
1805
+ missing
1806
+ };
1807
+ };
1808
+ //#endregion
1809
+ //#region src/plugins/deploy/providers/d1.ts
1810
+ /**
1811
+ * @file deploy plugin — D1 provisioning adapter.
1812
+ *
1813
+ * Creates a Cloudflare D1 database via `wrangler d1 create <binding>`, captures the created
1814
+ * database id from wrangler's output (so writeWranglerConfig can write a real `database_id`
1815
+ * instead of an empty placeholder), and applies migrations when declared.
1816
+ * Node-only; never imported by the runtime Worker bundle.
1817
+ */
1818
+ /**
1819
+ * Parse the created D1 database id from `wrangler d1 create` output.
1820
+ * Wrangler prints the new binding as JSON (`"database_id": "..."`) or TOML
1821
+ * (`database_id = "..."`); the leading boundary keeps the match anchored to the field name.
1822
+ *
1823
+ * @param output - Raw stdout from the wrangler create command.
1824
+ * @returns The database id, or undefined when none is found.
1825
+ * @example
1826
+ * ```ts
1827
+ * parseD1DatabaseId('{ "database_id": "uuid-1234" }'); // "uuid-1234"
1828
+ * ```
1829
+ */
1830
+ const parseD1DatabaseId = (output) => {
1831
+ return /(?:^|[\s,{])"?database_id"?\s*[:=]\s*"([^"]+)"/m.exec(output)?.[1];
1832
+ };
1833
+ /**
1834
+ * Provision a D1 database via `wrangler d1 create`, capture its id, and apply migrations.
1835
+ *
1836
+ * @param manifest - The D1 resource descriptor.
1837
+ * @param _ci - Whether running non-interactively.
1838
+ * @returns The captured database id when wrangler reported one, else an empty outcome.
1839
+ * @example
1840
+ * ```ts
1841
+ * const { id } = await provisionD1({ kind: "d1", binding: "DB", migrations: "./migrations" }, false);
1842
+ * ```
1843
+ */
1844
+ const provisionD1 = async (manifest, _ci) => {
1845
+ const id = parseD1DatabaseId(await runWrangler([
1846
+ "d1",
1847
+ "create",
1848
+ manifest.binding
1849
+ ]));
1850
+ if (manifest.migrations) await runWrangler([
1851
+ "d1",
1852
+ "migrations",
1853
+ "apply",
1854
+ manifest.binding,
1855
+ "--local"
1856
+ ]);
1857
+ return id ? { id } : {};
1858
+ };
1859
+ //#endregion
1860
+ //#region src/plugins/deploy/providers/do.ts
1861
+ /**
1862
+ * Provision Durable Object bindings. DOs are config-driven (no `wrangler do create` command
1863
+ * exists) — the actual binding entries are written by writeWranglerConfig. This function is
1864
+ * a resolved no-op for the dispatch step.
1865
+ *
1866
+ * @param _manifest - The Durable Objects resource descriptor.
1867
+ * @param _ci - Whether running non-interactively.
1868
+ * @returns Resolves immediately (DOs are config-only provisioning).
1869
+ * @example
1870
+ * ```ts
1871
+ * await provisionDurableObject({ kind: "do", bindings: { counter: "COUNTER" } }, false);
1872
+ * ```
1873
+ */
1874
+ const provisionDurableObject = async (_manifest, _ci) => {};
1875
+ //#endregion
1876
+ //#region src/plugins/deploy/providers/kv.ts
1877
+ /**
1878
+ * @file deploy plugin — KV provisioning adapter.
1879
+ *
1880
+ * Creates a Cloudflare KV namespace via `wrangler kv namespace create <binding>` and captures
1881
+ * the created namespace id from wrangler's output, so writeWranglerConfig can write a real `id`
1882
+ * (not an empty placeholder) into the generated wrangler config — otherwise the binding resolves
1883
+ * to nothing at runtime. Node-only; never imported by the runtime Worker bundle.
1884
+ */
1885
+ /**
1886
+ * Parse the created KV namespace id from `wrangler kv namespace create` output.
1887
+ * Wrangler prints the new binding as JSON (`"id": "..."`) or TOML (`id = "..."`); the leading
1888
+ * boundary (start / whitespace / `{` / `,`) keeps the match off a longer identifier such as
1889
+ * `kv_namespace_id`.
1890
+ *
1891
+ * @param output - Raw stdout from the wrangler create command.
1892
+ * @returns The namespace id, or undefined when none is found.
1893
+ * @example
1894
+ * ```ts
1895
+ * parseKvNamespaceId('{ "id": "abc123" }'); // "abc123"
1896
+ * ```
1897
+ */
1898
+ const parseKvNamespaceId = (output) => {
1899
+ return /(?:^|[\s,{])"?id"?\s*[:=]\s*"([^"]+)"/m.exec(output)?.[1];
1900
+ };
1901
+ /**
1902
+ * Provision a KV namespace via `wrangler kv namespace create` and capture its id.
1903
+ *
1904
+ * @param manifest - The KV resource descriptor.
1905
+ * @param _ci - Whether running non-interactively (passed through; wrangler respects env vars).
1906
+ * @returns The captured namespace id when wrangler reported one, else an empty outcome.
1907
+ * @example
1908
+ * ```ts
1909
+ * const { id } = await provisionKv({ kind: "kv", binding: "CACHE" }, false);
1910
+ * ```
1911
+ */
1912
+ const provisionKv = async (manifest, _ci) => {
1913
+ const id = parseKvNamespaceId(await runWrangler([
1914
+ "kv",
1915
+ "namespace",
1916
+ "create",
1917
+ manifest.binding
1918
+ ]));
1919
+ return id ? { id } : {};
1920
+ };
1921
+ //#endregion
1922
+ //#region src/plugins/deploy/providers/queues.ts
1923
+ /**
1924
+ * @file deploy plugin — Queues provisioning adapter.
1925
+ *
1926
+ * Creates Cloudflare Queues via `wrangler queues create <name>` for each producer.
1927
+ * Node-only; never imported by the runtime Worker bundle.
1928
+ */
1929
+ /**
1930
+ * Provision queues via `wrangler queues create` for each declared producer.
1931
+ *
1932
+ * @param manifest - The queue resource descriptor.
1933
+ * @param _ci - Whether running non-interactively.
1934
+ * @returns Resolves once all queues are created.
1935
+ * @example
1936
+ * ```ts
1937
+ * await provisionQueue({ kind: "queue", producers: ["orders"] }, false);
1938
+ * ```
1939
+ */
1940
+ const provisionQueue = async (manifest, _ci) => {
1941
+ for (const producer of manifest.producers) await runWrangler([
1942
+ "queues",
1943
+ "create",
1944
+ producer
1945
+ ]);
1946
+ };
1947
+ //#endregion
1948
+ //#region src/plugins/deploy/providers/r2.ts
1949
+ /**
1950
+ * @file deploy plugin — R2 provisioning + asset upload adapter.
1951
+ *
1952
+ * Provides two exports:
1953
+ * - `provisionR2`: creates an R2 bucket via `wrangler r2 bucket create`.
1954
+ * - `uploadDirToR2`: walks a directory recursively and uploads each file via
1955
+ * `wrangler r2 object put`, returning the uploaded file count.
1956
+ *
1957
+ * Node-only; never imported by the runtime Worker bundle.
1958
+ */
1959
+ /**
1960
+ * Provision an R2 bucket via `wrangler r2 bucket create`.
1961
+ *
1962
+ * @param manifest - The R2 resource descriptor.
1963
+ * @param _ci - Whether running non-interactively.
1964
+ * @returns Resolves once the bucket is created.
1965
+ * @example
1966
+ * ```ts
1967
+ * await provisionR2({ kind: "r2", bucket: "ASSETS" }, false);
1968
+ * ```
1969
+ */
1970
+ const provisionR2 = async (manifest, _ci) => {
1971
+ await runWrangler([
1972
+ "r2",
1973
+ "bucket",
1974
+ "create",
1975
+ manifest.bucket
1976
+ ]);
1977
+ };
1978
+ /**
1979
+ * Walk a directory recursively and return all file paths (absolute).
1980
+ *
1981
+ * @param directory - Directory path to walk.
1982
+ * @returns All file paths found under the directory.
1983
+ * @example
1984
+ * ```ts
1985
+ * const files = await walkDir("./public");
1986
+ * ```
1987
+ */
1988
+ const walkDir = async (directory) => {
1989
+ const entries = await (0, node_fs_promises.readdir)(directory);
1990
+ const results = [];
1991
+ for (const entry of entries) {
1992
+ const fullPath = node_path.default.join(directory, entry);
1993
+ if ((await (0, node_fs_promises.stat)(fullPath)).isDirectory()) {
1994
+ const nested = await walkDir(fullPath);
1995
+ results.push(...nested);
1996
+ } else results.push(fullPath);
1997
+ }
1998
+ return results;
1999
+ };
2000
+ /**
2001
+ * Upload a directory to an R2 bucket and return the uploaded file count.
2002
+ * Each file is uploaded via `wrangler r2 object put <bucket>/<key> --file <path>`.
2003
+ *
2004
+ * @param bucket - The R2 bucket binding name.
2005
+ * @param directory - The directory to upload.
2006
+ * @returns The number of files uploaded.
2007
+ * @example
2008
+ * ```ts
2009
+ * const count = await uploadDirToR2("ASSETS", "./public");
2010
+ * ```
2011
+ */
2012
+ const uploadDirToR2 = async (bucket, directory) => {
2013
+ const files = await walkDir(directory);
2014
+ for (const filePath of files) await runWrangler([
2015
+ "r2",
2016
+ "object",
2017
+ "put",
2018
+ `${bucket}/${node_path.default.relative(directory, filePath)}`,
2019
+ "--file",
2020
+ filePath
2021
+ ]);
2022
+ return files.length;
2023
+ };
2024
+ //#endregion
2025
+ //#region src/plugins/deploy/providers/index.ts
2026
+ /**
2027
+ * Dispatch a resource descriptor to the matching provider's provisioning routine.
2028
+ *
2029
+ * @param resource - The resource descriptor to provision.
2030
+ * @param ci - Whether running non-interactively.
2031
+ * @returns The provisioning outcome — `{ id }` for kv/d1, `{}` for r2/queue/do.
2032
+ * @example
2033
+ * ```ts
2034
+ * const { id } = await provisionResource({ kind: "kv", binding: "CACHE" }, false);
2035
+ * await provisionResource({ kind: "r2", bucket: "ASSETS" }, false); // {}
2036
+ * ```
2037
+ */
2038
+ const provisionResource = async (resource, ci) => {
2039
+ switch (resource.kind) {
2040
+ case "kv": return provisionKv(resource, ci);
2041
+ case "d1": return provisionD1(resource, ci);
2042
+ case "r2":
2043
+ await provisionR2(resource, ci);
2044
+ return {};
2045
+ case "queue":
2046
+ await provisionQueue(resource, ci);
2047
+ return {};
2048
+ case "do":
2049
+ await provisionDurableObject(resource, ci);
2050
+ return {};
2051
+ }
2052
+ };
2053
+ //#endregion
2054
+ //#region src/plugins/deploy/tty.ts
2055
+ /**
2056
+ * @file deploy plugin — TTY detection (isolated so the guided flow is testable).
2057
+ *
2058
+ * The guided deploy only prompts on an interactive terminal; in a pipe or CI it must never block
2059
+ * on stdin. Kept in its own module so tests can mock it without stubbing `process.stdout`.
2060
+ * Node-only; never imported by the runtime Worker bundle.
2061
+ */
2062
+ /**
2063
+ * Whether stdout is an interactive TTY (so prompts are safe to show).
2064
+ *
2065
+ * @returns True when stdout is a terminal.
2066
+ * @example
2067
+ * ```ts
2068
+ * if (stdoutIsTty()) await prompts.confirm("Deploy?");
2069
+ * ```
2070
+ */
2071
+ const stdoutIsTty = () => process.stdout.isTTY === true;
2072
+ //#endregion
2073
+ //#region src/plugins/deploy/wrangler-config.ts
2074
+ /**
2075
+ * @file deploy plugin — wrangler config generation + scaffold.
2076
+ *
2077
+ * Provides two exports:
2078
+ * - `writeWranglerConfig`: generates/updates a wrangler.jsonc file from an ExternalManifest.
2079
+ * Non-destructive: preserves existing top-level keys not managed by deploy.
2080
+ * - `scaffoldWranglerAndCi`: creates a minimal starter wrangler config when the file does not
2081
+ * exist yet; idempotent (leaves existing files untouched).
2082
+ *
2083
+ * Node-only; never imported by the runtime Worker bundle.
2084
+ */
2085
+ /**
2086
+ * Strip JSONC line- and block-comments, then JSON.parse the result.
2087
+ *
2088
+ * @param source - Raw JSONC file contents.
2089
+ * @returns The parsed object.
2090
+ * @example
2091
+ * ```ts
2092
+ * const cfg = parseJsonc('{ "name": "w" } // trailing comment');
2093
+ * ```
2094
+ */
2095
+ const parseJsonc = (source) => {
2096
+ const stripped = source.replaceAll(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/gu, "");
2097
+ return JSON.parse(stripped);
2098
+ };
2099
+ /**
2100
+ * Build the wrangler `kv_namespaces` array from the manifest's kv resources.
2101
+ *
2102
+ * @param resources - All resource descriptors from the manifest.
2103
+ * @param ids - Captured Cloudflare ids keyed by binding; the entry's `id` is filled from here.
2104
+ * @returns One wrangler KV namespace entry per kv resource (real `id` when known, else "").
2105
+ * @example
2106
+ * ```ts
2107
+ * const kv = buildKvNamespaces([{ kind: "kv", binding: "CACHE" }], { CACHE: "ns123" });
2108
+ * ```
2109
+ */
2110
+ const buildKvNamespaces = (resources, ids) => resources.filter((resource) => resource.kind === "kv").map((resource) => ({
2111
+ binding: resource.binding,
2112
+ id: ids[resource.binding] ?? ""
2113
+ }));
2114
+ /**
2115
+ * Build the wrangler `r2_buckets` array from the manifest's r2 resources.
2116
+ *
2117
+ * @param resources - All resource descriptors from the manifest.
2118
+ * @returns One wrangler R2 bucket entry per r2 resource.
2119
+ * @example
2120
+ * ```ts
2121
+ * const r2 = buildR2Buckets([{ kind: "r2", bucket: "ASSETS" }]);
2122
+ * ```
2123
+ */
2124
+ const buildR2Buckets = (resources) => resources.filter((resource) => resource.kind === "r2").map((resource) => ({
2125
+ binding: resource.bucket,
2126
+ bucket_name: resource.bucket.toLowerCase()
2127
+ }));
2128
+ /**
2129
+ * Build the wrangler `d1_databases` array from the manifest's d1 resources.
2130
+ *
2131
+ * @param resources - All resource descriptors from the manifest.
2132
+ * @param ids - Captured Cloudflare ids keyed by binding; the entry's `database_id` is filled from here.
2133
+ * @returns One wrangler D1 database entry per d1 resource (migrations_dir set when present).
2134
+ * @example
2135
+ * ```ts
2136
+ * const d1 = buildD1Databases([{ kind: "d1", binding: "DB" }], { DB: "uuid-1234" });
2137
+ * ```
2138
+ */
2139
+ const buildD1Databases = (resources, ids) => resources.filter((resource) => resource.kind === "d1").map((resource) => {
2140
+ const entry = {
2141
+ binding: resource.binding,
2142
+ database_name: resource.binding.toLowerCase(),
2143
+ database_id: ids[resource.binding] ?? ""
2144
+ };
2145
+ if (resource.migrations) entry.migrations_dir = resource.migrations;
2146
+ return entry;
2147
+ });
2148
+ /**
2149
+ * Build the wrangler `queues` producers section from the manifest's queue resources.
2150
+ *
2151
+ * @param resources - All resource descriptors from the manifest.
2152
+ * @returns The queues section, or undefined when there are no queue resources.
2153
+ * @example
2154
+ * ```ts
2155
+ * const q = buildQueues([{ kind: "queue", producers: ["jobs"] }]);
2156
+ * ```
2157
+ */
2158
+ const buildQueues = (resources) => {
2159
+ const queueResources = resources.filter((resource) => resource.kind === "queue");
2160
+ if (queueResources.length === 0) return void 0;
2161
+ return { producers: queueResources.flatMap((resource) => resource.producers.map((producer) => ({
2162
+ queue: producer,
2163
+ binding: producer.toUpperCase()
2164
+ }))) };
2165
+ };
2166
+ /**
2167
+ * Build the wrangler `durable_objects` bindings section from the manifest's do resources.
2168
+ *
2169
+ * @param resources - All resource descriptors from the manifest.
2170
+ * @returns The durable_objects section, or undefined when there are no do resources.
2171
+ * @example
2172
+ * ```ts
2173
+ * const dobj = buildDurableObjects([{ kind: "do", bindings: { Counter: "COUNTER" } }]);
2174
+ * ```
2175
+ */
2176
+ const buildDurableObjects = (resources) => {
2177
+ const doResources = resources.filter((resource) => resource.kind === "do");
2178
+ if (doResources.length === 0) return void 0;
2179
+ return { bindings: doResources.flatMap((resource) => Object.entries(resource.bindings).map(([className, bindingName]) => ({
2180
+ name: bindingName,
2181
+ class_name: className
2182
+ }))) };
2183
+ };
2184
+ /**
2185
+ * Generate/update the wrangler config file from a manifest (non-destructive merge).
2186
+ * If the file exists, its top-level keys are preserved and only deploy-managed keys
2187
+ * (name, compatibility_date, kv_namespaces, r2_buckets, d1_databases, queues,
2188
+ * durable_objects) are updated.
2189
+ *
2190
+ * @param configFile - Path to the wrangler config file.
2191
+ * @param manifest - The assembled deploy manifest.
2192
+ * @param ids - Captured Cloudflare ids keyed by binding (kv namespace id, d1 database id). Defaults
2193
+ * to an empty map, in which case `id`/`database_id` are written as "" (e.g. the universal path).
2194
+ * @returns Resolves once the file is written.
2195
+ * @example
2196
+ * ```ts
2197
+ * await writeWranglerConfig("wrangler.jsonc", manifest, { CACHE: "ns123", DB: "uuid-1234" });
2198
+ * ```
2199
+ */
2200
+ const writeWranglerConfig = async (configFile, manifest, ids = {}) => {
2201
+ let existing = {};
2202
+ if ((0, node_fs.existsSync)(configFile)) try {
2203
+ existing = parseJsonc((0, node_fs.readFileSync)(configFile, "utf8"));
2204
+ } catch {
2205
+ existing = {};
2206
+ }
2207
+ const kvNamespaces = buildKvNamespaces(manifest.resources, ids);
2208
+ const r2Buckets = buildR2Buckets(manifest.resources);
2209
+ const d1Databases = buildD1Databases(manifest.resources, ids);
2210
+ const queues = buildQueues(manifest.resources);
2211
+ const durableObjects = buildDurableObjects(manifest.resources);
2212
+ const updated = {
2213
+ ...existing,
2214
+ name: manifest.name,
2215
+ compatibility_date: manifest.compatibilityDate
2216
+ };
2217
+ if (kvNamespaces.length > 0) updated.kv_namespaces = kvNamespaces;
2218
+ if (r2Buckets.length > 0) updated.r2_buckets = r2Buckets;
2219
+ if (d1Databases.length > 0) updated.d1_databases = d1Databases;
2220
+ if (queues !== void 0) updated.queues = queues;
2221
+ if (durableObjects !== void 0) updated.durable_objects = durableObjects;
2222
+ await (0, node_fs_promises.writeFile)(configFile, JSON.stringify(updated, void 0, 2));
2223
+ };
2224
+ /**
2225
+ * Scaffold a starting wrangler config and, when ci is set, CI workflow files.
2226
+ * Idempotent: an existing config file is left completely untouched.
2227
+ *
2228
+ * @param configFile - Path to the wrangler config file.
2229
+ * @param _ci - Whether to also scaffold CI workflow files.
2230
+ * @returns Resolves once scaffolding is written.
2231
+ * @example
2232
+ * ```ts
2233
+ * await scaffoldWranglerAndCi("wrangler.jsonc", true);
2234
+ * ```
2235
+ */
2236
+ const scaffoldWranglerAndCi = async (configFile, _ci) => {
2237
+ if ((0, node_fs.existsSync)(configFile)) return;
2238
+ const starter = {
2239
+ name: "my-worker",
2240
+ main: "src/worker.ts",
2241
+ compatibility_date: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)
2242
+ };
2243
+ await (0, node_fs_promises.writeFile)(configFile, JSON.stringify(starter, void 0, 2));
2244
+ };
2245
+ //#endregion
2246
+ //#region src/plugins/deploy/api.ts
2247
+ /**
2248
+ * @file deploy plugin — API factory (run, dev, init, checkInfra, provisionInfra).
2249
+ *
2250
+ * Pure ctx-taking factory. Assembles the deploy manifest from each resource plugin's own
2251
+ * deployManifest() api (never sibling pluginConfigs — design F6), runs an infra preflight
2252
+ * (check-before-create + capture real ids), generates/updates the wrangler config, uploads the
2253
+ * R2 upload dir, and runs wrangler deploy. Emits only global events: deploy:phase,
2254
+ * deploy:complete, provision:resource, provision:plan, provision:skip.
2255
+ *
2256
+ * Node-only: uses node:child_process (via runner.ts), node:fs (via wrangler-config.ts), and the
2257
+ * Cloudflare REST API (via infra/). Never called in the deployed Worker runtime.
2258
+ */
2259
+ /**
2260
+ * Derive a human-readable name string from a resource descriptor (used in provision events).
2261
+ *
2262
+ * @param resource - The resource descriptor.
2263
+ * @returns A name suitable for the provision:resource / provision:skip event payload.
2264
+ * @example
2265
+ * ```ts
2266
+ * resourceName({ kind: "kv", binding: "CACHE" }); // "CACHE"
2267
+ * ```
2268
+ */
2269
+ const resourceName = (resource) => {
2270
+ switch (resource.kind) {
2271
+ case "r2": return resource.bucket;
2272
+ case "do": return Object.values(resource.bindings).join(",");
2273
+ case "queue": return resource.producers.join(",");
2274
+ default: return resource.binding;
2275
+ }
2276
+ };
2277
+ /**
2278
+ * Assemble the deploy manifest from each present resource plugin's OWN deployManifest() api,
2279
+ * gated by ctx.has(name) so absent plugins are skipped — never sibling pluginConfigs (F6).
2280
+ *
2281
+ * @param ctx - The deploy plugin context.
2282
+ * @returns The assembled manifest (name, compatibilityDate, resources).
2283
+ * @example
2284
+ * ```ts
2285
+ * const manifest = assembleManifest(ctx);
2286
+ * ```
2287
+ */
2288
+ const assembleManifest = (ctx) => ({
2289
+ name: ctx.global.name,
2290
+ compatibilityDate: ctx.global.compatibilityDate,
2291
+ resources: [
2292
+ ctx.has("storage") ? ctx.require(storagePlugin).deployManifest() : void 0,
2293
+ ctx.has("kv") ? ctx.require(kvPlugin).deployManifest() : void 0,
2294
+ ctx.has("d1") ? ctx.require(d1Plugin).deployManifest() : void 0,
2295
+ ctx.has("queues") ? ctx.require(queuesPlugin).deployManifest() : void 0,
2296
+ ctx.has("durableObjects") ? ctx.require(durableObjectsPlugin).deployManifest() : void 0
2297
+ ].filter((resource) => resource !== void 0)
2298
+ });
2299
+ /**
2300
+ * Act on an infra plan: skip the resources that already exist (reusing their ids), create only
2301
+ * the missing ones (capturing each new id), and announce each via provision:skip / :resource.
2302
+ *
2303
+ * @param ctx - The deploy plugin context.
2304
+ * @param plan - The infra plan from planInfra (existing vs missing).
2305
+ * @param ci - Whether provisioning runs non-interactively (forwarded to each provider).
2306
+ * @returns The provisioning result: created, skipped, and the merged binding → id map.
2307
+ * @example
2308
+ * ```ts
2309
+ * const { ids } = await applyPlan(ctx, plan, false);
2310
+ * ```
2311
+ */
2312
+ const applyPlan = async (ctx, plan, ci) => {
2313
+ const ids = {};
2314
+ for (const ref of plan.exists) {
2315
+ if (ref.id !== void 0 && (ref.resource.kind === "kv" || ref.resource.kind === "d1")) ids[ref.resource.binding] = ref.id;
2316
+ ctx.emit("provision:skip", {
2317
+ kind: ref.resource.kind,
2318
+ name: resourceName(ref.resource)
2319
+ });
2320
+ }
2321
+ const created = [];
2322
+ for (const resource of plan.missing) {
2323
+ const { id } = await provisionResource(resource, ci);
2324
+ if (id !== void 0 && (resource.kind === "kv" || resource.kind === "d1")) ids[resource.binding] = id;
2325
+ created.push(id === void 0 ? { resource } : {
2326
+ resource,
2327
+ id
2328
+ });
2329
+ ctx.emit("provision:resource", {
2330
+ kind: resource.kind,
2331
+ name: resourceName(resource)
2332
+ });
2333
+ }
2334
+ return {
2335
+ created,
2336
+ skipped: plan.exists,
2337
+ ids
2338
+ };
2339
+ };
2340
+ /**
2341
+ * Create the deploy api. Assembles the manifest from each resource plugin's own deployManifest(),
2342
+ * runs an infra preflight (check-before-create + id capture), generates config, uploads, and runs
2343
+ * `wrangler deploy`, emitting global deploy events along the way.
2344
+ *
2345
+ * @param ctx - Plugin context (own config + require + has + emit + global + env).
2346
+ * @returns The app.deploy api: run / dev / init / checkInfra / provisionInfra.
2347
+ * @example
2348
+ * ```ts
2349
+ * const api = createDeployApi(ctx);
2350
+ * await api.run();
2351
+ * ```
2352
+ */
2353
+ const createDeployApi = (ctx) => ({
2354
+ /**
2355
+ * Run the full deploy pipeline: detect → preflight (check-before-create) → provision (only the
2356
+ * missing) → wrangler-config (with real ids) → upload → deploy. When opts.manifest is supplied
2357
+ * it is used verbatim (universal path).
2358
+ *
2359
+ * @param opts - Optional run options.
2360
+ * @param opts.ci - CI/automated mode: never prompts, auto-confirms every gate. When false (the
2361
+ * default) and stdout is a TTY, the deploy is guided — each gate is confirmed interactively.
2362
+ * Falls back to ctx.config.ci when omitted.
2363
+ * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
2364
+ * @param opts.manifest - Caller-supplied manifest (bypasses deployManifest() assembly).
2365
+ * @returns Resolves once the deploy completes.
2366
+ * @example
2367
+ * ```ts
2368
+ * await api.run({ webBuild: () => web.cli.build() }); // guided on a TTY
2369
+ * await api.run({ ci: true, manifest: { name: "w", compatibilityDate: "2026-06-17", resources: [] } });
2370
+ * ```
2371
+ */
2372
+ async run(opts) {
2373
+ const ci = opts?.ci ?? ctx.config.ci;
2374
+ const confirm = !ci && stdoutIsTty() ? (0, _moku_labs_common_cli.createBrandPrompts)().confirm : async (_question) => true;
2375
+ ctx.emit("deploy:phase", { phase: "auth" });
2376
+ await verifyAuth(ctx);
2377
+ const webBuild = opts?.webBuild ?? ctx.config.webBuild;
2378
+ if (webBuild !== void 0) {
2379
+ ctx.emit("deploy:phase", {
2380
+ phase: "build",
2381
+ detail: "web"
2382
+ });
2383
+ await webBuild();
2384
+ }
2385
+ ctx.emit("deploy:phase", { phase: "detect" });
2386
+ const manifest = opts?.manifest ?? assembleManifest(ctx);
2387
+ ctx.emit("deploy:phase", { phase: "provision" });
2388
+ const plan = await planInfra(ctx, manifest);
2389
+ if (plan.missing.length > 0 && !await confirm(`Create ${plan.missing.length} missing resource(s) in "${plan.account}"?`)) {
2390
+ ctx.emit("deploy:phase", { phase: "aborted" });
2391
+ return;
2392
+ }
2393
+ const { ids } = await applyPlan(ctx, plan, ci);
2394
+ ctx.emit("deploy:phase", { phase: "wrangler-config" });
2395
+ await writeWranglerConfig(ctx.config.configFile, manifest, ids);
2396
+ const r2Resource = manifest.resources.find((resource) => resource.kind === "r2");
2397
+ if (r2Resource?.upload) {
2398
+ const count = await uploadDirToR2(r2Resource.bucket, r2Resource.upload);
2399
+ ctx.emit("deploy:phase", {
2400
+ phase: "upload",
2401
+ detail: `${String(count)} files`
2402
+ });
2403
+ }
2404
+ if (!await confirm(`Deploy "${manifest.name}" to ${ctx.global.stage}?`)) {
2405
+ ctx.emit("deploy:phase", { phase: "aborted" });
2406
+ return;
2407
+ }
2408
+ ctx.emit("deploy:phase", { phase: "deploy" });
2409
+ const url = await runWrangler([
2410
+ "deploy",
2411
+ "--config",
2412
+ ctx.config.configFile
2413
+ ]);
2414
+ ctx.emit("deploy:complete", { url });
2415
+ },
2416
+ /**
2417
+ * Start a long-lived local dev session: cold-build the Moku site, spawn `wrangler dev
2418
+ * --live-reload`, and watch the site sources — rebuilding on change (wrangler live-reloads the
2419
+ * browser). Resolves on SIGINT.
2420
+ *
2421
+ * @param opts - Optional options.
2422
+ * @param opts.port - Local dev port (default 8787).
2423
+ * @param opts.webBuild - Rebuild the web site on change (e.g. `() => webApp.cli.build()`).
2424
+ * @returns Resolves when the dev session ends.
2425
+ * @example
2426
+ * ```ts
2427
+ * await api.dev({ port: 8787, webBuild: () => web.cli.build() });
2428
+ * ```
2429
+ */
2430
+ dev: (opts) => runDev(ctx, opts, realDevDeps()),
2431
+ /**
2432
+ * Scaffold a starting wrangler config (and CI files when ci is set).
2433
+ * Idempotent: an existing config file is left untouched.
2434
+ *
2435
+ * @param opts - Optional options.
2436
+ * @param opts.ci - Also scaffold CI workflow files.
2437
+ * @returns Resolves once scaffolding is written.
2438
+ * @example
2439
+ * ```ts
2440
+ * await api.init({ ci: true });
2441
+ * ```
2442
+ */
2443
+ init: async (opts) => {
2444
+ await scaffoldWranglerAndCi(ctx.config.configFile, opts?.ci ?? ctx.config.ci);
2445
+ },
2446
+ /**
2447
+ * Read-only infra preflight: assemble the manifest, resolve the account, list what exists in
2448
+ * Cloudflare, diff, emit provision:plan, and return the plan. Writes nothing.
2449
+ *
2450
+ * @returns The infra plan (existing vs missing resources, with captured ids).
2451
+ * @example
2452
+ * ```ts
2453
+ * const plan = await api.checkInfra();
2454
+ * ```
2455
+ */
2456
+ checkInfra: () => planInfra(ctx, assembleManifest(ctx)),
2457
+ /**
2458
+ * Create only the resources missing from the plan (skipping existing), capturing each id.
2459
+ *
2460
+ * @param plan - A plan produced by checkInfra().
2461
+ * @returns The provisioning result: created, skipped, and the merged id map.
2462
+ * @example
2463
+ * ```ts
2464
+ * const { created } = await api.provisionInfra(await api.checkInfra());
2465
+ * ```
2466
+ */
2467
+ provisionInfra: (plan) => applyPlan(ctx, plan, ctx.config.ci),
2468
+ /**
2469
+ * Verify the `.env` Cloudflare API token (must be active) and resolve its account; emits
2470
+ * auth:verified. Throws a branded error pointing at `auth setup` when absent/invalid/inactive.
2471
+ *
2472
+ * @returns The verified auth status (account + id).
2473
+ * @example
2474
+ * ```ts
2475
+ * const { account } = await api.verifyAuth();
2476
+ * ```
2477
+ */
2478
+ verifyAuth: () => verifyAuth(ctx),
2479
+ /**
2480
+ * Derive the minimum Cloudflare API token this app needs from its manifest (pure, no network).
2481
+ *
2482
+ * @returns The token requirement (full set + groups to add to the stock template).
2483
+ * @example
2484
+ * ```ts
2485
+ * const { toAdd } = api.requiredToken();
2486
+ * ```
2487
+ */
2488
+ requiredToken: () => requiredToken(assembleManifest(ctx)),
2489
+ /**
2490
+ * Render the `auth setup` guidance from the derived token requirement (pure, no network).
2491
+ *
2492
+ * @returns The rendered instruction text.
2493
+ * @example
2494
+ * ```ts
2495
+ * const text = api.tokenInstructions();
2496
+ * ```
2497
+ */
2498
+ tokenInstructions: () => tokenInstructions(assembleManifest(ctx)),
2499
+ /**
2500
+ * Run an arbitrary wrangler command, streaming its output (the branded CLI escape hatch).
2501
+ *
2502
+ * @param args - The wrangler arguments.
2503
+ * @returns Resolves once wrangler exits.
2504
+ * @example
2505
+ * ```ts
2506
+ * await api.wrangler(["kv", "namespace", "list"]);
2507
+ * ```
2508
+ */
2509
+ wrangler: (args) => runWranglerInherit(args)
2510
+ });
2511
+ /**
2512
+ * Complex tier (node-only) — build-time deploy orchestrator over the five resource plugins.
2513
+ *
2514
+ * Assembles each resource plugin's deployManifest() via ctx.require, provisions resources,
2515
+ * generates/updates wrangler config, uploads the R2 upload dir, and runs wrangler deploy.
2516
+ * Also supports a universal path: run({ manifest }) uses a caller-supplied manifest verbatim.
2517
+ *
2518
+ * Emits only the global events `deploy:phase`, `deploy:complete`, and `provision:resource`
2519
+ * (declared in WorkerEvents — no per-plugin events block).
2520
+ *
2521
+ * @see README.md
2522
+ */
2523
+ const deployPlugin = createPlugin("deploy", {
2524
+ config: {
2525
+ configFile: "wrangler.jsonc",
2526
+ ci: false,
2527
+ watch: ["src/**/*.{ts,tsx,css}", "public/**/*"],
2528
+ buildCommand: "",
2529
+ migrateLocal: true,
2530
+ debounceMs: 120
2531
+ },
2532
+ depends: [
2533
+ storagePlugin,
2534
+ kvPlugin,
2535
+ d1Plugin,
2536
+ queuesPlugin,
2537
+ durableObjectsPlugin
2538
+ ],
2539
+ api: (ctx) => createDeployApi(ctx)
2540
+ });
2541
+ //#endregion
2542
+ //#region src/plugins/cli/args.ts
2543
+ /**
2544
+ * @file cli plugin — argv parsing helpers (isolated so they unit-test without a real process).
2545
+ *
2546
+ * `dev` resolves its port from the command line (`bun scripts/dev.ts --port 3000`) so a consumer
2547
+ * never hardcodes it in the app. Pure: takes an argv array, reads no globals. Node-only tooling.
2548
+ */
2549
+ /** The valid TCP port range a `--port` value must fall within to be accepted. */
2550
+ const MAX_PORT = 65535;
2551
+ /**
2552
+ * Extract a `--port`/`-p` value from a single token (and the token after it, for the spaced form).
2553
+ *
2554
+ * @param token - The current argv token.
2555
+ * @param next - The following argv token (the value, for the `--port 3000` spaced form).
2556
+ * @returns The raw string value when this token is a port flag, else undefined.
2557
+ * @example
2558
+ * ```ts
2559
+ * portValueFrom("--port=3000", undefined); // "3000"
2560
+ * portValueFrom("--port", "3000"); // "3000"
2561
+ * portValueFrom("--config", "x"); // undefined
2562
+ * ```
2563
+ */
2564
+ const portValueFrom = (token, next) => {
2565
+ const inline = /^(?:--port|-p)=(.+)$/u.exec(token);
2566
+ if (inline) return inline[1];
2567
+ if (token === "--port" || token === "-p") return next;
2568
+ };
2569
+ /**
2570
+ * Parse a `--port <n>` / `--port=<n>` / `-p <n>` flag out of an argv array.
2571
+ *
2572
+ * Returns the first valid port (a positive integer ≤ 65535) found, or undefined when the flag is
2573
+ * absent or its value is not a usable port — letting the caller fall back to a default.
2574
+ *
2575
+ * @param argv - The argv array to scan (the caller passes the process argv).
2576
+ * @returns The parsed port number, or undefined when no valid `--port`/`-p` flag is present.
2577
+ * @example
2578
+ * ```ts
2579
+ * parsePortArg(["bun", "scripts/dev.ts", "--port", "3000"]); // 3000
2580
+ * parsePortArg(["bun", "scripts/dev.ts", "--port=3000"]); // 3000
2581
+ * parsePortArg(["bun", "scripts/dev.ts"]); // undefined
2582
+ * ```
2583
+ */
2584
+ const parsePortArg = (argv) => {
2585
+ for (let index = 0; index < argv.length; index++) {
2586
+ const token = argv[index];
2587
+ if (token === void 0) continue;
2588
+ const raw = portValueFrom(token, argv[index + 1]);
2589
+ if (raw === void 0) continue;
2590
+ const port = Number(raw);
2591
+ if (Number.isInteger(port) && port > 0 && port <= MAX_PORT) return port;
2592
+ }
2593
+ };
2594
+ //#endregion
2595
+ //#region src/plugins/cli/api.ts
2596
+ /**
2597
+ * @file cli plugin — API factory (dev, deploy, auth, doctor).
2598
+ */
2599
+ /**
2600
+ * Builds app.cli.* over the deploy plugin (via ctx.require(deployPlugin)). `dev`/`deploy` resolve
2601
+ * their args (port from `--port`; guided unless `ci`) then delegate, catching any failure into a
2602
+ * branded `✗` line + non-zero exit; the read-only verbs (auth/doctor/whoami) render in Moku style.
2603
+ *
2604
+ * @param ctx - CLI plugin context (own config + typed require to deployPlugin).
2605
+ * @returns The cli API object (dev, deploy, auth, doctor, whoami, wrangler).
2606
+ * @example
2607
+ * ```ts
2608
+ * const api = createCliApi(ctx);
2609
+ * await api.dev({ webBuild: () => web.cli.build() }); // → deploy.dev({ port })
2610
+ * await api.deploy({ ci: true }); // → deploy.run({ ci: true })
2611
+ * ```
2612
+ */
2613
+ const createCliApi = (ctx) => ({
2614
+ /**
2615
+ * Run the Worker locally. Resolves the port from `opts.port`, else a `--port <n>` CLI flag, else
2616
+ * `ctx.config.port` (8787). Prints a branded dev-session banner, then delegates to deploy.dev; a
2617
+ * `webBuild` hook (e.g. `() => webApp.cli.build()`) wires the web build into the dev loop so the
2618
+ * site recompiles on change. A failure renders a branded `✗` line + non-zero exit, not a stack.
2619
+ *
2620
+ * @param opts - Optional local dev options.
2621
+ * @param opts.port - Local dev port to bind. Overrides the `--port` flag and the default.
2622
+ * @param opts.webBuild - Rebuild the web site on change (e.g. `() => webApp.cli.build()`).
2623
+ * @returns Resolves when the dev session ends.
2624
+ * @example
2625
+ * ```ts
2626
+ * await api.dev({ webBuild: () => web.cli.build() }); // port from --port or 8787
2627
+ * ```
2628
+ */
2629
+ async dev(opts) {
2630
+ const ui = (0, _moku_labs_common_cli.createBrandConsole)();
2631
+ ui.lockup({
2632
+ wordmark: "moku worker",
2633
+ label: "dev session"
2634
+ });
2635
+ const port = opts?.port ?? parsePortArg(process.argv) ?? ctx.config.port;
2636
+ try {
2637
+ await ctx.require(deployPlugin).dev(opts?.webBuild ? {
2638
+ port,
2639
+ webBuild: opts.webBuild
2640
+ } : { port });
2641
+ ui.check(true, "dev session stopped cleanly");
2642
+ } catch (error) {
2643
+ ui.error(error instanceof Error ? error.message : String(error));
2644
+ process.exitCode = 1;
2645
+ }
2646
+ },
2647
+ /**
2648
+ * One-command Cloudflare deploy; forwards opts verbatim to deploy.run. Guided/interactive by
2649
+ * default; `{ ci: true }` runs the automated path (CI). A `webBuild` hook builds the web site
2650
+ * first (before `wrangler deploy`). A failure renders a branded `✗` line + non-zero exit code
2651
+ * (matching cli.auth/doctor), never a raw stack trace.
2652
+ *
2653
+ * @param opts - Optional deploy options.
2654
+ * @param opts.ci - Automated mode: never prompts, auto-confirms. Omit/false → guided on a TTY.
2655
+ * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
2656
+ * @returns Resolves once the deploy completes (or after a failure is rendered).
2657
+ * @example
2658
+ * ```ts
2659
+ * await api.deploy({ webBuild: () => web.cli.build() }); // guided
2660
+ * await api.deploy({ ci: true, webBuild: () => web.cli.build() }); // CI
2661
+ * ```
2662
+ */
2663
+ async deploy(opts) {
2664
+ try {
2665
+ await ctx.require(deployPlugin).run(opts);
2666
+ } catch (error) {
2667
+ (0, _moku_labs_common_cli.createBrandConsole)().error(error instanceof Error ? error.message : String(error));
2668
+ process.exitCode = 1;
2669
+ }
2670
+ },
2671
+ /**
2672
+ * Verify the `.env` token (no sub) or print the config-derived token guidance (`"setup"`),
2673
+ * rendered in Moku style. `setup` works without a token; verify reports the resolved account.
2674
+ *
2675
+ * @param sub - Pass "setup" to print guidance; omit to verify the current token.
2676
+ * @returns Resolves once the check or guidance render completes.
2677
+ * @example
2678
+ * ```ts
2679
+ * await api.auth("setup"); // print what token to create
2680
+ * await api.auth(); // verify the current token
2681
+ * ```
2682
+ */
2683
+ async auth(sub) {
2684
+ const deploy = ctx.require(deployPlugin);
2685
+ const ui = (0, _moku_labs_common_cli.createBrandConsole)();
2686
+ if (sub === "setup") {
2687
+ for (const line of deploy.tokenInstructions().split("\n")) ui.line(line);
2688
+ return;
2689
+ }
2690
+ try {
2691
+ const status = await deploy.verifyAuth();
2692
+ ui.check(true, "token valid", `account "${status.account}" (${status.accountId})`);
2693
+ } catch (error) {
2694
+ ui.error(error instanceof Error ? error.message : String(error));
2695
+ }
2696
+ },
2697
+ /**
2698
+ * One-shot preflight report: token + account (verifyAuth) then infra drift (checkInfra),
2699
+ * each as a branded check line. Stops after the token check when auth fails.
2700
+ *
2701
+ * @returns Resolves once the report is printed.
2702
+ * @example
2703
+ * ```ts
2704
+ * await api.doctor();
2705
+ * ```
2706
+ */
2707
+ async doctor() {
2708
+ const deploy = ctx.require(deployPlugin);
2709
+ const ui = (0, _moku_labs_common_cli.createBrandConsole)();
2710
+ ui.heading("doctor");
2711
+ let tokenOk = false;
2712
+ try {
2713
+ const status = await deploy.verifyAuth();
2714
+ tokenOk = true;
2715
+ ui.check(true, "token", `valid · account "${status.account}" (${status.accountId})`);
2716
+ } catch (error) {
2717
+ ui.check(false, "token", error instanceof Error ? error.message : String(error));
2718
+ }
2719
+ if (!tokenOk) {
2720
+ ui.line("Run `auth setup` for the exact token to create.");
2721
+ return;
2722
+ }
2723
+ try {
2724
+ const plan = await deploy.checkInfra();
2725
+ ui.check(true, "infra", `${plan.exists.length} exist, ${plan.missing.length} to create in "${plan.account}"`);
2726
+ } catch (error) {
2727
+ ui.check(false, "infra", error instanceof Error ? error.message : String(error));
2728
+ }
2729
+ },
2730
+ /**
2731
+ * Print the resolved Cloudflare account for the current `.env` token.
2732
+ *
2733
+ * @returns Resolves once the account summary is printed.
2734
+ * @example
2735
+ * ```ts
2736
+ * await api.whoami();
2737
+ * ```
2738
+ */
2739
+ async whoami() {
2740
+ const ui = (0, _moku_labs_common_cli.createBrandConsole)();
2741
+ try {
2742
+ const status = await ctx.require(deployPlugin).verifyAuth();
2743
+ ui.check(true, "account", `${status.account} (${status.accountId})`);
2744
+ } catch (error) {
2745
+ ui.error(error instanceof Error ? error.message : String(error));
2746
+ }
2747
+ },
2748
+ /**
2749
+ * Run an arbitrary wrangler command through the branded CLI (escape hatch). Streams its output.
2750
+ *
2751
+ * @param args - The wrangler arguments.
2752
+ * @returns Resolves once wrangler exits.
2753
+ * @example
2754
+ * ```ts
2755
+ * await api.wrangler(["kv", "namespace", "list"]);
2756
+ * ```
2757
+ */
2758
+ async wrangler(args) {
2759
+ (0, _moku_labs_common_cli.createBrandConsole)().heading(`wrangler ${args.join(" ")}`);
2760
+ await ctx.require(deployPlugin).wrangler(args);
2761
+ }
2762
+ });
2763
+ //#endregion
2764
+ //#region src/plugins/cli/handlers.ts
2765
+ /** Divider drawn before the native `wrangler dev` TUI so the moku preamble reads as one section. */
2766
+ const WRANGLER_DIVIDER = ` ── wrangler ${"─".repeat(48)}`;
2767
+ /**
2768
+ * Builds the hook handlers that turn global deploy events into a live progress TUI.
2769
+ * Each logs a clean, prefix-free message via `ctx.log`; the branded log sink (installed
2770
+ * by the cli plugin's onInit from `@moku-labs/common/cli`) adds the `›` marker, brand
2771
+ * color, and stderr routing. Pure observers — print and return; never mutate state,
2772
+ * never block the deploy pipeline (fire-and-forget, spec/07 §3,§4).
2773
+ *
2774
+ * @param ctx - CLI plugin context with injected log core API.
2775
+ * @returns Hook map for the three global deploy events.
2776
+ * @example
2777
+ * ```ts
2778
+ * const hooks = createCliHooks(ctx);
2779
+ * hooks["deploy:phase"]({ phase: "detect" }); // logs "detect" → renders " › detect"
2780
+ * hooks["provision:resource"]({ kind: "kv", name: "KV" }); // logs "kv KV" → " › kv KV"
2781
+ * hooks["deploy:complete"]({ url: "https://x.workers.dev" }); // "deployed → https://x.workers.dev"
2782
+ * ```
2783
+ */
2784
+ const createCliHooks = (ctx) => {
2785
+ const ui = (0, _moku_labs_common_cli.createBrandConsole)();
2786
+ return {
2787
+ /**
2788
+ * Log one clean line per pipeline phase: "phase" or "phase · detail".
2789
+ *
2790
+ * @param p - The deploy:phase event payload.
2791
+ * @example
2792
+ * ```ts
2793
+ * handler({ phase: "detect" }); // "detect"
2794
+ * handler({ phase: "upload", detail: "3 files" }); // "upload · 3 files"
2795
+ * ```
2796
+ */
2797
+ "deploy:phase"(p) {
2798
+ ctx.log.info(p.detail ? `${p.phase} · ${p.detail}` : p.phase);
2799
+ },
2800
+ /**
2801
+ * Log the infra preflight summary: "infra · N exist, M to create · account".
2802
+ *
2803
+ * @param p - The provision:plan event payload.
2804
+ * @example
2805
+ * ```ts
2806
+ * handler({ exists: 2, missing: 1, account: "Play Co" }); // "infra · 2 exist, 1 to create · Play Co"
2807
+ * ```
2808
+ */
2809
+ "provision:plan"(p) {
2810
+ ctx.log.info(`infra · ${p.exists} exist, ${p.missing} to create · ${p.account}`);
2811
+ },
2812
+ /**
2813
+ * Log one clean line per provisioned resource: "kind name".
2814
+ *
2815
+ * @param p - The provision:resource event payload.
2816
+ * @example
2817
+ * ```ts
2818
+ * handler({ kind: "kv", name: "KV" }); // "kv KV"
2819
+ * ```
2820
+ */
2821
+ "provision:resource"(p) {
2822
+ ctx.log.info(`${p.kind} ${p.name}`);
2823
+ },
2824
+ /**
2825
+ * Log one clean line per already-existing resource (skipped): "kind name (exists)".
2826
+ *
2827
+ * @param p - The provision:skip event payload.
2828
+ * @example
2829
+ * ```ts
2830
+ * handler({ kind: "kv", name: "KV" }); // "kv KV (exists)"
2831
+ * ```
2832
+ */
2833
+ "provision:skip"(p) {
2834
+ ctx.log.info(`${p.kind} ${p.name} (exists)`);
2835
+ },
2836
+ /**
2837
+ * Log one dev-session phase: "phase" or "phase · detail".
2838
+ *
2839
+ * @param p - The dev:phase event payload.
2840
+ * @example
2841
+ * ```ts
2842
+ * handler({ phase: "serve", detail: "http://localhost:8787" }); // "serve · http://localhost:8787"
2843
+ * ```
2844
+ */
2845
+ "dev:phase"(p) {
2846
+ ctx.log.info(p.detail ? `${p.phase} · ${p.detail}` : p.phase);
2847
+ if (p.phase === "serve") ui.line(WRANGLER_DIVIDER);
2848
+ },
2849
+ /**
2850
+ * Log the site rebuild result: "site <n> files · <ms>ms" (omits the count when unknown).
2851
+ *
2852
+ * @param p - The dev:rebuilt event payload.
2853
+ * @example
2854
+ * ```ts
2855
+ * handler({ files: 12, ms: 240 }); // "site 12 files · 240ms"
2856
+ * handler({ files: 0, ms: 240 }); // "site · 240ms"
2857
+ * ```
2858
+ */
2859
+ "dev:rebuilt"(p) {
2860
+ ctx.log.info(p.files > 0 ? `site ${String(p.files)} files · ${String(p.ms)}ms` : `site · ${String(p.ms)}ms`);
2861
+ },
2862
+ /**
2863
+ * Log a non-fatal dev build failure via warn (the session keeps serving the last good build).
2864
+ *
2865
+ * @param p - The dev:error event payload.
2866
+ * @example
2867
+ * ```ts
2868
+ * handler({ message: "build failed" }); // warn "build failed"
2869
+ * ```
2870
+ */
2871
+ "dev:error"(p) {
2872
+ ctx.log.warn(p.message);
2873
+ },
2874
+ /**
2875
+ * Log the terminal success line with the deployed URL.
2876
+ *
2877
+ * @param p - The deploy:complete event payload.
2878
+ * @example
2879
+ * ```ts
2880
+ * handler({ url: "https://my-worker.workers.dev" }); // "deployed → https://my-worker.workers.dev"
2881
+ * ```
2882
+ */
2883
+ "deploy:complete"(p) {
2884
+ ctx.log.info(`deployed → ${p.url}`);
2885
+ }
2886
+ };
2887
+ };
2888
+ /**
2889
+ * Standard tier (node-only) — developer-facing CLI surface.
2890
+ *
2891
+ * Mounts `app.cli.dev()` and `app.cli.deploy()` as thin passthroughs to deployPlugin.
2892
+ * Hooks subscribe to the global deploy:phase / provision:resource / deploy:complete events
2893
+ * and print a live progress TUI via the injected ctx.log core API.
2894
+ *
2895
+ * Inline lambdas on `api`/`hooks` preserve event-name inference so the hook map keys
2896
+ * are constrained to `WorkerEvents` keys (spec/15 §5).
2897
+ *
2898
+ * @see README.md
2899
+ */
2900
+ const cliPlugin = createPlugin("cli", {
2901
+ depends: [deployPlugin],
2902
+ config: { port: 8787 },
2903
+ onInit: (ctx) => {
2904
+ ctx.log.clearSinks();
2905
+ ctx.log.addSink((0, _moku_labs_common_cli.brandedSink)("info"));
2906
+ },
2907
+ api: (ctx) => createCliApi(ctx),
2908
+ hooks: (ctx) => createCliHooks(ctx)
2909
+ });
2910
+ //#endregion
2911
+ Object.defineProperty(exports, "bindingsPlugin", {
2912
+ enumerable: true,
2913
+ get: function() {
2914
+ return bindingsPlugin;
2915
+ }
2916
+ });
2917
+ Object.defineProperty(exports, "cliPlugin", {
2918
+ enumerable: true,
2919
+ get: function() {
2920
+ return cliPlugin;
2921
+ }
2922
+ });
2923
+ Object.defineProperty(exports, "coreConfig", {
2924
+ enumerable: true,
2925
+ get: function() {
2926
+ return coreConfig;
2927
+ }
2928
+ });
2929
+ Object.defineProperty(exports, "createCore", {
2930
+ enumerable: true,
2931
+ get: function() {
2932
+ return createCore;
2933
+ }
2934
+ });
2935
+ Object.defineProperty(exports, "createPlugin", {
2936
+ enumerable: true,
2937
+ get: function() {
2938
+ return createPlugin;
2939
+ }
2940
+ });
2941
+ Object.defineProperty(exports, "d1Plugin", {
2942
+ enumerable: true,
2943
+ get: function() {
2944
+ return d1Plugin;
2945
+ }
2946
+ });
2947
+ Object.defineProperty(exports, "defineDurableObject", {
2948
+ enumerable: true,
2949
+ get: function() {
2950
+ return defineDurableObject;
2951
+ }
2952
+ });
2953
+ Object.defineProperty(exports, "deployPlugin", {
2954
+ enumerable: true,
2955
+ get: function() {
2956
+ return deployPlugin;
2957
+ }
2958
+ });
2959
+ Object.defineProperty(exports, "durableObjectsPlugin", {
2960
+ enumerable: true,
2961
+ get: function() {
2962
+ return durableObjectsPlugin;
2963
+ }
2964
+ });
2965
+ Object.defineProperty(exports, "kvPlugin", {
2966
+ enumerable: true,
2967
+ get: function() {
2968
+ return kvPlugin;
2969
+ }
2970
+ });
2971
+ Object.defineProperty(exports, "queuesPlugin", {
2972
+ enumerable: true,
2973
+ get: function() {
2974
+ return queuesPlugin;
2975
+ }
2976
+ });
2977
+ Object.defineProperty(exports, "stagePlugin", {
2978
+ enumerable: true,
2979
+ get: function() {
2980
+ return stagePlugin;
2981
+ }
2982
+ });
2983
+ Object.defineProperty(exports, "storagePlugin", {
2984
+ enumerable: true,
2985
+ get: function() {
2986
+ return storagePlugin;
2987
+ }
2988
+ });