@gusto/baerly-storage 0.1.1 → 0.2.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 (114) hide show
  1. package/README.md +27 -3
  2. package/dist/API.md +103 -22
  3. package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
  4. package/dist/app-config.d.ts +1 -1
  5. package/dist/auth.d.ts +1 -1
  6. package/dist/baerly.js +10 -10
  7. package/dist/baerly.js.map +1 -1
  8. package/dist/bytes-BXdamO3L.js +11 -0
  9. package/dist/bytes-BXdamO3L.js.map +1 -0
  10. package/dist/{client-CC5yVs1S.d.ts → client-DYZfoZb9.d.ts} +3 -3
  11. package/dist/client-react.d.ts +76 -85
  12. package/dist/client-react.js +95 -53
  13. package/dist/client-react.js.map +1 -1
  14. package/dist/client.d.ts +3 -3
  15. package/dist/cloudflare.d.ts +31 -4
  16. package/dist/cloudflare.js +72 -6
  17. package/dist/cloudflare.js.map +1 -1
  18. package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
  19. package/dist/config-DVfDGyw1.js.map +1 -0
  20. package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
  21. package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
  22. package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
  23. package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
  24. package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
  25. package/dist/current-json-C-EyJqs0.js.map +1 -0
  26. package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
  27. package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
  28. package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
  29. package/dist/dev-vite.d.ts +3 -3
  30. package/dist/dev-vite.js +3 -3
  31. package/dist/dev.d.ts +1 -1
  32. package/dist/dev.js +1 -1
  33. package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
  34. package/dist/doctor-Db-hzPmE.js.map +1 -0
  35. package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
  36. package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
  37. package/dist/errors-DOdL95kK.js.map +1 -1
  38. package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
  39. package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
  40. package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
  41. package/dist/fsck-CPPZWt9p.js.map +1 -0
  42. package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
  43. package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
  44. package/dist/http.d.ts +3 -3
  45. package/dist/http.js +1 -1
  46. package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
  47. package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
  48. package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
  49. package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
  50. package/dist/index.d.ts +5 -5
  51. package/dist/index.js +3 -3
  52. package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
  53. package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
  54. package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
  55. package/dist/maintenance-BRrThz8V.d.ts +449 -0
  56. package/dist/maintenance-BvOv6BMM.js +1295 -0
  57. package/dist/maintenance-BvOv6BMM.js.map +1 -0
  58. package/dist/maintenance-ClzBC1Vv.js +1895 -0
  59. package/dist/maintenance-ClzBC1Vv.js.map +1 -0
  60. package/dist/maintenance.d.ts +2 -323
  61. package/dist/maintenance.js +2 -2
  62. package/dist/node.d.ts +20 -79
  63. package/dist/node.js +2 -2
  64. package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
  65. package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
  66. package/dist/observability.d.ts +2 -2
  67. package/dist/observability.js +2 -2
  68. package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
  69. package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
  70. package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
  71. package/dist/query-BmiQy328.js.map +1 -0
  72. package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
  73. package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
  74. package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
  75. package/dist/restore-C6IcmLeA.js.map +1 -0
  76. package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
  77. package/dist/snapshot-SS8USDUF.js.map +1 -0
  78. package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
  79. package/dist/src-DU1sCMlr.js.map +1 -0
  80. package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
  81. package/dist/src-QQ7jDeL2.js.map +1 -0
  82. package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
  83. package/dist/src-zhEAmmF7.js.map +1 -0
  84. package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
  85. package/dist/subcommand-DZcHcsYp.js.map +1 -0
  86. package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
  87. package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
  88. package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
  89. package/dist/validate-DCq_0DIn.js.map +1 -0
  90. package/package.json +13 -6
  91. package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
  92. package/dist/config-Bsg8wgwo.js.map +0 -1
  93. package/dist/current-json-BkatBzF7.js.map +0 -1
  94. package/dist/doctor-B8h9GCN9.js.map +0 -1
  95. package/dist/fsck-DEz9lyCy.js.map +0 -1
  96. package/dist/indexes-BXn7a06a.js +0 -297
  97. package/dist/indexes-BXn7a06a.js.map +0 -1
  98. package/dist/log-walk-DIru96UT.js.map +0 -1
  99. package/dist/maintenance-Bn6ul9aV.js +0 -758
  100. package/dist/maintenance-Bn6ul9aV.js.map +0 -1
  101. package/dist/query-DcSbFLJt.js.map +0 -1
  102. package/dist/rebuild-index-C5gTXryd.js +0 -119
  103. package/dist/rebuild-index-C5gTXryd.js.map +0 -1
  104. package/dist/restore-CbKVMMpm.js.map +0 -1
  105. package/dist/snapshot-D7C4_FSl.js +0 -71
  106. package/dist/snapshot-D7C4_FSl.js.map +0 -1
  107. package/dist/snapshot-z_N9hpTe.js +0 -917
  108. package/dist/snapshot-z_N9hpTe.js.map +0 -1
  109. package/dist/src-Chafbw8r.js.map +0 -1
  110. package/dist/src-Cr9C7_tT.js.map +0 -1
  111. package/dist/src-n0Te1r98.js.map +0 -1
  112. package/dist/subcommand-BWs6K7zb.js +0 -110
  113. package/dist/subcommand-BWs6K7zb.js.map +0 -1
  114. package/dist/validate-DhH1lO8I.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { t as __commonJSMin } from "./chunk-EAsCxrDo.js";
2
- import { t as createCurrentJson } from "./current-json-BkatBzF7.js";
2
+ import { n as createCurrentJson } from "./current-json-C-EyJqs0.js";
3
3
  import { t as BaerlyError } from "./errors-DOdL95kK.js";
4
4
  import { createHash } from "node:crypto";
5
5
  import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
@@ -177,7 +177,7 @@ const ensureTable = async (storage, args) => {
177
177
  const key = `app/${args.app}/tenant/${args.tenant}/manifests/${args.table}/current.json`;
178
178
  try {
179
179
  await createCurrentJson(storage, key, {
180
- schema_version: 1,
180
+ schema_version: 2,
181
181
  snapshot: null,
182
182
  next_seq: 0,
183
183
  log_seq_start: 0,
@@ -185,7 +185,10 @@ const ensureTable = async (storage, args) => {
185
185
  epoch: 0,
186
186
  owner: "",
187
187
  claimed_at: ""
188
- }
188
+ },
189
+ tail_bytes: 0,
190
+ snapshot_bytes: 0,
191
+ snapshot_rows: 0
189
192
  });
190
193
  } catch (error) {
191
194
  if (error instanceof BaerlyError && error.code === "Conflict") return;
@@ -194,6 +197,22 @@ const ensureTable = async (storage, args) => {
194
197
  };
195
198
  //#endregion
196
199
  //#region packages/dev/src/local-fs.ts
200
+ const utf8Encoder = new TextEncoder();
201
+ /**
202
+ * Compare two keys by their UTF-8 byte sequences — the order S3 and R2
203
+ * use for `list`. JS's default string sort compares UTF-16 code units,
204
+ * which diverges from UTF-8 byte order for supplementary-plane
205
+ * characters; using this keeps `list` ordering faithful to the real
206
+ * adapters. (All kernel keys are ASCII base-32, where both orders
207
+ * coincide.)
208
+ */
209
+ const compareKeysUtf8 = (a, b) => {
210
+ const ba = utf8Encoder.encode(a);
211
+ const bb = utf8Encoder.encode(b);
212
+ const n = Math.min(ba.length, bb.length);
213
+ for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
214
+ return ba.length - bb.length;
215
+ };
197
216
  /**
198
217
  * `Storage` backed by a directory tree. Keys may contain `/` and map
199
218
  * to nested directories on disk so `ls`/`cat` work as expected.
@@ -279,11 +298,11 @@ var LocalFsStorage = class {
279
298
  const maxKeys = opts?.maxKeys ?? Infinity;
280
299
  const keys = [];
281
300
  await walk(this.#root, keys);
282
- keys.sort();
301
+ keys.sort(compareKeysUtf8);
283
302
  let yielded = 0;
284
303
  for (const key of keys) {
285
304
  if (!key.startsWith(prefix)) continue;
286
- if (key <= startAfter) continue;
305
+ if (compareKeysUtf8(key, startAfter) <= 0) continue;
287
306
  if (yielded >= maxKeys) return;
288
307
  opts?.signal?.throwIfAborted();
289
308
  yield {
@@ -349,4 +368,4 @@ const walk = async (root, out) => {
349
368
  //#endregion
350
369
  export { require_picocolors_browser as a, printDevBanner as i, ensureTable as n, renderDevLanding as r, LocalFsStorage as t };
351
370
 
352
- //# sourceMappingURL=src-n0Te1r98.js.map
371
+ //# sourceMappingURL=src-QQ7jDeL2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-QQ7jDeL2.js","names":["#root","#pathFor"],"sources":["../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js","../packages/dev/src/dev-banner.ts","../packages/dev/src/dev-landing.ts","../packages/dev/src/ensure-table.ts","../packages/dev/src/local-fs.ts"],"sourcesContent":["var x=String;\nvar create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}};\nmodule.exports=create();\nmodule.exports.createColors = create;\n","import { createColors } from \"picocolors\";\n\nexport interface DevBannerHint {\n readonly key: string;\n readonly value: string;\n}\n\nexport interface DevBannerOpts {\n readonly name: string;\n readonly primaryUrl?: { readonly label: string; readonly url: string };\n readonly apiUrl?: { readonly label: string; readonly url: string; readonly note?: string };\n readonly hints?: ReadonlyArray<DevBannerHint>;\n /** Force plain-text output (no color, no `←`). Defaults to !isTTY || CI. */\n readonly plain?: boolean;\n /** Sink. Defaults to process.stderr. */\n readonly write?: (chunk: string) => void;\n}\n\nexport function printDevBanner(opts: DevBannerOpts): void {\n const isPlain =\n opts.plain !== undefined\n ? opts.plain\n : process.env[\"CI\"] !== undefined || !process.stderr.isTTY;\n const write = opts.write ?? ((chunk) => process.stderr.write(chunk));\n const pc = createColors(!isPlain);\n const hints = opts.hints ?? [];\n\n const lines: string[] = [];\n\n if (isPlain) {\n lines.push(`baerly · ${opts.name}`);\n\n if (opts.primaryUrl) {\n lines.push(`${opts.primaryUrl.label}: ${opts.primaryUrl.url}`);\n }\n if (opts.apiUrl) {\n const note = opts.apiUrl.note ? ` (${opts.apiUrl.note})` : \"\";\n lines.push(`${opts.apiUrl.label}: ${opts.apiUrl.url}${note}`);\n }\n for (const hint of hints) {\n lines.push(`${hint.key}: ${hint.value}`);\n }\n write(lines.join(\"\\n\") + \"\\n\");\n } else {\n lines.push(pc.bold(pc.cyan(`▎ baerly · ${opts.name}`)));\n lines.push(\"\");\n\n if (opts.primaryUrl) {\n const marker = ` ${pc.green(\"← open this\")}`;\n lines.push(` ${pc.dim(opts.primaryUrl.label)} → ${opts.primaryUrl.url}${marker}`);\n }\n if (opts.apiUrl) {\n const note = opts.apiUrl.note ? ` ${pc.dim(`(${opts.apiUrl.note})`)}` : \"\";\n lines.push(` ${pc.dim(opts.apiUrl.label)} → ${opts.apiUrl.url}${note}`);\n }\n if ((opts.primaryUrl || opts.apiUrl) && hints.length > 0) {\n lines.push(\"\");\n }\n if (hints.length > 0) {\n const maxKeyLen = Math.max(...hints.map((h) => h.key.length));\n for (const hint of hints) {\n lines.push(` ${pc.dim(hint.key.padEnd(maxKeyLen))} ${hint.value}`);\n }\n }\n lines.push(\"\");\n write(lines.join(\"\\n\"));\n }\n}\n","/**\n * Dev landing page for the API root (`GET /`).\n *\n * The HTTP surface is API-only: every path outside `/v1/*`\n * returns the {@link HttpErrorEnvelope} 404 shape. That's correct for\n * production but confusing in local dev — a user who clicks the\n * `http://localhost:3000` link in their terminal sees a JSON 404 and\n * assumes the server is broken.\n *\n * Adapters that wire the {@link DevLandingOptions} opt-in surface a\n * small HTML page on `GET /` instead: app label, a clickable link to\n * the UI, a `/v1/healthz` probe link, and a note that `/v1/c/*` is\n * auth-gated. `GET /favicon.ico` answers 204 so browsers don't pin a\n * second JSON 404 next to the landing page.\n *\n * Production deployments leave the option unset; the 404 falls\n * through to the existing envelope.\n */\n\n/** Options for {@link renderDevLanding}. */\nexport interface DevLandingOptions {\n /** Bucket-prefix / app name (typically passed through from the adapter's `app` option). */\n readonly app: string;\n /** URL of the human-facing UI (e.g., `\"http://localhost:5173\"`). */\n readonly uiUrl: string;\n}\n\n/**\n * Render the dev landing page HTML. Dependency-free; system fonts\n * only; no JS. All substitutions are HTML-escaped to keep the page\n * inert even when `app` / `uiUrl` come from env vars.\n */\nexport const renderDevLanding = (opts: DevLandingOptions): string => {\n const label = escapeHtml(opts.app);\n const app = escapeHtml(opts.app);\n const uiUrl = escapeHtml(opts.uiUrl);\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>${label} — baerly api</title>\n<style>\n body { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1.5rem; color: #222; line-height: 1.5; }\n h1 { font-size: 1.25rem; margin: 0 0 0.25rem; }\n p.tag { color: #666; margin: 0 0 1.5rem; font-size: 0.9rem; }\n a { color: #06c; }\n ul { padding-left: 1.25rem; }\n li { margin: 0.25rem 0; }\n code { background: #f3f3f3; padding: 0.1em 0.35em; border-radius: 3px; font-size: 0.9em; }\n</style>\n</head>\n<body>\n<h1>${label}</h1>\n<p class=\"tag\">baerly api server · app <code>${app}</code></p>\n<p>This is the API server. The UI lives at <a href=\"${uiUrl}\">${uiUrl}</a>.</p>\n<ul>\n <li>Open the UI: <a href=\"${uiUrl}\">${uiUrl}</a></li>\n <li>Health probe: <a href=\"/v1/healthz\">/v1/healthz</a></li>\n <li>CRUD routes under <code>/v1/c/*</code> require an auth header and aren't clickable from here.</li>\n</ul>\n</body>\n</html>\n`;\n};\n\nconst escapeHtml = (s: string): string =>\n s.replace(/[&<>\"']/g, (c) => {\n switch (c) {\n case \"&\": {\n return \"&amp;\";\n }\n case \"<\": {\n return \"&lt;\";\n }\n case \">\": {\n return \"&gt;\";\n }\n case '\"': {\n return \"&quot;\";\n }\n default: {\n return \"&#39;\";\n }\n }\n });\n","import {\n BaerlyError,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Optional pre-warm: idempotently create the `current.json` manifest\n * for a single `(app, tenant, table)` triple. The kernel auto-creates\n * this manifest on the first commit anyway (see `Db.create` and\n * `Writer.commit`), so calling `ensureTable` is **not required** for\n * correctness — it's a one-Class-A-PUT optimization for callers that\n * want the manifest in place before the first request lands (seed\n * scripts, deploy-time provisioning, CI fixtures that snapshot the\n * bucket between phases, etc.).\n *\n * Wraps {@link createCurrentJson} with the canonical key shape\n * (`app/<app>/tenant/<tenant>/manifests/<table>/current.json`) and\n * swallows `BaerlyError{code:\"Conflict\"}` so re-runs are safe. An\n * existing manifest is preserved verbatim — this function never\n * overwrites a populated manifest. The seed shape matches the\n * kernel's auto-create exactly, so a pre-warm and an\n * auto-provisioned bucket are byte-identical.\n *\n * @example\n * ```ts\n * import { LocalFsStorage, ensureTable } from \"@gusto/baerly-storage/dev\";\n *\n * const storage = new LocalFsStorage({ root: \"./.baerly-data\" });\n * // Pre-warm so the first request doesn't pay the bootstrap PUT.\n * await ensureTable(storage, { app: \"helpdesk\", tenant: \"demo\", table: \"tickets\" });\n * // …then `baerlyNode({ config, storage, verifier })`.\n * ```\n */\nexport const ensureTable = async (\n storage: Storage,\n args: { app: string; tenant: string; table: string },\n): Promise<void> => {\n const key = `app/${args.app}/tenant/${args.tenant}/manifests/${args.table}/current.json`;\n try {\n await createCurrentJson(storage, key, {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n next_seq: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n tail_bytes: 0,\n snapshot_bytes: 0,\n snapshot_rows: 0,\n });\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"Conflict\") {\n return;\n }\n throw error;\n }\n};\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, posix, relative, resolve, sep } from \"node:path\";\nimport {\n BaerlyError,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\n\nexport interface LocalFsStorageOptions {\n /** Root directory; treated as \"the bucket\". */\n root: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and R2\n * use for `list`. JS's default string sort compares UTF-16 code units,\n * which diverges from UTF-8 byte order for supplementary-plane\n * characters; using this keeps `list` ordering faithful to the real\n * adapters. (All kernel keys are ASCII base-32, where both orders\n * coincide.)\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 * `Storage` backed by a directory tree. Keys may contain `/` and map\n * to nested directories on disk so `ls`/`cat` work as expected.\n *\n * ETags are content-addressed: `\"<sha-256-hex>\"` (the surrounding\n * double-quotes match S3's wire format for non-multipart objects).\n * Identical bodies share an ETag across runs — the property that\n * makes this adapter useful for fixture-based tests.\n *\n * Writes are atomic via `writeFile(temp) + rename(final)`; readers\n * never see a partially-written file. The adapter does NOT coordinate\n * cross-process `ifMatch`/`ifNoneMatch` checks (a TOCTOU race is\n * possible if two processes write the same key concurrently).\n * Single-process `baerlyDev()` is the design center; multi-process\n * scenarios use the S3 / Minio path.\n *\n * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in\n * `@baerly/dev` because the protocol kernel is pure-modules / no I/O\n * and must remain Worker-bundleable.\n */\nexport class LocalFsStorage implements Storage {\n readonly #root: string;\n\n constructor(opts: LocalFsStorageOptions) {\n this.#root = resolve(opts.root);\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n let body: Buffer;\n try {\n body = await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.get(${key}): ${(error as Error).message}`,\n error,\n );\n }\n const etag = etagOf(body);\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: toUint8Array(body), etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n const newEtag = etagOf(body);\n\n if (opts?.ifMatch !== undefined || opts?.ifNoneMatch === \"*\") {\n // TOCTOU within a process — fine. Cross-process callers should\n // not rely on these guards (see class JSDoc).\n const existing = await readExisting(path);\n if (opts?.ifNoneMatch === \"*\" && existing !== null) {\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 === null) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n const currentEtag = etagOf(existing);\n if (currentEtag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`,\n );\n }\n }\n }\n\n await mkdir(dirname(path), { recursive: true });\n // Write to a unique temp path then rename for atomicity. Temp lives\n // in `os.tmpdir()` so a half-written file never appears under the\n // bucket root where `list` might see it. PID + timestamp + random\n // tail makes the name unique across concurrent writers in the same\n // process.\n const tmp = join(\n tmpdir(),\n `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n await writeFile(tmp, body);\n try {\n await rename(tmp, path);\n } catch (error) {\n // Best-effort cleanup of the temp file; swallow any error there\n // so the original failure surfaces unchanged.\n await rm(tmp, { force: true }).catch(() => {});\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n error,\n );\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n try {\n await rm(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return;\n } // idempotent\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.delete(${key}): ${(error as Error).message}`,\n error,\n );\n }\n }\n\n async *list(\n prefix: string,\n opts?: {\n startAfter?: string;\n maxKeys?: number;\n signal?: AbortSignal;\n },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const keys: string[] = [];\n await walk(this.#root, keys);\n keys.sort(compareKeysUtf8);\n let yielded = 0;\n for (const key of keys) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (compareKeysUtf8(key, startAfter) <= 0) {\n continue;\n }\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const buf = await readFile(this.#pathFor(key));\n yield { key, etag: etagOf(buf) };\n yielded += 1;\n }\n }\n\n /**\n * Map an S3-style key to a filesystem path under `#root`, rejecting\n * anything that could escape the root (path traversal, absolute\n * paths, empty segments, backslashes). All rejections throw\n * `BaerlyError(\"InvalidConfig\", …)`.\n */\n #pathFor(key: string): string {\n if (key.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"LocalFsStorage: empty key\");\n }\n if (key.startsWith(\"/\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: leading \"/\" in key: ${key}`);\n }\n if (key.includes(\"\\\\\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: backslash in key: ${key}`);\n }\n const segments = key.split(\"/\");\n if (segments.some((s) => s === \"\" || s === \".\" || s === \"..\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: illegal segment in key: ${key}`);\n }\n const path = join(this.#root, ...segments);\n if (path !== this.#root && !path.startsWith(this.#root + sep)) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: resolved path escapes root: ${key}`);\n }\n return path;\n }\n}\n\nconst etagOf = (body: Uint8Array): string => {\n const h = createHash(\"sha256\").update(body).digest(\"hex\");\n return `\"${h}\"`;\n};\n\nconst toUint8Array = (buf: Buffer): Uint8Array =>\n new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\nconst isErrnoException = (e: unknown): e is NodeJS.ErrnoException =>\n typeof e === \"object\" && e !== null && \"code\" in e;\n\nconst readExisting = async (path: string): Promise<Buffer | null> => {\n try {\n return await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n};\n\n/**\n * Recursive directory walk. Yields filesystem-relative paths in\n * forward-slash form so callers can use them as S3-style keys\n * regardless of the host's path separator.\n */\nconst walk = async (root: string, out: string[]): Promise<void> => {\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop()!;\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n continue;\n }\n throw error;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (entry.isFile()) {\n out.push(relative(root, full).split(sep).join(pos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M,OAAO,GACtB,IAAI,KAAK,SAAS,MAAM,IAAI,EAAE,MAAM,GAAG,EAAE,KAAK,MAAM,GAAG,CAAC;EAE5D;CACF;AACF"}
@@ -1,8 +1,27 @@
1
- import { d as SHARED_SECRET_MISSING_MESSAGE, f as decodeJsonBytes, l as NO_AUTH_CONFIGURED_MESSAGE, r as readCurrentJson } from "./current-json-BkatBzF7.js";
1
+ import { _ as SHARED_SECRET_MISSING_MESSAGE, h as NO_AUTH_CONFIGURED_MESSAGE, i as readCurrentJson, v as decodeJsonBytes } from "./current-json-C-EyJqs0.js";
2
2
  import { t as BaerlyError } from "./errors-DOdL95kK.js";
3
- import { a as runReplaceById, i as runInsert, s as Writer, t as makeQuery } from "./query-DcSbFLJt.js";
3
+ import { y as assertNameNotReserved } from "./maintenance-ClzBC1Vv.js";
4
+ import { a as runReplaceById, i as runInsert, s as Writer, t as makeQuery } from "./query-BmiQy328.js";
4
5
  import { t as sharedSecret } from "./shared-secret-BJdSwpgw.js";
5
6
  //#region packages/protocol/src/storage/memory.ts
7
+ const utf8Encoder = new TextEncoder();
8
+ /**
9
+ * Compare two keys by their UTF-8 byte sequences — the order S3 and
10
+ * R2 use for `list`. JavaScript's default string sort compares UTF-16
11
+ * code units, which diverges from UTF-8 byte order for supplementary-
12
+ * plane characters (e.g. emoji sort before high-BMP characters under
13
+ * UTF-16 but after them in UTF-8). Using this keeps the in-memory
14
+ * reference backend faithful to the real adapters. (All kernel keys
15
+ * are ASCII base-32, where the two orders coincide — this only
16
+ * matters for adversarial / non-ASCII keys.)
17
+ */
18
+ const compareKeysUtf8 = (a, b) => {
19
+ const ba = utf8Encoder.encode(a);
20
+ const bb = utf8Encoder.encode(b);
21
+ const n = Math.min(ba.length, bb.length);
22
+ for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
23
+ return ba.length - bb.length;
24
+ };
6
25
  /**
7
26
  * In-memory `Storage`. The randomized property test runs against
8
27
  * this; it must be deterministic — no clocks beyond the caller's,
@@ -11,6 +30,17 @@ import { t as sharedSecret } from "./shared-secret-BJdSwpgw.js";
11
30
  * ETags are a monotonically increasing hex counter formatted in the
12
31
  * `"<hex>"` shape S3 returns (the surrounding double-quotes are part
13
32
  * of the ETag header value). Keys are stored verbatim.
33
+ *
34
+ * **Test-confidence caveat:** every method resolves on the microtask
35
+ * queue with no real concurrency, so `put` reads `existing` and writes
36
+ * back with no interleaving. MemoryStorage therefore CANNOT exercise the
37
+ * compare-and-swap race the writer-fence model depends on — two writers
38
+ * contending on one `current.json` always serialize here, so a green run
39
+ * is necessary but not sufficient. That race is covered only by the
40
+ * randomized integration tests against real S3 / Minio
41
+ * (`tests/integration/randomized.test.ts`, `node-minio` variant).
42
+ * Relatedly, `serverDate` returns the local clock, not an independent
43
+ * server clock (see the `put` return below).
14
44
  */
15
45
  var MemoryStorage = class {
16
46
  #objects = /* @__PURE__ */ new Map();
@@ -56,7 +86,7 @@ var MemoryStorage = class {
56
86
  opts?.signal?.throwIfAborted();
57
87
  const startAfter = opts?.startAfter ?? "";
58
88
  const maxKeys = opts?.maxKeys ?? Infinity;
59
- const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && k > startAfter).toSorted();
89
+ const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0).toSorted(compareKeysUtf8);
60
90
  let yielded = 0;
61
91
  for (const key of sorted) {
62
92
  if (yielded >= maxKeys) return;
@@ -515,8 +545,9 @@ var Db = class Db {
515
545
  const assertKeySegment = (value, role, verb) => {
516
546
  if (value.length === 0) throw new BaerlyError("InvalidConfig", `${verb}: ${role} must be non-empty (got ${JSON.stringify(value)})`);
517
547
  if (value.includes("/")) throw new BaerlyError("InvalidConfig", `${verb}: "/" is reserved as the key-segment separator (got ${role}=${JSON.stringify(value)})`);
548
+ assertNameNotReserved(value, verb);
518
549
  };
519
550
  //#endregion
520
551
  export { MemoryStorage as i, resolveVerifier as n, collectionsToMaps as r, Db as t };
521
552
 
522
- //# sourceMappingURL=src-Chafbw8r.js.map
553
+ //# sourceMappingURL=src-zhEAmmF7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-zhEAmmF7.js","names":["#objects","#etagCounter","#nextEtag","#storage","#schemas","#indexes"],"sources":["../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":["import { BaerlyError } from \"../errors.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\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 #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 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 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 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 */\nexport type 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 LOG_KEY_PREFIX,\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 { assertNameNotReserved } from \"./names.ts\";\nimport type { CollectionReadContext } from \"./query.ts\";\nimport { Writer, type CommitInput } from \"./writer.ts\";\nimport { makeCollection } from \"./collection.ts\";\n\n/**\n * In-memory buffer for a single in-flight {@link Db.transaction}\n * call. The `Collection<T>` instance passed to the transaction body holds\n * a reference to this object; every mutation verb appends to\n * `mutations` instead of calling `Writer.commit` directly.\n *\n * After the body resolves, `Db.transaction` performs ONE\n * `Writer.commitBatch(...)` to commit every buffered mutation\n * in a single CAS attempt.\n *\n * @internal — referenced by `collection.ts` and `query.ts`; not part of\n * the public API surface for app code.\n */\nexport interface TxContext {\n /**\n * The collection name the transaction is scoped to. Mutation verbs\n * runtime-assert that their `Collection<T>`'s `name` matches this\n * field before appending — the type system already prevents the\n * legitimate path, this catches the bug path (a stale `Query<T>`\n * re-attached to a different collection's transaction).\n */\n readonly collection: string;\n\n /**\n * Mutations buffered in order of issuance. The commit converts\n * each into one `CommitInput` (`Writer`'s single-mutation\n * shape) and passes the array to `Writer.commitBatch`.\n */\n readonly mutations: BufferedMutation[];\n}\n\n/**\n * One buffered mutation. Mirrors {@link CommitInput} minus\n * `collection` (which is constant per transaction and lives on\n * `TxContext.collection`).\n *\n * @internal — only used inside the `Db.transaction` path.\n */\nexport interface BufferedMutation {\n readonly op: \"I\" | \"U\" | \"D\";\n readonly docId: string;\n readonly body?: DocumentData;\n readonly origin?: string;\n}\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 or contains `/` (the segment separator).\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `app` or `tenant` is\n * empty or contains `/`.\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 or\n * contains `/`.\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 or\n * contains `/`.\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 * Atomic mutation over a single collection. The callback receives a\n * `Collection<T>` (not a `Db`) so cross-collection writes inside a\n * transaction are a TypeScript error at compile time — not a\n * runtime trap. Mutation verbs (`insert`, `update`, `replace`,\n * `delete`) buffer; reads (`first`, `all`, `count`) go through\n * `Storage` live (no MVCC snapshot, no read-your-writes).\n *\n * Single-attempt: on CAS conflict throws\n * `BaerlyError{code:\"Conflict\"}`. The body MAY have already run its\n * read side-effects (no rollback of in-memory state); the write\n * side-effects either all landed or none did. Wrap in a retry\n * loop you wrote if you want one.\n *\n * Empty body (or a body that buffers nothing) resolves without\n * touching `current.json`.\n *\n * @throws BaerlyError code=\"Conflict\" — CAS lost on the collection's\n * `current.json`. Caller decides whether to re-run the body.\n * @throws Whatever the body throws — re-thrown as-is. The commit\n * is skipped when the body throws.\n * @throws BaerlyError code=\"InvalidConfig\" — `collection` is empty or\n * contains `/`.\n *\n * @remarks\n * Single-collection by design. Cross-collection 2PC was rejected on\n * cost grounds — multiple round-trips per commit, no native fencing\n * primitive on S3-compatible storage, no rollback to undo a\n * successful PUT — and because in-doubt-transaction recovery state\n * would contradict the stateless-writer model. Applications that\n * need cross-collection atomicity re-express it at the app layer: an\n * idempotent move keyed off source-row state, or a single\n * denormalized collection with a `status` column.\n *\n * @example\n * ```ts\n * await db.transaction(\"tickets\", async (tx) => {\n * const open = await tx.where({ status: \"open\" }).count();\n * if (open < 100) await tx.insert({ title: \"another\", status: \"open\" });\n * });\n * ```\n */\n async transaction<T extends DocumentData = DocumentData>(\n collection: string,\n body: (tx: Collection<T>) => Promise<void>,\n ): Promise<void> {\n assertKeySegment(collection, \"collection\", \"Db.transaction\");\n\n const txCtx: TxContext = { collection, mutations: [] };\n const collectionPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;\n\n // Build a Collection<T> whose mutation verbs buffer onto `txCtx`. The\n // read path ignores `txCtx` entirely (locked: no MVCC, no\n // read-your-writes inside a transaction).\n const schema = this.#schemas.get(collection);\n const indexes = this.#indexes.get(collection) ?? [];\n const tx = makeCollection<T>({\n storage: this.#storage,\n collectionPrefix,\n collectionName: collection,\n txCtx,\n indexes,\n ...(schema !== undefined ? { schema } : {}),\n });\n\n // Run the body. Reads go through Storage live; mutations append\n // to txCtx.mutations. A throw here propagates AS-IS and skips\n // the commit (txCtx.mutations is discarded).\n await body(tx);\n\n // Empty buffer — nothing to commit, nothing to throw.\n if (txCtx.mutations.length === 0) {\n return;\n }\n\n // Map BufferedMutations -> CommitInputs and fire one\n // single-attempt commitBatch. On CAS loss commitBatch throws\n // `Conflict` and we surface it unchanged.\n const inputs: CommitInput[] = [];\n for (const m of txCtx.mutations) {\n const input: CommitInput = {\n op: m.op,\n collection,\n docId: m.docId,\n ...(m.body !== undefined ? { body: m.body } : {}),\n ...(m.origin !== undefined ? { origin: m.origin } : {}),\n };\n inputs.push(input);\n }\n\n const writer = new Writer({\n storage: this.#storage,\n currentJsonKey: `${collectionPrefix}/current.json`,\n options: { indexes },\n });\n await writer.commitBatch(inputs);\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 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_KEY_PREFIX}/<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 const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/${LOG_KEY_PREFIX}/${seq}.json`;\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/**\n * Guard a string used as a path-segment in the bucket-key encoding.\n * Rejects empty and `/`-containing values with\n * `BaerlyError{code:\"InvalidConfig\"}`. `role` and `verb` are baked\n * into the message so the caller doesn't need to format their own.\n *\n * Used by {@link Db.create} (twice — `app`, `tenant`),\n * {@link Db.collectionReadContext} (once — `name`), and\n * {@link Db.transaction} (once — `collection`).\n *\n * @internal\n */\nconst assertKeySegment = (value: string, role: string, verb: string): void => {\n if (value.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${verb}: ${role} must be non-empty (got ${JSON.stringify(value)})`,\n );\n }\n if (value.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${verb}: \"/\" is reserved as the key-segment separator (got ${role}=${JSON.stringify(value)})`,\n );\n }\n // Applied to ALL key segments (app, tenant, collection) — one\n // consistent leading-`_` reservation (ADR-007).\n assertNameNotReserved(value, verb);\n};\n"],"mappings":";;;;;;AAgBA,MAAM,cAAc,IAAI,YAAY;;;;;;;;;;;AAYpC,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,IACf,OAAO,GAAG,KAAM,GAAG;CAGvB,OAAO,GAAG,SAAS,GAAG;AACxB;;;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I;GACF,SAAS,gBAAgB,IAAI,IAAI;EACnC,SAAS,OAAO;GACd,MAAM,IAAI,YACR,mBACA,gBAAgB,IAAI,2BACpB,KACF;EACF;EACA,OAAO;CACT;AACF;;;;;;;;;;;;;AAcA,MAAM,oBAAoB,OAAe,MAAc,SAAuB;CAC5E,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,YACR,iBACA,GAAG,KAAK,IAAI,KAAK,0BAA0B,KAAK,UAAU,KAAK,EAAE,EACnE;CAEF,IAAI,MAAM,SAAS,GAAG,GACpB,MAAM,IAAI,YACR,iBACA,GAAG,KAAK,sDAAsD,KAAK,GAAG,KAAK,UAAU,KAAK,EAAE,EAC9F;CAIF,sBAAsB,OAAO,IAAI;AACnC"}
@@ -1,18 +1,29 @@
1
- import { i as RATE_LIMIT_BACKOFF_MILLIS } from "./config-Bsg8wgwo.js";
2
- import { o as BaerlyError } from "./baerly.js";
1
+ import { d as RATE_LIMIT_BACKOFF_MILLIS, t as loadAppConfig } from "./config-DVfDGyw1.js";
2
+ import { a as setJsonMode, c as parseArgs, n as emitError, o as BaerlyError, s as defineCommand } from "./baerly.js";
3
+ import "node:stream";
3
4
  import { createHash } from "node:crypto";
4
5
  import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
5
6
  import { tmpdir } from "node:os";
6
7
  import { dirname, join, posix, relative, resolve, sep } from "node:path";
7
- //#region ../protocol/src/bytes.ts
8
+ //#region ../protocol/src/storage/memory.ts
9
+ const utf8Encoder$1 = new TextEncoder();
8
10
  /**
9
- * UTF-8 JSON byte helpers — names the encode/decode idiom used by
10
- * every content body, log entry, snapshot, and current.json payload.
11
+ * Compare two keys by their UTF-8 byte sequences — the order S3 and
12
+ * R2 use for `list`. JavaScript's default string sort compares UTF-16
13
+ * code units, which diverges from UTF-8 byte order for supplementary-
14
+ * plane characters (e.g. emoji sort before high-BMP characters under
15
+ * UTF-16 but after them in UTF-8). Using this keeps the in-memory
16
+ * reference backend faithful to the real adapters. (All kernel keys
17
+ * are ASCII base-32, where the two orders coincide — this only
18
+ * matters for adversarial / non-ASCII keys.)
11
19
  */
12
- const encodeJsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value));
13
- const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
14
- //#endregion
15
- //#region ../protocol/src/storage/memory.ts
20
+ const compareKeysUtf8$1 = (a, b) => {
21
+ const ba = utf8Encoder$1.encode(a);
22
+ const bb = utf8Encoder$1.encode(b);
23
+ const n = Math.min(ba.length, bb.length);
24
+ for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
25
+ return ba.length - bb.length;
26
+ };
16
27
  /**
17
28
  * In-memory `Storage`. The randomized property test runs against
18
29
  * this; it must be deterministic — no clocks beyond the caller's,
@@ -21,6 +32,17 @@ const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
21
32
  * ETags are a monotonically increasing hex counter formatted in the
22
33
  * `"<hex>"` shape S3 returns (the surrounding double-quotes are part
23
34
  * of the ETag header value). Keys are stored verbatim.
35
+ *
36
+ * **Test-confidence caveat:** every method resolves on the microtask
37
+ * queue with no real concurrency, so `put` reads `existing` and writes
38
+ * back with no interleaving. MemoryStorage therefore CANNOT exercise the
39
+ * compare-and-swap race the writer-fence model depends on — two writers
40
+ * contending on one `current.json` always serialize here, so a green run
41
+ * is necessary but not sufficient. That race is covered only by the
42
+ * randomized integration tests against real S3 / Minio
43
+ * (`tests/integration/randomized.test.ts`, `node-minio` variant).
44
+ * Relatedly, `serverDate` returns the local clock, not an independent
45
+ * server clock (see the `put` return below).
24
46
  */
25
47
  var MemoryStorage = class {
26
48
  #objects = /* @__PURE__ */ new Map();
@@ -66,7 +88,7 @@ var MemoryStorage = class {
66
88
  opts?.signal?.throwIfAborted();
67
89
  const startAfter = opts?.startAfter ?? "";
68
90
  const maxKeys = opts?.maxKeys ?? Infinity;
69
- const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && k > startAfter).toSorted();
91
+ const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && compareKeysUtf8$1(k, startAfter) > 0).toSorted(compareKeysUtf8$1);
70
92
  let yielded = 0;
71
93
  for (const key of sorted) {
72
94
  if (yielded >= maxKeys) return;
@@ -154,7 +176,23 @@ const uint2strDesc = (num, bits) => {
154
176
  };
155
177
  //#endregion
156
178
  //#region ../protocol/src/time.ts
157
- const timestamp = (epoch = 0) => uint2strDesc(epoch, 42);
179
+ /**
180
+ * Encode an epoch-millis instant as a lexicographically-DEScending
181
+ * base-32 key (newer sorts first). The load-bearing LSN ordering
182
+ * primitive — see {@link uint2strDesc}.
183
+ *
184
+ * `epoch` is REQUIRED and validated. There is no default: an argless
185
+ * call used to encode `0`, which descending-sorts as the most-ancient
186
+ * instant and would silently invert ordering. A non-finite, negative,
187
+ * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)
188
+ * would corrupt the key silently rather than fail loud, so it throws
189
+ * `Internal` instead — this is an invariant violation, not caller config
190
+ * (the only legitimate argument is `Date.now()`).
191
+ */
192
+ const timestamp = (epoch) => {
193
+ if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** 42) throw new BaerlyError("Internal", `timestamp(): epoch must be a non-negative integer < 2^42 (got ${epoch})`);
194
+ return uint2strDesc(epoch, 42);
195
+ };
158
196
  /**
159
197
  * Delay for `ms` milliseconds, with optional cancellation. If
160
198
  * `signal` aborts before the delay elapses, the returned promise
@@ -175,6 +213,22 @@ const delay = (ms, signal) => new Promise((resolve, reject) => {
175
213
  });
176
214
  //#endregion
177
215
  //#region ../dev/src/local-fs.ts
216
+ const utf8Encoder = new TextEncoder();
217
+ /**
218
+ * Compare two keys by their UTF-8 byte sequences — the order S3 and R2
219
+ * use for `list`. JS's default string sort compares UTF-16 code units,
220
+ * which diverges from UTF-8 byte order for supplementary-plane
221
+ * characters; using this keeps `list` ordering faithful to the real
222
+ * adapters. (All kernel keys are ASCII base-32, where both orders
223
+ * coincide.)
224
+ */
225
+ const compareKeysUtf8 = (a, b) => {
226
+ const ba = utf8Encoder.encode(a);
227
+ const bb = utf8Encoder.encode(b);
228
+ const n = Math.min(ba.length, bb.length);
229
+ for (let i = 0; i < n; i++) if (ba[i] !== bb[i]) return ba[i] - bb[i];
230
+ return ba.length - bb.length;
231
+ };
178
232
  /**
179
233
  * `Storage` backed by a directory tree. Keys may contain `/` and map
180
234
  * to nested directories on disk so `ls`/`cat` work as expected.
@@ -260,11 +314,11 @@ var LocalFsStorage = class {
260
314
  const maxKeys = opts?.maxKeys ?? Infinity;
261
315
  const keys = [];
262
316
  await walk(this.#root, keys);
263
- keys.sort();
317
+ keys.sort(compareKeysUtf8);
264
318
  let yielded = 0;
265
319
  for (const key of keys) {
266
320
  if (!key.startsWith(prefix)) continue;
267
- if (key <= startAfter) continue;
321
+ if (compareKeysUtf8(key, startAfter) <= 0) continue;
268
322
  if (yielded >= maxKeys) return;
269
323
  opts?.signal?.throwIfAborted();
270
324
  yield {
@@ -4115,6 +4169,40 @@ const xmlVal = (obj, name) => {
4115
4169
  if (typeof v !== "string" || v === "") return;
4116
4170
  return decodeURIComponent(v.replace(/\+/g, " "));
4117
4171
  };
4172
+ const rawXmlVal = (obj, name) => {
4173
+ const v = obj[name];
4174
+ return typeof v === "string" && v !== "" ? v : void 0;
4175
+ };
4176
+ /**
4177
+ * Parse an S3 `<Error><Code>…</Code><Message>…</Message></Error>`
4178
+ * body. Returns `undefined` when the body is not a recognizable S3
4179
+ * error document (empty, HTML, a success payload, or a DTD), so
4180
+ * callers can fall back to the raw response text. This never throws:
4181
+ * it runs on a path that is already reporting an error.
4182
+ */
4183
+ const parseS3Error = (xml) => {
4184
+ if (!/<Error\b/i.test(xml) || /<!DOCTYPE\b/i.test(xml)) return;
4185
+ let result;
4186
+ try {
4187
+ result = xmlParser.parse(xml);
4188
+ } catch {
4189
+ return;
4190
+ }
4191
+ const root = result.Error;
4192
+ if (root === void 0) return;
4193
+ const code = rawXmlVal(root, "Code");
4194
+ const message = rawXmlVal(root, "Message");
4195
+ if (code === void 0 && message === void 0) return;
4196
+ return {
4197
+ ...code !== void 0 && { Code: code },
4198
+ ...message !== void 0 && { Message: message }
4199
+ };
4200
+ };
4201
+ const parseLastModified = (lm) => {
4202
+ if (lm === void 0) return;
4203
+ const d = new Date(lm);
4204
+ return Number.isNaN(d.getTime()) ? void 0 : d;
4205
+ };
4118
4206
  const parseListObjectsV2CommandOutput = (xml) => {
4119
4207
  if (/<!DOCTYPE\b/i.test(xml)) throw new BaerlyError("InvalidResponse", "DTD not allowed in S3 XML responses");
4120
4208
  let result;
@@ -4126,14 +4214,13 @@ const parseListObjectsV2CommandOutput = (xml) => {
4126
4214
  const root = result.ListBucketResult ?? {};
4127
4215
  return {
4128
4216
  Contents: (root["Contents"] ?? []).map((content) => {
4129
- const lm = xmlVal(content, "LastModified");
4130
4217
  return {
4131
- ETag: xmlVal(content, "ETag"),
4218
+ ETag: rawXmlVal(content, "ETag"),
4132
4219
  Key: xmlVal(content, "Key"),
4133
- LastModified: lm ? new Date(lm) : void 0
4220
+ LastModified: parseLastModified(rawXmlVal(content, "LastModified"))
4134
4221
  };
4135
4222
  }),
4136
- NextContinuationToken: xmlVal(root, "NextContinuationToken")
4223
+ NextContinuationToken: rawXmlVal(root, "NextContinuationToken")
4137
4224
  };
4138
4225
  };
4139
4226
  //#endregion
@@ -4184,6 +4271,14 @@ const retryAfterCause = (res) => {
4184
4271
  const hint = parseRetryAfter(res.headers.get("Retry-After"));
4185
4272
  return hint !== void 0 ? { retryAfterSeconds: hint } : {};
4186
4273
  };
4274
+ const s3ErrorDetail = (status, body) => {
4275
+ const parsed = parseS3Error(body);
4276
+ if (parsed !== void 0) {
4277
+ const code = parsed.Code ?? "UnknownError";
4278
+ return parsed.Message !== void 0 ? `${status} ${code}: ${parsed.Message}` : `${status} ${code}`;
4279
+ }
4280
+ return `${status} ${body}`;
4281
+ };
4187
4282
  const retry = async (fn, { retries = 8, backoffMs = 100, maxDelayMs = 1e4 } = {}) => {
4188
4283
  let wait = backoffMs;
4189
4284
  for (let attempt = 0; attempt <= retries; attempt++) try {
@@ -4276,7 +4371,7 @@ var S3HttpStorage = class {
4276
4371
  status: res.status,
4277
4372
  ...retryAfterCause(res)
4278
4373
  });
4279
- throw new BaerlyError("InvalidResponse", `GET ${key}: ${res.status} ${await res.text()}`);
4374
+ throw new BaerlyError("InvalidResponse", `GET ${key}: ${s3ErrorDetail(res.status, await res.text())}`);
4280
4375
  }
4281
4376
  });
4282
4377
  }
@@ -4301,7 +4396,7 @@ var S3HttpStorage = class {
4301
4396
  status: res.status,
4302
4397
  ...retryAfterCause(res)
4303
4398
  });
4304
- if (res.status !== 200 && res.status !== 204) throw new BaerlyError("InvalidResponse", `PUT ${key}: ${res.status} ${await res.text()}`);
4399
+ if (res.status !== 200 && res.status !== 204) throw new BaerlyError("InvalidResponse", `PUT ${key}: ${s3ErrorDetail(res.status, await res.text())}`);
4305
4400
  const etag = res.headers.get("ETag");
4306
4401
  if (etag === null) throw new BaerlyError("InvalidResponse", `PUT ${key}: missing ETag`);
4307
4402
  const dateStr = res.headers.get("Date");
@@ -4337,6 +4432,7 @@ var S3HttpStorage = class {
4337
4432
  const params = new URLSearchParams();
4338
4433
  params.set("list-type", "2");
4339
4434
  params.set("prefix", prefix);
4435
+ params.set("encoding-type", "url");
4340
4436
  if (continuationToken !== void 0) params.set("continuation-token", continuationToken);
4341
4437
  else if (startAfter !== "") params.set("start-after", startAfter);
4342
4438
  if (opts?.maxKeys !== void 0) {
@@ -4365,7 +4461,7 @@ var S3HttpStorage = class {
4365
4461
  status: res.status,
4366
4462
  ...retryAfterCause(res)
4367
4463
  });
4368
- throw new BaerlyError("InvalidResponse", `LIST ${prefix}: ${res.status} ${await res.text()}`);
4464
+ throw new BaerlyError("InvalidResponse", `LIST ${prefix}: ${s3ErrorDetail(res.status, await res.text())}`);
4369
4465
  });
4370
4466
  if (outcome.kind === "ok") {
4371
4467
  parsed = parseListObjectsV2CommandOutput(outcome.body);
@@ -4917,6 +5013,110 @@ const normalizeKeyPrefix = (prefix) => {
4917
5013
  return `${prefix}/`;
4918
5014
  };
4919
5015
  //#endregion
4920
- export { decodeJsonBytes as a, uuid as i, timestamp as n, encodeJsonBytes as o, countKey as r, parseBucketUri as t };
5016
+ //#region src/subcommand.ts
5017
+ /** Shared exit-code mapping for caught `BaerlyError`s. */
5018
+ const errorToExitCode = (code) => {
5019
+ if (code === "InvalidConfig") return 1;
5020
+ if (code === "Conflict" || code === "Internal" || code === "InvalidResponse") return 3;
5021
+ return 2;
5022
+ };
5023
+ /**
5024
+ * Build the app/tenant resolver. Captures `name` to surface the
5025
+ * calling subcommand in the InvalidConfig hint.
5026
+ */
5027
+ const makeResolveAppTenant = (name) => {
5028
+ return async (args) => {
5029
+ const flagApp = typeof args.app === "string" && args.app.length > 0 ? args.app : void 0;
5030
+ const flagTenant = typeof args.tenant === "string" && args.tenant.length > 0 ? args.tenant : void 0;
5031
+ if (flagApp !== void 0 && flagTenant !== void 0) return {
5032
+ app: flagApp,
5033
+ tenant: flagTenant
5034
+ };
5035
+ try {
5036
+ const cfg = await loadAppConfig();
5037
+ return {
5038
+ app: flagApp ?? cfg.app,
5039
+ tenant: flagTenant ?? cfg.tenant
5040
+ };
5041
+ } catch (error) {
5042
+ throw new BaerlyError("InvalidConfig", `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${error instanceof BaerlyError ? error.message : error.message})`, error);
5043
+ }
5044
+ };
5045
+ };
5046
+ /**
5047
+ * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key
5048
+ * rejection, and error-to-exit-code mapping. Shared by both the citty
5049
+ * `run({ args })` path and the test `run(argv)` path. The caller
5050
+ * supplies the {@link SubcommandContext}; this lets each `run(argv)`
5051
+ * invocation attach its own `streams` override without leaking across
5052
+ * invocations.
5053
+ */
5054
+ const kebabToCamel = (s) => s.replace(/-(\w)/g, (_, c) => c.toUpperCase());
5055
+ const wrapHandler = (def) => {
5056
+ const allowedKeys = new Set(Object.keys(def.args).flatMap((k) => k.includes("-") ? [k, kebabToCamel(k)] : [k]).concat(["_"]));
5057
+ return async (args, ctx) => {
5058
+ if ("json" in def.args) setJsonMode(args.json === true);
5059
+ try {
5060
+ for (const k of Object.keys(args)) if (!allowedKeys.has(k)) throw new BaerlyError("InvalidConfig", `baerly ${def.name}: unknown flag --${k}`);
5061
+ return await def.handler(args, ctx);
5062
+ } catch (error) {
5063
+ if (error instanceof BaerlyError) {
5064
+ emitError(def.name, error.code, error.message);
5065
+ return errorToExitCode(error.code);
5066
+ }
5067
+ emitError(def.name, "Unknown", error.message);
5068
+ return 2;
5069
+ }
5070
+ };
5071
+ };
5072
+ /**
5073
+ * Wrap a baerly subcommand. Returns `{ cmd, run }` —
5074
+ * - `cmd` is a citty `defineCommand` block; mount it in
5075
+ * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a
5076
+ * non-zero exit so the parent process surfaces the failure.
5077
+ * - `run(argv)` is the in-process test entry. It parses `argv` with
5078
+ * citty's `parseArgs`, dispatches through the same wrapped
5079
+ * handler, and returns the integer exit code (does NOT call
5080
+ * `process.exit`).
5081
+ *
5082
+ * The two paths share `wrapHandler` so JSON-mode toggling,
5083
+ * unknown-flag rejection, and error-to-exit-code mapping behave
5084
+ * identically.
5085
+ */
5086
+ const defineBaerlySubcommand = (def) => {
5087
+ const resolveAppTenant = makeResolveAppTenant(def.name);
5088
+ const wrapped = wrapHandler(def);
5089
+ const cmd = defineCommand({
5090
+ meta: {
5091
+ name: def.name,
5092
+ description: def.meta.description
5093
+ },
5094
+ args: def.args,
5095
+ run: async ({ args }) => {
5096
+ const code = await wrapped(args, { resolveAppTenant });
5097
+ if (code !== 0) process.exit(code);
5098
+ }
5099
+ });
5100
+ const run = async (argv, options) => {
5101
+ let parsed;
5102
+ try {
5103
+ parsed = parseArgs(argv, def.args);
5104
+ } catch (error) {
5105
+ setJsonMode(argv.includes("--json"));
5106
+ emitError(def.name, "InvalidConfig", error.message);
5107
+ return 1;
5108
+ }
5109
+ return wrapped(parsed, {
5110
+ resolveAppTenant,
5111
+ streams: options?.streams
5112
+ });
5113
+ };
5114
+ return {
5115
+ cmd,
5116
+ run
5117
+ };
5118
+ };
5119
+ //#endregion
5120
+ export { uuid as a, countKey as i, parseBucketUri as n, timestamp as r, defineBaerlySubcommand as t };
4921
5121
 
4922
- //# sourceMappingURL=bucket-uri-BrDEYvzy.js.map
5122
+ //# sourceMappingURL=subcommand-DZcHcsYp.js.map