@gusto/baerly-storage 0.5.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 (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  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-Fe8CwB73.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-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  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-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  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 +38 -39
  53. package/dist/dev-vite.js +67 -36
  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-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.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-CuA9Mi3K.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 +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  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-a7PJHBCy.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-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  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-4FfGQNPw.js +22 -0
  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/sigv4-sign-5IUflUD_.js +507 -0
  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-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  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-DoDA-K7d.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-DBV1eQHC.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 +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,536 +0,0 @@
1
- import { t as sharedSecret } from "./shared-secret-DgEicd3x.js";
2
- import { a as decodeJsonBytes, i as readCurrentJson } from "./current-json-C6nhPOm1.js";
3
- import { _ as SHARED_SECRET_MISSING_MESSAGE, h as NO_AUTH_CONFIGURED_MESSAGE } from "./constants-CfeMWQWk.js";
4
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
5
- import { T as logObjectKey, w as probeTailFrom } from "./maintenance-B4Dki6Ig.js";
6
- import { a as runReplaceById, i as runInsert, s as assertPathSegment, t as makeQuery } from "./query-rAtXNQQB.js";
7
- import { t as assertValidStorageKey } from "./key-Di6yyxFu.js";
8
- //#region packages/protocol/src/env.ts
9
- const PAAS_MARKERS = [
10
- "RAILWAY_ENVIRONMENT",
11
- "RENDER",
12
- "FLY_APP_NAME",
13
- "K_SERVICE",
14
- "DYNO",
15
- "KUBERNETES_SERVICE_HOST",
16
- "ECS_CONTAINER_METADATA_URI_V4"
17
- ];
18
- /**
19
- * True when `env` looks like a deployed environment: `NODE_ENV=production`
20
- * or any {@link PAAS_MARKERS} set to a non-empty value. Decides whether a
21
- * non-durable store (in-memory, local-fs) should fail loud instead of
22
- * silently serving a production workload. A CI runner (`CI` set to a
23
- * non-empty, non-`false` value) is never treated as deployed, so PaaS
24
- * markers from an in-cluster CI agent do not trip it.
25
- */
26
- const isDeployedEnv = (env) => {
27
- const inCi = (env["CI"] ?? "") !== "" && env["CI"] !== "false";
28
- return env["NODE_ENV"] === "production" || !inCi && PAAS_MARKERS.some((m) => (env[m] ?? "") !== "");
29
- };
30
- //#endregion
31
- //#region packages/protocol/src/storage/memory.ts
32
- const utf8Encoder = new TextEncoder();
33
- const EPHEMERAL_ENV_OPT_IN = "BAERLY_ALLOW_EPHEMERAL_STORAGE";
34
- const readProcessEnv = () => globalThis.process?.env ?? {};
35
- let warnedEphemeralInDeployment = false;
36
- const assertEphemeralAllowed = (explicitOptIn) => {
37
- const env = readProcessEnv();
38
- if (!isDeployedEnv(env)) return;
39
- if (!explicitOptIn && env[EPHEMERAL_ENV_OPT_IN] !== "true") throw new BaerlyError("InvalidConfig", `Refusing to use in-memory storage in a deployed environment — all data is lost on restart. MemoryStorage is for tests/local dev only; configure a durable bucket (AWS S3 / Cloudflare R2). To intentionally opt in: new MemoryStorage({ ephemeral: true }) or ${EPHEMERAL_ENV_OPT_IN}=true.`);
40
- if (!warnedEphemeralInDeployment) {
41
- warnedEphemeralInDeployment = true;
42
- console.warn("[baerly] in-memory storage in a deployed environment — ALL DATA IS LOST ON RESTART.");
43
- }
44
- };
45
- /**
46
- * Compare two keys by their UTF-8 byte sequences — the order S3 and
47
- * R2 use for `list`. JavaScript's default string sort compares UTF-16
48
- * code units, which diverges from UTF-8 byte order for supplementary-
49
- * plane characters (e.g. emoji sort before high-BMP characters under
50
- * UTF-16 but after them in UTF-8). Using this keeps the in-memory
51
- * reference backend faithful to the real adapters. (All kernel keys
52
- * are ASCII base-32, where the two orders coincide — this only
53
- * matters for adversarial / non-ASCII keys.)
54
- */
55
- const compareKeysUtf8 = (a, b) => {
56
- const ba = utf8Encoder.encode(a);
57
- const bb = utf8Encoder.encode(b);
58
- const n = Math.min(ba.length, bb.length);
59
- for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
60
- return ba.length - bb.length;
61
- };
62
- /**
63
- * In-memory `Storage`. The randomized property test runs against
64
- * this; it must be deterministic — no clocks beyond the caller's,
65
- * no randomness, no I/O.
66
- *
67
- * ETags are a monotonically increasing hex counter formatted in the
68
- * `"<hex>"` shape S3 returns (the surrounding double-quotes are part
69
- * of the ETag header value). Keys are stored verbatim.
70
- *
71
- * **Test-confidence caveat:** every method resolves on the microtask
72
- * queue with no real concurrency, so `put` reads `existing` and writes
73
- * back with no interleaving. MemoryStorage therefore CANNOT exercise the
74
- * compare-and-swap race the writer-fence model depends on — two writers
75
- * contending on one `current.json` always serialize here, so a green run
76
- * is necessary but not sufficient. That race is covered only by the
77
- * randomized integration tests against real S3 / Minio
78
- * (`tests/integration/randomized.test.ts`, `node-minio` variant).
79
- * Relatedly, `serverDate` returns the local clock, not an independent
80
- * server clock (see the `put` return below).
81
- */
82
- var MemoryStorage = class {
83
- #objects = /* @__PURE__ */ new Map();
84
- #etagCounter = 0;
85
- constructor(opts) {
86
- assertEphemeralAllowed(opts?.ephemeral === true);
87
- }
88
- #nextEtag() {
89
- this.#etagCounter += 1;
90
- return `"${this.#etagCounter.toString(16)}"`;
91
- }
92
- async get(key, opts) {
93
- assertValidStorageKey(key);
94
- opts?.signal?.throwIfAborted();
95
- const stored = this.#objects.get(key);
96
- if (stored === void 0) return null;
97
- if (opts?.ifNoneMatch !== void 0 && opts.ifNoneMatch === stored.etag) return null;
98
- return {
99
- body: stored.body,
100
- etag: stored.etag
101
- };
102
- }
103
- async put(key, body, opts) {
104
- assertValidStorageKey(key);
105
- opts?.signal?.throwIfAborted();
106
- const existing = this.#objects.get(key);
107
- if (opts?.ifNoneMatch === "*" && existing !== void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
108
- if (opts?.ifMatch !== void 0) {
109
- if (existing === void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
110
- if (existing.etag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`);
111
- }
112
- const etag = this.#nextEtag();
113
- this.#objects.set(key, {
114
- body,
115
- etag,
116
- ...opts?.contentType !== void 0 && { contentType: opts.contentType }
117
- });
118
- return {
119
- etag,
120
- serverDate: /* @__PURE__ */ new Date()
121
- };
122
- }
123
- async delete(key, opts) {
124
- assertValidStorageKey(key);
125
- opts?.signal?.throwIfAborted();
126
- this.#objects.delete(key);
127
- }
128
- async *list(prefix, opts) {
129
- opts?.signal?.throwIfAborted();
130
- const startAfter = opts?.startAfter ?? "";
131
- const maxKeys = opts?.maxKeys ?? Infinity;
132
- const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0).toSorted(compareKeysUtf8);
133
- let yielded = 0;
134
- for (const key of sorted) {
135
- if (yielded >= maxKeys) return;
136
- opts?.signal?.throwIfAborted();
137
- const stored = this.#objects.get(key);
138
- if (stored === void 0) continue;
139
- yield {
140
- key,
141
- etag: stored.etag
142
- };
143
- yielded += 1;
144
- }
145
- }
146
- /**
147
- * Test-only: drop all objects.
148
- * @internal
149
- */
150
- _clear() {
151
- this.#objects.clear();
152
- this.#etagCounter = 0;
153
- }
154
- };
155
- //#endregion
156
- //#region packages/server/src/config.ts
157
- /**
158
- * Flatten `BaerlyConfig.collections` into the per-collection
159
- * `schemas` and `indexes` maps that {@link Db.create} consumes at
160
- * runtime. Used by the Cloudflare and Node adapters to pipe a
161
- * single `config` object through to the writer/planner.
162
- *
163
- * Both adapters import this helper rather than inlining the loop
164
- * so the projection rule (drop empty index arrays; omit absent
165
- * schemas) stays in one place. Future `CollectionDefinition`
166
- * fields (lifecycle hooks, replica_identity) land here too.
167
- */
168
- const collectionsToMaps = (collections) => {
169
- const schemas = /* @__PURE__ */ new Map();
170
- const indexes = /* @__PURE__ */ new Map();
171
- if (collections === void 0) return {
172
- schemas,
173
- indexes
174
- };
175
- for (const [name, def] of Object.entries(collections)) {
176
- if (def.schema !== void 0) schemas.set(name, def.schema);
177
- if (def.indexes !== void 0 && def.indexes.length > 0) indexes.set(name, def.indexes);
178
- }
179
- return {
180
- schemas,
181
- indexes
182
- };
183
- };
184
- //#endregion
185
- //#region packages/server/src/auth/internal/none-verifier.ts
186
- /**
187
- * Internal helper backing `config.auth === "none"`. Returns a
188
- * `Verifier` that resolves every request to the supplied
189
- * `tenantPrefix` with `identity: { kind: "none" }`. The kernel
190
- * NEVER reads the `Authorization` header in this mode — the network
191
- * seam itself is the trust boundary.
192
- *
193
- * Discriminant note: `identity.kind === "none"` distinguishes the
194
- * "operator opted into auth=none in baerly.config.ts" branch from the
195
- * bearer-token paths (`kind: "shared-secret"`, `kind: "jwt"`, etc).
196
- *
197
- * Not part of the public surface. Consumed by `baerlyWorker` /
198
- * `baerlyNode` resolution; the operator-facing API is the typed
199
- * `auth: "none"` field on `BaerlyAppConfig`.
200
- *
201
- * @internal
202
- */
203
- const noAuthVerifier = (tenantPrefix) => {
204
- return async () => ({
205
- tenantPrefix,
206
- identity: { kind: "none" }
207
- });
208
- };
209
- //#endregion
210
- //#region packages/server/src/auth/internal/resolve-verifier.ts
211
- /**
212
- * Resolve the per-request `Verifier` for an adapter factory using the
213
- * fixed order:
214
- *
215
- * 1. `factoryVerifier` set → use as-is (highest precedence; enables
216
- * env-aware construction via `cloudflareAccess(env)` etc).
217
- * 2. else `config.auth === "shared-secret"` → read `SHARED_SECRET`
218
- * via `readEnv`; throw `BaerlyError("InvalidConfig",
219
- * SHARED_SECRET_MISSING_MESSAGE)` when unset/empty; else build
220
- * `sharedSecret({ secret, tenantPrefix: config.tenant })`.
221
- * 3. else `config.auth === "none"` → `noAuthVerifier(config.tenant)`.
222
- * 4. else → throw `BaerlyError("InvalidConfig",
223
- * NO_AUTH_CONFIGURED_MESSAGE)`.
224
- *
225
- * Pure function — no I/O, no side effects beyond `sharedSecret`'s
226
- * own validation. Caller invokes once at adapter init time (or on
227
- * first fetch, depending on platform `await`-at-top-level
228
- * constraints).
229
- *
230
- * @throws BaerlyError code="InvalidConfig" — branches 2 and 4 above.
231
- *
232
- * @internal
233
- */
234
- const resolveVerifier = (input) => {
235
- if (input.factoryVerifier !== void 0) return input.factoryVerifier;
236
- if (input.config.auth === "shared-secret") {
237
- const secret = input.readEnv("SHARED_SECRET");
238
- if (secret === void 0 || secret.length === 0) throw new BaerlyError("InvalidConfig", SHARED_SECRET_MISSING_MESSAGE);
239
- return sharedSecret({
240
- secret,
241
- tenantPrefix: input.config.tenant
242
- });
243
- }
244
- if (input.config.auth === "none") return noAuthVerifier(input.config.tenant);
245
- throw new BaerlyError("InvalidConfig", NO_AUTH_CONFIGURED_MESSAGE);
246
- };
247
- //#endregion
248
- //#region packages/server/src/collection.ts
249
- /**
250
- * Build a `Collection<T>` bound to one `(tenant, collection)` read context.
251
- * Cheap: zero I/O, allocates one closure. Each modifier call returns
252
- * a FRESH `Query<T>` — calling `.where(p1)` and `.where(p2)` on the
253
- * same `Collection<T>` produces two independent chains.
254
- *
255
- * `.count()` shorthand defers to the empty-state `Query<T>.count()`
256
- * so the fold logic lives in one place.
257
- *
258
- * @example
259
- * ```ts
260
- * const collection = makeCollection<Ticket>({
261
- * storage,
262
- * collectionPrefix: "app/tickets/tenant/acme/manifests/tickets",
263
- * collectionName: "tickets",
264
- * });
265
- * const open = await collection.where({ status: "open" }).all();
266
- * ```
267
- *
268
- * @internal
269
- */
270
- const makeCollection = (ctx) => {
271
- const seed = {
272
- wire: void 0,
273
- order: void 0,
274
- limit: void 0
275
- };
276
- const byId = (id) => ({
277
- ...seed,
278
- wire: { clauses: [{
279
- op: "eq",
280
- field: "_id",
281
- value: id
282
- }] }
283
- });
284
- return {
285
- name: ctx.collectionName,
286
- first: () => makeQuery(ctx, seed).first(),
287
- all: () => makeQuery(ctx, seed).all(),
288
- count: () => makeQuery(ctx, seed).count(),
289
- get: (id) => makeQuery(ctx, byId(id)).first(),
290
- where: (p) => makeQuery(ctx, seed).where(p),
291
- order: (s) => makeQuery(ctx, {
292
- ...seed,
293
- order: s
294
- }),
295
- limit: (n) => makeQuery(ctx, {
296
- ...seed,
297
- limit: n
298
- }),
299
- /**
300
- * Insert one document. UUIDv7 auto-id when `_id` is absent or
301
- * empty; otherwise the caller-supplied `_id` is honoured. A
302
- * pre-commit existence check against the materialised collection
303
- * surfaces `Conflict` on duplicate `_id` without round-tripping
304
- * to the writer — matches the locked `Collection.insert` throws
305
- * contract (`@baerly/protocol/src/collection-api.ts`).
306
- *
307
- * Single-attempt per call: CAS retries (up to 8 attempts) live
308
- * inside `Writer.commit()`. On retry-budget exhaustion the
309
- * writer throws `Conflict` and we surface unchanged.
310
- *
311
- * @throws BaerlyError code="Conflict" — `_id` collision (pre-commit
312
- * check) or CAS retry budget exhausted.
313
- * @throws BaerlyError code="SchemaError" — from the per-collection
314
- * `SchemaValidator` threaded via {@link Db.collectionReadContext}.
315
- */
316
- insert: (doc) => runInsert(ctx, doc),
317
- update: (id, patch) => makeQuery(ctx, byId(id)).update(patch),
318
- replace: (id, doc) => runReplaceById(ctx, id, doc),
319
- delete: (id) => makeQuery(ctx, byId(id)).delete()
320
- };
321
- };
322
- //#endregion
323
- //#region packages/server/src/db.ts
324
- /**
325
- * Physical-key prefix for a `(app, tenant)` pair. Trailing slash is
326
- * part of the prefix so a caller's `list("")` resolves to
327
- * `list("app/<app>/tenant/<tenant>/")` and cannot enumerate a sibling
328
- * tenant whose name shares a prefix.
329
- */
330
- const physicalPrefixFor = (app, tenant) => `app/${app}/tenant/${tenant}/`;
331
- /**
332
- * Runtime entry point. One `Db` per `(app, tenant)` request.
333
- *
334
- * Construct via {@link Db.create} — the constructor is private so
335
- * callers don't accidentally bypass validation.
336
- *
337
- * **Collection provisioning.** `Db` provisions collections implicitly on
338
- * the first commit — the writer auto-creates the per-collection
339
- * `current.json` manifest with a zero-state seed, costing one extra
340
- * Class A PUT on the very first write per collection and zero
341
- * thereafter. There is no `ensureCollection` method on this class. For
342
- * eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures
343
- * that want byte-identical bytes before the first request), use
344
- * {@link "@gusto/baerly-storage/dev".ensureTable}.
345
- *
346
- * @example
347
- * ```ts
348
- * import { Db } from "@gusto/baerly-storage";
349
- * import { MemoryStorage } from "@gusto/baerly-storage";
350
- *
351
- * const db = Db.create({
352
- * storage: new MemoryStorage(),
353
- * app: "tickets",
354
- * tenant: "acme-co",
355
- * });
356
- *
357
- * await db.collection("tickets").insert({ title: "first ticket", status: "open" });
358
- * const open = await db.collection("tickets").where({ status: "open" }).all();
359
- * ```
360
- *
361
- * @remarks
362
- * **Anti-patterns** (TS compile errors, not runtime rejections):
363
- * - `db.collection(name).insertOne({...})` / `.insert({...})` —
364
- * the Mongo verb. Use `.insert(row)` (returns `{ _id }`).
365
- * - `db.collection(name).findOne({...})` / `.find({...})` —
366
- * the Mongo read verbs. Use `.get(id)` for by-id reads and
367
- * `.where({...}).first()` / `.all()` for predicate reads.
368
- * - `db.collection(name).aggregate([...])` — no pipeline stage
369
- * model. Compose via `.where().order().limit()` modifiers.
370
- * - Raw SQL strings of any shape. The kernel has no SQL parser.
371
- */
372
- var Db = class Db {
373
- app;
374
- tenant;
375
- /**
376
- * Underlying `Storage`, captured so the collection API can issue reads
377
- * using physical keys directly.
378
- */
379
- #storage;
380
- /**
381
- * Per-collection {@link SchemaValidator}s threaded onto every
382
- * {@link CollectionReadContext} this `Db` mints. Empty map means "no
383
- * validation declared" — every write proceeds at zero overhead.
384
- *
385
- * Derived from `config.collections[*].schema` via
386
- * {@link collectionsToMaps} at {@link Db.create} time.
387
- */
388
- #schemas;
389
- /**
390
- * Per-collection {@link IndexDefinition}s threaded onto every
391
- * {@link CollectionReadContext} this `Db` mints. Empty map means "no
392
- * indexes declared" — every read falls through to the snapshot +
393
- * log fold path.
394
- *
395
- * Derived from `config.collections[*].indexes` via
396
- * {@link collectionsToMaps} at {@link Db.create} time.
397
- */
398
- #indexes;
399
- constructor(app, tenant, storage, schemas, indexes) {
400
- this.app = app;
401
- this.tenant = tenant;
402
- this.#storage = storage;
403
- this.#schemas = schemas;
404
- this.#indexes = indexes;
405
- }
406
- /**
407
- * Build a tenant-scoped `Db`. Throws
408
- * `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
409
- * is empty, contains `/`, is `"."` or `".."`, contains control
410
- * characters, starts with the reserved `"_"` prefix, or exceeds
411
- * 256 bytes.
412
- *
413
- * @throws BaerlyError code="InvalidConfig" when `app` or `tenant` is
414
- * empty, contains `/`, is `"."` or `".."`, contains control
415
- * characters, starts with the reserved `"_"` prefix, or exceeds
416
- * 256 bytes.
417
- *
418
- * @example
419
- * ```ts
420
- * const db = Db.create({ storage, app: "tickets", tenant: "acme" });
421
- * await db.collection("tickets").insert({ title: "hi" });
422
- * ```
423
- */
424
- static create(config) {
425
- const { storage, app, tenant } = config;
426
- assertKeySegment(app, "app", "Db.create");
427
- assertKeySegment(tenant, "tenant", "Db.create");
428
- const derived = config.config !== void 0 ? collectionsToMaps(config.config.collections) : void 0;
429
- return new Db(app, tenant, storage, derived?.schemas ?? /* @__PURE__ */ new Map(), derived?.indexes ?? /* @__PURE__ */ new Map());
430
- }
431
- collection(name) {
432
- return makeCollection(this.collectionReadContext(name));
433
- }
434
- /**
435
- * Build a freshly-seeded {@link CollectionReadContext} for `name`. The
436
- * HTTP router uses this so it can drive `runAllWithMeta` directly
437
- * (the return shape carries the manifest-pointer cursor used to
438
- * pack `_meta` onto the read response envelope). Application
439
- * callers should keep using
440
- * {@link Db.collection}; the chainable terminals destructure the cursor
441
- * out and discard it to keep the locked `Query<T>` signature.
442
- *
443
- * Runs the same `name`-validation guard as {@link Db.collection}.
444
- *
445
- * @throws BaerlyError code="InvalidConfig" when `name` is empty,
446
- * contains `/`, is `"."` or `".."`, contains control characters,
447
- * starts with the reserved `"_"` prefix, or exceeds 256 bytes.
448
- * @internal
449
- */
450
- collectionReadContext(name) {
451
- assertKeySegment(name, "collection", "Db.collection");
452
- const schema = this.#schemas.get(name);
453
- return {
454
- storage: this.#storage,
455
- collectionPrefix: `${physicalPrefixFor(this.app, this.tenant)}manifests/${name}`,
456
- collectionName: name,
457
- indexes: this.#indexes.get(name) ?? [],
458
- ...schema !== void 0 ? { schema } : {}
459
- };
460
- }
461
- /**
462
- * Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns
463
- * `null` when the collection has not been provisioned yet (no
464
- * `current.json` exists). Throws `BaerlyError{code:"InvalidResponse"}`
465
- * on a malformed body — same contract as the underlying
466
- * {@link readCurrentJson} helper in `@baerly/protocol`.
467
- *
468
- * Backs the `/v1/since` long-poll handler in
469
- * `packages/server/src/http/since.ts`; that handler needs the parsed
470
- * `CurrentJson` plus an ETag for the follow-up reads.
471
- *
472
- * @internal — typed seam for the HTTP handler; app code should use
473
- * the collection API.
474
- */
475
- async getCurrentJson(collection, opts) {
476
- assertPathSegment(collection, "collection");
477
- const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/current.json`;
478
- return readCurrentJson(this.#storage, key, opts);
479
- }
480
- /**
481
- * Read + parse one `LogEntry` by `seq` from
482
- * `manifests/<collection>/log/<seq>.json`. Returns `null`
483
- * when the entry is missing — this typically means the GC sweeper
484
- * deleted the entry between a `readCurrentJson` and this GET (the
485
- * `/v1/since` handler treats the race as silent and skips the
486
- * entry). Throws `BaerlyError{code:"InvalidResponse"}` on a body
487
- * that isn't valid JSON.
488
- *
489
- * @internal — typed seam for the HTTP handler; app code should use
490
- * the collection API.
491
- */
492
- async getLogEntry(collection, seq, opts) {
493
- assertPathSegment(collection, "collection");
494
- const key = logObjectKey(`${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`, seq);
495
- const got = await this.#storage.get(key, opts);
496
- if (got === null) return null;
497
- let parsed;
498
- try {
499
- parsed = decodeJsonBytes(got.body);
500
- } catch (error) {
501
- throw new BaerlyError("InvalidResponse", `log entry at ${key}: body is not valid JSON`, error);
502
- }
503
- return parsed;
504
- }
505
- /**
506
- * Forward-probe the TRUE committed log tail from `hint` (a lower
507
- * bound, typically `tail_hint`). Backs the `/v1/since` end-bound.
508
- *
509
- * @internal — typed seam for the HTTP handler.
510
- */
511
- async probeLogTail(collection, hint, opts) {
512
- assertPathSegment(collection, "collection");
513
- const logPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;
514
- const { tail } = await probeTailFrom(this.#storage, logPrefix, hint, opts);
515
- return tail;
516
- }
517
- };
518
- /**
519
- * Guard a string used as a path-segment in the bucket-key encoding.
520
- * Routes through the single shared {@link assertPathSegment} rule
521
- * (empty / `"/"` / `"."`|`".."` / C0-C1 control / leading `"_"` (ADR-003) /
522
- * overlong), all as `BaerlyError{code:"InvalidConfig"}`. `role` and `verb`
523
- * are baked into the message so the caller doesn't need to format their own.
524
- *
525
- * Used by {@link Db.create} (twice — `app`, `tenant`) and
526
- * {@link Db.collectionReadContext} (once — `name`).
527
- *
528
- * @internal
529
- */
530
- const assertKeySegment = (value, role, verb) => {
531
- assertPathSegment(value, role, verb);
532
- };
533
- //#endregion
534
- export { isDeployedEnv as a, MemoryStorage as i, resolveVerifier as n, collectionsToMaps as r, Db as t };
535
-
536
- //# sourceMappingURL=src-CYHFDrKz.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-CYHFDrKz.js","names":["#objects","#etagCounter","#nextEtag","#storage","#schemas","#indexes"],"sources":["../packages/protocol/src/env.ts","../packages/protocol/src/storage/memory.ts","../packages/server/src/config.ts","../packages/server/src/auth/internal/none-verifier.ts","../packages/server/src/auth/internal/resolve-verifier.ts","../packages/server/src/collection.ts","../packages/server/src/db.ts"],"sourcesContent":["// Deployment detection shared by the in-memory storage guard and the\n// Node resolveStorageFromEnv resolver. Pure (env passed in) so it stays\n// Workerd-loadable. Markers are vars each platform sets unconditionally:\n// Cloud Run, Heroku, Kubernetes, ECS, Railway, Render, Fly.\n//\n// The list is deliberately conservative: every marker here is set ONLY by\n// the platform at runtime, never by that platform's local dev emulator, so\n// detection cannot false-positive a developer's machine. Serverless markers\n// like VERCEL / NETLIFY / AWS_LAMBDA_FUNCTION_NAME are intentionally omitted\n// — their local emulators (`vercel dev`, `netlify dev`, SAM local) set the\n// same vars, so adding them would break local development. Before adding a\n// marker, confirm it is never set by that platform's dev tooling. An\n// unmarked host should set NODE_ENV=production to opt into the guard.\nexport const PAAS_MARKERS = [\n \"RAILWAY_ENVIRONMENT\",\n \"RENDER\",\n \"FLY_APP_NAME\",\n \"K_SERVICE\",\n \"DYNO\",\n \"KUBERNETES_SERVICE_HOST\",\n \"ECS_CONTAINER_METADATA_URI_V4\",\n] as const;\n\n/**\n * True when `env` looks like a deployed environment: `NODE_ENV=production`\n * or any {@link PAAS_MARKERS} set to a non-empty value. Decides whether a\n * non-durable store (in-memory, local-fs) should fail loud instead of\n * silently serving a production workload. A CI runner (`CI` set to a\n * non-empty, non-`false` value) is never treated as deployed, so PaaS\n * markers from an in-cluster CI agent do not trip it.\n */\nexport const isDeployedEnv = (env: Record<string, string | undefined>): boolean => {\n // A CI runner is never a deployment — even in a k8s pod that sets a PaaS\n // marker (e.g. KUBERNETES_SERVICE_HOST) — so it must not trip the markers.\n const inCi = (env[\"CI\"] ?? \"\") !== \"\" && env[\"CI\"] !== \"false\";\n return (\n env[\"NODE_ENV\"] === \"production\" || (!inCi && PAAS_MARKERS.some((m) => (env[m] ?? \"\") !== \"\"))\n );\n};\n","import { isDeployedEnv } from \"../env.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport { assertValidStorageKey } from \"./key.ts\";\nimport type {\n Storage,\n StorageGetOptions,\n StorageGetResult,\n StorageListEntry,\n StoragePutOptions,\n StoragePutResult,\n} from \"./types.ts\";\n\ninterface StoredObject {\n body: Uint8Array;\n etag: string;\n contentType?: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\nconst EPHEMERAL_ENV_OPT_IN = \"BAERLY_ALLOW_EPHEMERAL_STORAGE\";\n\n// Read process env without a `node:` import so protocol stays Workerd-\n// loadable (on Workerd `process` is absent → env is `{}` → not deployed).\nconst readProcessEnv = (): Record<string, string | undefined> =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n\nlet warnedEphemeralInDeployment = false;\n\n// Fail closed when in-memory storage would silently back a deployed\n// workload (writes \"succeed\" into RAM, vanish on restart). No-op in\n// dev/test; bypass in a deployment only via an explicit acknowledgement.\nconst assertEphemeralAllowed = (explicitOptIn: boolean): void => {\n const env = readProcessEnv();\n if (!isDeployedEnv(env)) {\n return;\n }\n if (!explicitOptIn && env[EPHEMERAL_ENV_OPT_IN] !== \"true\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"Refusing to use in-memory storage in a deployed environment — all data is lost on restart. \" +\n \"MemoryStorage is for tests/local dev only; configure a durable bucket (AWS S3 / Cloudflare R2). \" +\n `To intentionally opt in: new MemoryStorage({ ephemeral: true }) or ${EPHEMERAL_ENV_OPT_IN}=true.`,\n );\n }\n if (!warnedEphemeralInDeployment) {\n warnedEphemeralInDeployment = true;\n console.warn(\n \"[baerly] in-memory storage in a deployed environment — ALL DATA IS LOST ON RESTART.\",\n );\n }\n};\n\n/** Options for {@link MemoryStorage}. */\nexport interface MemoryStorageOptions {\n /**\n * Acknowledge the store is intentionally ephemeral — required to\n * construct in a detected deployment ({@link isDeployedEnv}); ignored in\n * dev/test. Env equivalent: `BAERLY_ALLOW_EPHEMERAL_STORAGE=true`.\n */\n ephemeral?: boolean;\n}\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and\n * R2 use for `list`. JavaScript's default string sort compares UTF-16\n * code units, which diverges from UTF-8 byte order for supplementary-\n * plane characters (e.g. emoji sort before high-BMP characters under\n * UTF-16 but after them in UTF-8). Using this keeps the in-memory\n * reference backend faithful to the real adapters. (All kernel keys\n * are ASCII base-32, where the two orders coincide — this only\n * matters for adversarial / non-ASCII keys.)\n */\nconst compareKeysUtf8 = (a: string, b: string): number => {\n const ba = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ba.length, bb.length);\n for (let i = 0; i < n; i++) {\n if (ba[i] !== bb[i]) {\n return ba[i]! - bb[i]!;\n }\n }\n return ba.length - bb.length;\n};\n\n/**\n * In-memory `Storage`. The randomized property test runs against\n * this; it must be deterministic — no clocks beyond the caller's,\n * no randomness, no I/O.\n *\n * ETags are a monotonically increasing hex counter formatted in the\n * `\"<hex>\"` shape S3 returns (the surrounding double-quotes are part\n * of the ETag header value). Keys are stored verbatim.\n *\n * **Test-confidence caveat:** every method resolves on the microtask\n * queue with no real concurrency, so `put` reads `existing` and writes\n * back with no interleaving. MemoryStorage therefore CANNOT exercise the\n * compare-and-swap race the writer-fence model depends on — two writers\n * contending on one `current.json` always serialize here, so a green run\n * is necessary but not sufficient. That race is covered only by the\n * randomized integration tests against real S3 / Minio\n * (`tests/integration/randomized.test.ts`, `node-minio` variant).\n * Relatedly, `serverDate` returns the local clock, not an independent\n * server clock (see the `put` return below).\n */\nexport class MemoryStorage implements Storage {\n readonly #objects = new Map<string, StoredObject>();\n #etagCounter = 0;\n\n constructor(opts?: MemoryStorageOptions) {\n assertEphemeralAllowed(opts?.ephemeral === true);\n }\n\n #nextEtag(): string {\n this.#etagCounter += 1;\n return `\"${this.#etagCounter.toString(16)}\"`;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n return null;\n }\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === stored.etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: stored.body, etag: stored.etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const existing = this.#objects.get(key);\n\n if (opts?.ifNoneMatch === \"*\" && existing !== undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (existing.etag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`,\n );\n }\n }\n\n const etag = this.#nextEtag();\n this.#objects.set(key, {\n body,\n etag,\n // Stryker disable next-line ObjectLiteral,ConditionalExpression: contentType is stored in the internal StoredObject but never returned by get() — the Storage interface has no contentType on StorageGetResult, so any mutation of this spread is observable-equivalent\n ...(opts?.contentType !== undefined && { contentType: opts.contentType }),\n });\n // `serverDate` is intentionally returned — the kernel's adaptive\n // clock-skew loop consumes the write-time server clock. `list()`\n // deliberately omits `lastModified`: the in-memory impl has no\n // independent server clock, and its only consumer (GC's `due_at`\n // anchor) falls back to `now()` when it is absent, so omitting it\n // changes nothing.\n return { etag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n this.#objects.delete(key);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const sorted = [...this.#objects.keys()]\n .filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0)\n .toSorted(compareKeysUtf8);\n let yielded = 0;\n for (const key of sorted) {\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n // Stryker disable next-line ConditionalExpression,BlockStatement: unreachable guard — keys come from Map.keys() so the corresponding value is always present; this branch exists only to satisfy noUncheckedIndexedAccess\n if (stored === undefined) {\n continue;\n }\n yield { key, etag: stored.etag };\n yielded += 1;\n }\n }\n\n /**\n * Test-only: drop all objects.\n * @internal\n */\n _clear(): void {\n this.#objects.clear();\n this.#etagCounter = 0;\n }\n}\n\n// Process-singleton MemoryStorage map keyed by bucket. Tests that need\n// multiple `Db` / `Writer` instances to see each other's writes\n// against an in-memory backend reach for this via\n// {@link getOrCreateMemoryStorageForBucket}; {@link resetMemoryStorage}\n// drops every bucket between test cases.\nconst sharedPerBucket = new Map<string, MemoryStorage>();\n\n/**\n * Test isolation: drop every bucket's contents from the shared\n * memory storage used by {@link getOrCreateMemoryStorageForBucket}.\n * Direct `MemoryStorage` instances built via `new MemoryStorage()`\n * are unaffected — those are isolated by construction.\n */\nexport const resetMemoryStorage = (): void => {\n sharedPerBucket.clear();\n};\n\n/**\n * Get the process-singleton {@link MemoryStorage} for the named\n * bucket, creating one on first access. Use this when constructing\n * a `Storage` directly so multiple consumers in the same process\n * see each other's writes for the same bucket name.\n */\nexport const getOrCreateMemoryStorageForBucket = (bucket: string): MemoryStorage => {\n let s = sharedPerBucket.get(bucket);\n if (s === undefined) {\n s = new MemoryStorage();\n sharedPerBucket.set(bucket, s);\n }\n return s;\n};\n","/**\n * Runtime helpers for the `BaerlyConfig` shape.\n *\n * The type declarations (`BaerlyConfig`, `BaerlyAppConfig`,\n * `CollectionDefinition`, `CollectionNames`, `RowOf`, `UnboundConfig`,\n * `defineConfig`) live in `@baerly/protocol` — the cross-platform\n * package — so cross-platform consumers (client, scaffold\n * `baerly.config.ts`) can reference them without dragging the\n * Node-only server modules (`AsyncLocalStorage` etc.) into their\n * typecheck graph.\n *\n * This file keeps only the runtime helper `collectionsToMaps`, which\n * the Cloudflare and Node adapters call to flatten\n * `BaerlyConfig.collections` into the per-collection maps that\n * `Db.create` consumes.\n *\n * @see @baerly/protocol app-config.ts — type declarations.\n */\n\nimport type { BaerlyConfig, IndexDefinition, SchemaValidator } from \"@baerly/protocol\";\n\n/**\n * Flatten `BaerlyConfig.collections` into the per-collection\n * `schemas` and `indexes` maps that {@link Db.create} consumes at\n * runtime. Used by the Cloudflare and Node adapters to pipe a\n * single `config` object through to the writer/planner.\n *\n * Both adapters import this helper rather than inlining the loop\n * so the projection rule (drop empty index arrays; omit absent\n * schemas) stays in one place. Future `CollectionDefinition`\n * fields (lifecycle hooks, replica_identity) land here too.\n */\nexport const collectionsToMaps = (\n collections: BaerlyConfig[\"collections\"] | undefined,\n): {\n schemas: ReadonlyMap<string, SchemaValidator>;\n indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;\n} => {\n const schemas = new Map<string, SchemaValidator>();\n const indexes = new Map<string, ReadonlyArray<IndexDefinition>>();\n if (collections === undefined) {\n return { schemas, indexes };\n }\n for (const [name, def] of Object.entries(collections)) {\n if (def.schema !== undefined) {\n schemas.set(name, def.schema);\n }\n if (def.indexes !== undefined && def.indexes.length > 0) {\n indexes.set(name, def.indexes);\n }\n }\n return { schemas, indexes };\n};\n","import type { Verifier } from \"@baerly/protocol\";\n\n/**\n * Internal helper backing `config.auth === \"none\"`. Returns a\n * `Verifier` that resolves every request to the supplied\n * `tenantPrefix` with `identity: { kind: \"none\" }`. The kernel\n * NEVER reads the `Authorization` header in this mode — the network\n * seam itself is the trust boundary.\n *\n * Discriminant note: `identity.kind === \"none\"` distinguishes the\n * \"operator opted into auth=none in baerly.config.ts\" branch from the\n * bearer-token paths (`kind: \"shared-secret\"`, `kind: \"jwt\"`, etc).\n *\n * Not part of the public surface. Consumed by `baerlyWorker` /\n * `baerlyNode` resolution; the operator-facing API is the typed\n * `auth: \"none\"` field on `BaerlyAppConfig`.\n *\n * @internal\n */\nexport const noAuthVerifier = (tenantPrefix: string): Verifier => {\n return async () => ({ tenantPrefix, identity: { kind: \"none\" } });\n};\n","import {\n type BaerlyAppConfig,\n BaerlyError,\n NO_AUTH_CONFIGURED_MESSAGE,\n SHARED_SECRET_MISSING_MESSAGE,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { sharedSecret } from \"../presets/shared-secret.ts\";\nimport { noAuthVerifier } from \"./none-verifier.ts\";\n\n/**\n * Read env var lazily via a host-supplied accessor so the same\n * resolver works in CF Workers (env binding) and Node\n * (`process.env`). Returns `undefined` for an unset OR empty string —\n * both branches mean \"operator forgot to set it\".\n */\ntype EnvAccessor = (name: string) => string | undefined;\n\n/**\n * Inputs to {@link resolveVerifier}. `factoryVerifier` is the\n * adapter-factory `verifier:` option (may be undefined). `config`\n * carries the typed `auth` posture + the `tenant` pin. `readEnv`\n * is the per-host env accessor.\n */\nexport interface ResolveVerifierInput {\n readonly factoryVerifier: Verifier | undefined;\n readonly config: BaerlyAppConfig;\n readonly readEnv: EnvAccessor;\n}\n\n/**\n * Resolve the per-request `Verifier` for an adapter factory using the\n * fixed order:\n *\n * 1. `factoryVerifier` set → use as-is (highest precedence; enables\n * env-aware construction via `cloudflareAccess(env)` etc).\n * 2. else `config.auth === \"shared-secret\"` → read `SHARED_SECRET`\n * via `readEnv`; throw `BaerlyError(\"InvalidConfig\",\n * SHARED_SECRET_MISSING_MESSAGE)` when unset/empty; else build\n * `sharedSecret({ secret, tenantPrefix: config.tenant })`.\n * 3. else `config.auth === \"none\"` → `noAuthVerifier(config.tenant)`.\n * 4. else → throw `BaerlyError(\"InvalidConfig\",\n * NO_AUTH_CONFIGURED_MESSAGE)`.\n *\n * Pure function — no I/O, no side effects beyond `sharedSecret`'s\n * own validation. Caller invokes once at adapter init time (or on\n * first fetch, depending on platform `await`-at-top-level\n * constraints).\n *\n * @throws BaerlyError code=\"InvalidConfig\" — branches 2 and 4 above.\n *\n * @internal\n */\nexport const resolveVerifier = (input: ResolveVerifierInput): Verifier => {\n if (input.factoryVerifier !== undefined) {\n return input.factoryVerifier;\n }\n if (input.config.auth === \"shared-secret\") {\n const secret = input.readEnv(\"SHARED_SECRET\");\n if (secret === undefined || secret.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", SHARED_SECRET_MISSING_MESSAGE);\n }\n return sharedSecret({ secret, tenantPrefix: input.config.tenant });\n }\n if (input.config.auth === \"none\") {\n return noAuthVerifier(input.config.tenant);\n }\n // Exhaustiveness backstop. The AuthConfig union is locked to\n // [\"none\", \"shared-secret\"]; reaching this branch means the caller\n // passed a config that has neither the typed field nor a factory\n // override. Same operator remediation as the type-level error.\n throw new BaerlyError(\"InvalidConfig\", NO_AUTH_CONFIGURED_MESSAGE);\n};\n","/**\n * `Collection<T>` factory. `Db.collection(name)` returns the result of\n * `makeCollection(ctx)` — a cheap, no-I/O handle. By-id mutations route\n * through dedicated runners: `insert` → `runInsert`,\n * `replace(id, doc)` → `runReplaceById`. `update(id, patch)` and\n * `delete(id)` forward to the predicate-form runners via a `byId`\n * wire — those Query verbs are genuinely bulk, so the by-id case is\n * just a one-row predicate.\n *\n * `Collection.insert(doc)` is the public insert path. The locked\n * `Query<T>` interface (`@baerly/protocol/src/collection-api.ts`) intentionally\n * does NOT declare `insert` — chainable inserts are out of scope.\n * For an inserted doc whose predicate-bound shape matters,\n * `db.collection(...).insert(...)` is the path; predicates are a read-\n * side concern.\n */\n\nimport {\n type Collection,\n type DocumentData,\n type OrderSpec,\n type PredicateWire,\n} from \"@baerly/protocol\";\nimport { makeQuery, runInsert, runReplaceById, type CollectionReadContext } from \"./query.ts\";\n\n/**\n * Build a `Collection<T>` bound to one `(tenant, collection)` read context.\n * Cheap: zero I/O, allocates one closure. Each modifier call returns\n * a FRESH `Query<T>` — calling `.where(p1)` and `.where(p2)` on the\n * same `Collection<T>` produces two independent chains.\n *\n * `.count()` shorthand defers to the empty-state `Query<T>.count()`\n * so the fold logic lives in one place.\n *\n * @example\n * ```ts\n * const collection = makeCollection<Ticket>({\n * storage,\n * collectionPrefix: \"app/tickets/tenant/acme/manifests/tickets\",\n * collectionName: \"tickets\",\n * });\n * const open = await collection.where({ status: \"open\" }).all();\n * ```\n *\n * @internal\n */\nexport const makeCollection = <T extends DocumentData>(\n ctx: CollectionReadContext,\n): Collection<T> => {\n // Empty seed state. Every modifier merges into a frozen copy.\n const seed = {\n wire: undefined as PredicateWire | undefined,\n order: undefined as OrderSpec<T> | undefined,\n limit: undefined as number | undefined,\n };\n // Kernel-internal `_id`-shaped wire. Bypasses `validateWire`\n // (which rejects top-level `_id`) by construction — the wire is\n // never wire-submitted; it short-circuits to `Map.get` via\n // `singleIdFromPredicate` inside `runRead`.\n const byId = (id: string) => ({\n ...seed,\n wire: { clauses: [{ op: \"eq\" as const, field: \"_id\", value: id }] } as PredicateWire,\n });\n return {\n name: ctx.collectionName,\n first: () => makeQuery<T>(ctx, seed).first(),\n all: () => makeQuery<T>(ctx, seed).all(),\n count: () => makeQuery<T>(ctx, seed).count(),\n get: (id) => makeQuery<T>(ctx, byId(id)).first(),\n where: (p) => makeQuery<T>(ctx, seed).where(p),\n order: (s) => makeQuery<T>(ctx, { ...seed, order: s }),\n limit: (n) => makeQuery<T>(ctx, { ...seed, limit: n }),\n /**\n * Insert one document. UUIDv7 auto-id when `_id` is absent or\n * empty; otherwise the caller-supplied `_id` is honoured. A\n * pre-commit existence check against the materialised collection\n * surfaces `Conflict` on duplicate `_id` without round-tripping\n * to the writer — matches the locked `Collection.insert` throws\n * contract (`@baerly/protocol/src/collection-api.ts`).\n *\n * Single-attempt per call: CAS retries (up to 8 attempts) live\n * inside `Writer.commit()`. On retry-budget exhaustion the\n * writer throws `Conflict` and we surface unchanged.\n *\n * @throws BaerlyError code=\"Conflict\" — `_id` collision (pre-commit\n * check) or CAS retry budget exhausted.\n * @throws BaerlyError code=\"SchemaError\" — from the per-collection\n * `SchemaValidator` threaded via {@link Db.collectionReadContext}.\n */\n insert: (doc) => runInsert<T>(ctx, doc),\n update: (id, patch) => makeQuery<T>(ctx, byId(id)).update(patch),\n replace: (id, doc) => runReplaceById<T>(ctx, id, doc),\n delete: (id) => makeQuery<T>(ctx, byId(id)).delete(),\n };\n};\n","import {\n type BaerlyConfig,\n BaerlyError,\n type Collection,\n type CollectionNames,\n type CurrentJsonRead,\n decodeJsonBytes,\n type DocumentData,\n type IndexDefinition,\n logObjectKey,\n type LogEntry,\n readCurrentJson,\n type RowOf,\n type SchemaValidator,\n type Storage,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { collectionsToMaps } from \"./config.ts\";\nimport { probeTailFrom } from \"./log-tail.ts\";\nimport { assertPathSegment } from \"./path-segment.ts\";\nimport type { CollectionReadContext } from \"./query.ts\";\nimport { makeCollection } from \"./collection.ts\";\n\n/**\n * Physical-key prefix for a `(app, tenant)` pair. Trailing slash is\n * part of the prefix so a caller's `list(\"\")` resolves to\n * `list(\"app/<app>/tenant/<tenant>/\")` and cannot enumerate a sibling\n * tenant whose name shares a prefix.\n */\nconst physicalPrefixFor = (app: string, tenant: string): string => `app/${app}/tenant/${tenant}/`;\n\n/**\n * Runtime entry point. One `Db` per `(app, tenant)` request.\n *\n * Construct via {@link Db.create} — the constructor is private so\n * callers don't accidentally bypass validation.\n *\n * **Collection provisioning.** `Db` provisions collections implicitly on\n * the first commit — the writer auto-creates the per-collection\n * `current.json` manifest with a zero-state seed, costing one extra\n * Class A PUT on the very first write per collection and zero\n * thereafter. There is no `ensureCollection` method on this class. For\n * eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures\n * that want byte-identical bytes before the first request), use\n * {@link \"@gusto/baerly-storage/dev\".ensureTable}.\n *\n * @example\n * ```ts\n * import { Db } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const db = Db.create({\n * storage: new MemoryStorage(),\n * app: \"tickets\",\n * tenant: \"acme-co\",\n * });\n *\n * await db.collection(\"tickets\").insert({ title: \"first ticket\", status: \"open\" });\n * const open = await db.collection(\"tickets\").where({ status: \"open\" }).all();\n * ```\n *\n * @remarks\n * **Anti-patterns** (TS compile errors, not runtime rejections):\n * - `db.collection(name).insertOne({...})` / `.insert({...})` —\n * the Mongo verb. Use `.insert(row)` (returns `{ _id }`).\n * - `db.collection(name).findOne({...})` / `.find({...})` —\n * the Mongo read verbs. Use `.get(id)` for by-id reads and\n * `.where({...}).first()` / `.all()` for predicate reads.\n * - `db.collection(name).aggregate([...])` — no pipeline stage\n * model. Compose via `.where().order().limit()` modifiers.\n * - Raw SQL strings of any shape. The kernel has no SQL parser.\n */\nexport class Db<TConfig extends BaerlyConfig = UnboundConfig> {\n readonly app: string;\n readonly tenant: string;\n /**\n * Underlying `Storage`, captured so the collection API can issue reads\n * using physical keys directly.\n */\n readonly #storage: Storage;\n /**\n * Per-collection {@link SchemaValidator}s threaded onto every\n * {@link CollectionReadContext} this `Db` mints. Empty map means \"no\n * validation declared\" — every write proceeds at zero overhead.\n *\n * Derived from `config.collections[*].schema` via\n * {@link collectionsToMaps} at {@link Db.create} time.\n */\n readonly #schemas: ReadonlyMap<string, SchemaValidator>;\n /**\n * Per-collection {@link IndexDefinition}s threaded onto every\n * {@link CollectionReadContext} this `Db` mints. Empty map means \"no\n * indexes declared\" — every read falls through to the snapshot +\n * log fold path.\n *\n * Derived from `config.collections[*].indexes` via\n * {@link collectionsToMaps} at {@link Db.create} time.\n */\n readonly #indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;\n\n private constructor(\n app: string,\n tenant: string,\n storage: Storage,\n schemas: ReadonlyMap<string, SchemaValidator>,\n indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>,\n ) {\n this.app = app;\n this.tenant = tenant;\n this.#storage = storage;\n this.#schemas = schemas;\n this.#indexes = indexes;\n }\n\n /**\n * Build a tenant-scoped `Db`. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` if either `app` or `tenant`\n * is empty, contains `/`, is `\".\"` or `\"..\"`, contains control\n * characters, starts with the reserved `\"_\"` prefix, or exceeds\n * 256 bytes.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `app` or `tenant` is\n * empty, contains `/`, is `\".\"` or `\"..\"`, contains control\n * characters, starts with the reserved `\"_\"` prefix, or exceeds\n * 256 bytes.\n *\n * @example\n * ```ts\n * const db = Db.create({ storage, app: \"tickets\", tenant: \"acme\" });\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * ```\n */\n static create<TConfig extends BaerlyConfig = UnboundConfig>(config: {\n storage: Storage;\n app: string;\n tenant: string;\n /**\n * Optional. Pass the value returned by {@link defineConfig} from\n * your `baerly.config.ts`. Two things happen:\n *\n * 1. **Types.** `db.collection(name)` narrows `name` to declared\n * collection names and infers the row type from\n * `collections[name].schema` via {@link RowOf}.\n * 2. **Runtime.** Schemas and indexes are derived from\n * `config.collections` via {@link collectionsToMaps}. Schema\n * validation and index routing are wired automatically — no\n * second hand-off step.\n *\n * @example\n * ```ts\n * import config from \"../baerly.config.ts\";\n * const db = Db.create({\n * storage: new MemoryStorage(),\n * app: \"helpdesk\",\n * tenant: \"test\",\n * config,\n * });\n * // db.collection(\"tickets\") is typed AND validates writes against\n * // the schema declared in baerly.config.ts.\n * ```\n */\n config?: TConfig;\n }): Db<TConfig> {\n const { storage, app, tenant } = config;\n assertKeySegment(app, \"app\", \"Db.create\");\n assertKeySegment(tenant, \"tenant\", \"Db.create\");\n // Always derive runtime maps from `config.collections`. Absent\n // config ⇒ empty maps (no schemas, no indexes); the kernel\n // behaves the same as a config with `collections: {}`.\n const derived =\n config.config !== undefined ? collectionsToMaps(config.config.collections) : undefined;\n return new Db<TConfig>(\n app,\n tenant,\n storage,\n derived?.schemas ?? new Map(),\n derived?.indexes ?? new Map(),\n );\n }\n\n /**\n * Typed handle for a single collection. Cheap; creates no I/O. Same\n * `name` returns a FRESH `Collection<T>` object on each call (chain\n * identity is intentional — modifiers return new objects).\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty,\n * contains `/`, is `\".\"` or `\"..\"`, contains control characters,\n * starts with the reserved `\"_\"` prefix, or exceeds 256 bytes.\n *\n * @example\n * ```ts\n * // With a baerly.config.ts bound via Db.create({..., config}),\n * // db.collection(name) infers the row type from the declared schema —\n * // no <Ticket> generic needed.\n * const open = await db.collection(\"tickets\")\n * .where({ status: \"open\" })\n * .order({ commit_ts: \"desc\" })\n * .limit(50)\n * .all();\n * ```\n */\n // One signature. When `TConfig` extends `UnboundConfig`,\n // `CollectionNames<UnboundConfig>` widens to `string` so kernel-internal\n // paths against `Db<UnboundConfig>` still resolve without a separate\n // untyped overload. The impl signature stays widened (`Collection<any>`)\n // — the runtime never narrows; `makeCollection<DocumentData>` builds a\n // single row-agnostic handle and TypeScript handles the rest at the\n // call site.\n collection<N extends CollectionNames<TConfig>>(\n name: N,\n ): Collection<RowOf<TConfig, N> & DocumentData>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- impl signature must be wider than the public overload; with Predicate<T> typed, Collection<DocumentData> is no longer assignable to Collection<RowOf<...>&DocumentData> due to contravariance on where(). `any` widens correctly.\n collection(name: string): Collection<any> {\n return makeCollection<DocumentData>(this.collectionReadContext(name));\n }\n\n /**\n * Build a freshly-seeded {@link CollectionReadContext} for `name`. The\n * HTTP router uses this so it can drive `runAllWithMeta` directly\n * (the return shape carries the manifest-pointer cursor used to\n * pack `_meta` onto the read response envelope). Application\n * callers should keep using\n * {@link Db.collection}; the chainable terminals destructure the cursor\n * out and discard it to keep the locked `Query<T>` signature.\n *\n * Runs the same `name`-validation guard as {@link Db.collection}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty,\n * contains `/`, is `\".\"` or `\"..\"`, contains control characters,\n * starts with the reserved `\"_\"` prefix, or exceeds 256 bytes.\n * @internal\n */\n collectionReadContext(name: string): CollectionReadContext {\n assertKeySegment(name, \"collection\", \"Db.collection\");\n const schema = this.#schemas.get(name);\n return {\n storage: this.#storage,\n collectionPrefix: `${physicalPrefixFor(this.app, this.tenant)}manifests/${name}`,\n collectionName: name,\n indexes: this.#indexes.get(name) ?? [],\n ...(schema !== undefined ? { schema } : {}),\n };\n }\n\n /**\n * Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns\n * `null` when the collection has not been provisioned yet (no\n * `current.json` exists). Throws `BaerlyError{code:\"InvalidResponse\"}`\n * on a malformed body — same contract as the underlying\n * {@link readCurrentJson} helper in `@baerly/protocol`.\n *\n * Backs the `/v1/since` long-poll handler in\n * `packages/server/src/http/since.ts`; that handler needs the parsed\n * `CurrentJson` plus an ETag for the follow-up reads.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\n async getCurrentJson(\n collection: string,\n opts?: { signal?: AbortSignal },\n ): Promise<CurrentJsonRead | null> {\n // Defensive at the db layer so ALL callers are covered — including\n // the `/v1/since` handler, whose only inline screen catches empty /\n // `/` and lets `..` / control bytes through into this key.\n assertPathSegment(collection, \"collection\");\n const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/current.json`;\n return readCurrentJson(this.#storage, key, opts);\n }\n\n /**\n * Read + parse one `LogEntry` by `seq` from\n * `manifests/<collection>/log/<seq>.json`. Returns `null`\n * when the entry is missing — this typically means the GC sweeper\n * deleted the entry between a `readCurrentJson` and this GET (the\n * `/v1/since` handler treats the race as silent and skips the\n * entry). Throws `BaerlyError{code:\"InvalidResponse\"}` on a body\n * that isn't valid JSON.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\n async getLogEntry(\n collection: string,\n seq: number,\n opts?: { signal?: AbortSignal },\n ): Promise<LogEntry | null> {\n // Defensive at the db layer so ALL callers are covered — same\n // rationale as `getCurrentJson`; the `/v1/since` poll reaches here.\n assertPathSegment(collection, \"collection\");\n const key = logObjectKey(\n `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`,\n seq,\n );\n const got = await this.#storage.get(key, opts);\n if (got === null) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `log entry at ${key}: body is not valid JSON`,\n error,\n );\n }\n return parsed as LogEntry;\n }\n\n /**\n * Forward-probe the TRUE committed log tail from `hint` (a lower\n * bound, typically `tail_hint`). Backs the `/v1/since` end-bound.\n *\n * @internal — typed seam for the HTTP handler.\n */\n async probeLogTail(\n collection: string,\n hint: number,\n opts?: { signal?: AbortSignal },\n ): Promise<number> {\n assertPathSegment(collection, \"collection\");\n const logPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;\n const { tail } = await probeTailFrom(this.#storage, logPrefix, hint, opts);\n return tail;\n }\n}\n\n/**\n * Guard a string used as a path-segment in the bucket-key encoding.\n * Routes through the single shared {@link assertPathSegment} rule\n * (empty / `\"/\"` / `\".\"`|`\"..\"` / C0-C1 control / leading `\"_\"` (ADR-003) /\n * overlong), all as `BaerlyError{code:\"InvalidConfig\"}`. `role` and `verb`\n * are baked into the message so the caller doesn't need to format their own.\n *\n * Used by {@link Db.create} (twice — `app`, `tenant`) and\n * {@link Db.collectionReadContext} (once — `name`).\n *\n * @internal\n */\nconst assertKeySegment = (value: string, role: string, verb: string): void => {\n assertPathSegment(value, role, verb);\n};\n"],"mappings":";;;;;;;;AAaA,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,MAAa,iBAAiB,QAAqD;CAGjF,MAAM,QAAQ,IAAI,SAAS,QAAQ,MAAM,IAAI,UAAU;CACvD,OACE,IAAI,gBAAgB,gBAAiB,CAAC,QAAQ,aAAa,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;AAEhG;;;ACpBA,MAAM,cAAc,IAAI,YAAY;AAEpC,MAAM,uBAAuB;AAI7B,MAAM,uBACH,WAA0E,SAAS,OAAO,CAAC;AAE9F,IAAI,8BAA8B;AAKlC,MAAM,0BAA0B,kBAAiC;CAC/D,MAAM,MAAM,eAAe;CAC3B,IAAI,CAAC,cAAc,GAAG,GACpB;CAEF,IAAI,CAAC,iBAAiB,IAAI,0BAA0B,QAClD,MAAM,IAAI,YACR,iBACA,iQAEwE,qBAAqB,OAC/F;CAEF,IAAI,CAAC,6BAA6B;EAChC,8BAA8B;EAC9B,QAAQ,KACN,qFACF;CACF;AACF;;;;;;;;;;;AAsBA,MAAM,mBAAmB,GAAW,MAAsB;CACxD,MAAM,KAAK,YAAY,OAAO,CAAC;CAC/B,MAAM,KAAK,YAAY,OAAO,CAAC;CAC/B,MAAM,IAAI,KAAK,IAAI,GAAG,QAAQ,GAAG,MAAM;CACvC,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,GAAG,OAAO,GAAG,IAC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