@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/RECIPES.md CHANGED
@@ -1,122 +1,440 @@
1
1
  # baerly-storage — common mistakes & recipes
2
2
 
3
- > Companion to `dist/API.md`. API.md is the surface; this file is the
4
- > "why did my call fail" lookup, keyed by the exact error string you
5
- > see. If a fix here disagrees with the `.d.ts` types, the types win.
3
+ > Companion to `dist/API.md`. API.md is the surface; this file is the "why did my call fail" lookup, keyed by the exact error string you see. If a fix here disagrees with the `.d.ts` types, the types win.
6
4
 
7
5
  ## Common mistakes (keyed by the error you see)
8
6
 
9
7
  ### `Request body must be { doc: object }` (HTTP 400, `code="SchemaError"`)
10
8
 
11
- **Cause:** POSTed a flat document body to `/v1/c/<collection>`.
12
- **Fix:** Wrap it: `{ "doc": { ...yourFields } }`. The insert verb reads
13
- `body.doc`, not the body itself. Same pattern for PATCH (`patch:`) and
14
- PUT (`doc:`).
15
- The wire `resolution` says: `Send a JSON body shaped { "doc": { ... } } for POST/PUT, or { "patch": { ... } } for PATCH.`
9
+ **Cause:** POSTed a flat document body to `/v1/c/<collection>`. **Fix:** Wrap it: `{ "doc": { ...yourFields } }`. The insert verb reads `body.doc`, not the body itself. Same pattern for PATCH (`patch:`) and PUT (`doc:`). The wire `resolution` says: `Send a JSON body shaped { "doc": { ... } } for POST/PUT, or { "patch": { ... } } for PATCH.`
16
10
 
17
11
  ### `BaerlyError code="SchemaError"` on insert/update/replace
18
12
 
19
- **Cause:** the document failed schema validation, OR the body is not
20
- valid JSON / contains an array where `DocumentValue` is required, OR a
21
- `null` field value (use `.optional()`; `null` in an *update patch* is the
22
- RFC 7386 deletion sentinel, not a storable value).
23
- **Fix:** read `error.issues` (each `{ path, message }`) for the offending
24
- field path. Declare `_id: z.string()` (required) in your schema — the
25
- validator runs on the post-image, so optional `_id` is wrong.
26
-
27
- ### `BaerlyError code="Conflict"` (HTTP 409)
28
-
29
- **Cause:** the write conflicted with existing state. CAS conflicts are
30
- retryable (`retriable: true`); duplicate caller-supplied `_id` inserts are
31
- terminal (`retriable: false`).
32
- **Fix:** follow the wire `resolution`. For retryable CAS conflicts, re-read,
33
- re-apply, and retry with bounded backoff. For duplicate `_id` conflicts,
34
- choose a different `_id`, or omit `_id` so baerly-storage can mint one.
35
- The in-process writer already retries a bounded number of CAS attempts; a
36
- remote client that sees `retriable: true` should apply its own bounded backoff.
13
+ **Cause:** the document failed schema validation (including a `null` your schema does not allow: `.optional()` rejects `null`), OR the body is not valid JSON / contains an array where `DocumentValue` is required. **Fix:** read `error.issues` (each `{ path, message }`) for the offending field path. Declare `_id: z.string()` (required) in your schema — the validator runs on the post-image, so optional `_id` is wrong.
14
+
15
+ ### `Type 'null' is not assignable to type 'DocumentValue'` (TS2322)
16
+
17
+ Also `Type 'null' is not assignable to type 'string | undefined'` (or another field type) on an `update` patch.
18
+
19
+ **Cause:** `null` is not a stored value in the typed document contract. `DocumentValue` excludes it, so `insert` and `replace` reject a `null` value at compile time, even on a collection whose schema uses `.nullable()` (the row type then admits `null`, the write types still do not). An `update` patch is a `MergePatch<T>`: `null` there means "delete this field", so it is accepted on an optional key and rejected on a required one. To change part of an optional object, pass the whole object or use `replace`.
20
+
21
+ The runtime is more permissive:
22
+
23
+ - `insert` and `replace` (in-process and over HTTP) store `null` at any depth as written, and reads return it. With a bound schema, the schema decides: `.optional()` rejects `null` with `SchemaError`, `.nullable()` accepts it.
24
+ - In an `update` patch, a `null` member deletes that field at any depth (RFC 7396), so a patch never stores `null`, including in a patch object written under a field that is absent or not an object. A `null` inside an array is stored as written.
25
+ - A predicate cannot match `null`: `.where({ field: null })` throws `InvalidConfig`, and no other value matches a stored `null`.
26
+
27
+ **Fix:** model an absent value by omitting the field, with `.optional()` in the schema. To remove an optional field, `update(id, { field: null })`; to remove a required field, `replace` the row without it. Don't cast `null` past the types to store it: typed rows and predicates do not account for stored nulls.
28
+
29
+ ### `Type 'Bookmark' does not satisfy the constraint 'DocumentData'` (TS2344)
30
+
31
+ **Cause:** a row type you wrote by hand for a collection the bound `config` does not declare is a plain `interface Bookmark { _id: string; url: string }`. It has no index signature, so it fails `T extends DocumentData`. The constraint is deliberate: it keeps a row JSON-compatible.
32
+
33
+ **Fix:** `extends DocumentData`, then cast the handle at the construction site. On the HTTP client, build an unbound client (no `config`, so collection names widen to `string` and rows are typed `DocumentData & { _id: string }`) and cast to `ClientCollection<T>`; on an unbound `Db` (no `config`; a config-bound `Db` rejects undeclared names at compile time), cast `db.collection(name)` to `Collection<T>`. The cast is for the typed fields: every read already types `_id` as a string, so `row._id` passes to `get` / `update` / `replace` / `delete` with or without it, and `T` need not declare `_id`.
34
+
35
+ ```ts
36
+ import {
37
+ createBaerlyClient,
38
+ type ClientCollection,
39
+ type DocumentData,
40
+ } from "@gusto/baerly-storage/client";
41
+
42
+ interface Bookmark extends DocumentData {
43
+ _id: string;
44
+ url: string;
45
+ }
46
+
47
+ const raw = createBaerlyClient({ baseUrl: "" });
48
+ const bookmarks = raw.collection("bookmarks") as ClientCollection<Bookmark>;
49
+ await bookmarks.all();
50
+ ```
51
+
52
+ For a collection declared in `config`, don't cast: pass `config` and name the row with `RowOf<typeof config, "notes">` (API.md, `DocumentData`).
53
+
54
+ The generic on `client.collection<N>(name)` is the collection name (constrained to `CollectionNames<typeof config>`), never the row type: don't pass a row type to it.
55
+
56
+ ### `BaerlyError code="InvalidConfig"` — `Predicate value at ... is an array`
57
+
58
+ **Full message:** `Predicate value at <path> is an array — match nested objects with a sub-predicate or use callback form (q.in(field, values)) for set membership.`
59
+
60
+ **Cause:** an object-literal `.where({ field: [...] })` received an array. The object form is equality only, and its values are string, number, boolean or a nested object; scalar fields reject an array at compile time, and the runtime throws this error.
61
+
62
+ **Fix:** for set membership use the callback form, `.where((q) => q.in("status", ["open", "pending"]))`. To match a nested object, pass a sub-predicate (`{ assignee: { team: "platform" } }`).
63
+
64
+ ### `BaerlyError code="WriteConflict"` (HTTP 409)
65
+
66
+ **Cause:** another write won a race this call needed to win, and the losing commit did not land. `retriable` is `true`. A bulk `.where(...).update()` / `.delete()` may have applied earlier rows; re-issuing the call is safe. **Fix:** re-read, re-apply, and retry with bounded backoff. The in-process writer makes one commit attempt and does not retry it (storage adapters retry individual requests); a remote client that sees `retriable: true` should apply its own bounded backoff.
67
+
68
+ ### `BaerlyError code="AlreadyExists"` (HTTP 409)
69
+
70
+ **Cause:** a caller-supplied `_id` on `insert` is held by a live row (or `baerly admin restore` targeted an existing collection without `--force`). The first insert of an `_id` wins: of concurrent inserts of one `_id`, at most one commits and the others throw `AlreadyExists`, committing nothing (an identical `mintedId` resend replays instead; see the next section). `retriable` is `false`: never retry. **Fix:** choose a different `_id`, omit `_id` so baerly-storage can mint one, or change the stored row with `update` / `replace`. After a same-`_id` retry following `AmbiguousCommit`, the stored row may be your first attempt: re-read it instead (see below). The same holds for an insert that omitted `_id`: the client resends it under its minted `_id`, so this error can mean your first attempt landed and the row changed since. Re-read it; do not insert again without an `_id`, which mints a second row.
71
+
72
+ ### `BaerlyError code="CapacityExceeded"` (HTTP 409)
73
+
74
+ **Cause:** the collection has reached the fold ceiling of the host serving the request (`E` rows or `C` snapshot bytes for its maintenance profile), so the write was refused and not committed. `retriable` is `false`. The refusal is recomputed on every request; nothing is stored. A batch `.where(...).update()` / `.delete()` is checked before its first row commits, and again at a row's commit if a concurrent write landed since; refused part-way, it keeps the rows it already committed. **Fix:** depends on the message.
75
+
76
+ - **Growth refused** (an insert, or an update that makes a row larger): deletes and same-size or shrinking updates still commit. Delete or shrink rows; once write-tick maintenance folds them, growth is accepted again.
77
+ - **Every write refused** ("no fold can make progress here"): the stored snapshot is already past this host's ceiling, typically after a larger host folded it, a pending insert cannot fold onto an `E`-row snapshot, or a fold pass's worth of pending changes in a row each leave the snapshot past the byte ceiling. The collection has outgrown this host: export it with `baerly admin dump`, or have the operator move it to a larger host. Reads within the read bounds keep working either way.
78
+ - **Request limit** ("does not fit in one request on this host"): the request ran out of storage calls, and the refused write sent nothing. A multi-row `update()` / `delete()` keeps the rows before the refused one; re-run it as a new request (it re-reads and re-matches), or narrow it with `where` / `limit` so each request does less.
79
+ - **Read refused** ("this read of collection ... was refused and returned no rows"): the read needs more work than one request does on this host. It returned no rows, never a truncated answer, and wrote nothing. `err.resolution` names the remedy for the bound it hit: narrow the predicate or add a limit, delete or shrink rows, or retry once maintenance has absorbed pending writes.
80
+
81
+ **Warned before it happens:** a write that leaves the collection at 90% or more of the limit succeeds with a `Baerly-Capacity-Warning` response header. `createBaerlyClient({ onWarning })` hands it to your callback as `{ code: "CapacityWarning", message, method, path }`; delete or shrink rows then, before writes start being refused. The write's result is unchanged and a throwing callback cannot fail it. Cross-origin, your CORS layer must list `Baerly-Capacity-Warning` in `Access-Control-Expose-Headers`.
82
+
83
+ ### `BaerlyError code="MaintenancePending"` (HTTP 503, `Retry-After`)
84
+
85
+ **Cause:** the write would grow the collection past its host's fold ceiling until pending changes fold, and folding them makes room (typically after the collection moved from a host with a larger ceiling, with deletes still pending). The write ran one bounded fold and was refused without committing (a batch refused part-way keeps the rows it already committed). `retriable` is `true`. The refusal is recomputed on every request; nothing is stored. **Fix:** wait `err.retryAfter` seconds (the `Retry-After` header over HTTP), then repeat the call. Reads keep working. `createBaerlyClient` already does this on every verb: it resends the identical request (an auto-ID insert keeps its minted `_id`) up to 3 attempts in total, waiting each hint of at most 10 s, so the error reaches your code only once those run out. The React subscription poll waits at least `retryAfter` before re-polling. Resending is safe because the refusal committed nothing and each HTTP write is one row. In-process, a multi-row `update` refused part-way keeps the rows before it; re-running it is safe, since a merge patch re-applied to a row it already changed leaves that row as it is.
86
+
87
+ ### `BaerlyError code="CursorExpired"` (HTTP 410)
88
+
89
+ **Cause:** a `/v1/since` cursor can no longer resume: the changes after it are no longer retained, or `baerly admin restore --force` truncated the generation it was minted in. `retriable` is `false`; the same cursor never succeeds again. A malformed cursor is `SchemaError` (400) instead. **Fix:** re-read the rows you show, then resume with `cursor=` (empty); the changes between the dead cursor and the restart are not replayed. Back off before the restart so a cursor that expires on every lap cannot become a hot loop. The React hooks do this for you.
90
+
91
+ ### `_id must be in Unicode Normalization Form C` (HTTP 400, `code="InvalidConfig"`)
92
+
93
+ **Cause:** `insert`, `replace`, or `update` got an `_id` that is not NFC, such as `"cafe\u0301"` (NFD) instead of `"caf\u00e9"`. Each `_id` has one spelling, because R2 stores canonically-equivalent keys as one object. **Fix:** pass `id.normalize("NFC")`. A row an earlier release stored under a non-NFC `_id` still reads and deletes; to keep it writable, insert a copy under a fresh NFC id that is not canonically equivalent to the original (for example, omit `_id` for a UUID), then delete the original.
94
+
95
+ ### `app`/`tenant`/`collection must be in Unicode Normalization Form C` (HTTP 400, `code="InvalidConfig"`)
96
+
97
+ **Cause:** `Db.create`, `db.collection`, or an HTTP route got an app, tenant, or collection name that is not NFC, such as `"cafe\u0301"` (NFD) instead of `"caf\u00e9"`. R2 stores canonically-equivalent keys as one object, so the two spellings would address one key prefix there and two elsewhere. **Fix:** pass `name.normalize("NFC")` for a new name. Data an earlier release stored under a non-NFC name is accessible through `baerly inspect`, `baerly export`, `baerly admin dump`, and `baerly admin fsck`. To keep it writable, dump it and restore it under an NFC name that is not canonically equivalent to the original, then point the app at the new name:
98
+
99
+ ```sh
100
+ baerly admin dump --bucket=$B --app=app --tenant=t --collection=$'cafe\u0301' > rows.ndjson
101
+ baerly admin restore --bucket=$B --app=app --tenant=t --collection=$'caf\u00e9-v2' < rows.ndjson
102
+ ```
103
+
104
+ The normalized original name is not a safe target: on R2 it addresses the legacy objects. Run `baerly admin fsck` first: it flags non-NFC names. `baerly admin dump` also flags non-NFC `_id`s and canonically-equivalent twin `_id`s, which restore refuses or which have only one NFC spelling; give each a fresh NFC `_id` in the NDJSON before restoring.
105
+
106
+ The alias guard checks stored collection names, not app or tenant identity. Normalized legacy app or tenant aliases can still read and modify the same data on R2; migrate those namespaces to fresh names instead of relying on refusal.
107
+
108
+ ### `collection ... addresses data stored under the canonically-equivalent name ...` (HTTP 400, `code="InvalidConfig"`)
109
+
110
+ **Cause:** on R2, this NFC collection name addresses objects an earlier release wrote under a non-NFC spelling of the same name. Reads, writes, folds, and exports refuse rather than skip those rows. **Fix:** keep the app on a different NFC name. Dump the data under the stored spelling (`baerly admin dump --collection=<stored name>`) and restore it under an NFC name that is not canonically equivalent to either spelling, as in the entry above.
111
+
112
+ If the log contains both spellings, stop writes and maintenance and keep a copy of the source bucket. Use `baerly admin dump --recover-legacy-names --collection=<exact stored name>` with the same bucket, app, and tenant flags to recover each spelling separately into different fresh collections. Recovery keeps rows, updates, and deletes separate even when `_id`s overlap. It requires a snapshot naming the selected spelling or no snapshot; an opposite-spelling snapshot is refused. Rows discarded by older compaction cannot be reconstructed, so historical completeness is not guaranteed.
113
+
114
+ ### Resending an auto-ID insert over HTTP (`mintedId`)
115
+
116
+ **Cause:** an HTTP client minted the insert's `_id` and resent the insert after losing the first response. Without a signal the resend is a caller-supplied duplicate and gets `409 AlreadyExists`, though the row is the client's own. **Fix:** send the minted id in both places, `{ "doc": { "_id": m, ... }, "mintedId": m }`. A resend that finds a live row for `m` holding the same document (key order ignored) returns the original `201 { "_id": m }` and commits nothing; a different current body gets `409 AlreadyExists`. Deletion permits reinsertion; updating back to the original body permits replay. Calling `insert(doc)` again is a new operation and mints a new auto-ID, rather than retransmitting the constructed request. `mintedId` must be a canonical UUIDv7 equal to `doc._id`, else `400 SchemaError`, so a human-chosen id like `"migration-x"` cannot opt in. Leave `mintedId` out whenever you chose the `_id`: an insert without it keeps strict `AlreadyExists` on any live row, even an identical one, which is what makes `insert({ _id: "migration-x", done: true })` a run-once guard with a single winner. A server that predates the field reads only `doc` and answers the resend `409`, never with a second row. In-process `Collection.insert` takes no such flag. A minted replay is an equality oracle: anyone who can insert into the collection learns whether the row stored under an `_id` equals the body they sent (`201`) or not (`409`).
117
+
118
+ ### AmbiguousCommit recovery
119
+
120
+ `AmbiguousCommit` (HTTP 409) means a committing create may be durable, but its outcome could not be resolved. It is not retriable by default. `err._id` names the affected row, including the id an auto-ID insert minted. Re-read that row and compare it with the intended state. A matching row can help reconcile the outcome; absence does not prove failure, because a send may still complete or a later write may have superseded it.
121
+
122
+ ```ts
123
+ const tickets = db.collection("tickets");
124
+ try {
125
+ await tickets.insert({ title: "hi" });
126
+ } catch (err) {
127
+ if (!(err instanceof BaerlyError) || err.code !== "AmbiguousCommit" || !err._id) {
128
+ throw err;
129
+ }
130
+ if ((await tickets.get(err._id)) === undefined) {
131
+ // The same `_id` targets the same row, never a second document.
132
+ await tickets.insert({ _id: err._id, title: "hi" }).catch((retryErr: unknown) => {
133
+ // `AlreadyExists`: the first attempt landed after the re-read;
134
+ // re-read and compare rather than inserting under a new `_id`.
135
+ if (!(retryErr instanceof BaerlyError) || retryErr.code !== "AlreadyExists") {
136
+ throw retryErr;
137
+ }
138
+ });
139
+ }
140
+ }
141
+ ```
142
+
143
+ Retrying is an explicit at-least-once choice and may repeat logical work: a same-`_id` insert retry targets one row and commits only while no live row holds that `_id`, but a retried `update` or `replace` can still overwrite a concurrent change to it. For bulk mutations, rows before the ambiguous row are already applied and `err._id` names the ambiguous one, but no partial-progress count is returned; inspect the affected rows before deciding whether to resume.
37
144
 
38
145
  ### `db.collection(name).insertOne(...)` / `.find(...)` is not a function
39
146
 
40
- **Cause:** Mongo muscle memory. No such method.
41
- **Fix:** `db.collection(name).insert(row)` and
42
- `.where({ field: value }).all()` / `.where(q => q.gte("count", 1)).all()`.
147
+ **Cause:** Mongo muscle memory. No such method. **Fix:** `db.collection(name).insert(row)` and `.where({ field: value }).all()` / `.where(q => q.gte("count", 1)).all()`.
43
148
 
44
149
  ### `.useIndex(...)` / `.hint(...)` is not a function
45
150
 
46
- **Cause:** SQL/ORM muscle memory. No such method.
47
- **Fix:** the planner picks the index automatically from the
48
- `IndexDefinition`s registered in `baerly.config.ts`.
151
+ **Cause:** SQL/ORM muscle memory. No such method. **Fix:** use `.where(...)` directly. Reads always fold the authoritative snapshot and log; declared `indexes` do not change how a read runs.
152
+
153
+ ### `compact` / `runGc` / `CLOUDFLARE_FREE_TIER` is not exported from `/maintenance`
154
+
155
+ **Cause:** `@gusto/baerly-storage/maintenance` exports one function, `runScheduledMaintenance`, addressed by collection. Its phases, host tiers and `current.json` keys are internal. **Fix:** `runScheduledMaintenance({ storage, app, tenant, collection }, { tier })`, `tier` being the `BAERLY_MAINTENANCE_PROFILE` value (`"cf-free"`, `"cf-paid"`, or the unbounded default `"node"`). A schedule is optional: every write already runs bounded maintenance.
49
156
 
50
157
  ### `BaerlyError code="InvalidConfig"` — `baerly: no auth configured`
51
158
 
52
159
  **Full message:** `baerly: no auth configured. Set \`auth\` in baerly.config.ts ("none", "shared-secret") or pass \`verifier\` on the adapter factory.`
53
160
 
54
- **Cause:** the adapter resolved no `Verifier`.
55
- **Fix:** set `auth` in `baerly.config.ts` (`"none"` or `"shared-secret"`)
56
- or pass `verifier:` on the adapter factory.
161
+ **Cause:** the adapter resolved no `Verifier`. **Fix:** set `auth` in `baerly.config.ts` (`"none"` or `"shared-secret"`) or pass `verifier:` on the adapter factory.
57
162
 
58
163
  ### `BaerlyError code="InvalidConfig"` — `SHARED_SECRET env is empty/unset`
59
164
 
60
165
  **Full message:** `baerly: auth="shared-secret" but SHARED_SECRET env is empty/unset. Cloudflare: \`wrangler secret put SHARED_SECRET\`, or add to .dev.vars for local dev. Node: set in process env.`
61
166
 
62
- **Cause:** `auth: "shared-secret"` was set but the `SHARED_SECRET`
63
- environment variable is missing or empty at startup.
64
- **Fix:** set the `SHARED_SECRET` env (`wrangler secret put SHARED_SECRET`
65
- on Cloudflare, `.dev.vars` for local dev, process env on Node).
167
+ **Cause:** `auth: "shared-secret"` was set but the `SHARED_SECRET` environment variable is missing or empty at startup. **Fix:** set the `SHARED_SECRET` env (`wrangler secret put SHARED_SECRET` on Cloudflare, `.dev.vars` for local dev, process env on Node).
66
168
 
67
169
  ### `BaerlyError code="InvalidConfig"` — `Refusing to start: no durable storage configured` / `Refusing to use in-memory storage`
68
170
 
69
- **Cause:** a deployed process (`NODE_ENV=production` or a known PaaS marker)
70
- reached storage selection with no real bucket configured — or constructed
71
- `MemoryStorage` there. In-memory "succeeds" into RAM and vanishes on every
72
- restart; local-fs is single-process with no cross-process CAS. Both are
73
- refused in a deployment so the failure is loud at boot, not silent data loss
74
- in production.
75
- **Fix:** don't hand-roll storage selection — call `resolveStorageFromEnv()`
76
- from `@gusto/baerly-storage/node` (`R2_ACCOUNT_ID` → R2, `BUCKET` → S3, else
77
- local-fs in dev) and configure a bucket: `BUCKET` + `AWS_ACCESS_KEY_ID` +
78
- `AWS_SECRET_ACCESS_KEY` (add `R2_ACCOUNT_ID` for R2). To catch an
79
- unreachable or CAS-broken bucket at boot rather than on the first write,
80
- `await assertStorageReachable(storage)`. Intentionally ephemeral (a throwaway
81
- demo)? Opt in explicitly: `new MemoryStorage({ ephemeral: true })` or
82
- `BAERLY_ALLOW_EPHEMERAL_STORAGE=true`.
171
+ **Cause:** a deployed process (`NODE_ENV=production` or a known PaaS marker) reached storage selection with no real bucket configured — or constructed `MemoryStorage` there. In-memory "succeeds" into RAM and vanishes on every restart; local-fs is single-process with no cross-process CAS. Both are refused in a deployment so the failure is loud at boot, not silent data loss in production. **Fix:** don't hand-roll storage selection — call `resolveStorageFromEnv()` from `@gusto/baerly-storage/node` (`R2_ACCOUNT_ID` → R2, `BUCKET` → S3, else local-fs in dev) and configure a bucket: `BUCKET` + `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (add `R2_ACCOUNT_ID` for R2). To catch an unreachable or CAS-broken bucket at boot rather than on the first write, `await assertStorageReachable(storage)`. Intentionally ephemeral (a throwaway demo)? Opt in explicitly: `new MemoryStorage({ ephemeral: true })` or `BAERLY_ALLOW_EPHEMERAL_STORAGE=true`.
83
172
 
84
173
  ### `BaerlyError code="UseQueryAwaitedRecorder"`
85
174
 
86
- **Cause:** awaited a terminal (`.get`/`.first`/`.all`/`.count`) inside a
87
- `useQuery` callback. The recorder is synchronous; awaiting it yields a
88
- sentinel and the next property access throws.
89
- **Fix:** don't `await` in `useQuery` — for compound reads use
90
- `Promise.all` (parallel) or compose two `useQuery` calls with
91
- `useQuery.skip` (dependent). For writes use `useMutation()`.
175
+ **Cause:** awaited a terminal (`.get`/`.first`/`.all`/`.count`) inside a `useQuery` callback. The recorder is synchronous; awaiting it yields a sentinel and the next property access throws. **Fix:** don't `await` in `useQuery` — for compound reads use `Promise.all` (parallel) or compose two `useQuery` calls with `useQuery.skip` (dependent). For writes use `useMutation()`.
92
176
 
93
177
  ### `BaerlyError code="UnexpectedWriteInQuery"`
94
178
 
95
- **Cause:** called a write verb (`insert`/`update`/`replace`/`delete`)
96
- inside a `useQuery` callback.
97
- **Fix:** reads go in `useQuery`, writes go in `useMutation()`.
179
+ **Cause:** called a write verb (`insert`/`update`/`replace`/`delete`) inside a `useQuery` callback. **Fix:** reads go in `useQuery`, writes go in `useMutation()`.
98
180
 
99
181
  ## Anti-patterns (compile-clean but wrong)
100
182
 
101
- - Don't reach into `node_modules/@gusto/baerly-storage/dist/` at runtime —
102
- consume the published exports.
183
+ - Don't reach into `node_modules/@gusto/baerly-storage/dist/` at runtime — consume the published exports.
103
184
  - Don't widen branded types (`UUID`, `ContentVersionId`) with `as string`.
104
- - Don't put `SHARED_SECRET` in the SPA bundle — it is server-to-server
105
- only.
106
- - Don't mutate `VerifierResult.tenantPrefix` between the verifier and
107
- `Db.create` — the dispatcher pins the tenant from the verifier's return.
108
- - `z.string().nullable()` in a schema — `DocumentValue` excludes `null`.
109
- - Raw SQL / `WHERE` clauses / hand-built query AST — the only query
110
- surface is the `.where(...)` method chain.
111
- - `.all()` on a hot path — page or cursor-iterate; `.all()` is for
112
- bounded result sets.
113
- - Relying on baerly to cap or scope a read. `GET /v1/c/:collection` (and
114
- `.all()`) returns the **whole collection** — there is no default row
115
- cap, and auth pins a tenant, not a row owner. Scope non-owner reads in
116
- your own route: inject a `where owner_id = <verified id>` predicate
117
- (ideally index-backed) and clamp `limit = min(requested ?? MAX, MAX)`.
118
- Rejecting `?limit` backfires — it forces the uncapped path. See
119
- `docs/guide/auth.md` § Authorization Boundary.
185
+ - Don't put `SHARED_SECRET` in the SPA bundle — it is server-to-server only.
186
+ - Don't mutate `VerifierResult.tenantPrefix` between the verifier and `Db.create` — the dispatcher pins the tenant from the verifier's return.
187
+ - `z.string().nullable()` in a schema: the runtime stores the `null`, but the typed write contract excludes it (`DocumentValue` has no `null`). Use `.optional()`; see the TS2322 entry above.
188
+ - Raw SQL / `WHERE` clauses / hand-built query AST — the only query surface is the `.where(...)` method chain.
189
+ - Paging or cursor-iterating `.all()`: there is no offset, page or cursor API. Bound every read instead: scope it with `.where(...)` and cap it with `.limit(n)` (plus `.order(...)` for a stable top N). Each read still folds the whole collection, so a limit caps the rows returned, not the work done. Under `baerlyWorker`, a read that needs more work than one request allows is refused with `CapacityExceeded` (see above); other hosts do not bound reads.
190
+ - Relying on baerly to cap or scope a read. `GET /v1/c/:collection` (and `.all()`) returns the **whole collection** — there is no default row cap, and auth pins a tenant, not a row owner. Scope non-owner reads in your own route: inject a `where owner_id = <verified id>` predicate and clamp `limit = min(requested ?? MAX, MAX)`. Rejecting `?limit` backfires — it forces the uncapped path. See `docs/guide/auth.md` § Authorization Boundary.
191
+
192
+ ## Recipe — authoring a gated adapter
193
+
194
+ Use this shape to serve the `/v1/*` API from your own server, under your own path, behind your own policy: `createRouter` from `@gusto/baerly-storage/http` does the routing, and your code does everything in front of it. `createRouter` has no auth seam. It serves every request it receives as the tenant of the `Db` you hand it, so the order is fixed:
195
+
196
+ 1. Authenticate first, with a preset `Verifier` from `@gusto/baerly-storage/auth` or your own.
197
+ 2. Take the tenant from the verified identity (`tenantPrefix`), never from the URL, a header or the body.
198
+ 3. Apply your own gate (roles, collection allow-lists) before any `Db` work.
199
+ 4. Build a fresh `Db` per request with `Db.create({ storage, app, tenant, config })`.
200
+ 5. Strip your mount prefix: the router matches `/v1/...` paths.
201
+
202
+ ```ts
203
+ // src/server/db-route.ts — serves /db/v1/* behind a JWT and a role check.
204
+ import { BaerlyError, Db } from "@gusto/baerly-storage";
205
+ import { bearerJwt } from "@gusto/baerly-storage/auth";
206
+ import { createRouter, mapError } from "@gusto/baerly-storage/http";
207
+ import { resolveStorageFromEnv } from "@gusto/baerly-storage/node";
208
+ import config from "../../baerly.config.ts";
209
+
210
+ const PREFIX = "/db";
211
+ const { storage } = resolveStorageFromEnv();
212
+ const verifier = bearerJwt({
213
+ jwks: "https://login.example.com/.well-known/jwks.json",
214
+ issuer: "https://login.example.com/",
215
+ audience: "https://api.example.com/",
216
+ });
217
+
218
+ export async function handleDb(req: Request): Promise<Response> {
219
+ try {
220
+ const verified = await verifier(req); // (1) authenticate first
221
+ if (verified === null) throw new BaerlyError("Unauthorized", "Missing or invalid token");
222
+ const roles = (verified.identity as { roles?: unknown }).roles; // unverified shape
223
+ if (req.method !== "GET" && !(Array.isArray(roles) && roles.includes("editor"))) {
224
+ throw new BaerlyError("AccessDenied", "Writes need the editor role"); // (3) → 403
225
+ }
226
+ const db = Db.create({ storage, app: config.app, tenant: verified.tenantPrefix, config }); // (2, 4)
227
+ const url = new URL(req.url);
228
+ url.pathname = url.pathname.slice(PREFIX.length); // (5) /db/v1/c/notes → /v1/c/notes
229
+ return await createRouter({ db }).fetch(new Request(url, req));
230
+ } catch (err) {
231
+ const { status, envelope } = mapError(err); // verifier and Db.create throws
232
+ return Response.json(envelope, { status });
233
+ }
234
+ }
235
+ ```
236
+
237
+ Dispatch only `/db/*` requests to `handleDb`. The router maps its own errors to the wire envelope (with `Retry-After` on `MaintenancePending`); the `catch` covers what runs before it. `mapError` sends `AccessDenied` with a generic message. On Workers, build the storage inside `fetch` with `r2BindingStorage(env.BUCKET)` instead of `resolveStorageFromEnv()`. Authentication picks a tenant, not a row owner; scope reads in the gate too (see [Anti-patterns](#anti-patterns-compile-clean-but-wrong), "Relying on baerly to cap or scope a read").
238
+
239
+ **What the stock adapters add.** `baerlyWorker` and `baerlyNode` do more than run the verifier: they serve `/v1/healthz` and `/v1/spec`, emit the canonical log line, and select the host's maintenance profile. A bare `createRouter` still runs write-tick maintenance on writes, but under the default profile, the smallest one, on every host: its fold ceilings are the Workers Free ones, so a collection refuses growth with `CapacityExceeded` sooner than under `baerlyNode`. It does not read the operator's maintenance settings, and on Workers it folds before the response rather than in `ctx.waitUntil`, and neither budgets storage calls against the invocation's subrequest limit nor bounds reads. When you need that behavior, keep the stock adapter and gate in front of it: pass your policy as its `verifier`, or check the request and strip your prefix before delegating, to `baerlyNode(...).fetch(req)` on Node (see API.md, "Recipe — custom routes in front of `baerlyNode`") or `baerlyWorker(...).fetch(req, env, ctx)` on Workers (see API.md, "Recipe — server-stamped trusted fields").
240
+
241
+ ## Recipe — storage credentials on Node
242
+
243
+ The Node storage factories (`s3Storage`, `r2Storage`, `minioStorage`, `gcsStorage` from `@gusto/baerly-storage/node`) take one `credentials` field: either a static `Credentials` object or a `CredentialsProvider`, an async function returning one. On Workers, use the R2 binding (`r2BindingStorage(env.BUCKET)`) instead; it needs no credentials.
244
+
245
+ ```ts
246
+ type Credentials = {
247
+ readonly accessKeyId: string;
248
+ readonly secretAccessKey: string;
249
+ readonly sessionToken?: string;
250
+ readonly expiration?: Date; // absent ⇒ static
251
+ };
252
+ type CredentialsProvider = () => Promise<Credentials>;
253
+ ```
254
+
255
+ `gcsStorage` signs GOOG4-HMAC-SHA256 with a GCS HMAC key (Cloud Console → Cloud Storage → Settings → Interoperability): pass the access ID as `accessKeyId` and the secret as `secretAccessKey`. Service-account keys, OAuth and ADC are not supported.
256
+
257
+ ### Static credentials
258
+
259
+ ```ts
260
+ import { s3Storage } from "@gusto/baerly-storage/node";
261
+
262
+ export const storage = s3Storage({
263
+ region: process.env["AWS_REGION"] ?? "us-east-1",
264
+ bucket: process.env["BUCKET"]!,
265
+ credentials: {
266
+ accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
267
+ secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
268
+ },
269
+ });
270
+ ```
271
+
272
+ `resolveStorageFromEnv()` builds the same thing from `BUCKET` + `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (plus `R2_ACCOUNT_ID` for R2); use a factory directly when you need a provider below.
273
+
274
+ ### Expiration and refresh
275
+
276
+ A provider is called on the first signed request. The signer caches what it returns until five minutes before `expiration`, then calls the provider again; concurrent requests share one in-flight call, and a rejected call is retried on the next request. A result without `expiration` is cached for the life of the storage handle, so a provider of rotating credentials must return the credentials' real `expiration` on every result; otherwise storage requests start failing once the first credentials expire. As a backstop, an S3 `400 ExpiredToken` or `TokenRefreshRequired` response drops the cached credentials and resends the request once with a fresh provider call; a second such response throws `AccessDenied` naming the S3 code.
277
+
278
+ ### EKS: `fromEks()`
279
+
280
+ ```ts
281
+ import { fromEks, s3Storage } from "@gusto/baerly-storage/node";
282
+
283
+ export const storage = s3Storage({
284
+ region: process.env["AWS_REGION"] ?? "us-east-1",
285
+ bucket: process.env["BUCKET"]!,
286
+ credentials: fromEks(),
287
+ });
288
+ ```
289
+
290
+ `fromEks()` checks the environment on every call: EKS Pod Identity when `AWS_CONTAINER_CREDENTIALS_FULL_URI` is set (it also reads the token file named by `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`), else IRSA when `AWS_WEB_IDENTITY_TOKEN_FILE` is set (it also needs `AWS_ROLE_ARN`, exchanges the token with STS `AssumeRoleWithWebIdentity`, and honors `AWS_ROLE_SESSION_NAME` and `AWS_REGION` / `AWS_DEFAULT_REGION`), else it throws `InvalidConfig`. Pod Identity refuses an `AWS_CONTAINER_CREDENTIALS_FULL_URI` that is not loopback or the ECS / EKS agent address, so the token never leaves the node. To pin one mechanism, use `fromEksPodIdentity()` or `fromWebIdentity()` from the same subpath. All three return `expiration`, so refresh is automatic.
291
+
292
+ ### Your own provider
293
+
294
+ ```ts
295
+ import { type CredentialsProvider, s3Storage } from "@gusto/baerly-storage/node";
296
+
297
+ // Stand-in for your secrets store; it must report when the credentials expire.
298
+ declare function fetchFromVault(): Promise<{
299
+ id: string;
300
+ secret: string;
301
+ token: string;
302
+ expiresAt: string;
303
+ }>;
304
+
305
+ const fromVault: CredentialsProvider = async () => {
306
+ const s = await fetchFromVault();
307
+ return {
308
+ accessKeyId: s.id,
309
+ secretAccessKey: s.secret,
310
+ sessionToken: s.token,
311
+ expiration: new Date(s.expiresAt),
312
+ };
313
+ };
314
+
315
+ export const storage = s3Storage({
316
+ region: "us-east-1",
317
+ bucket: "my-bucket",
318
+ credentials: fromVault,
319
+ });
320
+ ```
321
+
322
+ ### AWS SDK credential providers
323
+
324
+ The `Credentials` shape matches the AWS SDK's `AwsCredentialIdentity`, so any provider from `@aws-sdk/credential-providers` (ECS task roles, EC2 instance metadata, SSO, `~/.aws/config` profiles, the default Node chain) passes through unchanged, `expiration` included. baerly-storage does not depend on the AWS SDK; add `@aws-sdk/credential-providers` to your app when you need one.
325
+
326
+ ```ts
327
+ import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
328
+ import { s3Storage } from "@gusto/baerly-storage/node";
329
+
330
+ export const storage = s3Storage({
331
+ region: process.env["AWS_REGION"] ?? "us-east-1",
332
+ bucket: process.env["BUCKET"]!,
333
+ credentials: fromNodeProviderChain(),
334
+ });
335
+ ```
336
+
337
+ ## Recipe — wrapping the client `fetch`
338
+
339
+ `createBaerlyClient({ fetch: customFetcher })` is the one composable seam for cross-cutting HTTP concerns: logging, tracing, auth refresh. The `Fetcher` type, exported from `@gusto/baerly-storage/client`, is `(req: Request) => Promise<Response>`.
340
+
341
+ Wrappers compose as ordinary JavaScript functions: outermost sees the request first and the response last; innermost is closest to the network.
342
+
343
+ ### Hook callbacks (success / error)
344
+
345
+ ```ts
346
+ import { createBaerlyClient, type Fetcher } from "@gusto/baerly-storage/client";
347
+
348
+ const withHooks =
349
+ (
350
+ next: Fetcher,
351
+ onSuccess: (req: Request, res: Response) => void,
352
+ onError: (req: Request, err: unknown) => void,
353
+ ): Fetcher =>
354
+ async (req) => {
355
+ try {
356
+ const res = await next(req);
357
+ onSuccess(req, res);
358
+ return res;
359
+ } catch (err) {
360
+ onError(req, err);
361
+ throw err;
362
+ }
363
+ };
364
+
365
+ export const client = createBaerlyClient({
366
+ baseUrl: "https://api.example.com",
367
+ fetch: withHooks(
368
+ (req) => globalThis.fetch(req),
369
+ (req, res) => console.info({ url: req.url, status: res.status }),
370
+ (req, err) => console.error({ url: req.url, err }),
371
+ ),
372
+ });
373
+ ```
374
+
375
+ `onSuccess` fires for **any** HTTP response that completes — 4xx and 5xx included, because those are not thrown exceptions. Branch on `res.ok` if you want "2xx only."
376
+
377
+ ### Retries are built in
378
+
379
+ Don't add a retry wrapper. The client calls `fetch` once per attempt, so a wrapper that retries multiplies the client's own attempts. The client already makes up to 3 attempts, with jittered backoff or the server's `Retry-After`:
380
+
381
+ - `GET` requests and auto-ID inserts are resent after a transport failure: a thrown `fetch`, or a 5xx, 408 or 429 response with no error envelope (a proxy or CDN answering for the server). An auto-ID insert keeps its minted `_id`, so a resend replays the first commit instead of adding a row.
382
+ - Every verb is resent after `MaintenancePending` (503), waiting its `retryAfter`.
383
+ - An enveloped `NetworkError` (502) is not resent: the server's storage adapter already retried it.
384
+
385
+ Other writes (an insert with your own `_id`, `update`, `replace`, `delete`) are sent once on a transport failure, because the first attempt may have committed. Decide at the call site whether to repeat one; an `AmbiguousCommit` needs a re-read first (see [AmbiguousCommit recovery](#ambiguouscommit-recovery)). Pass `opts.signal` to bound how long a call, retries included, may take.
386
+
387
+ ### Refresh credentials on 401
388
+
389
+ ```ts
390
+ import type { Fetcher } from "@gusto/baerly-storage/client";
391
+
392
+ export const withAuthRefresh =
393
+ (next: Fetcher, refresh: () => Promise<string>): Fetcher =>
394
+ async (req) => {
395
+ const res = await next(req.clone());
396
+ if (res.status !== 401) return res;
397
+ const token = await refresh();
398
+ const retried = new Request(req, {
399
+ headers: new Headers({
400
+ ...Object.fromEntries(req.headers),
401
+ Authorization: `Bearer ${token}`,
402
+ }),
403
+ });
404
+ return next(retried);
405
+ };
406
+ ```
407
+
408
+ If the refreshed call also returns 401, the wrapper returns that response unchanged — no second retry, avoiding an infinite refresh loop on a stale/revoked token. Wire sign-out / re-auth-prompt into the caller, not into this wrapper. The `req.clone()` is required because a `Request` body is a one-shot stream.
409
+
410
+ ### Long-poll calls (`GET /v1/since`)
411
+
412
+ The long-poll path routes through the same `Fetcher`. Logging and auth-refresh wrappers apply uniformly. If a wrapper needs to distinguish long-poll from one-shot reads, inspect `req.url` for `/v1/since`. Most wrappers don't need to.
413
+
414
+ ### Composition order
415
+
416
+ The outer wrapper sees what the inner one does: `withHooks(withAuthRefresh(fetch, refresh), …)` observes only the final response of a refreshed call, while `withAuthRefresh(withHooks(fetch, …), refresh)` observes both the 401 and the retried call. Pick by what you want to observe.
417
+
418
+ ## Recipe — scheduled maintenance
419
+
420
+ Maintenance is automatic and write-triggered, with no cron, sidecar, scheduler, timer, lock or app-config knob, identically on every host. Every write runs a bounded GC slice inline plus a go/no-go compaction fold bounded by a fold-size ceiling whose default is safe on every tier. A size-ratio threshold means idle buckets pay nothing. Concurrent folds are safe without coordination: the commit is a compare-and-swap, so a fold that loses to a concurrent write is discarded and its leftover swept by GC. On Cloudflare the fold is deferred past the response via `ctx.waitUntil`; everywhere else it runs inline. **Reads are pure**: they never run maintenance, so the published idle-reader cost bound holds.
421
+
422
+ A bucket maintains itself as long as it takes writes. A bucket served read-only does not auto-compact and pays a small, bounded replay: fine at small scale, a signal to graduate once a collection is large. The repository's `docs/spec/scale-ceilings.md` owns the per-tier envelope and `docs/about/graduation.md` the `BAERLY_MAINTENANCE_*` operator env vars (you almost never need them).
423
+
424
+ A schedule is optional. To also run maintenance on one (useful for a collection served mostly read-only), call `runScheduledMaintenance` once per collection. `tier` is the `BAERLY_MAINTENANCE_PROFILE` value: `"cf-free"` or `"cf-paid"` caps the pass to fit one Workers invocation on that plan, and `"node"` (the default) is unbounded. Run one collection per Cloudflare invocation: shard the schedule or persist a collection cursor instead of looping tenants or collections.
425
+
426
+ ```ts
427
+ import { runScheduledMaintenance } from "@gusto/baerly-storage/maintenance";
428
+
429
+ const target = { storage, app, tenant, collection: "notes" };
430
+ const res = await runScheduledMaintenance(target); // Node
431
+ // res: { folded, deferred?: { reason }, gcDeleted, pending }
432
+ await runScheduledMaintenance(target, { tier: "cf-paid" }); // a Workers Paid cron
433
+ ```
434
+
435
+ One whole pass fits an invocation on Workers Free with the R2 binding and on Workers Paid. S3 storage on Workers needs Paid with `BAERLY_MAINTENANCE_PROFILE=cf-paid`.
436
+
437
+ Node and Cloudflare Paid scheduled passes fold any pending write, so repeated passes drain a low-write collection to zero. Cloudflare Free folds only when at least 20 entries are pending, one 20-entry slice per pass; a remaining tail of 1–19 entries stays unfolded until more writes arrive.
120
438
 
121
439
  ## Where to look next
122
440
 
@@ -9,7 +9,7 @@ This file is generated at build time from each dependency's own LICENSE
9
9
  file and is not hand-maintained.
10
10
 
11
11
  ==============================================================================
12
- @hono/node-server@2.0.6
12
+ @hono/node-server@2.1.8
13
13
  License: MIT
14
14
  Repository: git+https://github.com/honojs/node-server.git
15
15
 
@@ -36,7 +36,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
36
36
  SOFTWARE.
37
37
 
38
38
  ==============================================================================
39
- @logtape/logtape@2.2.4
39
+ @logtape/logtape@2.4.2
40
40
  License: MIT
41
41
  Repository: git+https://github.com/dahlia/logtape.git
42
42
 
@@ -62,7 +62,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
62
62
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
63
63
 
64
64
  ==============================================================================
65
- @rgrove/parse-xml@4.2.1
65
+ @rgrove/parse-xml@5.2.0
66
66
  License: ISC
67
67
  Repository: https://github.com/rgrove/parse-xml.git
68
68
 
@@ -135,7 +135,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
135
135
  SOFTWARE.
136
136
 
137
137
  ==============================================================================
138
- hono@4.12.27
138
+ hono@4.13.19
139
139
  License: MIT
140
140
  Repository: git+https://github.com/honojs/hono.git
141
141
 
@@ -162,7 +162,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
162
162
  SOFTWARE.
163
163
 
164
164
  ==============================================================================
165
- jose@6.2.3
165
+ jose@6.2.17
166
166
  License: MIT
167
167
  Repository: panva/jose
168
168
 
@@ -215,24 +215,3 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
215
215
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
216
216
  SOFTWARE.
217
217
 
218
- ==============================================================================
219
- picocolors@1.1.1
220
- License: ISC
221
- Repository: alexeyraspopov/picocolors
222
-
223
- ISC License
224
-
225
- Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
226
-
227
- Permission to use, copy, modify, and/or distribute this software for any
228
- purpose with or without fee is hereby granted, provided that the above
229
- copyright notice and this permission notice appear in all copies.
230
-
231
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
232
- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
233
- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
234
- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
235
- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
236
- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
237
- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
238
-