@zabaca/zbc 0.4.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import * as path from 'node:path'
2
2
  import * as fs from 'node:fs'
3
- import { execFileSync, execSync } from 'node:child_process'
3
+ import { execSync, spawnSync } from 'node:child_process'
4
4
  import { z } from 'zod'
5
5
  import { defineModule } from '../../src/define-module'
6
6
 
@@ -8,14 +8,14 @@ import { defineModule } from '../../src/define-module'
8
8
  * cloudflare — deploys a Cloudflare Worker (optionally with static assets, a
9
9
  * Durable Object, and a Container) via `wrangler deploy`.
10
10
  *
11
- * This is a THIN orchestrator, the same shape as the vercel/turso/lima-engine
12
- * modules: `apply` runs on the operator machine, reads CF creds from
13
- * `ctx.secrets`, runs an optional local build, then shells `wrangler deploy` in
14
- * the package's own directory. The Worker TOPOLOGY (name, assets binding,
15
- * durable_objects, containers, migrations) lives in that package's
16
- * `wrangler.jsonc` — wrangler is the source of truth for it, not this module.
17
- * That keeps the module reusable for the eventual Astro-off-Vercel migration
18
- * (a plain assets Worker) as well as the container-backed payloads.
11
+ * This is a THIN orchestrator, the same shape as the turso module: `apply` runs
12
+ * on the operator machine, reads CF creds from `ctx.secrets`, runs an optional
13
+ * local build, then shells `wrangler deploy` in the package's own directory. The
14
+ * Worker TOPOLOGY (name, assets binding, durable_objects, containers,
15
+ * migrations) lives in that package's `wrangler.jsonc` — wrangler is the source
16
+ * of truth for it, not this module. That keeps the module reusable for both
17
+ * plain assets Workers (e.g. a static Astro/Next site) and container-backed
18
+ * payloads (e.g. a DO-bound NATS server).
19
19
  *
20
20
  * Auth is non-interactive: wrangler reads `CLOUDFLARE_API_TOKEN` +
21
21
  * `CLOUDFLARE_ACCOUNT_ID` from the environment, so no `wrangler login` is
@@ -27,35 +27,58 @@ import { defineModule } from '../../src/define-module'
27
27
  * with Docker, so Docker must be running locally at apply time, and the account
28
28
  * must be on a Workers Paid plan with Containers enabled. A plain assets Worker
29
29
  * (Phase A) has neither requirement.
30
+ *
31
+ * Two config knobs shape WHICH worker a given apply targets:
32
+ * - `wranglerEnv` selects a named `env.<name>` block in the package's
33
+ * wrangler.jsonc (`--env`), so one package can ship distinct workers per zbc
34
+ * environment from a single config file.
35
+ * - `workerName` renames the deployed worker (`--name`), which is what powers
36
+ * per-PR preview workers (`zbc-<app>-pr-<N>`). The `*.workers.dev` deploy-URL
37
+ * regex still matches a renamed worker's URL.
38
+ *
39
+ * IMPORT SYNC: `workerSecrets` and `workerVars` entries can be either a plain
40
+ * name (resolved from this environment's secrets.yaml, exactly as before) or a
41
+ * `{ name, from, output }` reference into an imported instance's outputs
42
+ * (`ctx.imports[from][output]`, populated by the engine from that instance's
43
+ * validated outputs). Secrets are pushed via `wrangler secret put`, piped
44
+ * through stdin; vars are passed as `wrangler deploy --var KEY:VALUE`. The two
45
+ * are deliberately separate fields — a var is visible in `wrangler.jsonc`/the
46
+ * dashboard, a secret is not — so an imported value's exposure is an explicit
47
+ * per-entry choice, never inferred. Referencing an instance not listed in this
48
+ * instance's `imports`, or an output key that instance doesn't emit, is a hard
49
+ * error naming both.
30
50
  */
31
51
 
32
52
  /** Resolve the wrangler binary: prefer the package-local one, else `bunx`. */
33
53
  function resolveWrangler(workdir: string): { cmd: string; pre: string[] } {
34
54
  const local = path.join(workdir, 'node_modules', '.bin', 'wrangler')
35
55
  if (fs.existsSync(local)) return { cmd: local, pre: [] }
36
- // Fall back to bunx; --bun keeps it on the bun runtime already in use.
37
- return { cmd: 'bunx', pre: ['--bun', 'wrangler'] }
56
+ // Fall back to bunx on the NODE runtime. Never pass --bun: wrangler under
57
+ // the bun runtime exits 0 after uploading the version but silently skips the
58
+ // deploy/trigger step (2026-07-12 lov incident in Zabaca/ceo: three green
59
+ // applies, zero code deployed).
60
+ return { cmd: 'bunx', pre: ['wrangler'] }
38
61
  }
39
62
 
40
63
  /** Run wrangler in `workdir` with CF creds in the env; return captured stdout. */
41
64
  function wrangler(workdir: string, args: string[], env: NodeJS.ProcessEnv, input?: string): string {
42
65
  const { cmd, pre } = resolveWrangler(workdir)
43
- try {
44
- const out = execFileSync(cmd, [...pre, ...args], {
45
- cwd: workdir,
46
- env,
47
- input,
48
- stdio: ['pipe', 'pipe', 'pipe'],
49
- maxBuffer: 64 * 1024 * 1024,
50
- })
51
- return out.toString()
52
- } catch (err: unknown) {
53
- const stderr = (err as { stderr?: Buffer }).stderr?.toString() ?? ''
54
- const stdout = (err as { stdout?: Buffer }).stdout?.toString() ?? ''
66
+ // spawnSync (not execFileSync) so BOTH streams are captured on success too:
67
+ // wrangler splits its human output across stdout/stderr, and parsing only
68
+ // stdout is how the 2026-07-12 silent-no-deploy went unnoticed.
69
+ const res = spawnSync(cmd, [...pre, ...args], {
70
+ cwd: workdir,
71
+ env,
72
+ input,
73
+ maxBuffer: 64 * 1024 * 1024,
74
+ })
75
+ const combined = `${res.stdout?.toString() ?? ''}\n${res.stderr?.toString() ?? ''}`
76
+ if (res.status !== 0 || res.error) {
55
77
  throw new Error(
56
- `wrangler ${args.join(' ')} failed:\n${stderr || stdout || (err as Error).message}`,
78
+ `wrangler ${args.join(' ')} failed (exit ${res.status}):\n${combined.trim() || res.error?.message}`,
57
79
  )
58
80
  }
81
+ return combined
59
82
  }
60
83
 
61
84
  const buildSchema = z.object({
@@ -63,6 +86,56 @@ const buildSchema = z.object({
63
86
  cwd: z.string().optional(),
64
87
  })
65
88
 
89
+ /**
90
+ * A worker secret/var entry: either a plain name (resolved from this
91
+ * environment's secrets.yaml) or a reference into an imported instance's
92
+ * outputs (`ctx.imports[from][output]`).
93
+ */
94
+ const workerValueSchema = z.union([
95
+ z.string(),
96
+ z.object({
97
+ /** Env var name inside the Worker. */
98
+ name: z.string(),
99
+ /** Instance name — must be listed in this instance's `imports`. */
100
+ from: z.string(),
101
+ /** Which output of that instance to read. */
102
+ output: z.string(),
103
+ }),
104
+ ])
105
+
106
+ type WorkerValueEntry = z.infer<typeof workerValueSchema>
107
+
108
+ /** Resolve a workerSecrets/workerVars entry to its `{ name, value }` pair. */
109
+ function resolveWorkerValue(
110
+ entry: WorkerValueEntry,
111
+ ctx: { secrets: Record<string, string>; imports: Record<string, unknown> },
112
+ fieldName: string,
113
+ ): { name: string; value: string } {
114
+ if (typeof entry === 'string') {
115
+ const value = ctx.secrets[entry]
116
+ if (!value) {
117
+ throw new Error(
118
+ `${fieldName} references "${entry}" but it's missing from this environment's secrets.yaml`,
119
+ )
120
+ }
121
+ return { name: entry, value }
122
+ }
123
+
124
+ const instanceOutputs = ctx.imports[entry.from]
125
+ if (instanceOutputs === undefined) {
126
+ throw new Error(
127
+ `${fieldName} entry "${entry.name}" references instance "${entry.from}", which is not in this instance's imports`,
128
+ )
129
+ }
130
+ const value = (instanceOutputs as Record<string, unknown> | null)?.[entry.output]
131
+ if (typeof value !== 'string') {
132
+ throw new Error(
133
+ `${fieldName} entry "${entry.name}" references output "${entry.output}" on instance "${entry.from}", which doesn't emit it`,
134
+ )
135
+ }
136
+ return { name: entry.name, value }
137
+ }
138
+
66
139
  export const cloudflareModule = defineModule({
67
140
  name: 'cloudflare',
68
141
  configSchema: z.object({
@@ -76,12 +149,21 @@ export const cloudflareModule = defineModule({
76
149
  /** Optional local build run before deploy (e.g. `vite build` for assets). */
77
150
  build: buildSchema.optional(),
78
151
  /**
79
- * Worker secrets to push after deploy. Each entry names a key in this
80
- * environment's secrets.yaml; the same name becomes a Worker secret
81
- * binding (read at runtime as `env.<NAME>`). Pushed via `wrangler secret
82
- * put` with the value piped through stdin.
152
+ * Worker secrets to push after deploy. Each entry is either a plain name
153
+ * — a key in this environment's secrets.yaml, becoming a Worker secret
154
+ * binding of the same name (read at runtime as `env.<NAME>`) — or a
155
+ * `{ name, from, output }` reference into an imported instance's outputs.
156
+ * Pushed via `wrangler secret put` with the value piped through stdin.
157
+ */
158
+ workerSecrets: z.array(workerValueSchema).default([]),
159
+ /**
160
+ * Worker vars to set at deploy time (`wrangler deploy --var KEY:VALUE`).
161
+ * Same entry shape as `workerSecrets` — plain name (from secrets.yaml) or
162
+ * `{ name, from, output }` — but for non-secret, publicly-visible config.
163
+ * Unlike secrets, var values are passed on the command line, so never
164
+ * route sensitive values through this field.
83
165
  */
84
- workerSecrets: z.array(z.string()).default([]),
166
+ workerVars: z.array(workerValueSchema).default([]),
85
167
  /**
86
168
  * For container-backed Workers: roll the running container to the new image
87
169
  * IMMEDIATELY on deploy (`--containers-rollout immediate`). The wrangler
@@ -91,9 +173,33 @@ export const cloudflareModule = defineModule({
91
173
  * deploy time. No-op for asset-only Workers.
92
174
  */
93
175
  immediateContainerRollout: z.boolean().default(false),
176
+ /**
177
+ * Wrangler named environment (`--env <name>`). When set, deploy and every
178
+ * `secret put` target the matching `env.<name>` block in the package's
179
+ * wrangler.jsonc, so a non-production zbc environment (e.g. `preview`) can
180
+ * ship a DISTINCT worker (own name/domain/bindings) from the same package —
181
+ * without a separate wrangler config. Omit for the top-level (production)
182
+ * worker.
183
+ */
184
+ wranglerEnv: z.string().optional(),
185
+ /**
186
+ * Override the deployed worker name (`--name <workerName>`). This is what
187
+ * enables per-PR preview workers (e.g. `zbc-landing-pr-42`) from a single
188
+ * wrangler.jsonc: the preview instance sets a PR-scoped name so each PR
189
+ * lands on its own isolated worker + `*.workers.dev` URL. Omit to use the
190
+ * `name` declared in wrangler.jsonc.
191
+ */
192
+ workerName: z.string().optional(),
94
193
  }),
95
194
  outputs: z.object({
96
195
  deployUrl: z.string(),
196
+ /**
197
+ * The deployed Worker's script name, parsed from wrangler's "Deployed
198
+ * <name> triggers" confirmation. Lets dependents reference this worker
199
+ * without repeating the name from wrangler.jsonc (e.g. cloudflare-email's
200
+ * catchAll.workerName as `{ from, output: 'workerName' }`).
201
+ */
202
+ workerName: z.string(),
97
203
  }),
98
204
  async apply(config, ctx) {
99
205
  const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
@@ -116,31 +222,60 @@ export const cloudflareModule = defineModule({
116
222
  execSync(config.build.command, { cwd: buildCwd, stdio: 'inherit', env })
117
223
  }
118
224
 
119
- // 2. Deploy. Creates/updates the Worker script (+ assets, DO, container).
225
+ // 2. Resolve every workerVars/workerSecrets entry BEFORE deploy so a bad
226
+ // reference (unknown import, missing output/secret) fails fast, without
227
+ // leaving a deployed-but-unconfigured worker. `resolveWorkerValue` is
228
+ // pure — only the wrangler pushes below have side effects. --var values
229
+ // additionally ship as part of `wrangler deploy` itself (not a follow-up
230
+ // call); secrets are pushed after deploy (step 4) since the script must
231
+ // exist first.
232
+ const resolvedVars = config.workerVars.map((entry) =>
233
+ resolveWorkerValue(entry, ctx, 'workerVars'),
234
+ )
235
+ const resolvedSecrets = config.workerSecrets.map((entry) =>
236
+ resolveWorkerValue(entry, ctx, 'workerSecrets'),
237
+ )
238
+
239
+ // 3. Deploy. Creates/updates the Worker script (+ assets, DO, container).
240
+ // --env selects the named wrangler environment (e.g. preview) so it ships
241
+ // a distinct worker from the same package; --name overrides the worker
242
+ // name (per-PR preview workers); both omitted = the package's default.
120
243
  const deployArgs = ['deploy']
244
+ if (config.wranglerEnv) deployArgs.push('--env', config.wranglerEnv)
245
+ if (config.workerName) deployArgs.push('--name', config.workerName)
121
246
  if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
247
+ for (const { name, value } of resolvedVars) deployArgs.push('--var', `${name}:${value}`)
122
248
  console.log(
123
- ` Deploying via wrangler (in ${config.workdir})${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}`,
249
+ ` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}`,
124
250
  )
125
251
  const out = wrangler(workdir, deployArgs, env)
252
+ // Success theater guard: wrangler can exit 0 without actually deploying
253
+ // (the --bun incident above). Require the deploy confirmation line — and
254
+ // capture the deployed script name from it for the workerName output.
255
+ const deployedMatch = out.match(/Deployed\s+(\S+)\s+triggers/)
256
+ if (!deployedMatch) {
257
+ throw new Error(
258
+ `wrangler deploy exited 0 but printed no "Deployed ... triggers" confirmation:\n${out}`,
259
+ )
260
+ }
261
+ const workerName = deployedMatch[1]!
126
262
  const urlMatch = out.match(/https:\/\/[^\s"',]+\.workers\.dev[^\s"',]*/)
127
263
  const deployUrl = urlMatch?.[0] ?? ''
128
264
  console.log(` Deployed: ${deployUrl || '(URL not parsed — see wrangler output)'}`)
129
265
 
130
- // 3. Push Worker secrets (after deploy: the script must exist first). Value
131
- // piped via stdin so it never lands in a command string or the log.
132
- for (const name of config.workerSecrets) {
133
- const value = ctx.secrets[name]
134
- if (!value) {
135
- throw new Error(
136
- `workerSecrets references "${name}" but it's missing from this environment's secrets.yaml`,
137
- )
138
- }
139
- wrangler(workdir, ['secret', 'put', name], env, value)
266
+ // 4. Push Worker secrets (after deploy: the script must exist first).
267
+ // Already resolved in step 2, so a misconfigured reference never reaches
268
+ // this point. Value piped via stdin so it never lands in a command
269
+ // string or the log.
270
+ for (const { name, value } of resolvedSecrets) {
271
+ const secretArgs = ['secret', 'put', name]
272
+ if (config.wranglerEnv) secretArgs.push('--env', config.wranglerEnv)
273
+ if (config.workerName) secretArgs.push('--name', config.workerName)
274
+ wrangler(workdir, secretArgs, env, value)
140
275
  console.log(` Set Worker secret: ${name}`)
141
276
  }
142
277
 
143
- return { deployUrl }
278
+ return { deployUrl, workerName }
144
279
  },
145
280
  async destroy(config, ctx) {
146
281
  const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
@@ -152,9 +287,13 @@ export const cloudflareModule = defineModule({
152
287
  }
153
288
  const workdir = path.resolve(ctx.projectRoot, config.workdir)
154
289
  // `wrangler delete` removes the Worker (and its DO/container). Non-fatal if
155
- // already gone.
290
+ // already gone. --env / --name target the same worker `apply` deployed
291
+ // (named environment and/or per-PR preview name).
156
292
  try {
157
- wrangler(workdir, ['delete', '--force'], env)
293
+ const deleteArgs = ['delete', '--force']
294
+ if (config.wranglerEnv) deleteArgs.push('--env', config.wranglerEnv)
295
+ if (config.workerName) deleteArgs.push('--name', config.workerName)
296
+ wrangler(workdir, deleteArgs, env)
158
297
  console.log(' Deleted Worker')
159
298
  } catch (err) {
160
299
  console.log(` Worker delete skipped: ${(err as Error).message}`)
@@ -11,5 +11,5 @@
11
11
  "secrets": ["CLOUDFLARE_API_TOKEN"],
12
12
  "signupUrl": "https://dash.cloudflare.com/sign-up",
13
13
  "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
14
- "instructions": "Add CLOUDFLARE_API_TOKEN to packages/infra/environments/<env>/secrets.yaml; set accountId in the instance config (not a secret). The Worker topology lives in the package's own wrangler.jsonc, which is the source of truth for it. Container-backed Workers need Docker running locally at apply time and a Workers Paid plan with Containers enabled."
14
+ "instructions": "Add CLOUDFLARE_API_TOKEN to packages/infra/environments/<env>/secrets.yaml; set accountId in the instance config (not a secret). The Worker topology lives in the package's own wrangler.jsonc, which is the source of truth for it. For per-PR preview workers, set workerName (e.g. `zbc-<app>-pr-${process.env.PR_NUMBER}`) on the preview instance; use wranglerEnv to select a named `env.<name>` block in wrangler.jsonc instead. Container-backed Workers need Docker running locally at apply time and a Workers Paid plan with Containers enabled. workerSecrets/workerVars entries are either a plain name (from secrets.yaml) or `{ name, from, output }` to pull a value from an imported instance's outputs (the instance must also be listed in this instance's `imports`) — secrets are pushed via `wrangler secret put`, vars via `wrangler deploy --var`."
15
15
  }