@zabaca/zbc 0.26.0 → 0.27.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 (33) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/package.json +1 -1
  3. package/src/commands/secret.ts +1 -66
  4. package/src/commands/update.ts +44 -1
  5. package/src/engine/actions.ts +35 -3
  6. package/src/engine/on-demand.ts +9 -1
  7. package/src/engine/secret-outputs.ts +15 -0
  8. package/src/engine/secrets.ts +81 -1
  9. package/src/utils/copy-refresh.ts +124 -19
  10. package/src/utils/template-history.ts +66 -0
  11. package/templates/history.json +1 -0
  12. package/templates/infra/modules/cloudflare/index.ts +140 -1
  13. package/templates/infra/modules/cloudflare-access/index.ts +176 -65
  14. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  15. package/templates/infra/modules/cloudflare-api/index.ts +56 -0
  16. package/templates/infra/modules/cloudflare-email/index.ts +44 -17
  17. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  18. package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
  19. package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
  20. package/templates/infra/modules/cloudflare-token/index.ts +46 -17
  21. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  22. package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
  23. package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
  24. package/templates/infra/modules/d1/index.ts +37 -35
  25. package/templates/infra/modules/d1/registry.json +1 -1
  26. package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
  27. package/templates/infra/modules/queue/index.ts +28 -18
  28. package/templates/infra/modules/queue/registry.json +1 -1
  29. package/templates/infra/modules/r2/index.ts +20 -11
  30. package/templates/infra/modules/r2/registry.json +1 -1
  31. package/templates/infra/src/context.ts +41 -0
  32. package/templates/infra/src/testing.ts +19 -1
  33. package/templates/infra/src/types.ts +23 -0
@@ -2,6 +2,7 @@ import type { Dirent } from 'node:fs'
2
2
  import * as fs from 'node:fs/promises'
3
3
  import * as path from 'node:path'
4
4
  import { copyTemplateDir, templatesRoot } from './copy-template'
5
+ import { fingerprint, loadTemplateHistory, type TemplateHistory } from './template-history'
5
6
 
6
7
  /**
7
8
  * Copy mode's update path. The CLI already carries the templates it scaffolds,
@@ -9,14 +10,37 @@ import { copyTemplateDir, templatesRoot } from './copy-template'
9
10
  * the engine `src/`, plus every built-in module the project already added.
10
11
  *
11
12
  * Two things it must never do: pull in built-in modules the project did not
12
- * ask for, and touch a module the consumer wrote (anything not bundled). Both
13
- * fall out of "refresh what is present and bundled".
13
+ * ask for, and touch what the consumer wrote. The first falls out of "refresh
14
+ * what is present and bundled". The second cannot be read off a name: a
15
+ * directory called `d1` may hold our module at an older vintage, our module
16
+ * with the consumer's edits, or a `d1` the consumer wrote before ours existed.
17
+ * So every file is asked whether any version of ours ever read like it
18
+ * (`template-history.ts`), and only a file that did is replaced or removed.
14
19
  *
15
- * It overlays *and prunes*: a file upstream renamed away would otherwise stay
16
- * importable beside its replacement, which is a project running two engine
17
- * vintages at once with nothing to show for it.
20
+ * - A module with a file at one of our paths that matches no version of ours
21
+ * is the consumer's: it is kept whole and named. Half a refresh would leave
22
+ * their `index.ts` beside our new `registry.json`.
23
+ * - The engine cannot be kept in part, since its files import each other: an
24
+ * edited engine file stops the update before anything is written.
25
+ * - `overwriteEngine` takes ours for the engine; `overwriteModules` for the
26
+ * modules as well.
27
+ * - A file at a path we never shipped, with content we never shipped, is the
28
+ * consumer's own and is never deleted, flag or no flag.
29
+ *
30
+ * It overlays *and prunes*: a file of ours that upstream renamed away would
31
+ * otherwise stay importable beside its replacement, which is a project running
32
+ * two engine vintages at once with nothing to show for it.
18
33
  */
19
34
 
35
+ export interface RefreshOptions {
36
+ /** Replace engine files the consumer edited with ours. */
37
+ overwriteEngine?: boolean
38
+ /** Replace built-in-named modules the consumer edited or wrote with ours. */
39
+ overwriteModules?: boolean
40
+ /** The fingerprints of every past revision; the shipped list by default. */
41
+ history?: TemplateHistory
42
+ }
43
+
20
44
  export interface RefreshResult {
21
45
  /** Paths (project-relative) refreshed from the bundled templates. */
22
46
  refreshed: string[]
@@ -24,6 +48,17 @@ export interface RefreshResult {
24
48
  removed: string[]
25
49
  /** Paths left alone, with why — symlinks, mostly. */
26
50
  skipped: { path: string; reason: string }[]
51
+ /** Built-in-named modules left whole because these files match no version of ours. */
52
+ kept: { path: string; files: string[] }[]
53
+ /** Files of the consumer's own, beside ours in a refreshed directory, left where they are. */
54
+ own: string[]
55
+ /**
56
+ * Engine files the consumer edited. When this is not empty nothing was
57
+ * written at all: the caller stops and says how to proceed.
58
+ */
59
+ editedEngine: string[]
60
+ /** Sibling modules a refreshed module imports that the project does not have. */
61
+ missingModules: string[]
27
62
  /**
28
63
  * Dependencies a refreshed module declares that packages/infra does not have.
29
64
  * Reported rather than installed: `zbc update` must not reach the network on
@@ -72,24 +107,47 @@ async function walk(root: string, base = ''): Promise<string[]> {
72
107
  return out
73
108
  }
74
109
 
110
+ interface Reading {
111
+ /** At one of our paths, but no version of ours read like this: the consumer's edit. */
112
+ edited: string[]
113
+ /** Ours, at a path this CLI no longer ships: renamed or dropped upstream. */
114
+ renamedAway: string[]
115
+ /** Not at one of our paths and never ours: the consumer's own file. */
116
+ own: string[]
117
+ }
118
+
119
+ /** Sort what is in `destDir` against what `srcDir` ships and what we have ever shipped. */
120
+ async function read(srcDir: string, destDir: string, known: Set<string>): Promise<Reading> {
121
+ const upstream = new Set((await walk(srcDir)).filter((f) => !f.endsWith('.test.ts')))
122
+ const reading: Reading = { edited: [], renamedAway: [], own: [] }
123
+ for (const rel of await walk(destDir)) {
124
+ if (rel.endsWith('.test.ts')) continue
125
+ const content = await fs.readFile(path.join(destDir, rel), 'utf8')
126
+ let ours = known.has(fingerprint(content))
127
+ if (upstream.has(rel)) {
128
+ // Whatever the list says, a file equal to the one about to replace it is ours.
129
+ ours ||=
130
+ fingerprint(await fs.readFile(path.join(srcDir, rel), 'utf8')) === fingerprint(content)
131
+ if (!ours) reading.edited.push(rel)
132
+ } else if (ours) reading.renamedAway.push(rel)
133
+ else reading.own.push(rel)
134
+ }
135
+ return reading
136
+ }
137
+
75
138
  /**
76
- * Overlay `src` onto `dest`, then delete anything in `dest` the template tree
139
+ * Overlay `src` onto `dest`, then delete the files of ours the template tree
77
140
  * no longer has. Test files are excluded both ways — the published CLI drops
78
141
  * them, so their absence upstream is not a rename.
79
142
  */
80
- async function relayDir(srcDir: string, destDir: string): Promise<string[]> {
143
+ async function relayDir(srcDir: string, destDir: string, reading: Reading): Promise<string[]> {
81
144
  await copyTemplateDir(srcDir, destDir, { skipIfExists: false, excludeTests: true })
82
- const upstream = new Set((await walk(srcDir)).filter((f) => !f.endsWith('.test.ts')))
83
- const removed: string[] = []
84
- for (const rel of await walk(destDir)) {
85
- if (upstream.has(rel) || rel.endsWith('.test.ts')) continue
86
- await fs.rm(path.join(destDir, rel))
87
- removed.push(rel)
88
- }
89
- return removed
145
+ for (const rel of reading.renamedAway) await fs.rm(path.join(destDir, rel))
146
+ return reading.renamedAway
90
147
  }
91
148
 
92
149
  interface RegistryDeps {
150
+ modules?: string[]
93
151
  dependencies?: Record<string, string>
94
152
  devDependencies?: Record<string, string>
95
153
  optionalDependencies?: Record<string, string>
@@ -110,6 +168,17 @@ async function declaredDependencies(moduleDir: string): Promise<Record<string, s
110
168
  }
111
169
  }
112
170
 
171
+ /** The sibling modules a module's code imports as `../<name>` (its manifest's `modules`). */
172
+ async function declaredModules(moduleDir: string): Promise<string[]> {
173
+ const file = Bun.file(path.join(moduleDir, 'registry.json'))
174
+ if (!(await file.exists())) return []
175
+ try {
176
+ return ((await file.json()) as RegistryDeps).modules ?? []
177
+ } catch {
178
+ return []
179
+ }
180
+ }
181
+
113
182
  async function installedDependencies(infraDir: string): Promise<Set<string>> {
114
183
  const file = Bun.file(path.join(infraDir, 'package.json'))
115
184
  if (!(await file.exists())) return new Set()
@@ -127,25 +196,46 @@ async function installedDependencies(infraDir: string): Promise<Set<string>> {
127
196
  }
128
197
  }
129
198
 
130
- export async function refreshCopiedTemplates(projectRoot: string): Promise<RefreshResult> {
199
+ export async function refreshCopiedTemplates(
200
+ projectRoot: string,
201
+ options: RefreshOptions = {},
202
+ ): Promise<RefreshResult> {
131
203
  const tplInfra = path.join(templatesRoot(), 'infra')
132
204
  const infraDir = path.join(projectRoot, 'packages/infra')
205
+ const history = options.history ?? loadTemplateHistory()
133
206
  const result: RefreshResult = {
134
207
  refreshed: [],
135
208
  removed: [],
136
209
  skipped: [],
210
+ kept: [],
211
+ own: [],
212
+ editedEngine: [],
213
+ missingModules: [],
137
214
  missingDependencies: {},
138
215
  }
139
216
 
217
+ // Read the engine before writing anything: an edit there stops the whole
218
+ // update, and a stop that has already rewritten three modules is not one.
219
+ const engineSrc = path.join(tplInfra, 'src')
140
220
  const engineDest = path.join(infraDir, 'src')
221
+ let engine: Reading | undefined
141
222
  if (await isSymlink(engineDest)) {
142
223
  // This repo's own packages/infra/src is a symlink into the templates;
143
224
  // writing through it would edit the source of truth from a consumer command.
144
225
  result.skipped.push({ path: 'packages/infra/src', reason: 'symlink' })
145
226
  } else if (await exists(engineDest)) {
146
- const removed = await relayDir(path.join(tplInfra, 'src'), engineDest)
227
+ engine = await read(engineSrc, engineDest, new Set(history.src))
228
+ if (engine.edited.length > 0 && !options.overwriteEngine) {
229
+ result.editedEngine = engine.edited.map((f) => `packages/infra/src/${f}`)
230
+ return result
231
+ }
232
+ }
233
+
234
+ if (engine) {
235
+ const removed = await relayDir(engineSrc, engineDest, engine)
147
236
  result.refreshed.push('packages/infra/src')
148
237
  result.removed.push(...removed.map((f) => `packages/infra/src/${f}`))
238
+ result.own.push(...engine.own.map((f) => `packages/infra/src/${f}`))
149
239
  }
150
240
 
151
241
  const modulesDest = path.join(infraDir, 'modules')
@@ -161,23 +251,38 @@ export async function refreshCopiedTemplates(projectRoot: string): Promise<Refre
161
251
  .map((e) => e.name),
162
252
  )
163
253
  const installed = await installedDependencies(infraDir)
254
+ const wanted = new Set<string>()
164
255
 
165
256
  for (const entry of await fs.readdir(modulesDest, { withFileTypes: true })) {
166
257
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
167
258
  const rel = `packages/infra/modules/${entry.name}`
168
- // Consumer-owned modules are not ours to rewrite.
259
+ // A module under a name we do not ship is the consumer's by its name alone.
169
260
  if (!bundled.has(entry.name)) continue
170
261
  if (entry.isSymbolicLink()) {
171
262
  result.skipped.push({ path: rel, reason: 'symlink' })
172
263
  continue
173
264
  }
174
265
  const srcDir = path.join(tplInfra, 'modules', entry.name)
175
- const removed = await relayDir(srcDir, path.join(modulesDest, entry.name))
266
+ const destDir = path.join(modulesDest, entry.name)
267
+ const reading = await read(srcDir, destDir, new Set(history.modules[entry.name] ?? []))
268
+ if (reading.edited.length > 0 && !options.overwriteModules) {
269
+ result.kept.push({ path: rel, files: reading.edited })
270
+ continue
271
+ }
272
+ const removed = await relayDir(srcDir, destDir, reading)
176
273
  result.refreshed.push(rel)
177
274
  result.removed.push(...removed.map((f) => `${rel}/${f}`))
275
+ result.own.push(...reading.own.map((f) => `${rel}/${f}`))
178
276
  for (const [name, version] of Object.entries(await declaredDependencies(srcDir))) {
179
277
  if (!installed.has(name)) result.missingDependencies[name] = version
180
278
  }
279
+ for (const name of await declaredModules(srcDir)) wanted.add(name)
280
+ }
281
+
282
+ // A refreshed module may import a library that did not exist when the project
283
+ // copied it. `update` adds nothing the project did not ask for, so it says so.
284
+ for (const name of [...wanted].toSorted()) {
285
+ if (!(await exists(path.join(modulesDest, name)))) result.missingModules.push(name)
181
286
  }
182
287
 
183
288
  return result
@@ -0,0 +1,66 @@
1
+ import * as crypto from 'node:crypto'
2
+ import * as fs from 'node:fs'
3
+ import * as path from 'node:path'
4
+ import { templatesRoot } from './copy-template'
5
+
6
+ /**
7
+ * What `zbc update` needs to tell our own old code from a consumer's.
8
+ *
9
+ * A copy-mode project holds the engine and the built-in modules as plain files,
10
+ * and a module directory named `d1` says nothing about who wrote what is in it:
11
+ * one consumer's `d1` is a copy of ours from an earlier release, another's was
12
+ * written before ours existed. The published CLI has no git history to ask, so
13
+ * it carries the answer: a fingerprint of every revision of every file the
14
+ * templates have ever held, per unit (the engine `src`, or one module). A file
15
+ * whose fingerprint is in the set is ours, at some vintage, and is safe to
16
+ * replace or prune. One that is not was written or edited by the consumer.
17
+ *
18
+ * `scripts/template-history.ts` writes the list; it only ever grows.
19
+ */
20
+
21
+ export interface TemplateHistory {
22
+ /** Fingerprints of every revision of every file the engine `src/` has held. */
23
+ src: string[]
24
+ /** The same per built-in module, keyed by directory name. */
25
+ modules: Record<string, string[]>
26
+ }
27
+
28
+ /**
29
+ * Reduce a file to what it does. Out go the things a formatter owns (quote
30
+ * style, semicolons, trailing commas, every space and line break, so a long
31
+ * import prettier wrapped over six lines still reads as ours) and comments.
32
+ *
33
+ * Comments go because the question here is whether replacing the file loses
34
+ * the consumer anything that runs: one consumer rewrote the punctuation of
35
+ * every comment in its copy of the engine, and without this no update could
36
+ * ever reach it. A `//` straight after a colon is left alone, since that is a
37
+ * URL in a string far more often than a comment.
38
+ */
39
+ export function normalize(source: string): string {
40
+ return source
41
+ .replace(/\/\*[\s\S]*?\*\//g, '')
42
+ .replace(/(^|[^:])\/\/.*$/gm, '$1')
43
+ .replace(/["`]/g, "'")
44
+ .replace(/\s+/g, '')
45
+ .replace(/;/g, '')
46
+ .replace(/,(?=[)\]}])/g, '')
47
+ }
48
+
49
+ /** Sixteen hex characters of the normalised content's sha256. */
50
+ export function fingerprint(content: string): string {
51
+ return crypto.createHash('sha256').update(normalize(content)).digest('hex').slice(0, 16)
52
+ }
53
+
54
+ export function historyPath(): string {
55
+ return path.join(templatesRoot(), 'history.json')
56
+ }
57
+
58
+ /** The shipped list. A CLI built without one knows no history, which only makes it more careful. */
59
+ export function loadTemplateHistory(file = historyPath()): TemplateHistory {
60
+ try {
61
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<TemplateHistory>
62
+ return { src: parsed.src ?? [], modules: parsed.modules ?? {} }
63
+ } catch {
64
+ return { src: [], modules: {} }
65
+ }
66
+ }
@@ -0,0 +1 @@
1
+ {"src":["03465882c48eda7a","08dfef58c7aaa085","1cb9fbc7287804fd","212058b4cf645126","2166dfb799348b4e","2bd9836e6e9139f3","3058cf40096977ab","347cfb1ee57ec671","3667704de953bdab","4e244104218fe2cb","55da26c9db6f26cb","58e3f0d05357ead2","59bae6268b36701a","5ddd42dcefb92dd0","68bae40f05467752","747228c705b11d4e","88de60f6114a7fa5","8cacee2fbe4f7a09","917dfe4ddd67ec57","af921031cda3165c","b890770a8b136748","bfd77d3bda314e8b","c8bd2a9e9f9551d9","cb09733a2411579e","cb81b204e5f447cc","cc94f18a004aba5d","d13ace1bb2f53755","d92ca991417d1a9b","dabb9f64240b1c6f"],"modules":{"cloudflare":["06bbf1b35604306d","1c7a6e16f1b867f0","2682c5f3ef6cab0c","2d7a7939eb8872ca","36c1bca208793392","37807fe3d5042276","4cc54e3154bcfe9e","4fe2ea871de6e743","536209f853b71749","6084aa4167618322","687b75ceaebb8ef0","6ac1647137df1a85","6eaad97237ac0687","92cece7eabe7c8c5","9a008df8a0f8c9d1","9e86f4ba937b9ee3","b266de092bc97613","b6382f53b98d13e0","c318abe2edcc0753","e084e73c20088c7b"],"cloudflare-access":["0f185f7b77b44fe3","1ed97208e9bbf058","326b4749c6da0610","3c5894ff0be9d477","4aa1213dc6ca925c","726145d710554917","80d5348067acd076","84833035e9aa15d8","a86a8a893cfcc729","b6704b248c37d423","de14a0c490d8f6f6"],"cloudflare-api":["34dc1f1113b93f5f","418719ea73894a66","45d7cdfda8f6dfdd","4e77033aee735ccb","681aefdbdac1c5e0","82aefe0e0dd2e56b","8dcde96f515fa76d","f32ec49f4c9b6735"],"cloudflare-email":["4780e5b903d80935","4903ce268128fada","5bb76c19abae293d","6a0513bb67d78f8d","74f26c9df5c3c0ae","88a1ecd0d2c06ccb","a2bc5bdf74557624","b857bfe6118205f6","df9155611410f279","e0fb57c584823b00"],"cloudflare-stored-token":["9de9c20f4aae04a0","ba1b80b3be96ed86"],"cloudflare-token":["0d00bccd69cb82df","187986600ef2ecf0","1f1f99b00a70ee32","3b9f45de8a20710e","50d7c8a11a53925d","77efc6d02ca10b4f","855c1be1e8c7e937","9dc7111315ac1684","bdc18b0653a3b14f","c07cb05db1bea974","cf7ccc5e4ede8844","d5402f8bc9f5033b","e0259e092bc4da23","f94e4c4deabcca77","fb3761850c423bf5"],"cloudflare-tunnel":["00244f309afe8850","38e9033e4ea59735","97bce322a23fc5e4","9d8efda9c6558d35","9f632f54006fd107","c80ceae3f00e3f28","d5c4dc57698a2eeb","eb0eea2cd0c91e02"],"cloudflare-zone":["04cc6f77d80e40e8","12024ebde5164d70","171448cf37402fb7","41996b00cada53de","9d7080d7555d3bdd","a28bfae8177e278e","b701f20fa82567d0","d3c653b693cdaa1b","debca2ba59daf43e","eec003d0291bd099"],"d1":["3b747b2fb93146c1","675e62f28440fb7b","c046cc4f036f5c34","c0ac33a4a5453512","c996cb2d09f1bca0","ce79df51660a181b"],"docker-compose-stack":["2af7db146de34e07","ccba371fdefa0889","dcc022bd20d60e89"],"fly":["0cce6a3c9943d3bf","23051a397800c5ee","259dfadde9217dc6","374aa12a383556a5","6d21c3301e7e8c26","aef4216f65d05e11","b38e9eb066e2221f","f4a88196670f6a6e","f4bd5c4694d236b1"],"gcp-api":["07eed51dfc04bcdf","91a9afb707ea9355"],"gcp-service-account":["95d06bb603ba6723","c55994a69b49af81"],"host-dir":["50f6831ecaa0c67b","97ee336e322b8110","b835c422ae865d61"],"host-exec":["21bf91bdce04bac6","4e845769ed158498","bd201ddc1f461399"],"host-file":["3298087996013f79","48e5cdb4f00b3952","6eef31d4c54eaea7","a1bfa0f149e4406d"],"host-symlink":["4402e3207c07ab2d","54c8d9dff657e04b"],"incus-core":["00ab57608ef534e6","1d758ab733b3ab59","308f7a771355ac36","34647f78ac61d048","86f7f4b11fb7e20c","d09814b9c7ad573a"],"incus-storage-pool":["1b1202460c0b2de0","aaca83f691541330"],"nats-server":["2be90e33cdff4955","45e1e06c0ec814e9","93a13ff36d57605f"],"provision-core":["36a34ccca800f6ef","6bba00da01fcbaa2","88e945b115cc393d","8aa73f4a61e5375d","8ac1c148fad308cf","93ed7b1498c71a61"],"queue":["7eb1b4b6a04d87df","81f45c9033ad561d","9067f0b998c9e467","9a9be4e0f39dc4ba"],"r2":["186b6825e1d5f7ba","5db07a6753ff2abc","646407efecb52253","71b8f2fec30b0b52","962279eb12a18f73","b134bb16157a30f0","b3d10e22fd46b380","bf95b7c59ea0c6c5","c6d0d6024066b35c"],"remote-provision":["0365de8bb164e6dc","1989e63bc0039e8a","870a5bad136517bb","8c484514a2e0e58a"],"systemd-mask":["7a7685eda8efe67d","e91437190e65edcb"],"systemd-unit":["288ea5990229f30b","3ce315ef7880610b","9232311112f42b3f"],"turso":["2a5a24e5c569ed64","469281443b3cd144","7172345dac8ed40f","7cb03ab396e4f9a5","877e8db2ab8ecff8","ab3b727f963a18fd","b93a33f372c8c705","fab9090110fad4d4"],"vercel":["01e2a82da909a576","3553da00dd75a0aa","423bac1041a24cc9","7f54cdbd467a3a84","b4886210479aae7e"],"vm":["3fc1abaab5b6ba2d","9317e528780643d6","ea77340408170595","f4782518f103519d","f482753fb60c0709"],"vm-provision":["69501352b3131806","8f594f83c5abf037","926b598ddfb678ea","f9117e35d0cabbc8"]}}
@@ -137,6 +137,60 @@ const buildSchema = z.object({
137
137
  cwd: z.string().optional(),
138
138
  })
139
139
 
140
+ /**
141
+ * Poll `url` until its body contains `expected`, `consecutive` times in a row.
142
+ *
143
+ * A refused connection, a 5xx and an old version are all the same answer here,
144
+ * "not yet", because all three are what a deploy looks like from outside for
145
+ * its first seconds. Only the clock ends the wait, and the error then carries
146
+ * the last thing seen, since "timed out" alone does not say whether the Worker
147
+ * was down, old, or answering something else entirely.
148
+ *
149
+ * Exported for tests.
150
+ */
151
+ export async function awaitServed(opts: {
152
+ url: string
153
+ expected: string
154
+ headers: Record<string, string>
155
+ timeoutMs: number
156
+ intervalMs: number
157
+ consecutive: number
158
+ }): Promise<{ attempts: number; ms: number }> {
159
+ const started = Date.now()
160
+ let attempts = 0
161
+ let streak = 0
162
+ let last = 'no answer yet'
163
+ for (;;) {
164
+ attempts++
165
+ try {
166
+ const res = await fetch(opts.url, {
167
+ headers: opts.headers,
168
+ redirect: 'manual',
169
+ signal: AbortSignal.timeout(Math.max(opts.intervalMs, 10_000)),
170
+ })
171
+ const body = await res.text()
172
+ if (res.ok && body.includes(opts.expected)) {
173
+ streak++
174
+ if (streak >= opts.consecutive) return { attempts, ms: Date.now() - started }
175
+ } else {
176
+ streak = 0
177
+ last = `HTTP ${res.status}: ${body.slice(0, 200).replace(/\s+/g, ' ').trim() || '(empty body)'}`
178
+ }
179
+ } catch (err) {
180
+ streak = 0
181
+ last = `no response (${(err as Error).message})`
182
+ }
183
+ if (Date.now() - started + opts.intervalMs > opts.timeoutMs) {
184
+ throw new Error(
185
+ `${opts.url} did not name the deploy ${opts.expected} within ${Math.round(opts.timeoutMs / 1000)}s ` +
186
+ `(${attempts} request(s)). Last answer: ${last}. ` +
187
+ 'wrangler accepted the deploy, so the code is uploaded; what answers at that address is not it yet, or does not report its id.',
188
+ )
189
+ }
190
+ await new Promise((resolve) => setTimeout(resolve, opts.intervalMs))
191
+ }
192
+ }
193
+
140
194
  /**
141
195
  * The origin a route pattern answers on, for `deployUrl` when there is no
142
196
  * workers.dev URL to report.
@@ -549,6 +603,47 @@ export const cloudflareModule = defineModule({
549
603
  * pinning a value outranks the module deriving one.
550
604
  */
551
605
  deployIdVar: z.string().optional(),
606
+ /**
607
+ * Read the deploy id back from the Worker before the apply returns.
608
+ *
609
+ * wrangler exiting 0 says the upload was accepted. It does not say which
610
+ * version answers a request: the edge serves the old one for a while, a
611
+ * container keeps its old image, a route may point somewhere else. Seven
612
+ * consumers each wrote the same loop after `zbc apply` (poll a path until
613
+ * it names the commit just deployed, and only then tag or go on), and none
614
+ * of them shares a line with another.
615
+ *
616
+ * With this set, apply GETs `path` on the deployed Worker until the body
617
+ * contains the value of `deployIdVar`, `consecutive` times in a row, and
618
+ * fails when `timeoutMs` passes first, saying what the last answer was.
619
+ * What the path answers is the payload's job: a handler that returns its
620
+ * own var proves the Worker, and one that also asks its container proves
621
+ * the container.
622
+ *
623
+ * Needs `deployIdVar`: without an id in the artifact there is nothing to
624
+ * look for, and that is refused before anything is built.
625
+ *
626
+ * Why this is not a `ready` probe: the engine runs a probe only at an
627
+ * `imports` edge, and a deployed Worker is usually what nothing imports.
628
+ */
629
+ deployCheck: z
630
+ .object({
631
+ /** The path to GET, e.g. `/api/health`. */
632
+ path: z.string().startsWith('/'),
633
+ /**
634
+ * Where the Worker answers, e.g. `https://app.example.com`. Defaults to
635
+ * `deployUrl`. Required for a Worker whose hostname is a `custom_domain`
636
+ * in its own wrangler config, which leaves `deployUrl` empty.
637
+ */
638
+ origin: z.string().url().optional(),
639
+ /** Request headers: a literal, or `{ secret }` for a key of secrets.yaml. */
640
+ headers: z.record(z.union([z.string(), z.object({ secret: z.string() })])).default({}),
641
+ timeoutMs: z.number().int().positive().default(180_000),
642
+ intervalMs: z.number().int().positive().default(5_000),
643
+ /** Matching answers in a row before it counts: the edge serves old and new together for a while. */
644
+ consecutive: z.number().int().positive().default(2),
645
+ })
646
+ .optional(),
552
647
  /**
553
648
  * For container-backed Workers: roll the CONTAINER APPLICATION to the new
554
649
  * image on deploy (`--containers-rollout immediate`) instead of wrangler's
@@ -627,6 +722,8 @@ export const cloudflareModule = defineModule({
627
722
  }),
628
723
  outputs: z.object({
629
724
  deployUrl: z.string(),
725
+ /** The value of `deployIdVar` this apply shipped; absent when that key is unset. */
726
+ deployId: z.string().optional(),
630
727
  /**
631
728
  * The deployed Worker's script name, parsed from wrangler's "Deployed
632
729
  * <name> triggers" confirmation. Lets dependents reference this worker
@@ -643,6 +740,22 @@ export const cloudflareModule = defineModule({
643
740
  ? ctx.output(config.apiToken, 'apiToken')
644
741
  : ctx.secret('CLOUDFLARE_API_TOKEN')
645
742
 
743
+ if (config.deployCheck && !config.deployIdVar) {
744
+ throw new Error(
745
+ 'deployCheck is set but deployIdVar is not: the check looks for the deploy id in what the Worker answers, ' +
746
+ 'and without deployIdVar no id is put in the Worker. Set deployIdVar to the var the Worker reports.',
747
+ )
748
+ }
749
+ // Read before anything runs, for the same reason as the token.
750
+ const checkHeaders = Object.fromEntries(
751
+ Object.entries(config.deployCheck?.headers ?? {}).map(([name, value]) => [
752
+ name,
753
+ typeof value === 'string'
754
+ ? value
755
+ : ctx.secret(value.secret, { field: `deployCheck.headers.${name}` }),
756
+ ]),
757
+ )
758
+
646
759
  const env: NodeJS.ProcessEnv = {
647
760
  ...process.env,
648
761
  CLOUDFLARE_API_TOKEN: apiToken,
@@ -797,7 +910,33 @@ export const cloudflareModule = defineModule({
797
910
  console.log(` Set Worker secret: ${name}`)
798
911
  }
799
912
 
800
- return { deployUrl, workerName }
913
+ // 5. Read the deploy id back. After the secrets: each push is a new
914
+ // version of the script, and the one that must answer is the last.
915
+ const deployId = config.deployIdVar
916
+ ? resolvedVars.find((v) => v.name === config.deployIdVar)?.value
917
+ : undefined
918
+ if (config.deployCheck && deployId !== undefined) {
919
+ const origin = (config.deployCheck.origin ?? deployUrl).replace(/\/$/, '')
920
+ if (!origin) {
921
+ throw new Error(
922
+ 'deployCheck has nowhere to ask: wrangler printed no workers.dev URL and this instance has no `routes`. ' +
923
+ 'Set deployCheck.origin to where the Worker answers.',
924
+ )
925
+ }
926
+ const url = `${origin}${config.deployCheck.path}`
927
+ console.log(` Waiting for ${url} to name ${deployId}`)
928
+ const { attempts, ms } = await awaitServed({
929
+ url,
930
+ expected: deployId,
931
+ headers: checkHeaders,
932
+ timeoutMs: config.deployCheck.timeoutMs,
933
+ intervalMs: config.deployCheck.intervalMs,
934
+ consecutive: config.deployCheck.consecutive,
935
+ })
936
+ console.log(` Served: ${deployId} (${attempts} request(s), ${Math.round(ms / 1000)}s)`)
937
+ }
938
+
939
+ return { deployUrl, workerName, ...(deployId !== undefined ? { deployId } : {}) }
801
940
  },
802
941
  async destroy(config, ctx) {
803
942
  // Resolved exactly the way `apply` resolves it. The engine applies the