@zabaca/zbc 0.24.0 → 0.25.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 (34) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/list.ts +6 -3
  5. package/src/commands/update.ts +42 -0
  6. package/src/engine/destroy.ts +23 -2
  7. package/src/engine/resolve.ts +5 -0
  8. package/src/utils/subtree.ts +37 -7
  9. package/src/utils/vendor-stamp.ts +92 -1
  10. package/src/utils/vendored-app.ts +353 -0
  11. package/templates/CLAUDE.md +1 -1
  12. package/templates/apps/walgit/worker/mcp.ts +1 -2
  13. package/templates/apps/warehouse/worker/router.ts +1 -2
  14. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  15. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  16. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  17. package/templates/infra/modules/d1/index.ts +133 -4
  18. package/templates/infra/modules/d1/registry.json +4 -1
  19. package/templates/infra/modules/queue/index.ts +313 -0
  20. package/templates/infra/modules/queue/registry.json +13 -0
  21. package/templates/infra/modules/r2/registry.json +1 -1
  22. package/templates/infra/src/define-module.ts +19 -2
  23. package/templates/infra/src/types.ts +24 -0
  24. package/templates/apps/inbox/package.json +0 -26
  25. package/templates/apps/inbox/public/index.html +0 -379
  26. package/templates/apps/inbox/registry.json +0 -9
  27. package/templates/apps/inbox/tsconfig.json +0 -19
  28. package/templates/apps/inbox/worker/api.ts +0 -197
  29. package/templates/apps/inbox/worker/commands.ts +0 -299
  30. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  31. package/templates/apps/inbox/worker/index.ts +0 -195
  32. package/templates/apps/inbox/worker/mcp.ts +0 -228
  33. package/templates/apps/inbox/worker/shared.ts +0 -117
  34. package/templates/apps/inbox/wrangler.jsonc +0 -48
package/CHANGELOG.md CHANGED
@@ -5,6 +5,34 @@ only add or fix things are described by their `release(cli): @zabaca/zbc <x.y.z>
5
5
  commit message and the PRs it names; this file exists for the ones a consumer
6
6
  has to read before upgrading.
7
7
 
8
+ ## 0.25.0
9
+
10
+ ### The `inbox` app template is removed
11
+
12
+ `zbc add inbox` no longer resolves: the single-mailbox inbox Worker is gone from
13
+ the templates, with no alias left behind.
14
+
15
+ A project that already scaffolded it is untouched. `packages/inbox/` and its
16
+ three instance files are that project's own code, they keep deploying as they
17
+ did, and `zbc update` never looked at them. What ends is upstream: no fix to
18
+ that template will arrive.
19
+
20
+ What replaces it is `space`, below: a company's mail is one part of it. It is a
21
+ different application, not a newer inbox, so there is nothing to migrate
22
+ automatically.
23
+
24
+ ### `space` is pulled, not copied
25
+
26
+ `zbc add space` and `zbc update space` vendor a whole application (a small
27
+ company's mail, chat and calls, calendar, forms and signed documents, clients
28
+ and knowledge, in one Worker) as a git subtree of its own public repository at
29
+ `vendor/space/`, on its own version tags. It is not in this package.
30
+
31
+ `.zbc-vendor.json` gains an `apps` entry recording the repository, the ref and
32
+ the commit pulled. Commit it, as you do the engine's stamp. A project that has
33
+ no engine stamp gets a file holding only `apps`, which `zbc apply` reads exactly
34
+ as it read the missing file.
35
+
8
36
  ## 0.16.4
9
37
 
10
38
  ### The package no longer carries the publisher's `node_modules`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zabaca/zbc",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Zabaca stack CLI — scaffold and deploy infrastructure",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -23,7 +23,8 @@
23
23
  "!templates/**/node_modules",
24
24
  "!templates/**/*.test.ts",
25
25
  "!templates/**/.wrangler",
26
- "!templates/**/.DS_Store"
26
+ "!templates/**/.DS_Store",
27
+ "!templates/apps/space"
27
28
  ],
28
29
  "scripts": {
29
30
  "test": "bun test",
@@ -11,6 +11,7 @@ import {
11
11
  copyTemplateFile,
12
12
  } from '../utils/copy-template'
13
13
  import { isVendorMode, VENDOR_PREFIX } from '../utils/subtree'
14
+ import { addVendoredApp, VENDORED_APPS, type VendoredApp } from '../utils/vendored-app'
14
15
 
15
16
  interface RegistryFile {
16
17
  path: string
@@ -66,7 +67,7 @@ interface RegistryManifest {
66
67
  * packages/infra/modules/. 'library': code the modules beside it import and
67
68
  * that defines no module — same directory shape, same install path, but
68
69
  * nothing to write an instance file for. 'app': a full package scaffolded
69
- * into targetDir (e.g. packages/inbox). */
70
+ * into targetDir (e.g. packages/warehouse). */
70
71
  kind?: RegistryKind
71
72
  description?: string
72
73
  files?: RegistryFile[]
@@ -306,9 +307,8 @@ async function installApp(
306
307
  console.log(`zbc add: ${registry.name} (app)`)
307
308
 
308
309
  // 1. Auto-vendor the infra modules this app depends on. One seen-set across
309
- // the whole list: `inbox` names `cloudflare-email` and `r2`, and both of
310
- // those now name `cloudflare-api` — a fresh walk per entry would install
311
- // it twice.
310
+ // the whole list: two of an app's modules routinely name the same library
311
+ // (`cloudflare-api`), and a fresh walk per entry would install it twice.
312
312
  const seen = new Set<string>()
313
313
  for (const dep of registry.modules ?? []) {
314
314
  if (seen.has(dep)) continue
@@ -394,7 +394,7 @@ export const addCommand = defineCommand({
394
394
  module: {
395
395
  type: 'positional',
396
396
  description:
397
- 'Module or app name (e.g. turso, cloudflare, cloudflare-email, r2, inbox, secret-relay, warehouse)',
397
+ 'Module or app name (e.g. turso, cloudflare, cloudflare-email, r2, secret-relay, warehouse, space)',
398
398
  required: true,
399
399
  },
400
400
  'account-id': {
@@ -411,6 +411,14 @@ export const addCommand = defineCommand({
411
411
  description: 'Collect missing registry-declared secrets via a Secret Request (default: true)',
412
412
  default: true,
413
413
  },
414
+ ref: {
415
+ type: 'string',
416
+ description: 'Vendored apps (space): the ref to pull (default: the newest version tag)',
417
+ },
418
+ 'app-url': {
419
+ type: 'string',
420
+ description: 'Vendored apps (space): pull from this repository instead (a fork)',
421
+ },
414
422
  },
415
423
  async run({ args }) {
416
424
  const name = args.module
@@ -422,6 +430,18 @@ export const addCommand = defineCommand({
422
430
  process.exit(1)
423
431
  }
424
432
 
433
+ // A vendored app is not in this package: it is pulled from its own public
434
+ // copy, so it is looked for by name before the bundled registry is.
435
+ const vendoredApp = VENDORED_APPS[name]
436
+ if (vendoredApp) {
437
+ await addVendored(vendoredApp, projectRoot, infraDir, {
438
+ ref: args.ref,
439
+ url: args['app-url'],
440
+ env: args.env,
441
+ })
442
+ return
443
+ }
444
+
425
445
  const source = await resolveModuleSource(projectRoot, name)
426
446
  const registry = (await Bun.file(
427
447
  path.join(source.dir, 'registry.json'),
@@ -458,6 +478,59 @@ export const addCommand = defineCommand({
458
478
  },
459
479
  })
460
480
 
481
+ /**
482
+ * `zbc add <vendored app>`: pull the app's public copy into the project as a
483
+ * subtree, then install the zbc modules its deploy builds from. Files only, as
484
+ * every `add` is: nothing is deployed, and what the pull left in the working
485
+ * tree (the workspace entry, the starting files, the stamp) is the operator's
486
+ * to read and commit.
487
+ */
488
+ async function addVendored(
489
+ app: VendoredApp,
490
+ projectRoot: string,
491
+ infraDir: string,
492
+ opts: { ref?: string; url?: string; env: string },
493
+ ): Promise<void> {
494
+ console.log(`zbc add: ${app.name} (vendored app, pulled into ${app.prefix}/)`)
495
+ let result: Awaited<ReturnType<typeof addVendoredApp>>
496
+ try {
497
+ result = await addVendoredApp(projectRoot, app, opts)
498
+ } catch (err) {
499
+ console.error(`✗ ${(err as Error).message}`)
500
+ process.exit(1)
501
+ }
502
+ console.log(` pulled ${result.ref} (${result.commit.slice(0, 12)}) as one squashed commit`)
503
+ for (const pattern of result.workspacesAdded) console.log(` workspace: ${pattern}`)
504
+
505
+ // The modules the app's deploy builds its instances from. One seen-set, as an
506
+ // app template's dependencies get.
507
+ const seen = new Set<string>()
508
+ for (const dep of result.manifest.modules ?? []) {
509
+ if (seen.has(dep)) continue
510
+ const depRegistry = await installModule(dep, projectRoot, infraDir, {
511
+ quietSkip: true,
512
+ seen,
513
+ asDependency: true,
514
+ })
515
+ if (depRegistry) console.log(` ↳ module its deploy uses: ${dep}`)
516
+ }
517
+
518
+ await run(projectRoot, 'bun', ['install'])
519
+
520
+ console.log('')
521
+ console.log(`✓ ${app.name} is at ${app.prefix}/, recorded in .zbc-vendor.json`)
522
+ if (result.starter.written.length > 0) {
523
+ console.log(
524
+ ` Starting files for the "${opts.env}" environment were written; they are yours to edit.`,
525
+ )
526
+ }
527
+ console.log(` Read ${app.prefix}/docs/install.md for what to fill in before the first apply.`)
528
+ console.log(' Review what the pull left in the working tree, and commit it.')
529
+ console.log(
530
+ ` Later: \`zbc update ${app.name}\` pulls a newer copy over it and keeps your edits.`,
531
+ )
532
+ }
533
+
461
534
  /** Post-install: collect the registry's declared secrets via a Secret Request.
462
535
  * A missing relay downgrades to instructions — `add` itself still succeeds. */
463
536
  async function collectDeclaredSecrets(
@@ -2,7 +2,7 @@ import * as path from 'node:path'
2
2
  import { defineCommand } from 'citty'
3
3
  import { listActions, type ListedAction } from '../engine/actions'
4
4
  import { discoverInstances } from '../engine/discover'
5
- import { isEphemeral, resolveOrder } from '../engine/resolve'
5
+ import { isEphemeral, isRetained, resolveOrder } from '../engine/resolve'
6
6
  import { findProjectRoot } from '../utils/find-project-root'
7
7
  import { loadConfig } from '../utils/load-config'
8
8
 
@@ -11,7 +11,9 @@ export interface ListedInstance {
11
11
  name: string
12
12
  module: string
13
13
  ephemeral: boolean
14
- /** Whether the module defines `destroy` — i.e. whether `zbc destroy` reaches it. */
14
+ /** Set `retain: true`: `zbc destroy` leaves it standing. See `InstanceOptions.retain`. */
15
+ retain: boolean
16
+ /** Whether `zbc destroy` reaches it: the module defines `destroy` and the instance is not retained. */
15
17
  destroyable: boolean
16
18
  imports: string[]
17
19
  /** Operator-invoked verbs the module declares — see `zbc run`. Usually empty. */
@@ -63,6 +65,7 @@ export const listCommand = defineCommand({
63
65
  name: instance.name,
64
66
  module: instance.moduleName,
65
67
  ephemeral: isEphemeral(instance),
68
+ retain: isRetained(instance),
66
69
  destroyable: instance._definition.destroy !== undefined,
67
70
  imports: instance.imports.map((dep) => dep.name),
68
71
  actions: listActions(instance),
@@ -82,7 +85,7 @@ export const listCommand = defineCommand({
82
85
  for (const instance of listed) {
83
86
  const notes = [
84
87
  instance.ephemeral ? 'ephemeral' : '',
85
- instance.destroyable ? 'destroyable' : 'no destroy',
88
+ instance.retain ? 'retain' : instance.destroyable ? 'destroyable' : 'no destroy',
86
89
  instance.imports.length > 0 ? `imports: ${instance.imports.join(', ')}` : '',
87
90
  instance.actions.length > 0
88
91
  ? `actions: ${instance.actions.map((action) => action.name).join(', ')}`
@@ -12,6 +12,7 @@ import {
12
12
  subtreePull,
13
13
  VENDOR_PREFIX,
14
14
  } from '../utils/subtree'
15
+ import { describeAppAudit, updateVendoredApp, VENDORED_APPS } from '../utils/vendored-app'
15
16
  import pkg from '../../package.json' with { type: 'json' }
16
17
 
17
18
  export const updateCommand = defineCommand({
@@ -20,6 +21,20 @@ export const updateCommand = defineCommand({
20
21
  description: `Bring the vendored zbc engine + built-in modules up to this CLI's version`,
21
22
  },
22
23
  args: {
24
+ app: {
25
+ type: 'positional',
26
+ description: `A vendored app to update instead of the engine (${Object.keys(VENDORED_APPS).join(', ')})`,
27
+ required: false,
28
+ },
29
+ ref: {
30
+ type: 'string',
31
+ description:
32
+ 'With an app: the ref to pull (default: the newest version tag; a branch pulls the newest commit)',
33
+ },
34
+ 'app-url': {
35
+ type: 'string',
36
+ description: 'With an app: pull from this repository instead (a fork)',
37
+ },
23
38
  'core-url': {
24
39
  type: 'string',
25
40
  description: `zbc-core repository (default: ${DEFAULT_CORE_URL})`,
@@ -37,6 +52,33 @@ export const updateCommand = defineCommand({
37
52
  async run({ args }) {
38
53
  const projectRoot = await findProjectRoot()
39
54
 
55
+ // A vendored app is updated by name, and only it: the engine's vintage is a
56
+ // separate pull of a separate repository, on its own versions.
57
+ if (args.app !== undefined) {
58
+ const app = VENDORED_APPS[args.app]
59
+ if (!app) {
60
+ console.error(
61
+ `✗ "${args.app}" is not a vendored app. Available: ${Object.keys(VENDORED_APPS).join(', ')}. Run \`zbc update\` alone for the engine and modules.`,
62
+ )
63
+ process.exit(1)
64
+ }
65
+ console.log(`zbc update: ${app.name} → ${app.prefix}`)
66
+ let result: Awaited<ReturnType<typeof updateVendoredApp>>
67
+ try {
68
+ result = await updateVendoredApp(projectRoot, app, { ref: args.ref, url: args['app-url'] })
69
+ } catch (err) {
70
+ console.error(`✗ ${(err as Error).message}`)
71
+ process.exit(1)
72
+ }
73
+ console.log(`✓ ${app.prefix} is on ${result.ref} (${result.commit.slice(0, 12)})`)
74
+ for (const pattern of result.workspacesAdded) console.log(` workspace added: ${pattern}`)
75
+ for (const line of describeAppAudit(app, result.audit)) console.log(line)
76
+ console.log(
77
+ ' Review the squash merge commit, commit .zbc-vendor.json, and run `bun install`.',
78
+ )
79
+ return
80
+ }
81
+
40
82
  // Copy mode used to be a dead end here — the only way to receive an engine
41
83
  // fix was a hand diff, which is how consumers ended up reimplementing what
42
84
  // we ship. The CLI carries the templates, so it can re-lay them in place.
@@ -3,7 +3,7 @@ import type { InstanceRunOptions } from './apply'
3
3
  import { discoverInstances } from './discover'
4
4
  import { withOnDemandImports } from './on-demand'
5
5
  import { createReadinessGate } from './readiness'
6
- import { resolveOrder } from './resolve'
6
+ import { isRetained, resolveOrder } from './resolve'
7
7
  import { createSecretOutputRegistry, redactError } from './secret-outputs'
8
8
  import { loadSecrets } from './secrets'
9
9
 
@@ -37,6 +37,8 @@ export async function destroyInstances(
37
37
  reversed = [found]
38
38
  }
39
39
 
40
+ const retained = new Set(instances.filter(isRetained).map((i) => i.name))
41
+
40
42
  // Outputs of instances applied on demand, shared across the whole run: a
41
43
  // credential minted for one teardown is the same credential for the next.
42
44
  const outputs = new Map<string, unknown>()
@@ -51,6 +53,20 @@ export async function destroyInstances(
51
53
  }
52
54
 
53
55
  for (const instance of reversed) {
56
+ // Before the destroy lookup, because a retained instance has none: the
57
+ // operator is owed the reason, and a request to destroy THIS instance by
58
+ // name is refused rather than reported as a skip that reads like success.
59
+ if (isRetained(instance)) {
60
+ if (opts.target) {
61
+ throw new Error(
62
+ `Instance "${instance.name}" sets retain: zbc destroy never deletes it. Remove retain ` +
63
+ `in a reviewed change first, or delete the resource in the provider by hand.`,
64
+ )
65
+ }
66
+ console.log(`⊘ ${instance.moduleName}:${instance.name} is retained, left standing`)
67
+ continue
68
+ }
69
+
54
70
  const { destroy } = instance._definition
55
71
  if (!destroy) {
56
72
  console.log(`⊘ ${instance.moduleName}:${instance.name} has no destroy — skipping`)
@@ -80,8 +96,13 @@ export async function destroyInstances(
80
96
  `${field} references instance "${ref.from}", whose outputs a targeted destroy will not create. ` +
81
97
  `Run \`zbc destroy <env>\` for the whole environment, which applies "${ref.from}" only to tear ` +
82
98
  `it down again, or apply "${ref.from}" yourself first.`,
99
+ // A retained import is applied like any other (its apply adopts the
100
+ // live resource), but this run will not tear it down, so the line
101
+ // must not say it will.
83
102
  afterApply: (name) =>
84
- `✓ ${name} applied — this destroy created it; the run tears it down below`,
103
+ retained.has(name)
104
+ ? `✓ ${name} applied, because ${instance.name}'s destroy reads it; it is retained, so this run leaves it standing`
105
+ : `✓ ${name} applied — this destroy created it; the run tears it down below`,
85
106
  },
86
107
  (ctx) => destroy(validatedConfig, ctx),
87
108
  )
@@ -97,6 +97,11 @@ export function isEphemeral(instance: ModuleInstance): boolean {
97
97
  return declared ?? legacyConfigEphemeral(instance.moduleName, instance.config)
98
98
  }
99
99
 
100
+ /** Whether `zbc destroy` must leave this instance's resource standing. See `InstanceOptions.retain`. */
101
+ export function isRetained(instance: ModuleInstance): boolean {
102
+ return (instance as { retain?: boolean }).retain === true
103
+ }
104
+
100
105
  /**
101
106
  * An ephemeral instance of a module with no `destroy` is a contradiction, and
102
107
  * the engine refuses it before it applies anything — including the instances
@@ -22,7 +22,7 @@ export async function isVendorMode(projectRoot: string): Promise<boolean> {
22
22
  return Bun.file(path.join(projectRoot, VENDOR_PREFIX, 'src/define-module.ts')).exists()
23
23
  }
24
24
 
25
- function git(cwd: string, args: string[]): string {
25
+ export function git(cwd: string, args: string[]): string {
26
26
  const res = spawnSync('git', args, { cwd, encoding: 'utf8' })
27
27
  if (res.status !== 0 || res.error) {
28
28
  const detail = `${res.stdout ?? ''}\n${res.stderr ?? ''}`.trim()
@@ -44,14 +44,44 @@ export function ensureCleanGitTree(cwd: string): void {
44
44
  }
45
45
  }
46
46
 
47
- /** Vendor core at vendor/zbc (squashed). One commit, reversible via git. */
48
- export function subtreeAdd(cwd: string, opts: { url: string; ref: string }): void {
47
+ /**
48
+ * Where a subtree lands. The engine's is `vendor/zbc`, the default; a vendored
49
+ * app names its own (`vendor/space`), so one project can hold several subtrees
50
+ * and each pull only ever touches its own prefix.
51
+ */
52
+ interface SubtreeOptions {
53
+ url: string
54
+ ref: string
55
+ prefix?: string
56
+ }
57
+
58
+ /** Vendor a repository at the prefix (squashed). One commit, reversible via git. */
59
+ export function subtreeAdd(cwd: string, opts: SubtreeOptions): void {
49
60
  ensureCleanGitTree(cwd)
50
- git(cwd, ['subtree', 'add', `--prefix=${VENDOR_PREFIX}`, opts.url, opts.ref, '--squash'])
61
+ const prefix = opts.prefix ?? VENDOR_PREFIX
62
+ git(cwd, ['subtree', 'add', `--prefix=${prefix}`, opts.url, opts.ref, '--squash'])
51
63
  }
52
64
 
53
- /** Pull a newer core ref into vendor/zbc (squashed merge). */
54
- export function subtreePull(cwd: string, opts: { url: string; ref: string }): void {
65
+ /** Pull a newer ref into the prefix (squashed merge). */
66
+ export function subtreePull(cwd: string, opts: SubtreeOptions): void {
55
67
  ensureCleanGitTree(cwd)
56
- git(cwd, ['subtree', 'pull', `--prefix=${VENDOR_PREFIX}`, opts.url, opts.ref, '--squash'])
68
+ const prefix = opts.prefix ?? VENDOR_PREFIX
69
+ git(cwd, ['subtree', 'pull', `--prefix=${prefix}`, opts.url, opts.ref, '--squash'])
70
+ }
71
+
72
+ /**
73
+ * The upstream commit a prefix was last pulled at, read from git's own record:
74
+ * every squashed `subtree add` and `subtree pull` writes a commit whose message
75
+ * carries `git-subtree-dir` and `git-subtree-split`. Null when the prefix was
76
+ * never vendored as a subtree in this history.
77
+ */
78
+ export function subtreeSplitCommit(cwd: string, prefix: string): string | null {
79
+ const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
80
+ let body: string
81
+ try {
82
+ body = git(cwd, ['log', '-1', `--grep=^git-subtree-dir: ${escaped}/*$`, '--format=%B'])
83
+ } catch {
84
+ return null
85
+ }
86
+ return /^git-subtree-split: ([0-9a-f]{7,64})$/m.exec(body)?.[1] ?? null
57
87
  }
@@ -64,7 +64,98 @@ export async function writeStamp(
64
64
  ...(stamp.coreRef ? { coreRef: stamp.coreRef } : {}),
65
65
  vendoredAt: stamp.vendoredAt ?? new Date().toISOString(),
66
66
  }
67
- await Bun.write(stampPath(projectRoot), `${JSON.stringify(body, null, 2)}\n`)
67
+ // The engine's stamp and the vendored apps' share the file, and each writer
68
+ // owns only its half: an `update` of the engine must not forget which apps
69
+ // the project pulled.
70
+ const apps = await readAppStamps(projectRoot)
71
+ const whole = Object.keys(apps).length > 0 ? { ...body, apps } : body
72
+ await Bun.write(stampPath(projectRoot), `${JSON.stringify(whole, null, 2)}\n`)
73
+ }
74
+
75
+ /**
76
+ * What one vendored app is on: an app (`space`) is pulled as a subtree of its
77
+ * own public copy at its own prefix, on its own versions, so it has a vintage
78
+ * the engine's stamp cannot say. `commit` is the upstream commit, which is what
79
+ * tells a tag pull from a pull of the newest commit and what a survey compares
80
+ * a consumer's files against.
81
+ */
82
+ export interface AppStamp {
83
+ /** The repository pulled from. */
84
+ url: string
85
+ /** The ref asked for: a tag, or a branch for the newest commit. */
86
+ ref: string
87
+ /** The upstream commit that ref resolved to. */
88
+ commit: string
89
+ /** ISO timestamp of the pull. */
90
+ vendoredAt: string
91
+ }
92
+
93
+ /** Every vendored app's stamp, by app name. A missing or unreadable file is none. */
94
+ export async function readAppStamps(projectRoot: string): Promise<Record<string, AppStamp>> {
95
+ const file = Bun.file(stampPath(projectRoot))
96
+ if (!(await file.exists())) return {}
97
+ try {
98
+ const raw = (await file.json()) as { apps?: Record<string, Partial<AppStamp>> }
99
+ const out: Record<string, AppStamp> = {}
100
+ for (const [name, app] of Object.entries(raw.apps ?? {})) {
101
+ if (typeof app?.ref !== 'string' || typeof app.commit !== 'string') continue
102
+ out[name] = {
103
+ url: typeof app.url === 'string' ? app.url : '',
104
+ ref: app.ref,
105
+ commit: app.commit,
106
+ vendoredAt: typeof app.vendoredAt === 'string' ? app.vendoredAt : '',
107
+ }
108
+ }
109
+ return out
110
+ } catch {
111
+ return {}
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Refuse a stamp file that is there and cannot be read, BEFORE a pull: found after it, the pull is already a commit
117
+ * and the project is left half way. A missing file is fine; it is written whole.
118
+ */
119
+ export async function assertStampReadable(projectRoot: string): Promise<void> {
120
+ const file = Bun.file(stampPath(projectRoot))
121
+ if (!(await file.exists())) return
122
+ try {
123
+ await file.json()
124
+ } catch {
125
+ throw new Error(`${STAMP_FILE} is not valid JSON; fix or delete it, then run the command again`)
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Record one app's pull, leaving the engine's stamp and the other apps' as they
131
+ * are. A project with no engine stamp gets a file holding only `apps`, which
132
+ * `readStamp` reads as "unknown", exactly as it read the missing file.
133
+ */
134
+ export async function writeAppStamp(
135
+ projectRoot: string,
136
+ name: string,
137
+ stamp: Omit<AppStamp, 'vendoredAt'> & { vendoredAt?: string },
138
+ ): Promise<void> {
139
+ const file = Bun.file(stampPath(projectRoot))
140
+ let whole: Record<string, unknown> = {}
141
+ if (await file.exists()) {
142
+ try {
143
+ whole = (await file.json()) as Record<string, unknown>
144
+ } catch {
145
+ // Writing over a file that cannot be read would drop the engine's half of it without a word.
146
+ throw new Error(
147
+ `${STAMP_FILE} is not valid JSON; fix or delete it, then run the command again`,
148
+ )
149
+ }
150
+ }
151
+ const apps = await readAppStamps(projectRoot)
152
+ apps[name] = {
153
+ url: stamp.url,
154
+ ref: stamp.ref,
155
+ commit: stamp.commit,
156
+ vendoredAt: stamp.vendoredAt ?? new Date().toISOString(),
157
+ }
158
+ await Bun.write(stampPath(projectRoot), `${JSON.stringify({ ...whole, apps }, null, 2)}\n`)
68
159
  }
69
160
 
70
161
  function parseVersion(v: string): number[] {