@zabaca/zbc 0.24.0 → 0.26.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 (71) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/init.ts +105 -10
  5. package/src/commands/list.ts +6 -3
  6. package/src/commands/update.ts +75 -6
  7. package/src/engine/destroy.ts +23 -2
  8. package/src/engine/resolve.ts +5 -0
  9. package/src/utils/detect-mode.ts +1 -1
  10. package/src/utils/host-workspaces.ts +57 -0
  11. package/src/utils/subtree.ts +78 -9
  12. package/src/utils/vendor-audit.ts +12 -8
  13. package/src/utils/vendor-stamp.ts +102 -1
  14. package/src/utils/vendored-app.ts +356 -0
  15. package/templates/CLAUDE.md +1 -1
  16. package/templates/apps/walgit/CONTEXT.md +45 -4
  17. package/templates/apps/walgit/README.md +394 -11
  18. package/templates/apps/walgit/shared/browse.ts +61 -0
  19. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  20. package/templates/apps/walgit/shared/container-env.ts +12 -0
  21. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  22. package/templates/apps/walgit/shared/credentials.ts +4 -0
  23. package/templates/apps/walgit/shared/events.ts +35 -1
  24. package/templates/apps/walgit/shared/instructions.ts +4 -1
  25. package/templates/apps/walgit/shared/landing.ts +2 -1
  26. package/templates/apps/walgit/shared/llms.ts +73 -5
  27. package/templates/apps/walgit/shared/mcp.ts +19 -3
  28. package/templates/apps/walgit/shared/protocol.ts +40 -3
  29. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  30. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  31. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  32. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  33. package/templates/apps/walgit/shared/webhook.ts +281 -0
  34. package/templates/apps/walgit/src/admin.ts +510 -0
  35. package/templates/apps/walgit/src/announce-main.ts +17 -9
  36. package/templates/apps/walgit/src/announce.ts +86 -0
  37. package/templates/apps/walgit/src/browse.ts +255 -2
  38. package/templates/apps/walgit/src/cli.ts +140 -0
  39. package/templates/apps/walgit/src/expire.ts +5 -0
  40. package/templates/apps/walgit/src/git.ts +103 -0
  41. package/templates/apps/walgit/src/hook-main.ts +6 -3
  42. package/templates/apps/walgit/src/http.ts +563 -3
  43. package/templates/apps/walgit/src/limits.ts +3 -0
  44. package/templates/apps/walgit/src/merge.ts +525 -0
  45. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  46. package/templates/apps/walgit/src/server.ts +65 -1
  47. package/templates/apps/walgit/worker/events-do.ts +218 -3
  48. package/templates/apps/walgit/worker/index.ts +134 -9
  49. package/templates/apps/walgit/worker/mcp.ts +18 -4
  50. package/templates/apps/warehouse/worker/router.ts +1 -2
  51. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  52. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  53. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  54. package/templates/infra/modules/d1/index.ts +133 -4
  55. package/templates/infra/modules/d1/registry.json +4 -1
  56. package/templates/infra/modules/queue/index.ts +313 -0
  57. package/templates/infra/modules/queue/registry.json +13 -0
  58. package/templates/infra/modules/r2/registry.json +1 -1
  59. package/templates/infra/src/define-module.ts +19 -2
  60. package/templates/infra/src/types.ts +24 -0
  61. package/templates/apps/inbox/package.json +0 -26
  62. package/templates/apps/inbox/public/index.html +0 -379
  63. package/templates/apps/inbox/registry.json +0 -9
  64. package/templates/apps/inbox/tsconfig.json +0 -19
  65. package/templates/apps/inbox/worker/api.ts +0 -197
  66. package/templates/apps/inbox/worker/commands.ts +0 -299
  67. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  68. package/templates/apps/inbox/worker/index.ts +0 -195
  69. package/templates/apps/inbox/worker/mcp.ts +0 -228
  70. package/templates/apps/inbox/worker/shared.ts +0 -117
  71. package/templates/apps/inbox/wrangler.jsonc +0 -48
@@ -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
  /**
@@ -22,7 +23,7 @@ export async function isVendorMode(projectRoot: string): Promise<boolean> {
22
23
  return Bun.file(path.join(projectRoot, VENDOR_PREFIX, 'src/define-module.ts')).exists()
23
24
  }
24
25
 
25
- function git(cwd: string, args: string[]): string {
26
+ export function git(cwd: string, args: string[]): string {
26
27
  const res = spawnSync('git', args, { cwd, encoding: 'utf8' })
27
28
  if (res.status !== 0 || res.error) {
28
29
  const detail = `${res.stdout ?? ''}\n${res.stderr ?? ''}`.trim()
@@ -44,14 +45,82 @@ export function ensureCleanGitTree(cwd: string): void {
44
45
  }
45
46
  }
46
47
 
47
- /** Vendor core at vendor/zbc (squashed). One commit, reversible via git. */
48
- export function subtreeAdd(cwd: string, opts: { url: string; ref: string }): void {
49
- ensureCleanGitTree(cwd)
50
- git(cwd, ['subtree', 'add', `--prefix=${VENDOR_PREFIX}`, opts.url, opts.ref, '--squash'])
48
+ /**
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('/')
51
67
  }
52
68
 
53
- /** Pull a newer core ref into vendor/zbc (squashed merge). */
54
- export function subtreePull(cwd: string, opts: { url: string; ref: string }): void {
55
- ensureCleanGitTree(cwd)
56
- git(cwd, ['subtree', 'pull', `--prefix=${VENDOR_PREFIX}`, opts.url, opts.ref, '--squash'])
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.
86
+ */
87
+ interface SubtreeOptions {
88
+ url: string
89
+ ref: string
90
+ prefix?: string
91
+ }
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
+
100
+ /** Vendor a repository at the prefix (squashed). One commit, reversible via git. */
101
+ export function subtreeAdd(projectRoot: string, opts: SubtreeOptions): void {
102
+ subtree(projectRoot, 'add', opts)
103
+ }
104
+
105
+ /** Pull a newer ref into the prefix (squashed merge). */
106
+ export function subtreePull(projectRoot: string, opts: SubtreeOptions): void {
107
+ subtree(projectRoot, 'pull', opts)
108
+ }
109
+
110
+ /**
111
+ * The upstream commit a prefix was last pulled at, read from git's own record:
112
+ * every squashed `subtree add` and `subtree pull` writes a commit whose message
113
+ * carries `git-subtree-dir` and `git-subtree-split`. Null when the prefix was
114
+ * never vendored as a subtree in this history. `prefix` is project-relative;
115
+ * git recorded the top-level-relative one.
116
+ */
117
+ export function subtreeSplitCommit(projectRoot: string, prefix: string): string | null {
118
+ const escaped = gitPrefix(projectRoot, prefix).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
119
+ let body: string
120
+ try {
121
+ body = git(projectRoot, ['log', '-1', `--grep=^git-subtree-dir: ${escaped}/*$`, '--format=%B'])
122
+ } catch {
123
+ return null
124
+ }
125
+ return /^git-subtree-split: ([0-9a-f]{7,64})$/m.exec(body)?.[1] ?? null
57
126
  }
@@ -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,9 +70,102 @@ 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 } : {}),
75
+ vendoredAt: stamp.vendoredAt ?? new Date().toISOString(),
76
+ }
77
+ // The engine's stamp and the vendored apps' share the file, and each writer
78
+ // owns only its half: an `update` of the engine must not forget which apps
79
+ // the project pulled.
80
+ const apps = await readAppStamps(projectRoot)
81
+ const whole = Object.keys(apps).length > 0 ? { ...body, apps } : body
82
+ await Bun.write(stampPath(projectRoot), `${JSON.stringify(whole, null, 2)}\n`)
83
+ }
84
+
85
+ /**
86
+ * What one vendored app is on: an app (`space`) is pulled as a subtree of its
87
+ * own public copy at its own prefix, on its own versions, so it has a vintage
88
+ * the engine's stamp cannot say. `commit` is the upstream commit, which is what
89
+ * tells a tag pull from a pull of the newest commit and what a survey compares
90
+ * a consumer's files against.
91
+ */
92
+ export interface AppStamp {
93
+ /** The repository pulled from. */
94
+ url: string
95
+ /** The ref asked for: a tag, or a branch for the newest commit. */
96
+ ref: string
97
+ /** The upstream commit that ref resolved to. */
98
+ commit: string
99
+ /** ISO timestamp of the pull. */
100
+ vendoredAt: string
101
+ }
102
+
103
+ /** Every vendored app's stamp, by app name. A missing or unreadable file is none. */
104
+ export async function readAppStamps(projectRoot: string): Promise<Record<string, AppStamp>> {
105
+ const file = Bun.file(stampPath(projectRoot))
106
+ if (!(await file.exists())) return {}
107
+ try {
108
+ const raw = (await file.json()) as { apps?: Record<string, Partial<AppStamp>> }
109
+ const out: Record<string, AppStamp> = {}
110
+ for (const [name, app] of Object.entries(raw.apps ?? {})) {
111
+ if (typeof app?.ref !== 'string' || typeof app.commit !== 'string') continue
112
+ out[name] = {
113
+ url: typeof app.url === 'string' ? app.url : '',
114
+ ref: app.ref,
115
+ commit: app.commit,
116
+ vendoredAt: typeof app.vendoredAt === 'string' ? app.vendoredAt : '',
117
+ }
118
+ }
119
+ return out
120
+ } catch {
121
+ return {}
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Refuse a stamp file that is there and cannot be read, BEFORE a pull: found after it, the pull is already a commit
127
+ * and the project is left half way. A missing file is fine; it is written whole.
128
+ */
129
+ export async function assertStampReadable(projectRoot: string): Promise<void> {
130
+ const file = Bun.file(stampPath(projectRoot))
131
+ if (!(await file.exists())) return
132
+ try {
133
+ await file.json()
134
+ } catch {
135
+ throw new Error(`${STAMP_FILE} is not valid JSON; fix or delete it, then run the command again`)
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Record one app's pull, leaving the engine's stamp and the other apps' as they
141
+ * are. A project with no engine stamp gets a file holding only `apps`, which
142
+ * `readStamp` reads as "unknown", exactly as it read the missing file.
143
+ */
144
+ export async function writeAppStamp(
145
+ projectRoot: string,
146
+ name: string,
147
+ stamp: Omit<AppStamp, 'vendoredAt'> & { vendoredAt?: string },
148
+ ): Promise<void> {
149
+ const file = Bun.file(stampPath(projectRoot))
150
+ let whole: Record<string, unknown> = {}
151
+ if (await file.exists()) {
152
+ try {
153
+ whole = (await file.json()) as Record<string, unknown>
154
+ } catch {
155
+ // Writing over a file that cannot be read would drop the engine's half of it without a word.
156
+ throw new Error(
157
+ `${STAMP_FILE} is not valid JSON; fix or delete it, then run the command again`,
158
+ )
159
+ }
160
+ }
161
+ const apps = await readAppStamps(projectRoot)
162
+ apps[name] = {
163
+ url: stamp.url,
164
+ ref: stamp.ref,
165
+ commit: stamp.commit,
65
166
  vendoredAt: stamp.vendoredAt ?? new Date().toISOString(),
66
167
  }
67
- await Bun.write(stampPath(projectRoot), `${JSON.stringify(body, null, 2)}\n`)
168
+ await Bun.write(stampPath(projectRoot), `${JSON.stringify({ ...whole, apps }, null, 2)}\n`)
68
169
  }
69
170
 
70
171
  function parseVersion(v: string): number[] {