@gusto/baerly-storage 0.3.0 → 0.4.1

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 (141) hide show
  1. package/README.md +157 -92
  2. package/dist/API.md +64 -32
  3. package/dist/CHANGELOG.md +301 -5
  4. package/dist/RECIPES.md +125 -0
  5. package/dist/THIRD-PARTY-LICENSES.txt +22 -96
  6. package/dist/{app-config-BIzyAKzy.d.ts → app-config-DyiFK3_k.d.ts} +43 -11
  7. package/dist/app-config.d.ts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.js +13 -13
  10. package/dist/auth.js.map +1 -1
  11. package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
  12. package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
  13. package/dist/baerly.js +35 -15
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +342 -0
  16. package/dist/{client-BJXF3XJA.d.ts → client-Fe8CwB73.d.ts} +3 -3
  17. package/dist/client-react.d.ts +3 -3
  18. package/dist/client-react.js +4 -4
  19. package/dist/client-react.js.map +1 -1
  20. package/dist/client.d.ts +4 -4
  21. package/dist/client.js +3 -3
  22. package/dist/{cloudflare-Cn2ibODt.js → cloudflare-DzKBrUlg.js} +2 -2
  23. package/dist/{cloudflare-Cn2ibODt.js.map → cloudflare-DzKBrUlg.js.map} +1 -1
  24. package/dist/cloudflare.d.ts +49 -6
  25. package/dist/cloudflare.js +55 -21
  26. package/dist/cloudflare.js.map +1 -1
  27. package/dist/config-1tv0-Yzm.js +2693 -0
  28. package/dist/config-1tv0-Yzm.js.map +1 -0
  29. package/dist/constants-CfeMWQWk.js +222 -0
  30. package/dist/constants-CfeMWQWk.js.map +1 -0
  31. package/dist/{cost-BZ_MDBmn.js → cost-DSMIVqzL.js} +42 -43
  32. package/dist/cost-DSMIVqzL.js.map +1 -0
  33. package/dist/{current-json-DsN7FNY1.js → current-json-C6nhPOm1.js} +6 -204
  34. package/dist/current-json-C6nhPOm1.js.map +1 -0
  35. package/dist/{db-CCT6tDfY.d.ts → db-DsPkOVEH.d.ts} +3 -3
  36. package/dist/{deploy-BKKyGlSJ.js → deploy-DonTr-CV.js} +4 -4
  37. package/dist/{deploy-BKKyGlSJ.js.map → deploy-DonTr-CV.js.map} +1 -1
  38. package/dist/dev-vite.d.ts +9 -5
  39. package/dist/dev-vite.js +5 -4
  40. package/dist/dev-vite.js.map +1 -1
  41. package/dist/dev.d.ts +1 -1
  42. package/dist/dev.js +1 -1
  43. package/dist/{doctor-BVU4GNXN.js → doctor-DSIyCDg_.js} +5 -8
  44. package/dist/{doctor-BVU4GNXN.js.map → doctor-DSIyCDg_.js.map} +1 -1
  45. package/dist/{dump-DPEAKub6.js → dump-Bh5k26VQ.js} +9 -32
  46. package/dist/dump-Bh5k26VQ.js.map +1 -0
  47. package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
  48. package/dist/errors-Dfa3p78c.js.map +1 -0
  49. package/dist/{export-BcuCLFFe.js → export-DtF5tDIM.js} +9 -32
  50. package/dist/{export-BcuCLFFe.js.map → export-DtF5tDIM.js.map} +1 -1
  51. package/dist/{fsck-RXgLOaJG.js → fsck-D_djMO5D.js} +10 -33
  52. package/dist/fsck-D_djMO5D.js.map +1 -0
  53. package/dist/{http-Bd4byR4n.js → http-DxM9MflO.js} +123 -35
  54. package/dist/http-DxM9MflO.js.map +1 -0
  55. package/dist/http.d.ts +42 -26
  56. package/dist/http.js +3 -2
  57. package/dist/{index-DnBGSeuU.d.ts → index-0rZcMBwy.d.ts} +2 -2
  58. package/dist/{index-Cmsxx-ZN.d.ts → index-B6oexfOB.d.ts} +7 -7
  59. package/dist/{index-BDceQQi-.d.ts → index-BNRh23K9.d.ts} +4 -4
  60. package/dist/{index-DW7GT6M2.d.ts → index-BYk9oCNf.d.ts} +193 -163
  61. package/dist/index.d.ts +6 -6
  62. package/dist/index.js +4 -4
  63. package/dist/{indexes-Cx7uMXm0.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
  64. package/dist/{inspect-DhI49PSi.js → inspect-6WZ-pC7-.js} +10 -33
  65. package/dist/inspect-6WZ-pC7-.js.map +1 -0
  66. package/dist/key-Di6yyxFu.js +35 -0
  67. package/dist/key-Di6yyxFu.js.map +1 -0
  68. package/dist/{log-tail-DXeDkWEp.js → log-tail-D98U1JBo.js} +31 -7
  69. package/dist/log-tail-D98U1JBo.js.map +1 -0
  70. package/dist/{maintenance-CWBQpZ2y.js → maintenance-B4Dki6Ig.js} +77 -22
  71. package/dist/maintenance-B4Dki6Ig.js.map +1 -0
  72. package/dist/{maintenance-BkhUr72A.d.ts → maintenance-B_e0T99L.d.ts} +28 -5
  73. package/dist/{maintenance-C_KSkVjd.js → maintenance-C7coQp4c.js} +17 -16
  74. package/dist/maintenance-C7coQp4c.js.map +1 -0
  75. package/dist/maintenance.d.ts +3 -3
  76. package/dist/maintenance.js +3 -3
  77. package/dist/node.d.ts +168 -65
  78. package/dist/node.js +3 -2
  79. package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
  80. package/dist/normalize-rjnZLwS4.js.map +1 -0
  81. package/dist/{observability-BYd-RzEx.js → observability-wzs3-BL_.js} +233 -71
  82. package/dist/observability-wzs3-BL_.js.map +1 -0
  83. package/dist/observability.d.ts +2 -2
  84. package/dist/observability.js +1 -1
  85. package/dist/{plan-DIu_B6fy.js → plan-a7PJHBCy.js} +2 -2
  86. package/dist/{plan-DIu_B6fy.js.map → plan-a7PJHBCy.js.map} +1 -1
  87. package/dist/{query-sQNO5vU_.js → query-rAtXNQQB.js} +96 -207
  88. package/dist/query-rAtXNQQB.js.map +1 -0
  89. package/dist/{rebuild-index-DP4CqSSs.js → rebuild-index-BVzQSZlm.js} +9 -32
  90. package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
  91. package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
  92. package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
  93. package/dist/{restore-DpQYef6r.js → restore-R-4rbciV.js} +73 -100
  94. package/dist/restore-R-4rbciV.js.map +1 -0
  95. package/dist/runtime-spec-_GTdeSMo.js +391 -0
  96. package/dist/runtime-spec-_GTdeSMo.js.map +1 -0
  97. package/dist/s3-http-B-z8th6O.d.ts +60 -0
  98. package/dist/s3.d.ts +47 -0
  99. package/dist/s3.js +45 -0
  100. package/dist/s3.js.map +1 -0
  101. package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
  102. package/dist/shared-secret-DgEicd3x.js.map +1 -0
  103. package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
  104. package/dist/src-CYHFDrKz.js.map +1 -0
  105. package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
  106. package/dist/src-DYZ4H1aF.js.map +1 -0
  107. package/dist/src-D__mHQmQ.js +2271 -0
  108. package/dist/src-D__mHQmQ.js.map +1 -0
  109. package/dist/{subcommand-CP9NY2J4.js → subcommand-DoDA-K7d.js} +44 -6
  110. package/dist/subcommand-DoDA-K7d.js.map +1 -0
  111. package/dist/time-DUqvFMHq.js +119 -0
  112. package/dist/time-DUqvFMHq.js.map +1 -0
  113. package/dist/{usage-CTfDq9HR.js → usage-DBV1eQHC.js} +7 -22
  114. package/dist/usage-DBV1eQHC.js.map +1 -0
  115. package/dist/wire-izfGZDvr.js.map +1 -1
  116. package/package.json +51 -27
  117. package/dist/config-CGyBopy3.js +0 -5326
  118. package/dist/config-CGyBopy3.js.map +0 -1
  119. package/dist/cost-BZ_MDBmn.js.map +0 -1
  120. package/dist/current-json-DsN7FNY1.js.map +0 -1
  121. package/dist/dump-DPEAKub6.js.map +0 -1
  122. package/dist/errors-DOdL95kK.js.map +0 -1
  123. package/dist/fsck-RXgLOaJG.js.map +0 -1
  124. package/dist/http-Bd4byR4n.js.map +0 -1
  125. package/dist/inspect-DhI49PSi.js.map +0 -1
  126. package/dist/log-tail-DXeDkWEp.js.map +0 -1
  127. package/dist/maintenance-CWBQpZ2y.js.map +0 -1
  128. package/dist/maintenance-C_KSkVjd.js.map +0 -1
  129. package/dist/normalize-XWY25_sG.js.map +0 -1
  130. package/dist/observability-BYd-RzEx.js.map +0 -1
  131. package/dist/query-sQNO5vU_.js.map +0 -1
  132. package/dist/rebuild-index-DP4CqSSs.js.map +0 -1
  133. package/dist/restore-DpQYef6r.js.map +0 -1
  134. package/dist/shared-secret-BJdSwpgw.js.map +0 -1
  135. package/dist/src-CWpkSbvJ.js.map +0 -1
  136. package/dist/src-D24wDpzR.js +0 -6247
  137. package/dist/src-D24wDpzR.js.map +0 -1
  138. package/dist/src-Db4-qVtM.js.map +0 -1
  139. package/dist/subcommand-CP9NY2J4.js.map +0 -1
  140. package/dist/usage-CTfDq9HR.js.map +0 -1
  141. /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"restore-DpQYef6r.js","names":["#storage","#currentJsonKey","#maxRetries","#initialBackoffMs","#random","#indexes","#verifyLogIntegrityOnCommit","#singleAttemptCommit","#backoff","#emitWriteMetrics","#provisionCurrentJson","#walkLog","#observe429","#cleanupStaleIndexKeysBestEffort","#readPreImage"],"sources":["../packages/server/src/doc-id.ts","../packages/server/src/key-limit.ts","../packages/server/src/log-conflict-adoption.ts","../packages/server/src/writer.ts","../packages/cli/src/admin/restore.ts"],"sourcesContent":["import { assertPathSegment } from \"./path-segment.ts\";\n\n/**\n * Guard a caller-supplied `_id` before it becomes a written key segment\n * (index keys, log `doc_id`) or filesystem path (`LocalFsStorage`). The\n * `_id` analogue of `assertKeySegment` (`db.ts`). Routes through the\n * single shared {@link assertPathSegment} rule (empty / `\"/\"` /\n * `\".\"`|`\"..\"` / C0-C1 control chars / leading `\"_\"` (ADR-007) / overlong,\n * all as `BaerlyError{code:\"InvalidConfig\"}`).\n */\nexport const assertDocId = (id: string): void => {\n assertPathSegment(id, \"_id\");\n};\n","import { BaerlyError, MAX_KEY_BYTES } from \"@baerly/protocol\";\n\nconst utf8 = new TextEncoder();\n\n/**\n * Reject an assembled object key over the S3/R2 full-key ceiling\n * ({@link MAX_KEY_BYTES}) as `InvalidConfig`. Per-segment caps don't\n * bound the sum, and index values skip `assertPathSegment` entirely, so\n * this post-encoding check at the writer's PUT sites is their only\n * overflow guard. @see docs/spec/storage-compatibility.md\n */\nexport const assertKeyWithinLimit = (key: string): void => {\n const bytes = utf8.encode(key).length;\n if (bytes > MAX_KEY_BYTES) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `object key exceeds ${MAX_KEY_BYTES} bytes (got ${bytes}): ${JSON.stringify(key.slice(0, 80))}…`,\n );\n }\n};\n","/**\n * Self-session log-conflict adoption — the one decision that\n * distinguishes a retry of our own prior commit attempt from a\n * peer racing us at the same `seq`.\n *\n * Background. `Writer.#singleAttemptCommit` creates each log entry\n * with `If-None-Match: \"*\"` — and that create IS the commit. A 412 on\n * `/log/<seq>.json` can mean either\n *\n * (a) a peer genuinely won that seq (a foreign entry is committed\n * there); or\n * (b) our OWN previous attempt landed the committing log create but\n * its ack was lost — we never observed the `200` — and we're now\n * re-driving the same logical commit.\n *\n * This function makes the (a)/(b) call. It is callable, separately\n * testable, and patent-disclosable in isolation from the rest of the\n * commit path.\n *\n * ## Soundness invariant\n *\n * Adoption is sound iff all four hold:\n *\n * 1. **Same session.** `existing.session === self.session`. The\n * session id is a per-commit, in-RAM-only secret minted at\n * `Writer.commit` from `crypto.randomUUID().slice(0,\n * SESSION_ID_LENGTH)`; an adversary with bucket-write access\n * can forge any other field but cannot forge a value they\n * did not observe being PUT.\n * 2. **Matching seq.** `existing.seq === self.expectedSeq`. The\n * seq match is also implied by the key shape (the writer\n * reads `/log/<expectedSeq>.json`), but is re-asserted here\n * so the invariant is visible at the decision site.\n * 3. **Matching write intent.** The occupant's writer-minted log\n * fields match the entry this writer just attempted to create.\n * Same session + same seq alone is not sufficient: a collision,\n * test seam, or out-of-model bucket writer must not be able to\n * make this writer adopt a different logical mutation.\n * 4. **Single-input commit.** `self.batchSize === 1`. Every\n * commit is single-input now, so this always holds; the guard\n * is retained as a defensive invariant (its removal is the\n * deferred follow-up tracked as D1.5). It is sound only for a single-input\n * commit because per-input adoption decisions would not\n * compose with the single-key single-write commit (the one\n * `log/<seq>` create is the all-or-nothing commit point).\n *\n * When any of (1)/(2)/(3)/(4) fails, the caller MUST refuse adoption\n * and treat the occupant as a conflicting committed entry.\n *\n * ## Threat model\n *\n * The adversary may (a) write arbitrary bytes to any key in the\n * bucket, (b) replay any PUT they previously observed on the wire,\n * (c) reorder or drop network packets between the writer and the\n * bucket. The adversary may NOT (d) read the writer's local RAM\n * and therefore cannot learn the per-commit `session` id before\n * observing the writer's own `/log/<seq>.json` PUT. Under these\n * constraints, conditions (1)+(2)+(3)+(4) close every attack path in\n * the adversarial-replay property test\n * (`tests/integration/log-conflict-adversarial.test.ts`).\n *\n * **Pinned by:** `tests/integration/log-conflict-forgery.test.ts`\n * exercises the session-id-unguessability claim under a\n * `ForgeryStorage` adversary that plants arbitrary entries at the\n * writer's expected log key. Property verified by default at\n * `numRuns: 1000`; `FC_NUM_RUNS=10000` for the hardening sweep.\n *\n * ## Prior art\n *\n * SlateDB's manifest-pivot writer protocol (rfcs/0001-manifest.md,\n * scenarios 1–4) is the closest published prior art on the broader\n * commit-protocol skeleton. SlateDB's scenario 3 — \"conflicting SST\n * has same `writer_epoch` as me\" — is explicitly labelled an\n * **illegal state that should panic**. The three-clause adoption\n * decision encoded here (same session ∧ matching seq ∧ matching intent ∧ single-input)\n * recognises that case as the writer's own prior in-flight attempt\n * and adopts it as success rather than aborting, closing the recovery\n * gap SlateDB leaves to operator intervention.\n *\n * Apache Iceberg and Delta Lake commits surface analogous failures as\n * `CommitFailedException` / commit-conflict retries; neither inspects\n * the conflicting object to determine ownership.\n *\n * See `docs/spec/prior-art.md` for the consolidated IDS-shaped\n * differentiation.\n *\n * @see docs/spec/sync-protocol.md §\"Contention and retries\"\n */\n\nimport type { LogEntry } from \"@baerly/protocol\";\n\n/**\n * Inputs to {@link tryAdoptOwnSessionLogEntry}. All fields are\n * required; the writer constructs this struct at the call site.\n */\nexport interface AdoptionContext {\n /**\n * The entry the writer just attempted to PUT. Carries the\n * writer's session, expected seq, and the rest of the LogEntry\n * shape minted in `Writer.#singleAttemptCommit` step 3.\n */\n readonly self: LogEntry;\n /**\n * The entry currently stored at `/log/<self.seq>.json`, as read\n * back after a 412. The caller is responsible for the GET (the\n * function is pure, no I/O).\n */\n readonly existing: LogEntry;\n /**\n * Input count of the parent commit attempt. Always `1` now —\n * `Writer.commit` is the only commit path and is single-input.\n * Adoption is only safe when this is exactly `1`; the field is\n * retained as a defensive invariant (removing it is the deferred\n * follow-up tracked as D1.5).\n */\n readonly batchSize: number;\n}\n\n/**\n * Discriminated outcome of {@link tryAdoptOwnSessionLogEntry}.\n * `adopt: true` carries the existing entry (which by the invariant\n * matches `self` on writer-minted intent fields); the caller\n * substitutes it for `self` so the returned `CommitResult` matches\n * what's actually stored. `adopt: false` carries a machine-readable\n * `reason` so callers and tests can discriminate which clause of the\n * invariant failed.\n */\nexport type AdoptionDecision =\n | { readonly adopt: true; readonly entry: LogEntry }\n | {\n readonly adopt: false;\n readonly reason: \"foreign-session\" | \"wrong-seq\" | \"intent-mismatch\" | \"batch\";\n };\n\n/**\n * Decide whether the entry already at `/log/<seq>.json` is the\n * writer's own prior in-flight attempt and may be adopted. Pure\n * function; no I/O. The caller performs the GET (when the log PUT\n * surfaces 412) and passes the read-back body in `ctx.existing`.\n *\n * ## Correctness precondition\n *\n * A fresh `session` id is minted per `commit()` call, seq-stable\n * across that call's retries. Adoption compares the writer-minted\n * intent/body fields as well as session and seq: a dropped-ack retry\n * reuses the same attempted entry and adopts, while a same-session /\n * same-seq occupant carrying a different logical mutation is treated as\n * a conflict and skipped by the caller's forward-probe loop.\n *\n * @see {@link AdoptionDecision} for the return shape.\n * @see The soundness invariant in this module's header docstring.\n */\nexport const tryAdoptOwnSessionLogEntry = (ctx: AdoptionContext): AdoptionDecision => {\n // Clause (4) — single-input commit. Always holds now (every commit\n // is single-input); evaluated first as a defensive guard before any\n // field comparison.\n if (ctx.batchSize !== 1) {\n return { adopt: false, reason: \"batch\" };\n }\n // Clause (1) — same session.\n if (ctx.existing.session !== ctx.self.session) {\n return { adopt: false, reason: \"foreign-session\" };\n }\n // Clause (2) — matching seq. The seq is also implied by the\n // key the caller read from, but re-asserted here for\n // patent-disclosure clarity.\n if (ctx.existing.seq !== ctx.self.seq) {\n return { adopt: false, reason: \"wrong-seq\" };\n }\n // Clause (3) — matching write intent: full-entry equality, including\n // `commit_ts`. A legitimate lost-ack self-retry passes this ONLY under\n // two premises:\n // P1 (single mint): `commit_ts`/`lsn`/`session` are minted once per\n // `#singleAttemptCommit` (one `Date.now()`) and the inner\n // transient-retry loop re-PUTs the IDENTICAL `entry`, so a real\n // read-back is byte-identical to `self`, `commit_ts` included.\n // P2 (order-stable round-trip): stored bytes are\n // `encodeJsonBytes` (`JSON.stringify`) and read back via\n // `JSON.parse`; `JSON.stringify(JSON.parse(...))` preserves key\n // order, so the two stringifications match.\n // If either breaks (re-mint on retry, or a canonical/sorting encoder /\n // normalizing read-back), a legit self-retry would falsely mismatch\n // here and DUPLICATE-write. P2 is pinned by `bytes.test.ts`.\n if (JSON.stringify(ctx.existing) !== JSON.stringify(ctx.self)) {\n return { adopt: false, reason: \"intent-mismatch\" };\n }\n return { adopt: true, entry: ctx.existing };\n};\n","/**\n * `Writer` — stateless multi-instance write engine (single-write commit).\n *\n * Each {@link Writer.commit} reads `current.json` FRESH (for\n * `log_seq_start` / `tail_hint` as a probe FLOOR — a lower bound, NOT a\n * CAS precondition), PUTs the content body, then **creates `log/<seq>`\n * via `If-None-Match: \"*\"`. That create IS the commit / linearization\n * point.** The writer writes NOTHING to `current.json` on the commit\n * path; `tail_hint` advances outside ordinary commits via compaction\n * folds, write-tick refreshes, and explicit operator/import paths. The\n * commit model and its invariants are recorded in ADR-008\n * (`docs/adr/008-single-write-commit.md`). The\n * optional integrity walk is gated by\n * {@link WriterOptions.verifyLogIntegrityOnCommit} (default off).\n *\n * No per-write cache: every commit re-reads + re-probes, so N stateless\n * instances contend at one place — the `If-None-Match` create of\n * `log/<seq>`. The loser gets a 412 and re-probes forward to the next\n * empty slot. A 412 from the writer's OWN session at the same seq is its\n * own lost-ack / crashed-but-durable commit → adopted (not retried), so\n * the write lands at EXACTLY `seq`, never duplicated.\n *\n * **Crash safety.** Order is content + additive index `newKeys` →\n * `log/<seq>` create → stale index-key DELETEs. A crash before the\n * create leaves an unreferenced content body + orphan additive index\n * keys (no log entry references them), not an orphan log entry with\n * missing content — the compactor sweeps the content, and a stray\n * additive key only ever yields a false-POSITIVE candidate that\n * `matchesWire` (read path) drops. Emitting `newKeys` before the commit\n * means a committed row is ALWAYS index-findable; the stale-key DELETE\n * stays after the commit so a crash can never de-index a committed\n * doc. See `index-emit-order.test.ts` and ADR-008 Q4.\n *\n * **`LogEntry` shape.** Emitted entries follow the contract in\n * `packages/protocol/src/log.ts` (see {@link LogEntry}) and\n * `docs/spec/log-entry-shape.md`. The on-bucket key is\n * `log/<seq>.json` (the integer `seq` is the load-bearing\n * identifier; the `lsn` string is schema-only).\n *\n * @see docs/spec/sync-protocol.md for the protocol invariants this\n * loop preserves.\n * @see docs/spec/log-entry-shape.md for the per-field contract.\n */\n\nimport {\n CURRENT_JSON_SCHEMA_VERSION,\n type CurrentJson,\n type CurrentJsonRead,\n type DocumentData,\n type LogEntry,\n type MetricsRecorder,\n createCurrentJson,\n decodeJsonBytes,\n encodeJsonBytes,\n logObjectKey,\n logSeqStartOf,\n BaerlyError,\n noopMetricsRecorder,\n type Storage,\n LOG_FORWARD_PROBE_CAP,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_TAIL_HINT_REFRESH_WRITES,\n S3_REQUEST_MAX_RETRIES,\n SESSION_ID_LENGTH,\n countKey,\n readCurrentJson,\n timestamp,\n uuid,\n versionFromContent,\n} from \"@baerly/protocol\";\nimport { assertDocId } from \"./doc-id.ts\";\nimport { allIndexKeysFor, type IndexDefinition, validateIndexDefinition } from \"./indexes.ts\";\nimport { assertKeyWithinLimit } from \"./key-limit.ts\";\nimport { readLogEntry, walkLogRange } from \"./log-walk.ts\";\nimport { findLogTail } from \"./log-tail.ts\";\nimport { tryAdoptOwnSessionLogEntry } from \"./log-conflict-adoption.ts\";\nimport {\n dispatchInlineAwaited,\n runBoundedMaintenance,\n shouldFireMaintenance,\n} from \"./maintenance.ts\";\nimport { getCurrentContext } from \"./observability/context.ts\";\n\nconst ctxMetrics = (): MetricsRecorder => getCurrentContext()?.recorder ?? noopMetricsRecorder;\n\n/**\n * Tunables for {@link Writer}. All optional; defaults match the\n * legacy retry budget so the new loop is a drop-in replacement.\n */\nexport interface WriterOptions {\n /**\n * Max retryable `Conflict` attempts before throwing `Conflict`.\n * Foreign log-create 412s are resolved inside a single attempt by\n * occupant read-back plus bounded forward re-probe; this budget is\n * retained for future retryable conflicts and tests.\n */\n readonly maxRetries?: number;\n\n /** Initial backoff in ms; doubles per attempt, capped at 1500ms. Default 25. */\n readonly initialBackoffMs?: number;\n\n /**\n * Pure function returning a number in [0, 1). Used for jitter; tests\n * inject a deterministic generator. Defaults to `Math.random`.\n */\n readonly random?: () => number;\n\n /**\n * Optional. Indexes declared for the collection this writer\n * commits to. Each commit emits one zero-byte PUT per declared\n * index (when the indexed field is set on the doc) — the additive\n * `newKeys` go down BEFORE the committing `log/<seq>` create, so a\n * committed row is always index-findable. On U/D, the writer reads\n * the pre-image content body from the log (one back-walk per\n * indexed collection, NOT per index) to compute the stale-key set;\n * stale keys are DELETE'd AFTER the commit, computed from the\n * resolved committing seq's pre-image.\n *\n * Validated at construction via {@link validateIndexDefinition} —\n * an invalid def throws `BaerlyError{code:\"SchemaError\"}`\n * synchronously, before the first commit. Empty / undefined is\n * a no-op (writer behaves identically to the no-index path — no\n * extra GET, no extra PUTs).\n *\n * Note: `Writer` is per-collection (the `currentJsonKey`\n * is per-collection), so this array applies to one collection\n * only — adapters that serve multiple collections instantiate\n * one writer per collection.\n *\n * Emits one new metric when at least one index is declared:\n * - `db.write.index_ops_per_logical_write` (histogram,\n * labelled by `collection`) — `K (PUT) + L (DELETE)` per\n * successful commit.\n */\n readonly indexes?: ReadonlyArray<IndexDefinition>;\n\n /**\n * When `true`, every commit walks the live log range\n * `[log_seq_start, tail_hint)` before minting a new entry, surfacing\n * a missing or malformed entry as `BaerlyError{code:\"Internal\"}`\n * (or `\"InvalidResponse\"` for parse failures). The walk is purely\n * observational — the per-doc fold lives in the read path\n * (`./query.ts`) and any hole inside the visible range would also\n * fire on the next read.\n *\n * Production callers default this OFF: under contention the walk\n * issues `O(tail)` Class-B GETs per CAS attempt and the retry\n * budget multiplies that by {@link S3_REQUEST_MAX_RETRIES}. Tests\n * that intentionally puncture bucket state to exercise the\n * invariant trigger opt in by passing `true`.\n *\n * Default `false`.\n */\n readonly verifyLogIntegrityOnCommit?: boolean;\n}\n\n/**\n * Single-doc mutation request. One `commit()` ↔ one {@link LogEntry}.\n */\nexport interface CommitInput {\n /** The mutation op. Maps directly to {@link LogEntry.op}. */\n readonly op: \"I\" | \"U\" | \"D\";\n\n /** The collection (table) name. Becomes {@link LogEntry.collection}. */\n readonly collection: string;\n\n /** The document primary key. Becomes {@link LogEntry.doc_id}. */\n readonly docId: string;\n\n /**\n * For `I` / `U`: the post-image. Becomes {@link LogEntry.after}. Must\n * be `undefined` for `op: \"D\"`.\n */\n readonly body?: DocumentData;\n\n /** Optional ISO-8601 origin marker; becomes {@link LogEntry.origin}. */\n readonly origin?: string;\n}\n\n/** Return shape of {@link Writer.commit}. */\nexport interface CommitResult {\n /** The committed `LogEntry`. Caller can ack on `entry.lsn`. */\n readonly entry: LogEntry;\n\n /**\n * ETag of `current.json` as read at the start of the commit. The\n * commit path no longer writes `current.json` (the `log/<seq>`\n * create IS the commit), so this is the manifest's pre-commit ETag,\n * not a post-write one.\n */\n readonly currentEtag: string;\n\n /** How many commit attempts it took (1 = first try won). */\n readonly attempts: number;\n}\n\nconst DEFAULT_INITIAL_BACKOFF_MS = 25;\nconst MAX_BACKOFF_MS = 1500;\nconst APPLICATION_JSON = \"application/json\";\n\n/**\n * Empty body for index entries. Each index entry is a fact (\"doc\n * `<docId>` has `<field> = <value>`\"), not data — readers list the\n * prefix, extract the doc id, then GET the content body separately.\n * Pre-allocated module-level constant so every index PUT shares one\n * zero-length buffer.\n */\nconst EMPTY_BODY = new Uint8Array(0);\n\n/**\n * Successful outcome of one full {@link Writer.#singleAttemptCommit}\n * attempt. A retryable log-create 412 that resolved to a foreign-session\n * occupant beyond the forward-probe budget throws\n * `BaerlyError{code:\"Conflict\"}`; the caller catches via\n * {@link isPreconditionFailed} and decides whether to retry. Non-retryable\n * failures (protocol-invariant violations, network errors) propagate.\n */\ninterface SingleAttemptSuccess {\n readonly entries: readonly LogEntry[];\n readonly currentEtag: string;\n readonly classAOps: number;\n}\n\n/**\n * Stateless write engine for the multi-instance core.\n *\n * Construction is cheap and performs zero I/O — adapters build a\n * fresh `Writer` per request and discard it. All real work\n * happens in {@link commit}.\n *\n * @example\n * ```ts\n * import { Writer } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const writer = new Writer({\n * storage: new MemoryStorage(),\n * currentJsonKey: \"app/tickets/tenant/acme/manifests/tickets/current.json\",\n * });\n *\n * const result = await writer.commit({\n * op: \"I\",\n * collection: \"tickets\",\n * docId: \"doc-1\",\n * body: { _id: \"doc-1\", title: \"hello\" },\n * });\n * console.log(result.entry.seq, result.attempts);\n * ```\n */\nexport class Writer {\n readonly #storage: Storage;\n readonly #currentJsonKey: string;\n readonly #maxRetries: number;\n readonly #initialBackoffMs: number;\n readonly #random: () => number;\n readonly #indexes: ReadonlyArray<IndexDefinition>;\n readonly #verifyLogIntegrityOnCommit: boolean;\n\n constructor(opts: {\n storage: Storage;\n /**\n * Full bucket-relative key of the CAS pointer, e.g.\n * `app/tickets/tenant/acme/manifests/tickets/current.json`. The\n * collection-prefix half lives at\n * `currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"))` — the\n * log and content keys are derived from it.\n */\n currentJsonKey: string;\n options?: WriterOptions;\n }) {\n this.#storage = opts.storage;\n this.#currentJsonKey = opts.currentJsonKey;\n this.#maxRetries = opts.options?.maxRetries ?? S3_REQUEST_MAX_RETRIES;\n this.#initialBackoffMs = opts.options?.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;\n this.#random = opts.options?.random ?? Math.random;\n const indexes = opts.options?.indexes ?? [];\n for (const def of indexes) {\n validateIndexDefinition(def);\n }\n this.#indexes = indexes;\n this.#verifyLogIntegrityOnCommit = opts.options?.verifyLogIntegrityOnCommit ?? false;\n }\n\n /**\n * Atomically commit one mutation. Reads `current.json` fresh (as a\n * probe FLOOR, not a CAS precondition), PUTs the content body and any\n * additive index `newKeys`, then creates `log/<seq>` via\n * `If-None-Match: \"*\"` — that create IS the commit (single-write\n * commit; no `current.json` CAS follows it). Stale index keys are\n * DELETE'd after the commit.\n *\n * The hot-path cost under no contention on an unindexed collection is\n * 1 GET + 2 PUTs (content + the committing `log/<seq>` create); each\n * declared index that projects a key on this write adds one PUT\n * (new key, before the commit) and, on U/D, up to one DELETE (stale\n * key, after the commit). An in-flight peer write costs one extra GET\n * + the backoff sleep per retry.\n *\n * Idempotency: PUT content uses `If-None-Match: \"*\"`, so a retry of\n * the same logical write produces the same content key and the\n * second PUT no-ops. The `log/<seq>` create also uses\n * `If-None-Match: \"*\"`, so two writers racing the same tail cause\n * exactly one create to win; the loser reads back the occupant,\n * adopts its own lost-ack write or re-probes forward to the next\n * empty slot.\n *\n * @throws BaerlyError code=\"Conflict\" when a retryable conflict\n * escapes the single-attempt helper and exhausts the retry budget\n * (presently unreachable on the log-create 412 path).\n * @throws BaerlyError code=\"Internal\" when a log entry expected in\n * `[0, tail_hint)` is missing — a protocol-invariant violation\n * (compactor bug or stale `current.json`).\n * @throws BaerlyError code=\"InvalidResponse\" when a log-entry body\n * isn't valid JSON.\n *\n * **Implicit provisioning.** When `current.json` does not exist at\n * `currentJsonKey` (fresh bucket, fresh collection), the writer\n * auto-creates it with a zero-state manifest before the commit\n * lands. The cost is one extra Class A PUT on the very first\n * commit per collection; steady-state cost is unchanged. A peer\n * racing the same first-write loses cleanly on the create CAS\n * and re-reads to pick up the winner's manifest.\n */\n async commit(input: CommitInput): Promise<CommitResult> {\n // Validate the doc id BEFORE any I/O so every commit caller — the\n // public write path AND a direct caller like `baerly admin restore`\n // — is covered (defense in depth, mirroring the db-layer guard).\n // Rejects empty / `\"/\"` / `\".\"`|`\"..\"` / control / leading `\"_\"` /\n // overlong `docId` as `BaerlyError{code:\"InvalidConfig\"}`, so a\n // traversal-shaped `_id` can never become a written key segment.\n assertDocId(input.docId);\n const session = uuid().slice(0, SESSION_ID_LENGTH);\n const logPrefix = this.#currentJsonKey.slice(0, this.#currentJsonKey.lastIndexOf(\"/\"));\n\n // NOTE: with the post-commit fence-verify removed, no `Conflict`\n // currently escapes `#singleAttemptCommit` — a log-create 412 is\n // always resolved internally (own-session adoption or a bounded\n // forward-probe to the next empty slot; only an exhausted probe cap\n // throws, as `Internal`, not `Conflict`). So the retry-catch arm and\n // the budget-exhausted `Conflict` throw below are presently\n // unreachable. They are retained deliberately: they cost nothing on\n // the happy path and re-arm automatically if a future change ever\n // re-introduces a retryable `Conflict` out of the helper.\n for (let attempt = 1; attempt <= this.#maxRetries; attempt++) {\n let success: SingleAttemptSuccess;\n try {\n success = await this.#singleAttemptCommit([input], session, logPrefix, \"Writer\");\n } catch (error) {\n // Only a retryable `Conflict` (see NOTE above — currently none)\n // backs off and retries. Anything else propagates.\n if (!isPreconditionFailed(error)) {\n throw error;\n }\n await this.#backoff(attempt);\n continue;\n }\n // `success.classAOps` is the per-attempt base; add `(attempt\n // - 1)` to bill prior failed attempts as one PUT each (the\n // simple-and-test-locked cost model — not a precise replay\n // of every PUT in every dropped attempt).\n this.#emitWriteMetrics(input.collection, success.classAOps + (attempt - 1));\n return {\n entry: success.entries[0]!,\n currentEtag: success.currentEtag,\n attempts: attempt,\n };\n }\n\n // Retry budget exhausted.\n throw new BaerlyError(\n \"Conflict\",\n `Writer: CAS conflict on ${this.#currentJsonKey} after ${this.#maxRetries} attempts`,\n );\n }\n\n /**\n * One full commit attempt — the body of {@link commit}. Reads\n * `current.json`, PUTs content + additive index `newKeys` in parallel,\n * then forward-probes the tail and creates `log/<seq>` once via\n * `If-None-Match: \"*\"` — the numbered log create IS the commit\n * (single-write commit; no `current.json` CAS follows it). Stale index\n * keys are DELETE'd after the commit. Returns the success payload.\n *\n * Called only as `#singleAttemptCommit([input], …)`: the array shape\n * is retained dead-generality (D1.5), but every call commits exactly\n * one entry.\n *\n * A log-create 412 is disambiguated by session read-back: own session\n * / own seq ⇒ our crashed-or-lost-ack commit is already durable ⇒\n * adopt; foreign session ⇒ re-probe forward and retry at the next\n * empty slot. Thrown `BaerlyError`s (Internal, InvalidResponse,\n * NetworkError) propagate.\n *\n * Crash safety invariant: content + additive index `newKeys` PUTs are\n * awaited before the log create. A crash before the create leaves\n * orphan content + additive index keys (no log entry references them)\n * — the compactor sweeps the content, and a stray additive key only\n * yields a false-positive candidate that `matchesWire` drops. A crash\n * AFTER the create is a durable, committed write at `seq` whose index\n * `newKeys` are already present (so it's index-findable); the only\n * residual is a possibly-undeleted stale OLD-value key, dropped by\n * `matchesWire` and cleaned by a later write / `rebuild-index`. The\n * inverse — committed log entry with missing content, or a de-indexed\n * committed doc — is never produced.\n */\n async #singleAttemptCommit(\n inputs: readonly CommitInput[],\n session: string,\n logPrefix: string,\n errorPrefix: string,\n ): Promise<SingleAttemptSuccess> {\n // ── Step 1. Read current.json (fresh; carries the ETag). ────────\n // On a fresh bucket / fresh collection the manifest doesn't exist\n // yet. Auto-create it with a zero-state initial so `db.collection(x)\n // .insert(...)` works zero-shot. A peer racing the same create\n // loses cleanly on `If-None-Match: \"*\"`; we re-read to pick up\n // the winner's manifest. Cost: one extra Class A PUT on the very\n // first commit per collection, zero overhead thereafter.\n const read =\n (await readCurrentJson(this.#storage, this.#currentJsonKey)) ??\n (await this.#provisionCurrentJson());\n const current = read.json;\n const baseEtag = read.etag;\n\n // ── Step 2. Optional integrity walk (`verifyLogIntegrityOnCommit`,\n // default off). Surfaces missing / malformed entries inside\n // `[log_seq_start, tail_hint)` as `Internal` / `InvalidResponse`;\n // entries below `log_seq_start` are folded into the snapshot\n // by `compact()` and possibly swept by `runGc()`, so the walk is\n // bounded to the live tail. The read path catches the same\n // conditions on the next consult — production callers leave the\n // walk off to avoid `O(tail)` Class-B GETs per CAS attempt.\n if (this.#verifyLogIntegrityOnCommit) {\n await this.#walkLog(logPrefix, logSeqStartOf(current), current.tail_hint);\n }\n\n // ── Step 3. Find the true tail (Class B forward-probe), then mint. ─\n // `tail_hint` is a non-authoritative lower bound (the writer no\n // longer advances it — only the compactor stamps it durably). The\n // forward-probe discovers the first empty seq >= the floor: the slot\n // this commit will create. Floor at `max(log_seq_start, tail_hint)`\n // so a compactor that advanced `log_seq_start` past a stale\n // `tail_hint` doesn't make us re-walk folded-but-unswept entries.\n // Bind to a local (oxlint `no-await-expression-member`).\n const probeFloor = Math.max(logSeqStartOf(current), current.tail_hint);\n // `findLogTail`'s density precondition holds: the floor sits in the\n // dense prefix because tail_hint advancers probe or derive known tails\n // from committed entries, while ordinary writer commits never stamp\n // `tail_hint`, so nothing advances the floor past a hole.\n const preCommitTail = await findLogTail(this.#storage, logPrefix, probeFloor);\n let seq = preCommitTail;\n\n // All entries share `session` (one session per logical commit) and\n // a single commit instant: `lsn`'s timestamp and `commit_ts` are\n // derived from ONE clock read so they can't drift apart under skew\n // (a reader validates `commit_ts` against `LAG_WINDOW_MILLIS`, and\n // two independent reads could straddle that band). The LSN's\n // `countKey(seq)` suffix MUST track the probed seq — it's compared on\n // adoption, so a stale suffix would misfire the disambiguation.\n const commitNowMs = Date.now();\n const commitTs = new Date(commitNowMs).toISOString();\n const lsnTimestamp = timestamp(commitNowMs);\n const input0 = inputs[0]!;\n const mintEntry = (atSeq: number): LogEntry => ({\n lsn: `${lsnTimestamp}_${session}_${countKey(atSeq)}`,\n commit_ts: commitTs,\n op: input0.op,\n collection: input0.collection,\n doc_id: input0.docId,\n session,\n seq: atSeq,\n ...(input0.op !== \"D\" && input0.body !== undefined ? { after: input0.body } : {}),\n ...(input0.origin !== undefined ? { origin: input0.origin } : {}),\n });\n let entry = mintEntry(seq);\n\n // ── Step 4. PUT content bodies + additive index `newKeys` (BEFORE\n // the commit). ──────────────────────────────────────────────────\n // Content PUT: `ifNoneMatch: \"*\"` makes a same-hash re-write a\n // no-op (412 swallowed). Crash-recovery and same-body replay\n // both rely on this idempotency property. Content is content-\n // addressed, so writing it before the commit is crash-safe: a\n // crash here leaves an unreferenced body the compactor sweeps,\n // never an orphan log entry with missing content.\n //\n // Additive index `newKeys` (the markers for the doc's NEW value)\n // ALSO go down here, before the committing create. `newKeys`\n // depend only on `body` + `docId` (NOT on `seq`), so they're\n // stable across the forward re-probe — emit them once. Emitting\n // BEFORE the commit guarantees a committed row is ALWAYS index-\n // findable (no false-negative). A crash after a `newKey` PUT but\n // before the commit leaves an orphan additive key for an\n // UNcommitted write — benign: the index read includes the\n // candidate docId, the fold finds no committed (or the prior)\n // value, and `matchesWire` (query.ts) drops the false-positive.\n // The stale-key DELETEs (de-indexing the OLD value) stay AFTER the\n // commit (Step 5b), so a crash can never de-index a committed doc.\n // See ADR-008 Q4 + `index-emit-order.test.ts`.\n let contentPutCount = 0;\n let newKeysClassA = 0;\n const parallelPuts: Array<Promise<unknown>> = [];\n for (const input of inputs) {\n if (input.op !== \"D\" && input.body !== undefined) {\n contentPutCount++;\n const bytes = encodeJsonBytes(input.body);\n const version = await versionFromContent(bytes);\n const contentKey = `${logPrefix}/content/${version}.json`;\n assertKeyWithinLimit(contentKey);\n parallelPuts.push(\n this.#storage\n .put(contentKey, bytes, { ifNoneMatch: \"*\", contentType: APPLICATION_JSON })\n .catch((error: unknown) => {\n this.#observe429(error, input.collection);\n if (isPreconditionFailed(error)) {\n return;\n }\n throw error;\n }),\n );\n }\n // Additive index keys for the NEW value — emitted before the\n // commit on I/U (a D has no new value). `op:\"D\"` and a missing\n // body project to no keys. Empty `#indexes` short-circuits.\n if (this.#indexes.length > 0 && input.op !== \"D\") {\n const newKeys = allIndexKeysFor(logPrefix, this.#indexes, input.body, input.docId);\n for (const k of newKeys) {\n assertKeyWithinLimit(k);\n newKeysClassA++;\n parallelPuts.push(\n this.#storage\n .put(k, EMPTY_BODY, { ifNoneMatch: \"*\", contentType: APPLICATION_JSON })\n .catch((error: unknown) => {\n this.#observe429(error, input.collection);\n if (isPreconditionFailed(error)) {\n return;\n }\n throw error;\n }),\n );\n }\n }\n }\n await Promise.all(parallelPuts);\n\n // ── Step 5. Create the commit: PUT log/<seq> via If-None-Match. ─\n // The numbered log create IS the commit (single-write commit). No\n // `current.json` CAS follows it — the create is the linearization\n // point (exactly-one-winner, CI-gated across all backends).\n //\n // 200 ⇒ committed at `seq`. 412 ⇒ disambiguate by session read-back:\n // - own session / own seq ⇒ our crashed-or-lost-ack commit is\n // already durable at `seq` ⇒ adopt the resolved `seq` and fall\n // through to the SAME index emit (Step 5b). The adopted commit\n // is EXACTLY the attempt that may have died after creating\n // `log/<seq>` but before emitting its index, so re-running the\n // (idempotent) emit completes it.\n // - foreign session / wrong seq ⇒ re-probe forward and retry at the\n // new first-empty slot (bounded by LOG_FORWARD_PROBE_CAP).\n // A transient NetworkError (e.g. a dropped ack on a create that may\n // already have landed) retries the SAME `seq`: the retry either\n // re-creates (write never landed) or hits the durable write → 412 →\n // own-session adoption. Either way the write lands at EXACTLY `seq`,\n // never duplicated.\n let committedEntry: LogEntry = entry;\n let probes = 0;\n let transientRetries = 0;\n for (;;) {\n const logEntryKey = logObjectKey(logPrefix, seq);\n assertKeyWithinLimit(logEntryKey);\n let conflicted = false;\n try {\n await this.#storage.put(logEntryKey, encodeJsonBytes(entry), {\n ifNoneMatch: \"*\",\n contentType: APPLICATION_JSON,\n });\n } catch (error) {\n this.#observe429(error, entry.collection);\n if (isPreconditionFailed(error)) {\n ctxMetrics().counter(\"db.r2.put.412_total\", 1, {\n collection: entry.collection,\n step: \"log-put\",\n });\n conflicted = true;\n } else if (isTransientWrite(error) && transientRetries < this.#maxRetries) {\n // Possible lost-ack — retry the SAME seq (idempotent: adoption\n // closes the double-commit window). Bounded backoff (full jitter,\n // same as the outer loop) so a backend in transient distress\n // isn't hammered; a persistent NetworkError still surfaces.\n transientRetries++;\n await this.#backoff(transientRetries);\n continue;\n } else {\n throw error;\n }\n }\n if (!conflicted) {\n committedEntry = entry;\n break;\n }\n // 412 — read back the occupant and decide.\n const existing = await readLogEntry(this.#storage, logEntryKey);\n const decision = tryAdoptOwnSessionLogEntry({\n self: entry,\n existing,\n batchSize: inputs.length,\n });\n if (decision.adopt) {\n // Own crashed/lost-ack commit already durable at `seq`. Adopt it\n // (byte-identical to the attempted `entry`, INCLUDING `commit_ts`\n // — adoption compares the full entry) — the logical write lands at\n // EXACTLY `seq`, never duplicated. Fall through to Step 5b: the\n // adopted attempt may have died after the create but before the\n // index emit, so the (idempotent) emit must still run.\n committedEntry = decision.entry;\n break;\n }\n // Foreign session (or wrong seq) — re-probe forward from seq+1 and\n // retry at the new first-empty slot, re-minting seq + LSN.\n if (++probes > LOG_FORWARD_PROBE_CAP) {\n throw new BaerlyError(\n \"Internal\",\n `${errorPrefix}: log-tail forward-probe exceeded ${LOG_FORWARD_PROBE_CAP} on ${this.#currentJsonKey}`,\n );\n }\n seq = await findLogTail(this.#storage, logPrefix, seq + 1);\n entry = mintEntry(seq);\n }\n const committedEntries: readonly LogEntry[] = [committedEntry];\n\n // ── Step 5b. DELETE stale secondary-index keys (AFTER the commit). ─\n // The additive `newKeys` already went down in Step 4 (before the\n // commit), so a committed row is always index-findable. This block\n // handles only the OTHER half: deleting the OLD value's now-obsolete\n // markers. Keeping the stale-key DELETE AFTER the commit is the\n // load-bearing polarity (ADR-008 Q4): a crash here leaves the OLD\n // value's marker lingering — benign, the index read includes the\n // candidate, the fold sees the doc's NEW committed value, and\n // `matchesWire` (query.ts) drops the false-positive; the lingering\n // key is cleaned by a later same-doc write or operator\n // `rebuild-index`. The inverse — de-indexing a committed doc with no\n // log entry to drive repair — can NEVER happen, since the DELETE is\n // strictly after the commit.\n //\n // BOTH the fresh-win and the own-session-adoption break above reach\n // here with the resolved committing `seq`. Adoption correctness: an\n // adopted lost-ack commit is EXACTLY the attempt that may have died\n // after the create but before this DELETE, so it MUST run it too (do\n // not skip it). Idempotent under re-run: `Storage.delete` is\n // contractually idempotent, and the Step-4 `newKeys` PUT is\n // `ifNoneMatch: \"*\"` (412 swallowed).\n //\n // Empty `#indexes` short-circuits the whole block (including the\n // pre-image GET), preserving zero behaviour change for collections\n // without declared indexes. An `op:\"I\"` has no pre-image and no\n // stale keys, so it never reads.\n //\n // The pre-image is read at the RESOLVED committing `seq` (Step 5\n // may have advanced `seq` past a foreign winner): `#readPreImage`\n // back-walks from `seq - 1`, so it skips the just-committed entry\n // and finds the prior same-doc image. For a same-`docId` input\n // earlier in this batch the in-batch image takes precedence.\n //\n // Filter-aware projection (T4): `allIndexKeysFor` short-circuits on\n // `def.predicate` miss. The diff `oldKeys \\ newKeys` covers all four\n // U-quadrants (match→match deletes only the changed keys; match→miss\n // DELETEs all; miss→match deletes nothing; miss→miss no-ops), each\n // pinned by a named test in `writer.test.ts` (\"Writer — filtered\n // index\").\n const staleKeysClassA = await this.#cleanupStaleIndexKeysBestEffort({\n inputs,\n logPrefix,\n seq,\n });\n // The per-logical-write index-op histogram counts BOTH halves: the\n // `newKeys` PUTs (Step 4) and the `staleKeys` DELETEs (Step 5b).\n const indexClassA = newKeysClassA + staleKeysClassA;\n if (this.#indexes.length > 0 && indexClassA > 0) {\n ctxMetrics().histogram(\"db.write.index_ops_per_logical_write\", indexClassA, {\n collection: input0.collection,\n });\n }\n\n // ── Step 6. (removed). No current.json write on the commit path. ─\n // The numbered log create above IS the commit. `tail_hint` is\n // refreshed durably only by the compactor; the writer never advances\n // it. The maintenance trigger below reads a DERIVED tail-byte\n // estimate (`estimateTailBytes`), so there is no stored byte counter.\n\n // ── Step 6b. Write-tick maintenance dispatch. ───────────────────\n // Single funnel site: write-tick maintenance dispatch. Reached by\n // `commit()` exactly once per logical commit, after the committing\n // log create has landed.\n //\n // Config rides the per-request observability context\n // (`getCurrentContext()?.maintenance`), set by the adapter — NOT the\n // Writer constructor / `Db.create`. Absent ⇒ inline dispatch +\n // CF-free-safe caps, so a bare `Db.create(...).collection(...)\n // .insert(...)` maintains inline by default once enough writes\n // accrue.\n //\n // `prevSeq` is the pre-commit tail (`preCommitTail`); the slot we won\n // is `seq` (== prevSeq unless a forward re-probe moved it past a\n // foreign winner), so the boundary check spans `(prevSeq,\n // observedTail]`. `observedTail = seq+1` is a fresh in-memory lower\n // bound on the true tail: winning `log/<seq>` means `[tail_hint, seq)`\n // were observed occupied, so `seq+1 ≤ true tail`. We pass `current`\n // (the Step-1 read) for the snapshot fields — there is no `next`.\n const prevSeq = preCommitTail;\n const observedTail = seq + 1;\n const maint = getCurrentContext()?.maintenance;\n // Same absent-context default as runBoundedMaintenance's\n // `options?.profile ?? MAINTENANCE_PROFILE_CF_FREE` — keep the two in\n // step (this gate reads only gcInterval; the runner resolves the whole\n // profile) so the pre-fire cadence can't diverge from the fold's.\n const gcInterval =\n maint?.options?.profile?.gcInterval ?? MAINTENANCE_PROFILE_CF_FREE.gcInterval;\n const maintenanceDue =\n maint?.disabled === true\n ? observedTail - current.tail_hint >= MAINTENANCE_TAIL_HINT_REFRESH_WRITES\n : shouldFireMaintenance(current, prevSeq, gcInterval, observedTail);\n if (maintenanceDue) {\n const dispatch = maint?.dispatch ?? dispatchInlineAwaited;\n // `await dispatch(...)`: `dispatchInlineAwaited` returns the\n // task's promise (awaited inline — deterministic for tests +\n // correct for serverful Node). A `ctx.waitUntil`-style dispatch\n // returns void (fire-and-forget off the ack); `await void` is a\n // no-op. The `.then(() => {}, () => {})` is belt-and-suspenders:\n // `runBoundedMaintenance` already swallows internally, but this\n // guarantees a dispatched task can NEVER reject the commit even\n // if a future change makes it throw.\n await dispatch(() =>\n runBoundedMaintenance(\n {\n storage: this.#storage,\n currentJsonKey: this.#currentJsonKey,\n prevSeq,\n // Thread the in-memory observed tail so the runner's Gate-1\n // ratio + GC cadence key off the true tail without an\n // O(gap) re-probe (the stored `tail_hint` is only a lower\n // bound under single-write commit).\n observedTail,\n // `disabled` disables fold/GC phases inside the runner but\n // still permits the bounded tail_hint refresh that prevents a\n // maintenance-off collection from drifting past the probe cap.\n ...(maint?.disabled === true && { disabled: true }),\n ...(maint?.maxFoldBytes !== undefined && { maxFoldBytes: maint.maxFoldBytes }),\n },\n maint?.options,\n ).then(\n () => {},\n () => {},\n ),\n );\n }\n\n // Base class-A op count for this attempt: content PUTs (skipping\n // `op:\"D\"`) + the single log create + index PUTs + index DELETEs.\n // No current.json CAS anymore. Forward-probe GETs are Class B and\n // excluded. The caller of `commit()` adds `(attempt - 1)` for retry\n // cost.\n const classAOps = contentPutCount + 1 + indexClassA;\n return {\n entries: committedEntries,\n // No current.json write on the commit path — return the manifest\n // etag read in Step 1 (still a valid etag of the current manifest).\n currentEtag: baseEtag,\n classAOps,\n };\n }\n\n /**\n * Auto-create the per-collection `current.json` at\n * `this.#currentJsonKey` with a zero-state initial manifest. Called\n * by `#singleAttemptCommit` when the read returned `null` (fresh\n * bucket / fresh collection).\n *\n * Concurrency: `createCurrentJson` uses `If-None-Match: \"*\"`. If a\n * peer raced us and won, the storage layer surfaces `Conflict`; we\n * recover by re-reading the now-present manifest. We do NOT retry\n * the create — a single recover-via-read covers every race that\n * could have produced our null read.\n *\n * The seed shape (`snapshot: null`, `tail_hint: 0`, `log_seq_start:\n * 0`, `writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" }`)\n * matches `ensureTable` and `baerly deploy`'s pre-warm path, so an\n * operator who pre-provisions and a writer who auto-creates land\n * on byte-identical bytes.\n *\n * @throws BaerlyError code=\"InvalidResponse\" — the post-recover\n * re-read also returned null. Defensive guard; in practice\n * unreachable because the Conflict implies the key now exists.\n */\n async #provisionCurrentJson(): Promise<CurrentJsonRead> {\n const initial: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n tail_hint: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n try {\n return await createCurrentJson(this.#storage, this.#currentJsonKey, initial);\n } catch (error) {\n if (!(error instanceof BaerlyError) || error.code !== \"Conflict\") {\n throw error;\n }\n }\n const recovered = await readCurrentJson(this.#storage, this.#currentJsonKey);\n if (recovered === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Writer: current.json missing at ${this.#currentJsonKey} after auto-create raced and recover read returned null`,\n );\n }\n return recovered;\n }\n\n async #cleanupStaleIndexKeysBestEffort(args: {\n inputs: readonly CommitInput[];\n logPrefix: string;\n seq: number;\n }): Promise<number> {\n if (this.#indexes.length === 0) {\n return 0;\n }\n\n let staleKeysClassA = 0;\n const indexDeletes: Array<Promise<unknown>> = [];\n // Per-docId in-batch image map: a later input on the same docId\n // reads the in-batch pre-image, not the on-disk one.\n const inBatchImage = new Map<string, DocumentData | undefined>();\n for (const input of args.inputs) {\n let staleKeys: readonly string[] = [];\n try {\n if (input.op === \"U\") {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(args.logPrefix, input.collection, input.docId, args.seq);\n const oldKeys = allIndexKeysFor(args.logPrefix, this.#indexes, preImage, input.docId);\n const newSet = new Set(\n allIndexKeysFor(args.logPrefix, this.#indexes, input.body, input.docId),\n );\n staleKeys = oldKeys.filter((k) => !newSet.has(k));\n } else if (input.op === \"D\") {\n const preImage = inBatchImage.has(input.docId)\n ? inBatchImage.get(input.docId)\n : await this.#readPreImage(args.logPrefix, input.collection, input.docId, args.seq);\n staleKeys = allIndexKeysFor(args.logPrefix, this.#indexes, preImage, input.docId);\n }\n } catch {\n ctxMetrics().counter(\"db.write.index_cleanup_errors_total\", 1, {\n collection: input.collection,\n step: \"pre-image-read\",\n });\n inBatchImage.set(input.docId, input.op === \"D\" ? undefined : input.body);\n continue;\n }\n\n // (op:\"I\" has no pre-image → no stale keys.)\n for (const k of staleKeys) {\n indexDeletes.push(\n this.#storage.delete(k).catch(() => {\n ctxMetrics().counter(\"db.write.index_cleanup_errors_total\", 1, {\n collection: input.collection,\n step: \"delete\",\n });\n }),\n );\n }\n staleKeysClassA += staleKeys.length;\n inBatchImage.set(input.docId, input.op === \"D\" ? undefined : input.body);\n }\n await Promise.all(indexDeletes);\n return staleKeysClassA;\n }\n\n /**\n * Read the pre-image content body for a doc by walking the live log\n * backwards from `currentNextSeq` looking for the most-recent I/U\n * entry on this `(collection, docId)`. Returns `undefined` when:\n *\n * - the doc's most-recent op was `D` (tombstone — no live body);\n * - no entry for this doc lives inside the visible log range\n * `[log_seq_start, currentNextSeq)` (a fresh-insert race or the\n * doc has been folded into the snapshot but is no longer\n * referenced).\n *\n * Used ONLY by the index-emission path's stale-key half (Step 5b, on\n * `U` / `D`) to compute which OLD-value keys to DELETE. Bounded by\n * `log_seq_start`: entries below have been folded into the snapshot\n * and may already be swept off the bucket — a snapshot fold is the\n * rebuild command's job (see `./rebuild-index.ts`), not the writer's.\n *\n * **Cost note:** linear walk, O(snapshot lag). For helpdesk-shape\n * collections (100s of docs, <10k log entries) this is fine — the\n * compactor folds the live tail every ~100 entries\n * (`packages/server/src/compactor.ts`). A follow-up ticket caches\n * per-doc index head in `current.json` for O(1) lookup.\n */\n async #readPreImage(\n logPrefix: string,\n collection: string,\n docId: string,\n currentNextSeq: number,\n ): Promise<DocumentData | undefined> {\n // Walk newest-to-oldest so we hit the most-recent op first.\n // `s = -1` is the natural empty-bucket sentinel.\n for (let s = currentNextSeq - 1; s >= 0; s--) {\n const logKey = logObjectKey(logPrefix, s);\n const got = await this.#storage.get(logKey);\n if (got === null) {\n // A hole below the visible range — either we walked past\n // `log_seq_start` (the entry was folded + swept) or a peer\n // is mid-CAS on a write we don't see yet. Bail; the\n // rebuild command (`rebuildIndex`) handles holes by\n // re-projecting from the snapshot.\n continue;\n }\n let entry: LogEntry;\n try {\n entry = decodeJsonBytes<LogEntry>(got.body);\n } catch {\n // Malformed entry shouldn't propagate up the index-emission\n // path — let the outer commit's `#walkLog` (step 2) flag it\n // as the protocol violation. Skip.\n continue;\n }\n if (entry.collection !== collection || entry.doc_id !== docId) {\n continue;\n }\n if (entry.op === \"D\") {\n return undefined;\n } // last op was delete\n if ((entry.op === \"I\" || entry.op === \"U\") && entry.after !== undefined) {\n return entry.after;\n }\n }\n return undefined;\n }\n\n /**\n * Walk `log/<logSeqStart>.json` … `log/<nextSeq - 1>.json` with\n * bounded parallelism via `walkLogRange`. Materialised entries are\n * discarded — the walk's only job is to surface a hole or a\n * malformed body inside the visible range as\n * `BaerlyError{code:\"Internal\"}` / `\"InvalidResponse\"`.\n *\n * Gated on `verifyLogIntegrityOnCommit`; default off in production\n * because the per-doc fold already lives in the read path. See the\n * option's docstring for the rationale and the opt-in convention.\n *\n * `logSeqStart` is the boundary set by the compactor on\n * `current.json.log_seq_start`. Entries below it have been folded\n * into the snapshot and may have been swept off the bucket, so the\n * walk MUST NOT GET-require them.\n */\n async #walkLog(logPrefix: string, logSeqStart: number, nextSeq: number): Promise<void> {\n await walkLogRange(this.#storage, logPrefix, logSeqStart, nextSeq);\n }\n\n /**\n * Bump the `db.r2.put.429_total` counter when `err` looks like an\n * R2 prefix-partition rate-limit. Best-effort: detected via\n * `BaerlyError{code:\"NetworkError\"}` with a `429` token in the\n * message. Called from every PUT call site's catch arm; mutually\n * exclusive in practice with `isPreconditionFailed` (412 ≠ 429).\n */\n #observe429(err: unknown, collection: string): void {\n if (is429(err)) {\n ctxMetrics().counter(\"db.r2.put.429_total\", 1, { collection });\n }\n }\n\n /**\n * Emit the per-logical-write `class_a_ops_per_logical_write`\n * histogram for `commit`. `classAOps` is the per-attempt base plus\n * a charge for prior failed attempts (the retry-budget cost model),\n * computed by the caller.\n */\n #emitWriteMetrics(collection: string, classAOps: number): void {\n ctxMetrics().histogram(\"db.write.class_a_ops_per_logical_write\", classAOps, { collection });\n }\n\n /**\n * Exponential backoff with full jitter. `25 * 2^(attempt-1)` capped\n * at 1500ms; uniform jitter in `[0, base)` keeps colliding peers\n * from re-racing in lockstep. Worst-case total wait across the\n * default 8 attempts is roughly 2.5 s — well under a typical\n * Worker request budget.\n */\n async #backoff(attempt: number): Promise<void> {\n const base = Math.min(this.#initialBackoffMs * 2 ** (attempt - 1), MAX_BACKOFF_MS);\n const sleepMs = base * this.#random();\n if (sleepMs <= 0) {\n return;\n }\n await new Promise<void>((r) => setTimeout(r, sleepMs));\n }\n}\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\n/**\n * `true` when the underlying storage surfaced a `PreconditionFailed`\n * 412 (or its non-S3 equivalents). Every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`.\n */\nconst isPreconditionFailed = (err: unknown): boolean =>\n err instanceof BaerlyError && err.code === \"Conflict\";\n\n/**\n * `true` when a log-create PUT failed transiently (a `NetworkError`) —\n * the write may or may not have landed (a dropped ack). Safe to retry\n * the SAME seq: own-session adoption closes the double-commit window if\n * it did land. NOT a 412 (that's handled by adoption directly).\n */\nconst isTransientWrite = (err: unknown): boolean =>\n err instanceof BaerlyError && err.code === \"NetworkError\";\n\n/**\n * `true` when the underlying storage surfaced an R2 prefix-partition\n * rate-limit. {@link S3HttpStorage} stamps the upstream HTTP status\n * onto `BaerlyError.cause` as `{ status }`; we discriminate on that\n * structured field rather than regex-matching the message.\n */\nconst is429 = (err: unknown): boolean => {\n if (!(err instanceof BaerlyError) || err.code !== \"NetworkError\") {\n return false;\n }\n const cause = err.cause as { status?: number } | undefined;\n return cause?.status === 429;\n};\n","/**\n * `baerly admin restore` — bulk-import NDJSON into a fresh collection.\n *\n * Reads NDJSON from stdin, reconstructs each row, and calls\n * `Writer.commit({op:\"I\"})` per row into the target bucket.\n * Programmatic callers (today: tests + the export round-trip\n * integration test) can divert the input by passing\n * `{ streams: { stdin } }` to {@link runRestore}. Idempotent on a fresh\n * bucket: re-running on a half-completed restore **refuses** unless\n * `--force` is set (which reseeds a fresh `current.json` above the old\n * tail first).\n *\n * Args:\n * --bucket Required. Target bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Target collection name.\n * --force Truncate the target if it exists (reseed above the old tail).\n * --json JSON envelope.\n *\n * stdin: NDJSON, one `{_id, ...}` row per line. Empty lines tolerated.\n * EOF terminates.\n *\n * Cost shape: under single-write commit each `Writer.commit` is 2 Class\n * A PUTs (content + the committing `log/<seq>` create — no per-row\n * `current.json` write). So: 1 PUT current.json (initial seed) + N × 2\n * + 1 PUT current.json (final `tail_hint` stamp) = 2N + 2 Class A ops\n * for N rows.\n *\n * Partial-restore semantics: a mid-stream Network / Internal / parse\n * error leaves the target in a partial state (some rows committed,\n * `current.json` advanced to wherever the last successful commit\n * landed). Re-run with `--force` to truncate, or hand-clean. The\n * malformed-line case (missing `_id`, bad JSON) fails fast on that\n * line; rows committed BEFORE it survive.\n *\n * Exit codes:\n * 0 — every row committed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Network / storage error mid-stream, or a malformed NDJSON\n * line (raised as a plain `Error`, not `BaerlyError`).\n * 3 — Conflict from a pre-existing target without --force, or from a\n * concurrent writer when --force was used.\n */\n\nimport { createInterface } from \"node:readline\";\nimport { type ArgsDef } from \"citty\";\nimport {\n BaerlyError,\n CURRENT_JSON_SCHEMA_VERSION,\n createCurrentJson,\n type CurrentJson,\n type DocumentData,\n encodeJsonBytes,\n readCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\nimport { Writer } from \"@baerly/server/_internal/testing\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { assertCollectionArg, defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst RESTORE_OWNER = \"baerly-restore\";\n\nconst RESTORE_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Target bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Target collection name.\",\n valueHint: \"name\",\n },\n force: {\n type: \"boolean\",\n description: \"Truncate the target if it exists (bump fence + reseed current.json).\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst tailFromListedLogKeys = async (\n storage: Storage,\n collectionPrefix: string,\n): Promise<number> => {\n const logPrefix = `${collectionPrefix}/log/`;\n let maxSeq = -1;\n for await (const entry of storage.list(logPrefix)) {\n const tail = entry.key.slice(logPrefix.length);\n const match = /^(\\d+)\\.json$/.exec(tail);\n if (match === null) {\n continue;\n }\n const seq = Number.parseInt(match[1]!, 10);\n if (Number.isFinite(seq) && seq > maxSeq) {\n maxSeq = seq;\n }\n }\n return maxSeq + 1;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.restore\",\n meta: {\n description: \"Bulk-import canonical NDJSON into a fresh collection.\",\n },\n args: RESTORE_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly admin restore\");\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n\n let baseSeq = 0;\n const head = await readCurrentJson(bucket.storage, currentJsonKey);\n if (head !== null && args.force !== true) {\n throw new BaerlyError(\n \"Conflict\",\n `baerly admin restore: ${currentJsonKey} exists; pass --force to truncate`,\n );\n }\n if (head !== null) {\n // --force: reseed `current.json` above the old tail under\n // If-Match. The If-Match guards against a concurrent COMPACTOR\n // (the only steady-state writer of `current.json` under\n // single-write commit) landing between our read and our PUT —\n // that surfaces Conflict (exit 3). It does NOT fence concurrent\n // WRITERS: under single-write commit writers never touch\n // `current.json`, so the dormant `writer_fence` epoch is no\n // longer consulted. `restore` therefore assumes operational\n // exclusivity — do not run it against a collection taking live\n // writes. (We still bump the fence epoch to keep the field\n // monotone, but nothing reads it.)\n //\n // CRITICAL: stale log entries from the old generation still\n // live on disk under `log/<seq>.json` paths. The writer's\n // `If-None-Match: \"*\"` log PUT will 412 if we restart `tail_hint`\n // at 0 and collide with `log/0.json`. We instead advance\n // `tail_hint` and `log_seq_start` past the old data so new\n // commits land at fresh sequence numbers and the old log files\n // become unreferenced orphans (the compactor / GC sweep them on\n // the next maintenance pass). Do this from LISTed log keys, not\n // by folding the old log bodies: `--force` must be able to recover\n // from malformed old entries, and a hole must not make us\n // under-shoot a later old entry.\n const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n const truncatedNext = await tailFromListedLogKeys(bucket.storage, collectionPrefix);\n baseSeq = truncatedNext;\n const reseeded: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n tail_hint: truncatedNext,\n log_seq_start: truncatedNext,\n writer_fence: {\n epoch: head.json.writer_fence.epoch + 1,\n owner: RESTORE_OWNER,\n claimed_at: \"\",\n },\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n try {\n await bucket.storage.put(currentJsonKey, encodeJsonBytes(reseeded), {\n ifMatch: head.etag,\n contentType: \"application/json\",\n });\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `baerly admin restore: failed to reseed current.json: ${(error as Error).message}`,\n );\n }\n } else {\n // Fresh target: seed `current.json` with `tail_hint=0`.\n const seed: CurrentJson = {\n schema_version: CURRENT_JSON_SCHEMA_VERSION,\n snapshot: null,\n tail_hint: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: RESTORE_OWNER, claimed_at: \"\" },\n snapshot_bytes: 0,\n snapshot_rows: 0,\n };\n await createCurrentJson(bucket.storage, currentJsonKey, seed);\n }\n\n const writer = new Writer({ storage: bucket.storage, currentJsonKey });\n\n const input = ctx.streams?.stdin ?? process.stdin;\n const rl = createInterface({ input, crlfDelay: Infinity });\n let count = 0;\n let lineNo = 0;\n for await (const line of rl) {\n lineNo++;\n if (line.length === 0) {\n continue;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch (error) {\n // Malformed NDJSON mid-stream → exit 2 (the ticket's\n // partial-restore contract: the line that failed wasn't\n // committed, but anything BEFORE it survives). Bare `Error`\n // (not `BaerlyError`) routes through the helper's \"unknown\"\n // arm → exit 2.\n throw new Error(\n `baerly admin restore: line ${lineNo} is not valid JSON: ${(error as Error).message}`,\n { cause: error },\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(`baerly admin restore: line ${lineNo} is not a JSON object`);\n }\n const row = parsed as Record<string, unknown>;\n const id = row[\"_id\"];\n if (typeof id !== \"string\" || id.length === 0) {\n throw new Error(`baerly admin restore: line ${lineNo} missing non-empty string _id`);\n }\n // Pass the full object as the body — `_id` is part of the\n // body in the doc shape, and the writer keys on `docId`\n // separately.\n const body = row as unknown as DocumentData;\n await writer.commit({\n op: \"I\",\n collection: args.collection,\n docId: id,\n body,\n });\n count++;\n }\n // Stamp the final `tail_hint` durably. Under single-write commit the\n // writer never advances the hint (it's compactor-advanced) — but a\n // bulk restore knows exactly how many rows it wrote, so it stamps the\n // true tail (`baseSeq + count`) under If-Match so the restored bucket\n // reads efficiently without a forward-probe. A concurrent compactor\n // between our last commit and this stamp surfaces Conflict (exit 3).\n // CLAMP: `tail_hint` is a monotone lower bound, so never stamp it\n // BELOW what is already durable — take the max of our computed tail,\n // the value already stored, and `log_seq_start`. (Defends against a\n // compactor that advanced the hint between the reseed and here.)\n if (count > 0) {\n const afterLoad = await readCurrentJson(bucket.storage, currentJsonKey);\n if (afterLoad !== null) {\n const clampedTail = Math.max(\n baseSeq + count,\n afterLoad.json.tail_hint,\n afterLoad.json.log_seq_start,\n );\n const stamped: CurrentJson = { ...afterLoad.json, tail_hint: clampedTail };\n await bucket.storage.put(currentJsonKey, encodeJsonBytes(stamped), {\n ifMatch: afterLoad.etag,\n contentType: \"application/json\",\n });\n }\n }\n emitSuccess({\n command: \"admin.restore\",\n status: \"ok\",\n collection: args.collection,\n restored: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin restore`. */\nexport const restoreCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runRestore = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;AAUA,MAAa,eAAe,OAAqB;CAC/C,kBAAkB,IAAI,KAAK;AAC7B;;;ACVA,MAAM,OAAO,IAAI,YAAY;;;;;;;;AAS7B,MAAa,wBAAwB,QAAsB;CACzD,MAAM,QAAQ,KAAK,OAAO,GAAG,CAAC,CAAC;CAC/B,IAAI,QAAA,MACF,MAAM,IAAI,YACR,iBACA,sBAAsB,cAAc,cAAc,MAAM,KAAK,KAAK,UAAU,IAAI,MAAM,GAAG,EAAE,CAAC,EAAE,EAChG;AAEJ;;;;;;;;;;;;;;;;;;;;;ACqIA,MAAa,8BAA8B,QAA2C;CAIpF,IAAI,IAAI,cAAc,GACpB,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAQ;CAGzC,IAAI,IAAI,SAAS,YAAY,IAAI,KAA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,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GACvE,MAAM,IAAI,MAAM,8BAA8B,OAAO,sBAAsB;GAE7E,MAAM,MAAM;GACZ,MAAM,KAAK,IAAI;GACf,IAAI,OAAO,OAAO,YAAY,GAAG,WAAW,GAC1C,MAAM,IAAI,MAAM,8BAA8B,OAAO,8BAA8B;GAKrF,MAAM,OAAO;GACb,MAAM,OAAO,OAAO;IAClB,IAAI;IACJ,YAAY,KAAK;IACjB,OAAO;IACP;GACF,CAAC;GACD;EACF;EAWA,IAAI,QAAQ,GAAG;GACb,MAAM,YAAY,MAAM,gBAAgB,OAAO,SAAS,cAAc;GACtE,IAAI,cAAc,MAAM;IACtB,MAAM,cAAc,KAAK,IACvB,UAAU,OACV,UAAU,KAAK,WACf,UAAU,KAAK,aACjB;IACA,MAAM,UAAuB;KAAE,GAAG,UAAU;KAAM,WAAW;IAAY;IACzE,MAAM,OAAO,QAAQ,IAAI,gBAAgB,gBAAgB,OAAO,GAAG;KACjE,SAAS,UAAU;KACnB,aAAa;IACf,CAAC;GACH;EACF;EACA,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB,UAAU;EACZ,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,aAAa,OAAO;AAOP,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"shared-secret-BJdSwpgw.js","names":[],"sources":["../packages/server/src/auth/internal/timing-safe-equal.ts","../packages/server/src/auth/presets/shared-secret.ts"],"sourcesContent":["/**\n * Constant-time byte-array equality. Length mismatch short-circuits —\n * the attacker already knows the expected length is a few-dozen bytes,\n * so revealing it is a non-secret. The diff loop only runs when the\n * lengths match, so its timing cannot leak the position of the first\n * differing byte.\n *\n * Hoisted out of {@link sharedSecret} so future verifiers can reuse\n * the same implementation — one TODO is easier to land than two.\n */\nexport const timingSafeEqual = (a: Uint8Array, b: Uint8Array): boolean => {\n if (a.length !== b.length) {\n return false;\n }\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= a[i]! ^ b[i]!;\n }\n return diff === 0;\n};\n","import { BaerlyError, type Verifier } from \"@baerly/protocol\";\nimport { timingSafeEqual } from \"../internal/timing-safe-equal.ts\";\n\n/**\n * Options for {@link sharedSecret}.\n *\n * - `secret` — the bearer token clients must present. Compared with\n * constant-time `timingSafeEqual` — see {@link sharedSecret} for\n * why naive `===` is not enough.\n * - `tenantPrefix` — the value returned in `VerifierResult.tenantPrefix`.\n * Single-tenant deployments pass a constant (`\"acme\"`). Multi-tenant\n * deployments don't use `sharedSecret`; they reach for `bearerJwt`\n * or `cloudflareAccess` instead.\n */\nexport interface SharedSecretOptions {\n readonly secret: string;\n readonly tenantPrefix: string;\n}\n\n/**\n * Build a `Verifier` that accepts `Authorization: Bearer <secret>`\n * and pins every request to a single tenant. The simplest preset —\n * use for single-tenant deployments before you've stood up an IdP.\n *\n * **Why constant-time compare:** a naive `===` against the bearer\n * token leaks timing information about which character first\n * differed. Real-world relevance over HTTPS is debated, but\n * `timingSafeEqual` is one line of code and erases the question.\n *\n * **Identity shape.** On success the returned `VerifierResult` has:\n * ```ts\n * { tenantPrefix: \"<configured>\", identity: { kind: \"shared-secret\" } }\n * ```\n * `sharedSecret` has no notion of a per-user subject — every caller\n * presenting the bearer is the same principal. Downstream code that\n * wants a stable per-request `sender_sub` should fall back to a\n * synthetic value (`\"shared-secret:\" + tenantPrefix`) when\n * `identity.kind === \"shared-secret\"`. The `kind` field is the\n * discriminant across all preset identities; switch on it instead of\n * sniffing properties.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `secret` empty or\n * `tenantPrefix` empty / contains \"/\".\n *\n * @example\n * ```ts\n * import { sharedSecret } from \"@gusto/baerly-storage/auth\";\n * const verifier = sharedSecret({\n * secret: env.SHARED_SECRET,\n * tenantPrefix: \"acme\",\n * });\n * ```\n */\nexport const sharedSecret = (opts: SharedSecretOptions): Verifier => {\n if (opts.secret.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"sharedSecret: secret must be non-empty\");\n }\n if (opts.tenantPrefix.length === 0 || opts.tenantPrefix.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `sharedSecret: tenantPrefix must be non-empty and \"/\"-free (got ${JSON.stringify(opts.tenantPrefix)})`,\n );\n }\n const expected = new TextEncoder().encode(`Bearer ${opts.secret}`);\n return async (req: Request) => {\n const header = req.headers.get(\"Authorization\") ?? \"\";\n const actual = new TextEncoder().encode(header);\n if (!timingSafeEqual(expected, actual)) {\n return null;\n }\n return { tenantPrefix: opts.tenantPrefix, identity: { kind: \"shared-secret\" } };\n };\n};\n"],"mappings":";;;;;;;;;;;;AAUA,MAAa,mBAAmB,GAAe,MAA2B;CACxE,IAAI,EAAE,WAAW,EAAE,QACjB,OAAO;CAET,IAAI,OAAO;CACX,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAC5B,QAAQ,EAAE,KAAM,EAAE;CAEpB,OAAO,SAAS;AAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACkCA,MAAa,gBAAgB,SAAwC;CACnE,IAAI,KAAK,OAAO,WAAW,GACzB,MAAM,IAAI,YAAY,iBAAiB,wCAAwC;CAEjF,IAAI,KAAK,aAAa,WAAW,KAAK,KAAK,aAAa,SAAS,GAAG,GAClE,MAAM,IAAI,YACR,iBACA,kEAAkE,KAAK,UAAU,KAAK,YAAY,EAAE,EACtG;CAEF,MAAM,WAAW,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU,KAAK,QAAQ;CACjE,OAAO,OAAO,QAAiB;EAC7B,MAAM,SAAS,IAAI,QAAQ,IAAI,eAAe,KAAK;EAEnD,IAAI,CAAC,gBAAgB,UADN,IAAI,YAAY,CAAC,CAAC,OAAO,MACJ,CAAC,GACnC,OAAO;EAET,OAAO;GAAE,cAAc,KAAK;GAAc,UAAU,EAAE,MAAM,gBAAgB;EAAE;CAChF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-CWpkSbvJ.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 tail_hint: 0,\n log_seq_start: 0,\n writer_fence: { epoch: 0, owner: \"\", claimed_at: \"\" },\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 { link, 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\n/**\n * Reserved prefix for the in-directory create-if-absent temp (see `put`).\n * `walk`/`list` skip it; it is internal/transient and never a real key.\n */\nconst TEMP_PREFIX = \".baerly-tmp-\";\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.\n *\n * `ifNoneMatch:\"*\"` uses a same-dir temp + `link(2)` (atomic exclusive\n * create; `EEXIST` ⇒ key exists) so concurrent creates have exactly one\n * winner. Same-dir avoids `EXDEV`; temp+`link` over `open(…,\"wx\")` keeps\n * a partially-written new key invisible to a concurrent reader. `ifMatch`\n * keeps the `rename` path (in-process TOCTOU only; cross-process\n * contention uses the S3 / Minio `If-Match` 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 await mkdir(dirname(path), { recursive: true });\n\n if (opts?.ifNoneMatch === \"*\") {\n // Atomic exclusive create via link(2) — see class JSDoc.\n const tmp = join(\n dirname(path),\n `${TEMP_PREFIX}${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n try {\n await writeFile(tmp, body);\n await link(tmp, path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"EEXIST\") {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n error,\n );\n } finally {\n // Best-effort cleanup — a failed write may leave a partial temp,\n // and a cleanup failure must not mask a Conflict thrown above.\n await rm(tmp, { force: true }).catch(() => {});\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n if (opts?.ifMatch !== undefined) {\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 (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 // Unconditional PUT (or ifMatch already verified above).\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() && !entry.name.startsWith(TEMP_PREFIX)) {\n // Skip the transient create-if-absent temps (see TEMP_PREFIX) so a\n // concurrent list during a create never surfaces a half-linked key.\n out.push(relative(root, full).split(sep).join(posix.sep));\n }\n }\n }\n};\n"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;CAAA,IAAI,IAAE;CACN,IAAI,SAAO,WAAW;EAAC,OAAO;GAAC,kBAAiB;GAAM,OAAM;GAAE,MAAK;GAAE,KAAI;GAAE,QAAO;GAAE,WAAU;GAAE,SAAQ;GAAE,QAAO;GAAE,eAAc;GAAE,OAAM;GAAE,KAAI;GAAE,OAAM;GAAE,QAAO;GAAE,MAAK;GAAE,SAAQ;GAAE,MAAK;GAAE,OAAM;GAAE,MAAK;GAAE,SAAQ;GAAE,OAAM;GAAE,SAAQ;GAAE,UAAS;GAAE,QAAO;GAAE,WAAU;GAAE,QAAO;GAAE,SAAQ;GAAE,aAAY;GAAE,WAAU;GAAE,aAAY;GAAE,cAAa;GAAE,YAAW;GAAE,eAAc;GAAE,YAAW;GAAE,aAAY;GAAE,eAAc;GAAE,aAAY;GAAE,eAAc;GAAE,gBAAe;GAAE,cAAa;GAAE,iBAAgB;GAAE,cAAa;GAAE,eAAc;EAAC;CAAC;CACtgB,OAAO,UAAQ,OAAO;CACtB,OAAO,QAAQ,eAAe;;;;;ACe9B,SAAgB,eAAe,MAA2B;CACxD,MAAM,UACJ,KAAK,UAAU,KAAA,IACX,KAAK,QACL,QAAQ,IAAI,UAAU,KAAA,KAAa,CAAC,QAAQ,OAAO;CACzD,MAAM,QAAQ,KAAK,WAAW,UAAU,QAAQ,OAAO,MAAM,KAAK;CA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