@zabaca/zbc 0.13.0 → 0.15.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +117 -6
  2. package/package.json +5 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/apply.ts +33 -9
  5. package/src/commands/destroy.ts +1 -1
  6. package/src/commands/init.ts +1 -0
  7. package/src/engine/apply.ts +110 -22
  8. package/src/engine/destroy.ts +183 -14
  9. package/src/engine/discover.ts +1 -1
  10. package/src/engine/resolve.ts +113 -14
  11. package/src/utils/copy-template.ts +10 -0
  12. package/templates/CLAUDE.md +1 -1
  13. package/templates/apps/inbox/package.json +3 -1
  14. package/templates/apps/inbox/tsconfig.json +3 -1
  15. package/templates/apps/inbox/worker/api.ts +197 -0
  16. package/templates/apps/inbox/worker/commands.ts +299 -0
  17. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  18. package/templates/apps/inbox/worker/index.ts +15 -202
  19. package/templates/apps/inbox/worker/mcp.ts +49 -100
  20. package/templates/infra/modules/cloudflare/index.ts +29 -73
  21. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  22. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  23. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  24. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  25. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  26. package/templates/infra/modules/cloudflare-token/index.ts +10 -32
  27. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  28. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  29. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  30. package/templates/infra/modules/fly/index.ts +17 -42
  31. package/templates/infra/modules/fly/registry.json +1 -1
  32. package/templates/infra/modules/host-file/index.ts +6 -7
  33. package/templates/infra/modules/provision-core/index.ts +21 -15
  34. package/templates/infra/modules/r2/index.ts +40 -71
  35. package/templates/infra/modules/r2/registry.json +1 -1
  36. package/templates/infra/modules/remote-provision/index.ts +1 -3
  37. package/templates/infra/modules/turso/index.ts +2 -15
  38. package/templates/infra/modules/vm-provision/index.ts +10 -3
  39. package/templates/infra/src/context.ts +115 -0
  40. package/templates/infra/src/define-module.ts +41 -2
  41. package/templates/infra/src/index.ts +11 -1
  42. package/templates/infra/src/types.ts +85 -3
  43. package/src/commands/add-registry.test.ts +0 -92
  44. package/src/commands/secret.test.ts +0 -717
  45. package/src/commands/vendor-mode.test.ts +0 -183
  46. package/src/infra-types.ts +0 -38
  47. package/src/utils/subtree.test.ts +0 -127
  48. package/templates/apps/inbox/worker/send-op.ts +0 -174
@@ -3,12 +3,13 @@ import * as fs from 'node:fs'
3
3
  import { execSync, spawnSync } from 'node:child_process'
4
4
  import { z } from 'zod'
5
5
  import { defineModule } from '../../src/define-module'
6
+ import { resolveOutput, resolveSecret } from '../../src/context'
6
7
 
7
8
  /**
8
9
  * fly — deploys a package to Fly.io via `fly deploy`.
9
10
  *
10
11
  * Same shape as the `cloudflare` module: a THIN orchestrator. `apply` runs on
11
- * the operator machine, reads the Fly credential from `ctx.secrets`, runs an
12
+ * the operator machine, reads the Fly credential through `ctx.secret`, runs an
12
13
  * optional local build, then shells `fly deploy` in the package's own
13
14
  * directory. The app TOPOLOGY (processes, services, ports, handlers, VM size,
14
15
  * regions, autostop/autostart) lives in that package's `fly.toml` — Fly is the
@@ -77,50 +78,34 @@ const flyValueSchema = z.union([
77
78
 
78
79
  type FlyValueEntry = z.infer<typeof flyValueSchema>
79
80
 
80
- /** Resolve a flySecrets entry to its `{ name, value }` pair. */
81
+ /**
82
+ * Resolve a flySecrets entry to its `{ name, value }` pair.
83
+ *
84
+ * Takes the two raw fields rather than an `ApplyContext` — a full context is
85
+ * structurally one of these, and it keeps the helper callable with a literal.
86
+ * `resolveSecret`/`resolveOutput` are the same implementations `ctx.secret` and
87
+ * `ctx.output` are built from, so the failures read identically either way.
88
+ */
81
89
  export function resolveFlyValue(
82
90
  entry: FlyValueEntry,
83
91
  ctx: { secrets: Record<string, string>; imports: Record<string, unknown> },
84
92
  fieldName: string,
85
93
  ): { name: string; value: string } {
86
94
  if (typeof entry === 'string') {
87
- const value = ctx.secrets[entry]
88
- if (!value) {
89
- throw new Error(
90
- `${fieldName} references "${entry}" but it's missing from this environment's secrets.yaml`,
91
- )
92
- }
93
- return { name: entry, value }
95
+ return { name: entry, value: resolveSecret(ctx.secrets, entry, { field: fieldName }) }
94
96
  }
95
97
 
96
98
  if ('value' in entry) {
97
99
  return { name: entry.name, value: entry.value }
98
100
  }
99
101
 
102
+ const field = `${fieldName} entry "${entry.name}"`
103
+
100
104
  if ('secret' in entry) {
101
- const value = ctx.secrets[entry.secret]
102
- if (!value) {
103
- throw new Error(
104
- `${fieldName} entry "${entry.name}" reads secret "${entry.secret}", ` +
105
- "which is missing from this environment's secrets.yaml",
106
- )
107
- }
108
- return { name: entry.name, value }
105
+ return { name: entry.name, value: resolveSecret(ctx.secrets, entry.secret, { field }) }
109
106
  }
110
107
 
111
- const instanceOutputs = ctx.imports[entry.from]
112
- if (!instanceOutputs) {
113
- throw new Error(
114
- `${fieldName} entry "${entry.name}" reads from instance "${entry.from}", which is not in this instance's imports`,
115
- )
116
- }
117
- const value = (instanceOutputs as Record<string, unknown>)[entry.output]
118
- if (value === undefined) {
119
- throw new Error(
120
- `${fieldName} entry "${entry.name}" reads output "${entry.output}" from instance "${entry.from}", which does not emit it`,
121
- )
122
- }
123
- return { name: entry.name, value: String(value) }
108
+ return { name: entry.name, value: resolveOutput(entry, ctx.imports, field) }
124
109
  }
125
110
 
126
111
  /** Run flyctl, capturing BOTH streams — flyctl splits human output across them,
@@ -286,8 +271,6 @@ export const flyModule = defineModule({
286
271
  * record, to order the two within one apply.
287
272
  */
288
273
  certs: z.array(z.string()).default([]),
289
- /** Destroy+recreate the whole app on every apply (preview environments). */
290
- ephemeral: z.boolean().default(false),
291
274
  }),
292
275
  outputs: z.object({
293
276
  appName: z.string(),
@@ -299,8 +282,7 @@ export const flyModule = defineModule({
299
282
  ipv6: z.string(),
300
283
  }),
301
284
  async apply(config, ctx) {
302
- const token = ctx.secrets['FLY_API_TOKEN']
303
- if (!token) throw new Error('Missing secret: FLY_API_TOKEN')
285
+ const token = ctx.secret('FLY_API_TOKEN')
304
286
 
305
287
  const env: NodeJS.ProcessEnv = { ...process.env, FLY_API_TOKEN: token }
306
288
  const workdir = path.resolve(ctx.projectRoot, config.workdir)
@@ -311,12 +293,6 @@ export const flyModule = defineModule({
311
293
  )
312
294
  }
313
295
 
314
- // 0. Ephemeral: tear the whole app down first so every apply starts clean.
315
- if (config.ephemeral) {
316
- console.log(` Ephemeral: destroying ${appName} before recreate`)
317
- fly(workdir, ['apps', 'destroy', appName, '--yes'], env, { allowFailure: true })
318
- }
319
-
320
296
  // 1. Ensure the app exists. `fly deploy` does not create one, and the
321
297
  // failure it gives for a missing app is not obviously that.
322
298
  const list = fly(workdir, ['apps', 'list'], env)
@@ -438,8 +414,7 @@ export const flyModule = defineModule({
438
414
  return { appName, hostname, ipv4: v4, ipv6: v6 }
439
415
  },
440
416
  async destroy(config, ctx) {
441
- const token = ctx.secrets['FLY_API_TOKEN']
442
- if (!token) throw new Error('Missing secret: FLY_API_TOKEN')
417
+ const token = ctx.secret('FLY_API_TOKEN')
443
418
  const env: NodeJS.ProcessEnv = { ...process.env, FLY_API_TOKEN: token }
444
419
  const workdir = path.resolve(ctx.projectRoot, config.workdir)
445
420
  const appName = config.appName ?? appNameFromFlyToml(workdir)
@@ -8,5 +8,5 @@
8
8
  "secrets": ["FLY_API_TOKEN"],
9
9
  "signupUrl": "https://fly.io/app/sign-up",
10
10
  "tokenUrl": "https://fly.io/user/personal_access_tokens",
11
- "instructions": "Requires flyctl on PATH (`brew install flyctl`). Add FLY_API_TOKEN to packages/infra/environments/<env>/secrets.yaml — mint a PERSONAL ACCESS TOKEN, not a deploy token: a deploy token is app-scoped and cannot create apps or allocate IPs. IMPORTANT: Fly tokens start `FlyV1 fm2_…` and contain a literal space; do not strip whitespace when handling the value or you get a bare 401. The app topology (processes, services, ports, handlers, VM size, autostop/autostart) lives in the package's own fly.toml, which is the source of truth; this module only orchestrates create + IPs + build + deploy. Set `ipv4: \"dedicated\"` for ANY service port that is not 80/443 — shared IPv4 covers 80/443 only, it bills $2/mo, and without it a raw-TCP service is silently unreachable. Dedicated IPv6 is free but may be unroutable from some networks, so it is not a substitute. For per-PR preview apps set `appName` (e.g. `myapp-pr-${process.env.PR_NUMBER}`) plus `ephemeral: true`. `flySecrets` entries are a plain name (from secrets.yaml), `{ name, value }`, or `{ name, from, output }` to pull from an imported instance's outputs; they are staged with `fly secrets set --stage` so the deploy that follows picks them up as one deployment. Set `localBuild: true` to build with the local Docker daemon instead of Fly's remote builder."
11
+ "instructions": "Requires flyctl on PATH (`brew install flyctl`). Add FLY_API_TOKEN to packages/infra/environments/<env>/secrets.yaml — mint a PERSONAL ACCESS TOKEN, not a deploy token: a deploy token is app-scoped and cannot create apps or allocate IPs. IMPORTANT: Fly tokens start `FlyV1 fm2_…` and contain a literal space; do not strip whitespace when handling the value or you get a bare 401. The app topology (processes, services, ports, handlers, VM size, autostop/autostart) lives in the package's own fly.toml, which is the source of truth; this module only orchestrates create + IPs + build + deploy. Set `ipv4: \"dedicated\"` for ANY service port that is not 80/443 — shared IPv4 covers 80/443 only, it bills $2/mo, and without it a raw-TCP service is silently unreachable. Dedicated IPv6 is free but may be unroutable from some networks, so it is not a substitute. For per-PR preview apps set `appName` (e.g. `myapp-pr-${process.env.PR_NUMBER}`) in config, plus `ephemeral: true` on the INSTANCE (a sibling of `name`/`config`, not a config field) — the engine then destroys and recreates the app on every apply. `flySecrets` entries are a plain name (from secrets.yaml), `{ name, value }`, or `{ name, from, output }` to pull from an imported instance's outputs; they are staged with `fly secrets set --stage` so the deploy that follows picks them up as one deployment. Set `localBuild: true` to build with the local Docker daemon instead of Fly's remote builder."
12
12
  }
@@ -22,14 +22,13 @@ export const hostFileModule = defineModule({
22
22
  }),
23
23
  outputs: z.object({ path: z.string(), changed: z.boolean() }),
24
24
  apply: async (config, ctx) => {
25
+ // `allowBlank`: presence is the contract. An empty secret is a legitimate
26
+ // file body, and refusing it would make "no value yet" unrepresentable.
25
27
  const desired =
26
- config.content !== undefined ? config.content : ctx.secrets[config.secretKey!]
27
- if (desired === undefined) {
28
- throw new Error(`secret "${config.secretKey}" not found in secrets.yaml`)
29
- }
30
- const existing = fs.existsSync(config.path)
31
- ? fs.readFileSync(config.path, 'utf8')
32
- : null
28
+ config.content !== undefined
29
+ ? config.content
30
+ : ctx.secret(config.secretKey!, { allowBlank: true })
31
+ const existing = fs.existsSync(config.path) ? fs.readFileSync(config.path, 'utf8') : null
33
32
  const changed = existing !== desired
34
33
  const mode = parseInt(config.mode, 8)
35
34
  if (changed) {
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'node:crypto'
2
+ import { resolveOutput } from '../../src/context'
2
3
 
3
4
  // The parts of "converge the inside of a machine" that do not care how the
4
5
  // work is delivered: what to run, whether to run it, and how to decide that
@@ -93,6 +94,20 @@ export function renderProvisionScript(input: {
93
94
  * Reads `ENVVAR: "instance.field"` references out of another instance's
94
95
  * outputs. Outputs only exist during an apply, so this is the only way a
95
96
  * just-minted credential can reach a script without being written down.
97
+ *
98
+ * Only the dotted spelling is this function's own — `instance.field` is a
99
+ * flatter form than the `{ from, output }` every other module takes, and it is
100
+ * kept because it is what instance files already say. Once split, the lookup
101
+ * is the engine's `resolveOutput`, the same one behind `ctx.output`.
102
+ *
103
+ * `allowBlank`: an empty value is a real answer here. The authkey module mints
104
+ * only when there is a join to perform, and reports `''` otherwise —
105
+ * `shouldProvision` reads exactly that to decide whether an unchanged digest
106
+ * still has work.
107
+ *
108
+ * A non-string output is now an error rather than a `String(value)`. Exporting
109
+ * `TS_AUTHKEY=true` because a ref pointed at a boolean output is not a value
110
+ * any script wanted, and it reaches the guest looking exactly like one that was.
96
111
  */
97
112
  export function resolveVolatileEnv(
98
113
  spec: Record<string, string>,
@@ -104,21 +119,12 @@ export function resolveVolatileEnv(
104
119
  if (dot <= 0 || dot === ref.length - 1) {
105
120
  throw new Error(`volatileEnvFrom.${envVar}: "${ref}" is not of the form instance.field`)
106
121
  }
107
- const instance = ref.slice(0, dot)
108
- const field = ref.slice(dot + 1)
109
- const source = imports[instance]
110
- if (source === undefined || source === null || typeof source !== 'object') {
111
- throw new Error(
112
- `volatileEnvFrom.${envVar}: no imported instance named "${instance}" — add it to this instance's imports`,
113
- )
114
- }
115
- const value = (source as Record<string, unknown>)[field]
116
- if (value === undefined) {
117
- throw new Error(
118
- `volatileEnvFrom.${envVar}: instance "${instance}" has no output field "${field}"`,
119
- )
120
- }
121
- out[envVar] = String(value)
122
+ out[envVar] = resolveOutput(
123
+ { from: ref.slice(0, dot), output: ref.slice(dot + 1) },
124
+ imports,
125
+ `volatileEnvFrom.${envVar}`,
126
+ { allowBlank: true },
127
+ )
122
128
  }
123
129
  return out
124
130
  }
@@ -1,9 +1,10 @@
1
1
  import { z } from 'zod'
2
2
  import { defineModule } from '../../src/define-module'
3
+ import { cf, type CfOptions } from '../cloudflare-api'
3
4
 
4
5
  /**
5
6
  * r2 — provisions a Cloudflare R2 bucket via the REST API (turso-style:
6
- * token from ctx.secrets, idempotent list→create, console.log progress).
7
+ * token through ctx.secret, idempotent list→create, console.log progress).
7
8
  *
8
9
  * Exists so bucket lifecycle is owned by infra instead of being a side effect
9
10
  * of `wrangler deploy` prompting to create a missing bucket. A worker wires
@@ -13,46 +14,18 @@ import { defineModule } from '../../src/define-module'
13
14
  * Token scope: CLOUDFLARE_API_TOKEN needs Account → Workers R2 Storage: Edit.
14
15
  */
15
16
 
16
- const API = 'https://api.cloudflare.com/client/v4'
17
-
18
- interface CfEnvelope<T> {
19
- success: boolean
20
- errors: Array<{ code: number; message: string }>
21
- result: T
22
- }
23
-
24
- async function cfFetch<T>(
25
- token: string,
26
- path: string,
27
- init?: { method?: string; body?: unknown },
28
- ): Promise<T> {
29
- const res = await fetch(`${API}${path}`, {
30
- method: init?.method ?? 'GET',
31
- headers: {
32
- Authorization: `Bearer ${token}`,
33
- 'Content-Type': 'application/json',
34
- },
35
- body: init?.body === undefined ? undefined : JSON.stringify(init.body),
36
- })
37
- let envelope: CfEnvelope<T>
38
- try {
39
- envelope = (await res.json()) as CfEnvelope<T>
40
- } catch {
41
- throw new Error(`Cloudflare API ${path}: HTTP ${res.status} (non-JSON body)`)
42
- }
43
- if (!res.ok || !envelope.success) {
44
- const codes = (envelope.errors ?? []).map((e) => e.code)
45
- const detail = (envelope.errors ?? []).map((e) => `${e.code}: ${e.message}`).join('; ')
46
- if (codes.includes(10000)) {
47
- throw new Error(
48
- `Cloudflare API ${path} rejected the token (10000 Authentication error). ` +
49
- `CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
50
- `Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
51
- )
52
- }
53
- throw new Error(`Cloudflare API ${path} failed (HTTP ${res.status}): ${detail}`)
54
- }
55
- return envelope.result
17
+ /**
18
+ * Named per-code guidance for this module's calls — the one genuinely
19
+ * per-module part of a Cloudflare failure. Everything else about the envelope
20
+ * (the base URL, the error shapes, the typed throw) is `../cloudflare-api`'s.
21
+ */
22
+ const OPTS: CfOptions = {
23
+ hints: {
24
+ 10000:
25
+ `rejected the token (10000 Authentication error). ` +
26
+ `CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
27
+ `Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
28
+ },
56
29
  }
57
30
 
58
31
  export const r2Module = defineModule({
@@ -67,50 +40,36 @@ export const r2Module = defineModule({
67
40
  * applied at creation; Cloudflare doesn't support relocating a bucket.
68
41
  */
69
42
  locationHint: z.string().optional(),
70
- /**
71
- * Destroy+recreate on every apply (preview environments). NOTE: deleting
72
- * a non-empty bucket fails — the management API has no object purge, so
73
- * ephemeral only works cleanly for buckets whose objects the app cleans
74
- * up, or that stay small enough to purge by hand.
75
- */
76
- ephemeral: z.boolean().default(false),
77
43
  }),
78
44
  outputs: z.object({
79
45
  bucketName: z.string(),
80
46
  }),
81
47
  async apply(config, ctx) {
82
- const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
83
- if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
48
+ const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
84
49
  const base = `/accounts/${config.accountId}/r2/buckets`
85
50
 
86
- if (config.ephemeral) {
87
- try {
88
- await cfFetch(apiToken, `${base}/${encodeURIComponent(config.bucketName)}`, {
89
- method: 'DELETE',
90
- })
91
- console.log(` Deleted ephemeral bucket "${config.bucketName}"`)
92
- } catch {
93
- // Didn't exist (or non-empty — creation below will then no-op via the
94
- // existence check, which for ephemeral means stale objects persist).
95
- }
96
- }
97
-
98
- const listing = await cfFetch<{ buckets: Array<{ name: string }> }>(
51
+ const listing = await cf<{ buckets: Array<{ name: string }> }>(
99
52
  apiToken,
53
+ 'GET',
100
54
  `${base}?per_page=1000`,
55
+ undefined,
56
+ OPTS,
101
57
  )
102
58
  const exists = listing.buckets.some((b) => b.name === config.bucketName)
103
59
 
104
60
  if (exists) {
105
61
  console.log(` Bucket "${config.bucketName}" already exists`)
106
62
  } else {
107
- await cfFetch(apiToken, base, {
108
- method: 'POST',
109
- body: {
63
+ await cf(
64
+ apiToken,
65
+ 'POST',
66
+ base,
67
+ {
110
68
  name: config.bucketName,
111
69
  ...(config.locationHint ? { locationHint: config.locationHint } : {}),
112
70
  },
113
- })
71
+ OPTS,
72
+ )
114
73
  console.log(
115
74
  ` Created bucket "${config.bucketName}"${config.locationHint ? ` (${config.locationHint})` : ''}`,
116
75
  )
@@ -118,14 +77,24 @@ export const r2Module = defineModule({
118
77
 
119
78
  return { bucketName: config.bucketName }
120
79
  },
80
+ /**
81
+ * Delete the bucket. NOTE: the management API refuses to delete a NON-EMPTY
82
+ * bucket and has no object purge, so this — and therefore an `ephemeral: true`
83
+ * r2 instance, whose destroy+re-apply the engine drives — only comes out clean
84
+ * for buckets whose objects the app itself removes, or that stay small enough
85
+ * to purge by hand. A refusal is logged, not thrown: it is the ordinary
86
+ * outcome for a bucket still holding data, and a `zbc destroy` that aborted
87
+ * there would strand every instance behind it.
88
+ */
121
89
  async destroy(config, ctx) {
122
- const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
123
- if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
90
+ const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
124
91
  try {
125
- await cfFetch(
92
+ await cf(
126
93
  apiToken,
94
+ 'DELETE',
127
95
  `/accounts/${config.accountId}/r2/buckets/${encodeURIComponent(config.bucketName)}`,
128
- { method: 'DELETE' },
96
+ undefined,
97
+ OPTS,
129
98
  )
130
99
  console.log(` Deleted bucket "${config.bucketName}"`)
131
100
  } catch (err) {
@@ -4,5 +4,5 @@
4
4
  "files": [{ "path": "index.ts" }],
5
5
  "secrets": ["CLOUDFLARE_API_TOKEN"],
6
6
  "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
7
- "instructions": "CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }"
7
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope. In COPY mode run `zbc add cloudflare-api` too.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }"
8
8
  }
@@ -85,9 +85,7 @@ export const remoteProvisionModule = defineModule({
85
85
  apply: async (config, ctx) => {
86
86
  const env: Record<string, string> = { ...config.env }
87
87
  for (const [key, secretKey] of Object.entries(config.envSecrets)) {
88
- const value = ctx.secrets[secretKey]
89
- if (value === undefined) throw new Error(`secret "${secretKey}" not found in secrets.yaml`)
90
- env[key] = value
88
+ env[key] = ctx.secret(secretKey, { allowBlank: true, field: `envSecrets.${key}` })
91
89
  }
92
90
 
93
91
  const volatileEnv = resolveVolatileEnv(config.volatileEnvFrom, ctx.imports)
@@ -96,7 +96,6 @@ export const tursoModule = defineModule({
96
96
  dbName: z.string(),
97
97
  group: z.string().default('default'),
98
98
  primaryLocation: z.string().default('iad'),
99
- ephemeral: z.boolean().default(false),
100
99
  /**
101
100
  * Path to a Drizzle migrations folder, relative to the monorepo root
102
101
  * (resolved via ctx.projectRoot). When provided, apply() runs migrations
@@ -109,8 +108,7 @@ export const tursoModule = defineModule({
109
108
  authToken: z.string(),
110
109
  }),
111
110
  async apply(config, ctx) {
112
- const apiToken = ctx.secrets['TURSO_API_TOKEN']
113
- if (!apiToken) throw new Error('Missing secret: TURSO_API_TOKEN')
111
+ const apiToken = ctx.secret('TURSO_API_TOKEN')
114
112
 
115
113
  // Imported here rather than at the top of the file, the way the migration
116
114
  // dependencies below already are: a consumer that vendors zbc-core but
@@ -121,16 +119,6 @@ export const tursoModule = defineModule({
121
119
  const { createClient } = await import('@tursodatabase/api')
122
120
  const turso = createClient({ org: config.orgName, token: apiToken })
123
121
 
124
- // For ephemeral databases, destroy first to get a clean state
125
- if (config.ephemeral) {
126
- try {
127
- await turso.databases.delete(config.dbName)
128
- console.log(` Deleted ephemeral database "${config.dbName}"`)
129
- } catch {
130
- // Database didn't exist — that's fine
131
- }
132
- }
133
-
134
122
  // Check if database already exists
135
123
  const databases = await turso.databases.list()
136
124
  const existing = databases.find((db) => db.name === config.dbName)
@@ -210,8 +198,7 @@ export const tursoModule = defineModule({
210
198
  }
211
199
  },
212
200
  async destroy(config, ctx) {
213
- const apiToken = ctx.secrets['TURSO_API_TOKEN']
214
- if (!apiToken) throw new Error('Missing secret: TURSO_API_TOKEN')
201
+ const apiToken = ctx.secret('TURSO_API_TOKEN')
215
202
 
216
203
  const { createClient } = await import('@tursodatabase/api')
217
204
  const turso = createClient({ org: config.orgName, token: apiToken })
@@ -44,6 +44,15 @@ export interface VmOutputs {
44
44
  target?: IncusTarget
45
45
  }
46
46
 
47
+ /**
48
+ * The one legitimate raw reader of `ctx.imports`.
49
+ *
50
+ * Every other lookup in core names what it wants — `ctx.output({ from, output
51
+ * }, field)` — because the instance file said so. This one has nothing to name:
52
+ * it SEARCHES the imports for outputs shaped like a vm, so that an instance
53
+ * importing exactly one vm need not repeat that vm's name. A ref-based
54
+ * resolver cannot express "whichever one it is", which is why this stays.
55
+ */
47
56
  export function findVmOutputs(imports: Record<string, unknown>): VmOutputs[] {
48
57
  return Object.values(imports).filter((o): o is VmOutputs => {
49
58
  if (typeof o !== 'object' || o === null) return false
@@ -104,12 +113,10 @@ export const vmProvisionModule = defineModule({
104
113
 
105
114
  const env: Record<string, string> = { ...config.env }
106
115
  for (const [key, secretKey] of Object.entries(config.envSecrets)) {
107
- const value = ctx.secrets[secretKey]
108
116
  // Presence is the contract, not non-emptiness — an intentionally blank
109
117
  // placeholder lets a script no-op the step it gates until the real value
110
118
  // is filled in, at which point the digest changes and it re-provisions.
111
- if (value === undefined) throw new Error(`secret "${secretKey}" not found in secrets.yaml`)
112
- env[key] = value
119
+ env[key] = ctx.secret(secretKey, { allowBlank: true, field: `envSecrets.${key}` })
113
120
  }
114
121
 
115
122
  const volatileEnv = resolveVolatileEnv(config.volatileEnvFrom, ctx.imports)
@@ -0,0 +1,115 @@
1
+ // The two questions every module used to answer for itself.
2
+ //
3
+ // "What is this secret" was written seventeen times, in two spellings that
4
+ // disagree about what absent means (`!value`, which calls an empty string
5
+ // missing, and `=== undefined`, which does not). "What did the instance I
6
+ // imported emit" was written six times, and the copies differed in whether a
7
+ // non-string counted, whether an empty string counted, and which of the three
8
+ // distinct failures they could tell apart.
9
+ //
10
+ // Both live here now, and `ApplyContext` is how a module reaches them. The
11
+ // wording of the three `output` failures is `cloudflare-api`'s `resolveRef`
12
+ // verbatim: a missing import and a missing output are both silently
13
+ // `undefined` otherwise, and an apply that carries `Bearer undefined` fails
14
+ // much later, at a Cloudflare 403 that reads like a permissions problem.
15
+ //
16
+ // Runs under the CLI and under a consumer's own bun. Pure — no I/O, no
17
+ // runtime-specific globals — which is what lets it be tested as a value.
18
+
19
+ import type {
20
+ ApplyContext,
21
+ ApplyContextInput,
22
+ OutputOptions,
23
+ OutputRef,
24
+ SecretOptions,
25
+ } from './types'
26
+
27
+ /** `ctx.secret`, over a plain secrets record. */
28
+ export function resolveSecret(
29
+ secrets: Record<string, string>,
30
+ key: string,
31
+ opts: SecretOptions = {},
32
+ ): string {
33
+ const raw = secrets[key]
34
+ const subject =
35
+ opts.field === undefined ? `Secret "${key}"` : `${opts.field} needs secret "${key}", which`
36
+ if (raw === undefined) {
37
+ throw new Error(`${subject} is missing from this environment's secrets.yaml`)
38
+ }
39
+ // `KEY:` with nothing after it parses to null, and that is the most natural
40
+ // spelling of the intentionally blank placeholder `allowBlank` exists for —
41
+ // so it means what `KEY: ""` means rather than a different failure. The
42
+ // coercion also keeps the return type honest: without it, a module that asked
43
+ // for a string gets `null` and finds out somewhere much further downstream.
44
+ const value = raw === null ? '' : raw
45
+ if (value === '' && !opts.allowBlank) {
46
+ throw new Error(`${subject} is empty in this environment's secrets.yaml`)
47
+ }
48
+ return value
49
+ }
50
+
51
+ /**
52
+ * `ctx.output`, over a plain imports record.
53
+ *
54
+ * The three messages are the whole value of this function: `field` says which
55
+ * line of the instance file to look at, and the three cases are told apart
56
+ * because they have three different fixes.
57
+ *
58
+ * `ref` is typed loosely on purpose. A zod-inferred config marks both halves
59
+ * optional in some spellings, and the checks have to run at runtime regardless
60
+ * — a `from` naming an instance that is not imported is a real failure mode and
61
+ * nothing in the type system is catching it here.
62
+ */
63
+ export function resolveOutput(
64
+ ref: OutputRef,
65
+ imports: Record<string, unknown>,
66
+ field: string,
67
+ opts: OutputOptions = {},
68
+ ): string {
69
+ if (!ref.from || !ref.output) {
70
+ throw new Error(`${field} must name both an instance (\`from\`) and an output (\`output\`)`)
71
+ }
72
+ const outputs = imports[ref.from]
73
+ if (outputs === undefined) {
74
+ throw new Error(
75
+ `${field} references instance "${ref.from}", which is not in this instance's imports`,
76
+ )
77
+ }
78
+ const value = (outputs as Record<string, unknown> | null)?.[ref.output]
79
+ if (typeof value !== 'string' || (value === '' && !opts.allowBlank)) {
80
+ throw new Error(
81
+ `${field} references output "${ref.output}" on instance "${ref.from}", which doesn't emit it`,
82
+ )
83
+ }
84
+ return value
85
+ }
86
+
87
+ /** The context the engine hands a module: the three fields plus the two rules. */
88
+ export function createApplyContext(input: ApplyContextInput): ApplyContext {
89
+ return {
90
+ secrets: input.secrets,
91
+ imports: input.imports,
92
+ projectRoot: input.projectRoot,
93
+ secret(key, opts) {
94
+ return resolveSecret(input.secrets, key, opts)
95
+ },
96
+ output(ref, field, opts) {
97
+ return resolveOutput(ref, input.imports, field, opts)
98
+ },
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Upgrade whatever a caller passed into a full context, leaving one that is
104
+ * already full — the engine's destroy context resolves imports on demand, and
105
+ * rebuilding it here would throw that away.
106
+ *
107
+ * `defineModule` calls this on every `apply`/`destroy`, so a module body may
108
+ * assume the methods exist no matter who invoked it.
109
+ */
110
+ export function ensureApplyContext(ctx: ApplyContextInput | ApplyContext): ApplyContext {
111
+ const candidate = ctx as ApplyContext
112
+ return typeof candidate.secret === 'function' && typeof candidate.output === 'function'
113
+ ? candidate
114
+ : createApplyContext(ctx)
115
+ }
@@ -1,4 +1,5 @@
1
1
  import type { z } from 'zod'
2
+ import { ensureApplyContext } from './context'
2
3
  import type { ApplyFn, DestroyFn, ModuleDefinition, ModuleInstance, InstanceOptions } from './types'
3
4
 
4
5
  interface DefineModuleOptions<TConfig extends z.ZodType, TOutputs extends z.ZodType> {
@@ -9,6 +10,38 @@ interface DefineModuleOptions<TConfig extends z.ZodType, TOutputs extends z.ZodT
9
10
  destroy?: DestroyFn<z.infer<TConfig>>
10
11
  }
11
12
 
13
+ /**
14
+ * The four modules that declared `ephemeral` in their own config schema before
15
+ * 0.14 — and therefore the only four for which `config: { ephemeral: true }` in
16
+ * a consumer's checked-in instance file ever meant anything.
17
+ *
18
+ * The list is deliberately closed. Every other module's `z.object` STRIPPED an
19
+ * `ephemeral` key, so a stray one — copy-pasted from the old README, which
20
+ * documented the flag as a config field — was silently inert. Honouring it
21
+ * everywhere would give that stray key teeth it never had: `wrangler delete
22
+ * --force` against a live Worker on the next `zbc apply production`, or a hard
23
+ * failure on a module that has no `destroy` at all.
24
+ */
25
+ const LEGACY_EPHEMERAL_MODULES = new Set(['turso', 'r2', 'fly', 'cloudflare-token'])
26
+
27
+ /**
28
+ * The pre-0.14 spelling: `ephemeral` as a field of a module's own config
29
+ * schema. Three of the four modules above acted on it inline, with three
30
+ * different failure policies; the fourth declared it and never read it. The
31
+ * engine owns the rule now, but a consumer's checked-in preview instance files
32
+ * still say `config: { ephemeral: true }` and `zbc update` must not break them —
33
+ * so that spelling keeps working for those four, with a deprecation line
34
+ * printed by `zbc apply`.
35
+ */
36
+ export function legacyConfigEphemeral(moduleName: string, config: unknown): boolean {
37
+ return (
38
+ LEGACY_EPHEMERAL_MODULES.has(moduleName) &&
39
+ typeof config === 'object' &&
40
+ config !== null &&
41
+ (config as Record<string, unknown>).ephemeral === true
42
+ )
43
+ }
44
+
12
45
  export function defineModule<TConfig extends z.ZodType, TOutputs extends z.ZodType>(
13
46
  opts: DefineModuleOptions<TConfig, TOutputs>,
14
47
  ): ModuleDefinition<TConfig, TOutputs> {
@@ -16,14 +49,20 @@ export function defineModule<TConfig extends z.ZodType, TOutputs extends z.ZodTy
16
49
  name: opts.name,
17
50
  configSchema: opts.configSchema,
18
51
  outputsSchema: opts.outputs,
19
- apply: opts.apply,
20
- destroy: opts.destroy,
52
+ // The context is normalized HERE rather than in the engine, so a module
53
+ // body may assume `ctx.secret`/`ctx.output` exist whoever called it — the
54
+ // engine, another module's test, a consumer's script. A caller that
55
+ // already holds a full context (the destroy path's on-demand one) is
56
+ // passed through untouched.
57
+ apply: (config, ctx) => opts.apply(config, ensureApplyContext(ctx)),
58
+ destroy: opts.destroy && ((config, ctx) => opts.destroy!(config, ensureApplyContext(ctx))),
21
59
  instance(instanceOpts: InstanceOptions<TConfig>): ModuleInstance<TOutputs> {
22
60
  return {
23
61
  name: instanceOpts.name,
24
62
  moduleName: opts.name,
25
63
  config: instanceOpts.config,
26
64
  imports: instanceOpts.imports ?? [],
65
+ ephemeral: instanceOpts.ephemeral ?? legacyConfigEphemeral(opts.name, instanceOpts.config),
27
66
  _outputsSchema: opts.outputs,
28
67
  _definition: definition as ModuleDefinition<any, TOutputs>,
29
68
  }