@gusto/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.
Files changed (123) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +108 -44
  4. package/dist/API.md +192 -121
  5. package/dist/CHANGELOG.md +144 -0
  6. package/dist/THIRD-PARTY-LICENSES.txt +312 -0
  7. package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
  8. package/dist/app-config.d.ts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.js +288 -288
  11. package/dist/auth.js.map +1 -1
  12. package/dist/baerly.js +10 -10
  13. package/dist/baerly.js.map +1 -1
  14. package/dist/bytes-BXdamO3L.js.map +1 -1
  15. package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
  16. package/dist/client-react.d.ts +76 -85
  17. package/dist/client-react.js +95 -53
  18. package/dist/client-react.js.map +1 -1
  19. package/dist/client.d.ts +3 -3
  20. package/dist/client.js.map +1 -1
  21. package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
  22. package/dist/cloudflare-Cn2ibODt.js.map +1 -0
  23. package/dist/cloudflare.d.ts +4 -4
  24. package/dist/cloudflare.js +10 -11
  25. package/dist/cloudflare.js.map +1 -1
  26. package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
  27. package/dist/config-CGyBopy3.js.map +1 -0
  28. package/dist/context-DRZ3tZ5l.js.map +1 -1
  29. package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
  30. package/dist/cost-BZ_MDBmn.js.map +1 -0
  31. package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
  32. package/dist/current-json-DsN7FNY1.js.map +1 -0
  33. package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
  34. package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
  35. package/dist/deploy-BKKyGlSJ.js.map +1 -0
  36. package/dist/dev-vite.d.ts +5 -5
  37. package/dist/dev-vite.js +5 -5
  38. package/dist/dev-vite.js.map +1 -1
  39. package/dist/dev.d.ts +1 -1
  40. package/dist/dev.js +1 -1
  41. package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
  42. package/dist/doctor-BVU4GNXN.js.map +1 -0
  43. package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
  44. package/dist/dump-DPEAKub6.js.map +1 -0
  45. package/dist/errors-DOdL95kK.js.map +1 -1
  46. package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
  47. package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
  48. package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
  49. package/dist/fsck-RXgLOaJG.js.map +1 -0
  50. package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
  51. package/dist/http-Bd4byR4n.js.map +1 -0
  52. package/dist/http.d.ts +15 -15
  53. package/dist/http.js +1 -1
  54. package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
  55. package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
  56. package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
  57. package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
  58. package/dist/index.d.ts +6 -6
  59. package/dist/index.js +4 -4
  60. package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
  61. package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
  62. package/dist/inspect-DhI49PSi.js.map +1 -0
  63. package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
  64. package/dist/log-tail-DXeDkWEp.js.map +1 -0
  65. package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
  66. package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
  67. package/dist/maintenance-CWBQpZ2y.js.map +1 -0
  68. package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
  69. package/dist/maintenance-C_KSkVjd.js.map +1 -0
  70. package/dist/maintenance.d.ts +3 -2
  71. package/dist/maintenance.js +3 -2
  72. package/dist/node.d.ts +13 -8
  73. package/dist/node.js +1 -1
  74. package/dist/normalize-XWY25_sG.js.map +1 -1
  75. package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
  76. package/dist/observability-BYd-RzEx.js.map +1 -0
  77. package/dist/observability.d.ts +3 -3
  78. package/dist/observability.js +1 -1
  79. package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
  80. package/dist/plan-DIu_B6fy.js.map +1 -0
  81. package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
  82. package/dist/query-sQNO5vU_.js.map +1 -0
  83. package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
  84. package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
  85. package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
  86. package/dist/restore-DpQYef6r.js.map +1 -0
  87. package/dist/shared-secret-BJdSwpgw.js.map +1 -1
  88. package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
  89. package/dist/src-CWpkSbvJ.js.map +1 -0
  90. package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
  91. package/dist/src-D24wDpzR.js.map +1 -0
  92. package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
  93. package/dist/src-Db4-qVtM.js.map +1 -0
  94. package/dist/subcommand-CP9NY2J4.js +159 -0
  95. package/dist/subcommand-CP9NY2J4.js.map +1 -0
  96. package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
  97. package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
  98. package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
  99. package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
  100. package/package.json +42 -31
  101. package/dist/cloudflare-CINJPKCW.js.map +0 -1
  102. package/dist/config-DVfDGyw1.js +0 -278
  103. package/dist/config-DVfDGyw1.js.map +0 -1
  104. package/dist/cost-CQt1YRkA.js.map +0 -1
  105. package/dist/current-json-C-EyJqs0.js.map +0 -1
  106. package/dist/deploy-CrAbfgCq.js.map +0 -1
  107. package/dist/doctor-Db-hzPmE.js.map +0 -1
  108. package/dist/dump-BYA55NLP.js.map +0 -1
  109. package/dist/fsck-CPPZWt9p.js.map +0 -1
  110. package/dist/http-Cw8p6y5b.js.map +0 -1
  111. package/dist/inspect-Bdbzvi-_.js.map +0 -1
  112. package/dist/maintenance-BvOv6BMM.js.map +0 -1
  113. package/dist/maintenance-ClzBC1Vv.js.map +0 -1
  114. package/dist/observability-CpOiEN0k.js.map +0 -1
  115. package/dist/plan-DOTl21vq.js.map +0 -1
  116. package/dist/query-BmiQy328.js.map +0 -1
  117. package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
  118. package/dist/restore-C6IcmLeA.js.map +0 -1
  119. package/dist/snapshot-SS8USDUF.js.map +0 -1
  120. package/dist/src-DU1sCMlr.js.map +0 -1
  121. package/dist/src-QQ7jDeL2.js.map +0 -1
  122. package/dist/src-zhEAmmF7.js.map +0 -1
  123. package/dist/subcommand-DZcHcsYp.js.map +0 -1
package/dist/API.md CHANGED
@@ -17,18 +17,29 @@ directory remain the source of truth (the bundler chunks them across
17
17
  noisy to read flat — read this first, drop into the `.d.ts` chunks
18
18
  only for exact signatures).
19
19
 
20
+ The public surface is intentionally small and **closed**: the absence
21
+ of a method is a design choice, not an undocumented gap. Every
22
+ unsupported operation is a compile error — the type system enforces the
23
+ vocabulary rather than surfacing a runtime "not implemented", so an agent
24
+ reaches the correct call zero-shot without inventing ceremony the kernel
25
+ doesn't support. The predicate operator set is the concrete example
26
+ (see [Predicates](#predicates)).
27
+
20
28
  ## Imports cheat sheet
21
29
 
22
30
  ```ts
23
31
  // Server kernel
24
32
  import {
25
33
  Db,
26
- MemoryStorage, // in-memory `Storage`; canonical for tests
27
- type Collection, type Query,
34
+ MemoryStorage, // in-memory `Storage`; canonical for tests
35
+ type Collection,
36
+ type Query,
28
37
  type DocumentData,
29
- type RowOf, type CollectionNames, // row-shape inference from a bound config
30
- BaerlyError, type BaerlyErrorCode,
31
- defineConfig, // narrower; root barrel
38
+ type RowOf,
39
+ type CollectionNames, // row-shape inference from a bound config
40
+ BaerlyError,
41
+ type BaerlyErrorCode,
42
+ defineConfig, // narrower; root barrel
32
43
  } from "@gusto/baerly-storage";
33
44
 
34
45
  // Scaffold-aware config (`app`, `tenant`, `target`, `domain`, …)
@@ -43,18 +54,25 @@ import { createRouter, mapError } from "@gusto/baerly-storage/http";
43
54
  // Browser / Node client (HTTP)
44
55
  import {
45
56
  createBaerlyClient,
46
- type BaerlyClient, type ClientCollection, type ClientQuery,
47
- type TerminalOptions, type Fetcher,
57
+ type BaerlyClient,
58
+ type ClientCollection,
59
+ type ClientQuery,
60
+ type TerminalOptions,
61
+ type Fetcher,
48
62
  } from "@gusto/baerly-storage/client";
49
63
 
50
64
  // Auth verifiers
51
- import {
52
- sharedSecret, cloudflareAccess, bearerJwt,
53
- } from "@gusto/baerly-storage/auth";
65
+ import { sharedSecret, cloudflareAccess, bearerJwt } from "@gusto/baerly-storage/auth";
54
66
 
55
67
  // Adapters
56
68
  import { baerlyWorker, r2BindingStorage } from "@gusto/baerly-storage/cloudflare";
57
- import { baerlyNode, s3Storage, r2Storage, minioStorage, gcsStorage } from "@gusto/baerly-storage/node";
69
+ import {
70
+ baerlyNode,
71
+ s3Storage,
72
+ r2Storage,
73
+ minioStorage,
74
+ gcsStorage,
75
+ } from "@gusto/baerly-storage/node";
58
76
 
59
77
  // Dev helpers (Vite, local-fs storage)
60
78
  import { baerlyDevAuth, loadDevVars } from "@gusto/baerly-storage/dev/vite";
@@ -72,11 +90,11 @@ import { Db, MemoryStorage } from "@gusto/baerly-storage";
72
90
  import config from "./baerly.config";
73
91
 
74
92
  const db = Db.create({
75
- storage: new MemoryStorage(), // or `s3Storage(...)`, `r2BindingStorage(env.BUCKET)`, …
93
+ storage: new MemoryStorage(), // or `s3Storage(...)`, `r2BindingStorage(env.BUCKET)`, …
76
94
  app: "tickets",
77
95
  tenant: "acme-co",
78
- config, // ← optional. Wires schemas + indexes
79
- // AND narrows `db.collection(name)` types.
96
+ config, // ← optional. Wires schemas + indexes
97
+ // AND narrows `db.collection(name)` types.
80
98
  });
81
99
 
82
100
  await db.collection("tickets").insert({ title: "first ticket", status: "open" });
@@ -88,7 +106,7 @@ backs an independent in-process bucket — two `Db` instances built
88
106
  against two `new MemoryStorage()`s see two empty, isolated stores.
89
107
  This is what makes it the canonical test fixture: one fresh instance
90
108
  per test gives a hermetic bucket without `beforeEach` cleanup. Pass
91
- the *same* `MemoryStorage` instance to multiple `Db` constructors
109
+ the _same_ `MemoryStorage` instance to multiple `Db` constructors
92
110
  when you want two writers contending on one bucket.
93
111
 
94
112
  Full `Db.create` config:
@@ -112,7 +130,9 @@ import type { Db } from "@gusto/baerly-storage";
112
130
  import type config from "./baerly.config";
113
131
 
114
132
  let cached: Db<typeof config> | undefined;
115
- export function setDbForTesting(db: Db<typeof config>) { cached = db; }
133
+ export function setDbForTesting(db: Db<typeof config>) {
134
+ cached = db;
135
+ }
116
136
  ```
117
137
 
118
138
  The narrowed `Db<typeof config>` carries the same `collection(name)`
@@ -135,7 +155,7 @@ interface Collection<T extends DocumentData = DocumentData> {
135
155
  count(): Promise<number>;
136
156
  get(id: string): Promise<T | undefined>;
137
157
  // Modifiers — return Query<T>.
138
- where(predicate: PredicateArg<T>): Query<T>; // PredicateArg = Predicate<T> | (q => PredicateBuilder<T>)
158
+ where(predicate: PredicateArg<T>): Query<T>; // PredicateArg = Predicate<T> | (q => PredicateBuilder<T>)
139
159
  order(spec: OrderSpec<T>): Query<T>;
140
160
  limit(n: number): Query<T>;
141
161
  // Writes — by primary key.
@@ -189,11 +209,15 @@ paths (`author._id`) on referenced documents are still allowed.
189
209
  ```ts
190
210
  db.collection("tickets").where({ status: "open" }).all();
191
211
  db.collection("tickets").where({ "assignee.team": "platform" }).all();
192
- db.collection("tickets").where(q => q.gte("count", 1).lt("count", 10)).all();
193
- db.collection("tickets").where(q => q.in("status", ["open", "pending"])).all();
212
+ db.collection("tickets")
213
+ .where((q) => q.gte("count", 1).lt("count", 10))
214
+ .all();
215
+ db.collection("tickets")
216
+ .where((q) => q.in("status", ["open", "pending"]))
217
+ .all();
194
218
  db.collection("tickets")
195
219
  .where({ status: "open" })
196
- .where(q => q.gte("priority", 5))
220
+ .where((q) => q.gte("priority", 5))
197
221
  .all();
198
222
  ```
199
223
 
@@ -204,10 +228,12 @@ db.collection("tickets")
204
228
  ```ts
205
229
  interface PredicateClause {
206
230
  readonly op: "eq" | "gt" | "gte" | "lt" | "lte" | "in";
207
- readonly field: string; // top-level or dotted path
208
- readonly value: DocumentValue | ReadonlyArray<DocumentValue>; // array iff op === "in"
231
+ readonly field: string; // top-level or dotted path
232
+ readonly value: DocumentValue | ReadonlyArray<DocumentValue>; // array iff op === "in"
233
+ }
234
+ interface PredicateWire {
235
+ readonly clauses: ReadonlyArray<PredicateClause>;
209
236
  }
210
- interface PredicateWire { readonly clauses: ReadonlyArray<PredicateClause>; }
211
237
  ```
212
238
 
213
239
  Example: `.where({ status: "open" })` → `{"clauses":[{"op":"eq","field":"status","value":"open"}]}`.
@@ -227,7 +253,9 @@ await db.collection("tickets").update("01HQ...", { status: "closed" });
227
253
  // → { modified: 1 } (JSON-merge-patch RFC 7386; `null` deletes a field)
228
254
 
229
255
  await db.collection("tickets").replace("01HQ...", {
230
- _id: "01HQ...", status: "open", title: "rewrite",
256
+ _id: "01HQ...",
257
+ status: "open",
258
+ title: "rewrite",
231
259
  });
232
260
  // → void (whole-document overwrite)
233
261
 
@@ -235,7 +263,8 @@ await db.collection("tickets").delete("01HQ...");
235
263
  // → { deleted: 1 } (or `{ deleted: 0 }` if the id is unknown)
236
264
 
237
265
  // Bulk-by-predicate (Query<T>):
238
- await db.collection("tickets")
266
+ await db
267
+ .collection("tickets")
239
268
  .where({ status: "open" })
240
269
  .update({ status: "closed", closed_at: new Date().toISOString() });
241
270
  // → { modified: N }
@@ -280,7 +309,10 @@ Two ways to get a typed row:
280
309
  the construction site for a narrower row shape:
281
310
  ```ts
282
311
  import type { Collection, DocumentData } from "@gusto/baerly-storage";
283
- interface Bookmark extends DocumentData { _id: string; url: string }
312
+ interface Bookmark extends DocumentData {
313
+ _id: string;
314
+ url: string;
315
+ }
284
316
  const bookmarks = db.collection("bookmarks") as Collection<Bookmark>;
285
317
  await bookmarks.all();
286
318
  ```
@@ -303,18 +335,18 @@ try {
303
335
  }
304
336
  ```
305
337
 
306
- | `code` | HTTP | When |
307
- | ------------------------ | ---- | -------------------------------------------------------------------- |
308
- | `InvalidConfig` | 400 | Caller config/input is invalid (bad bucket, malformed predicate, …) |
309
- | `NetworkError` | 502 | Transport (S3 5xx, retries exhausted) |
310
- | `AccessDenied` | 403 | S3 403 or bucket policy denied |
311
- | `InvalidResponse` | 502 | Server returned unparseable body |
312
- | `Internal` | 500 | Invariant violation — file a bug |
313
- | `SchemaError` | 422 | JSON shape invalid or bound schema rejected the doc |
314
- | `Conflict` | 409 | CAS retry budget exhausted, or `insert` `_id` collision |
315
- | `Unauthorized` | 401 | Verifier returned no identity |
316
- | `NotFound` | 404 | Row by id not found |
317
- | `PayloadTooLarge` | 413 | Body > 1 MiB cap |
338
+ | `code` | HTTP | When |
339
+ | ------------------------ | ---- | ---------------------------------------------------------------------- |
340
+ | `InvalidConfig` | 400 | Caller config/input is invalid (bad bucket, malformed predicate, …) |
341
+ | `NetworkError` | 502 | Transport (S3 5xx, retries exhausted) |
342
+ | `AccessDenied` | 403 | S3 403 or bucket policy denied |
343
+ | `InvalidResponse` | 502 | Server returned unparseable body |
344
+ | `Internal` | 500 | Invariant violation — file a bug |
345
+ | `SchemaError` | 400 | JSON shape invalid or bound schema rejected the doc |
346
+ | `Conflict` | 409 | CAS retry budget exhausted, or `insert` `_id` collision |
347
+ | `Unauthorized` | 401 | Verifier returned no identity |
348
+ | `NotFound` | 404 | Row by id not found |
349
+ | `PayloadTooLarge` | 413 | Body > 1 MiB cap |
318
350
  | `UnsatisfiablePredicate` | 400 | Predicate is well-formed but contradicts itself (empty `in` set, etc.) |
319
351
 
320
352
  ### Mapping errors to HTTP yourself
@@ -361,7 +393,7 @@ import { defineConfig } from "@gusto/baerly-storage/config";
361
393
  import { z } from "zod";
362
394
 
363
395
  const TicketSchema = z.object({
364
- _id: z.string(), // required — see callout below
396
+ _id: z.string(), // required — see callout below
365
397
  status: z.enum(["open", "closed"]),
366
398
  title: z.string().min(1),
367
399
  tags: z.array(z.string()).optional(),
@@ -373,8 +405,8 @@ export default defineConfig({
373
405
  target: "cloudflare",
374
406
  collections: {
375
407
  tickets: {
376
- schema: TicketSchema, // StandardSchema v1
377
- indexes: [{ name: "by_status", on: "status" }], // single-field equality
408
+ schema: TicketSchema, // StandardSchema v1
409
+ indexes: [{ name: "by_status", on: "status" }], // single-field equality
378
410
  },
379
411
  },
380
412
  });
@@ -384,7 +416,7 @@ Schemas: any [StandardSchema v1](https://standardschema.dev) validator
384
416
  (Zod 3.24+, Valibot 0.36+, ArkType 2.0+). Validation runs on the
385
417
  post-image: `update` and `replace` see the full doc, not just the
386
418
  patch. Failures → `BaerlyError{code:"SchemaError", issues:[…]}`,
387
- mapped to HTTP 422.
419
+ mapped to HTTP 400.
388
420
 
389
421
  **Author `_id` as required, not `.optional()`.** The validator runs
390
422
  on the post-image — by the time it fires, the server has already
@@ -396,7 +428,13 @@ still accepts a doc without `_id` (the public signature is
396
428
  required does not break the "omit and let the server mint it" path.
397
429
  The win is on the read side: `db.collection("tickets").all()` is
398
430
  typed `Ticket[]` with `_id: string` (required), so route handlers
399
- and response schemas don't need a parallel "_id-required" row type.
431
+ and response schemas don't need a parallel "\_id-required" row type.
432
+
433
+ `_id` is server-minted (UUIDv7, sorts by mint time) — there is no
434
+ exported id generator, and minting one client-side is unsupported.
435
+ For a write that must reference its own id, write the parent first and
436
+ read back the `_id` the server returns; design cross-collection writes
437
+ parent-first with cleanup, not by pre-minting ids.
400
438
 
401
439
  Indexes: declared here, threaded into `Db.create` automatically. The
402
440
  read-path auto-planner picks an index when the predicate matches;
@@ -406,11 +444,11 @@ preserved).
406
444
  ## `createBaerlyClient` (browser / Node HTTP client)
407
445
 
408
446
  ```ts
409
- import type config from "./baerly.config"; // type-only — server adapter stays out of the SPA bundle
447
+ import type config from "./baerly.config"; // type-only — server adapter stays out of the SPA bundle
410
448
  const client = createBaerlyClient<typeof config>({
411
- baseUrl: "", // same-origin
412
- headers: { Authorization: "Bearer …" }, // wrap `fetch` for per-call refresh
413
- fetch: customFetcher, // optional Fetcher middleware
449
+ baseUrl: "", // same-origin
450
+ headers: { Authorization: "Bearer …" }, // wrap `fetch` for per-call refresh
451
+ fetch: customFetcher, // optional Fetcher middleware
414
452
  });
415
453
 
416
454
  await client.collection("tickets").where({ status: "open" }).all();
@@ -421,7 +459,7 @@ trailing `TerminalOptions`:
421
459
 
422
460
  ```ts
423
461
  interface TerminalOptions {
424
- signal?: AbortSignal; // cancels this specific request
462
+ signal?: AbortSignal; // cancels this specific request
425
463
  }
426
464
 
427
465
  await client.collection("tickets").all({ signal: ac.signal });
@@ -447,12 +485,12 @@ interface SinceResponse {
447
485
  }
448
486
 
449
487
  interface LogEntry {
450
- readonly lsn: string; // opaque cursor; lex-asc, monotonic
451
- readonly commit_ts: string; // ISO-8601 ms
488
+ readonly lsn: string; // opaque cursor; lex-asc, monotonic
489
+ readonly commit_ts: string; // ISO-8601 ms
452
490
  readonly op: "I" | "U" | "D";
453
491
  readonly collection: string;
454
- readonly doc_id: string; // I/U/D only
455
- readonly after?: DocumentData; // I/U — post-image (Debezium's `after`)
492
+ readonly doc_id: string; // I/U/D only
493
+ readonly after?: DocumentData; // I/U — post-image (Debezium's `after`)
456
494
  readonly session: string;
457
495
  readonly seq: number;
458
496
  // `before` / `key_old` / `origin` are optional; see `LogEntry` JSDoc.
@@ -460,7 +498,7 @@ interface LogEntry {
460
498
  ```
461
499
 
462
500
  **Cursor priming.** First call: pass `cursor=` (empty string). The
463
- server's fast path returns immediately *iff* the log already has
501
+ server's fast path returns immediately _iff_ the log already has
464
502
  entries for this collection — you get `events: [...]` and the
465
503
  last entry's `lsn` as `next_cursor`. **If the collection is empty,
466
504
  the first call blocks for the full long-poll budget (~25 s) before
@@ -492,42 +530,58 @@ shrink `sinceTimeoutMs` in production code paths — it multiplies the
492
530
  R2 class-A op count per idle long-poll connection.
493
531
 
494
532
  React applications use `@gusto/baerly-storage/client/react` (see next
495
- section) instead of poking `/v1/since` by hand; hand-rolled
496
- subscribers in other UI frameworks can `fetch` this endpoint
497
- directly, or import the internal `pollSinceOnce` helper from
498
- `@baerly/client` if cursor-aware tailing is needed.
533
+ section) instead of poking `/v1/since` by hand. Hand-rolled
534
+ subscribers in other UI frameworks `fetch` this endpoint directly:
535
+ loop, `fetch`-ing with `cursor=` (empty) first, then threading the
536
+ returned `next_cursor` back as `cursor` on each subsequent call (the
537
+ cursor is opaque — treat it as a string). The wire shape above is the
538
+ public contract; there is no exported cursor-tailing helper.
539
+
540
+ ## React: `createBaerlyReact`
541
+
542
+ `@gusto/baerly-storage/client/react` exports one factory,
543
+ `createBaerlyReact<typeof config>()`. Call it once and export the
544
+ result; it returns `{ BaerlyProvider, useQuery, useMutation,
545
+ useBaerlyClient }` all bound to your config, so a `useQuery` /
546
+ `useMutation` callback's `c.collection("notes")` infers the real row
547
+ type — **no `as Promise<Note[]>` cast**. (React context can't carry a
548
+ generic to the hooks; binding once at the factory is what threads it.)
549
+ The provider owns a shared `/v1/since` long-poll per `(client,
550
+ collection)`; idle cycles cost zero list reads, and any non-empty batch
551
+ invalidates every `useQuery` whose chain touches the firing collection.
499
552
 
500
- ## React: `BaerlyProvider`, `useQuery`, `useMutation`
553
+ ```ts
554
+ // src/web/client.ts — wire the client + bound hooks once.
555
+ import { createBaerlyClient } from "@gusto/baerly-storage/client";
556
+ import { createBaerlyReact } from "@gusto/baerly-storage/client/react";
557
+ import config from "../../baerly.config.ts";
501
558
 
502
- `@gusto/baerly-storage/client/react` exposes three symbols. The provider
503
- owns a shared `/v1/since` long-poll per `(client, collection)`; idle
504
- cycles cost zero list reads, and any non-empty batch invalidates
505
- every `useQuery` whose chain touches the firing collection.
559
+ export const client = createBaerlyClient({ baseUrl: "", config });
560
+ export const { BaerlyProvider, useQuery, useMutation } = createBaerlyReact<typeof config>();
561
+ ```
506
562
 
507
563
  ```tsx
508
- import {
509
- BaerlyProvider, useQuery, useMutation,
510
- } from "@gusto/baerly-storage/client/react";
564
+ // Components import the bound hooks from your module, not the package.
565
+ import { BaerlyProvider, client, useMutation, useQuery } from "./client.ts";
511
566
 
512
567
  // 1. Wrap your app once.
513
- <BaerlyProvider client={createBaerlyClient({ baseUrl: "", config })}>
568
+ <BaerlyProvider client={client}>
514
569
  <App />
515
- </BaerlyProvider>
570
+ </BaerlyProvider>;
516
571
 
517
- // 2. useQuery(cb, deps) — cb receives the bare client and returns
518
- // a ClientCollection / ClientQuery chain. Re-runs on deps change OR
519
- // on long-poll invalidation. Result is a discriminated union:
520
- const result = useQuery((c) => c.collection("notes").all() as Promise<Note[]>, []);
572
+ // 2. useQuery(cb, deps) — the callback receives the bound client and
573
+ // returns a ClientCollection / ClientQuery chain. Re-runs on deps
574
+ // change OR on long-poll invalidation. Result is a discriminated
575
+ // union; the row type is inferred from the collection name:
576
+ const result = useQuery((c) => c.collection("notes").all(), []);
521
577
  // result.status: "loading" | "ok" | "error" | "skipped"
522
- // result.data: T[] | undefined (present iff status === "ok")
578
+ // result.data: Note[] | undefined (present iff status === "ok")
523
579
  // result.error: BaerlyError | undefined (present iff status === "error")
524
580
 
525
581
  // 3. useQuery.skip — short-circuit to status: "skipped", no
526
582
  // subscription. Use for conditional or dependent reads.
527
583
  const filtered = useQuery(
528
- (c) => filter === "all"
529
- ? useQuery.skip
530
- : c.collection("notes").where({ status: filter }).all() as Promise<Note[]>,
584
+ (c) => (filter === "all" ? useQuery.skip : c.collection("notes").where({ status: filter }).all()),
531
585
  [filter],
532
586
  );
533
587
 
@@ -538,17 +592,23 @@ const [mutate, { isPending, error }] = useMutation();
538
592
  await mutate((c) => c.collection("notes").insert({ body }));
539
593
  ```
540
594
 
595
+ > No type parameter (`createBaerlyReact()`) gives an unbound surface —
596
+ > collection names widen to `string`, rows to `DocumentData` — matching
597
+ > the in-process `Db.collection` fallback. There are no loose hooks to
598
+ > import directly: an unbound hook can't see the config, so binding at
599
+ > the factory is the only path.
600
+
541
601
  ## HTTP wire format
542
602
 
543
603
  The JS SDK is the canonical path. Reach for `curl` only when
544
604
  debugging. Mutation bodies are wrapped:
545
605
 
546
- | Route | Body | Response |
547
- | -------------------------------- | ------------------- | ------------------------------ |
548
- | `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
549
- | `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
550
- | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
551
- | `DELETE /v1/c/:collection/:id` | — | `204` |
606
+ | Route | Body | Response |
607
+ | ------------------------------ | ----------------- | ---------------- |
608
+ | `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
609
+ | `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
610
+ | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
611
+ | `DELETE /v1/c/:collection/:id` | — | `204` |
552
612
 
553
613
  Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
554
614
  `GET /v1/since?collection=…&cursor=…`) take no body and return
@@ -572,11 +632,11 @@ routes in front of `baerlyNode`" below).
572
632
  `GET /v1/c/:collection` accepts three JSON-encoded query params; all are
573
633
  optional and compose:
574
634
 
575
- | Param | Encodes | Wire example |
576
- | ---------- | -------------------------------------- | -------------------------------------------- |
577
- | `?where=` | `PredicateWire` (see "Wire format" above) | `?where=%7B%22clauses%22%3A%5B%5D%7D` |
578
- | `?order=` | `{ [field]: "asc" \| "desc" }` | `?order=%7B%22sent_at%22%3A%22desc%22%7D` |
579
- | `?limit=` | bare integer (no JSON wrapper) | `?limit=50` |
635
+ | Param | Encodes | Wire example |
636
+ | --------- | ----------------------------------------- | ----------------------------------------- |
637
+ | `?where=` | `PredicateWire` (see "Wire format" above) | `?where=%7B%22clauses%22%3A%5B%5D%7D` |
638
+ | `?order=` | `{ [field]: "asc" \| "desc" }` | `?order=%7B%22sent_at%22%3A%22desc%22%7D` |
639
+ | `?limit=` | bare integer (no JSON wrapper) | `?limit=50` |
580
640
 
581
641
  `?order=` and `?where=` are JSON, **not** Rails-style `field:asc` —
582
642
  the kernel `JSON.parse`s them and returns `400 SchemaError` on a flat
@@ -635,7 +695,9 @@ export default defineConfig({
635
695
  tenant: "main",
636
696
  target: "cloudflare",
637
697
  auth: "none", // dev only — production swaps to "shared-secret" or a custom Verifier
638
- collections: { /* … */ },
698
+ collections: {
699
+ /* … */
700
+ },
639
701
  });
640
702
 
641
703
  // src/server/index.ts
@@ -644,7 +706,6 @@ import config from "../../baerly.config.ts";
644
706
  export default baerlyWorker(() => ({ config }));
645
707
  ```
646
708
 
647
-
648
709
  `s3Storage` / `r2Storage` / `minioStorage` / `gcsStorage` from
649
710
  `@gusto/baerly-storage/node` are re-exports of one factory family — same
650
711
  shape (bucket + credentials), all hide `aws4fetch` / `@xmldom/xmldom`
@@ -663,11 +724,11 @@ returns `VerifierResult | null` (null = 401 unauth; thrown
663
724
  `BaerlyError` = 500 operator fault — the dispatcher splits the
664
725
  codes deliberately so on-call paging targets operator faults only).
665
726
 
666
- | Preset | Identity source | Tenant derivation |
667
- | ------------------ | ------------------------------------------------------------------------------- | -------------------------------------------------- |
668
- | `sharedSecret` | `Authorization: Bearer <secret>` with constant-time compare | `tenantPrefix:` option (single-tenant only) |
669
- | `bearerJwt` | JWT over JWKS, `iss` + `aud` + `alg` allowlist | Configurable `tenantClaim` (default `"tenant"`) or fixed `tenantPrefix:` override |
670
- | `cloudflareAccess` | `Cf-Access-Jwt-Assertion` header (thin shim over `bearerJwt`) | Same as `bearerJwt` |
727
+ | Preset | Identity source | Tenant derivation |
728
+ | ------------------ | ------------------------------------------------------------- | --------------------------------------------------------------------------------- |
729
+ | `sharedSecret` | `Authorization: Bearer <secret>` with constant-time compare | `tenantPrefix:` option (single-tenant only) |
730
+ | `bearerJwt` | JWT over JWKS, `iss` + `aud` + `alg` allowlist | Configurable `tenantClaim` (default `"tenant"`) or fixed `tenantPrefix:` override |
731
+ | `cloudflareAccess` | `Cf-Access-Jwt-Assertion` header (thin shim over `bearerJwt`) | Same as `bearerJwt` |
671
732
 
672
733
  ```ts
673
734
  import { sharedSecret, bearerJwt, cloudflareAccess } from "@gusto/baerly-storage/auth";
@@ -715,20 +776,20 @@ options.
715
776
 
716
777
  ### Field reference
717
778
 
718
- | Field | Meaning |
719
- | ------------------------------------------- | ------------------------------------------------------------------------------------ |
720
- | `request_id` | Correlation key. Set from `X-Request-Id` if provided, else minted fresh. |
721
- | `method` / `path` / `status` | HTTP request line + response code. |
722
- | `cache_status` | `"hit" \| "miss" \| "bypass"` — Cloudflare adapter only. Node adapter omits. |
723
- | `duration_ms` | `performance.now()` delta, monotonic wall-clock. |
724
- | `outcome` | `"read"` (GET <400), `"committed"` (non-GET <400), `"conflict"` (409), or `"error"`. |
725
- | `db.storage.class_a_ops_total` | PUT + DELETE + LIST count. S3-pricing Class A — cost-dominant. |
726
- | `db.storage.class_b_ops_total` | GET count. S3-pricing Class B. |
727
- | `db.storage.<op>.calls_total` | Per-op breakdown for `get` / `put` / `delete` / `list`. |
728
- | `db.storage.<op>.duration_ms_sum` / `_count`| Per-call duration histogram. |
729
- | `db.write.class_a_ops_per_logical_write_*` | Writer's per-`commit()` Class-A-op count. |
730
- | `db.r2.put.412_total` / `429_total` | CAS conflicts (412) and storage rate-limit hits (429). |
731
- | `error.code` / `error.message` / `error.stack` | Failure-path only. `error.code` is `BaerlyErrorCode`. |
779
+ | Field | Meaning |
780
+ | ---------------------------------------------- | ------------------------------------------------------------------------------------ |
781
+ | `request_id` | Correlation key. Set from `X-Request-Id` if provided, else minted fresh. |
782
+ | `method` / `path` / `status` | HTTP request line + response code. |
783
+ | `cache_status` | `"hit" \| "miss" \| "bypass"` — Cloudflare adapter only. Node adapter omits. |
784
+ | `duration_ms` | `performance.now()` delta, monotonic wall-clock. |
785
+ | `outcome` | `"read"` (GET <400), `"committed"` (non-GET <400), `"conflict"` (409), or `"error"`. |
786
+ | `db.storage.class_a_ops_total` | PUT + DELETE + LIST count. S3-pricing Class A — cost-dominant. |
787
+ | `db.storage.class_b_ops_total` | GET count. S3-pricing Class B. |
788
+ | `db.storage.<op>.calls_total` | Per-op breakdown for `get` / `put` / `delete` / `list`. |
789
+ | `db.storage.<op>.duration_ms_sum` / `_count` | Per-call duration histogram. |
790
+ | `db.write.class_a_ops_per_logical_write_*` | Writer's per-`commit()` Class-A-op count. |
791
+ | `db.r2.put.412_total` / `429_total` | CAS conflicts (412) and storage rate-limit hits (429). |
792
+ | `error.code` / `error.message` / `error.stack` | Failure-path only. `error.code` is `BaerlyErrorCode`. |
732
793
 
733
794
  Class-A / Class-B totals are the load-bearing fields — the cost
734
795
  model puts a per-request ceiling on Class-A ops and the canonical
@@ -736,12 +797,12 @@ line is how you verify a deployed service stays under it.
736
797
 
737
798
  ### Log levels
738
799
 
739
- | Level | What lands |
740
- | ------- | -------------------------------------------------------------------------------- |
741
- | `error` | `status >= 500` or an exception was thrown. |
742
- | `warn` | Adds 4xx canonical lines and explicit `warn` records. |
743
- | `info` | Default. Adds 2xx canonical lines and lifecycle events. |
744
- | `debug` | Adds per-storage-op events. **High volume**; off in production. |
800
+ | Level | What lands |
801
+ | ------- | --------------------------------------------------------------- |
802
+ | `error` | `status >= 500` or an exception was thrown. |
803
+ | `warn` | Adds 4xx canonical lines and explicit `warn` records. |
804
+ | `info` | Default. Adds 2xx canonical lines and lifecycle events. |
805
+ | `debug` | Adds per-storage-op events. **High volume**; off in production. |
745
806
 
746
807
  Set `LOG_LEVEL` env var or the typed `observability.level` factory
747
808
  option. Sink wiring (Workers Analytics Engine, OTel, Datadog) lives
@@ -856,15 +917,13 @@ const inner = baerlyNode({
856
917
  serve({
857
918
  port: Number(process.env["PORT"] ?? 8080),
858
919
  fetch: (req) =>
859
- new URL(req.url).pathname === "/health-check"
860
- ? Response.json({ ok: true })
861
- : inner.fetch(req),
920
+ new URL(req.url).pathname === "/health-check" ? Response.json({ ok: true }) : inner.fetch(req),
862
921
  });
863
922
  ```
864
923
 
865
924
  The handle's `fetch` is the documented embedding seam (it's also what
866
925
  the Vite dev middleware and tests consume) — there's no separate
867
- `createApp` to reach for. If you don't need a *custom* probe path,
926
+ `createApp` to reach for. If you don't need a _custom_ probe path,
868
927
  skip all of this and point your platform at the built-in
869
928
  `GET /v1/healthz` (see above).
870
929
 
@@ -895,7 +954,12 @@ the network. Three recipes cover the common cases.
895
954
  ```ts
896
955
  import { createBaerlyClient, type Fetcher } from "@gusto/baerly-storage/client";
897
956
 
898
- const withHooks = (next: Fetcher, onSuccess: (req: Request, res: Response) => void, onError: (req: Request, err: unknown) => void): Fetcher =>
957
+ const withHooks =
958
+ (
959
+ next: Fetcher,
960
+ onSuccess: (req: Request, res: Response) => void,
961
+ onError: (req: Request, err: unknown) => void,
962
+ ): Fetcher =>
899
963
  async (req) => {
900
964
  try {
901
965
  const res = await next(req);
@@ -909,7 +973,8 @@ const withHooks = (next: Fetcher, onSuccess: (req: Request, res: Response) => vo
909
973
 
910
974
  const client = createBaerlyClient({
911
975
  baseUrl: "https://api.example.com",
912
- fetch: withHooks(globalThis.fetch,
976
+ fetch: withHooks(
977
+ globalThis.fetch,
913
978
  (req, res) => log.info({ url: req.url, status: res.status }),
914
979
  (req, err) => log.error({ url: req.url, err }),
915
980
  ),
@@ -923,7 +988,8 @@ const client = createBaerlyClient({
923
988
  ### Retry on transient failures (GET only)
924
989
 
925
990
  ```ts
926
- const withRetry = (next: Fetcher, max = 3, baseMs = 100): Fetcher =>
991
+ const withRetry =
992
+ (next: Fetcher, max = 3, baseMs = 100): Fetcher =>
927
993
  async (req) => {
928
994
  for (let i = 0; i < max - 1; i++) {
929
995
  const res = await next(req.clone());
@@ -944,7 +1010,8 @@ one-shot stream.
944
1010
  ### Refresh credentials on 401
945
1011
 
946
1012
  ```ts
947
- const withAuthRefresh = (next: Fetcher, refresh: () => Promise<string>): Fetcher =>
1013
+ const withAuthRefresh =
1014
+ (next: Fetcher, refresh: () => Promise<string>): Fetcher =>
948
1015
  async (req) => {
949
1016
  const res = await next(req.clone());
950
1017
  if (res.status !== 401) return res;
@@ -993,6 +1060,10 @@ once. Pick by what you want to observe.
993
1060
 
994
1061
  ## Where to look next
995
1062
 
1063
+ - **A call you expected doesn't type-check?** The public surface is
1064
+ additive-only locked (ADR-002), but the rare breaking change carries an
1065
+ old→new migration in `dist/CHANGELOG.md` (`cat dist/CHANGELOG.md`). The
1066
+ `.d.ts` types are canonical; the changelog is the recovery path.
996
1067
  - Per-symbol JSDoc: read the `.d.ts` chunks in this directory
997
1068
  (`db-*.d.ts`, `index-*.d.ts`, `client-*.d.ts`, …) — the bundler
998
1069
  splits them; `cat dist/*.d.ts` gives the union.