@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,65 @@
1
+ # Production Dockerfile emitted by `create-baerly --target=node --with=docker`.
2
+ # Distroless final stage, non-root user, HEALTHCHECK via a Node
3
+ # script (distroless ships no wget/curl).
4
+ #
5
+ # Runtime path: node --experimental-strip-types src/server/index.ts.
6
+ # No `tsc` emit at runtime — the server runs straight off TS source.
7
+ # The SPA bundle (vite build) lives under dist/client/ and is served
8
+ # by createListener({ webRoot }).
9
+
10
+ # Base images are tag-pinned (not digest-pinned) so this template
11
+ # stays fresh as new patch images ship. Once you vendor this file,
12
+ # pin to digests for reproducibility: `docker pull <image>` then
13
+ # `docker inspect --format='{{index .RepoDigests 0}}' <image>` and
14
+ # replace the tag with `@sha256:...`.
15
+
16
+ # ---- Build stage ----
17
+ FROM node:24-bookworm-slim AS build
18
+ WORKDIR /app
19
+
20
+ RUN corepack enable
21
+ # pnpm version is driven by `packageManager` in package.json (pnpm 11.1.2).
22
+
23
+ # Manifest first for layer-cache hits.
24
+ COPY pnpm-lock.yaml package.json ./
25
+
26
+ RUN pnpm install --frozen-lockfile
27
+
28
+ # Source + build the SPA.
29
+ COPY . .
30
+ RUN pnpm build
31
+
32
+ # Prune to production deps for the runtime image.
33
+ RUN pnpm install --prod --frozen-lockfile
34
+
35
+ # ---- Runtime stage ----
36
+ FROM gcr.io/distroless/nodejs24-debian12 AS runtime
37
+ WORKDIR /app
38
+
39
+ # Distroless's `nonroot` user is UID 65532. We run as that.
40
+ USER nonroot:nonroot
41
+
42
+ # Copy the TS source, the SPA build, the healthcheck, the manifest,
43
+ # and the prune'd node_modules.
44
+ COPY --from=build --chown=nonroot:nonroot /app/src src
45
+ COPY --from=build --chown=nonroot:nonroot /app/dist/client dist/client
46
+ COPY --from=build --chown=nonroot:nonroot /app/healthcheck.js healthcheck.js
47
+ COPY --from=build --chown=nonroot:nonroot /app/package.json package.json
48
+ COPY --from=build --chown=nonroot:nonroot /app/node_modules node_modules
49
+
50
+ # OCI image labels — registries surface these.
51
+ LABEL org.opencontainers.image.title="minimal-node"
52
+ LABEL org.opencontainers.image.description="Baerly app — vendorless document database."
53
+ LABEL org.opencontainers.image.source="https://github.com/your-org/minimal-node"
54
+
55
+ ENV NODE_ENV=production
56
+ ENV PORT=8080
57
+ EXPOSE 8080
58
+
59
+ # Node-script HEALTHCHECK — distroless ships no wget/curl.
60
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
61
+ CMD ["node", "healthcheck.js"]
62
+
63
+ # Distroless's entrypoint IS node; we pass --experimental-strip-types
64
+ # and the TS source path as args.
65
+ ENTRYPOINT ["node", "--experimental-strip-types", "src/server/index.ts"]
@@ -0,0 +1,15 @@
1
+ // HEALTHCHECK script. Called by Docker against the container's
2
+ // running process. Exits 0 on liveness, 1 on failure. Pure Node
3
+ // (no deps); distroless can't run a shell.
4
+ import { request } from "node:http";
5
+
6
+ const req = request(
7
+ { host: "127.0.0.1", port: process.env.PORT ?? 8080, path: "/v1/healthz" },
8
+ (res) => process.exit(res.statusCode === 200 ? 0 : 1),
9
+ );
10
+ req.on("error", () => process.exit(1));
11
+ req.setTimeout(2000, () => {
12
+ req.destroy();
13
+ process.exit(1);
14
+ });
15
+ req.end();
@@ -0,0 +1,10 @@
1
+ {
2
+ "renames": [
3
+ { "from": "minimal-cloudflare", "fromKey": "appName" },
4
+ { "from": "minimal-demo", "fromKey": "tenant" }
5
+ ],
6
+ "excludePaths": [".baerly/scaffold.json"],
7
+ "excludeNames": ["node_modules", "dist", ".wrangler", ".dev.vars", ".DS_Store", "*.tsbuildinfo"],
8
+ "dropDevDeps": [],
9
+ "copies": [{ "from": "AGENTS.md", "to": "CLAUDE.md" }]
10
+ }
@@ -0,0 +1,556 @@
1
+ ---
2
+ title: AGENTS.md — agent guidance for minimal-cloudflare
3
+ audience: agent
4
+ summary: How to develop and deploy minimal-cloudflare, 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-cloudflare` is a baerly app scaffolded with `create-baerly-storage`.
43
+ The Worker-side server lives in `src/server/`; the optional client
44
+ lives in `src/web/`. Configuration lives in `baerly.config.ts`.
45
+
46
+ Single package, single `vite` process: `@cloudflare/vite-plugin` runs
47
+ the Worker inside `workerd` alongside the SPA dev server, and
48
+ `wrangler.jsonc:assets` ships the built `dist/client/` bundle next to
49
+ the Worker on deploy. Same origin in dev and prod, one deploy.
50
+
51
+ Public API docs: https://docs.baerly.dev/ (the JSDoc on
52
+ `baerly-storage`'s `Db` and `Collection` is the canonical reference;
53
+ read it via your editor's TS LS or via the published types).
54
+
55
+ ## Toolchain
56
+
57
+ - **Package manager:** pnpm. The emitted repo pins
58
+ `packageManager: pnpm@11.1.2`.
59
+ - **Test runner:** vitest.
60
+ - **Type checker:** TypeScript 5.6+. (The baerly-storage monorepo
61
+ itself uses TypeScript 7 via `@typescript/native-preview`; this
62
+ template tracks the broadly-compatible TS major so scaffolded
63
+ apps work with the wider ecosystem.)
64
+ - **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the
65
+ code stays compatible with type-stripping runtimes (Node's
66
+ `--experimental-strip-types`, esbuild's strip path). The flag bans
67
+ TS constructs that can't be type-erased: write
68
+ `class { x: T; constructor(x: T) { this.x = x } }` explicitly
69
+ instead of parameter-property shorthand
70
+ (`constructor(private x: T) {}` fails with TS1294). The same goes
71
+ for `enum`, namespaces with non-type bindings, and `private` /
72
+ `protected` / `public` accessibility modifiers on constructor
73
+ parameters.
74
+
75
+ ## Verification
76
+
77
+ | Command | What it does | Runtime |
78
+ | ---------------- | --------------------------------------------------------------------------------------- | ---------------- |
79
+ | `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 |
80
+ | `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 |
81
+ | `pnpm typecheck` | TS typecheck across the worker + web project references (`tsc -b --noEmit`) | seconds |
82
+ | `pnpm test` | `vitest run --passWithNoTests` — standalone `vitest.config.ts` (Node env, ignores `vite.config.ts` so the Cloudflare plugin doesn't load). The minimal template ships no SPA tests by default; `--passWithNoTests` keeps the gate green until you add one. | seconds |
83
+ | `pnpm dev` | Run `vite` — the Cloudflare plugin runs the Worker inside `workerd` next to the SPA dev server; same origin on :5173 | seconds to start |
84
+ | `pnpm build` | `tsc -b && vite build` — emits `dist/client/` for the Workers Assets binding | seconds |
85
+ | `pnpm deploy` | `wrangler deploy` — ships Worker + assets in one shipment (auto-creates R2 on first run via `--x-provision`) | seconds |
86
+
87
+ **`pnpm verify` exercises typecheck + tests only.** The dev-auth
88
+ middleware, the SPA bundle, and any custom `/api/*` route are NOT
89
+ under test — verify will exit green even when the dev plugin returns
90
+ 401 on every browser request or the SPA throws on mount. For changes
91
+ that touch `vite.config.ts`, `src/server/index.ts`, or SPA logic, run
92
+ `pnpm dev` and exercise the change in a browser (or `curl
93
+ http://localhost:5173/<path>`) before declaring the task complete.
94
+
95
+ ## Where the code is
96
+
97
+ | Path | What it is |
98
+ | -------------------------- | ------------------------------------------------------------------------------------ |
99
+ | `src/server/index.ts` | Worker entry — `baerlyWorker((env) => ({ verifier }))` |
100
+ | `wrangler.jsonc` | Cloudflare Worker manifest — name, R2 binding, assets, vars, triggers, limits, observability |
101
+ | `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.ts`. |
102
+ | `src/web/main.ts` | SPA client entry — 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 or replace; `client.collection<Row>(name)` is the typed surface. Workers Assets serves the built bundle from `dist/client/`. |
103
+ | `vite.config.ts` | Vite + `@cloudflare/vite-plugin` — runs the Worker inside `workerd` in dev |
104
+ | `tsconfig.json` | Root project-references stub |
105
+ | `tsconfig.app.json` | Client TS project (`src/web/`, DOM lib) |
106
+ | `tsconfig.worker.json` | Worker TS project (`src/server/`, workerd lib) |
107
+ | `baerly.config.ts` | App config — `app`, `tenant`, `target`, `domain`, `collections` (schemas live here). |
108
+ | `types.ts` | Shared types between the Worker (`src/server/`) and the SPA (`src/web/`). Both project tsconfigs include this file; put any row type or interface that crosses the boundary here. |
109
+
110
+ > **`baerly.config.ts` and `types.ts` are dual-included** by both
111
+ > `tsconfig.app.json` and `tsconfig.worker.json`. Both can only
112
+ > import from `baerly-storage`, `zod`, and other dual-included root
113
+ > files. Paths under `src/server/` are worker-only; importing them
114
+ > here triggers `TS6307: File … is not listed within the file list
115
+ > of project … tsconfig.app.json`. Cross-boundary interfaces belong
116
+ > in `types.ts`; re-export from a server-only file if downstream code
117
+ > wants a local name.
118
+
119
+ ## When editing X, read Y
120
+
121
+ - **Typed collections** — three ways to get a typed row, in DX order:
122
+ 1. **Bind the config.** Declare the collection (with an optional
123
+ schema) in `baerly.config.ts`, pass `config` to
124
+ `createBaerlyClient({ baseUrl, config })` (or `Db.create({
125
+ storage, config })`), and `client.collection("tickets")` returns
126
+ `ClientCollection<Row>` with `Row` derived from the schema. No
127
+ generic needed.
128
+ 2. **Explicit generic, kernel constraint.** Without a declared
129
+ collection, the second overload requires the row to satisfy
130
+ the kernel's `DocumentData` shape (`{ [k: string]: DocumentValue }`):
131
+ ```ts
132
+ import type { DocumentData } from "@gusto/baerly-storage";
133
+ interface Bookmark extends DocumentData { _id: string; url: string }
134
+ await client.collection<Bookmark>("bookmarks").all();
135
+ ```
136
+ A plain `interface Bookmark { _id: string; url: string }`
137
+ (no index signature) will fail with TS2344 — the constraint
138
+ is intentional so the row stays JSON-compatible.
139
+
140
+ - **Writing tests** — the kernel exports `MemoryStorage`, an
141
+ in-memory `Storage` impl that's the canonical backend for unit
142
+ tests. Don't roll your own — `Db.create({ storage, app, tenant,
143
+ config })` is the same boilerplate prod uses; passing
144
+ `new MemoryStorage()` swaps R2 for an in-process map.
145
+
146
+ ```ts
147
+ // src/notes.test.ts
148
+ import { test, expect } from "vitest";
149
+ import { Db, MemoryStorage } from "@gusto/baerly-storage";
150
+ import config from "../baerly.config.ts";
151
+
152
+ test("notes round-trip", async () => {
153
+ const db = Db.create({
154
+ storage: new MemoryStorage(),
155
+ app: "test",
156
+ tenant: "t",
157
+ config,
158
+ });
159
+ const { _id } = await db.collection("notes").insert({ body: "hello" });
160
+ const row = await db.collection("notes").get(_id);
161
+ expect(row?.body).toBe("hello");
162
+ });
163
+ ```
164
+
165
+ Each `new MemoryStorage()` is a fresh bucket — no shared state
166
+ across tests. For multi-writer scenarios (causal-consistency
167
+ tests, etc.), construct one `MemoryStorage` and pass the same
168
+ instance into multiple `Db.create` calls so they share the
169
+ underlying bucket.
170
+
171
+ - **Predicates** — `db.collection("tickets").where({...}).all()`. Two
172
+ shapes:
173
+
174
+ - **Object literal** — equality only (top-level, dotted-path, or
175
+ nested literal sub-predicate). Multi-field is implicit AND.
176
+ - **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`
177
+ for the operator vocabulary. The methods on `PredicateBuilder<T>`
178
+ ARE the supported surface — invoking `q.or` / `q.regex` /
179
+ `q.ne` / `q.exists` is a TS compile error, not a runtime
180
+ `InvalidConfig`. Chained `.where(...).where(...)` AND-merges
181
+ across calls and across shapes.
182
+
183
+ ```ts
184
+ // Top-level equality (Db inside the Worker, client in the SPA)
185
+ await db.collection("tickets").where({ status: "open" }).all();
186
+
187
+ // Dotted-path on a nested field
188
+ await db.collection("tickets")
189
+ .where({ "assignee.team": "platform" })
190
+ .all();
191
+
192
+ // Operator on a single field — set membership (callback form)
193
+ await db.collection("tickets")
194
+ .where(q => q.in("status", ["open", "pending"]))
195
+ .all();
196
+
197
+ // Range — also callback form
198
+ await db.collection("tickets")
199
+ .where(q => q.gte("priority", 5).lt("priority", 10))
200
+ .all();
201
+
202
+ // AND-merge across two .where() calls (mix shapes freely)
203
+ await db.collection("tickets")
204
+ .where({ status: "open" })
205
+ .where(q => q.gte("priority", 5))
206
+ .all();
207
+ ```
208
+
209
+ The plain-equality value type is JSON-arrayless: string / number /
210
+ boolean / nested object. Use `q.in("status", [...])` for
211
+ set membership when you'd otherwise want
212
+ `{ status: ["open","pending"] }`.
213
+
214
+ - **Indexes** — declare them in `baerly.config.ts`; the read-path
215
+ planner picks one automatically when the predicate's equality
216
+ fields cover an index's keys. No call-site hint is needed (the
217
+ earlier `.useIndex(name)` chain was removed when the planner
218
+ shipped — `Query<T>` has no such method).
219
+
220
+ ```ts
221
+ import { defineConfig } from "@gusto/baerly-storage/config";
222
+
223
+ export default defineConfig({
224
+ collections: {
225
+ tickets: {
226
+ indexes: [{ name: "by_status", on: "status" }],
227
+ },
228
+ },
229
+ });
230
+ ```
231
+
232
+ With that declared, `db.collection("tickets").where({ status: "open"
233
+ }).all()` walks `by_status` automatically. Composite indexes
234
+ (`on: ["status", "priority"]`) match any leftmost prefix.
235
+ Mismatches (predicate doesn't cover any index) fall back to a full
236
+ table scan with a metric bump; correctness is preserved because the
237
+ reader re-checks the predicate in memory regardless of how it got
238
+ the row set.
239
+
240
+ - **Schemas (live feature)** — schemas are validated on the server
241
+ for every `insert` / `update` / `replace` when bound. Declare via
242
+ `defineConfig` using any StandardSchema v1 validator (Zod 3.24+,
243
+ Valibot 0.36+, ArkType 2.0+, or anything implementing the spec):
244
+
245
+ ```ts
246
+ import { z } from "zod";
247
+ import { defineConfig } from "@gusto/baerly-storage/config";
248
+
249
+ const Ticket = z.object({
250
+ _id: z.string().optional(),
251
+ status: z.enum(["open", "closed"]),
252
+ title: z.string().min(1),
253
+ });
254
+
255
+ export default defineConfig({
256
+ collections: {
257
+ tickets: { schema: Ticket },
258
+ },
259
+ });
260
+ ```
261
+
262
+ On a validation failure the server throws
263
+ `BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
264
+ HTTP clients see a 422 with the same envelope. Validation runs
265
+ on the post-image so `update` and `replace` see the full doc, not
266
+ just the patch.
267
+
268
+ - **HTTP wire format (calling `/v1/*` directly)** — the JS SDK
269
+ (`db.collection(name).insert(...)`) is the canonical path; reach for `curl`
270
+ only when debugging the wire. Mutation bodies are wrapped:
271
+
272
+ | Route | Body | Response |
273
+ | --------------------------- | ------------------- | ----------------------------- |
274
+ | `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
275
+ | `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
276
+ | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
277
+ | `DELETE /v1/c/:collection/:id` | — | `204` |
278
+
279
+ Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
280
+ `GET /v1/since?collection=…&cursor=…`) take no body and return
281
+ `{ data, _meta }` or a route-specific envelope. A flat `POST` body
282
+ (without the `doc` wrapper) returns
283
+ `400 SchemaError "Request body must be { doc: object }"` — the
284
+ wording is locked by `assertJsonBodyField` in the kernel. Canonical
285
+ reference: the `Routes` type and the JSDoc on `createRouter` in
286
+ `baerly-storage`.
287
+
288
+ - **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`:
289
+ every request resolves to `tenant: "minimal-demo"` and `Authorization`
290
+ is ignored. The adapter reads `config.auth` to pick its verifier;
291
+ a `verifier:` on the factory overrides it. `baerly doctor
292
+ --target=cloudflare` warns on `"none"` for deploy targets. See
293
+ "Going to production" below for the two production-fit recipes.
294
+
295
+ ### Going to production
296
+
297
+ The scaffold ships `auth: "none"` so the day-1 happy path works with
298
+ zero env vars. Two patterns flip to a production-fit posture; pick the
299
+ one matching your gate.
300
+
301
+ <!-- pattern-a:start -->
302
+ **Pattern A — env-aware verifier (recommended for CF Access).** Same
303
+ artifact ships to dev and prod; the factory `verifier:` override
304
+ engages only when prod env vars are present. `baerlyWorker` resolves
305
+ the factory `verifier:` first, so the override silently supersedes
306
+ `config.auth: "none"` in prod.
307
+
308
+ ```ts
309
+ // baerly.config.ts — unchanged
310
+ import { defineConfig } from "@gusto/baerly-storage/config";
311
+
312
+ export default defineConfig({
313
+ app: "minimal-cloudflare",
314
+ tenant: "minimal-demo",
315
+ target: "cloudflare",
316
+ auth: "none", // dev default
317
+ collections: { notes: {} },
318
+ });
319
+ ```
320
+
321
+ ```ts
322
+ // src/server/index.ts
323
+ import { baerlyWorker, type BaerlyEnv } from "@gusto/baerly-storage/cloudflare";
324
+ import { cloudflareAccess } from "@gusto/baerly-storage/auth";
325
+ import config from "../../baerly.config.ts";
326
+
327
+ interface AppEnv extends BaerlyEnv {
328
+ readonly CF_ACCESS_TEAM_DOMAIN?: string;
329
+ readonly CF_ACCESS_AUDIENCE_TAG?: string;
330
+ }
331
+
332
+ export default baerlyWorker<AppEnv>((env) => ({
333
+ config,
334
+ ...(env.CF_ACCESS_TEAM_DOMAIN !== undefined &&
335
+ env.CF_ACCESS_AUDIENCE_TAG !== undefined && {
336
+ verifier: cloudflareAccess({
337
+ teamDomain: env.CF_ACCESS_TEAM_DOMAIN,
338
+ audienceTag: env.CF_ACCESS_AUDIENCE_TAG,
339
+ }),
340
+ }),
341
+ }));
342
+ ```
343
+
344
+ Set both `CF_ACCESS_TEAM_DOMAIN` and `CF_ACCESS_AUDIENCE_TAG` in
345
+ `wrangler.jsonc:vars` for prod (they're public identifiers, not
346
+ secrets). Dev `wrangler dev` sees them as `undefined`, the spread
347
+ short-circuits, and `config.auth: "none"` runs. Prod sees them set
348
+ and `cloudflareAccess` engages.
349
+
350
+ <!-- pattern-a:end -->
351
+ <!-- pattern-b:start -->
352
+ **Pattern B — `auth: "shared-secret"`.** Single-tenant
353
+ server-to-server callers (CI, cron, internal services). No factory
354
+ code changes; only `baerly.config.ts` flips:
355
+
356
+ ```ts
357
+ // baerly.config.ts
358
+ auth: "shared-secret", // ← flip from "none"
359
+ ```
360
+
361
+ ```sh
362
+ # Dev:
363
+ echo 'SHARED_SECRET=dev-shared-secret' > .dev.vars
364
+
365
+ # Prod:
366
+ wrangler secret put SHARED_SECRET
367
+ ```
368
+
369
+ The Vite dev plugin needs the bearer injected for browser calls —
370
+ re-enable `baerlyDevAuth` in `vite.config.ts`:
371
+
372
+ ```ts
373
+ import { cloudflare } from "@cloudflare/vite-plugin";
374
+ import { defineConfig } from "vite";
375
+ import { baerlyDevAuth, loadDevVars } from "@gusto/baerly-storage/dev/vite";
376
+
377
+ const { SHARED_SECRET } = loadDevVars(".dev.vars", "SHARED_SECRET");
378
+
379
+ export default defineConfig({
380
+ plugins: [
381
+ cloudflare(),
382
+ ...(SHARED_SECRET !== undefined
383
+ ? [baerlyDevAuth({ secret: SHARED_SECRET })]
384
+ : []),
385
+ ],
386
+ });
387
+ ```
388
+
389
+ `baerly doctor --target=cloudflare` FAILs (`auth.shared-secret-missing`)
390
+ if `auth: "shared-secret"` is set without `SHARED_SECRET` reachable
391
+ from the runtime env.
392
+
393
+ <!-- pattern-b:end -->
394
+ - **Extending the Worker with a custom route** — `baerlyWorker(...)`
395
+ owns `/v1/*` + `/healthz`. For server-side endpoints the SPA
396
+ client can't run on its own (the canonical case: an endpoint that
397
+ needs `db.transaction(...)`, since `createBaerlyClient` is
398
+ reads + by-id mutations only), wrap the worker `fetch`:
399
+
400
+ ```ts
401
+ // src/server/index.ts
402
+ import { baerlyWorker, r2BindingStorage, type BaerlyEnv } from "@gusto/baerly-storage/cloudflare";
403
+ import { Db } from "@gusto/baerly-storage";
404
+ import config from "../../baerly.config.ts";
405
+
406
+ // Hoist the baerly handler so its resolved state is cached for
407
+ // the isolate. With `auth: "none"` in `baerly.config.ts` the
408
+ // adapter pins every `/v1/*` call to `config.tenant` and skips
409
+ // any header check.
410
+ const baerly = baerlyWorker<BaerlyEnv>(() => ({ config }));
411
+
412
+ export default {
413
+ // Keep `req` / `env` / `ctx` inferred — the `satisfies
414
+ // ExportedHandler<BaerlyEnv>` line below narrows them to the
415
+ // same shapes `baerly.fetch!` accepts.
416
+ async fetch(req, env, ctx): Promise<Response> {
417
+ const url = new URL(req.url);
418
+ if (req.method === "POST" && url.pathname.startsWith("/api/")) {
419
+ // Under `auth: "none"` the SPA hits `/api/*` unauthenticated
420
+ // — pin every custom route to `config.tenant` here. When you
421
+ // flip to `auth: "shared-secret"` or pass a custom
422
+ // `verifier:`, replicate that check explicitly (read
423
+ // `Authorization`, verify, derive `tenantPrefix`) — see the
424
+ // "Going to production" recipe.
425
+ const db = Db.create({
426
+ storage: r2BindingStorage(env.BUCKET),
427
+ app: config.app,
428
+ tenant: config.tenant,
429
+ config,
430
+ });
431
+ // …db.transaction(...), db.collection(...).get(id), etc.
432
+ return new Response(null, { status: 204 });
433
+ }
434
+ // Fall through to the baerly cascade for /v1/* + /healthz.
435
+ return baerly.fetch!(req, env, ctx);
436
+ },
437
+ } satisfies ExportedHandler<BaerlyEnv>;
438
+ ```
439
+
440
+ Under `auth: "none"` the dev plugin no longer injects an
441
+ `Authorization` header — `/api/*` and `/v1/*` reach the Worker
442
+ unauthenticated and the adapter pins both to `config.tenant`. When
443
+ you flip to `auth: "shared-secret"` (or a custom verifier) per the
444
+ "Going to production" recipe, your `/api/*` handler must read and
445
+ verify `Authorization` explicitly; `baerlyWorker` only does the
446
+ header check for routes it owns (`/v1/*`).
447
+
448
+ - **Secrets vs. vars** — `wrangler.jsonc:vars` carries non-secret
449
+ config (`APP`, `TENANT`, and CF Access identifiers
450
+ `CF_ACCESS_TEAM_DOMAIN` / `CF_ACCESS_AUDIENCE_TAG` — both are
451
+ public identifiers, not secrets). Secrets like
452
+ `SHARED_SECRET` (only required if you flip `auth` to
453
+ `"shared-secret"`) live in `.dev.vars` for local `wrangler dev`
454
+ and behind `wrangler secret put` in production. `baerly doctor
455
+ --target=cloudflare` reads `CF_ACCESS_*` from `wrangler.jsonc:vars`
456
+ only, so setting them via `wrangler secret put` would silently
457
+ defeat the doctor check.
458
+
459
+ - **Maintenance loop (Cloudflare)** — opt-in. Add
460
+ `"triggers": { "crons": ["* * * * *"] }` to `wrangler.jsonc` and
461
+ wire `scheduled` on the options the factory returns from `baerlyWorker((env) => ({ ... }))`. The
462
+ handler is your code, so you choose what to call
463
+ (`runScheduledMaintenance`, `compact`, `runGc`) and which
464
+ `current.json` keys to target. Multi-tenant deployments iterate
465
+ their own keys; single-tenant deployments call once with a fixed
466
+ key. See the JSDoc on `WorkerScheduledHandler` in
467
+ `@gusto/baerly-storage/cloudflare` and `runScheduledMaintenance` in
468
+ `@gusto/baerly-storage/maintenance` for the wiring + free-vs-paid-tier
469
+ subrequest-budget guidance.
470
+
471
+ Maintenance emits one canonical info line per run on stdout
472
+ (Workers Logs ingestion). Filter your log stream on
473
+ `"unit_of_work": "maintenance"` and read these fields:
474
+
475
+ - `compact_written` — log entries folded into the new snapshot
476
+ this tick (`0` when the live tail was below
477
+ `minEntriesToCompact`). Only set when the tick called
478
+ `runScheduledMaintenance` or `compact` directly; isolated
479
+ `runGc` ticks emit their own `unit_of_work: "gc"` line.
480
+ - `gc_swept` — keys deleted this tick (`0` when no candidates
481
+ aged out). Only set when the tick called
482
+ `runScheduledMaintenance` or `runGc` directly.
483
+ - The kernel also emits the recorder-bag fields alongside:
484
+ `db.compact.entries_folded_p50` / `_p99` / `_count` / `_sum`,
485
+ `db.manifest.lag_window_depth`, `db.orphan.candidate_count`,
486
+ `db.gc.entries_swept_per_second`, `db.gc.swept_total`.
487
+ Useful for dashboards; the four explicit fields above are
488
+ the at-a-glance summary.
489
+
490
+ - **Deploy** — `baerly deploy --target=cloudflare` runs
491
+ `wrangler deploy --x-provision --x-auto-create` (Wrangler 4.10+)
492
+ to auto-create the declared R2 buckets and ship the Worker. When
493
+ the experimental flag is unavailable it falls back to
494
+ `wrangler r2 bucket create` + `wrangler deploy`. The fallback is
495
+ also what `baerly doctor --target=cloudflare --fix` exercises.
496
+
497
+ ## Anti-patterns
498
+
499
+ - Widening branded types from `baerly-storage` (`UUID`,
500
+ `ContentVersionId`). The types prevent confusion bugs.
501
+ - Reaching into `node_modules/@gusto/baerly-storage/dist/` directly —
502
+ consume the published exports.
503
+ - Mutating `VerifierResult.tenantPrefix` between the verifier
504
+ and `Db.create`. The dispatcher pins the tenant from the
505
+ verifier's return value.
506
+ - Calling `db.collection(...).all()` (or any unbounded read) inside a
507
+ per-request handler. The call scans the entire collection on every
508
+ request — fine for a fixture-sized table, catastrophic at any real
509
+ size, and `pnpm verify` doesn't surface the cost. Push the filter
510
+ into the predicate so the index planner can prune
511
+ (`db.collection("notes").where({ ... }).all()`), or maintain a
512
+ side-projection (D1/KV/search index) populated incrementally from
513
+ the `/v1/since` log feed or from a write hook — never re-scan per
514
+ request.
515
+
516
+ ## When to graduate
517
+
518
+ baerly is designed for the small-to-medium operating point. The cost
519
+ model puts the soft ceiling at:
520
+
521
+ - **~30 writes / minute / collection**
522
+ - **~10 GB / tenant**
523
+ - **~100 collections / tenant**
524
+
525
+ Past those, S3 list-prefix latency, manifest fold cost, and per-class
526
+ op pricing start to dominate; you're better off on a real database.
527
+ Pick your graduation target:
528
+ - **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
529
+ - **Off-Workers or portability matters:** managed Postgres.
530
+ - **Single-instance Node:** SQLite via Litestream.
531
+
532
+ Either way, the export below is mechanical because log entries are
533
+ Postgres-logical-replication-shaped — graduation is a Baerly win,
534
+ not a churn event.
535
+
536
+ **Estimate your current rate:** `baerly admin usage --target=...`
537
+ lists recent log entries per collection and computes
538
+ writes/min. Warning at 50% of the ceiling; export suggestion at
539
+ 100%.
540
+
541
+ **Export when ready:** `baerly export --target=sqlite|postgres|d1
542
+ --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
543
+ canonical SQL dump (and a `<output>.plan.json` sidecar carrying the
544
+ inferred `ExportPlan`) that you load into your graduation target.
545
+ The export is point-in-time and honours the active schema. Flags:
546
+ `--where=<json-predicate>`, `--where-comment`, `--output`,
547
+ `--no-sidecar`, `--json`. Exit codes: 0 success, 1 InvalidConfig,
548
+ 2 Storage/Network, 3 Protocol invariant.
549
+
550
+ ## Pointers
551
+
552
+ - `baerly.config.ts` — app config.
553
+ - `src/server/index.ts` — Worker entry.
554
+ - `wrangler.jsonc` — Cloudflare Worker manifest (R2 binding, `assets:`, vars, cron, observability).
555
+ - `vite.config.ts` — Vite + `@cloudflare/vite-plugin`.
556
+ - `package.json` — root scripts + dependencies.