@zabaca/zbc 0.25.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 (74) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/package.json +1 -1
  3. package/src/commands/init.ts +105 -10
  4. package/src/commands/secret.ts +1 -66
  5. package/src/commands/update.ts +77 -7
  6. package/src/engine/actions.ts +35 -3
  7. package/src/engine/on-demand.ts +9 -1
  8. package/src/engine/secret-outputs.ts +15 -0
  9. package/src/engine/secrets.ts +81 -1
  10. package/src/utils/copy-refresh.ts +124 -19
  11. package/src/utils/detect-mode.ts +1 -1
  12. package/src/utils/host-workspaces.ts +57 -0
  13. package/src/utils/subtree.ts +54 -15
  14. package/src/utils/template-history.ts +66 -0
  15. package/src/utils/vendor-audit.ts +12 -8
  16. package/src/utils/vendor-stamp.ts +10 -0
  17. package/src/utils/vendored-app.ts +3 -0
  18. package/templates/apps/walgit/CONTEXT.md +45 -4
  19. package/templates/apps/walgit/README.md +394 -11
  20. package/templates/apps/walgit/shared/browse.ts +61 -0
  21. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  22. package/templates/apps/walgit/shared/container-env.ts +12 -0
  23. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  24. package/templates/apps/walgit/shared/credentials.ts +4 -0
  25. package/templates/apps/walgit/shared/events.ts +35 -1
  26. package/templates/apps/walgit/shared/instructions.ts +4 -1
  27. package/templates/apps/walgit/shared/landing.ts +2 -1
  28. package/templates/apps/walgit/shared/llms.ts +73 -5
  29. package/templates/apps/walgit/shared/mcp.ts +19 -3
  30. package/templates/apps/walgit/shared/protocol.ts +40 -3
  31. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  32. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  33. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  34. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  35. package/templates/apps/walgit/shared/webhook.ts +281 -0
  36. package/templates/apps/walgit/src/admin.ts +510 -0
  37. package/templates/apps/walgit/src/announce-main.ts +17 -9
  38. package/templates/apps/walgit/src/announce.ts +86 -0
  39. package/templates/apps/walgit/src/browse.ts +255 -2
  40. package/templates/apps/walgit/src/cli.ts +140 -0
  41. package/templates/apps/walgit/src/expire.ts +5 -0
  42. package/templates/apps/walgit/src/git.ts +103 -0
  43. package/templates/apps/walgit/src/hook-main.ts +6 -3
  44. package/templates/apps/walgit/src/http.ts +563 -3
  45. package/templates/apps/walgit/src/limits.ts +3 -0
  46. package/templates/apps/walgit/src/merge.ts +525 -0
  47. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  48. package/templates/apps/walgit/src/server.ts +65 -1
  49. package/templates/apps/walgit/worker/events-do.ts +218 -3
  50. package/templates/apps/walgit/worker/index.ts +134 -9
  51. package/templates/apps/walgit/worker/mcp.ts +17 -2
  52. package/templates/history.json +1 -0
  53. package/templates/infra/modules/cloudflare/index.ts +140 -1
  54. package/templates/infra/modules/cloudflare-access/index.ts +176 -65
  55. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  56. package/templates/infra/modules/cloudflare-api/index.ts +56 -0
  57. package/templates/infra/modules/cloudflare-email/index.ts +44 -17
  58. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  59. package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
  60. package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
  61. package/templates/infra/modules/cloudflare-token/index.ts +46 -17
  62. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  63. package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
  64. package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
  65. package/templates/infra/modules/d1/index.ts +37 -35
  66. package/templates/infra/modules/d1/registry.json +1 -1
  67. package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
  68. package/templates/infra/modules/queue/index.ts +28 -18
  69. package/templates/infra/modules/queue/registry.json +1 -1
  70. package/templates/infra/modules/r2/index.ts +20 -11
  71. package/templates/infra/modules/r2/registry.json +1 -1
  72. package/templates/infra/src/context.ts +41 -0
  73. package/templates/infra/src/testing.ts +19 -1
  74. package/templates/infra/src/types.ts +23 -0
@@ -57,6 +57,11 @@ export interface SecretOutputRegistry {
57
57
  * not the caller, decides there is nothing to hide.
58
58
  */
59
59
  record(instance: ModuleInstance, outputs: unknown): void
60
+ /**
61
+ * Remember one credential that is no instance's output: a value an action
62
+ * just stored. It is scrubbed from text as a declared output is.
63
+ */
64
+ recordValue(label: string, value: string): void
60
65
  /** Whether this run has minted anything at all — see `redactError`. */
61
66
  hasSecrets(): boolean
62
67
  /**
@@ -134,6 +139,16 @@ export function createSecretOutputRegistry(): SecretOutputRegistry {
134
139
  secrets.sort((a, b) => b.value.length - a.value.length)
135
140
  }
136
141
  },
142
+ recordValue(label, value) {
143
+ if (value.length < MIN_REDACTABLE_LENGTH) return
144
+ const existing = secrets.find((s) => s.value === value)
145
+ if (existing) {
146
+ if (!existing.labels.includes(label)) existing.labels.push(label)
147
+ return
148
+ }
149
+ secrets.push({ value, labels: [label] })
150
+ secrets.sort((a, b) => b.value.length - a.value.length)
151
+ },
137
152
  hasSecrets() {
138
153
  return secrets.length > 0
139
154
  },
@@ -1,5 +1,5 @@
1
1
  import * as path from 'node:path'
2
- import { parse as parseYaml } from 'yaml'
2
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
3
3
 
4
4
  export async function loadSecrets(envDir: string): Promise<Record<string, string>> {
5
5
  const secretsPath = path.join(envDir, 'secrets.yaml')
@@ -31,3 +31,83 @@ export async function loadSecrets(envDir: string): Promise<Record<string, string
31
31
 
32
32
  return parsed as Record<string, string>
33
33
  }
34
+
35
+ /**
36
+ * Merge `values` into the environment's secrets.yaml. With a `.sops.yaml` at
37
+ * the project root, writes go through sops so plaintext never lands on disk:
38
+ * `sops set` per key into an existing encrypted file, or a stdin-piped
39
+ * `sops -e` (with --filename-override so creation rules match) to create one.
40
+ * Without `.sops.yaml`, falls back to plain YAML (development mode, mirroring
41
+ * loadSecrets).
42
+ */
43
+ export async function writeSecrets(
44
+ projectRoot: string,
45
+ envDir: string,
46
+ values: Record<string, string>,
47
+ opts: { valueViaStdin?: boolean } = {},
48
+ ): Promise<void> {
49
+ const secretsPath = path.join(envDir, 'secrets.yaml')
50
+ const file = Bun.file(secretsPath)
51
+ const exists = await file.exists()
52
+ const hasSopsConfig = await Bun.file(path.join(projectRoot, '.sops.yaml')).exists()
53
+
54
+ if (!hasSopsConfig) {
55
+ const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
56
+ await Bun.write(secretsPath, stringifyYaml({ ...existing, ...values }))
57
+ return
58
+ }
59
+
60
+ const alreadyEncrypted = exists && parseYaml(await file.text())?.sops
61
+ if (alreadyEncrypted) {
62
+ for (const [key, value] of Object.entries(values)) {
63
+ // On stdin the value is in no process listing. `--value-stdin` is newer
64
+ // than `sops set` itself, so only the caller that asks for it depends on it.
65
+ const proc = opts.valueViaStdin
66
+ ? Bun.spawnSync(['sops', 'set', '--value-stdin', secretsPath, `["${key}"]`], {
67
+ cwd: projectRoot,
68
+ env: process.env,
69
+ stdin: new TextEncoder().encode(JSON.stringify(value)),
70
+ stderr: 'pipe',
71
+ })
72
+ : Bun.spawnSync(['sops', 'set', secretsPath, `["${key}"]`, JSON.stringify(value)], {
73
+ cwd: projectRoot,
74
+ env: process.env,
75
+ stderr: 'pipe',
76
+ })
77
+ if (proc.exitCode !== 0) {
78
+ throw new Error(`sops set failed for ${key}: ${proc.stderr.toString()}`)
79
+ }
80
+ }
81
+ return
82
+ }
83
+
84
+ // Missing (or plain, pre-sops) file: merge in memory, encrypt via stdin so
85
+ // plaintext never touches the filesystem.
86
+ const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
87
+ const plaintext = stringifyYaml({ ...existing, ...values })
88
+ const proc = Bun.spawnSync(
89
+ [
90
+ 'sops',
91
+ '--config',
92
+ path.join(projectRoot, '.sops.yaml'),
93
+ '--filename-override',
94
+ secretsPath,
95
+ '-e',
96
+ '--input-type',
97
+ 'yaml',
98
+ '--output-type',
99
+ 'yaml',
100
+ '/dev/stdin',
101
+ ],
102
+ {
103
+ cwd: projectRoot,
104
+ env: process.env,
105
+ stdin: new TextEncoder().encode(plaintext),
106
+ stderr: 'pipe',
107
+ },
108
+ )
109
+ if (proc.exitCode !== 0) {
110
+ throw new Error(`sops encrypt failed: ${proc.stderr.toString()}`)
111
+ }
112
+ await Bun.write(secretsPath, proc.stdout)
113
+ }
@@ -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
@@ -39,7 +39,7 @@ export async function detectMode(cwd: string): Promise<InitMode> {
39
39
  return {
40
40
  kind: 'incompatible',
41
41
  reason:
42
- 'package.json exists but has no `workspaces` field. v1 only supports greenfield or existing Bun workspaces. Add `"workspaces": ["packages/*"]` and re-run.',
42
+ 'package.json exists but has no `workspaces` field, so this is not a Bun workspace (a pnpm repo, say). Put the zbc project in a folder of its own instead — `zbc init <name> --subtree --dir deploy/zbc`, or run init from inside that folder — which leaves this package.json, its lockfile and node_modules alone. Or, for a Bun repo, add `"workspaces": ["packages/*"]` and re-run.',
43
43
  }
44
44
  }
45
45
 
@@ -0,0 +1,57 @@
1
+ import * as path from 'node:path'
2
+ import { parse as parseYaml } from 'yaml'
3
+
4
+ /**
5
+ * The workspace globs a repository's own package manager reads: the root
6
+ * `package.json` `workspaces` (npm, Yarn, Bun) and `pnpm-workspace.yaml`
7
+ * `packages` (pnpm). A missing or unreadable file contributes none.
8
+ */
9
+ export async function hostWorkspaceGlobs(repoTop: string): Promise<string[]> {
10
+ const globs: string[] = []
11
+ const pkgFile = Bun.file(path.join(repoTop, 'package.json'))
12
+ if (await pkgFile.exists()) {
13
+ try {
14
+ const pkg = (await pkgFile.json()) as { workspaces?: string[] | { packages?: string[] } }
15
+ const ws = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces?.packages ?? [])
16
+ globs.push(...ws.filter((g): g is string => typeof g === 'string'))
17
+ } catch {
18
+ // Not ours to diagnose: detect-mode reports an unreadable manifest.
19
+ }
20
+ }
21
+ const pnpmFile = Bun.file(path.join(repoTop, 'pnpm-workspace.yaml'))
22
+ if (await pnpmFile.exists()) {
23
+ try {
24
+ const doc = parseYaml(await pnpmFile.text()) as { packages?: unknown } | null
25
+ if (Array.isArray(doc?.packages)) {
26
+ globs.push(...doc.packages.filter((g): g is string => typeof g === 'string'))
27
+ }
28
+ } catch {
29
+ // An unparseable pnpm-workspace.yaml is pnpm's to complain about.
30
+ }
31
+ }
32
+ return globs
33
+ }
34
+
35
+ // `./apps/*/` and `apps/*` are the same glob to a package manager.
36
+ const strip = (glob: string) => glob.replace(/^\.\//, '').replace(/\/+$/, '')
37
+
38
+ /**
39
+ * The host globs that cover the zbc project folder (`subdir`, top-level
40
+ * relative) or the `packages/infra` package inside it — either one is a
41
+ * package the host's package manager would try to install and link. A `!`
42
+ * glob that excludes the path wins, as it does for pnpm and Yarn.
43
+ */
44
+ export async function hostWorkspaceGlobsCovering(
45
+ repoTop: string,
46
+ subdir: string,
47
+ ): Promise<string[]> {
48
+ const globs = await hostWorkspaceGlobs(repoTop)
49
+ const includes = globs.filter((g) => !g.startsWith('!')).map(strip)
50
+ const excludes = globs.filter((g) => g.startsWith('!')).map((g) => strip(g.slice(1)))
51
+ const candidates = [subdir, `${subdir}/packages/infra`]
52
+ return includes.filter((glob) =>
53
+ candidates.some(
54
+ (dir) => new Bun.Glob(glob).match(dir) && !excludes.some((ex) => new Bun.Glob(ex).match(dir)),
55
+ ),
56
+ )
57
+ }
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process'
2
+ import * as fs from 'node:fs'
2
3
  import * as path from 'node:path'
3
4
 
4
5
  /**
@@ -45,9 +46,43 @@ export function ensureCleanGitTree(cwd: string): void {
45
46
  }
46
47
 
47
48
  /**
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.
49
+ * The repository's top level, or null outside a git work tree. A zbc project
50
+ * may be a subfolder of a larger repository (a pnpm monorepo adopting zbc in
51
+ * `deploy/zbc/`), and git's own paths are the top level's, not the project's.
52
+ */
53
+ export function gitTopLevel(cwd: string): string | null {
54
+ const res = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' })
55
+ if (res.status !== 0 || res.error) return null
56
+ return res.stdout.trim() || null
57
+ }
58
+
59
+ /** The project root relative to the top level, posix-style; '' at the top level or outside git. */
60
+ export function projectSubdir(projectRoot: string): string {
61
+ const top = gitTopLevel(projectRoot)
62
+ if (top === null) return ''
63
+ // Both sides through realpath: git reports the resolved top level, and a
64
+ // project reached through a symlink (macOS's /tmp) would otherwise climb out.
65
+ const rel = path.relative(fs.realpathSync(top), fs.realpathSync(projectRoot))
66
+ return rel.split(path.sep).join('/')
67
+ }
68
+
69
+ /**
70
+ * Where git sees a project-relative path: `vendor/zbc` in a project at the top
71
+ * level, `deploy/zbc/vendor/zbc` in one at `deploy/zbc/`. Derived on every
72
+ * call, never stored, so a project folder that moves keeps working. Outside a
73
+ * git work tree it is the project-relative path unchanged.
74
+ */
75
+ export function gitPrefix(projectRoot: string, prefix: string = VENDOR_PREFIX): string {
76
+ const sub = projectSubdir(projectRoot)
77
+ return sub === '' ? prefix : path.posix.join(sub, prefix)
78
+ }
79
+
80
+ /**
81
+ * Where a subtree lands, relative to the project root. The engine's is
82
+ * `vendor/zbc`, the default; a vendored app names its own (`vendor/space`), so
83
+ * one project can hold several subtrees and each pull only ever touches its own
84
+ * prefix. `git subtree` refuses to run anywhere but the top level, so these
85
+ * resolve the top level and the prefix as git sees it themselves.
51
86
  */
52
87
  interface SubtreeOptions {
53
88
  url: string
@@ -55,31 +90,35 @@ interface SubtreeOptions {
55
90
  prefix?: string
56
91
  }
57
92
 
93
+ function subtree(projectRoot: string, verb: 'add' | 'pull', opts: SubtreeOptions): void {
94
+ ensureCleanGitTree(projectRoot)
95
+ const top = gitTopLevel(projectRoot) ?? projectRoot
96
+ const prefix = gitPrefix(projectRoot, opts.prefix ?? VENDOR_PREFIX)
97
+ git(top, ['subtree', verb, `--prefix=${prefix}`, opts.url, opts.ref, '--squash'])
98
+ }
99
+
58
100
  /** Vendor a repository at the prefix (squashed). One commit, reversible via git. */
59
- export function subtreeAdd(cwd: string, opts: SubtreeOptions): void {
60
- ensureCleanGitTree(cwd)
61
- const prefix = opts.prefix ?? VENDOR_PREFIX
62
- git(cwd, ['subtree', 'add', `--prefix=${prefix}`, opts.url, opts.ref, '--squash'])
101
+ export function subtreeAdd(projectRoot: string, opts: SubtreeOptions): void {
102
+ subtree(projectRoot, 'add', opts)
63
103
  }
64
104
 
65
105
  /** Pull a newer ref into the prefix (squashed merge). */
66
- export function subtreePull(cwd: string, opts: SubtreeOptions): void {
67
- ensureCleanGitTree(cwd)
68
- const prefix = opts.prefix ?? VENDOR_PREFIX
69
- git(cwd, ['subtree', 'pull', `--prefix=${prefix}`, opts.url, opts.ref, '--squash'])
106
+ export function subtreePull(projectRoot: string, opts: SubtreeOptions): void {
107
+ subtree(projectRoot, 'pull', opts)
70
108
  }
71
109
 
72
110
  /**
73
111
  * The upstream commit a prefix was last pulled at, read from git's own record:
74
112
  * every squashed `subtree add` and `subtree pull` writes a commit whose message
75
113
  * carries `git-subtree-dir` and `git-subtree-split`. Null when the prefix was
76
- * never vendored as a subtree in this history.
114
+ * never vendored as a subtree in this history. `prefix` is project-relative;
115
+ * git recorded the top-level-relative one.
77
116
  */
78
- export function subtreeSplitCommit(cwd: string, prefix: string): string | null {
79
- const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
117
+ export function subtreeSplitCommit(projectRoot: string, prefix: string): string | null {
118
+ const escaped = gitPrefix(projectRoot, prefix).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
80
119
  let body: string
81
120
  try {
82
- body = git(cwd, ['log', '-1', `--grep=^git-subtree-dir: ${escaped}/*$`, '--format=%B'])
121
+ body = git(projectRoot, ['log', '-1', `--grep=^git-subtree-dir: ${escaped}/*$`, '--format=%B'])
83
122
  } catch {
84
123
  return null
85
124
  }
@@ -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
+ }
@@ -3,7 +3,7 @@ import type { Dirent } from 'node:fs'
3
3
  import * as fs from 'node:fs/promises'
4
4
  import * as path from 'node:path'
5
5
  import { templatesRoot } from './copy-template'
6
- import { VENDOR_PREFIX } from './subtree'
6
+ import { gitPrefix, gitTopLevel, VENDOR_PREFIX } from './subtree'
7
7
 
8
8
  /**
9
9
  * The reverse drift hazard: files a consumer wrote *inside* `vendor/zbc/`.
@@ -23,15 +23,18 @@ import { VENDOR_PREFIX } from './subtree'
23
23
  * vendor/zbc cannot, and must not be reported as consumer-authored.
24
24
  */
25
25
  function trackedVendorFiles(projectRoot: string): string[] {
26
- const res = spawnSync('git', ['ls-files', '-z', '--', VENDOR_PREFIX], {
27
- cwd: projectRoot,
26
+ // Asked at the top level with the prefix as git sees it, so the listing is
27
+ // the same whether the project is the repository or a subfolder of one.
28
+ const prefix = gitPrefix(projectRoot)
29
+ const res = spawnSync('git', ['ls-files', '-z', '--', prefix], {
30
+ cwd: gitTopLevel(projectRoot) ?? projectRoot,
28
31
  encoding: 'utf8',
29
32
  })
30
33
  if (res.status !== 0 || res.error) return []
31
34
  return res.stdout
32
35
  .split('\0')
33
36
  .filter((line) => line.length > 0)
34
- .map((line) => path.posix.relative(VENDOR_PREFIX, line))
37
+ .map((line) => path.posix.relative(prefix, line))
35
38
  }
36
39
 
37
40
  async function walk(root: string, base = ''): Promise<string[]> {
@@ -62,11 +65,12 @@ export async function foreignVendorFiles(projectRoot: string): Promise<string[]>
62
65
  return vendored.filter((rel) => !rel.endsWith('.test.ts') && !upstream.has(rel)).toSorted()
63
66
  }
64
67
 
65
- export function describeForeignFiles(files: string[]): string[] {
68
+ /** `prefix` is the one to name: the top-level-relative prefix when the project is a subfolder. */
69
+ export function describeForeignFiles(files: string[], prefix: string = VENDOR_PREFIX): string[] {
66
70
  if (files.length === 0) return []
67
71
  return [
68
- `⚠ ${files.length} file(s) under ${VENDOR_PREFIX}/ are not shipped by zbc-core at that path:`,
69
- ...files.map((f) => ` ${VENDOR_PREFIX}/${f}`),
70
- ` ${VENDOR_PREFIX}/ is upstream's — \`git subtree push\` would carry these into zbc-core. Move consumer-authored files outside the prefix (e.g. docs/ or packages/infra/).`,
72
+ `⚠ ${files.length} file(s) under ${prefix}/ are not shipped by zbc-core at that path:`,
73
+ ...files.map((f) => ` ${prefix}/${f}`),
74
+ ` ${prefix}/ is upstream's — \`git subtree push\` would carry these into zbc-core. Move consumer-authored files outside the prefix (e.g. docs/ or packages/infra/).`,
71
75
  ]
72
76
  }
@@ -27,6 +27,13 @@ export interface VendorStamp {
27
27
  cliVersion: string
28
28
  /** zbc-core ref pulled, for subtree mode. */
29
29
  coreRef?: string
30
+ /**
31
+ * The subtree prefix as git saw it, recorded for information only when the
32
+ * project is a subfolder of its repository (`deploy/zbc/vendor/zbc`); absent
33
+ * means `vendor/zbc`. The commands always derive it again, and `zbc update`
34
+ * warns when the two disagree (the folder was moved).
35
+ */
36
+ prefix?: string
30
37
  /** ISO timestamp of the vendoring. */
31
38
  vendoredAt: string
32
39
  }
@@ -47,6 +54,7 @@ export async function readStamp(projectRoot: string): Promise<VendorStamp | null
47
54
  mode: raw.mode,
48
55
  cliVersion: raw.cliVersion,
49
56
  coreRef: typeof raw.coreRef === 'string' ? raw.coreRef : undefined,
57
+ prefix: typeof raw.prefix === 'string' ? raw.prefix : undefined,
50
58
  vendoredAt: typeof raw.vendoredAt === 'string' ? raw.vendoredAt : '',
51
59
  }
52
60
  } catch {
@@ -62,6 +70,8 @@ export async function writeStamp(
62
70
  mode: stamp.mode,
63
71
  cliVersion: stamp.cliVersion,
64
72
  ...(stamp.coreRef ? { coreRef: stamp.coreRef } : {}),
73
+ // A project at the top level writes exactly the stamp it always did.
74
+ ...(stamp.prefix && stamp.prefix !== VENDOR_PREFIX ? { prefix: stamp.prefix } : {}),
65
75
  vendoredAt: stamp.vendoredAt ?? new Date().toISOString(),
66
76
  }
67
77
  // The engine's stamp and the vendored apps' share the file, and each writer