@gusto/create-baerly-storage 0.1.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 (88) hide show
  1. package/dist/index.js +2737 -0
  2. package/dist/index.js.map +1 -0
  3. package/dist/templates/addons/docker/.dockerignore +13 -0
  4. package/dist/templates/addons/docker/Dockerfile +65 -0
  5. package/dist/templates/addons/docker/healthcheck.js +15 -0
  6. package/dist/templates/minimal-cloudflare/.baerly/scaffold.json +10 -0
  7. package/dist/templates/minimal-cloudflare/AGENTS.md +556 -0
  8. package/dist/templates/minimal-cloudflare/README.md +169 -0
  9. package/dist/templates/minimal-cloudflare/_gitignore +6 -0
  10. package/dist/templates/minimal-cloudflare/baerly.config.ts +20 -0
  11. package/dist/templates/minimal-cloudflare/index.html +12 -0
  12. package/dist/templates/minimal-cloudflare/package.json +28 -0
  13. package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +15 -0
  14. package/dist/templates/minimal-cloudflare/src/notes.test.ts +19 -0
  15. package/dist/templates/minimal-cloudflare/src/server/index.ts +11 -0
  16. package/dist/templates/minimal-cloudflare/src/web/main.ts +27 -0
  17. package/dist/templates/minimal-cloudflare/tsconfig.app.json +28 -0
  18. package/dist/templates/minimal-cloudflare/tsconfig.json +9 -0
  19. package/dist/templates/minimal-cloudflare/tsconfig.worker.json +28 -0
  20. package/dist/templates/minimal-cloudflare/types.ts +23 -0
  21. package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +16 -0
  22. package/dist/templates/minimal-cloudflare/vite.config.ts +6 -0
  23. package/dist/templates/minimal-cloudflare/vitest.config.ts +11 -0
  24. package/dist/templates/minimal-cloudflare/wrangler.jsonc +27 -0
  25. package/dist/templates/minimal-node/.baerly/scaffold.json +13 -0
  26. package/dist/templates/minimal-node/.env.example +14 -0
  27. package/dist/templates/minimal-node/AGENTS.md +488 -0
  28. package/dist/templates/minimal-node/README.md +180 -0
  29. package/dist/templates/minimal-node/_gitignore +7 -0
  30. package/dist/templates/minimal-node/baerly.config.ts +20 -0
  31. package/dist/templates/minimal-node/index.html +12 -0
  32. package/dist/templates/minimal-node/package.json +26 -0
  33. package/dist/templates/minimal-node/pnpm-workspace.yaml +9 -0
  34. package/dist/templates/minimal-node/src/notes.test.ts +19 -0
  35. package/dist/templates/minimal-node/src/server/index.ts +46 -0
  36. package/dist/templates/minimal-node/src/web/main.ts +27 -0
  37. package/dist/templates/minimal-node/tsconfig.app.json +28 -0
  38. package/dist/templates/minimal-node/tsconfig.json +9 -0
  39. package/dist/templates/minimal-node/tsconfig.server.json +28 -0
  40. package/dist/templates/minimal-node/types.ts +23 -0
  41. package/dist/templates/minimal-node/uint8array-base64.d.ts +16 -0
  42. package/dist/templates/minimal-node/vite.config.ts +15 -0
  43. package/dist/templates/minimal-node/vitest.config.ts +12 -0
  44. package/dist/templates/react-cloudflare/.baerly/scaffold.json +10 -0
  45. package/dist/templates/react-cloudflare/AGENTS.md +715 -0
  46. package/dist/templates/react-cloudflare/README.md +115 -0
  47. package/dist/templates/react-cloudflare/_gitignore +6 -0
  48. package/dist/templates/react-cloudflare/baerly.config.ts +37 -0
  49. package/dist/templates/react-cloudflare/index.html +12 -0
  50. package/dist/templates/react-cloudflare/package.json +34 -0
  51. package/dist/templates/react-cloudflare/pnpm-workspace.yaml +15 -0
  52. package/dist/templates/react-cloudflare/src/notes.test.ts +19 -0
  53. package/dist/templates/react-cloudflare/src/server/index.ts +12 -0
  54. package/dist/templates/react-cloudflare/src/web/App.tsx +38 -0
  55. package/dist/templates/react-cloudflare/src/web/NoteList.tsx +93 -0
  56. package/dist/templates/react-cloudflare/src/web/client.ts +13 -0
  57. package/dist/templates/react-cloudflare/src/web/main.tsx +14 -0
  58. package/dist/templates/react-cloudflare/src/web/styles.css +57 -0
  59. package/dist/templates/react-cloudflare/tsconfig.app.json +29 -0
  60. package/dist/templates/react-cloudflare/tsconfig.json +9 -0
  61. package/dist/templates/react-cloudflare/tsconfig.worker.json +28 -0
  62. package/dist/templates/react-cloudflare/uint8array-base64.d.ts +16 -0
  63. package/dist/templates/react-cloudflare/vite.config.ts +7 -0
  64. package/dist/templates/react-cloudflare/vitest.config.ts +11 -0
  65. package/dist/templates/react-cloudflare/wrangler.jsonc +27 -0
  66. package/dist/templates/react-node/.baerly/scaffold.json +13 -0
  67. package/dist/templates/react-node/.env.example +14 -0
  68. package/dist/templates/react-node/AGENTS.md +662 -0
  69. package/dist/templates/react-node/README.md +187 -0
  70. package/dist/templates/react-node/_gitignore +7 -0
  71. package/dist/templates/react-node/baerly.config.ts +37 -0
  72. package/dist/templates/react-node/index.html +12 -0
  73. package/dist/templates/react-node/package.json +32 -0
  74. package/dist/templates/react-node/pnpm-workspace.yaml +9 -0
  75. package/dist/templates/react-node/src/notes.test.ts +19 -0
  76. package/dist/templates/react-node/src/server/index.ts +48 -0
  77. package/dist/templates/react-node/src/web/App.tsx +38 -0
  78. package/dist/templates/react-node/src/web/NoteList.tsx +93 -0
  79. package/dist/templates/react-node/src/web/client.ts +13 -0
  80. package/dist/templates/react-node/src/web/main.tsx +14 -0
  81. package/dist/templates/react-node/src/web/styles.css +57 -0
  82. package/dist/templates/react-node/tsconfig.app.json +29 -0
  83. package/dist/templates/react-node/tsconfig.json +9 -0
  84. package/dist/templates/react-node/tsconfig.server.json +28 -0
  85. package/dist/templates/react-node/uint8array-base64.d.ts +16 -0
  86. package/dist/templates/react-node/vite.config.ts +17 -0
  87. package/dist/templates/react-node/vitest.config.ts +12 -0
  88. package/package.json +41 -0
@@ -0,0 +1,488 @@
1
+ ---
2
+ title: AGENTS.md — agent guidance for minimal-node
3
+ audience: agent
4
+ summary: How to develop and deploy minimal-node, a baerly app.
5
+ tags: [agent-entry, baerly]
6
+ ---
7
+
8
+ # AGENTS.md
9
+
10
+ ## STOP — read this before writing any storage code
11
+
12
+ Your training data is dense with Postgres + Prisma/Drizzle, Mongo,
13
+ and Firebase patterns. **None of them apply here.** This is a baerly
14
+ app — a small, LLM-legible document database with a narrow API on top
15
+ of S3-compatible storage. Before writing or modifying storage code,
16
+ read:
17
+
18
+ - **`node_modules/@gusto/baerly-storage/dist/API.md`** — hand-authored
19
+ public-API quickref. Read first. Lists every method, every error
20
+ code, every example. If a pattern you want to use isn't here, it
21
+ doesn't exist in baerly.
22
+ - **`node_modules/@gusto/baerly-storage/dist/*.d.ts`** — authoritative type
23
+ signatures. `Db`, `Collection<T>`, `Query<T>`, and `Predicate<T>` are
24
+ the whole API surface.
25
+
26
+ Common anti-patterns that compile but are wrong:
27
+
28
+ - `db.collection(name).insertOne(...)` / `.find({...})` (Mongo) — use
29
+ `db.collection(name).insert(row)` and `.where({ ... }).all()`.
30
+ - `z.string().nullable()` in a schema — `DocumentValue` excludes
31
+ `null`. Use `.optional()`; `null` in an update patch is the RFC
32
+ 7396 deletion sentinel, not a storable value.
33
+ - Raw SQL strings, `WHERE` clauses, hand-built query AST — the only
34
+ query surface is `db.collection(...).where({ field: value }).all()` or
35
+ `.where(q => q.gte("count", 1))`. See **Predicates** below.
36
+ - `.useIndex("name")` / `.hint(...)` — no such methods. The planner
37
+ picks the index automatically from `IndexDefinition`s in
38
+ `baerly.config.ts`. See **Indexes** below.
39
+
40
+ ## What this is
41
+
42
+ `minimal-node` is a baerly app scaffolded with `create-baerly-storage` for the
43
+ Node target — any host that runs `node server.js` (Railway, Render,
44
+ Fly without Docker, Heroku, a VM, a container scheduler). One flat
45
+ package: the Node-side server lives in `src/server/index.ts`; the
46
+ optional client lives in `src/web/`. Configuration lives in
47
+ `baerly.config.ts`.
48
+
49
+ Single package, single `vite` process: `baerlyDev()` from
50
+ `@gusto/baerly-storage/dev/vite` mounts the Node HTTP listener as Vite
51
+ middleware on `:5173` alongside the SPA dev server, so `pnpm dev`
52
+ brings up SPA + HMR + `/v1/*` in one command — same origin in dev,
53
+ same `dist/client/`-served origin in production via `pnpm start`
54
+ (the listener serves the built SPA via the `baerlyNode({ webRoot })`
55
+ option).
56
+
57
+ If this scaffold was created with `--with=docker`, you'll also have a
58
+ multi-stage distroless `Dockerfile`, a `.dockerignore`, and a
59
+ `healthcheck.js` at the project root — wired to the same
60
+ `pnpm install && pnpm build && pnpm start` flow.
61
+
62
+ Public API docs: https://docs.baerly.dev/ (the JSDoc on
63
+ `baerly-storage`'s `Db` and `Collection` is the canonical reference;
64
+ read it via your editor's TS LS or via the published types).
65
+
66
+ ## Toolchain
67
+
68
+ - **Package manager:** pnpm. The emitted repo pins
69
+ `packageManager: pnpm@11.1.2`.
70
+ - **Test runner:** vitest.
71
+ - **Type checker:** TypeScript 5.6+. (The baerly-storage monorepo
72
+ itself uses TypeScript 7 via `@typescript/native-preview`; this
73
+ template tracks the broadly-compatible TS major so scaffolded
74
+ apps work with the wider ecosystem.)
75
+ - **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the
76
+ code stays compatible with type-stripping runtimes (Node's
77
+ `--experimental-strip-types`, esbuild's strip path). The flag bans
78
+ TS constructs that can't be type-erased: write
79
+ `class { x: T; constructor(x: T) { this.x = x } }` explicitly
80
+ instead of parameter-property shorthand
81
+ (`constructor(private x: T) {}` fails with TS1294). The same goes
82
+ for `enum`, namespaces with non-type bindings, and `private` /
83
+ `protected` / `public` accessibility modifiers on constructor
84
+ parameters.
85
+
86
+ ## Verification
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 |
97
+
98
+ **`pnpm verify` exercises typecheck + tests only.** The dev-auth
99
+ middleware, the SPA bundle, and any custom `/api/*` route are NOT
100
+ under test — verify will exit green even when the dev plugin returns
101
+ 401 on every browser request or the SPA throws on mount. For changes
102
+ that touch `vite.config.ts`, `src/server/index.ts`, or SPA logic, run
103
+ `pnpm dev` and exercise the change in a browser (or `curl
104
+ http://localhost:5173/<path>`) before declaring the task complete.
105
+
106
+ ## Where the code is
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. |
116
+
117
+ > **`baerly.config.ts` and `types.ts` are dual-included** by both
118
+ > `tsconfig.app.json` and `tsconfig.server.json`. Both can only
119
+ > import from `baerly-storage`, `zod`, and other dual-included root
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.
125
+
126
+ ## When editing X, read Y
127
+
128
+ - **Writing tests** — the kernel exports `MemoryStorage`, an
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.
133
+
134
+ ```ts
135
+ // src/notes.test.ts
136
+ import { test, expect } from "vitest";
137
+ import { Db, MemoryStorage } from "@gusto/baerly-storage";
138
+ import config from "../baerly.config.ts";
139
+
140
+ test("notes round-trip", async () => {
141
+ const db = Db.create({
142
+ storage: new MemoryStorage(),
143
+ app: "test",
144
+ tenant: "t",
145
+ config,
146
+ });
147
+ const { _id } = await db.collection("notes").insert({ body: "hello" });
148
+ const row = await db.collection("notes").get(_id);
149
+ expect(row?.body).toBe("hello");
150
+ });
151
+ ```
152
+
153
+ Each `new MemoryStorage()` is a fresh bucket — no shared state
154
+ across tests. For multi-writer scenarios (causal-consistency
155
+ tests, etc.), construct one `MemoryStorage` and pass the same
156
+ instance into multiple `Db.create` calls so they share the
157
+ underlying bucket.
158
+
159
+ - **Predicates** — `db.collection<Doc>(name).where({...}).all()`. Two
160
+ shapes:
161
+
162
+ - **Object literal** — equality only (top-level, dotted-path, or
163
+ nested literal sub-predicate). Multi-field is implicit AND.
164
+ - **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`
165
+ for the operator vocabulary. The methods on `PredicateBuilder<T>`
166
+ ARE the supported surface — `q.or` / `q.regex` / `q.ne` /
167
+ `q.exists` are TS compile errors. Chained `.where(...).where(...)`
168
+ AND-merges across shapes.
169
+
170
+ ```ts
171
+ // Top-level equality
172
+ await db.collection("tickets").where({ status: "open" }).all();
173
+
174
+ // Dotted-path on a nested field
175
+ await db.collection("tickets")
176
+ .where({ "assignee.team": "platform" })
177
+ .all();
178
+
179
+ // Operator on a single field — set membership (callback form)
180
+ await db.collection("tickets")
181
+ .where(q => q.in("status", ["open", "pending"]))
182
+ .all();
183
+
184
+ // Range — also callback form
185
+ await db.collection("tickets")
186
+ .where(q => q.gte("priority", 5).lt("priority", 10))
187
+ .all();
188
+
189
+ // AND-merge across two .where() calls (mix shapes freely)
190
+ await db.collection("tickets")
191
+ .where({ status: "open" })
192
+ .where(q => q.gte("priority", 5))
193
+ .all();
194
+ ```
195
+
196
+ The plain-equality value type is JSON-arrayless: string / number /
197
+ boolean / nested object. Use `q.in("status", [...])` for
198
+ set membership when you'd otherwise want
199
+ `{ status: ["open","pending"] }`.
200
+
201
+ - **Indexes** — declare them in `baerly.config.ts`; the read-path
202
+ planner picks one automatically when the predicate's equality
203
+ fields cover an index's keys. No call-site hint is needed (the
204
+ earlier `.useIndex(name)` chain was removed when the planner
205
+ shipped — `Query<T>` has no such method).
206
+
207
+ ```ts
208
+ import { defineConfig } from "@gusto/baerly-storage/config";
209
+
210
+ export default defineConfig({
211
+ collections: {
212
+ tickets: {
213
+ indexes: [{ name: "by_status", on: "status" }],
214
+ },
215
+ },
216
+ });
217
+ ```
218
+
219
+ With that declared, `db.collection("tickets").where({ status: "open"
220
+ }).all()` walks `by_status` automatically. Composite indexes
221
+ (`on: ["status", "priority"]`) match any leftmost prefix.
222
+ Mismatches (predicate doesn't cover any index) fall back to a full
223
+ table scan with a metric bump; correctness is preserved because the
224
+ reader re-checks the predicate in memory regardless of how it got
225
+ the row set.
226
+
227
+ - **Schemas (live feature)** — schemas are validated on the server
228
+ for every `insert` / `update` / `replace` when bound. Declare via
229
+ `defineConfig` using any StandardSchema v1 validator (Zod 3.24+,
230
+ Valibot 0.36+, ArkType 2.0+, or anything implementing the spec):
231
+
232
+ ```ts
233
+ import { z } from "zod";
234
+ import { defineConfig } from "@gusto/baerly-storage/config";
235
+
236
+ const Ticket = z.object({
237
+ _id: z.string().optional(),
238
+ status: z.enum(["open", "closed"]),
239
+ title: z.string().min(1),
240
+ });
241
+
242
+ export default defineConfig({
243
+ collections: {
244
+ tickets: { schema: Ticket },
245
+ },
246
+ });
247
+ ```
248
+
249
+ On a validation failure the server throws
250
+ `BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
251
+ HTTP clients see a 422 with the same envelope. Validation runs
252
+ on the post-image so `update` and `replace` see the full doc, not
253
+ just the patch.
254
+
255
+ - **HTTP wire format (calling `/v1/*` directly)** — the JS SDK
256
+ (`db.collection(name).insert(...)`) is the canonical path; reach for `curl`
257
+ only when debugging the wire. Mutation bodies are wrapped:
258
+
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` |
265
+
266
+ Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
267
+ `GET /v1/since?collection=…&cursor=…`) take no body and return
268
+ `{ data, _meta }` or a route-specific envelope. A flat `POST` body
269
+ (without the `doc` wrapper) returns
270
+ `400 SchemaError "Request body must be { doc: object }"` — the
271
+ wording is locked by `assertJsonBodyField` in the kernel. Canonical
272
+ reference: the `Routes` type and the JSDoc on `createRouter` in
273
+ `baerly-storage`.
274
+
275
+ - **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`:
276
+ every request resolves to `tenant: "minimal-demo"` and `Authorization`
277
+ 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.
281
+
282
+ ### Going to production
283
+
284
+ The scaffold ships `auth: "none"` so the day-1 happy path works with
285
+ zero env vars. Two patterns flip to a production-fit posture; pick
286
+ the one matching your gate.
287
+
288
+ <!-- pattern-b:start -->
289
+ **Pattern B — `auth: "shared-secret"`** (single-tenant
290
+ server-to-server). No factory code changes; `baerly.config.ts` flips:
291
+
292
+ ```ts
293
+ // baerly.config.ts
294
+ auth: "shared-secret", // ← flip from "none"
295
+ ```
296
+
297
+ Dev: put `SHARED_SECRET=dev-shared-secret` in `.env`. Prod: set
298
+ `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`.
302
+
303
+ <!-- pattern-b:end -->
304
+ <!-- pattern-c:start -->
305
+ **Pattern C — JWKS-backed JWT** (multi-tenant; OIDC IdP). The factory
306
+ `verifier:` overrides `config.auth`, so dev keeps `"none"` and prod
307
+ gets `bearerJwt`:
308
+
309
+ ```ts
310
+ // baerly.config.ts — unchanged
311
+ auth: "none", // dev default
312
+ ```
313
+
314
+ ```ts
315
+ // src/server/index.ts
316
+ import { baerlyNode, s3Storage } from "@gusto/baerly-storage/node";
317
+ import { bearerJwt } from "@gusto/baerly-storage/auth";
318
+ import config from "../../baerly.config.ts";
319
+
320
+ await baerlyNode({
321
+ config,
322
+ storage: s3Storage({
323
+ region: process.env["AWS_REGION"] ?? "us-east-1",
324
+ bucket: process.env["BUCKET"]!,
325
+ credentials: {
326
+ accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
327
+ secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
328
+ },
329
+ }),
330
+ ...(process.env["JWKS_URL"] !== undefined && {
331
+ verifier: bearerJwt({
332
+ jwks: process.env["JWKS_URL"],
333
+ issuer: process.env["JWT_ISSUER"]!,
334
+ audience: process.env["JWT_AUDIENCE"]!,
335
+ }),
336
+ }),
337
+ }).listen(Number(process.env["PORT"] ?? 8080));
338
+ ```
339
+
340
+ Dev sees `JWKS_URL` as `undefined`, spread short-circuits, and
341
+ `config.auth: "none"` runs. Prod sets `JWKS_URL` + `JWT_ISSUER` +
342
+ `JWT_AUDIENCE` and `bearerJwt` engages.
343
+
344
+ <!-- pattern-c:end -->
345
+ - **Storage backend** — `src/server/index.ts` picks between
346
+ `s3Storage` (AWS) and `r2Storage` (Cloudflare R2) based on whether
347
+ `R2_ACCOUNT_ID` is set. To use **Minio** (self-hosted dev S3) or
348
+ **GCS** (HMAC keys), swap the import to `minioStorage` /
349
+ `gcsStorage` from `@gusto/baerly-storage/node`. All four factories take
350
+ the same shape — a single bucket-name + credentials object — and
351
+ hide `aws4fetch` / `@xmldom/xmldom` behind the package boundary.
352
+ JSDoc `@example` blocks for each factory are visible in your
353
+ editor's TS hover.
354
+
355
+ - **Switching from static creds to EKS Pod Identity** — in
356
+ `src/server/index.ts`, swap `credentials: { accessKeyId,
357
+ secretAccessKey }` for `credentials: fromEksPodIdentity()` and add
358
+ `fromEksPodIdentity` to your import:
359
+ `import { s3Storage, fromEksPodIdentity } from "@gusto/baerly-storage/node"`.
360
+ The agent reads `AWS_CONTAINER_CREDENTIALS_FULL_URI` +
361
+ `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` (EKS injects both). For
362
+ IRSA / ECS / EC2 / other AWS contexts, see
363
+ `packages/adapter-node/AGENTS.md` — pass any
364
+ `() => Promise<Credentials>` or an `@aws-sdk/credential-providers`
365
+ factory through the seam.
366
+
367
+ - **Maintenance loop (Node)** — `src/server/index.ts` passes a
368
+ `maintenance: { collections, tenants }` option to `baerlyNode`.
369
+ Each tick (hourly by default; override via
370
+ `maintenance.intervalMs`) runs one compact+GC pass per
371
+ `(tenant, collection)` pair against the engine's default
372
+ unbounded maintenance profile (folds the entire live tail; sweeps
373
+ every aged-out candidate the GC marks).
374
+
375
+ Opt-in via the `MAINTENANCE_COLLECTIONS` env var — a comma-
376
+ separated list of collection slugs:
377
+
378
+ ```sh
379
+ MAINTENANCE_COLLECTIONS=tickets,comments
380
+ ```
381
+
382
+ When unset, the entry passes `maintenance: undefined` to
383
+ `baerlyNode` and no in-process loop runs. Operators who prefer
384
+ external scheduling can wire a separate cron trigger (PaaS cron,
385
+ k8s CronJob, systemd timer) per collection that invokes
386
+ `runMaintenanceTick` directly — that function stays exported
387
+ from `@gusto/baerly-storage/node`.
388
+
389
+ The template is single-tenant by default (`tenants: [TENANT]`).
390
+ Multi-tenant deployments override the `tenants` array in
391
+ `src/server/index.ts`; the cross-product `tenants × collections`
392
+ defines the work per tick. A separate `runMaintenanceTick` call
393
+ fires per pair, and a failure on one pair logs to stderr without
394
+ crashing the process or blocking the others.
395
+
396
+ Maintenance emits one canonical info line per `(tenant,
397
+ collection)` run on stdout.
398
+ Filter your log stream on `"unit_of_work": "maintenance"` and
399
+ read these fields:
400
+
401
+ - `compact_written` — log entries folded into the new snapshot
402
+ this tick (`0` when the live tail was below
403
+ `minEntriesToCompact`).
404
+ - `gc_swept` — keys deleted this tick (`0` when no candidates
405
+ aged out).
406
+ - The kernel also emits the recorder-bag fields alongside:
407
+ `db.compact.entries_folded_p50` / `_p99` / `_count` / `_sum`,
408
+ `db.manifest.lag_window_depth`, `db.orphan.candidate_count`,
409
+ `db.gc.entries_swept_per_second`, `db.gc.swept_total`.
410
+ Useful for dashboards; the four explicit fields above are
411
+ the at-a-glance summary.
412
+
413
+ - **Deploy** — runs anywhere `node server.js` runs. The
414
+ `package.json`'s `start` script is
415
+ `node --experimental-strip-types src/server/index.ts`. Arrange the
416
+ host to run `pnpm install && pnpm build` (populates
417
+ `dist/client/` for the `webRoot` static-serve branch) before
418
+ `pnpm start`. Set env vars from `.env.example` in the host's
419
+ config.
420
+
421
+ Shapes: **managed PaaS** (Railway, Render, DO App Platform, Fly
422
+ without Docker, Heroku) auto-detects Node and runs the root
423
+ scripts directly. **VM / bare-metal** uses your process manager
424
+ of choice (systemd, pm2). **Container** (Docker, k8s, ECS, Fly
425
+ Machines with a Dockerfile) — scaffold with `--with=docker` to
426
+ add a production Dockerfile alongside this shape, or write your
427
+ own.
428
+
429
+ ## Anti-patterns
430
+
431
+ - Widening branded types from `baerly-storage` (`UUID`,
432
+ `ContentVersionId`). The types prevent confusion bugs.
433
+ - Reaching into `node_modules/@gusto/baerly-storage/dist/` directly —
434
+ consume the published exports.
435
+ - Mutating `VerifierResult.tenantPrefix` between the verifier
436
+ and `Db.create`. The dispatcher pins the tenant from the
437
+ verifier's return value.
438
+ - Calling `db.collection(...).all()` (or any unbounded read) inside a
439
+ per-request handler. The call scans the entire collection on every
440
+ request — fine for a fixture-sized table, catastrophic at any real
441
+ size, and `pnpm verify` doesn't surface the cost. Push the filter
442
+ into the predicate so the index planner can prune
443
+ (`db.collection("notes").where({ ... }).all()`), or maintain a
444
+ side-projection (Postgres/SQLite/search index) populated
445
+ incrementally from the `/v1/since` log feed or from a write hook —
446
+ never re-scan per request.
447
+
448
+ ## When to graduate
449
+
450
+ baerly is designed for the small-to-medium operating point. The cost
451
+ model puts the soft ceiling at:
452
+
453
+ - **~30 writes / minute / collection**
454
+ - **~10 GB / tenant**
455
+ - **~100 collections / tenant**
456
+
457
+ Past those, S3 list-prefix latency, manifest fold cost, and per-class
458
+ op pricing start to dominate; you're better off on a real database.
459
+ Pick your graduation target:
460
+ - **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
461
+ - **Off-Workers or portability matters:** managed Postgres.
462
+ - **Single-instance Node:** SQLite via Litestream.
463
+
464
+ Either way, the export below is mechanical because log entries are
465
+ Postgres-logical-replication-shaped — graduation is a Baerly win,
466
+ not a churn event.
467
+
468
+ **Estimate your current rate:** `baerly admin usage --target=...`
469
+ lists recent log entries per collection and computes
470
+ writes/min. Warning at 50% of the ceiling; export suggestion at
471
+ 100%.
472
+
473
+ **Export when ready:** `baerly export --target=sqlite|postgres|d1
474
+ --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
475
+ canonical SQL dump (and a `<output>.plan.json` sidecar carrying the
476
+ inferred `ExportPlan`) that you load into your graduation target.
477
+ The export is point-in-time and honours the active schema. Flags:
478
+ `--where=<json-predicate>`, `--where-comment`, `--output`,
479
+ `--no-sidecar`, `--json`. Exit codes: 0 success, 1 InvalidConfig,
480
+ 2 Storage/Network, 3 Protocol invariant.
481
+
482
+ ## Pointers
483
+
484
+ - `baerly.config.ts` — app config.
485
+ - `src/server/index.ts` — node:http listener entry.
486
+ - `src/web/main.ts`, `index.html` — SPA client entry.
487
+ - `vite.config.ts` — Vite client build (output `dist/client/`).
488
+ - `package.json` — single-package root scripts.
@@ -0,0 +1,180 @@
1
+ # minimal-node
2
+
3
+ A baerly app scaffolded with `@gusto/create-baerly-storage` for the **Node** target —
4
+ any host that runs `node server.js` (Railway, Render, Fly without
5
+ Docker, Heroku, a VM, a container scheduler, your laptop). Uses
6
+ `@gusto/baerly-storage/node` against an S3-compatible bucket (AWS S3, R2 via
7
+ S3-compat, Minio, etc.). Ships `auth: "none"` so the day-1 happy
8
+ path works with zero env vars; flip to a shared secret or wire
9
+ `bearerJwt` against your OIDC IdP before deploy — see "Going to
10
+ production" below.
11
+
12
+ To ship a production Dockerfile alongside, scaffold with
13
+ `--with=docker` — the add-on writes a multi-stage distroless Dockerfile,
14
+ `.dockerignore`, and `healthcheck.js` into this same shape.
15
+
16
+ ## What you got
17
+
18
+ ```
19
+ minimal-node/
20
+ ├── package.json # one package, all deps
21
+ ├── tsconfig.json # project-references stub
22
+ ├── tsconfig.app.json # client TS project (src/web)
23
+ ├── tsconfig.server.json # Node server TS project (src/server)
24
+ ├── vite.config.ts # Vite SPA build → dist/client/
25
+ ├── index.html # SPA shell — Vite's entry point
26
+ ├── .env.example # storage creds, verifier, observability
27
+ ├── baerly.config.ts # app, tenant, target, domain
28
+ ├── AGENTS.md # deeper guide: predicates, schemas,
29
+ │ # auth recipes, graduation
30
+ ├── src/
31
+ │ ├── server/
32
+ │ │ └── index.ts # baerlyNode({ app, storage, verifier, webRoot, maintenance? }).listen(PORT)
33
+ │ └── web/
34
+ │ └── main.ts # SPA client entry — bundled into dist/client/
35
+ └── README.md
36
+ ```
37
+
38
+ ## Run locally
39
+
40
+ ```sh
41
+ pnpm install
42
+ pnpm dev
43
+ ```
44
+
45
+ `pnpm dev` runs `vite`. `baerlyDev()` from `@gusto/baerly-storage/dev/vite`
46
+ mounts the Node HTTP listener as Connect middleware on the same Vite
47
+ process that serves the SPA, so `GET /` hits the SPA on
48
+ `http://localhost:5173/` and anything baerly handles (e.g.
49
+ `GET /v1/healthz`) is served on the same origin — one process, one
50
+ port, SPA + HMR + `/v1/*` in one command. Storage is `LocalFsStorage`
51
+ rooted at `.baerly-data/`, so first-touch needs no S3 creds, no JWKS,
52
+ and no second process.
53
+
54
+ For production-shaped local runs (S3 and the bundled SPA served
55
+ from `dist/client/`):
56
+
57
+ ```sh
58
+ pnpm build
59
+ BUCKET=... AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... pnpm start
60
+ ```
61
+
62
+ The server reads `BUCKET`, `AWS_ACCESS_KEY_ID`,
63
+ `AWS_SECRET_ACCESS_KEY` at startup. The default `auth: "none"`
64
+ posture needs no auth env vars; if you adopt Pattern B / C from
65
+ "Going to production" below, also set `SHARED_SECRET` (Pattern B)
66
+ or `JWKS_URL` + `JWT_ISSUER` + `JWT_AUDIENCE` (Pattern C). Optional:
67
+ `R2_ACCOUNT_ID` (switches the storage factory from `s3Storage` to
68
+ `r2Storage`), `AWS_REGION`, `PORT`, `TENANT`, `WEB_ROOT`,
69
+ `MAINTENANCE_COLLECTIONS` (comma-separated collection slugs — when
70
+ set, `baerlyNode` runs one compact+GC pass per `(tenant, collection)`
71
+ pair on its hourly tick; leave unset to skip the in-process loop and
72
+ schedule maintenance externally — a PaaS cron, k8s CronJob, systemd
73
+ timer).
74
+
75
+ After `pnpm build`, `http://localhost:8080/` serves the built SPA
76
+ out of `dist/client/` and `http://localhost:8080/v1/*` is the
77
+ baerly HTTP surface — single origin, no CORS.
78
+
79
+ `pnpm typecheck` runs `tsc -b --noEmit` across both project
80
+ references.
81
+
82
+ ## Deploy
83
+
84
+ This scaffold runs anywhere `node server.js` runs. The `package.json`
85
+ exposes `build` (Vite SPA + TS check) and `start`
86
+ (`node --experimental-strip-types src/server/index.ts`); arrange your
87
+ host to run `pnpm install && pnpm build`, then `pnpm start`.
88
+
89
+ Concrete shapes:
90
+
91
+ - **Managed PaaS** (Railway, Render, DO App Platform, Fly Machines
92
+ without a Dockerfile, Heroku): push the repo to a connected GitHub
93
+ repo, set env vars from `.env.example` in the dashboard, deploy.
94
+ The platform's buildpack detects Node and runs the root scripts.
95
+ - **VM / bare-metal**: clone, install Node 24+, copy `.env.example`
96
+ to `.env`, run `pnpm install && pnpm build && pnpm start` under
97
+ your process manager of choice (systemd, pm2, etc.).
98
+ - **Container** (Docker, k8s, ECS, Fly Machines with a Dockerfile):
99
+ scaffold with `pnpm create @gusto/baerly-storage@latest --target=node --with=docker` to add
100
+ a production Dockerfile, `.dockerignore`, and `healthcheck.js`
101
+ alongside this shape, then `docker build .`.
102
+
103
+ Verify: `curl https://<your-service>/v1/healthz`.
104
+
105
+ ## Next steps
106
+
107
+ 1. **Read `AGENTS.md`** for the agent-facing guide — predicates,
108
+ indexes, schemas, auth recipes (JWKS setup), the in-process
109
+ maintenance loop, and the graduation criteria. (Claude Code
110
+ users: `@gusto/create-baerly-storage` mirrors `AGENTS.md` to `CLAUDE.md` at
111
+ scaffold time.)
112
+ 2. **Declare your first collection schema** in `baerly.config.ts`
113
+ via `defineConfig({ collections: { ... } })` and pass it to
114
+ `Db.create({ ..., collections })`. Schema validation is live;
115
+ bad inserts return 422.
116
+ 3. **Set up production auth** — follow `AGENTS.md` → "Going to
117
+ production". Pattern B flips `auth: "shared-secret"` and reads
118
+ `SHARED_SECRET` from `process.env`; Pattern C wires `bearerJwt`
119
+ against your OIDC IdP via an env-aware factory `verifier:`
120
+ override (`JWKS_URL` + `JWT_ISSUER` + `JWT_AUDIENCE`).
121
+ `baerly doctor --target=node` reports any gaps.
122
+
123
+ ## When to graduate
124
+
125
+ baerly is designed for the small-to-medium operating point. Past these
126
+ thresholds, S3 list-prefix latency and per-class operation pricing
127
+ start to dominate, and you're better off on a real database:
128
+
129
+ - **~30 writes / minute / collection**
130
+ - **~10 GB / tenant**
131
+ - **~100 collections / tenant**
132
+
133
+ When you cross the soft ceiling, graduation is mechanical:
134
+ `baerly export --target=postgres` walks your log entries (already
135
+ Postgres-logical-replication-shaped) into a real DB. If your
136
+ deploy target is Cloudflare Workers and you'll accept Cloudflare
137
+ lock-in, [D1](https://developers.cloudflare.com/d1/) is cheaper
138
+ per-write at M-size and is a natural next step. If you're on
139
+ AWS, on-prem, or want your data portable, managed Postgres is
140
+ the typical destination. Either way — graduation is a Baerly win,
141
+ not a churn event.
142
+
143
+ **Export to a real database** (swap `--target=` for `sqlite`,
144
+ `postgres`, or `d1`):
145
+
146
+ ```sh
147
+ baerly export --target=postgres \
148
+ --bucket=minimal-node --app=minimal-node --tenant=<your-tenant> \
149
+ --collection=<collection-name> --output=./out.sql
150
+ ```
151
+
152
+ The export is a **point-in-time** snapshot and honors any active
153
+ schema on the collection. Your data was already in your bucket and
154
+ your code is a portable HTTP server, so the graduation doesn't
155
+ require vendor cooperation.
156
+
157
+ ## Production auth
158
+
159
+ The scaffold ships `auth: "none"` so the day-1 happy path works
160
+ with zero env vars; every request resolves to `config.tenant`.
161
+ Before deploy, follow `AGENTS.md` → "Going to production":
162
+
163
+ - **Pattern B — `auth: "shared-secret"`.** Single-tenant
164
+ server-to-server callers (CI, cron, internal services). Flip
165
+ `auth` in `baerly.config.ts` and put `SHARED_SECRET` in
166
+ `process.env` (your PaaS / secret manager).
167
+ - **Pattern C — JWKS-backed JWT (recommended for multi-tenant).**
168
+ Same artifact in dev and prod; the factory `verifier:` override
169
+ engages when `JWKS_URL` is set. `bearerJwt()` (re-exported from
170
+ `@gusto/baerly-storage/auth`) validates against your IdP's JWKS endpoint
171
+ (`https://<issuer>/.well-known/jwks.json`) with `JWT_ISSUER` +
172
+ `JWT_AUDIENCE` and pins the tenant from a claim.
173
+
174
+ ## Pointers
175
+
176
+ - `baerly.config.ts` — app config (`app`, `tenant`, `target`, `domain`).
177
+ - `src/server/index.ts` — node:http listener entry.
178
+ - `src/web/main.ts`, `index.html` — SPA client entry built into `dist/client/`.
179
+ - `vite.config.ts` — Vite client build.
180
+ - `AGENTS.md` — agent-facing guide (mirrored to `CLAUDE.md` at scaffold time).
@@ -0,0 +1,7 @@
1
+ node_modules/
2
+ dist/
3
+ .baerly-data/
4
+ .env
5
+ .env.local
6
+ .DS_Store
7
+ *.tsbuildinfo