@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
@@ -0,0 +1,353 @@
1
+ import * as fs from 'node:fs/promises'
2
+ import * as path from 'node:path'
3
+ import { copyTemplateFile } from './copy-template'
4
+ import {
5
+ ensureCleanGitTree,
6
+ git,
7
+ isVendorMode,
8
+ subtreeAdd,
9
+ subtreePull,
10
+ subtreeSplitCommit,
11
+ VENDOR_PREFIX,
12
+ } from './subtree'
13
+ import { assertStampReadable, readAppStamps, writeAppStamp } from './vendor-stamp'
14
+
15
+ /**
16
+ * A vendored app: a whole application a project pulls as a git subtree of the
17
+ * app's own public copy, at a prefix of its own, and keeps as files it may
18
+ * change. It is the engine's distribution (ADR-0005) applied to an app that is
19
+ * too large, and changes too often, to be a template copied once: `zbc add
20
+ * <app>` runs the squashed `subtree add`, `zbc update <app>` the squashed pull,
21
+ * and the project's own edits ride through a pull as any merge carries them.
22
+ *
23
+ * The app is NOT in the npm package. The CLI knows only its name, where its
24
+ * public copy is and where it lands; everything else about it (its workspace
25
+ * folders, the modules its deploy needs, the files a new install starts from)
26
+ * is the app's own manifest, read from the pulled copy, so the app can change
27
+ * those without a CLI release.
28
+ */
29
+ export interface VendoredApp {
30
+ name: string
31
+ /** The app's public copy: a repository CI splits from this one, never edited directly. */
32
+ url: string
33
+ /** Where it lands in a project, relative to the project root. */
34
+ prefix: string
35
+ }
36
+
37
+ export const VENDORED_APPS: Record<string, VendoredApp> = {
38
+ space: {
39
+ name: 'space',
40
+ url: 'https://github.com/Zabaca/zbc-space.git',
41
+ prefix: 'vendor/space',
42
+ },
43
+ }
44
+
45
+ /** The app's manifest, at the root of its folder. */
46
+ export const APP_MANIFEST = 'zbc-app.json'
47
+
48
+ export interface AppManifest {
49
+ name: string
50
+ /** Workspace patterns, relative to the app's folder (`packages/*`). */
51
+ workspaces?: string[]
52
+ /** The zbc modules the app's deploy builds its instances from. */
53
+ modules?: string[]
54
+ /**
55
+ * Files a new install starts from: `from` is relative to the app's folder,
56
+ * `to` to the project root. Both may hold `{{ENV}}`; what a file's body may
57
+ * hold is `layStarter`'s to say. Written only when absent: they are the
58
+ * project's own from then on.
59
+ */
60
+ starter?: { from: string; to: string }[]
61
+ }
62
+
63
+ export async function readAppManifest(projectRoot: string, app: VendoredApp): Promise<AppManifest> {
64
+ const file = Bun.file(path.join(projectRoot, app.prefix, APP_MANIFEST))
65
+ if (!(await file.exists())) return { name: app.name }
66
+ return (await file.json()) as AppManifest
67
+ }
68
+
69
+ /** `v1.4.0` as its three numbers. */
70
+ const numbers = (tag: string) => tag.slice(1).split('.').map(Number)
71
+
72
+ /**
73
+ * The newest version tag of a repository (`v1.4.0`, read as numbers), asked of
74
+ * the remote without fetching it. An app's tags are its own versions, not the
75
+ * CLI's, so there is no version to compute a ref from as the engine does.
76
+ */
77
+ export function newestTag(url: string, cwd: string = process.cwd()): string {
78
+ const listing = git(cwd, ['ls-remote', '--tags', '--refs', url])
79
+ const tags = listing
80
+ .split('\n')
81
+ .map((line) => /refs\/tags\/(v\d+\.\d+\.\d+)$/.exec(line)?.[1])
82
+ .filter((tag): tag is string => tag !== undefined)
83
+ if (tags.length === 0) {
84
+ throw new Error(
85
+ `${url} has no version tag (vX.Y.Z). Name a ref instead: --ref main pulls the newest commit.`,
86
+ )
87
+ }
88
+ return tags.toSorted((a, b) => {
89
+ const [x, y] = [numbers(a), numbers(b)]
90
+ return x[0]! - y[0]! || x[1]! - y[1]! || x[2]! - y[2]!
91
+ })[tags.length - 1]!
92
+ }
93
+
94
+ /**
95
+ * Add the app's workspace folders to the project's root manifest. Returns the
96
+ * patterns it added; one already listed is left alone, so a second run adds
97
+ * nothing.
98
+ */
99
+ export async function addWorkspaces(
100
+ projectRoot: string,
101
+ app: VendoredApp,
102
+ patterns: string[],
103
+ ): Promise<string[]> {
104
+ const file = path.join(projectRoot, 'package.json')
105
+ const pkg = JSON.parse(await fs.readFile(file, 'utf8')) as {
106
+ workspaces?: string[] | { packages?: string[] }
107
+ }
108
+ // Both spellings a root manifest may use: a list, or `{ packages: [...] }`.
109
+ const listed = Array.isArray(pkg.workspaces) ? pkg.workspaces : (pkg.workspaces?.packages ?? [])
110
+ const wanted = patterns.map((pattern) => path.posix.join(app.prefix, pattern))
111
+ const added = wanted.filter((pattern) => !listed.includes(pattern))
112
+ if (added.length === 0) return []
113
+ const next = [...listed, ...added]
114
+ if (Array.isArray(pkg.workspaces) || pkg.workspaces === undefined) pkg.workspaces = next
115
+ else pkg.workspaces.packages = next
116
+ await fs.writeFile(file, `${JSON.stringify(pkg, null, 2)}\n`)
117
+ return added
118
+ }
119
+
120
+ /**
121
+ * Where the things a starter file imports are, from the project root. The app's
122
+ * glue imports the project's own zbc modules, and where those are depends on
123
+ * how the project took the engine: a subtree project has them under
124
+ * `vendor/zbc`, a copy-mode one under `packages/infra`.
125
+ */
126
+ export async function starterRoots(
127
+ projectRoot: string,
128
+ app: VendoredApp,
129
+ ): Promise<{ APP: string; MODULES: string; ENGINE: string }> {
130
+ const vendored = await isVendorMode(projectRoot)
131
+ return {
132
+ APP: app.prefix,
133
+ MODULES: vendored ? `${VENDOR_PREFIX}/modules` : 'packages/infra/modules',
134
+ ENGINE: vendored ? `${VENDOR_PREFIX}/src` : 'packages/infra/src',
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Write the files a new install starts from, each only when absent. Returns the
140
+ * project-relative paths written and the ones left as they were.
141
+ *
142
+ * A file's body may hold `{{ENV}}`, and `{{APP}}`, `{{MODULES}}` and
143
+ * `{{ENGINE}}`, which become the path from THAT file's folder to the app's
144
+ * folder, the project's zbc modules and its engine, so a starter's imports are
145
+ * right wherever the manifest puts it.
146
+ */
147
+ export async function layStarter(
148
+ projectRoot: string,
149
+ app: VendoredApp,
150
+ manifest: AppManifest,
151
+ env: string,
152
+ ): Promise<{ written: string[]; kept: string[] }> {
153
+ const roots = await starterRoots(projectRoot, app)
154
+ const inPath = (text: string) => text.replaceAll('{{ENV}}', env)
155
+ const written: string[] = []
156
+ const kept: string[] = []
157
+ for (const entry of manifest.starter ?? []) {
158
+ const appRoot = path.join(projectRoot, app.prefix)
159
+ const from = path.resolve(appRoot, inPath(entry.from))
160
+ // And it is copied from the app's own folder, never from somewhere else in the project.
161
+ if (path.relative(appRoot, from).startsWith('..')) {
162
+ throw new Error(
163
+ `${app.name}'s manifest names a starter file outside its own folder: ${entry.from}`,
164
+ )
165
+ }
166
+ const to = inPath(entry.to)
167
+ // A starter path is the app's to name, and it names a place in the project:
168
+ // one that climbs out of the project root is refused before anything is written.
169
+ const dest = path.resolve(projectRoot, to)
170
+ if (path.isAbsolute(to) || path.relative(projectRoot, dest).startsWith('..')) {
171
+ throw new Error(`${app.name}'s manifest names a starter file outside the project: ${to}`)
172
+ }
173
+ const fromHere = (target: string) => {
174
+ const relative = path.posix.relative(path.posix.dirname(to), target)
175
+ return relative.startsWith('.') ? relative : `./${relative}`
176
+ }
177
+ const vars = {
178
+ ENV: env,
179
+ APP: fromHere(roots.APP),
180
+ MODULES: fromHere(roots.MODULES),
181
+ ENGINE: fromHere(roots.ENGINE),
182
+ }
183
+ const wrote = await copyTemplateFile(from, dest, { vars, skipIfExists: true })
184
+ ;(wrote ? written : kept).push(to)
185
+ }
186
+ return { written, kept }
187
+ }
188
+
189
+ export interface AppAudit {
190
+ /** Files the project tracks under the prefix that the pulled commit does not ship. */
191
+ own: string[]
192
+ /** Files that differ from the pulled commit: the project's edits. */
193
+ edited: string[]
194
+ /** Files the pulled commit ships that the project no longer has. */
195
+ removed: string[]
196
+ }
197
+
198
+ /**
199
+ * Compare what the project tracks under the app's prefix with the commit it
200
+ * pulled, blob for blob. Offline and exact: a pull has just fetched that commit,
201
+ * so git holds its tree. Null when git does not hold it (a fresh clone of the
202
+ * project, where the squashed history keeps only the commit's id).
203
+ */
204
+ export function auditVendoredApp(
205
+ projectRoot: string,
206
+ app: VendoredApp,
207
+ commit: string,
208
+ ): AppAudit | null {
209
+ let upstreamListing: string
210
+ try {
211
+ upstreamListing = git(projectRoot, ['ls-tree', '-r', '-z', commit])
212
+ } catch {
213
+ return null
214
+ }
215
+ const blobs = (listing: string, strip: string) => {
216
+ const map = new Map<string, string>()
217
+ for (const entry of listing.split('\0')) {
218
+ // `<mode> blob <sha>\t<path>` from ls-tree, `<mode> <sha> <stage>\t<path>` from ls-files.
219
+ const match = /^\d+ (?:blob )?([0-9a-f]+)(?: \d)?\t(.+)$/.exec(entry)
220
+ if (!match) continue
221
+ map.set(path.posix.relative(strip, match[2]!), match[1]!)
222
+ }
223
+ return map
224
+ }
225
+ const upstream = blobs(upstreamListing, '')
226
+ const local = blobs(git(projectRoot, ['ls-files', '-s', '-z', '--', app.prefix]), app.prefix)
227
+ const own = [...local.keys()].filter((file) => !upstream.has(file)).toSorted()
228
+ const edited = [...local.keys()]
229
+ .filter((file) => upstream.has(file) && upstream.get(file) !== local.get(file))
230
+ .toSorted()
231
+ const removed = [...upstream.keys()].filter((file) => !local.has(file)).toSorted()
232
+ return { own, edited, removed }
233
+ }
234
+
235
+ /** The audit as lines to print: information for whoever pulled, never a failure. */
236
+ export function describeAppAudit(app: VendoredApp, audit: AppAudit | null): string[] {
237
+ if (audit === null) {
238
+ return [
239
+ ` (the pulled commit is not in this clone, so ${app.prefix}/ was not compared with it)`,
240
+ ]
241
+ }
242
+ const lines: string[] = []
243
+ const list = (title: string, files: string[]) => {
244
+ if (files.length === 0) return
245
+ lines.push(` ${files.length} ${title}`)
246
+ for (const file of files.slice(0, 40)) lines.push(` ${app.prefix}/${file}`)
247
+ if (files.length > 40) lines.push(` ... and ${files.length - 40} more`)
248
+ }
249
+ list(
250
+ `file(s) under ${app.prefix}/ are this project's own (the copy does not ship them):`,
251
+ audit.own,
252
+ )
253
+ list("file(s) differ from the pulled copy (this project's edits, kept):", audit.edited)
254
+ list('file(s) the copy ships are not in this project:', audit.removed)
255
+ if (lines.length === 0) lines.push(` ${app.prefix}/ is the pulled copy, file for file.`)
256
+ return lines
257
+ }
258
+
259
+ export interface VendorResult {
260
+ ref: string
261
+ commit: string
262
+ workspacesAdded: string[]
263
+ starter: { written: string[]; kept: string[] }
264
+ manifest: AppManifest
265
+ }
266
+
267
+ /**
268
+ * `zbc add <app>`: the squashed subtree add at the newest tag (or the ref
269
+ * named), then what makes the folder usable: its workspace folders in the root
270
+ * manifest, the starting files of one environment, and the stamp. The subtree
271
+ * add is a commit; everything after it is left in the working tree for the
272
+ * operator to read and commit.
273
+ */
274
+ export async function addVendoredApp(
275
+ projectRoot: string,
276
+ app: VendoredApp,
277
+ opts: { ref?: string; url?: string; env: string },
278
+ ): Promise<VendorResult> {
279
+ if (await exists(path.join(projectRoot, app.prefix))) {
280
+ throw new Error(
281
+ `${app.prefix}/ is already there. \`zbc update ${app.name}\` pulls a newer copy over it.`,
282
+ )
283
+ }
284
+ ensureCleanGitTree(projectRoot)
285
+ await assertStampReadable(projectRoot)
286
+ const url = opts.url ?? app.url
287
+ const ref = opts.ref ?? newestTag(url, projectRoot)
288
+ subtreeAdd(projectRoot, { url, ref, prefix: app.prefix })
289
+ // The pull is a commit by now. What follows only writes files, so a failure in it leaves the app in place and
290
+ // says so: a second `add` would refuse the folder, and an `update` never writes the starting files.
291
+ try {
292
+ return await finishPull(projectRoot, app, { url, ref, env: opts.env })
293
+ } catch (err) {
294
+ throw new Error(
295
+ `${app.prefix}/ was pulled and committed (${ref}), but what follows the pull failed: ${(err as Error).message}\n` +
296
+ ` To start over: git reset --hard HEAD~1 (the pull is the last commit), delete what git status then lists as new, and run \`zbc add ${app.name}\` again.`,
297
+ { cause: err },
298
+ )
299
+ }
300
+ }
301
+
302
+ /**
303
+ * `zbc update <app>`: the squashed pull of the newest tag, or of the ref named
304
+ * (a branch for the newest commit). A conflict with the project's own edits is
305
+ * git's, left for the operator: it is the same merge any pull is.
306
+ */
307
+ export async function updateVendoredApp(
308
+ projectRoot: string,
309
+ app: VendoredApp,
310
+ opts: { ref?: string; url?: string },
311
+ ): Promise<VendorResult & { audit: AppAudit | null }> {
312
+ if (!(await exists(path.join(projectRoot, app.prefix)))) {
313
+ throw new Error(`${app.prefix}/ is not there. \`zbc add ${app.name}\` pulls it first.`)
314
+ }
315
+ ensureCleanGitTree(projectRoot)
316
+ await assertStampReadable(projectRoot)
317
+ // A fork pulls from where it was added from, unless told otherwise.
318
+ const stamped = (await readAppStamps(projectRoot))[app.name]
319
+ const url = opts.url ?? (stamped?.url || app.url)
320
+ const ref = opts.ref ?? newestTag(url, projectRoot)
321
+ subtreePull(projectRoot, { url, ref, prefix: app.prefix })
322
+ const result = await finishPull(projectRoot, app, { url, ref })
323
+ return { ...result, audit: auditVendoredApp(projectRoot, app, result.commit) }
324
+ }
325
+
326
+ async function finishPull(
327
+ projectRoot: string,
328
+ app: VendoredApp,
329
+ opts: { url: string; ref: string; env?: string },
330
+ ): Promise<VendorResult> {
331
+ const commit = subtreeSplitCommit(projectRoot, app.prefix)
332
+ if (commit === null) {
333
+ throw new Error(`git recorded no pulled commit for ${app.prefix}/: the subtree did not land.`)
334
+ }
335
+ const manifest = await readAppManifest(projectRoot, app)
336
+ const workspacesAdded = await addWorkspaces(projectRoot, app, manifest.workspaces ?? [])
337
+ // Starting files are an `add`'s: an update never writes into an environment.
338
+ const starter =
339
+ opts.env === undefined
340
+ ? { written: [], kept: [] }
341
+ : await layStarter(projectRoot, app, manifest, opts.env)
342
+ await writeAppStamp(projectRoot, app.name, { url: opts.url, ref: opts.ref, commit })
343
+ return { ref: opts.ref, commit, workspacesAdded, starter, manifest }
344
+ }
345
+
346
+ async function exists(target: string): Promise<boolean> {
347
+ try {
348
+ await fs.stat(target)
349
+ return true
350
+ } catch {
351
+ return false
352
+ }
353
+ }
@@ -20,7 +20,7 @@ writing a module. `.claude/settings.json` enables it. To install it by hand, run
20
20
  ## Common commands
21
21
 
22
22
  - `bun install` — install dependencies
23
- - `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`, `r2`) or scaffold an app template (`inbox` — an agent-accessible email inbox; `secret-relay` — the browser-based secret request relay; `warehouse` — a dlt+dbt-duckdb data warehouse/BI pipeline; each auto-vendors its module dependencies)
23
+ - `bunx @zabaca/zbc add <module>`, vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`, `r2`) or scaffold an app template (`secret-relay`: the browser-based secret request relay; `warehouse`: a dlt+dbt-duckdb data warehouse/BI pipeline; each auto-vendors its module dependencies), or pull the vendored app `space` (a company's mail, chat and calls, calendar, forms and signed documents, clients and knowledge in one Worker) into `vendor/space/` as a git subtree, which `bunx @zabaca/zbc update space` later updates
24
24
  - `bunx @zabaca/zbc apply <env>` — apply infrastructure for an environment
25
25
  - `bunx @zabaca/zbc apply <env> --json <path>` — the same, plus the result (`{ env, instances: [{ name, module, outputs }] }`) written to a file. Treat that file as secret: outputs carry credentials
26
26
  - `bunx @zabaca/zbc list <env>` — what the environment declares, in dependency order (add `--json` for a machine-readable listing)
@@ -71,8 +71,7 @@ interface Claim {
71
71
  /**
72
72
  * Answer one MCP request.
73
73
  *
74
- * A fresh `McpServer` per request, like the inbox's endpoint and for the same
75
- * reason: a Workers isolate is per-request and holds no session, so there is no
74
+ * A fresh `McpServer` per request: a Workers isolate is per-request and holds no session, so there is no
76
75
  * long-lived server to keep. `app.all` because Streamable HTTP puts client
77
76
  * messages on POST and the server-to-client stream on GET, and a transport
78
77
  * mounted for one of them is a client that connects and then hears nothing.
@@ -32,8 +32,7 @@ export interface Env extends MaterializeEnv {
32
32
  }
33
33
 
34
34
  /** Constant-time bearer check: compare SHA-256 digests via crypto.subtle.timingSafeEqual
35
- * so a mismatched length or value can't be distinguished by timing — ported exactly from
36
- * the inbox app template's `authorized()` (worker/index.ts there). */
35
+ * so a mismatched length or value can't be distinguished by timing. */
37
36
  export async function authorized(request: Request, env: Env): Promise<boolean> {
38
37
  if (!env.WAREHOUSE_TOKEN) return false
39
38
  const header = request.headers.get('authorization') ?? ''
@@ -2,8 +2,7 @@
2
2
  // implement `timingSafeEqual` — verified against this package's own Bun (`'timingSafeEqual'
3
3
  // in crypto.subtle` is false; calling it throws "is not a function"). It's a workerd-runtime
4
4
  // extension to SubtleCrypto, not part of the Web Crypto standard, so it's only real under
5
- // wrangler dev/deploy. router.ts's `authorized()` calls it exactly as the inbox app
6
- // template's worker/index.ts does — this shim exists purely so `bun test worker` can
5
+ // wrangler dev/deploy. router.ts's `authorized()` calls it, and this shim exists purely so `bun test worker` can
7
6
  // exercise authorized()'s true/false outcomes locally; it changes nothing about the code
8
7
  // under test, and is never loaded outside the test runner.
9
8
  import { timingSafeEqual as nodeTimingSafeEqual } from 'node:crypto'