@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
@@ -1,1113 +0,0 @@
1
- import { f as DocumentData, m as JSONValue, p as DocumentValue } from "./app-config-DyiFK3_k.js";
2
- //#region packages/protocol/src/errors.d.ts
3
- /**
4
- * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they
5
- * survive cross-realm boundaries (e.g. a Web Worker) and so callers can
6
- * pattern-match with grep-friendly equality.
7
- */
8
- type BaerlyErrorCode = /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */"InvalidConfig" /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */ | "NetworkError" /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */ | "AccessDenied" /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */ | "InvalidResponse" /** Internal invariant violation — should not be reachable. File a bug. */ | "Internal"
9
- /**
10
- * Document body failed schema validation. Emitted by the table-API
11
- * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when
12
- * the body is not valid JSON or contains an array where
13
- * `DocumentValue` is required; also emitted when a collection has a
14
- * declared `SchemaValidator` (via `Db.create({ collections })`) and
15
- * the bound schema rejects the doc. In the schema-rejection case the
16
- * error carries an `issues` array describing each failure. HTTP layer
17
- * maps this to 400.
18
- */
19
- | "SchemaError"
20
- /**
21
- * Write conflicted with current state: CAS retry budget exhausted,
22
- * duplicate caller-supplied `_id`, or an already-existing guarded
23
- * storage key. Check `BaerlyError.retriable` to decide whether the
24
- * same logical operation should be retried.
25
- */
26
- | "Conflict"
27
- /**
28
- * `Verifier` returned no identity. HTTP server maps to 401.
29
- * Code is reserved here so the union locks.
30
- */
31
- | "Unauthorized"
32
- /**
33
- * The addressed resource does not exist. HTTP server maps to 404.
34
- * Emitted by the row-by-id read / update / delete handlers in
35
- * `packages/server/src/http/router.ts` when the predicate
36
- * `{ _id }` matches zero rows. Not a protocol invariant —
37
- * callers may retry after creating the resource or treat as a
38
- * miss depending on intent. The CLI maps this to the generic
39
- * exit-2 "storage error" bucket, not the exit-3 "protocol
40
- * invariant" bucket.
41
- */
42
- | "NotFound"
43
- /**
44
- * Request body exceeded the server's size cap. HTTP server maps
45
- * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from
46
- * `packages/server/src/http/router.ts`). The Node adapter
47
- * enforces during the `node:http` stream pump so the process
48
- * never materializes a multi-MiB body; Workers also rely on
49
- * platform-side caps (16 MB free / 100 MB paid).
50
- */
51
- | "PayloadTooLarge"
52
- /**
53
- * A predicate is structurally well-formed but contradicts itself —
54
- * no document can match. Emitted by `validateWire` and
55
- * `mergePredicateWires`. Triggers:
56
- * - `{ clauses: [{op:"in", field:"priority", value:[]}] }` (empty `in` set)
57
- * - an `eq` clause with a value outside the residual interval
58
- * established by range clauses on the same field
59
- * - merging `{op:"gt", value:10}` with `{op:"lt", value:5}` on the
60
- * same field (empty interval)
61
- * - merging two `in` clauses on the same field with empty intersection
62
- *
63
- * Conflicting equality across clauses (`eq:"open"` + `eq:"closed"` on
64
- * the same field) surfaces as `InvalidConfig` rather than this code —
65
- * the merger treats it as a caller-side configuration bug, not an
66
- * algebraic contradiction.
67
- *
68
- * The HTTP layer treats this as a 400 (caller error). The distinct
69
- * code lets downstream code short-circuit empty-by-construction
70
- * without re-running the validator or parsing messages.
71
- */
72
- | "UnsatisfiablePredicate"
73
- /**
74
- * A `useQuery` callback awaited a recorder terminal
75
- * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per
76
- * render to capture the chain shape; it cannot survive an `await`
77
- * because the proxy doesn't proxy across microtask boundaries. The
78
- * recorder's terminal returns a thenable whose `.then` throws this
79
- * error synchronously, converting what would otherwise be a silent
80
- * spinner-hang into a render-time error the hook surfaces as
81
- * `status: "error"`. Companion `baerly/no-await-in-use-query` lint
82
- * flags the pattern at edit time. For compound reads, use
83
- * `Promise.all` (parallel) or compose two `useQuery` calls with
84
- * `useQuery.skip` (dependent).
85
- */
86
- | "UseQueryAwaitedRecorder"
87
- /**
88
- * A write method (`.insert`/`.update`/`.replace`/`.delete`) was
89
- * called on the recorder inside a `useQuery` callback. Writes
90
- * inside reads are a programming error; the recorder rejects them
91
- * synchronously from the discovery pass, before any I/O fires. Use
92
- * `useMutation()` instead.
93
- */
94
- | "UnexpectedWriteInQuery"
95
- /**
96
- * A `useMutation()` callback rejected with a non-`BaerlyError`
97
- * throwable. The hook wraps the original throw under this code so
98
- * the `error` slot is always a `BaerlyError`; the original value
99
- * is preserved on `.cause`.
100
- */
101
- | "MutationFailed";
102
- /**
103
- * The single error class thrown by baerly-storage. Discriminate by `code`, not
104
- * `instanceof`: the code string survives `JSON.stringify` round-trips
105
- * across Worker / iframe / postMessage realm boundaries, where each
106
- * realm has its own `BaerlyError` constructor identity. IDB-restored
107
- * writes can replay across realms, so `instanceof` would spuriously
108
- * fail on a structurally-identical error from another realm.
109
- *
110
- * @example
111
- * ```ts
112
- * try {
113
- * await db.collection("tickets").insert({ title: "hi" });
114
- * } catch (err) {
115
- * if (err instanceof BaerlyError && err.code === "Conflict") {
116
- * // Check err.retriable; CAS can retry, duplicate _id cannot.
117
- * }
118
- * throw err;
119
- * }
120
- * ```
121
- */
122
- declare class BaerlyError extends Error {
123
- readonly code: BaerlyErrorCode;
124
- readonly cause?: unknown;
125
- /**
126
- * Structured field-path issues, set only when `code === "SchemaError"`.
127
- * Each entry's `path` is a dotted-key list (e.g. `["assignee", "team"]`
128
- * or `["items", 3, "qty"]`) that targets the offending field on the
129
- * input document. `message` is the validator-emitted human string.
130
- *
131
- * The HTTP layer's `mapError` renders these into the 400 body via
132
- * the existing `HttpErrorEnvelope`; older callers that don't know
133
- * about `issues` see a plain message-only error and stay correct.
134
- */
135
- readonly issues?: ReadonlyArray<{
136
- readonly path: ReadonlyArray<string | number>;
137
- readonly message: string;
138
- }>;
139
- /**
140
- * Raw HTTP status, set only by the client-side wire decoder when
141
- * inflating an `HttpErrorEnvelope` into this class. Server-side
142
- * throws never set it (the HTTP layer's `mapError` derives the
143
- * outbound status from `code`). Useful for diagnostics — e.g. to
144
- * distinguish 404-as-"no such row" from 404-as-"route not found".
145
- * Discriminate by `code` for behavior; reach for `status` only when
146
- * you genuinely need the wire value.
147
- */
148
- readonly status?: number;
149
- /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */
150
- readonly resolution?: string;
151
- private readonly retriableOverride;
152
- /**
153
- * Whether this error instance is retriable. Defaults from `code`, but
154
- * context-sensitive throw sites can override it.
155
- */
156
- get retriable(): boolean;
157
- constructor(code: BaerlyErrorCode, message: string, cause?: unknown, issues?: ReadonlyArray<{
158
- readonly path: ReadonlyArray<string | number>;
159
- readonly message: string;
160
- }>, status?: number, resolution?: string, retriableOverride?: boolean);
161
- }
162
- //#endregion
163
- //#region packages/protocol/src/storage/types.d.ts
164
- /**
165
- * Object-storage abstraction. The protocol kernel writes through
166
- * this and only this. Implementations: in-memory (testing), S3 HTTP
167
- * and native GCS HTTP (production), R2 binding (production), local-fs
168
- * (dev).
169
- *
170
- * Cancellation: every method accepts an optional AbortSignal.
171
- * Implementations should respect it where feasible; consumers may
172
- * ignore it. We thread it through from the start so we don't have
173
- * to retrofit cancellation later.
174
- *
175
- * Encoding: bodies are `Uint8Array` (works in Workers + Node 24+),
176
- * not `Buffer`. Result types are `readonly` — the kernel doesn't
177
- * mutate what storage returns.
178
- *
179
- * Not-found is signalled by `null` (single discriminator), not by
180
- * throwing. Other failure modes throw `BaerlyError`.
181
- */
182
- interface Storage {
183
- /**
184
- * Fetch a single object. Returns `null` on not-found (404
185
- * semantics). With `ifNoneMatch`, returns `null` if the current
186
- * ETag matches (304 semantics — caller's cached copy is current).
187
- * With `versionId`, fetches a specific historical version (only
188
- * meaningful on a versioned S3 bucket; non-versioning impls may
189
- * ignore). Other failure modes throw `BaerlyError`.
190
- */
191
- get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null>;
192
- /**
193
- * Write a single object. Returns the new ETag and, when the
194
- * underlying transport surfaces it, the server's response time
195
- * as `serverDate` (S3's `Date` header). The kernel uses
196
- * `serverDate` to track adaptive clock-skew; impls may return
197
- * `undefined` if no server clock is available. Use `ifMatch` for
198
- * compare-and-swap (write only if the current ETag matches), or
199
- * `ifNoneMatch: "*"` for create-only (write only if no object
200
- * exists). Conflicts throw `BaerlyError` with HTTP 412 semantics.
201
- */
202
- put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult>;
203
- /**
204
- * Delete a single object. Idempotent: deleting a missing key is
205
- * not an error.
206
- */
207
- delete(key: string, opts?: {
208
- signal?: AbortSignal;
209
- }): Promise<void>;
210
- /**
211
- * Lex-asc enumeration of keys with the given prefix. Pagination is
212
- * implementation-internal; consumers iterate until exhaustion or
213
- * `maxKeys`. `startAfter` (exclusive) is a strict-greater cursor.
214
- */
215
- list(prefix: string, opts?: {
216
- startAfter?: string;
217
- maxKeys?: number;
218
- signal?: AbortSignal;
219
- }): AsyncIterable<StorageListEntry>;
220
- }
221
- interface StorageGetOptions {
222
- readonly ifNoneMatch?: string;
223
- /**
224
- * Pin to a specific historical version. Maps to S3's
225
- * `?versionId=…` query parameter on versioned buckets. Impls that
226
- * don't model versions may ignore.
227
- */
228
- readonly versionId?: string;
229
- readonly signal?: AbortSignal;
230
- }
231
- interface StorageGetResult {
232
- readonly body: Uint8Array;
233
- readonly etag: string;
234
- /**
235
- * S3 `x-amz-version-id` of the returned object on versioned
236
- * buckets; `undefined` for unversioned reads or impls without
237
- * native versioning.
238
- */
239
- readonly versionId?: string;
240
- }
241
- interface StoragePutResult {
242
- readonly etag: string;
243
- /**
244
- * Server-reported response time, used by the kernel's adaptive
245
- * clock-skew loop. Set by HTTP-backed impls from the response
246
- * `Date` header; in-memory impls fill in the local wall clock.
247
- * `undefined` if no clock signal is available.
248
- */
249
- readonly serverDate?: Date;
250
- /**
251
- * S3 `x-amz-version-id` of the new object version on versioned
252
- * buckets; `undefined` for unversioned writes or impls without
253
- * native versioning.
254
- */
255
- readonly versionId?: string;
256
- }
257
- interface StoragePutOptions {
258
- /** CAS guard: write only if ETag matches. */
259
- readonly ifMatch?: string;
260
- /** Create-only guard: write only if no object exists. */
261
- readonly ifNoneMatch?: "*";
262
- readonly contentType?: string;
263
- /** Cancel mid-flight; impls should respect when feasible. */
264
- readonly signal?: AbortSignal;
265
- }
266
- interface StorageListEntry {
267
- readonly key: string;
268
- readonly etag: string;
269
- /**
270
- * Server's `Last-Modified` for the listed object, when the backend
271
- * surfaces it. GC uses it to anchor a tombstone's `due_at` to the
272
- * object's server-side write time (`gc.ts`); when absent, GC falls
273
- * back to the local clock (`now()`). It is therefore an optional
274
- * precision hint, never load-bearing for correctness — impls
275
- * without a server clock (e.g. {@link MemoryStorage}) may omit it.
276
- *
277
- * The protocol's clock-skew handling rides on
278
- * {@link StoragePutResult.serverDate} (the write-time server clock),
279
- * not on this field.
280
- */
281
- readonly lastModified?: Date;
282
- }
283
- //#endregion
284
- //#region packages/protocol/src/coordination/current-json.d.ts
285
- /**
286
- * Per-collection control object. CAS-protected. One per
287
- * `(tenant, collection)` key — for example
288
- * `<tenant>/<collection>/current.json`. The compactor swaps snapshot
289
- * generations by CAS-writing this object; the Writer reads it on every
290
- * commit to find the snapshot pointer and a non-authoritative
291
- * tail-probe floor. The numbered log create mints the next integer
292
- * `seq`; no commit-path code CAS-advances `current.json`.
293
- *
294
- * The schema is forward-compatible: adding a new optional field is
295
- * non-breaking. Renaming or removing a field requires bumping
296
- * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject
297
- * unknown major versions with `BaerlyError{code:"InvalidResponse"}`.
298
- */
299
- interface CurrentJson {
300
- /**
301
- * Schema version. Today: `3`. Bump on any breaking change to
302
- * field semantics; readers must reject unknown major versions
303
- * with `BaerlyError{code:"InvalidResponse"}`.
304
- */
305
- schema_version: 3;
306
- /**
307
- * Pointer to the current snapshot generation. `null` before the
308
- * first compaction has produced a snapshot — readers fall back
309
- * to log-only replay. Shape is opaque-to-this-module; the
310
- * compactor owns its interpretation.
311
- */
312
- snapshot: string | null;
313
- /**
314
- * Non-authoritative monotone lower bound on the committed log tail.
315
- * The authoritative tail is discovered by forward-probe (log-tail.ts);
316
- * never trust this as the head. Durable advancement is owned by
317
- * compaction folds, write-tick tail refreshes, and explicit
318
- * operator/import paths; ordinary writer commits do not refresh it.
319
- */
320
- tail_hint: number;
321
- /**
322
- * Lowest live log sequence number. Entries with `seq < log_seq_start`
323
- * have been folded into the snapshot at {@link snapshot} (or, if
324
- * `snapshot === null`, have been dropped because the collection was
325
- * truncated). Readers walk `[log_seq_start, tail_hint)`. Always
326
- * present on disk — fresh `current.json` writes via
327
- * {@link createCurrentJson} set this to `0`; the compactor advances
328
- * it on every fold.
329
- *
330
- * Invariants the compactor maintains:
331
- * - `0 <= log_seq_start <= tail_hint`
332
- * - `log_seq_start` advances monotonically (never decreases)
333
- * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot
334
- * covers `[0, log_seq_start)`)
335
- */
336
- log_seq_start: number;
337
- /**
338
- * Embedded write-fence epoch. See {@link WriterFence}.
339
- */
340
- writer_fence: WriterFence;
341
- /** Byte size of the snapshot pointed to by `snapshot`. */
342
- snapshot_bytes: number;
343
- /**
344
- * Row count of the snapshot (= compactor `base.size`, free). With
345
- * `tail_hint - log_seq_start` (trusted tail entries) this gives the
346
- * fold's entry count for the ENTRY ceiling `E`. Seeded 0.
347
- */
348
- snapshot_rows: number;
349
- /**
350
- * Optional compactor-stamped mean folded-entry byte size. Maintenance
351
- * derives live-tail bytes as `entry_count × mean_entry_bytes` without
352
- * an exact stored counter; absent until first fold.
353
- */
354
- mean_entry_bytes?: number;
355
- /**
356
- * Baseline for rate-limiting the graduation defer-warn off SHARED
357
- * durable state, not per-isolate memory. The warn fires when the
358
- * observed/probed tail minus `last_warned_seq` reaches
359
- * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes
360
- * `last_warned_seq` to the observed/probed tail. Absent → 0.
361
- */
362
- last_warned_seq?: number;
363
- }
364
- /**
365
- * Fence-token sub-shape embedded in {@link CurrentJson}. The
366
- * monotonically-bumped `epoch` is the only safety-critical field —
367
- * `owner` is informational and may be missing in older records;
368
- * `claimed_at` is the server response date at claim time, NOT the
369
- * local clock; `lease_until` is reserved for manual rotation and is not
370
- * consumed by the current kernel. Log entries are not stamped with this
371
- * epoch; the fence is dormant authority metadata, not a reader replay
372
- * filter.
373
- *
374
- * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's
375
- * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view
376
- * number. In the earlier two-write commit design, every commit checked
377
- * the epoch before continuing under `current.json` authority. Under
378
- * single-write commit no production path reads or writes the fence.
379
- */
380
- interface WriterFence {
381
- /**
382
- * Monotonic unsigned integer. Bumped only by an explicit
383
- * {@link claimWriter} call — do NOT bump on every cold start, do
384
- * NOT bump on every commit. Under single-write commit this is retained
385
- * as an explicit admin/testing primitive only; no production commit
386
- * path claims or verifies the fence.
387
- */
388
- epoch: number;
389
- /**
390
- * Owner identifier — debug only, NOT consulted for safety.
391
- * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty
392
- * string when claim provenance is unknown (e.g. initial
393
- * creation). Safety derives from `epoch`, not from `owner`.
394
- */
395
- owner: string;
396
- /**
397
- * ISO-8601 timestamp from the `StoragePutResult.serverDate` on
398
- * the successful CAS PUT. **Never use `new Date()` or
399
- * `Date.now()` to populate this field** — under multi-instance
400
- * deployment the local clock may disagree with peers; the
401
- * server's clock is the only one all instances share. Format
402
- * via `serverDate.toISOString()`. The empty string `""` means
403
- * "claim time unknown" — readers MUST treat it as such rather
404
- * than parsing it.
405
- */
406
- claimed_at: string;
407
- /**
408
- * Optional explicit lease horizon, also ISO-8601. Reserved for
409
- * future manual rotation workflows; current code only writes
410
- * the field through if a caller supplies it and does not read
411
- * it.
412
- */
413
- lease_until?: string;
414
- }
415
- /**
416
- * Return shape from {@link readCurrentJson} et al.: the parsed JSON
417
- * plus the ETag needed for a follow-up CAS write.
418
- */
419
- interface CurrentJsonRead {
420
- readonly json: CurrentJson;
421
- readonly etag: string;
422
- }
423
- //#endregion
424
- //#region packages/protocol/src/query/builder.d.ts
425
- /**
426
- * Callback-form predicate builder. Methods append clauses and
427
- * return the same builder for chaining; chained calls AND-merge.
428
- *
429
- * The methods on this interface ARE the supported operator surface.
430
- * Vocabulary additions (`or`, `not`, `regex`, `ne`, `exists`, ...)
431
- * are intentionally absent — calling them is a TS2339 compile
432
- * error, not a runtime rejection. The algebra is conjunction-only in
433
- * perpetuity — see the API surface lock in
434
- * docs/contributing/conventions/change-discipline.md.
435
- *
436
- * @template T - the document shape the predicate is keyed against.
437
- */
438
- interface PredicateBuilder<T extends DocumentData = DocumentData> {
439
- /**
440
- * Strict equality on `field`. Use this for the in-callback
441
- * equality clauses that the object-form would also support;
442
- * mixing `q.eq(...)` with range / `in` clauses in one call is
443
- * the canonical "mixed equality + range" pattern.
444
- */
445
- eq<K extends Path<T>>(field: K, value: PathValue<T, K>): PredicateBuilder<T>;
446
- /**
447
- * Strict greater. `value` must be `string` or `number`; the
448
- * intersection at the type level rejects `boolean` / `null`
449
- * fields at the call site (`q.gt("done", true)` is a TS error
450
- * on a `done: boolean` field).
451
- */
452
- gt<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;
453
- /** Inclusive greater. See {@link gt} for the value-type constraint. */
454
- gte<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;
455
- /** Strict less. See {@link gt} for the value-type constraint. */
456
- lt<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;
457
- /** Inclusive less. See {@link gt} for the value-type constraint. */
458
- lte<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;
459
- /**
460
- * Set membership. Empty array is `UnsatisfiablePredicate` at
461
- * normalise time — the validator emits the error eagerly so the
462
- * caller sees it at the `.where(...)` call site, not later.
463
- */
464
- in<K extends Path<T>>(field: K, values: ReadonlyArray<PathValue<T, K>>): PredicateBuilder<T>;
465
- }
466
- /**
467
- * Argument shape accepted by `.where(...)`. Either the object-literal
468
- * equality form ({@link Predicate}) or a callback that drives a
469
- * {@link PredicateBuilder} and returns it (the chain terminator).
470
- */
471
- type PredicateArg<T extends DocumentData> = Predicate<T> | ((q: PredicateBuilder<T>) => PredicateBuilder<T>);
472
- //#endregion
473
- //#region packages/protocol/src/collection-api.d.ts
474
- /**
475
- * Handle on one collection. The common single-row case lives
476
- * here as direct verbs (`get(id)`, `update(id, patch)`,
477
- * `replace(id, doc)`, `delete(id)`) plus whole-collection reads
478
- * (`first()`, `all()`, `count()`). For bulk-by-predicate mutation —
479
- * or for chained `.where()` / `.order()` / `.limit()` reads — call
480
- * the modifier verbs to get a {@link Query} back.
481
- *
482
- * @template T — the document shape. Documents always carry an
483
- * auto-generated `_id` (UUIDv7); the type system
484
- * treats `_id` as optional on `insert` (server fills
485
- * it in) and required on read.
486
- */
487
- interface Collection<T extends DocumentData = DocumentData> {
488
- readonly name: string;
489
- /**
490
- * First document in the whole collection or `undefined` when the
491
- * collection is empty. Equivalent to `.where({}).first()`.
492
- *
493
- * @example
494
- * ```ts
495
- * const any = await db.collection("tickets").first();
496
- * ```
497
- */
498
- first(): Promise<T | undefined>;
499
- /**
500
- * Every document in the whole collection. Equivalent to
501
- * `.where({}).all()`. No implicit cap — prefer
502
- * `.where(p).limit(n).all()` on large collections.
503
- *
504
- * @example
505
- * ```ts
506
- * const all = await db.collection("tickets").all();
507
- * ```
508
- */
509
- all(): Promise<T[]>;
510
- /**
511
- * Count every row in the collection (equivalent to `.where({}).count()`).
512
- *
513
- * @example
514
- * ```ts
515
- * const total = await db.collection("tickets").count();
516
- * ```
517
- */
518
- count(): Promise<number>;
519
- /**
520
- * Fetch one document by primary key. Returns `undefined` when the
521
- * id is unknown — does not throw `NotFound`.
522
- *
523
- * @example
524
- * ```ts
525
- * const ticket = await db.collection("tickets").get(id);
526
- * if (ticket === undefined) {
527
- * // row not in this collection
528
- * }
529
- * ```
530
- */
531
- get(id: string): Promise<T | undefined>;
532
- /**
533
- * Filter rows. Two shapes:
534
- *
535
- * - **Object literal** — equality only. Top-level, dotted-path,
536
- * or nested-literal sub-predicate.
537
- * - **Callback DSL** — `q => q.eq(...).gt(...).in(...)`. The
538
- * operator vocabulary (`eq` / `gt` / `gte` / `lt` / `lte` /
539
- * `in`) lives here. Chained calls AND-merge inside one
540
- * callback; chained `.where(...).where(...)` AND-merges
541
- * across calls and across shapes.
542
- *
543
- * Methods that do not exist on {@link PredicateBuilder}
544
- * (`or`, `not`, `regex`, `ne`, `exists`, ...) are intentionally
545
- * absent — invoking them is a TS compile error.
546
- *
547
- * @example
548
- * ```ts
549
- * db.collection("tickets").where({ status: "open" }).all();
550
- * db.collection("tickets").where({ "assignee.team": "platform" }).all();
551
- * db.collection("tickets").where(q => q.gte("count", 1).lt("count", 10)).all();
552
- * db.collection("tickets").where(q => q.in("status", ["open", "pending"])).all();
553
- * db.collection("tickets")
554
- * .where({ status: "open" })
555
- * .where(q => q.gte("priority", 5))
556
- * .all();
557
- * ```
558
- */
559
- where(predicate: PredicateArg<T>): Query<T>;
560
- /** Order modifier; last call wins. */
561
- order(spec: OrderSpec<T>): Query<T>;
562
- /** Limit modifier; last call wins. */
563
- limit(n: number): Query<T>;
564
- /**
565
- * Insert a new document. UUIDv7 auto-id on `_id`; caller can
566
- * supply `_id` and the server honours it. Returns the new id.
567
- *
568
- * @throws BaerlyError{code: "Conflict"} — `_id` collision on
569
- * caller-supplied id.
570
- * @throws BaerlyError{code: "SchemaError"} — malformed JSON, or
571
- * schema-validation failure (when a schema is declared
572
- * for the collection via `Db.create({ collections })`).
573
- *
574
- * @example
575
- * ```ts
576
- * const { _id } = await db.collection("tickets").insert({
577
- * status: "open",
578
- * title: "Ship the docs",
579
- * });
580
- * ```
581
- */
582
- insert(doc: Partial<T> & DocumentData): Promise<{
583
- _id: string;
584
- }>;
585
- /**
586
- * JSON-merge-patch (RFC 7386) applied to one row by primary key.
587
- * For predicate-aware bulk mutation, use
588
- * `.where(predicate).update(patch)` on {@link Query}.
589
- *
590
- * @throws BaerlyError{code: "Conflict"} — concurrent write lost
591
- * the CAS race. Caller's choice whether to retry.
592
- * @throws BaerlyError{code: "SchemaError"} — patch produced an
593
- * invalid doc.
594
- *
595
- * @example
596
- * ```ts
597
- * const { modified } = await db.collection("tickets")
598
- * .update(id, { status: "closed" });
599
- * ```
600
- */
601
- update(id: string, patch: Partial<T>): Promise<{
602
- modified: number;
603
- }>;
604
- /**
605
- * Whole-document replace on one row by primary key. Throws
606
- * `BaerlyError{code:"NotFound"}` when no row exists at `id`.
607
- *
608
- * @example
609
- * ```ts
610
- * await db.collection("tickets")
611
- * .replace(id, { _id: id, status: "open", title: "Rewrite" });
612
- * ```
613
- */
614
- replace(id: string, doc: T): Promise<void>;
615
- /**
616
- * Delete one row by primary key. Returns `{ deleted: 0 }` when the
617
- * id is unknown rather than throwing. For predicate-aware bulk
618
- * delete, use `.where(predicate).delete()` on {@link Query}.
619
- *
620
- * @example
621
- * ```ts
622
- * const { deleted } = await db.collection("tickets").delete(id);
623
- * ```
624
- */
625
- delete(id: string): Promise<{
626
- deleted: number;
627
- }>;
628
- }
629
- /**
630
- * Decrementing depth markers for {@link Path}'s recursion cap.
631
- * The default of 4 means dotted paths up to `a.b.c.d.e` are legal;
632
- * `a.b.c.d.e.f` is rejected. Keeps `tsgo` recursion bounded.
633
- * @internal
634
- */
635
- type _PathDepth = [never, 0, 1, 2, 3, 4];
636
- /**
637
- * True when `V` is a value position that should terminate {@link Path}
638
- * recursion. Primitives, `null`, and arrays are leaves — we do not
639
- * descend into array indices via dotted-path keys (the runtime
640
- * evaluator treats every segment as an object key, so `"tags.0"`
641
- * would resolve to `arr["0"]`, which works but is poor DX).
642
- * @internal
643
- */
644
- type _IsPathLeaf<V> = V extends string | number | boolean | null ? true : V extends ReadonlyArray<unknown> ? true : false;
645
- /**
646
- * Strip the string index signature from `T` so {@link Path} can
647
- * iterate over named keys only. Without this, `T = DocumentData &
648
- * UserShape` (the canonical user-doc shape across the kernel)
649
- * collapses `keyof T` to `string` and defeats narrowing.
650
- *
651
- * The pattern `string extends K ? never : K` is the standard TS
652
- * idiom: the parameter of a `[k: string]: …` signature has type
653
- * `string`, so `string extends string` is true for it (excluded);
654
- * any literal key like `"status"` does not extend `string`
655
- * (kept).
656
- * @internal
657
- */
658
- type _StripIndex<T> = { [K in keyof T as string extends K ? never : K]: T[K] };
659
- /**
660
- * Recursively-derived union of every legal dotted-path key over `T`.
661
- * Depth-capped at 5 segments (`a.b.c.d.e` legal, `a.b.c.d.e.f` not) so
662
- * the type checker doesn't blow recursion limits on deep schemas.
663
- *
664
- * When `T` is just `DocumentData` (the default — no user shape
665
- * passed), `_StripIndex<T>` is `{}` and `_Keys<T>` is `never`. In
666
- * that case we fall through to bare `string` keys, preserving
667
- * today's open-keyed default behavior.
668
- * @internal
669
- */
670
- type _AllPaths<T, D extends _PathDepth[number] = 4> = [D] extends [never] ? never : T extends object ? keyof _StripIndex<T> & string extends never ? string : { [K in keyof _StripIndex<T> & string]: _IsPathLeaf<NonNullable<T[K]>> extends true ? K : K | `${K}.${_AllPaths<NonNullable<T[K]>, _PathDepth[D]>}` }[keyof _StripIndex<T> & string] : never;
671
- /**
672
- * Legal dotted-path keys over `T`, with the root-level `_id` filtered
673
- * out so the top-level shape no longer accepts `{ _id: "x" }`. Nested
674
- * `_id` paths (e.g. `"author._id"`) survive — only the bare `"_id"`
675
- * head and any literal `"_id.<rest>"` head are excluded (no
676
- * `_id.<rest>` shape exists today since `_id` is a string leaf, but
677
- * the template-string guard keeps the contract intact if the doc
678
- * shape ever changes).
679
- *
680
- * When `T = DocumentData` (no user-supplied shape), `_AllPaths<T>`
681
- * degrades to bare `string` and the `Exclude<>` wrapper leaves that
682
- * branch unchanged — open-keyed predicates still typecheck.
683
- * @internal
684
- */
685
- type Path<T, D extends _PathDepth[number] = 4> = Exclude<_AllPaths<T, D>, "_id" | `_id.${string}`>;
686
- /**
687
- * Resolves the leaf value type at dotted path `P` through `T`.
688
- * Paired with {@link Path} to type the value side of
689
- * {@link Predicate}. `NonNullable` collapses optional intermediate
690
- * fields so `"a.b"` resolves through `{ a?: { b: number } }`.
691
- *
692
- * Falls back to `DocumentValue` when `P` does not resolve to a
693
- * named key — this only happens when `Path<T> = string` (no user
694
- * shape), in which case any string is legal and the value side
695
- * widens to `DocumentValue` to match today's default.
696
- * @internal
697
- */
698
- type PathValue<T, P extends string> = P extends `${infer H}.${infer R}` ? H extends keyof T ? PathValue<NonNullable<T[H]>, R> : never : P extends keyof T ? T[P] : DocumentValue;
699
- /**
700
- * Recursive partial sub-predicate. The value side of a nested
701
- * predicate clause: every nested key is optional, and recurses into
702
- * objects. `_SubPredicate<{a: number, b: {c: string}}>` admits
703
- * `{a: 1}`, `{b: {c: "x"}}`, and `{a: 1, b: {c: "x"}}` — the same
704
- * open-world matching the matcher delivers at the wire level
705
- * (`{ assignee: { team: "x" } }` matches docs where
706
- * `assignee.team === "x"`, ignoring other keys on `assignee`).
707
- *
708
- * Recurses over `keyof T` directly (NOT through `Path<T>`) so the
709
- * root-level `_id` exclusion does not propagate — a nested `_id`
710
- * names the primary key of an embedded reference and remains
711
- * queryable (`.where({ author: { _id: "u1" } })` typechecks).
712
- * @internal
713
- */
714
- type _SubPredicate<T> = T extends object ? T extends ReadonlyArray<unknown> ? never : { readonly [K in keyof _StripIndex<T> & string]?: T[K] | _SubPredicate<T[K]> } : never;
715
- /**
716
- * Equality-only predicate over a document shape. Object-form
717
- * accepts:
718
- *
719
- * - top-level equality: `{ status: "open" }`
720
- * - dotted-path equality: `{ "assignee.team": "platform" }`
721
- * - nested literal sub-predicates: `{ assignee: { team: "platform" } }`
722
- * — the normaliser flattens to dotted-path `eq` clauses; the
723
- * nested object may carry only a subset of keys (open-world
724
- * matching against the document).
725
- *
726
- * **Operator vocabulary moved to the callback form.** Range / `in`
727
- * / mixed eq+range queries write
728
- * `.where(q => q.gt("priority", 5).in("status", ["open", "pending"]))`.
729
- * The methods on {@link PredicateBuilder} ARE the supported vocabulary
730
- * — there is no `$`-keyed object surface, so a method we did not
731
- * write cannot be called.
732
- *
733
- * **No top-level boolean connectives.** `or` / `not` are
734
- * intentionally absent. Use:
735
- * - `q.in(field, ["a", "b"])` for OR over one field.
736
- * - Chained `.where(p1).where(p2)` for AND across multiple
737
- * predicates — the chain AND-merges.
738
- *
739
- * **Depth cap.** Dotted paths are limited to 5 segments
740
- * (`a.b.c.d.e` legal, `a.b.c.d.e.f` not). Real doc-DB schemas rarely
741
- * exceed 2–3 levels.
742
- */
743
- type Predicate<T extends DocumentData = DocumentData> = { readonly [P in Path<T>]?: PathValue<T, P> extends DocumentValue ? PathValue<T, P> | _SubPredicate<PathValue<T, P>> : DocumentValue };
744
- /** Order specifier. Top-level fields only on day one. */
745
- type OrderSpec<T extends DocumentData = DocumentData> = { readonly [K in keyof T]?: "asc" | "desc" };
746
- /**
747
- * `Collection<T>` after at least one modifier. Carries predicate /
748
- * order / limit state forward. Modifiers compose; verbs are
749
- * terminal. Mutation verbs here are **predicate-aware bulk** — they
750
- * apply to every matching row. For the common single-row case
751
- * (`{ _id }`), prefer {@link Collection.update} / {@link Collection.replace} /
752
- * {@link Collection.delete}.
753
- */
754
- interface Query<T extends DocumentData = DocumentData> {
755
- where(predicate: PredicateArg<T>): Query<T>;
756
- order(spec: OrderSpec<T>): Query<T>;
757
- limit(n: number): Query<T>;
758
- /**
759
- * First match or `undefined`. Equivalent to `.limit(1).all()[0]`.
760
- *
761
- * @example
762
- * ```ts
763
- * const oldest = await db.collection("tickets")
764
- * .where({ status: "open" })
765
- * .order({ commit_ts: "asc" })
766
- * .first();
767
- * ```
768
- */
769
- first(): Promise<T | undefined>;
770
- /**
771
- * Every matching document, respecting `order` and `limit`. No
772
- * implicit cap — callers should always pair `.all()` with
773
- * `.limit(n)` on large collections.
774
- *
775
- * @example
776
- * ```ts
777
- * const open = await db.collection("tickets")
778
- * .where({ status: "open" })
779
- * .order({ commit_ts: "desc" })
780
- * .limit(50)
781
- * .all();
782
- * ```
783
- */
784
- all(): Promise<T[]>;
785
- /**
786
- * Count matching rows. Cheaper than `(await all()).length`.
787
- *
788
- * @example
789
- * ```ts
790
- * const open = await db.collection("tickets")
791
- * .where({ status: "open" })
792
- * .count();
793
- * ```
794
- */
795
- count(): Promise<number>;
796
- /**
797
- * Predicate-aware bulk mutation: JSON-merge-patch (RFC 7386)
798
- * applied to every matching doc. Atomic per row. `null` at any
799
- * field deletes it. For the single-row case prefer
800
- * {@link Collection.update}(id, patch).
801
- *
802
- * @throws BaerlyError{code: "Conflict"} — concurrent write lost
803
- * the CAS race. Caller's choice whether to retry.
804
- * @throws BaerlyError{code: "SchemaError"} — patch produced an
805
- * invalid doc.
806
- *
807
- * @example
808
- * ```ts
809
- * const { modified } = await db.collection("tickets")
810
- * .where({ status: "open" })
811
- * .update({ status: "closed", closed_at: new Date().toISOString() });
812
- * ```
813
- */
814
- update(patch: Partial<T>): Promise<{
815
- modified: number;
816
- }>;
817
- /**
818
- * Predicate-aware bulk delete: every matching document. For the
819
- * single-row case prefer {@link Collection.delete}(id).
820
- *
821
- * @example
822
- * ```ts
823
- * const { deleted } = await db.collection("tickets")
824
- * .where({ status: "closed" })
825
- * .delete();
826
- * ```
827
- */
828
- delete(): Promise<{
829
- deleted: number;
830
- }>;
831
- }
832
- //#endregion
833
- //#region packages/protocol/src/storage/memory.d.ts
834
- /** Options for {@link MemoryStorage}. */
835
- interface MemoryStorageOptions {
836
- /**
837
- * Acknowledge the store is intentionally ephemeral — required to
838
- * construct in a detected deployment ({@link isDeployedEnv}); ignored in
839
- * dev/test. Env equivalent: `BAERLY_ALLOW_EPHEMERAL_STORAGE=true`.
840
- */
841
- ephemeral?: boolean;
842
- }
843
- /**
844
- * In-memory `Storage`. The randomized property test runs against
845
- * this; it must be deterministic — no clocks beyond the caller's,
846
- * no randomness, no I/O.
847
- *
848
- * ETags are a monotonically increasing hex counter formatted in the
849
- * `"<hex>"` shape S3 returns (the surrounding double-quotes are part
850
- * of the ETag header value). Keys are stored verbatim.
851
- *
852
- * **Test-confidence caveat:** every method resolves on the microtask
853
- * queue with no real concurrency, so `put` reads `existing` and writes
854
- * back with no interleaving. MemoryStorage therefore CANNOT exercise the
855
- * compare-and-swap race the writer-fence model depends on — two writers
856
- * contending on one `current.json` always serialize here, so a green run
857
- * is necessary but not sufficient. That race is covered only by the
858
- * randomized integration tests against real S3 / Minio
859
- * (`tests/integration/randomized.test.ts`, `node-minio` variant).
860
- * Relatedly, `serverDate` returns the local clock, not an independent
861
- * server clock (see the `put` return below).
862
- */
863
- declare class MemoryStorage implements Storage {
864
- #private;
865
- constructor(opts?: MemoryStorageOptions);
866
- get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null>;
867
- put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult>;
868
- delete(key: string, opts?: {
869
- signal?: AbortSignal;
870
- }): Promise<void>;
871
- list(prefix: string, opts?: {
872
- startAfter?: string;
873
- maxKeys?: number;
874
- signal?: AbortSignal;
875
- }): AsyncIterable<StorageListEntry>;
876
- /**
877
- * Test-only: drop all objects.
878
- * @internal
879
- */
880
- _clear(): void;
881
- }
882
- //#endregion
883
- //#region packages/protocol/src/verifier.d.ts
884
- /**
885
- * Result of a successful {@link Verifier} call. Returned when the
886
- * request carries valid credentials; replaced with `null` on
887
- * failure.
888
- */
889
- interface VerifierResult {
890
- /**
891
- * Tenant identifier. Must be non-empty and contain no `/` (the
892
- * key-segment separator).
893
- */
894
- readonly tenantPrefix: string;
895
- /**
896
- * Per-Verifier identity payload. Opaque to the protocol kernel;
897
- * the caller-defined shape is whatever the Verifier factory
898
- * chooses to return.
899
- */
900
- readonly identity: unknown;
901
- }
902
- /**
903
- * Auth seam. Given an inbound {@link Request}, return either a
904
- * {@link VerifierResult} (authenticated) or `null` (rejected).
905
- *
906
- * One function, one responsibility — auth in baerly is not a
907
- * middleware chain. The HTTP dispatcher invokes the
908
- * configured `Verifier` exactly once per request, before any
909
- * `Storage` I/O, and either constructs a tenant-scoped `Db` or
910
- * returns 401 `BaerlyError{code:"Unauthorized"}`.
911
- *
912
- * `Request` is the standard `globalThis.Request` — the same shape
913
- * used by Cloudflare Workers, Node 24+, Bun, Deno, and browsers.
914
- * The kernel does **not** depend on `node:http`, `R2Bucket`, or
915
- * any platform binding. Preset factories that need platform
916
- * primitives (e.g. CF Access reads the `Cf-Access-Jwt-Assertion`
917
- * header; SigV4 verifies against a SHA-256 of the body) compose on
918
- * top.
919
- *
920
- * **Workers-types caveat.** `@cloudflare/workers-types` augments the
921
- * global `Request` with the generic parameters
922
- * `Request<CfHostMetadata, Cf>`. A Worker `fetch` handler receives
923
- * `req: Request<CfHostMetadata, Cf>`, but a `Verifier` declared in
924
- * user code resolves to `Request<unknown, CfProperties<unknown>>` —
925
- * the same runtime object, narrowed differently by the type system.
926
- * `baerlyWorker` handles this internally; you only see it if you
927
- * intercept routes in your own Worker `fetch` before forwarding to
928
- * `baerlyWorker`. In that case call the verifier with a one-line
929
- * cast: `await verifier(req as unknown as Request)`. The runtime
930
- * shape is identical; the cast is purely a generic-narrowing nudge.
931
- *
932
- * **Errors.** A `Verifier` SHOULD return `null` for any
933
- * unauthenticated outcome — missing header, bad signature, expired
934
- * token, IP outside allowlist. It MAY throw an `BaerlyError` for
935
- * configuration problems (the IdP's JWKS endpoint is unreachable,
936
- * the shared-secret env var is missing). Throws propagate to the
937
- * dispatcher, which maps them to 500 + `code:"Internal"`. The
938
- * dispatcher distinguishes "auth said no" (null → 401) from "auth
939
- * is broken" (throw → 500) on purpose: the first is a client
940
- * problem, the second is an operator problem.
941
- *
942
- * **Idempotence.** A `Verifier` MUST be safe to call multiple times
943
- * for the same `Request`. Preset factories that decode JWTs cache
944
- * the result on the request via a `WeakMap` if the cost is
945
- * material.
946
- *
947
- * Preset factories — `cloudflareAccess`, `bearerJwt`,
948
- * `sharedSecret` — live in `@gusto/baerly-storage/auth`
949
- * (`packages/server/src/auth/presets/`). The kernel owns the type;
950
- * the server owns the factories.
951
- *
952
- * @example
953
- * ```ts
954
- * import type { Verifier } from "baerly-storage";
955
- *
956
- * // A trivial Verifier that pins every request to one tenant.
957
- * // Useful for tests and single-tenant deployments instead of the
958
- * // preset factories.
959
- * const single: Verifier = async (_req) => ({
960
- * tenantPrefix: "acme-co",
961
- * identity: { kind: "static" },
962
- * });
963
- *
964
- * // A Verifier that reads an `X-Tenant` header and rejects when
965
- * // it's missing. The preset factories produce something like
966
- * // this on top of a real IdP — never trust an `X-Tenant` header
967
- * // in production.
968
- * const headerOnly: Verifier = async (req) => {
969
- * const tenant = req.headers.get("x-tenant");
970
- * if (!tenant) return null;
971
- * return { tenantPrefix: tenant, identity: null };
972
- * };
973
- * ```
974
- */
975
- type Verifier = (req: Request) => Promise<VerifierResult | null>;
976
- //#endregion
977
- //#region packages/protocol/src/log.d.ts
978
- /**
979
- * Debezium-style JSON CDC envelope using pgoutput's message-tag (`I`/`U`/`D`) vocabulary. One per mutation.
980
- *
981
- * `LogEntry` is now a public, versionless/additive-only wire contract:
982
- * 0.3.0 is the public early-access baseline. It is still pre-1.0 and
983
- * soaking, so breaking changes remain possible, but only through an
984
- * explicit compatibility decision, changelog/migration notes, and a
985
- * versioned release. Assume external consumers may exist; do not
986
- * silently rename, remove, or repurpose fields. Consumers must ignore
987
- * unknown keys; new optional fields can be added in compatible releases.
988
- *
989
- * Field requirement matrix:
990
- * - Always: `lsn`, `commit_ts`, `op`, `collection`, `session`,
991
- * `seq`.
992
- * - For I/U/D: `doc_id`.
993
- * - For I/U: `after` (full post-image).
994
- * - Optional: `before` (when `replica_identity === "FULL"`), `key_old`
995
- * (U/D when `replica_identity !== "PATCH_ONLY"`), `origin`.
996
- *
997
- * @see docs/spec/log-entry-shape.md
998
- */
999
- interface LogEntry {
1000
- /**
1001
- * Opaque, monotonic, lex-asc cursor. Shape is
1002
- * `<base32-time>_<session>_<seq>` — minted inside
1003
- * `Writer.commit` (see
1004
- * `packages/server/src/writer.ts`) from `timestamp()` +
1005
- * the per-commit `session` + `countKey(seq)`. Consumers ack and
1006
- * resume from this string.
1007
- *
1008
- * When you have a `LogEntry` in hand, prefer the structured
1009
- * `session` / `seq` fields below over parsing this string. The
1010
- * one place that *does* need to crack it open is the
1011
- * `/v1/since` boundary, where a client resumes from an opaque
1012
- * `next_cursor` and no `LogEntry` is in scope — that path uses
1013
- * `lsnParts` (the kernel-blessed parser) rather than ad-hoc
1014
- * `split("_")`.
1015
- */
1016
- lsn: string;
1017
- /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */
1018
- commit_ts: string;
1019
- /** Insert / Update / Delete. */
1020
- op: "I" | "U" | "D";
1021
- /**
1022
- * Collection name — the pgoutput RELATION analogue. Today this is
1023
- * the collection bound to the `current.json` whose `tail_hint` minted
1024
- * the entry. The table API makes collections first-class.
1025
- */
1026
- collection: string;
1027
- /**
1028
- * The document key (`ref.key`). Required for every op — `op` is
1029
- * `I | U | D` and all three carry it — so the wire type is required,
1030
- * not optional, matching `log-entry-shape.md`.
1031
- */
1032
- doc_id: string;
1033
- /** Required for I, U. The post-image (Debezium's `after`). */
1034
- after?: DocumentData;
1035
- /**
1036
- * The pre-image (Debezium's `before`). Present iff the
1037
- * collection's `replica_identity` is `FULL`. ~2× log size on
1038
- * update-heavy collections; off by default.
1039
- */
1040
- before?: DocumentData;
1041
- /**
1042
- * Pre-image of the primary key. U/D always carry this when
1043
- * `replica_identity` is not `PATCH_ONLY`. (For baerly-storage today,
1044
- * `_id` is the only PK.)
1045
- */
1046
- key_old?: {
1047
- readonly [pk: string]: JSONValue;
1048
- };
1049
- /** ORIGIN analogue — the writer session id. */
1050
- origin?: string;
1051
- /**
1052
- * Causal metadata (baerly-storage-only; no pgoutput analogue). The
1053
- * session id that built the `lsn`. Surfaces here so consumers
1054
- * can dedupe / order without parsing the cursor.
1055
- */
1056
- session: string;
1057
- /**
1058
- * The `log/<seq>` slot this entry occupies — the integer in its
1059
- * `log/<seq>.json` key, minted by `Writer.commit` as the forward-probed
1060
- * collection-log tail (the winning `If-None-Match: "*"` create). One
1061
- * entry per `session`, so this is a per-collection slot, not a
1062
- * per-session counter. Also encoded (descending base-32) as the LSN's
1063
- * third segment — see `lsnParts`.
1064
- */
1065
- seq: number;
1066
- }
1067
- //#endregion
1068
- //#region packages/protocol/src/metrics.d.ts
1069
- /**
1070
- * `MetricsRecorder` — internal emission contract for the six
1071
- * load-bearing kernel metrics. Writer / compactor / GC emit through
1072
- * an instance of this interface; in production the instance is the
1073
- * per-request `RequestScopedMetricsRecorder` on the active
1074
- * `ObservabilityContext`, and emissions flow onto the canonical line
1075
- * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and
1076
- * wrap their workload in `runWithContext` to attach it.
1077
- *
1078
- * Operators do not wire a custom sink against this interface — the
1079
- * operator's view of kernel emissions is the canonical line on
1080
- * stdout (one JSON object per HTTP request).
1081
- *
1082
- * **Naming convention** matches the load-bearing metrics:
1083
- * - `db.write.class_a_ops_per_logical_write` — histogram (recommend p99 alert ~5; not gated).
1084
- * Includes one Class A op per index PUT + index DELETE emitted
1085
- * in the commit's fence. Idle-reader cost is unchanged.
1086
- * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)
1087
- * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)
1088
- * - `db.write.index_ops_per_logical_write` — histogram.
1089
- * `K (PUT) + L (DELETE)` per commit. Per-collection label.
1090
- * - `db.manifest.lag_window_depth` — gauge (alert at >100)
1091
- * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)
1092
- * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)
1093
- * - `db.compact.entries_folded` — histogram (entries folded per run)
1094
- * - `db.gc.swept_total` — counter (labelled by reason)
1095
- *
1096
- * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase
1097
- * snake_case segments. Labels are flat
1098
- * `Readonly<Record<string, string>>` — no numbers, no nested objects.
1099
- *
1100
- * Metric emissions never throw on the hot path; the default
1101
- * `noopMetricsRecorder` cannot throw.
1102
- */
1103
- interface MetricsRecorder {
1104
- /** Monotonically-incrementing event count. */
1105
- counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;
1106
- /** Point-in-time value. */
1107
- gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;
1108
- /** Distribution sample. */
1109
- histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;
1110
- }
1111
- //#endregion
1112
- export { StoragePutOptions as _, MemoryStorage as a, BaerlyErrorCode as b, Predicate as c, CurrentJson as d, CurrentJsonRead as f, StorageListEntry as g, StorageGetResult as h, VerifierResult as i, Query as l, StorageGetOptions as m, LogEntry as n, Collection as o, Storage as p, Verifier as r, OrderSpec as s, MetricsRecorder as t, PredicateArg as u, StoragePutResult as v, BaerlyError as y };
1113
- //# sourceMappingURL=index-CEZKQsKt.d.ts.map