@moku-labs/worker 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,353 @@
1
+ import { PluginCtx, PluginInstance } from "@moku-labs/core";
2
+
3
+ //#region src/config.d.ts
4
+ /** Per-request Cloudflare bindings object (env). Framework-level shared type. */
5
+ type WorkerEnv = Record<string, unknown>;
6
+ /** Global framework config — flat, with complete defaults. */
7
+ type WorkerConfig = {
8
+ stage: "production" | "development" | "test";
9
+ name: string;
10
+ compatibilityDate: string;
11
+ };
12
+ /** Global framework events — declared once, visible to every plugin. */
13
+ type WorkerEvents = {
14
+ "request:start": {
15
+ method: string;
16
+ path: string;
17
+ requestId: string;
18
+ };
19
+ "request:end": {
20
+ method: string;
21
+ path: string;
22
+ status: number;
23
+ ms: number;
24
+ };
25
+ "deploy:phase": {
26
+ phase: string;
27
+ detail?: string;
28
+ };
29
+ "deploy:complete": {
30
+ url: string;
31
+ };
32
+ "provision:resource": {
33
+ kind: "kv" | "r2" | "d1" | "queue" | "do";
34
+ name: string;
35
+ };
36
+ "provision:plan": {
37
+ exists: number;
38
+ missing: number;
39
+ account: string;
40
+ };
41
+ "provision:skip": {
42
+ kind: "kv" | "r2" | "d1" | "queue" | "do";
43
+ name: string;
44
+ };
45
+ "auth:verified": {
46
+ account: string;
47
+ accountId: string;
48
+ scopes: string[];
49
+ };
50
+ "dev:phase": {
51
+ phase: string;
52
+ detail?: string;
53
+ };
54
+ "dev:rebuilt": {
55
+ files: number;
56
+ ms: number;
57
+ };
58
+ "dev:error": {
59
+ message: string;
60
+ };
61
+ };
62
+ /**
63
+ * Worker-bound plugin context for Layer-3 consumer plugins. Aliases the core
64
+ * {@link PluginCtx} with the global {@link WorkerEvents} pre-merged into the event
65
+ * map, so a consumer plugin types its own `config`/`state`/`emit` by passing only
66
+ * its OWN event map — never hand-merging `WorkerEvents`, and never importing from
67
+ * `@moku-labs/core` (a Layer-1 boundary the spec validator flags for consumers).
68
+ *
69
+ * A plugin that resolves sibling plugins also needs a `require` field; intersect the
70
+ * public `Server.RequireFn` for it, exactly as this framework's own plugins do. When
71
+ * you need the unaliased shape (e.g. a different global event map), use the raw
72
+ * re-exported {@link PluginCtx} instead.
73
+ *
74
+ * @template Config - This plugin's own flat configuration object.
75
+ * @template State - This plugin's mutable state (use `Record<string, never>` when stateless).
76
+ * @template Events - This plugin's own event map, merged on top of {@link WorkerEvents}; defaults to none.
77
+ * @example
78
+ * ```typescript
79
+ * import type { Server, WorkerPluginCtx } from "@moku-labs/worker";
80
+ * type MyEvents = { "my:done": { id: string } };
81
+ * export type MyCtx = WorkerPluginCtx<MyConfig, Record<string, never>, MyEvents> & {
82
+ * require: Server.RequireFn;
83
+ * };
84
+ * ```
85
+ */
86
+ type WorkerPluginCtx<Config, State, Events extends Record<string, unknown> = Record<never, never>> = PluginCtx<Config, State, WorkerEvents & Events>;
87
+ //#endregion
88
+ //#region src/plugins/deploy/types.d.ts
89
+ /**
90
+ * A web-site build hook wired in from the consumer's deploy/dev script — e.g.
91
+ * `() => webApp.cli.build()`. This is the seam that lets one small app-side script compose a
92
+ * Moku Web app with this Worker framework: `dev` / `deploy` invoke it to (re)build the site before
93
+ * serving or deploying. The hook may resolve ANYTHING — `void`, the web app's own build summary, or
94
+ * a `{ files }` count; when the resolved value carries a numeric `files` field it is surfaced in
95
+ * `dev:rebuilt`, otherwise the count is reported as 0. Returning `Promise<unknown>` keeps the hook
96
+ * assignable from any real build function (whose return type the worker framework cannot know).
97
+ *
98
+ * @returns Resolves when the web build completes (the value is read opportunistically for `files`).
99
+ * @example
100
+ * ```ts
101
+ * await server.cli.dev({ webBuild: () => web.cli.build() });
102
+ * ```
103
+ */
104
+ type WebBuild = () => Promise<unknown>;
105
+ /** deploy plugin configuration. Flat; complete defaults so omission never yields undefined. */
106
+ type Config$1 = {
107
+ /**
108
+ * Wrangler config file generated/updated and read by `wrangler deploy`. Default "wrangler.jsonc".
109
+ * Also the file parsed in the universal/non-moku path.
110
+ */
111
+ configFile: string;
112
+ /**
113
+ * Standing CI/automated default for `run()`. When true (or when stdout is non-TTY) the deploy
114
+ * never prompts and auto-confirms every gate; `run({ ci })` overrides it per call. CF credentials
115
+ * are read from the env (CLOUDFLARE_API_TOKEN / CLOUDFLARE_ACCOUNT_ID) via `ctx.env`. Default false.
116
+ */
117
+ ci: boolean; /** Globs watched by `dev()` to trigger a Moku-site rebuild. */
118
+ watch: string[];
119
+ /**
120
+ * Standing default web-site build hook (e.g. `() => webApp.cli.build()`). Usually passed
121
+ * call-time to `dev` / `deploy` via `opts.webBuild` (the script-driven path); set here only for
122
+ * a persistent default. When absent, dev() falls back to `buildCommand`, then auto-detects
123
+ * `scripts/build.ts`.
124
+ */
125
+ webBuild?: WebBuild; /** Shell rebuild fallback (e.g. "bun run scripts/build.ts"); empty → auto-detect scripts/build.ts. */
126
+ buildCommand: string; /** Apply local D1 migrations before serving when a d1 manifest is present. */
127
+ migrateLocal: boolean; /** Debounce window (ms) coalescing rapid file changes into one rebuild. */
128
+ debounceMs: number;
129
+ };
130
+ /** Discriminated union of resource descriptors returned by each plugin's deployManifest(). */
131
+ type ResourceManifest = {
132
+ kind: "r2";
133
+ bucket: string;
134
+ upload?: string;
135
+ } | {
136
+ kind: "kv";
137
+ binding: string;
138
+ } | {
139
+ kind: "d1";
140
+ binding: string;
141
+ migrations?: string;
142
+ } | {
143
+ kind: "queue";
144
+ producers: string[];
145
+ } | {
146
+ kind: "do";
147
+ bindings: Record<string, string>;
148
+ };
149
+ /**
150
+ * The whole deploy manifest the pipeline consumes (assembled, or caller-supplied for the
151
+ * universal path).
152
+ */
153
+ type ExternalManifest = {
154
+ /** Worker name. */name: string; /** Cloudflare compatibility date. */
155
+ compatibilityDate: string; /** Resource descriptors to provision. */
156
+ resources: ResourceManifest[];
157
+ };
158
+ /**
159
+ * A resource that already exists in the account (the infra preflight discovered it), with its
160
+ * captured Cloudflare id when the kind has one (kv namespace id, d1 database id).
161
+ */
162
+ type ProvisionedRef = {
163
+ /** The resource descriptor from the manifest. */resource: ResourceManifest; /** The existing resource's Cloudflare id (kv/d1 only). */
164
+ id?: string;
165
+ };
166
+ /**
167
+ * Read-only infra preflight result: which declared resources already exist in the Cloudflare
168
+ * account versus which are still missing and must be created. Produced by `checkInfra()`.
169
+ */
170
+ type InfraPlan = {
171
+ /** Resolved account display name (or id when the name is unknown). */account: string; /** Resolved Cloudflare account id used for the existence checks. */
172
+ accountId: string; /** Declared resources that already exist (with their captured ids where applicable). */
173
+ exists: ProvisionedRef[]; /** Declared resources that do not yet exist and must be created. */
174
+ missing: ResourceManifest[];
175
+ };
176
+ /**
177
+ * Outcome of acting on an {@link InfraPlan}: the resources just created, those skipped because
178
+ * they already existed, and the merged id map (binding → Cloudflare id) for the config writer.
179
+ */
180
+ type ProvisionResult = {
181
+ /** Resources created during this run. */created: ProvisionedRef[]; /** Resources skipped because they already existed. */
182
+ skipped: ProvisionedRef[]; /** Merged binding → Cloudflare id map (existing + created) for writeWranglerConfig. */
183
+ ids: Record<string, string>;
184
+ };
185
+ /** Result of verifying the `.env` Cloudflare API token and resolving its account. */
186
+ type AuthStatus = {
187
+ /** Whether the token is present and active. */ok: boolean; /** Resolved account display name (or id when the name is unknown). */
188
+ account: string; /** Resolved Cloudflare account id. */
189
+ accountId: string; /** Token scopes, when discoverable (empty otherwise). */
190
+ scopes: string[];
191
+ };
192
+ /** One Cloudflare API-token permission group the app's manifest requires. */
193
+ type PermissionGroup = {
194
+ /** Human-readable group label, e.g. "Account · D1". */group: string; /** Permission scope. */
195
+ scope: "Edit" | "Read"; /** Why it is required, e.g. "d1", "queue", "deploy", "account". */
196
+ reason: string; /** Whether Cloudflare's stock "Edit Cloudflare Workers" template already includes it. */
197
+ inBaseTemplate: boolean;
198
+ };
199
+ /** The Cloudflare API token this app requires, derived from its manifest. */
200
+ type TokenRequirement = {
201
+ /** The recommended starting template. */base: "Edit Cloudflare Workers"; /** The full set of permission groups required. */
202
+ required: PermissionGroup[]; /** Groups NOT in the base template that the user must add (e.g. D1, Queues). */
203
+ toAdd: PermissionGroup[];
204
+ };
205
+ //#endregion
206
+ //#region src/plugins/cli/types.d.ts
207
+ /** Resolved configuration for the cli plugin. Flat; complete defaults so omission never yields undefined. */
208
+ type Config = {
209
+ /**
210
+ * Default local dev port forwarded to deploy.dev when dev() gets no port.
211
+ * Passed through to `wrangler dev --port <n>`.
212
+ *
213
+ * @default 8787
214
+ */
215
+ readonly port: number;
216
+ };
217
+ /** Public api surface of the cli plugin, mounted at app.cli.*. */
218
+ type Api = {
219
+ /**
220
+ * Run the Worker locally via Wrangler (delegates to deploy.dev). Resolves the port from
221
+ * `opts.port`, else a `--port <n>` CLI flag, else the configured default (8787). A failure renders
222
+ * a branded `✗` line and sets a non-zero exit code rather than throwing a raw stack trace.
223
+ *
224
+ * @param opts - Optional port override and web build hook.
225
+ * @param opts.port - Local dev port to bind (overrides the `--port` flag and the default).
226
+ * @param opts.webBuild - Rebuild the web site on change (e.g. `() => webApp.cli.build()`).
227
+ * @returns Resolves when the dev session ends.
228
+ * @example
229
+ * ```ts
230
+ * await app.cli.dev({ webBuild: () => web.cli.build() }); // port from --port or 8787
231
+ * ```
232
+ */
233
+ dev(opts?: {
234
+ port?: number;
235
+ webBuild?: WebBuild;
236
+ }): Promise<void>;
237
+ /**
238
+ * One-command Cloudflare deploy (delegates to deploy.run). Guided/interactive by default; pass
239
+ * `{ ci: true }` for the automated/non-interactive path (CI). A failure renders a branded `✗`
240
+ * line and sets a non-zero exit code rather than throwing a raw stack trace.
241
+ *
242
+ * @param opts - Optional ci flag and a web build hook.
243
+ * @param opts.ci - Automated mode: never prompts, auto-confirms. Omit/false → guided on a TTY.
244
+ * @param opts.webBuild - Build the web site first (e.g. `() => webApp.cli.build()`), before deploy.
245
+ * @returns Resolves once the deploy completes (or after a failure is rendered).
246
+ * @example
247
+ * ```ts
248
+ * await app.cli.deploy({ webBuild: () => web.cli.build() }); // guided
249
+ * await app.cli.deploy({ ci: true, webBuild: () => web.cli.build() }); // CI
250
+ * ```
251
+ */
252
+ deploy(opts?: {
253
+ ci?: boolean;
254
+ webBuild?: WebBuild;
255
+ }): Promise<void>;
256
+ /**
257
+ * Verify the `.env` Cloudflare token (no sub), or print the config-derived token-creation
258
+ * guidance (`"setup"`). Delegates to deploy.verifyAuth() / deploy.tokenInstructions().
259
+ *
260
+ * @param sub - Pass "setup" to print token guidance; omit to verify the current token.
261
+ * @returns Resolves once the auth check or guidance render completes.
262
+ * @example
263
+ * ```ts
264
+ * await app.cli.auth(); // verify the current token
265
+ * await app.cli.auth("setup"); // print what token to create
266
+ * ```
267
+ */
268
+ auth(sub?: "setup"): Promise<void>;
269
+ /**
270
+ * One-shot preflight report: token + account (verifyAuth) and infra drift (checkInfra),
271
+ * each rendered as a branded check line.
272
+ *
273
+ * @returns Resolves once the report is printed.
274
+ * @example
275
+ * ```ts
276
+ * await app.cli.doctor();
277
+ * ```
278
+ */
279
+ doctor(): Promise<void>;
280
+ /**
281
+ * Print the resolved Cloudflare account for the current `.env` token (delegates to verifyAuth).
282
+ *
283
+ * @returns Resolves once the account summary is printed.
284
+ * @example
285
+ * ```ts
286
+ * await app.cli.whoami();
287
+ * ```
288
+ */
289
+ whoami(): Promise<void>;
290
+ /**
291
+ * Run an arbitrary `wrangler` command through the branded CLI — the escape hatch for subcommands
292
+ * Moku does not wrap (kv / d1 / r2 / queues / secret / tail / …). Streams wrangler's output.
293
+ *
294
+ * @param args - The wrangler arguments (e.g. ["kv", "namespace", "list"]).
295
+ * @returns Resolves once wrangler exits.
296
+ * @example
297
+ * ```ts
298
+ * await app.cli.wrangler(["kv", "namespace", "list"]);
299
+ * ```
300
+ */
301
+ wrangler(args: string[]): Promise<void>;
302
+ };
303
+ //#endregion
304
+ //#region src/plugins/cli/index.d.ts
305
+ /**
306
+ * Standard tier (node-only) — developer-facing CLI surface.
307
+ *
308
+ * Mounts `app.cli.dev()` and `app.cli.deploy()` as thin passthroughs to deployPlugin.
309
+ * Hooks subscribe to the global deploy:phase / provision:resource / deploy:complete events
310
+ * and print a live progress TUI via the injected ctx.log core API.
311
+ *
312
+ * Inline lambdas on `api`/`hooks` preserve event-name inference so the hook map keys
313
+ * are constrained to `WorkerEvents` keys (spec/15 §5).
314
+ *
315
+ * @see README.md
316
+ */
317
+ declare const cliPlugin: import("@moku-labs/core").PluginInstance<"cli", Config, Record<string, never>, Api, {}> & Record<never, never>;
318
+ //#endregion
319
+ //#region src/plugins/deploy/index.d.ts
320
+ /**
321
+ * Complex tier (node-only) — build-time deploy orchestrator over the five resource plugins.
322
+ *
323
+ * Assembles each resource plugin's deployManifest() via ctx.require, provisions resources,
324
+ * generates/updates wrangler config, uploads the R2 upload dir, and runs wrangler deploy.
325
+ * Also supports a universal path: run({ manifest }) uses a caller-supplied manifest verbatim.
326
+ *
327
+ * Emits only the global events `deploy:phase`, `deploy:complete`, and `provision:resource`
328
+ * (declared in WorkerEvents — no per-plugin events block).
329
+ *
330
+ * @see README.md
331
+ */
332
+ declare const deployPlugin: import("@moku-labs/core").PluginInstance<"deploy", Config$1, Record<string, never>, {
333
+ run(opts?: {
334
+ ci?: boolean;
335
+ webBuild?: WebBuild;
336
+ manifest?: ExternalManifest;
337
+ }): Promise<void>;
338
+ dev: (opts?: {
339
+ port?: number;
340
+ webBuild?: WebBuild;
341
+ }) => Promise<void>;
342
+ init: (opts?: {
343
+ ci?: boolean;
344
+ }) => Promise<void>;
345
+ checkInfra: () => Promise<InfraPlan>;
346
+ provisionInfra: (plan: InfraPlan) => Promise<ProvisionResult>;
347
+ verifyAuth: () => Promise<AuthStatus>;
348
+ requiredToken: () => TokenRequirement;
349
+ tokenInstructions: () => string;
350
+ wrangler: (args: string[]) => Promise<void>;
351
+ }, {}> & Record<never, never>;
352
+ //#endregion
353
+ export { WorkerConfig as a, WorkerPluginCtx as c, ResourceManifest as i, cliPlugin as n, WorkerEnv as o, ExternalManifest as r, WorkerEvents as s, deployPlugin as t };