@gusto/create-baerly-storage 0.1.2 → 0.3.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.
@@ -85,15 +85,15 @@ read it via your editor's TS LS or via the published types).
85
85
 
86
86
  ## Verification
87
87
 
88
- | Command | What it does | Runtime |
89
- | ------------------ | -------------------------------------------------- | ---------------- |
90
- | `pnpm install` | One-time bootstrap — the scaffold ships without `node_modules/`, so `pnpm verify` / `pnpm dev` fail with `Cannot find package '…'` until this runs once | seconds to a minute |
91
- | `pnpm verify` | `pnpm run typecheck && pnpm run test` — the green-light gate; what an agent should run as the smoke check before claiming the change works | seconds |
92
- | `pnpm typecheck` | TS typecheck across the `app` + `server` project references | seconds |
93
- | `pnpm test` | `vitest run --passWithNoTests` — standalone `vitest.config.ts` (Node env). The minimal template ships no SPA tests by default; `--passWithNoTests` keeps the gate green until you add one. | seconds |
94
- | `pnpm dev` | Run `vite` — `baerlyDev()` mounts the Node HTTP listener as Connect middleware next to the SPA dev server; same origin on :5173 | seconds to start |
95
- | `pnpm build` | `tsc -b && vite build` — emits the SPA into `dist/client/` | seconds |
96
- | `pnpm start` | `node --experimental-strip-types src/server/index.ts` — production entry; serves the SPA from `dist/client/` via `webRoot` | seconds to start |
88
+ | Command | What it does | Runtime |
89
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------- |
90
+ | `pnpm install` | One-time bootstrap — the scaffold ships without `node_modules/`, so `pnpm verify` / `pnpm dev` fail with `Cannot find package '…'` until this runs once | seconds to a minute |
91
+ | `pnpm verify` | `pnpm run typecheck && pnpm run test` — the green-light gate; what an agent should run as the smoke check before claiming the change works | seconds |
92
+ | `pnpm typecheck` | TS typecheck across the `app` + `server` project references | seconds |
93
+ | `pnpm test` | `vitest run --passWithNoTests` — standalone `vitest.config.ts` (Node env). The minimal template ships no SPA tests by default; `--passWithNoTests` keeps the gate green until you add one. | seconds |
94
+ | `pnpm dev` | Run `vite` — `baerlyDev()` mounts the Node HTTP listener as Connect middleware next to the SPA dev server; same origin on :5173 | seconds to start |
95
+ | `pnpm build` | `tsc -b && vite build` — emits the SPA into `dist/client/` | seconds |
96
+ | `pnpm start` | `node --experimental-strip-types src/server/index.ts` — production entry; serves the SPA from `dist/client/` via `webRoot` | seconds to start |
97
97
 
98
98
  **`pnpm verify` exercises typecheck + tests only.** The dev-auth
99
99
  middleware, the SPA bundle, and any custom `/api/*` route are NOT
@@ -105,31 +105,32 @@ http://localhost:5173/<path>`) before declaring the task complete.
105
105
 
106
106
  ## Where the code is
107
107
 
108
- | Path | What it is |
109
- | --------------------------- | --------------------------------------------------- |
110
- | `src/server/index.ts` | Server entry — composes `s3Storage` / `r2Storage` + a verifier and calls `baerlyNode({ ... }).listen(PORT)` |
111
- | `src/web/`, `index.html` | Optional SPA shell built by Vite into `dist/client/`. `src/web/main.ts` is a ~17-line hello-world: reads `client.collection<Note>("notes").all()` to render a `${n} note(s)` count and an `[Add note]` button that inserts a timestamped row and re-fetches. Demonstrates both read and write paths on first load — extend, replace, or remove the whole tree if not needed. |
112
- | `vite.config.ts` | Vite client build — `outDir: dist/client`; `baerlyDev()` mounts the Node listener as middleware so SPA + `/v1/*` share `:5173` in dev |
113
- | `tsconfig.{app,server}.json` | TS project references for the client and server projects |
114
- | `baerly.config.ts` | App config — `app`, `tenant`, `target`, `domain`, `collections` (schemas live here). |
115
- | `types.ts` | Shared types between the Node server (`src/server/`) and the SPA (`src/web/`). Both `tsconfig.app.json` and `tsconfig.server.json` include this file; put any row type or interface that crosses the boundary here. |
108
+ | Path | What it is |
109
+ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
110
+ | `src/server/index.ts` | Server entry — composes `s3Storage` / `r2Storage` + a verifier and calls `baerlyNode({ ... }).listen(PORT)` |
111
+ | `src/web/`, `index.html` | Optional SPA shell built by Vite into `dist/client/`. `src/web/main.ts` is a ~17-line hello-world: reads `client.collection("notes").all()` to render a `${n} note(s)` count and an `[Add note]` button that inserts a timestamped row and re-fetches. Demonstrates both read and write paths on first load — extend, replace, or remove the whole tree if not needed. The `config`-bound `client.collection("notes")` is the typed surface (the generic on `.collection()` is the collection **name**, not the row type). |
112
+ | `vite.config.ts` | Vite client build — `outDir: dist/client`; `baerlyDev()` mounts the Node listener as middleware so SPA + `/v1/*` share `:5173` in dev |
113
+ | `tsconfig.{app,server}.json` | TS project references for the client and server projects |
114
+ | `baerly.config.ts` | App config — `app`, `tenant`, `target`, `domain`, `collections` (schemas live here). |
115
+ | `types.ts` | Shared types between the Node server (`src/server/`) and the SPA (`src/web/`). Both `tsconfig.app.json` and `tsconfig.server.json` include this file; put any row type or interface that crosses the boundary here. |
116
116
 
117
117
  > **`baerly.config.ts` and `types.ts` are dual-included** by both
118
118
  > `tsconfig.app.json` and `tsconfig.server.json`. Both can only
119
119
  > import from `baerly-storage`, `zod`, and other dual-included root
120
120
  > files. Paths under `src/server/` are server-only; importing them
121
- > here triggers `TS6307: File … is not listed within the file list
122
- > of project … tsconfig.app.json`. Cross-boundary interfaces belong
123
- > in `types.ts`; re-export from a server-only file if downstream code
124
- > wants a local name.
121
+ > here triggers a `TS6307` "not listed within the file list of
122
+ > project … tsconfig.app.json" error. Cross-boundary interfaces
123
+ > belong in `types.ts`; re-export from a server-only file if
124
+ > downstream code wants a local name.
125
125
 
126
126
  ## When editing X, read Y
127
127
 
128
128
  - **Writing tests** — the kernel exports `MemoryStorage`, an
129
129
  in-memory `Storage` impl that's the canonical backend for unit
130
- tests. Don't roll your own — `Db.create({ storage, app, tenant,
131
- config })` is the same boilerplate prod uses; passing
132
- `new MemoryStorage()` swaps S3 for an in-process map.
130
+ tests. Don't roll your own: the same
131
+ `Db.create({ storage, app, tenant, config })` boilerplate prod uses
132
+ also accepts a `new MemoryStorage()` that swaps S3 for an
133
+ in-process map.
133
134
 
134
135
  ```ts
135
136
  // src/notes.test.ts
@@ -156,9 +157,10 @@ http://localhost:5173/<path>`) before declaring the task complete.
156
157
  instance into multiple `Db.create` calls so they share the
157
158
  underlying bucket.
158
159
 
159
- - **Predicates** — `db.collection<Doc>(name).where({...}).all()`. Two
160
- shapes:
161
-
160
+ - **Predicates** — `db.collection(name).where({...}).all()` (the row
161
+ type is inferred from the schema declared for `name` in
162
+ `baerly.config.ts`; the generic on `.collection()` is the collection
163
+ **name**, not the row type). Two shapes:
162
164
  - **Object literal** — equality only (top-level, dotted-path, or
163
165
  nested literal sub-predicate). Multi-field is implicit AND.
164
166
  - **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`
@@ -172,24 +174,25 @@ http://localhost:5173/<path>`) before declaring the task complete.
172
174
  await db.collection("tickets").where({ status: "open" }).all();
173
175
 
174
176
  // Dotted-path on a nested field
175
- await db.collection("tickets")
176
- .where({ "assignee.team": "platform" })
177
- .all();
177
+ await db.collection("tickets").where({ "assignee.team": "platform" }).all();
178
178
 
179
179
  // Operator on a single field — set membership (callback form)
180
- await db.collection("tickets")
181
- .where(q => q.in("status", ["open", "pending"]))
180
+ await db
181
+ .collection("tickets")
182
+ .where((q) => q.in("status", ["open", "pending"]))
182
183
  .all();
183
184
 
184
185
  // Range — also callback form
185
- await db.collection("tickets")
186
- .where(q => q.gte("priority", 5).lt("priority", 10))
186
+ await db
187
+ .collection("tickets")
188
+ .where((q) => q.gte("priority", 5).lt("priority", 10))
187
189
  .all();
188
190
 
189
191
  // AND-merge across two .where() calls (mix shapes freely)
190
- await db.collection("tickets")
192
+ await db
193
+ .collection("tickets")
191
194
  .where({ status: "open" })
192
- .where(q => q.gte("priority", 5))
195
+ .where((q) => q.gte("priority", 5))
193
196
  .all();
194
197
  ```
195
198
 
@@ -216,8 +219,9 @@ http://localhost:5173/<path>`) before declaring the task complete.
216
219
  });
217
220
  ```
218
221
 
219
- With that declared, `db.collection("tickets").where({ status: "open"
220
- }).all()` walks `by_status` automatically. Composite indexes
222
+ With that declared, a query like
223
+ `db.collection("tickets").where({ status: "open" }).all()` walks
224
+ `by_status` automatically. Composite indexes
221
225
  (`on: ["status", "priority"]`) match any leftmost prefix.
222
226
  Mismatches (predicate doesn't cover any index) fall back to a full
223
227
  table scan with a metric bump; correctness is preserved because the
@@ -248,7 +252,7 @@ http://localhost:5173/<path>`) before declaring the task complete.
248
252
 
249
253
  On a validation failure the server throws
250
254
  `BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
251
- HTTP clients see a 422 with the same envelope. Validation runs
255
+ HTTP clients see a 400 with the same envelope. Validation runs
252
256
  on the post-image so `update` and `replace` see the full doc, not
253
257
  just the patch.
254
258
 
@@ -256,12 +260,12 @@ http://localhost:5173/<path>`) before declaring the task complete.
256
260
  (`db.collection(name).insert(...)`) is the canonical path; reach for `curl`
257
261
  only when debugging the wire. Mutation bodies are wrapped:
258
262
 
259
- | Route | Body | Response |
260
- | --------------------------- | ------------------- | ----------------------------- |
261
- | `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
262
- | `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
263
- | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
264
- | `DELETE /v1/c/:collection/:id` | — | `204` |
263
+ | Route | Body | Response |
264
+ | ------------------------------ | ----------------- | ---------------- |
265
+ | `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
266
+ | `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
267
+ | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
268
+ | `DELETE /v1/c/:collection/:id` | — | `204` |
265
269
 
266
270
  Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
267
271
  `GET /v1/since?collection=…&cursor=…`) take no body and return
@@ -275,9 +279,11 @@ http://localhost:5173/<path>`) before declaring the task complete.
275
279
  - **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`:
276
280
  every request resolves to `tenant: "minimal-demo"` and `Authorization`
277
281
  is ignored. The adapter reads `config.auth` to pick its verifier;
278
- a `verifier:` on `baerlyNode({ ... })` overrides it. `baerly
279
- doctor --target=node` warns on `"none"` for deploy targets. See
280
- "Going to production" below for the two production-fit recipes.
282
+ a `verifier:` on `baerlyNode({ ... })` overrides it. There is no
283
+ `baerly doctor --target=node` backend today; verify bucket CAS with
284
+ `baerly doctor --bucket=<s3-uri>` and probe `/v1/healthz` after
285
+ deploy. See "Going to production" below for the two production-fit
286
+ recipes.
281
287
 
282
288
  ### Going to production
283
289
 
@@ -286,6 +292,7 @@ zero env vars. Two patterns flip to a production-fit posture; pick
286
292
  the one matching your gate.
287
293
 
288
294
  <!-- pattern-b:start -->
295
+
289
296
  **Pattern B — `auth: "shared-secret"`** (single-tenant
290
297
  server-to-server). No factory code changes; `baerly.config.ts` flips:
291
298
 
@@ -296,12 +303,13 @@ auth: "shared-secret", // ← flip from "none"
296
303
 
297
304
  Dev: put `SHARED_SECRET=dev-shared-secret` in `.env`. Prod: set
298
305
  `SHARED_SECRET` in the process environment (your PaaS / secret
299
- manager). `baerly doctor --target=node` FAILs if
300
- `auth: "shared-secret"` is set without `SHARED_SECRET` reachable from
301
- `process.env`.
306
+ manager). The Node process fails closed if `auth: "shared-secret"`
307
+ is set without `SHARED_SECRET` reachable from `process.env`; verify
308
+ the live bucket separately with `baerly doctor --bucket=<s3-uri>`.
302
309
 
303
310
  <!-- pattern-b:end -->
304
311
  <!-- pattern-c:start -->
312
+
305
313
  **Pattern C — JWKS-backed JWT** (multi-tenant; OIDC IdP). The factory
306
314
  `verifier:` overrides `config.auth`, so dev keeps `"none"` and prod
307
315
  gets `bearerJwt`:
@@ -332,6 +340,7 @@ await baerlyNode({
332
340
  jwks: process.env["JWKS_URL"],
333
341
  issuer: process.env["JWT_ISSUER"]!,
334
342
  audience: process.env["JWT_AUDIENCE"]!,
343
+ tenantPrefix: config.tenant, // or tenantClaim: "tenant"
335
344
  }),
336
345
  }),
337
346
  }).listen(Number(process.env["PORT"] ?? 8080));
@@ -339,9 +348,12 @@ await baerlyNode({
339
348
 
340
349
  Dev sees `JWKS_URL` as `undefined`, spread short-circuits, and
341
350
  `config.auth: "none"` runs. Prod sets `JWKS_URL` + `JWT_ISSUER` +
342
- `JWT_AUDIENCE` and `bearerJwt` engages.
351
+ `JWT_AUDIENCE` and `bearerJwt` engages. Use `tenantClaim` when your
352
+ IdP issues one tenant per token; use `tenantPrefix` for single-tenant
353
+ apps or tenancy enforced outside Baerly.
343
354
 
344
355
  <!-- pattern-c:end -->
356
+
345
357
  - **Storage backend** — `src/server/index.ts` picks between
346
358
  `s3Storage` (AWS) and `r2Storage` (Cloudflare R2) based on whether
347
359
  `R2_ACCOUNT_ID` is set. To use **Minio** (self-hosted dev S3) or
@@ -354,7 +366,7 @@ Dev sees `JWKS_URL` as `undefined`, spread short-circuits, and
354
366
 
355
367
  - **Switching from static creds to EKS Pod Identity** — in
356
368
  `src/server/index.ts`, swap `credentials: { accessKeyId,
357
- secretAccessKey }` for `credentials: fromEksPodIdentity()` and add
369
+ secretAccessKey }` for `credentials: fromEksPodIdentity()` and add
358
370
  `fromEksPodIdentity` to your import:
359
371
  `import { s3Storage, fromEksPodIdentity } from "@gusto/baerly-storage/node"`.
360
372
  The agent reads `AWS_CONTAINER_CREDENTIALS_FULL_URI` +
@@ -396,12 +408,14 @@ Dev sees `JWKS_URL` as `undefined`, spread short-circuits, and
396
408
  into the predicate so the index planner can prune
397
409
  (`db.collection("notes").where({ ... }).all()`), or maintain a
398
410
  side-projection (Postgres/SQLite/search index) populated
399
- incrementally from the `/v1/since` log feed or from a write hook —
411
+ incrementally from the `/v1/since?collection=<name>&cursor=<opaque>`
412
+ log feed or from a write hook —
400
413
  never re-scan per request.
401
414
 
402
415
  ## Maintenance
403
416
 
404
417
  <!-- pattern-d:start -->
418
+
405
419
  Maintenance is automatic and write-triggered. No cron, no sidecar, no scheduler, no
406
420
  timer, no lock, no app-config knob — identical on every host. Every write runs a
407
421
  bounded GC slice inline plus a go/no-go compaction fold bounded by a fold-size ceiling
@@ -415,10 +429,11 @@ maintenance, so the published idle-reader cost bound holds.
415
429
  A bucket maintains itself as long as it takes writes. A bucket served read-only does
416
430
  not auto-compact and pays a small, bounded replay — fine at small scale, a signal to
417
431
  graduate once a collection is large. See docs/about/graduation.md for the per-tier
418
- envelope and the BAERLY_MAINTENANCE_* operator env vars (you almost never need them).
432
+ envelope and the `BAERLY_MAINTENANCE_*` operator env vars (you almost never need them).
419
433
 
420
434
  Operator opt-in: call runScheduledMaintenance from @gusto/baerly-storage/maintenance on
421
435
  your own schedule. Not required for steady-state operation.
436
+
422
437
  <!-- pattern-d:end -->
423
438
 
424
439
  ## When to graduate
@@ -430,21 +445,25 @@ model puts the soft ceiling at:
430
445
  - **~10 GB / tenant**
431
446
  - **~100 collections / tenant**
432
447
 
433
- Past those, S3 list-prefix latency, manifest fold cost, and per-class
448
+ Past those, S3 list-prefix latency, snapshot fold cost, and per-class
434
449
  op pricing start to dominate; you're better off on a real database.
435
450
  Pick your graduation target:
451
+
436
452
  - **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
437
453
  - **Off-Workers or portability matters:** managed Postgres.
438
454
  - **Single-instance Node:** SQLite via Litestream.
439
455
 
440
456
  Either way, the export below is mechanical because log entries are
441
- Postgres-logical-replication-shaped — graduation is a Baerly win,
457
+ Debezium-style CDC change events — graduation is a Baerly win,
442
458
  not a churn event.
443
459
 
444
- **Estimate your current rate:** `baerly admin usage --target=...`
445
- lists recent log entries per collection and computes
446
- writes/min. Warning at 50% of the ceiling; export suggestion at
447
- 100%.
460
+ **Estimate your current rate:** for Node/self-hosted buckets,
461
+ `baerly admin usage --target=node --bucket=<bucket-uri> --app=<app>
462
+ --tenant=<tenant>` lists recent log entries per collection and computes
463
+ writes/min. On Cloudflare, use canonical logs for trend history and
464
+ `baerly cost --bucket=<bucket-uri> --collection=<collection>` for the
465
+ current operation-cost projection until the usage scanner is wired to
466
+ R2 bindings.
448
467
 
449
468
  **Export when ready:** `baerly export --target=sqlite|postgres|d1
450
469
  --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
@@ -9,6 +9,8 @@ path works with zero env vars; flip to a shared secret or wire
9
9
  `bearerJwt` against your OIDC IdP before deploy — see "Going to
10
10
  production" below.
11
11
 
12
+ **The only persistent component is your S3-compatible bucket** — there is no separate database server or daemon to deploy alongside the node process, no idle bill, and maintenance is automatic and write-triggered (no cron, no sidecar, no scheduler).
13
+
12
14
  To ship a production Dockerfile alongside, scaffold with
13
15
  `--with=docker` — the add-on writes a multi-stage distroless Dockerfile,
14
16
  `.dockerignore`, and `healthcheck.js` into this same shape.
@@ -29,7 +31,7 @@ minimal-node/
29
31
  │ # auth recipes, graduation
30
32
  ├── src/
31
33
  │ ├── server/
32
- │ │ └── index.ts # baerlyNode({ app, storage, verifier, webRoot, maintenance? }).listen(PORT)
34
+ │ │ └── index.ts # baerlyNode({ config, storage, verifier, webRoot }).listen(PORT)
33
35
  │ └── web/
34
36
  │ └── main.ts # SPA client entry — bundled into dist/client/
35
37
  └── README.md
@@ -108,20 +110,21 @@ Verify: `curl https://<your-service>/v1/healthz`.
108
110
  ## Next steps
109
111
 
110
112
  1. **Read `AGENTS.md`** for the agent-facing guide — predicates,
111
- indexes, schemas, auth recipes (JWKS setup), the in-process
112
- maintenance loop, and the graduation criteria. (Claude Code
113
+ indexes, schemas, auth recipes (JWKS setup), write-triggered
114
+ maintenance, and the graduation criteria. (Claude Code
113
115
  users: `@gusto/create-baerly-storage` mirrors `AGENTS.md` to `CLAUDE.md` at
114
116
  scaffold time.)
115
117
  2. **Declare your first collection schema** in `baerly.config.ts`
116
118
  via `defineConfig({ collections: { ... } })` and pass it to
117
119
  `Db.create({ ..., collections })`. Schema validation is live;
118
- bad inserts return 422.
120
+ bad inserts return 400.
119
121
  3. **Set up production auth** — follow `AGENTS.md` → "Going to
120
122
  production". Pattern B flips `auth: "shared-secret"` and reads
121
123
  `SHARED_SECRET` from `process.env`; Pattern C wires `bearerJwt`
122
124
  against your OIDC IdP via an env-aware factory `verifier:`
123
125
  override (`JWKS_URL` + `JWT_ISSUER` + `JWT_AUDIENCE`).
124
- `baerly doctor --target=node` reports any gaps.
126
+ Verify the bucket with `baerly doctor --bucket=<s3-uri>` and the
127
+ deployed service with `curl https://<your-service>/v1/healthz`.
125
128
 
126
129
  ## When to graduate
127
130
 
@@ -134,8 +137,7 @@ start to dominate, and you're better off on a real database:
134
137
  - **~100 collections / tenant**
135
138
 
136
139
  When you cross the soft ceiling, graduation is mechanical:
137
- `baerly export --target=postgres` walks your log entries (already
138
- Postgres-logical-replication-shaped) into a real DB. If your
140
+ `baerly export --target=postgres` walks your log entries (already Debezium-style CDC change events) into a real DB. If your
139
141
  deploy target is Cloudflare Workers and you'll accept Cloudflare
140
142
  lock-in, [D1](https://developers.cloudflare.com/d1/) is cheaper
141
143
  per-write at M-size and is a natural next step. If you're on
@@ -148,7 +150,7 @@ not a churn event.
148
150
 
149
151
  ```sh
150
152
  baerly export --target=postgres \
151
- --bucket=minimal-node --app=minimal-node --tenant=<your-tenant> \
153
+ --bucket=s3://minimal-node --app=minimal-node --tenant=<your-tenant> \
152
154
  --collection=<collection-name> --output=./out.sql
153
155
  ```
154
156
 
@@ -164,7 +166,7 @@ with zero env vars; every request resolves to `config.tenant`.
164
166
  Before deploy, follow `AGENTS.md` → "Going to production":
165
167
 
166
168
  - **Pattern B — `auth: "shared-secret"`.** Single-tenant
167
- server-to-server callers (CI, cron, internal services). Flip
169
+ server-to-server callers (CI and internal services). Flip
168
170
  `auth` in `baerly.config.ts` and put `SHARED_SECRET` in
169
171
  `process.env` (your PaaS / secret manager).
170
172
  - **Pattern C — JWKS-backed JWT (recommended for multi-tenant).**
@@ -16,11 +16,11 @@
16
16
  "aws4fetch": "^1.0.20"
17
17
  },
18
18
  "devDependencies": {
19
- "@types/node": "^24.0.0",
20
- "happy-dom": "^20.9.0",
19
+ "@types/node": "^25.9.2",
20
+ "happy-dom": "^20.10.2",
21
21
  "typescript": "^6.0.3",
22
- "vite": "^8.0.14",
23
- "vitest": "^4.1.7"
22
+ "vite": "^8.0.16",
23
+ "vitest": "^4.1.8"
24
24
  },
25
25
  "packageManager": "pnpm@11.1.2"
26
26
  }
@@ -104,7 +104,7 @@ http://localhost:5173/<path>`) before declaring the task complete.
104
104
  | Path | What it is |
105
105
  | -------------------------- | ---------------------------------------------------------------------------------------------------------------- |
106
106
  | `src/server/index.ts` | Server entry — `/v1/*` routing + SPA fallback via `env.ASSETS` |
107
- | `wrangler.jsonc` | Cloudflare Worker manifest — name, R2 binding, Assets binding, vars, triggers, limits, observability |
107
+ | `wrangler.jsonc` | Cloudflare Worker manifest — name, R2 binding, Assets binding, vars |
108
108
  | `src/web/` | React+Vite frontend. Served by the Worker via Workers Assets in production. |
109
109
  | `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.tsx`. |
110
110
  | `vite.config.ts` | Vite + `@vitejs/plugin-react` + `@cloudflare/vite-plugin` — runs the Worker inside `workerd` in dev |
@@ -125,22 +125,34 @@ http://localhost:5173/<path>`) before declaring the task complete.
125
125
 
126
126
  ## When editing X, read Y
127
127
 
128
- - **Typed collections** — three ways to get a typed row, in DX order:
128
+ - **Typed collections** — two ways to get a typed row, in DX order.
129
+ The generic on `client.collection<N>(name)` is the collection
130
+ **name** (constrained to `CollectionNames<typeof config>`), not the
131
+ row type — so don't pass a row type to it.
129
132
  1. **Bind the config.** This template's `src/web/client.ts`
130
133
  already passes `config` to `createBaerlyClient({ baseUrl,
131
134
  config })`, so `client.collection("notes")` returns
132
135
  `ClientCollection<Row>` with `Row` derived from the
133
136
  `NoteSchema` declared in `baerly.config.ts`. No generic
134
- needed. Use `client.collection<Note>("notes")` (with `Note`
135
- exported from `baerly.config.ts` next to the schema)
136
- only when you need the row type by name elsewhere.
137
- 2. **Explicit generic, kernel constraint.** Without a declared
138
- collection, the second overload requires the row to satisfy
139
- the kernel's `DocumentData` shape (`{ [k: string]: DocumentValue }`):
137
+ needed. When you need to name that row type elsewhere, use
138
+ `RowOf<typeof config, "notes">` (re-exported from
139
+ `@gusto/baerly-storage`) — not a generic on `.collection()`.
140
+ 2. **Cast the handle (undeclared collection).** This template's
141
+ `client` is bound to `config`, so its names narrow to the
142
+ declared collections. To reach a collection that isn't in
143
+ `config`, build an unbound client
144
+ (`createBaerlyClient({ baseUrl })` with no `config`) — its names
145
+ widen to `string` and its row defaults to `DocumentData`. Cast at
146
+ the construction site for a narrower shape that still satisfies
147
+ the kernel's `DocumentData` constraint
148
+ (`{ [k: string]: DocumentValue }`):
140
149
  ```ts
150
+ import { createBaerlyClient, type ClientCollection } from "@gusto/baerly-storage/client";
141
151
  import type { DocumentData } from "@gusto/baerly-storage";
142
152
  interface Bookmark extends DocumentData { _id: string; url: string }
143
- await client.collection<Bookmark>("bookmarks").all();
153
+ const raw = createBaerlyClient({ baseUrl: "" });
154
+ const bookmarks = raw.collection("bookmarks") as ClientCollection<Bookmark>;
155
+ await bookmarks.all();
144
156
  ```
145
157
  A plain `interface Bookmark { _id: string; url: string }`
146
158
  (no index signature) will fail with TS2344 — the constraint
@@ -266,7 +278,7 @@ http://localhost:5173/<path>`) before declaring the task complete.
266
278
 
267
279
  On a validation failure the server throws
268
280
  `BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
269
- HTTP clients see a 422 with the same envelope. Validation runs
281
+ HTTP clients see a 400 with the same envelope. Validation runs
270
282
  on the post-image so `update` and `replace` see the full doc, not
271
283
  just the patch.
272
284
 
@@ -353,6 +365,7 @@ export default baerlyWorker<AppEnv>((env) => ({
353
365
  verifier: cloudflareAccess({
354
366
  teamDomain: env.CF_ACCESS_TEAM_DOMAIN,
355
367
  audienceTag: env.CF_ACCESS_AUDIENCE_TAG,
368
+ tenantPrefix: config.tenant,
356
369
  }),
357
370
  }),
358
371
  }));
@@ -362,12 +375,14 @@ Set both `CF_ACCESS_TEAM_DOMAIN` and `CF_ACCESS_AUDIENCE_TAG` in
362
375
  `wrangler.jsonc:vars` for prod (they're public identifiers, not
363
376
  secrets). Dev `wrangler dev` sees them as `undefined`, the spread
364
377
  short-circuits, and `config.auth: "none"` runs. Prod sees them set
365
- and `cloudflareAccess` engages.
378
+ and `cloudflareAccess` engages. Every verified token is pinned to
379
+ `config.tenant`; pass `tenantClaim` instead only when your Access JWT
380
+ actually carries a tenant claim.
366
381
 
367
382
  <!-- pattern-a:end -->
368
383
  <!-- pattern-b:start -->
369
384
  **Pattern B — `auth: "shared-secret"`.** Single-tenant
370
- server-to-server callers (CI, cron, internal services). No factory
385
+ server-to-server callers (CI and internal services). No factory
371
386
  code changes; only `baerly.config.ts` flips:
372
387
 
373
388
  ```ts
@@ -411,10 +426,11 @@ from the runtime env.
411
426
 
412
427
  <!-- pattern-b:end -->
413
428
  - **Extending the Worker with a custom route** — `baerlyWorker(...)`
414
- owns `/v1/*` + `/healthz`. For server-side endpoints the SPA
429
+ owns `/v1/*`, including `/v1/healthz`. For server-side endpoints the SPA
415
430
  client can't run on its own (the canonical case: an endpoint that
416
- needs `db.transaction(...)`, since `createBaerlyClient` is
417
- reads + by-id mutations only), wrap the worker `fetch`:
431
+ fans a write across several documents server-side, since
432
+ `createBaerlyClient` is reads + by-id mutations only), wrap the
433
+ worker `fetch`:
418
434
 
419
435
  ```ts
420
436
  // src/server/index.ts
@@ -447,10 +463,10 @@ from the runtime env.
447
463
  tenant: config.tenant,
448
464
  config,
449
465
  });
450
- // …db.transaction(...), db.collection(...).get(id), etc.
466
+ // …db.collection(...).insert(doc), db.collection(...).get(id), etc.
451
467
  return new Response(null, { status: 204 });
452
468
  }
453
- // Fall through to the baerly cascade for /v1/* + /healthz.
469
+ // Fall through to the baerly cascade for /v1/*, including /v1/healthz.
454
470
  return baerly.fetch!(req, env, ctx);
455
471
  },
456
472
  } satisfies ExportedHandler<BaerlyEnv>;
@@ -498,7 +514,8 @@ from the runtime env.
498
514
  into the predicate so the index planner can prune
499
515
  (`db.collection("notes").where({ ... }).all()`), or maintain a
500
516
  side-projection (D1/KV/search index) populated incrementally from
501
- the `/v1/since` log feed or from a write hook — never re-scan per
517
+ the `/v1/since?collection=<name>&cursor=<opaque>` log feed or from
518
+ a write hook — never re-scan per
502
519
  request.
503
520
 
504
521
  ## Maintenance
@@ -517,7 +534,7 @@ maintenance, so the published idle-reader cost bound holds.
517
534
  A bucket maintains itself as long as it takes writes. A bucket served read-only does
518
535
  not auto-compact and pays a small, bounded replay — fine at small scale, a signal to
519
536
  graduate once a collection is large. See docs/about/graduation.md for the per-tier
520
- envelope and the BAERLY_MAINTENANCE_* operator env vars (you almost never need them).
537
+ envelope and the `BAERLY_MAINTENANCE_*` operator env vars (you almost never need them).
521
538
 
522
539
  Operator opt-in: call runScheduledMaintenance from @gusto/baerly-storage/maintenance on
523
540
  your own schedule. Not required for steady-state operation.
@@ -532,7 +549,7 @@ model puts the soft ceiling at:
532
549
  - **~10 GB / tenant**
533
550
  - **~100 collections / tenant**
534
551
 
535
- Past those, S3 list-prefix latency, manifest fold cost, and per-class
552
+ Past those, S3 list-prefix latency, snapshot fold cost, and per-class
536
553
  op pricing start to dominate; you're better off on a real database.
537
554
  Pick your graduation target:
538
555
  - **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
@@ -540,13 +557,16 @@ Pick your graduation target:
540
557
  - **Single-instance Node:** SQLite via Litestream.
541
558
 
542
559
  Either way, the export below is mechanical because log entries are
543
- Postgres-logical-replication-shaped — graduation is a Baerly win,
560
+ Debezium-style CDC change events — graduation is a Baerly win,
544
561
  not a churn event.
545
562
 
546
- **Estimate your current rate:** `baerly admin usage --target=...`
547
- lists recent log entries per collection and computes
548
- writes/min. Warning at 50% of the ceiling; export suggestion at
549
- 100%.
563
+ **Estimate your current rate:** for Node/self-hosted buckets,
564
+ `baerly admin usage --target=node --bucket=<bucket-uri> --app=<app>
565
+ --tenant=<tenant>` lists recent log entries per collection and computes
566
+ writes/min. On Cloudflare, use canonical logs for trend history and
567
+ `baerly cost --bucket=<bucket-uri> --collection=<collection>` for the
568
+ current operation-cost projection until the usage scanner is wired to
569
+ R2 bindings.
550
570
 
551
571
  **Export when ready:** `baerly export --target=sqlite|postgres|d1
552
572
  --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
@@ -611,23 +631,26 @@ the cache key changes when the filter does:
611
631
 
612
632
  ```tsx
613
633
  import { useState } from "react";
614
- import { useQuery } from "@gusto/baerly-storage/client/react";
615
634
  import { STATUSES, type Note } from "../../baerly.config.ts";
635
+ import { useQuery } from "./client.ts";
616
636
 
617
637
  type Filter = "all" | Note["status"];
618
638
 
619
639
  const [filter, setFilter] = useState<Filter>("all");
640
+ // `useQuery` comes from the bound factory in `client.ts`, so
641
+ // `c.collection("notes")` infers the `Note` row — no `<Note>`, no cast.
620
642
  const result = useQuery(
621
643
  (c) =>
622
644
  filter === "all"
623
- ? c.collection<Note>("notes").all()
624
- : c.collection<Note>("notes").where({ status: filter }).all(),
645
+ ? c.collection("notes").all()
646
+ : c.collection("notes").where({ status: filter }).all(),
625
647
  [filter],
626
648
  );
627
649
  ```
628
650
 
629
651
  `useQuery` re-runs the callback when `deps` changes OR when the
630
- `/v1/since` long-poll batches a non-empty change for any subscribed
652
+ `/v1/since?collection=<name>&cursor=<opaque>` long-poll batches a
653
+ non-empty change for any subscribed
631
654
  collection. Idle long-poll cycles (empty batches) drop at the
632
655
  `subscription-pool` layer, so a steady-state collection costs zero list
633
656
  reads. Add a `<select>` bound to `setFilter` and the list narrows live.
@@ -641,7 +664,7 @@ const filtered = useQuery(
641
664
  (c) =>
642
665
  filter === "all"
643
666
  ? useQuery.skip
644
- : c.collection<Note>("notes").where({ status: filter }).all(),
667
+ : c.collection("notes").where({ status: filter }).all(),
645
668
  [filter],
646
669
  );
647
670
  if (filtered.status === "skipped") return <FullList />;
@@ -651,7 +674,9 @@ For dependent reads, compose two `useQuery` calls — the second one
651
674
  returns `useQuery.skip` until the first resolves to `"ok"`:
652
675
 
653
676
  ```tsx
654
- const parent = useQuery((c) => c.collection<Note>("notes").get(id), [id]);
677
+ // `comments` must be declared in baerly.config.ts — the bound hooks
678
+ // only know your declared collections (an undeclared name is a type error).
679
+ const parent = useQuery((c) => c.collection("notes").get(id), [id]);
655
680
  const replies = useQuery(
656
681
  (c) =>
657
682
  parent.status === "ok"
@@ -701,6 +726,6 @@ That's why this recipe uses `.optional()` and not `.nullable()`.
701
726
 
702
727
  - `baerly.config.ts` — app config + `NoteSchema` + inferred `Note` type.
703
728
  - `src/server/index.ts` — Worker entry.
704
- - `wrangler.jsonc` — Cloudflare Worker manifest (R2 binding, `assets:`, vars, cron, observability).
729
+ - `wrangler.jsonc` — Cloudflare Worker manifest (R2 binding, `assets:`, vars).
705
730
  - `vite.config.ts` — Vite + `@vitejs/plugin-react` + `@cloudflare/vite-plugin`.
706
731
  - `package.json` — root scripts + dependencies.