@moku-labs/worker 0.9.2 → 0.11.0

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