@gusto/baerly-storage 0.6.0 → 0.7.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 (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +9 -14
  53. package/dist/dev-vite.js +11 -10
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
package/dist/API.md CHANGED
@@ -7,23 +7,9 @@ tags: [agent-quickref, baerly]
7
7
 
8
8
  # baerly-storage — public API quickref
9
9
 
10
- This file ships in `dist/API.md` so a freshly-installed
11
- `node_modules/@gusto/baerly-storage/dist/API.md` is one `cat` away from the
12
- full public surface. (It is named `API.md` rather than `AGENTS.md` to
13
- avoid colliding with the scaffolded user app's own `AGENTS.md` at the
14
- project root.) It is hand-curated; the `.d.ts` files in this same
15
- directory remain the source of truth (the bundler chunks them across
16
- `index-*.d.ts` / `client-*.d.ts` / `db-*.d.ts` / etc., so they're
17
- noisy to read flat — read this first, drop into the `.d.ts` chunks
18
- only for exact signatures).
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)).
10
+ This file ships in `dist/API.md` so a freshly-installed `node_modules/@gusto/baerly-storage/dist/API.md` is one `cat` away from the full public surface. (It is named `API.md` rather than `AGENTS.md` to avoid colliding with the scaffolded user app's own `AGENTS.md` at the project root.) It is hand-curated; the `.d.ts` files in this same directory remain the source of truth (the bundler chunks them across `index-*.d.ts` / `client-*.d.ts` / `db-*.d.ts` / etc., so they're noisy to read flat — read this first, drop into the `.d.ts` chunks only for exact signatures).
11
+
12
+ The public surface is intentionally small and **closed**: the absence of a method is a design choice, not an undocumented gap. Every unsupported operation is a compile error — the type system enforces the vocabulary rather than surfacing a runtime "not implemented", so an agent reaches the correct call zero-shot without inventing ceremony the kernel doesn't support. The predicate operator set is the concrete example (see [Predicates](#predicates)).
27
13
 
28
14
  ## Imports cheat sheet
29
15
 
@@ -50,7 +36,7 @@ import { defineConfig, type RowOf } from "@gusto/baerly-storage/config";
50
36
  // so `baerly.config.ts` siblings (e.g. `types.ts`) can import the inferred
51
37
  // row type without reaching into the server barrel.
52
38
 
53
- // HTTP helpers — for embed-by-hand routers that don't mount `createRouter`
39
+ // HTTP router + error mapping — custom adapters and embed-by-hand routes
54
40
  import { createRouter, mapError } from "@gusto/baerly-storage/http";
55
41
 
56
42
  // Browser / Node client (HTTP)
@@ -85,11 +71,9 @@ import { LocalFsStorage } from "@gusto/baerly-storage/dev";
85
71
 
86
72
  ## `Db.create({ storage, app, tenant, config? })`
87
73
 
88
- *When NOT to use: in a browser/SPA — use `createBaerlyClient` (HTTP) instead; `Db` is the in-process server surface.*
74
+ _When NOT to use: in a browser/SPA — use `createBaerlyClient` (HTTP) instead; `Db` is the in-process server surface._
89
75
 
90
- One `Db` per `(app, tenant)` request. The constructor is private —
91
- always go through `Db.create`. Collections are auto-provisioned on first
92
- write (no `ensureCollection` step).
76
+ One `Db` per `(app, tenant)` request. The constructor is private — always go through `Db.create`. Collections are auto-provisioned on first write (no `ensureCollection` step).
93
77
 
94
78
  ```ts
95
79
  import { Db, MemoryStorage } from "@gusto/baerly-storage";
@@ -99,7 +83,7 @@ const db = Db.create({
99
83
  storage: new MemoryStorage(), // or `s3Storage(...)`, `r2BindingStorage(env.BUCKET)`, …
100
84
  app: "tickets",
101
85
  tenant: "acme-co",
102
- config, // ← optional. Wires schemas + indexes
86
+ config, // ← optional. Wires schemas
103
87
  // AND narrows `db.collection(name)` types.
104
88
  });
105
89
 
@@ -107,13 +91,7 @@ await db.collection("tickets").insert({ title: "first ticket", status: "open" })
107
91
  const open = await db.collection("tickets").where({ status: "open" }).all();
108
92
  ```
109
93
 
110
- **`MemoryStorage` is per-instance.** Each `new MemoryStorage()`
111
- backs an independent in-process bucket — two `Db` instances built
112
- against two `new MemoryStorage()`s see two empty, isolated stores.
113
- This is what makes it the canonical test fixture: one fresh instance
114
- per test gives a hermetic bucket without `beforeEach` cleanup. Pass
115
- the _same_ `MemoryStorage` instance to multiple `Db` constructors
116
- when you want two writers contending on one bucket.
94
+ **`MemoryStorage` is per-instance.** Each `new MemoryStorage()` backs an independent in-process bucket — two `Db` instances built against two `new MemoryStorage()`s see two empty, isolated stores. This is what makes it the canonical test fixture: one fresh instance per test gives a hermetic bucket without `beforeEach` cleanup. Pass the _same_ `MemoryStorage` instance to multiple `Db` constructors when you want two writers contending on one bucket.
117
95
 
118
96
  Full `Db.create` config:
119
97
 
@@ -126,10 +104,7 @@ Db.create<TConfig>({
126
104
  });
127
105
  ```
128
106
 
129
- **`Db<typeof config>` is a usable type.** `Db.create({ ..., config })`
130
- returns `Db<typeof config>`, and that type is exported from the root
131
- barrel — so a test or DI helper can pin it without inferring through
132
- the factory call site:
107
+ **`Db<typeof config>` is a usable type.** `Db.create({ ..., config })` returns `Db<typeof config>`, and that type is exported from the root barrel — so a test or DI helper can pin it without inferring through the factory call site:
133
108
 
134
109
  ```ts
135
110
  import type { Db } from "@gusto/baerly-storage";
@@ -141,79 +116,58 @@ export function setDbForTesting(db: Db<typeof config>) {
141
116
  }
142
117
  ```
143
118
 
144
- The narrowed `Db<typeof config>` carries the same `collection(name)`
145
- overloads as the inferred return; `Db` (no parameter) widens to
146
- `Db<UnboundConfig>` and accepts any string collection name.
119
+ The narrowed `Db<typeof config>` carries the same `collection(name)` overloads as the inferred return; `Db` (no parameter) widens to `Db<UnboundConfig>` and accepts any string collection name.
147
120
 
148
121
  ## `db.collection(name)` → `Collection<T>`
149
122
 
150
- *When NOT to use: from the browser — call collection verbs over HTTP via `createBaerlyClient`.*
123
+ _When NOT to use: from the browser — call collection verbs over HTTP via `createBaerlyClient`._
151
124
 
152
- `Collection<T>` carries the common-case verbs directly (collection-level
153
- reads plus by-primary-key mutations). Modifiers (`where`, `order`,
154
- `limit`) return a `Query<T>` for bulk-by-predicate work. Terminals fire
155
- I/O on the spot.
125
+ `Collection<T>` carries the common-case verbs directly (collection-level reads plus by-primary-key mutations). Modifiers (`where`, `order`, `limit`) return a `Query<T>` for bulk-by-predicate work. Terminals fire I/O on the spot.
156
126
 
157
127
  ```ts
158
128
  interface Collection<T extends DocumentData = DocumentData> {
159
129
  readonly name: string;
160
- // Reads — whole collection / by id.
161
- first(): Promise<T | undefined>;
162
- all(): Promise<T[]>;
130
+ // Reads — whole collection / by id. Every row carries a string `_id`.
131
+ first(): Promise<(T & { _id: string }) | undefined>;
132
+ all(): Promise<(T & { _id: string })[]>;
163
133
  count(): Promise<number>;
164
- get(id: string): Promise<T | undefined>;
134
+ get(id: string): Promise<(T & { _id: string }) | undefined>;
165
135
  // Modifiers — return Query<T>.
166
136
  where(predicate: PredicateArg<T>): Query<T>; // PredicateArg = Predicate<T> | (q => PredicateBuilder<T>)
167
137
  order(spec: OrderSpec<T>): Query<T>;
168
138
  limit(n: number): Query<T>;
169
139
  // Writes — by primary key.
170
- insert(doc: Partial<T> & DocumentData): Promise<{ _id: string }>;
171
- update(id: string, patch: Partial<T>): Promise<{ modified: number }>;
140
+ insert(doc: Partial<T> & DocumentData & { _id?: string }): Promise<{ _id: string }>;
141
+ update(id: string, patch: MergePatch<T>): Promise<{ modified: number }>;
172
142
  replace(id: string, doc: T): Promise<void>;
173
143
  delete(id: string): Promise<{ deleted: number }>;
174
144
  }
175
145
  ```
176
146
 
177
- `Query<T>` keeps the chainable read terminals and the predicate-aware
178
- bulk mutation verbs:
147
+ `Query<T>` keeps the chainable read terminals and the predicate-aware bulk mutation verbs:
179
148
 
180
149
  ```ts
181
150
  interface Query<T> extends /* Collection<T>'s modifiers */ {
182
- first(): Promise<T | undefined>;
183
- all(): Promise<T[]>;
151
+ first(): Promise<(T & { _id: string }) | undefined>;
152
+ all(): Promise<(T & { _id: string })[]>;
184
153
  count(): Promise<number>;
185
- update(patch: Partial<T>): Promise<{ modified: number }>; // bulk
154
+ update(patch: MergePatch<T>): Promise<{ modified: number }>; // bulk
186
155
  delete(): Promise<{ deleted: number }>; // bulk
187
156
  }
188
157
  ```
189
158
 
190
- `replace` is by-id only — `Collection<T>.replace(id, doc)` throws
191
- `NotFound` on missing id. There is no predicate-form `.replace(doc)`
192
- on `Query<T>`: a strict-cardinality-1 verb is redundant ceremony to
193
- the by-id form (the public surface is additive-only locked, so a second
194
- type-valid path to one capability is redundancy).
159
+ `replace` is by-id only — `Collection<T>.replace(id, doc)` throws `NotFound` on missing id. There is no predicate-form `.replace(doc)` on `Query<T>`: a strict-cardinality-1 verb is redundant ceremony to the by-id form (the public surface is additive-only locked, so a second type-valid path to one capability is redundancy).
195
160
 
196
161
  ### Predicates
197
162
 
198
163
  Two shapes, both legal on `.where(...)`:
199
164
 
200
- 1. **Object literal** — equality only. Top-level, dotted-path, or
201
- nested literal sub-predicate. Multi-field is implicit AND.
202
- 2. **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`.
203
- The methods on `PredicateBuilder<T>` ARE the supported operator
204
- vocabulary; methods absent from the type (`or`, `not`, `regex`,
205
- `ne`, `exists`) do not exist and won't typecheck.
165
+ 1. **Object literal** — equality only. Top-level, dotted-path, or nested literal sub-predicate. Multi-field is implicit AND.
166
+ 2. **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`. The methods on `PredicateBuilder<T>` ARE the supported operator vocabulary; methods absent from the type (`or`, `not`, `regex`, `ne`, `exists`) do not exist and won't typecheck.
206
167
 
207
- Chained `.where(...).where(...)` AND-merges across calls and across
208
- shapes. Both forms normalise to one wire format (a flat clause list,
209
- `{ clauses: PredicateClause[] }`); the HTTP `?where=` param carries
210
- that wire JSON.
168
+ Chained `.where(...).where(...)` AND-merges across calls and across shapes. Both forms normalise to one wire format (a flat clause list, `{ clauses: PredicateClause[] }`); the HTTP `?where=` param carries that wire JSON.
211
169
 
212
- By-`_id` lookups go through `.get(id)` / `.update(id, patch)` /
213
- `.replace(id, doc)` / `.delete(id)`, **not** `.where({ _id: id })`.
214
- `_id` is excluded from `Path<T>` (and so from `PredicateBuilder<T>`),
215
- so `.where({ _id: ... })` is a compile-time TS error. Nested `_id`
216
- paths (`author._id`) on referenced documents are still allowed.
170
+ By-`_id` lookups go through `.get(id)` / `.update(id, patch)` / `.replace(id, doc)` / `.delete(id)`, **not** `.where({ _id: id })`. `_id` is excluded from `Path<T>` (and so from `PredicateBuilder<T>`), so `.where({ _id: ... })` is a compile-time TS error. Nested `_id` paths (`author._id`) on referenced documents are still allowed.
217
171
 
218
172
  ```ts
219
173
  db.collection("tickets").where({ status: "open" }).all();
@@ -245,13 +199,11 @@ interface PredicateWire {
245
199
  }
246
200
  ```
247
201
 
248
- Example: `.where({ status: "open" })` → `{"clauses":[{"op":"eq","field":"status","value":"open"}]}`.
249
- The empty wire `{"clauses":[]}` matches every document.
202
+ Example: `.where({ status: "open" })` → `{"clauses":[{"op":"eq","field":"status","value":"open"}]}`. The empty wire `{"clauses":[]}` matches every document.
250
203
 
251
204
  ## Mutations
252
205
 
253
- By-id (the common case) lives on `Collection<T>`; predicate-aware bulk
254
- verbs live on `Query<T>` after `.where(...)`.
206
+ By-id (the common case) lives on `Collection<T>`; predicate-aware bulk verbs live on `Query<T>` after `.where(...)`.
255
207
 
256
208
  ```ts
257
209
  await db.collection("tickets").insert({ status: "open", title: "ship it" });
@@ -259,7 +211,9 @@ await db.collection("tickets").insert({ status: "open", title: "ship it" });
259
211
 
260
212
  // By-id (Collection<T>):
261
213
  await db.collection("tickets").update("01HQ...", { status: "closed" });
262
- // → { modified: 1 } (JSON-merge-patch RFC 7386; `null` deletes a field)
214
+ // → { modified: 1 } (JSON-merge-patch RFC 7386)
215
+ await db.collection("tickets").update("01HQ...", { note: null });
216
+ // `null` deletes an optional field; a required one is a TS error, use `replace`
263
217
 
264
218
  await db.collection("tickets").replace("01HQ...", {
265
219
  _id: "01HQ...",
@@ -284,38 +238,26 @@ await db.collection("tickets").where({ status: "closed" }).delete();
284
238
 
285
239
  ## `DocumentData` — row shape constraint
286
240
 
287
- Every row type must satisfy
288
- `{ [k: string]: DocumentValue }` where
289
- `DocumentValue = string | number | boolean | DocumentData | Array<DocumentValue>`.
241
+ Every row type must satisfy `{ [k: string]: DocumentValue }` where `DocumentValue = string | number | boolean | DocumentData | Array<DocumentValue>`.
290
242
 
291
- Note: `null` is intentionally NOT a valid stored value. In a
292
- JSON-merge-patch (RFC 7386) `update`, `null` is the field-deletion
293
- sentinel; allowing it as a stored value would collapse "this field is
294
- null" with "delete this field". Use `.optional()` in your schema for
295
- absent values.
243
+ Note: `null` is not a stored value in the typed contract. In a JSON-merge-patch (RFC 7386) `update`, `null` is the field-deletion sentinel, so a stored `null` would collapse "this field is null" with "delete this field". `MergePatch<T>` admits `null` only on optional keys (a required nested object with a single object type takes a nested patch; an optional one takes its whole value or `null`; union-valued members take whole values; arrays replace whole); remove a required field with `replace`. Use `.optional()` in your schema for absent values. The runtime still stores a `null` that reaches `insert` / `replace` (RECIPES.md, TS2322).
296
244
 
297
245
  Two ways to get a typed row:
298
246
 
299
- 1. **Bind the config** (preferred). Declare collection in
300
- `baerly.config.ts` with a schema; pass `config` to `Db.create` /
301
- `createBaerlyClient`. `db.collection("tickets")` returns
302
- `Collection<RowOf<TConfig, "tickets">>`. No generic, no cast.
247
+ 1. **Bind the config** (preferred). Declare collection in `baerly.config.ts` with a schema; pass `config` to `Db.create` / `createBaerlyClient`. `db.collection("tickets")` returns `Collection<RowOf<TConfig, "tickets">>`. No generic, no cast.
303
248
 
304
- `RowOf<TConfig, "tickets">` is also a usable type when you need
305
- to name the row shape outside the chain — route-handler return
306
- types, response-schema bridges, helpers that take a row by hand:
249
+ `RowOf<TConfig, "tickets">` is also a usable type when you need to name the row shape outside the chain — route-handler return types, response-schema bridges, helpers that take a row by hand:
307
250
 
308
251
  ```ts
309
252
  import type { RowOf } from "@gusto/baerly-storage";
310
253
  import type config from "./baerly.config";
311
254
 
312
255
  type Ticket = RowOf<typeof config, "tickets">;
313
- // ^ same shape as `db.collection("tickets").all()` row.
256
+ // ^ `db.collection("tickets").all()` rows are `Ticket & { _id: string }`.
314
257
  // `CollectionNames<typeof config>` is the union of valid names.
315
258
  ```
316
259
 
317
- 2. **Falls back to `DocumentData`** when no config is bound. Cast at
318
- the construction site for a narrower row shape:
260
+ 2. **Falls back to `DocumentData`** when no config is bound. Rows still carry a string `_id`, so `get` / `update` / `replace` / `delete` take `row._id` as-is (`for (const row of await notes.all()) await notes.delete(row._id)`). Cast at the construction site for a narrower row shape:
319
261
  ```ts
320
262
  import type { Collection, DocumentData } from "@gusto/baerly-storage";
321
263
  interface Bookmark extends DocumentData {
@@ -325,52 +267,49 @@ Two ways to get a typed row:
325
267
  const bookmarks = db.collection("bookmarks") as Collection<Bookmark>;
326
268
  await bookmarks.all();
327
269
  ```
328
- A plain `interface Bookmark { _id: string; url: string }` (no
329
- index signature) fails the `T extends DocumentData` constraint by
330
- design — the constraint keeps the row JSON-compatible.
270
+ A plain `interface Bookmark { _id: string; url: string }` (no index signature) fails the `T extends DocumentData` constraint by design — the constraint keeps the row JSON-compatible.
331
271
 
332
272
  ## Errors
333
273
 
334
- `BaerlyError` is the single error class. Discriminate by `code`, not
335
- `instanceof` (the code string survives realm boundaries):
274
+ `BaerlyError` is the single error class. Discriminate by `code`, not `instanceof` (the code string survives realm boundaries):
336
275
 
337
276
  ```ts
338
277
  try {
339
- await db.collection("tickets").insert({ title: "hi" });
278
+ await db.collection("tickets").insert({ _id: "t-1", title: "hi" });
340
279
  } catch (err) {
341
- if (err instanceof BaerlyError && err.code === "Conflict") {
342
- // Check err.retriable: CAS conflicts can retry; duplicate _id cannot.
343
- }
280
+ if (!(err instanceof BaerlyError)) throw err;
281
+ if (err.code === "AmbiguousCommit") {
282
+ // May have landed: re-read err._id before deciding.
283
+ } else if (!err.retriable) throw err; // AlreadyExists: t-1 is taken
284
+ // else WriteConflict / NetworkError: retry with bounded backoff
344
285
  }
345
286
  ```
346
287
 
347
- | `code` | HTTP | When |
348
- | ------------------------ | ---- | ---------------------------------------------------------------------- |
349
- | `InvalidConfig` | 400 | Caller config/input is invalid (bad bucket, malformed predicate, …) |
350
- | `NetworkError` | 502 | Transport (S3 5xx, retries exhausted) |
351
- | `AccessDenied` | 403 | S3 403 or bucket policy denied |
352
- | `InvalidResponse` | 502 | Server returned unparseable body |
353
- | `Internal` | 500 | Invariant violation — file a bug |
354
- | `SchemaError` | 400 | JSON shape invalid or bound schema rejected the doc |
355
- | `Conflict` | 409 | CAS retry budget exhausted, or `insert` `_id` collision |
356
- | `Unauthorized` | 401 | Verifier returned no identity |
357
- | `NotFound` | 404 | Row by id not found |
358
- | `PayloadTooLarge` | 413 | Body > 1 MiB cap |
359
- | `UnsatisfiablePredicate` | 400 | Predicate is well-formed but contradicts itself (empty `in` set, etc.) |
288
+ | `code` | HTTP | When |
289
+ | ------------------------ | ---- | ------------------------------------------------ |
290
+ | `InvalidConfig` | 400 | Bad input (bucket, predicate, doc > 1 MiB) |
291
+ | `NetworkError` | 502 | Transport (S3 5xx, retries exhausted) |
292
+ | `AccessDenied` | 403 | S3 403 or bucket policy denied |
293
+ | `InvalidResponse` | 502 | Server returned unparseable body |
294
+ | `Internal` | 500 | Invariant violation — file a bug |
295
+ | `SchemaError` | 400 | Bad JSON shape, or bound schema rejected it |
296
+ | `WriteConflict` | 409 | Lost a write race; re-read, then retry |
297
+ | `AlreadyExists` | 409 | `insert` `_id` taken, or `restore` target exists |
298
+ | `AmbiguousCommit` | 409 | Commit may be durable; outcome unresolved |
299
+ | `CapacityExceeded` | 409 | Too much work for one request on this host |
300
+ | `MaintenancePending` | 503 | Maintenance behind; wait `retryAfter` seconds |
301
+ | `CursorExpired` | 410 | `/v1/since` cursor dead; restart with `cursor=` |
302
+ | `Unauthorized` | 401 | Verifier returned no identity |
303
+ | `NotFound` | 404 | Row by id not found |
304
+ | `PayloadTooLarge` | 413 | Body > 1 MiB cap |
305
+ | `UnsupportedMediaType` | 415 | Write body not sent as `application/json` |
306
+ | `UnsatisfiablePredicate` | 400 | Predicate contradicts itself (empty `in`, …) |
307
+
308
+ Only `NetworkError`, `WriteConflict` and `MaintenancePending` are `retriable`. Recovery: [RECIPES.md](RECIPES.md#ambiguouscommit-recovery).
360
309
 
361
310
  ### Mapping errors to HTTP yourself
362
311
 
363
- `baerlyWorker` and `baerlyNode` already translate `BaerlyError` →
364
- HTTP status + wire envelope; the table above is what they implement.
365
- If you mount the kernel's router directly (`createRouter` from
366
- `@gusto/baerly-storage/http`), you get the same translation for free
367
- under `/v1/*`.
368
-
369
- For an **embed-by-hand** router (your own Hono / Express / Fastify
370
- app calling `Db` directly, layering custom routes on top), reach
371
- for `mapError` from the same subpath — it consumes the table above
372
- in one call and returns the envelope and status code, so handlers
373
- don't grow a five-arm `if (err.code === ...)` ladder:
312
+ `baerlyWorker`, `baerlyNode`, and `createRouter` (from `@gusto/baerly-storage/http`) already translate `BaerlyError` → HTTP status + wire envelope per the table above. For an **embed-by-hand** router (your own Hono / Express / Fastify app calling `Db` directly), use `mapError` from the same subpath; it returns the envelope and status (set `Retry-After` from `envelope.error.retryAfter` yourself):
374
313
 
375
314
  ```ts
376
315
  import { mapError } from "@gusto/baerly-storage/http";
@@ -386,22 +325,13 @@ app.post("/notes", async (c) => {
386
325
  });
387
326
  ```
388
327
 
389
- `mapError` accepts any thrown value. Caller-facing errors such as
390
- `SchemaError`, `NotFound`, `PayloadTooLarge`, predicate `InvalidConfig`,
391
- and non-retriable caller `Conflict`s keep their actionable message.
392
- Storage/server diagnostics such as `Internal`, `NetworkError`,
393
- `InvalidResponse`, storage `AccessDenied`, storage `InvalidConfig`, and
394
- retriable CAS/storage `Conflict`s keep their code/status/retriable shape
395
- but use a generic wire message; the full thrown error is logged via the
396
- observability channel. Non-`BaerlyError` throws fall through to
397
- `500 Internal` with the message redacted. The HTTP status / envelope shape
398
- is locked.
328
+ `mapError` accepts any thrown value. Caller-facing codes (`SchemaError`, `NotFound`, `PayloadTooLarge`, `CapacityExceeded`, `AlreadyExists`, predicate `InvalidConfig`) keep their message. Diagnostics (`Internal`, `NetworkError`, `InvalidResponse`, storage `AccessDenied` / `InvalidConfig`, `WriteConflict`) keep code/status/`retriable` with a generic wire message; the full error goes to observability. Other throws become `500 Internal`, message redacted. The status/envelope shape is locked.
329
+
330
+ To serve the whole `/v1/*` API from your own server behind your own auth, gate and mount path, see RECIPES.md, "Recipe — authoring a gated adapter".
399
331
 
400
332
  ## `defineConfig({ app, tenant, target, collections })`
401
333
 
402
- Scaffold-aware: lives at `@gusto/baerly-storage/config`. Holds both deploy
403
- metadata (`app`, `tenant`, `target`, `domain`, `cloudflareAccess`,
404
- `requiredSecrets`, `observability`) AND the runtime schema map.
334
+ Scaffold-aware: lives at `@gusto/baerly-storage/config`. Holds both deploy metadata (`app`, `tenant`, `target`, `domain`, `cloudflareAccess`, `requiredSecrets`, `observability`) AND the runtime schema map.
405
335
 
406
336
  ```ts
407
337
  import { defineConfig } from "@gusto/baerly-storage/config";
@@ -421,46 +351,22 @@ export default defineConfig({
421
351
  collections: {
422
352
  tickets: {
423
353
  schema: TicketSchema, // StandardSchema v1
424
- indexes: [{ name: "by_status", on: "status" }], // single-field equality
425
354
  },
426
355
  },
427
356
  });
428
357
  ```
429
358
 
430
- Schemas: any [StandardSchema v1](https://standardschema.dev) validator
431
- (Zod 3.24+, Valibot 0.36+, ArkType 2.0+). Validation runs on the
432
- post-image: `update` and `replace` see the full doc, not just the
433
- patch. Failures → `BaerlyError{code:"SchemaError", issues:[…]}`,
434
- mapped to HTTP 400. Validation is write-path only — reads, export, and
435
- replay never re-validate, so a schema change never retroactively rejects
436
- existing rows.
437
-
438
- **Author `_id` as required, not `.optional()`.** The validator runs
439
- on the post-image — by the time it fires, the server has already
440
- filled in a UUIDv7 `_id` for inserts that omit it, so every row the
441
- validator sees has `_id` present. Declaring `_id: z.string()`
442
- (required) matches that runtime invariant. `Collection<T>.insert`
443
- still accepts a doc without `_id` (the public signature is
444
- `insert(doc: Partial<T> & DocumentData)`), so authoring `_id` as
445
- required does not break the "omit and let the server mint it" path.
446
- The win is on the read side: `db.collection("tickets").all()` is
447
- typed `Ticket[]` with `_id: string` (required), so route handlers
448
- and response schemas don't need a parallel "\_id-required" row type.
449
-
450
- `_id` is server-minted (UUIDv7, sorts by mint time) — there is no
451
- exported id generator, and minting one client-side is unsupported.
452
- For a write that must reference its own id, write the parent first and
453
- read back the `_id` the server returns; design cross-collection writes
454
- parent-first with cleanup, not by pre-minting ids.
455
-
456
- Indexes: declared here, threaded into `Db.create` automatically. The
457
- read-path auto-planner picks an index when the predicate matches;
458
- mismatches fall back to the full scan with a metric bump (correctness
459
- preserved).
359
+ Schemas: any [StandardSchema v1](https://standardschema.dev) validator (Zod 3.24+, Valibot 0.36+, ArkType 2.0+). Validation runs on the post-image: `update` and `replace` see the full doc, not just the patch. Failures → `BaerlyError{code:"SchemaError", issues:[…]}`, mapped to HTTP 400. Validation is write-path only — reads, export, and replay never re-validate, so a schema change never retroactively rejects existing rows.
360
+
361
+ **Author `_id` as required, not `.optional()`.** The validator runs on the post-image — by the time it fires, the server has already filled in a UUIDv7 `_id` for inserts that omit it, so every row the validator sees has `_id` present. Declaring `_id: z.string()` (required) matches that runtime invariant. `Collection<T>.insert` still accepts a doc without `_id` (the public signature is `insert(doc: Partial<T> & DocumentData & { _id?: string })`), so authoring `_id` as required does not break the "omit and let the server mint it" path. Rows from reads carry `_id: string` either way; the win is on the named type: `RowOf<typeof config, "tickets">` then has `_id: string` (required), so route handlers and response schemas don't need a parallel "\_id-required" row type.
362
+
363
+ An insert that omits `_id` gets a minted UUIDv7 (sorts by mint time); there is no exported id generator. In-process `insert` mints in the kernel. `createBaerlyClient` mints in the SDK and sends `mintedId`, so its resends replay. A raw-HTTP `POST` without `doc._id` is minted by the server; resending it adds a second row. To reference a new row's id, write the parent first and use the returned `_id`; design cross-collection writes parent-first with cleanup.
364
+
365
+ Do not declare `indexes`: they are validated at `Db.create` but never speed up or change a read, which folds the whole snapshot and log, and change no storage call a write makes.
460
366
 
461
367
  ## `createBaerlyClient` (browser / Node HTTP client)
462
368
 
463
- *When NOT to use: server-side in the same process as `Db` — call `Db`/`Collection` directly; the client is for out-of-process / browser callers.*
369
+ _When NOT to use: server-side in the same process as `Db` — call `Db`/`Collection` directly; the client is for out-of-process / browser callers._
464
370
 
465
371
  ```ts
466
372
  import type config from "./baerly.config"; // type-only — server adapter stays out of the SPA bundle
@@ -473,8 +379,7 @@ const client = createBaerlyClient<typeof config>({
473
379
  await client.collection("tickets").where({ status: "open" }).all();
474
380
  ```
475
381
 
476
- `ClientCollection<T>` mirrors `Collection<T>` but every terminal accepts a
477
- trailing `TerminalOptions`:
382
+ `ClientCollection<T>` mirrors `Collection<T>` but every terminal accepts a trailing `TerminalOptions`:
478
383
 
479
384
  ```ts
480
385
  interface TerminalOptions {
@@ -484,17 +389,15 @@ interface TerminalOptions {
484
389
  await client.collection("tickets").all({ signal: ac.signal });
485
390
  ```
486
391
 
487
- That extra options bag is the **only** API difference between
488
- `Collection<T>` and `ClientCollection<T>`. Same modifiers, same terminals,
489
- same predicates.
392
+ That extra options bag is the **only** API difference between `Collection<T>` and `ClientCollection<T>`. Same modifiers, same terminals, same predicates.
393
+
394
+ `onWarning(w)` gets server warnings on successful writes; see RECIPES.md, `CapacityExceeded`.
395
+
396
+ To log, trace or refresh auth on every request, wrap `fetch`; the client already retries (RECIPES.md, "Recipe — wrapping the client `fetch`").
490
397
 
491
398
  ## Long-poll: `/v1/since`
492
399
 
493
- `GET /v1/since?collection=…&cursor=…` is the long-poll endpoint that
494
- streams mutations without WebSockets. The server holds the request
495
- open for ~25 s; if new log entries land in that window it flushes
496
- them immediately, otherwise it returns an empty batch with the
497
- cursor unchanged.
400
+ `GET /v1/since?collection=…&cursor=…` is the long-poll endpoint that streams mutations without WebSockets. The server holds the request open for ~25 s; if new log entries land in that window it flushes them immediately, otherwise it returns an empty batch with the cursor unchanged.
498
401
 
499
402
  ```ts
500
403
  // Wire shape (returned raw — not wrapped in HttpOkEnvelope):
@@ -516,21 +419,9 @@ interface LogEntry {
516
419
  }
517
420
  ```
518
421
 
519
- **Cursor priming.** First call: pass `cursor=` (empty string). The
520
- server's fast path returns immediately _iff_ the log already has
521
- entries for this collection — you get `events: [...]` and the
522
- last entry's `lsn` as `next_cursor`. **If the collection is empty,
523
- the first call blocks for the full long-poll budget (~25 s) before
524
- returning `events: []` with `next_cursor: ''`.** Either prime by
525
- inserting one row first if you need an immediate response, or budget
526
- your client / test for the full timeout. Subsequent calls pass the
527
- returned cursor back — the cursor is opaque, treat it as a string,
528
- and `events` is empty iff the budget elapsed with no new writes
529
- (`next_cursor` unchanged).
530
-
531
- **Test-mode tuning.** Vitest's default per-test timeout is 5 s; the
532
- long-poll's 25 s budget will dominate that. Shrink it on the worker
533
- factory under a test-only env switch:
422
+ **Cursor priming.** First call: pass `cursor=` (empty string). The server's fast path returns immediately _iff_ the log already has entries for this collection — you get `events: [...]` and an opaque `next_cursor`. **If the collection is empty, the first call blocks for the full long-poll budget (~25 s) before returning `events: []` with `next_cursor: ''`.** Either prime by inserting one row first if you need an immediate response, or budget your client / test for the full timeout. Subsequent calls pass the returned cursor back — treat it as an opaque string, and `events` is empty iff the budget elapsed with no new writes (`next_cursor` unchanged).
423
+
424
+ **Test-mode tuning.** Vitest's default per-test timeout is 5 s; the long-poll's 25 s budget will dominate that. Shrink it on the worker factory under a test-only env switch:
534
425
 
535
426
  ```ts
536
427
  export default baerlyWorker((env) => ({
@@ -542,32 +433,15 @@ export default baerlyWorker((env) => ({
542
433
  }));
543
434
  ```
544
435
 
545
- In `vitest.config.mts`'s miniflare bindings, set them as numbers
546
- (`SINCE_TIMEOUT_MS: 2000`, `SINCE_POLL_INTERVAL_MS: 50`) so the
547
- factory sees `number | undefined` without runtime coercion. Don't
548
- shrink `sinceTimeoutMs` in production code paths — it multiplies the
549
- R2 class-A op count per idle long-poll connection.
436
+ In `vitest.config.mts`'s miniflare bindings, set them as numbers (`SINCE_TIMEOUT_MS: 2000`, `SINCE_POLL_INTERVAL_MS: 50`) so the factory sees `number | undefined` without runtime coercion. Don't shrink `sinceTimeoutMs` in production code paths — it multiplies the R2 class-A op count per idle long-poll connection.
437
+
438
+ React apps use `@gusto/baerly-storage/client/react` (see next section) instead of poking `/v1/since` by hand; hand-rolled subscribers in other frameworks `fetch` it directly. The wire shape above is the public contract; there is no cursor-tailing helper.
550
439
 
551
- React applications use `@gusto/baerly-storage/client/react` (see next
552
- section) instead of poking `/v1/since` by hand. Hand-rolled
553
- subscribers in other UI frameworks `fetch` this endpoint directly:
554
- loop, `fetch`-ing with `cursor=` (empty) first, then threading the
555
- returned `next_cursor` back as `cursor` on each subsequent call (the
556
- cursor is opaque — treat it as a string). The wire shape above is the
557
- public contract; there is no exported cursor-tailing helper.
440
+ **Handle `410 CursorExpired` or your loop will spin.** The cursor never works again: back off, re-read, then restart with `cursor=` (empty). Causes: RECIPES.md, `CursorExpired`.
558
441
 
559
442
  ## React: `createBaerlyReact`
560
443
 
561
- `@gusto/baerly-storage/client/react` exports one factory,
562
- `createBaerlyReact<typeof config>()`. Call it once and export the
563
- result; it returns `{ BaerlyProvider, useQuery, useMutation,
564
- useBaerlyClient }` all bound to your config, so a `useQuery` /
565
- `useMutation` callback's `c.collection("notes")` infers the real row
566
- type — **no `as Promise<Note[]>` cast**. (React context can't carry a
567
- generic to the hooks; binding once at the factory is what threads it.)
568
- The provider owns a shared `/v1/since` long-poll per `(client,
569
- collection)`; idle cycles cost zero list reads, and any non-empty batch
570
- invalidates every `useQuery` whose chain touches the firing collection.
444
+ `@gusto/baerly-storage/client/react` exports one factory, `createBaerlyReact<typeof config>()`. Call it once and export the result; it returns `{ BaerlyProvider, useQuery, useMutation, useBaerlyClient }` all bound to your config, so a `useQuery` / `useMutation` callback's `c.collection("notes")` infers the real row type — **no `as Promise<Note[]>` cast**. (React context can't carry a generic to the hooks; binding once at the factory is what threads it.) The provider owns a shared `/v1/since` long-poll per `(client, collection)`; idle cycles cost zero list reads, and any non-empty batch invalidates every `useQuery` whose chain touches the firing collection.
571
445
 
572
446
  ```ts
573
447
  // src/web/client.ts — wire the client + bound hooks once.
@@ -588,39 +462,32 @@ import { BaerlyProvider, client, useMutation, useQuery } from "./client.ts";
588
462
  <App />
589
463
  </BaerlyProvider>;
590
464
 
591
- // 2. useQuery(cb, deps) — the callback receives the bound client and
592
- // returns a ClientCollection / ClientQuery chain. Re-runs on deps
593
- // change OR on long-poll invalidation. Result is a discriminated
594
- // union; the row type is inferred from the collection name:
465
+ // 2. useQuery(cb, deps, options?) — inferred rows, live by default.
595
466
  const result = useQuery((c) => c.collection("notes").all(), []);
596
- // result.status: "loading" | "ok" | "error" | "skipped"
597
- // result.data: Note[] | undefined (present iff status === "ok")
598
- // result.error: BaerlyError | undefined (present iff status === "error")
467
+ // result has status, data/error, and a stable refetch().
468
+
469
+ // 3. live:false reads on mount, deps changes, and refetch—no /v1/since.
470
+ const report = useQuery((c) => c.collection("notes").all(), [reportDate], { live: false });
599
471
 
600
- // 3. useQuery.skip — short-circuit to status: "skipped", no
472
+ // 4. useQuery.skip — short-circuit to status: "skipped", no
601
473
  // subscription. Use for conditional or dependent reads.
602
474
  const filtered = useQuery(
603
475
  (c) => (filter === "all" ? useQuery.skip : c.collection("notes").where({ status: filter }).all()),
604
476
  [filter],
605
477
  );
606
478
 
607
- // 4. useMutation() — returns [mutate, { isPending, error }].
479
+ // 5. useMutation() — returns [mutate, { isPending, error }].
608
480
  // Run any client call inside mutate; subscribed useQuery reads
609
481
  // re-run automatically once the long-poll sees the write.
610
482
  const [mutate, { isPending, error }] = useMutation();
611
483
  await mutate((c) => c.collection("notes").insert({ body }));
612
484
  ```
613
485
 
614
- > No type parameter (`createBaerlyReact()`) gives an unbound surface —
615
- > collection names widen to `string`, rows to `DocumentData` — matching
616
- > the in-process `Db.collection` fallback. There are no loose hooks to
617
- > import directly: an unbound hook can't see the config, so binding at
618
- > the factory is the only path.
486
+ > No type parameter (`createBaerlyReact()`) gives an unbound surface — collection names widen to `string`, rows to `DocumentData` with a string `_id` — matching the in-process `Db.collection` fallback. There are no loose hooks to import directly: an unbound hook can't see the config, so binding at the factory is the only path.
619
487
 
620
488
  ## HTTP wire format
621
489
 
622
- The JS SDK is the canonical path. Reach for `curl` only when
623
- debugging. Mutation bodies are wrapped:
490
+ The JS SDK is the canonical path. Reach for `curl` only when debugging. Mutation bodies are wrapped and need `Content-Type: application/json` (else `415 UnsupportedMediaType`):
624
491
 
625
492
  | Route | Body | Response |
626
493
  | ------------------------------ | ----------------- | ---------------- |
@@ -629,54 +496,31 @@ debugging. Mutation bodies are wrapped:
629
496
  | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
630
497
  | `DELETE /v1/c/:collection/:id` | — | `204` |
631
498
 
632
- Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
633
- `GET /v1/since?collection=…&cursor=…`) take no body and return
634
- `{ data, _meta }` or a route-specific envelope. A flat `POST` body
635
- (no `doc` wrapper) returns
636
- `400 SchemaError "Request body must be { doc: object }"` — wording is
637
- locked by `assertJsonBodyField` in the kernel.
499
+ Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`, `GET /v1/since?collection=…&cursor=…`) take no body and return `{ data, _meta }` or a route-specific envelope. A flat `POST` body (no `doc` wrapper) returns `400 SchemaError "Request body must be { doc: object }"` — wording is locked by `assertJsonBodyField` in the kernel. `POST` accepts `"mintedId"` (UUIDv7 = `doc._id`): resends replay a matching live row, else `AlreadyExists`. Deletion permits reinsertion; each auto-ID `insert(doc)` mints anew. See RECIPES.md.
638
500
 
639
501
  ### Liveness probe (`GET /v1/healthz`)
640
502
 
641
- `baerlyWorker` and `baerlyNode` both mount an anonymous
642
- `GET /v1/healthz` → `200 {"ok":true}`. It is checked **before** the
643
- verifier and observability, so it never 401s and never floods your
644
- logs — wire your platform's liveness/readiness probe straight to it.
645
- If your probe path is fixed to something else (a k8s readiness path,
646
- say), put a custom route in front of the kernel (see "Recipe — custom
647
- routes in front of `baerlyNode`" below).
503
+ `baerlyWorker` and `baerlyNode` both mount an anonymous `GET /v1/healthz` → `200 {"ok":true}`. It is checked **before** the verifier and observability, so it never 401s and never floods your logs — wire your platform's liveness/readiness probe straight to it. If your probe path is fixed to something else (a k8s readiness path, say), put a custom route in front of the kernel (see "Recipe — custom routes in front of `baerlyNode`" below).
648
504
 
649
505
  ### Machine contract (`GET /v1/spec`)
650
506
 
651
- `baerlyWorker` and `baerlyNode` both mount an anonymous
652
- `GET /v1/spec` → the machine-readable contract IR (error codes +
653
- HTTP status, predicate operators, method/route tables) — the same
654
- data shipped as `dist/baerly.spec.json`. It runs the verifier
655
- tolerantly: an unauthenticated probe gets the static contract (no
656
- 401), and a request that the verifier accepts additionally gets a
657
- `collections` array of declared collection + index names.
507
+ `baerlyWorker` and `baerlyNode` both mount an anonymous `GET /v1/spec` → the machine-readable contract IR (error codes + HTTP status, predicate operators, method/route tables) — the same data shipped as `dist/baerly.spec.json`. It runs the verifier tolerantly: an unauthenticated probe gets the static contract (no 401), and a request that the verifier accepts additionally gets a `collections` array of declared collection + index names.
658
508
 
659
509
  ### Read modifiers (query params)
660
510
 
661
- `GET /v1/c/:collection` accepts three JSON-encoded query params; all are
662
- optional and compose:
511
+ `GET /v1/c/:collection` accepts three JSON-encoded query params; all are optional and compose:
663
512
 
664
- | Param | Encodes | Wire example |
665
- | --------- | ----------------------------------------- | ----------------------------------------- |
666
- | `?where=` | `PredicateWire` (see "Wire format" above) | `?where=%7B%22clauses%22%3A%5B%5D%7D` |
667
- | `?order=` | `{ [field]: "asc" \| "desc" }` | `?order=%7B%22sent_at%22%3A%22desc%22%7D` |
668
- | `?limit=` | bare integer (no JSON wrapper) | `?limit=50` |
513
+ | Param | Encodes | Wire example |
514
+ | --- | --- | --- |
515
+ | `?where=` | `PredicateWire` (see "Wire format" above) | `?where=%7B%22clauses%22%3A%5B%5D%7D` |
516
+ | `?order=` | `{ [field]: "asc" \| "desc" }` | `?order=%7B%22sent_at%22%3A%22desc%22%7D` |
517
+ | `?limit=` | bare integer (no JSON wrapper) | `?limit=50` |
669
518
 
670
- `?order=` and `?where=` are JSON, **not** Rails-style `field:asc` —
671
- the kernel `JSON.parse`s them and returns `400 SchemaError` on a flat
672
- string. Always `encodeURIComponent(JSON.stringify(spec))`. The JS SDK
673
- (`createBaerlyClient`) and the React hooks build these for you; reach
674
- for raw URLs only when scripting or when porting another framework's
675
- client.
519
+ `?order=` and `?where=` are JSON, **not** Rails-style `field:asc` — the kernel `JSON.parse`s them and returns `400 SchemaError` on a flat string. Always `encodeURIComponent(JSON.stringify(spec))`. The JS SDK (`createBaerlyClient`) and the React hooks build these for you; reach for raw URLs only when scripting or when porting another framework's client.
676
520
 
677
521
  ## Adapter factories
678
522
 
679
- *On Cloudflare Workers use `r2BindingStorage(env.BUCKET)` (the R2 binding), NOT the S3-credentials factory — credential-based factories assume `fetch` + Node TLS, not the Workers runtime.*
523
+ _On Cloudflare Workers use `r2BindingStorage(env.BUCKET)` (the R2 binding), NOT the S3-credentials factory — credential-based factories assume `fetch` + Node TLS, not the Workers runtime._
680
524
 
681
525
  ```ts
682
526
  // Cloudflare Worker entry
@@ -705,28 +549,11 @@ baerlyNode({
705
549
  }).listen(PORT);
706
550
  ```
707
551
 
708
- **Single-tenant CF Access.** Vanilla CF Access JWTs carry `sub`/`email`
709
- but no `tenant` claim. Pin the tenant from env instead of a claim:
710
- `cloudflareAccess({ teamDomain, audienceTag, tenantPrefix: "main" })`.
711
- Same option is available on `bearerJwt`.
712
-
713
- **Local dev (`wrangler dev`, no Vite).** Declare `auth: "none"` in
714
- `baerly.config.ts` for the dev posture — the adapter synthesizes a
715
- verifier that pins every request to `config.tenant` without consulting
716
- the `Authorization` header. Swap to `auth: "shared-secret"` (or pass a
717
- custom `Verifier` on the factory) when you're ready to gate by wire
718
- credentials. Production CF Worker recipes layer CF Access in front of
719
- the Worker route; the verifier reads the resulting JWT:
720
-
721
- **`auth` only gates the kernel's HTTP router.** `auth: "none"` /
722
- `"shared-secret"` is read by `baerlyWorker` / `baerlyNode` / the
723
- underlying `createRouter` — it controls who can hit `/v1/*`. If you
724
- use `Db` directly (no `createRouter`, no `baerlyWorker`/`baerlyNode`,
725
- e.g. server-internal jobs or your own Hono router), `auth` is
726
- inert: every `Db.create` callsite already carries an explicit
727
- `tenant:`, and your handler's own auth layer decides who reaches
728
- the call. Set `auth: "none"` in the config to silence the typecheck
729
- requirement in that case.
552
+ **Single-tenant CF Access.** Vanilla CF Access JWTs carry `sub`/`email` but no `tenant` claim. Pin the tenant from env instead of a claim: `cloudflareAccess({ teamDomain, audienceTag, tenantPrefix: "main" })`. Same option is available on `bearerJwt`.
553
+
554
+ **Local dev (`wrangler dev`, no Vite).** Declare `auth: "none"` in `baerly.config.ts` for the dev posture — the adapter synthesizes a verifier that pins every request to `config.tenant` without consulting the `Authorization` header. Swap to `auth: "shared-secret"` (or pass a custom `Verifier` on the factory) when you're ready to gate by wire credentials. Production CF Worker recipes layer CF Access in front of the Worker route; the verifier reads the resulting JWT:
555
+
556
+ **`auth` is enforced only by `baerlyWorker` / `baerlyNode`** (the dev Vite plugin and `baerly doctor` also read it). They resolve the verifier (from `auth`, or the `verifier:` override) and run it before building the per-request `Db` and router. `createRouter` has no auth seam: it serves every request it receives as its `Db`'s tenant. If you call `Db` or `createRouter` yourself (server-internal jobs, your own router), `auth` is inert and your code must authenticate and pick the tenant; set `auth: "none"` to satisfy the required field.
730
557
 
731
558
  ```ts
732
559
  // baerly.config.ts
@@ -736,9 +563,7 @@ export default defineConfig({
736
563
  tenant: "main",
737
564
  target: "cloudflare",
738
565
  auth: "none", // dev only — production swaps to "shared-secret" or a custom Verifier
739
- collections: {
740
- /* … */
741
- },
566
+ collections: {/* … */},
742
567
  });
743
568
 
744
569
  // src/server/index.ts
@@ -747,53 +572,31 @@ import config from "../../baerly.config.ts";
747
572
  export default baerlyWorker(() => ({ config }));
748
573
  ```
749
574
 
750
- `s3Storage` / `r2Storage` / `minioStorage` / `gcsStorage` from
751
- `@gusto/baerly-storage/node` are re-exports of one factory family — same
752
- shape (bucket + credentials), all hide their request signer (SigV4 for
753
- S3/R2/MinIO, GOOG4-HMAC for GCS) and XML parsing behind the package
754
- boundary.
575
+ `s3Storage` / `r2Storage` / `minioStorage` / `gcsStorage` from `@gusto/baerly-storage/node` are re-exports of one factory family — same shape (bucket + credentials), all hide their request signer (SigV4 for S3/R2/MinIO, GOOG4-HMAC for GCS) and XML parsing behind the package boundary. `credentials` takes static keys or an async provider (EKS, expiring, AWS SDK): RECIPES.md, "Recipe — storage credentials on Node".
755
576
 
756
577
  ### Verifier presets
757
578
 
758
- `@gusto/baerly-storage/auth` ships three `Verifier` functions you can pass
759
- to `baerlyWorker({ verifier })` or `baerlyNode({ verifier })`. Each
760
- returns `VerifierResult | null` (null = 401 unauth; thrown
761
- `BaerlyError` = 500 operator fault — the dispatcher splits the
762
- codes deliberately so on-call paging targets operator faults only).
579
+ `@gusto/baerly-storage/auth` ships three `Verifier` functions you can pass to `baerlyWorker({ verifier })` or `baerlyNode({ verifier })`. Each returns `VerifierResult | null` (null = 401 unauth; thrown `BaerlyError` = 500 operator fault — the dispatcher splits the codes deliberately so on-call paging targets operator faults only).
763
580
 
764
- | Preset | Identity source | Tenant derivation |
765
- | ------------------ | ------------------------------------------------------------- | --------------------------------------------------------------------------------- |
766
- | `sharedSecret` | `Authorization: Bearer <secret>` with constant-time compare | `tenantPrefix:` option (single-tenant only) |
767
- | `bearerJwt` | JWT over JWKS, `iss` + `aud` + `alg` allowlist | Configurable `tenantClaim` (default `"tenant"`) or fixed `tenantPrefix:` override |
768
- | `cloudflareAccess` | `Cf-Access-Jwt-Assertion` header (thin shim over `bearerJwt`) | Same as `bearerJwt` |
581
+ | Preset | Identity source | Tenant derivation |
582
+ | --- | --- | --- |
583
+ | `sharedSecret` | `Authorization: Bearer <secret>` with constant-time compare | `tenantPrefix:` option (single-tenant only) |
584
+ | `bearerJwt` | JWT over JWKS, `iss` + `aud` + required `exp` + `alg` allowlist | Configurable `tenantClaim` (default `"tenant"`) or fixed `tenantPrefix:` override |
585
+ | `cloudflareAccess` | `Cf-Access-Jwt-Assertion` header (thin shim over `bearerJwt`) | Same as `bearerJwt` |
769
586
 
770
587
  ```ts
771
588
  import { sharedSecret, bearerJwt, cloudflareAccess } from "@gusto/baerly-storage/auth";
772
589
  ```
773
590
 
774
- **`tenantPrefix:` (on `bearerJwt` and `cloudflareAccess`).** Pins
775
- every verified request to a fixed tenant, bypassing claim lookup.
776
- Use this in single-tenant deployments where the IdP doesn't ship a
777
- tenant claim — the default `tenantClaim: "tenant"` would 401 every
778
- request because vanilla CF Access JWTs carry only `sub`/`email`.
779
- Signature, audience, and expiry checks are still enforced; only
780
- tenant derivation is replaced.
591
+ **`tenantPrefix:` (on `bearerJwt` and `cloudflareAccess`).** Pins every verified request to a fixed tenant, bypassing claim lookup. Use this in single-tenant deployments where the IdP doesn't ship a tenant claim — the default `tenantClaim: "tenant"` would 401 every request because vanilla CF Access JWTs carry only `sub`/`email`. Signature, audience, and expiry checks are still enforced; only tenant derivation is replaced.
592
+
593
+ **`tenantClaim:`** picks the tenant a request reads and writes, so name a claim only an IdP admin can set. A claim the user can edit (profile metadata, a self-service attribute) lets them pick their own tenant.
781
594
 
782
- **Why a function and not a class?** The source repo's
783
- `docs/guide/auth.md` records the properties the shape upholds and the
784
- rejected alternatives (class hierarchy, middleware chain, closed enum,
785
- kernel-side composition).
595
+ **Why a function and not a class?** The source repo's `docs/guide/auth.md` records the properties the shape upholds and the rejected alternatives (class hierarchy, middleware chain, closed enum, kernel-side composition).
786
596
 
787
597
  ## Observability
788
598
 
789
- `baerlyWorker` and `baerlyNode` emit **one canonical log line per
790
- HTTP request** on stdout (default level `info`). Background work
791
- (compactor / GC / `runScheduledMaintenance`) emits a separate
792
- `unit_of_work: "maintenance"` line per tick. The Cloudflare adapter
793
- is JSON-only (Workers have no TTY); the Node adapter auto-selects a
794
- human-readable single-line shape when `process.stdout.isTTY ===
795
- true`. Sinks plug in via `observability.sink` on the factory
796
- options.
599
+ `baerlyWorker` and `baerlyNode` emit **one canonical log line per HTTP request** on stdout (default level `info`). Background work (compactor / GC / `runScheduledMaintenance`) emits a separate `unit_of_work: "maintenance"` line per tick. The Cloudflare adapter is JSON-only (Workers have no TTY); the Node adapter auto-selects a human-readable single-line shape when `process.stdout.isTTY === true`. Sinks plug in via `observability.sink` on the factory options.
797
600
 
798
601
  ```json
799
602
  {
@@ -805,7 +608,7 @@ options.
805
608
  "path": "/v1/c/tickets",
806
609
  "status": 200,
807
610
  "duration_ms": 14.207,
808
- "outcome": "ok",
611
+ "outcome": "committed",
809
612
  "db.storage.class_a_ops_total": 3,
810
613
  "db.storage.class_b_ops_total": 1,
811
614
  "db.write.class_a_ops_per_logical_write_sum": 3
@@ -814,24 +617,22 @@ options.
814
617
 
815
618
  ### Field reference
816
619
 
817
- | Field | Meaning |
818
- | ---------------------------------------------- | ------------------------------------------------------------------------------------ |
819
- | `request_id` | Correlation key. Set from `X-Request-Id` if provided, else minted fresh. |
820
- | `method` / `path` / `status` | HTTP request line + response code. |
821
- | `cache_status` | `"hit" \| "miss" \| "bypass"` — Cloudflare adapter only. Node adapter omits. |
822
- | `duration_ms` | `performance.now()` delta, monotonic wall-clock. |
823
- | `outcome` | `"read"` (GET <400), `"committed"` (non-GET <400), `"conflict"` (409), or `"error"`. |
824
- | `db.storage.class_a_ops_total` | PUT + DELETE + LIST count. S3-pricing Class A — cost-dominant. |
825
- | `db.storage.class_b_ops_total` | GET count. S3-pricing Class B. |
826
- | `db.storage.<op>.calls_total` | Per-op breakdown for `get` / `put` / `delete` / `list`. |
827
- | `db.storage.<op>.duration_ms_sum` / `_count` | Per-call duration histogram. |
828
- | `db.write.class_a_ops_per_logical_write_*` | Writer's per-`commit()` Class-A-op count. |
829
- | `db.r2.put.412_total` / `429_total` | CAS conflicts (412) and storage rate-limit hits (429). |
830
- | `error.code` / `error.message` / `error.stack` | Failure-path only. `error.code` is `BaerlyErrorCode`. |
831
-
832
- Class-A / Class-B totals are the load-bearing fields — the cost
833
- model puts a per-request ceiling on Class-A ops and the canonical
834
- line is how you verify a deployed service stays under it.
620
+ | Field | Meaning |
621
+ | --- | --- |
622
+ | `request_id` | Correlation key. Set from `X-Request-Id` when it is at most 128 characters of `[A-Za-z0-9_.:/+=@-]`, else minted fresh. |
623
+ | `method` / `path` / `status` | HTTP request line + response code. |
624
+ | `duration_ms` | `performance.now()` delta, monotonic wall-clock. |
625
+ | `outcome` | `"read"`/`"committed"` (<400), `"conflict"` (409), `"refused"` (capacity), `"error"`. |
626
+ | `db.storage.class_a_ops_total` | PUT + DELETE + LIST count. S3-pricing Class A — cost-dominant. |
627
+ | `db.storage.class_b_ops_total` | GET count. S3-pricing Class B. |
628
+ | `db.storage.<op>.calls_total` | Per-op breakdown for `get` / `put` / `delete` / `list`. |
629
+ | `db.storage.<op>.duration_ms_sum` / `_count` | Per-call duration histogram. |
630
+ | `db.write.class_a_ops_per_logical_write_*` | Writer's per-`commit()` Class-A-op count. |
631
+ | `db.r2.put.412_total` / `429_total` | CAS conflicts (412) and storage rate-limit hits (429). |
632
+ | `db.read.<unit>_total` | `decoded_entries` (snapshot rows + log entries), `live_documents`, `returned_rows`. |
633
+ | `error.code` / `error.message` / `error.stack` | Failure-path only. `error.code` is `BaerlyErrorCode`. |
634
+
635
+ Class-A / Class-B totals are the load-bearing fields — the cost model puts a per-request ceiling on Class-A ops and the canonical line is how you verify a deployed service stays under it.
835
636
 
836
637
  ### Log levels
837
638
 
@@ -842,20 +643,11 @@ line is how you verify a deployed service stays under it.
842
643
  | `info` | Default. Adds 2xx canonical lines and lifecycle events. |
843
644
  | `debug` | Adds per-storage-op events. **High volume**; off in production. |
844
645
 
845
- Set `LOG_LEVEL` env var or the typed `observability.level` factory
846
- option. Sink wiring (Workers Analytics Engine, OTel, Datadog) lives
847
- in the source repo's `docs/guide/observability.md`.
646
+ Set `LOG_LEVEL` env var or the typed `observability.level` factory option. Sink wiring (Workers Analytics Engine, OTel, Datadog) lives in the source repo's `docs/guide/observability.md`.
848
647
 
849
648
  ## Recipe — server-stamped trusted fields
850
649
 
851
- Use this shape when a column must come from the verified identity
852
- rather than the client request body (`sender_sub` on chat messages,
853
- `owner_id` on user-owned rows, `created_by` on audit logs). The
854
- HTTP routes `baerlyWorker` mounts under `/v1/c/:collection` accept the
855
- doc verbatim from the request body — they don't read the verifier
856
- identity into the row. Stamp it yourself in a custom route, then
857
- block direct client writes to the same collection so a malicious
858
- client can't supply the field by hand.
650
+ Use this shape when a column must come from the verified identity rather than the client request body (`sender_sub` on chat messages, `owner_id` on user-owned rows, `created_by` on audit logs). The HTTP routes `baerlyWorker` mounts under `/v1/c/:collection` accept the doc verbatim from the request body — they don't read the verifier identity into the row. Stamp it yourself in a custom route, then block direct client writes to the same collection so a malicious client can't supply the field by hand.
859
651
 
860
652
  ```ts
861
653
  // src/server/index.ts
@@ -916,30 +708,13 @@ export default {
916
708
  } satisfies ExportedHandler<BaerlyEnv>;
917
709
  ```
918
710
 
919
- The client reads via the normal `GET /v1/c/messages` route and tails
920
- via `GET /v1/since?collection=messages&cursor=…` — both still served by
921
- `inner`. Only writes go through `/api/messages`. Reads stay uncapped and
922
- tenant-wide — scope and clamp them in your route too (see RECIPES.md).
711
+ The client reads via the normal `GET /v1/c/messages` route and tails via `GET /v1/since?collection=messages&cursor=…` — both still served by `inner`. Only writes go through `/api/messages`. Reads stay uncapped and tenant-wide — scope and clamp them in your route too (see RECIPES.md).
923
712
 
924
- **Known limitations of this recipe.** The custom-route `Db.create` is
925
- a second instance — it doesn't share `baerlyWorker`'s
926
- `observableStorage(...)` wrapping (so custom-route writes don't land
927
- in the canonical-line storage counters) or the read-cache invalidation
928
- helper. For small chat-shaped apps this is acceptable; the
929
- observability gap is being tracked as a follow-up. If you also need
930
- PATCH/PUT/DELETE on the same collection, repeat steps (1) and (2) for
931
- each verb.
713
+ **Known limitations of this recipe.** The custom-route `Db.create` runs outside `baerlyWorker`'s request handling: its writes don't land in the canonical-line storage counters, run write-tick maintenance before the response instead of in `ctx.waitUntil`, and aren't budgeted against the subrequest limit (RECIPES.md, gated adapter). Worker reads always reach storage, so they see these writes. If you also need PATCH/PUT/DELETE on the same collection, repeat steps (1) and (2) for each verb.
932
714
 
933
715
  ## Recipe — custom routes in front of `baerlyNode`
934
716
 
935
- `baerlyNode(...).listen(port)` is the shortcut for the common case:
936
- no custom routes, the kernel owns the whole port. To put your own
937
- route in front of the kernel (a fixed-path health probe, a
938
- trusted-stamp write route à la the recipe above), grab the
939
- web-standard `fetch` handler off the handle instead of calling
940
- `.listen()`, and serve it yourself. `serve()` here is the same
941
- `@hono/node-server` entry `.listen()` uses internally — you're just
942
- taking ownership of the dispatch:
717
+ `baerlyNode(...).listen(port)` is the shortcut for the common case: no custom routes, the kernel owns the whole port. It binds every interface; `.listen(port, { hostname: "127.0.0.1" })` binds loopback only. To put your own route in front of the kernel (a fixed-path health probe, a trusted-stamp write route à la the recipe above), grab the web-standard `fetch` handler off the handle instead of calling `.listen()`, and serve it yourself. `serve()` comes from the same `@hono/node-server` package `.listen()` uses internally — you're just taking ownership of the dispatch:
943
718
 
944
719
  ```ts
945
720
  // src/server/index.ts
@@ -960,146 +735,20 @@ serve({
960
735
  });
961
736
  ```
962
737
 
963
- The handle's `fetch` is the documented embedding seam (it's also what
964
- the Vite dev middleware and tests consume) — there's no separate
965
- `createApp` to reach for. If you don't need a _custom_ probe path,
966
- skip all of this and point your platform at the built-in
967
- `GET /v1/healthz` (see above).
968
-
969
- > **Monorepo note.** `@hono/node-server` (and its `hono` peer) ship
970
- > as dependencies of the Node adapter, so the `serve` import resolves
971
- > out of the box in a scaffolded app. In a monorepo that prunes
972
- > unused peers (e.g. `yarn workspaces focus` in CI), add
973
- > `@hono/node-server` to the app's own `dependencies` so the import
974
- > survives the prune.
975
-
976
- ## Recipe — wrapping the client `fetch`
977
-
978
- `createBaerlyClient({ fetch: customFetcher })` is the one composable
979
- seam for cross-cutting HTTP concerns. The `Fetcher` type is one
980
- line:
981
-
982
- ```ts
983
- import { type Fetcher } from "@gusto/baerly-storage/client";
984
- // type Fetcher = (req: Request) => Promise<Response>;
985
- ```
986
-
987
- Wrappers compose as ordinary JavaScript functions: outermost sees
988
- the request first and the response last; innermost is closest to
989
- the network. Three recipes cover the common cases.
990
-
991
- ### Hook callbacks (success / error)
992
-
993
- ```ts
994
- import { createBaerlyClient, type Fetcher } from "@gusto/baerly-storage/client";
995
-
996
- const withHooks =
997
- (
998
- next: Fetcher,
999
- onSuccess: (req: Request, res: Response) => void,
1000
- onError: (req: Request, err: unknown) => void,
1001
- ): Fetcher =>
1002
- async (req) => {
1003
- try {
1004
- const res = await next(req);
1005
- onSuccess(req, res);
1006
- return res;
1007
- } catch (err) {
1008
- onError(req, err);
1009
- throw err;
1010
- }
1011
- };
1012
-
1013
- const client = createBaerlyClient({
1014
- baseUrl: "https://api.example.com",
1015
- fetch: withHooks(
1016
- globalThis.fetch,
1017
- (req, res) => log.info({ url: req.url, status: res.status }),
1018
- (req, err) => log.error({ url: req.url, err }),
1019
- ),
1020
- });
1021
- ```
1022
-
1023
- `onSuccess` fires for **any** HTTP response that completes — 4xx and
1024
- 5xx included, because those are not thrown exceptions. Branch on
1025
- `res.ok` if you want "2xx only."
1026
-
1027
- ### Retry on transient failures (GET only)
1028
-
1029
- ```ts
1030
- const withRetry =
1031
- (next: Fetcher, max = 3, baseMs = 100): Fetcher =>
1032
- async (req) => {
1033
- for (let i = 0; i < max - 1; i++) {
1034
- const res = await next(req.clone());
1035
- if (res.ok || res.status < 500 || req.method !== "GET") return res;
1036
- await new Promise((r) => setTimeout(r, baseMs * (i + 1)));
1037
- }
1038
- return next(req);
1039
- };
1040
- ```
1041
-
1042
- Only retry idempotent reads. `POST` / `PATCH` / `DELETE` may have
1043
- succeeded on the server even when the client sees a 5xx (commit
1044
- fence then network drop). Writes are CAS-guarded so duplicates
1045
- don't corrupt state — but they may surface as `PreconditionFailed`.
1046
- The `req.clone()` is required because a `Request` body is a
1047
- one-shot stream.
1048
-
1049
- ### Refresh credentials on 401
1050
-
1051
- ```ts
1052
- const withAuthRefresh =
1053
- (next: Fetcher, refresh: () => Promise<string>): Fetcher =>
1054
- async (req) => {
1055
- const res = await next(req.clone());
1056
- if (res.status !== 401) return res;
1057
- const token = await refresh();
1058
- const retried = new Request(req, {
1059
- headers: new Headers({
1060
- ...Object.fromEntries(req.headers),
1061
- Authorization: `Bearer ${token}`,
1062
- }),
1063
- });
1064
- return next(retried);
1065
- };
1066
- ```
1067
-
1068
- If the refreshed call also returns 401, the wrapper returns that
1069
- response unchanged — no second retry, avoiding an infinite refresh
1070
- loop on a stale/revoked token. Wire sign-out / re-auth-prompt into
1071
- the caller, not into this wrapper.
1072
-
1073
- ### Long-poll calls (`GET /v1/since`)
1074
-
1075
- The long-poll path routes through the same `Fetcher`. Retry,
1076
- logging, and auth-refresh wrappers apply uniformly. If a wrapper
1077
- needs to distinguish long-poll from one-shot reads, inspect
1078
- `req.url` for `/v1/since`. Most wrappers don't need to.
1079
-
1080
- ### Composition order
738
+ The handle's `fetch` is the documented embedding seam (it's also what the Vite dev middleware and tests consume) — there's no separate `createApp` to reach for. If you don't need a _custom_ probe path, skip all of this and point your platform at the built-in `GET /v1/healthz` (see above).
1081
739
 
1082
- The outer wrapper sees retries — `withRetry(withLogging(fetch))` logs
1083
- each attempt; `withLogging(withRetry(fetch))` logs the final outcome
1084
- once. Pick by what you want to observe.
740
+ > **Monorepo note.** `@hono/node-server` (and its `hono` peer) ship as dependencies of the Node adapter, so the `serve` import resolves out of the box in a scaffolded app. In a monorepo that prunes unused peers (e.g. `yarn workspaces focus` in CI), add `@hono/node-server` to the app's own `dependencies` so the import survives the prune.
1085
741
 
1086
742
  ## Anti-patterns
1087
743
 
1088
- A few that compile but are wrong (full list, keyed by the exact error
1089
- string you see: `cat node_modules/@gusto/baerly-storage/dist/RECIPES.md`):
744
+ A few that compile but are wrong (full list, keyed by the exact error string you see: `cat node_modules/@gusto/baerly-storage/dist/RECIPES.md`):
1090
745
 
1091
746
  - Don't widen branded types (`UUID`, `ContentVersionId`) with `as string`.
1092
747
  - Don't put `SHARED_SECRET` in the SPA bundle — it's server-to-server only.
1093
748
 
1094
749
  ## Where to look next
1095
750
 
1096
- - **A call you expected doesn't type-check?** The public surface is
1097
- additive-only locked, but the rare breaking change carries an
1098
- old→new migration in `dist/CHANGELOG.md` (`cat dist/CHANGELOG.md`). The
1099
- `.d.ts` types are canonical; the changelog is the recovery path.
1100
- - Per-symbol JSDoc: read the `.d.ts` chunks in this directory
1101
- (`db-*.d.ts`, `index-*.d.ts`, `client-*.d.ts`, …) — the bundler
1102
- splits them; `cat dist/*.d.ts` gives the union.
1103
- - Theoretical foundations + cost model: the repository's `docs/`
1104
- tree (`docs/about/`, `docs/spec/`).
751
+ - **A call you expected doesn't type-check?** The public surface is additive-only locked, but the rare breaking change carries an old→new migration in `dist/CHANGELOG.md` (`cat dist/CHANGELOG.md`). The `.d.ts` types are canonical; the changelog is the recovery path.
752
+ - Per-symbol JSDoc: read the `.d.ts` chunks in this directory (`db-*.d.ts`, `index-*.d.ts`, `client-*.d.ts`, …) — the bundler splits them; `cat dist/*.d.ts` gives the union.
753
+ - Theoretical foundations + cost model: the repository's `docs/` tree (`docs/about/`, `docs/spec/`).
1105
754
  - Common mistakes & recipes: `cat node_modules/@gusto/baerly-storage/dist/RECIPES.md`; deeper guides in the repo's `docs/guide/`.