@gusto/baerly-storage 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +157 -92
  2. package/dist/API.md +64 -32
  3. package/dist/CHANGELOG.md +295 -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-qL3_lTTU.js +391 -0
  96. package/dist/runtime-spec-qL3_lTTU.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-BG20LZs7.js +2271 -0
  104. package/dist/src-BG20LZs7.js.map +1 -0
  105. package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
  106. package/dist/src-CYHFDrKz.js.map +1 -0
  107. package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
  108. package/dist/src-DYZ4H1aF.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 +52 -28
  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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-1tv0-Yzm.js","names":["utf8Encoder","compareKeysUtf8","#objects","#etagCounter","#nextEtag","#root","#pathFor","#endpoint","#bucket","#fetch","#sign","#retries","#backoffMs","#dispatch","#objectUrl","#retry"],"sources":["../packages/protocol/src/constants.ts","../packages/protocol/src/env.ts","../packages/protocol/src/storage/key.ts","../packages/protocol/src/storage/memory.ts","../packages/protocol/src/types.ts","../packages/protocol/src/time.ts","../packages/dev/src/local-fs.ts","../node_modules/.pnpm/@rgrove+parse-xml@4.2.1/node_modules/@rgrove/parse-xml/dist/browser.js","../packages/adapter-node/src/xml.ts","../packages/adapter-node/src/s3-http.ts","../node_modules/.pnpm/aws4fetch@1.0.20/node_modules/aws4fetch/dist/aws4fetch.esm.mjs","../packages/adapter-node/src/credentials/signer.ts","../packages/adapter-node/src/storage-factories.ts","../packages/cli/src/bucket-uri.ts","../packages/cli/src/config.ts"],"sourcesContent":["/**\n * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key\n * over this fails the PUT with an opaque provider 400; baerly surfaces\n * it early as InvalidConfig. See docs/spec/storage-compatibility.md.\n */\nexport const MAX_KEY_BYTES = 1024;\n\n/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the descending base-32 seq segment in every LSN\n * (`<base32-time>_<session>_<seq>`, minted in `Writer.commit`).\n * The output character width is `Math.ceil(COUNT_BIT_WIDTH / 5) = 11`.\n *\n * **Domain:** 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1). A collection\n * would need 2^53 writes before the seq counter could overflow — an\n * unreachable ceiling in practice.\n *\n * **Why 53 bits:** JavaScript numbers are IEEE-754 doubles; the safe\n * integer range is exactly [0, 2^53 − 1]. Encoding at this width keeps\n * the arithmetic in the encoder and decoder (`uint2strDesc` /\n * `str2uintDesc` in `packages/protocol/src/types.ts`) exact and\n * leaves no headroom for the negative-overflow path that manifested\n * at the old 10-bit width (domain 0..1023).\n *\n * **Ordering property:** fixed-width base-32 encoding preserves\n * descending lex order across the entire domain\n * (`countKey(a) > countKey(b)` iff `a < b`), which the reverse-walk\n * on `Storage.list` relies on.\n *\n * **Three production consumers** must all agree on this value:\n * 1. Encoder — `countKey` in `packages/protocol/src/types.ts`\n * 2. Decoder — `lsnParts` in `packages/protocol/src/log.ts`\n * 3. Validator regex — `LSN_RE` in `packages/server/src/http/since.ts`\n * (derives its `{N}` from `Math.ceil(COUNT_BIT_WIDTH / 5)`)\n *\n * The independent shape-assertion literal in\n * `tests/fixtures/collection-api-cascade.ts` is kept hand-written and\n * is NOT a consumer of this constant (importing the production\n * validator into the test that checks it would make the assertion\n * a tautology).\n *\n * Changing this constant is a protocol-breaking change — it reshapes\n * every emitted LSN cursor.\n *\n * @see packages/protocol/src/types.ts (`countKey`, `uint2strDesc`)\n * @see packages/protocol/src/log.ts (`lsnParts`, `str2uintDesc` call)\n * @see packages/server/src/http/since.ts (`LSN_RE`)\n * @see docs/spec/log-entry-shape.md\n */\nexport const COUNT_BIT_WIDTH: number = 53;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):\n * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`\n * (rather than silently truncating reads). A runaway alarm only — the\n * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means\n * maintenance is off or the collection is far past graduation.\n *\n * @see packages/server/src/log-tail.ts (`probeTailFrom`)\n */\nexport const LOG_FORWARD_PROBE_CAP: number = 100_000;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 3 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * Current major version of the snapshot control-object schema\n * ({@link SnapshotBody}). Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `SnapshotBody` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/server/src/snapshot.ts\n */\nexport const SNAPSHOT_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `gc/pending.json` PUTs.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Default grace period between \"marking\" a key for GC and \"sweeping\"\n * (deleting) it. 7 days, chosen to span the worst plausible writer-\n * retry window (a paused-process writer that resumes hours later\n * should still find its idempotency anchor on the bucket). The\n * `runGc()` function accepts an override for tests.\n *\n * Why 7 days specifically:\n * - **1 day is too aggressive for batch workloads.** Worker isolate\n * scheduling pauses, cross-region replication lag, and\n * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly\n * exceed an hour under pathological conditions.\n * - **30 days is conservative beyond the worst plausible pause.**\n * Doubles `gc/pending.json` size at steady state and slows\n * visibility into \"did GC actually run?\" by 4×.\n * - **7 days spans the realistic upper bound** — long-running batch\n * jobs, multi-region propagation delays, queue backlogs, and\n * downstream outages the writer is retrying through. The protocol\n * is unaffected by the choice of value within the [hours, weeks]\n * range; this constant is the operator-tunable knob.\n *\n * Production code MUST NOT call `runGc` with `graceMillis` below the\n * default outside maintenance windows — going below the longest\n * plausible writer-retry latency risks deleting an anchor a writer\n * is about to find on retry. Test code that sets `graceMillis: 0` is\n * exercising the sweep path deliberately, not modelling production.\n *\n * @see packages/server/src/gc.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const GC_GRACE_PERIOD_MILLIS: number = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Cap on candidates kept in `gc/pending.json` to bound the size of\n * the file. The compactor marks at most this many candidates per\n * pass; subsequent passes pick up the rest. Larger collections will\n * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which\n * is acceptable.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_MAX_PENDING_CANDIDATES: number = 1000;\n\n/**\n * Bounded retry cap for the `gc/pending.json` CAS read-modify-write\n * loop in {@link casUpdateGcPending}. On `Conflict` (a concurrent GC\n * pass landed between this pass's read and its write) the loop\n * re-reads `latest` and re-applies the pure merge mutator, retrying up\n * to this many total attempts before surfacing `Conflict`. Safe to\n * retry because the mutator is pure and the sweep DELETEs are\n * idempotent and already performed; a re-merge against fresh state\n * never loses a concurrently-marked candidate. Small fixed cap — under\n * one writer per collection at steady state, contention is rare; this\n * just bounds the worst case so a pathological storm can't spin.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CAS_MAX_ATTEMPTS: number = 3;\n\n/**\n * Fold-trigger ratio: fold fires at tail ≥ R×snapshot. Pure READ-AMP / fold-frequency\n * knob — with the ceiling on the snapshot axis (Decision 3a, tail sliced) the\n * auto-maintained snapshot ceiling is S_max = C, NOT C/(1+R). R=1.0 caps steady-state\n * read-amp at ~2× and keeps compaction write-amp (≈1+1/R) moderate. See\n * docs/about/graduation.md for the derivation.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TARGET_RATIO: number = 1;\n\n/**\n * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also\n * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.\n *\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MIN_LIVE_BYTES: number = 64 * 1024;\n\n/**\n * Cold-start per-entry byte estimate for the ratio TRIGGER's derived live-tail\n * size (`estimateTailBytes`), used until the compactor stamps a real\n * `current.json.mean_entry_bytes` on the first fold. Folding too-few entries is\n * barred by Gate-1's entry-count floor (`minEntriesToCompact`), NOT by this\n * value — so over-estimating is equally safe; this is a first-fold-TIMING\n * choice. A small typical log-entry size keeps the first fold's cadence close\n * to a precisely measured path for typical entries; must be non-zero so a\n * bare `Db.create()` still bootstraps its first auto-fold (a 0 fallback leaves\n * the ratio dead pre-stamp). Large-body collections see a bounded first-fold\n * delay; after it stamps a real mean the estimate tracks the exact tail.\n *\n * @see packages/server/src/maintenance.ts (`estimateTailBytes`)\n */\n// Stryker disable next-line ArithmeticOperator: internal cold-start tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_COLD_START_ENTRY_BYTES: number = 128;\n\n/**\n * Per-tick GC budget — these are DEFAULTS (= the most-constrained tier, CF free, reusing\n * the TESTED `CLOUDFLARE_FREE_TIER` values in maintenance.ts / maintenance-budget.test.ts).\n * The adapter THREADS per-tier overrides into the context (§8.4); Node/CF-paid raise them.\n * NOT universal constants — a Node-sized value here would silently kill every CF-free fold\n * (round-4 Tier-1). gc pass ≈ 6 + maxMarks + maxSweeps subrequests (both GET/DELETE the\n * bucket — §3.1). Cadence is BOUNDARY-CROSSING (§3.1), not modulo.\n *\n * @see packages/server/src/maintenance.ts\n * @see packages/server/src/maintenance-budget.test.ts\n */\nexport const WRITE_TICK_GC_INTERVAL: number = 4; // tuned so maxSweeps/interval ≥ p (§7.1)\n\n/**\n * Fold-starvation guard (critique A): on `phasesPerTick:\"single\"`, every Nth GC-interval is a\n * HARD GC boundary the fold may NOT preempt, so a long fold-heavy drain can't starve GC to zero.\n * Stateless (seq-derived) — no per-isolate preemption counter (CF recycles isolates). At 4 a\n * sustained drain still yields ~1 GC tick per 4 GC-intervals.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const GC_STARVATION_GUARD: number = 4;\n\n/**\n * Maximum GC marks per write-tick pass (M in 6+M+S; GETs the live tail to hash).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_MARKS: number = 20;\n\n/**\n * Maximum GC sweeps per write-tick pass (S in 6+M+S; DELETE subrequests).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_SWEEPS: number = 10;\n\n/**\n * Per-pass tail SLICE default — compact()'s maxEntriesPerRun. Fold ≤ this+3 subrequests, so\n * a large tail drains incrementally over write-ticks (Decision 3). Adapter-overridable.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_FOLD_ENTRIES_PER_PASS: number = 20;\n\n/**\n * compact()'s minEntriesToCompact, set EXPLICITLY by the runner so it agrees with Gate 1\n * rather than inheriting compact()'s silent default 100 (which would contradict the 64 KB\n * first-fold story — round-4 Tier-3). Adapter-overridable; CF-free value.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_MIN_ENTRIES_TO_COMPACT: number = 50;\n\n/**\n * Node-tier write-tick maintenance caps — a MODERATE multiple of the CF-free `WRITE_TICK_*`\n * defaults, threaded into the per-request observability context by `baerlyNode` /\n * `createFetchHandler` (§8.4). Node v1 runs maintenance INLINE on the commit path (no\n * `waitUntil`), so the cap is NOT the CF subrequest wall — it's the worst-case single-write\n * added latency. A maintenance tick only fires on a ratio/boundary trip (rare), and when it\n * does it costs ~`maxFoldEntriesPerPass` + (6 + `gcMaxMarks` + `gcMaxSweeps`) storage\n * round-trips against a co-located S3/R2 — sub-second on the occasional boundary write at a\n * 10× multiple. These are deliberately BOUNDED (10× CF-free), NOT unbounded: the deleted\n * scheduled full-tail sweep folded the entire live tail in one shot, which a 100× multiple here\n * would reintroduce as multi-second commit stalls. Raise the snapshot ceiling separately via\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; these caps slice the per-pass work, not the ceiling.\n *\n * @see packages/adapter-node/src/server.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\nexport const NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS: number = 200;\n\n/** Node-tier GC marks per pass (M in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_MARKS: number = 200;\n\n/** Node-tier GC sweeps per pass (S in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_SWEEPS: number = 100;\n\n/**\n * Node-tier GC cadence (boundary-crossing). Shorter than the CF-free `WRITE_TICK_GC_INTERVAL`\n * (4) so the per-write sweep budget keeps up: `gcMaxSweeps / gcInterval = 100 / 2 = 50`\n * comfortably clears the garbage-per-write rate `p` (the `maxSweeps/interval ≥ p` invariant,\n * §7.1) with a wide margin.\n *\n * @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS}\n */\nexport const NODE_MAINTENANCE_GC_INTERVAL: number = 2;\n\n/**\n * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized\n * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable\n * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT: number = 512 * 1024;\n\n/**\n * The largest snapshot a Cloudflare **free-tier** isolate can safely\n * rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN\n * THRESHOLD, not a runtime cap: an operator who raises\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker\n * risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets\n * CPU-killed MID-REBUILD — the CAS never lands, so the fold silently\n * never advances `log_seq_start` and the tail grows unbounded.\n *\n * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default\n * (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget\n * (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the\n * point where one-shot rebuild fills the budget with little margin, so\n * anything strictly larger is no longer free-tier-safe. On CF **paid**\n * (raised CPU limits), Node, or once §11 chunked snapshots land, a\n * larger ceiling is fine — hence this is a one-time `console.warn` at\n * handler init, NOT a hard rejection.\n *\n * @see packages/adapter-cloudflare/src/worker.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const CF_FREE_MAX_SAFE_FOLD_BYTES: number = 1024 * 1024;\n\n/**\n * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry\n * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021\n * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — bench\n * landed; paid recalibration deferred.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_MAX_FOLD_ROWS: number = 2048;\n\n// Declared here (not the nominal server `MaintenanceProfile`) to avoid a server→protocol cycle; keep field-identical to it.\ntype MaintenanceProfileShape = Readonly<{\n gcInterval: number;\n gcMaxMarks: number;\n gcMaxSweeps: number;\n maxFoldEntriesPerPass: number;\n maxFoldBytes: number;\n maxFoldRows: number;\n}>;\n\n/** CF-free profile; the absent-context default. */\nexport const MAINTENANCE_PROFILE_CF_FREE: MaintenanceProfileShape = {\n gcInterval: WRITE_TICK_GC_INTERVAL,\n gcMaxMarks: WRITE_TICK_GC_MAX_MARKS,\n gcMaxSweeps: WRITE_TICK_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/** Node profile; 10× CF-free caps. */\nexport const MAINTENANCE_PROFILE_NODE: MaintenanceProfileShape = {\n gcInterval: NODE_MAINTENANCE_GC_INTERVAL,\n gcMaxMarks: NODE_MAINTENANCE_GC_MAX_MARKS,\n gcMaxSweeps: NODE_MAINTENANCE_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/**\n * CF-paid profile — opt-in via `BAERLY_MAINTENANCE_PROFILE=cf-paid`. A paid\n * isolate keeps the CPU-killable single-phase shape but has the 10,000-\n * subrequest budget (vs free's 50), so it reuses the `NODE_MAINTENANCE_*`\n * per-pass caps. CRITICAL: snapshot ceilings `maxFoldBytes` (`C`) /\n * `maxFoldRows` (`E`) are UNCHANGED — a profile moves rate, never correctness\n * (the equivalence invariant); the memory wall is raised via\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`.\n *\n * @see packages/adapter-cloudflare/src/worker.ts\n * @see docs/about/graduation.md\n */\nexport const MAINTENANCE_PROFILE_CF_PAID: MaintenanceProfileShape = {\n gcInterval: NODE_MAINTENANCE_GC_INTERVAL,\n gcMaxMarks: NODE_MAINTENANCE_GC_MAX_MARKS,\n gcMaxSweeps: NODE_MAINTENANCE_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/**\n * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate\n * memory — CF recycles isolates). ~once per this many writes.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_WARN_INTERVAL_WRITES: number = 1000;\n\n/**\n * Rate-limit for the maintenance tick's `tail_hint` advance on the\n * DEFER path (HR-2). When the fold defers (snapshot over the CF-CPU-kill\n * ceiling) the compactor never stamps `tail_hint` via its Step-7 fold\n * CAS, so the gap `(true_tail − tail_hint)` would grow without bound and\n * every read would re-walk the whole live tail via `probeTailFrom`. The\n * runner therefore advances `tail_hint` toward the observed tail with a\n * best-effort `current.json` CAS — but only once per this many writes,\n * so it is NOT a per-commit `current.json` write (which is exactly what\n * single-write commit removed).\n *\n * Sized at 128: it bounds a deferring collection's worst-case\n * read-walk to ≤128 forward GETs (≈one extra read-page sweep — a\n * negligible per-read latency cost), keeps the gap two-to-three orders\n * of magnitude below {@link LOG_FORWARD_PROBE_CAP} (so the cap-throw is a\n * pure runaway guard, never reached in normal operation), and holds the\n * hint-advance CAS rate under ~1% of the commit rate (negligible\n * Class-A cost, amortized). Smaller would tighten the read-walk at a\n * higher CAS rate; larger would loosen it — 128 is the modest middle.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TAIL_HINT_REFRESH_WRITES: number = 128;\n\n/**\n * Stable seed for `CurrentJson.snapshot === null` when building the\n * opaque `_meta.manifest_pointer` cursor emitted on read responses.\n * The literal no longer appears by itself on the wire; it is folded\n * into the server-side digest so the cursor never exposes physical\n * snapshot keys.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Two Class A ops: PUT content + the committing `log/<seq>` create\n * (`If-None-Match: \"*\"`). There is no `current.json` CAS on the commit\n * path — the winning log create IS the commit. The cost-model page\n * derives the free-tier write budget from this multiplier; the\n * maintenance end-to-end test asserts it at CI time. Changing this constant is a\n * cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/maintenance-e2e.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 2;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","// Deployment detection shared by the in-memory storage guard and the\n// Node resolveStorageFromEnv resolver. Pure (env passed in) so it stays\n// Workerd-loadable. Markers are vars each platform sets unconditionally:\n// Cloud Run, Heroku, Kubernetes, ECS, Railway, Render, Fly.\n//\n// The list is deliberately conservative: every marker here is set ONLY by\n// the platform at runtime, never by that platform's local dev emulator, so\n// detection cannot false-positive a developer's machine. Serverless markers\n// like VERCEL / NETLIFY / AWS_LAMBDA_FUNCTION_NAME are intentionally omitted\n// — their local emulators (`vercel dev`, `netlify dev`, SAM local) set the\n// same vars, so adding them would break local development. Before adding a\n// marker, confirm it is never set by that platform's dev tooling. An\n// unmarked host should set NODE_ENV=production to opt into the guard.\nexport const PAAS_MARKERS = [\n \"RAILWAY_ENVIRONMENT\",\n \"RENDER\",\n \"FLY_APP_NAME\",\n \"K_SERVICE\",\n \"DYNO\",\n \"KUBERNETES_SERVICE_HOST\",\n \"ECS_CONTAINER_METADATA_URI_V4\",\n] as const;\n\n/**\n * True when `env` looks like a deployed environment: `NODE_ENV=production`\n * or any {@link PAAS_MARKERS} set to a non-empty value. Decides whether a\n * non-durable store (in-memory, local-fs) should fail loud instead of\n * silently serving a production workload. A CI runner (`CI` set to a\n * non-empty, non-`false` value) is never treated as deployed, so PaaS\n * markers from an in-cluster CI agent do not trip it.\n */\nexport const isDeployedEnv = (env: Record<string, string | undefined>): boolean => {\n // A CI runner is never a deployment — even in a k8s pod that sets a PaaS\n // marker (e.g. KUBERNETES_SERVICE_HOST) — so it must not trip the markers.\n const inCi = (env[\"CI\"] ?? \"\") !== \"\" && env[\"CI\"] !== \"false\";\n return (\n env[\"NODE_ENV\"] === \"production\" || (!inCi && PAAS_MARKERS.some((m) => (env[m] ?? \"\") !== \"\"))\n );\n};\n","import { BaerlyError } from \"../errors.ts\";\n\n/**\n * Validate a raw {@link Storage} object key against the portable baerly key\n * grammar before it is used to address an object. A key MUST be non-empty\n * and `/`-delimited, with **no path segment equal to `.` or `..`**.\n *\n * The dot-segment rule is not a vendor quirk — it is a *client-side*\n * universal: RFC 3986 §5.2.4 \"remove dot segments\" is mandatory for every\n * conformant URL parser, so `<endpoint>/<bucket>/.` normalizes to\n * `<endpoint>/<bucket>/` and `<endpoint>/<bucket>/..` escapes the bucket\n * entirely — *before* the request is signed or sent, in TypeScript, Go,\n * Rust, Python, or any language a `Storage` port is written in. Such a key\n * cannot be addressed over the S3/R2 HTTP API regardless of backend; a bare\n * `.` PUT surfaces as a confusing bucket-root 403 rather than a clear\n * rejection. The kernel never emits such keys (caller-controlled segments\n * are already screened by `assertPathSegment` one layer up), so this is the\n * boundary guard that makes every adapter reject them *identically* and\n * gives ports a single, testable contract.\n *\n * Thrown as `BaerlyError{code:\"InvalidConfig\"}` to match the sibling\n * key/segment guards (`assertKeyWithinLimit`, `assertPathSegment`). The\n * full-key 1024-byte ceiling is enforced separately on the write path\n * (`assertKeyWithinLimit`), where multi-segment keys are assembled.\n *\n * @see docs/spec/storage-compatibility.md — \"Key namespace\"\n */\nexport function assertValidStorageKey(key: string): void {\n if (key.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"storage key must be a non-empty string\");\n }\n for (const segment of key.split(\"/\")) {\n if (segment === \".\" || segment === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `storage key may not contain a \".\" or \"..\" path segment — RFC 3986 dot-segment ` +\n `removal makes it unaddressable over the S3/R2 HTTP API: ${JSON.stringify(key)}`,\n );\n }\n }\n}\n","import { isDeployedEnv } from \"../env.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport { assertValidStorageKey } from \"./key.ts\";\nimport type {\n Storage,\n StorageGetOptions,\n StorageGetResult,\n StorageListEntry,\n StoragePutOptions,\n StoragePutResult,\n} from \"./types.ts\";\n\ninterface StoredObject {\n body: Uint8Array;\n etag: string;\n contentType?: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\nconst EPHEMERAL_ENV_OPT_IN = \"BAERLY_ALLOW_EPHEMERAL_STORAGE\";\n\n// Read process env without a `node:` import so protocol stays Workerd-\n// loadable (on Workerd `process` is absent → env is `{}` → not deployed).\nconst readProcessEnv = (): Record<string, string | undefined> =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n\nlet warnedEphemeralInDeployment = false;\n\n// Fail closed when in-memory storage would silently back a deployed\n// workload (writes \"succeed\" into RAM, vanish on restart). No-op in\n// dev/test; bypass in a deployment only via an explicit acknowledgement.\nconst assertEphemeralAllowed = (explicitOptIn: boolean): void => {\n const env = readProcessEnv();\n if (!isDeployedEnv(env)) {\n return;\n }\n if (!explicitOptIn && env[EPHEMERAL_ENV_OPT_IN] !== \"true\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"Refusing to use in-memory storage in a deployed environment — all data is lost on restart. \" +\n \"MemoryStorage is for tests/local dev only; configure a durable bucket (AWS S3 / Cloudflare R2). \" +\n `To intentionally opt in: new MemoryStorage({ ephemeral: true }) or ${EPHEMERAL_ENV_OPT_IN}=true.`,\n );\n }\n if (!warnedEphemeralInDeployment) {\n warnedEphemeralInDeployment = true;\n console.warn(\n \"[baerly] in-memory storage in a deployed environment — ALL DATA IS LOST ON RESTART.\",\n );\n }\n};\n\n/** Options for {@link MemoryStorage}. */\nexport interface MemoryStorageOptions {\n /**\n * Acknowledge the store is intentionally ephemeral — required to\n * construct in a detected deployment ({@link isDeployedEnv}); ignored in\n * dev/test. Env equivalent: `BAERLY_ALLOW_EPHEMERAL_STORAGE=true`.\n */\n ephemeral?: boolean;\n}\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and\n * R2 use for `list`. JavaScript's default string sort compares UTF-16\n * code units, which diverges from UTF-8 byte order for supplementary-\n * plane characters (e.g. emoji sort before high-BMP characters under\n * UTF-16 but after them in UTF-8). Using this keeps the in-memory\n * reference backend faithful to the real adapters. (All kernel keys\n * are ASCII base-32, where the two orders coincide — this only\n * matters for adversarial / non-ASCII keys.)\n */\nconst compareKeysUtf8 = (a: string, b: string): number => {\n const ba = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ba.length, bb.length);\n for (let i = 0; i < n; i++) {\n if (ba[i] !== bb[i]) {\n return ba[i]! - bb[i]!;\n }\n }\n return ba.length - bb.length;\n};\n\n/**\n * In-memory `Storage`. The randomized property test runs against\n * this; it must be deterministic — no clocks beyond the caller's,\n * no randomness, no I/O.\n *\n * ETags are a monotonically increasing hex counter formatted in the\n * `\"<hex>\"` shape S3 returns (the surrounding double-quotes are part\n * of the ETag header value). Keys are stored verbatim.\n *\n * **Test-confidence caveat:** every method resolves on the microtask\n * queue with no real concurrency, so `put` reads `existing` and writes\n * back with no interleaving. MemoryStorage therefore CANNOT exercise the\n * compare-and-swap race the writer-fence model depends on — two writers\n * contending on one `current.json` always serialize here, so a green run\n * is necessary but not sufficient. That race is covered only by the\n * randomized integration tests against real S3 / Minio\n * (`tests/integration/randomized.test.ts`, `node-minio` variant).\n * Relatedly, `serverDate` returns the local clock, not an independent\n * server clock (see the `put` return below).\n */\nexport class MemoryStorage implements Storage {\n readonly #objects = new Map<string, StoredObject>();\n #etagCounter = 0;\n\n constructor(opts?: MemoryStorageOptions) {\n assertEphemeralAllowed(opts?.ephemeral === true);\n }\n\n #nextEtag(): string {\n this.#etagCounter += 1;\n return `\"${this.#etagCounter.toString(16)}\"`;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n return null;\n }\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === stored.etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: stored.body, etag: stored.etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const existing = this.#objects.get(key);\n\n if (opts?.ifNoneMatch === \"*\" && existing !== undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (existing.etag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`,\n );\n }\n }\n\n const etag = this.#nextEtag();\n this.#objects.set(key, {\n body,\n etag,\n // Stryker disable next-line ObjectLiteral,ConditionalExpression: contentType is stored in the internal StoredObject but never returned by get() — the Storage interface has no contentType on StorageGetResult, so any mutation of this spread is observable-equivalent\n ...(opts?.contentType !== undefined && { contentType: opts.contentType }),\n });\n // `serverDate` is intentionally returned — the kernel's adaptive\n // clock-skew loop consumes the write-time server clock. `list()`\n // deliberately omits `lastModified`: the in-memory impl has no\n // independent server clock, and its only consumer (GC's `due_at`\n // anchor) falls back to `now()` when it is absent, so omitting it\n // changes nothing.\n return { etag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n this.#objects.delete(key);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const sorted = [...this.#objects.keys()]\n .filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0)\n .toSorted(compareKeysUtf8);\n let yielded = 0;\n for (const key of sorted) {\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n // Stryker disable next-line ConditionalExpression,BlockStatement: unreachable guard — keys come from Map.keys() so the corresponding value is always present; this branch exists only to satisfy noUncheckedIndexedAccess\n if (stored === undefined) {\n continue;\n }\n yield { key, etag: stored.etag };\n yielded += 1;\n }\n }\n\n /**\n * Test-only: drop all objects.\n * @internal\n */\n _clear(): void {\n this.#objects.clear();\n this.#etagCounter = 0;\n }\n}\n\n// Process-singleton MemoryStorage map keyed by bucket. Tests that need\n// multiple `Db` / `Writer` instances to see each other's writes\n// against an in-memory backend reach for this via\n// {@link getOrCreateMemoryStorageForBucket}; {@link resetMemoryStorage}\n// drops every bucket between test cases.\nconst sharedPerBucket = new Map<string, MemoryStorage>();\n\n/**\n * Test isolation: drop every bucket's contents from the shared\n * memory storage used by {@link getOrCreateMemoryStorageForBucket}.\n * Direct `MemoryStorage` instances built via `new MemoryStorage()`\n * are unaffected — those are isolated by construction.\n */\nexport const resetMemoryStorage = (): void => {\n sharedPerBucket.clear();\n};\n\n/**\n * Get the process-singleton {@link MemoryStorage} for the named\n * bucket, creating one on first access. Use this when constructing\n * a `Storage` directly so multiple consumers in the same process\n * see each other's writes for the same bucket name.\n */\nexport const getOrCreateMemoryStorageForBucket = (bucket: string): MemoryStorage => {\n let s = sharedPerBucket.get(bucket);\n if (s === undefined) {\n s = new MemoryStorage();\n sharedPerBucket.set(bucket, s);\n }\n return s;\n};\n","import { COUNT_BIT_WIDTH } from \"./constants.ts\";\n\ndeclare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. content versions are both strings, but\n * using the wrong one corrupts the per-collection log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A v4 UUID minted by this client. Used as session IDs and content\n * identifiers in non-versioned mode.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * SHA-256 content digest, lowercase hex truncated to\n * `VERSION_HEX_LENGTH` (32 chars). Minted by\n * `versionFromContent` in `useVersioning=false` mode and used as\n * the `<key>@<version>` suffix in content keys.\n *\n * The synthetic `local-${op}` placeholder used for in-flight\n * optimistic updates also wears this brand — it never round-trips\n * to S3, only flows through local optimistic state.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\n\n/**\n * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,\n * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.\n * Lex-sortable by mint time, so it pairs well with object-storage\n * list semantics. Returns a branded {@link UUID}.\n *\n * Uses `crypto.getRandomValues` which is universally available\n * (Node 19+, Workerd, Bun, browsers).\n *\n * @example\n * ```ts\n * const id = uuidv7();\n * // e.g. \"01956cad-4cc8-7abc-9def-0123456789ab\"\n * ```\n */\nexport const uuidv7 = (): UUID => {\n const millis = Date.now();\n const rand = new Uint8Array(10);\n crypto.getRandomValues(rand);\n // Version nibble: top 4 bits of rand[0] = 0b0111 (v7). The byte\n // sits at the start of the \"version-and-rand-a\" group below.\n rand[0] = (rand[0]! & 0x0f) | 0x70;\n // Variant bits: top 2 bits of rand[2] = 0b10 (RFC 4122 variant).\n // This byte starts the \"variant-and-rand-b\" group below.\n rand[2] = (rand[2]! & 0x3f) | 0x80;\n const millisHex = millis.toString(16).padStart(12, \"0\");\n const b = Array.from(rand, (n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}` as UUID;\n};\n\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to\n * produce an 11-char descending base-32 string with a domain of\n * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, COUNT_BIT_WIDTH);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"LSNs, wall clocks, and downstream\n * consumers\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\n/**\n * Encode an epoch-millis instant as a lexicographically-DEScending\n * base-32 key (newer sorts first). The load-bearing LSN ordering\n * primitive — see {@link uint2strDesc}.\n *\n * `epoch` is REQUIRED and validated. There is no default: an argless\n * call used to encode `0`, which descending-sorts as the most-ancient\n * instant and would silently invert ordering. A non-finite, negative,\n * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)\n * would corrupt the key silently rather than fail loud, so it throws\n * `Internal` instead — this is an invariant violation, not caller config\n * (the only legitimate argument is `Date.now()`).\n */\nexport const timestamp = (epoch: number): string => {\n if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** TIMESTAMP_BIT_WIDTH) {\n throw new BaerlyError(\n \"Internal\",\n `timestamp(): epoch must be a non-negative integer < 2^${TIMESTAMP_BIT_WIDTH} (got ${epoch})`,\n );\n }\n return uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n};\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry\n * loop so shutdown can interrupt an in-flight backoff instead of\n * waiting for it to complete.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n // Stryker disable next-line BooleanLiteral,ObjectLiteral: `{ once: true }` removes the\n // listener after the first fire. AbortController fires `abort` only once per signal, so\n // `once: false` / `{}` produce identical observable behaviour — the listener stays attached\n // to an already-fired signal, but calling reject on a settled Promise is a no-op. The\n // BooleanLiteral (once:false) and ObjectLiteral ({}) mutations are genuine equivalences.\n { once: true },\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 assertValidStorageKey,\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 // Shared Storage key grammar (non-empty, no `.`/`..` segments); the\n // FS-specific guards below add traversal/backslash/empty-segment checks.\n assertValidStorageKey(key);\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","/*! @rgrove/parse-xml v4.2.1 | ISC License | Copyright Ryan Grove */\n\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\n\n// src/index.ts\nvar src_exports = {};\n__export(src_exports, {\n XmlCdata: () => XmlCdata,\n XmlComment: () => XmlComment,\n XmlDeclaration: () => XmlDeclaration,\n XmlDocument: () => XmlDocument,\n XmlDocumentType: () => XmlDocumentType,\n XmlElement: () => XmlElement,\n XmlError: () => XmlError,\n XmlNode: () => XmlNode,\n XmlProcessingInstruction: () => XmlProcessingInstruction,\n XmlText: () => XmlText,\n parseXml: () => parseXml\n});\nmodule.exports = __toCommonJS(src_exports);\n\n// src/lib/StringScanner.ts\nvar emptyString = \"\";\nvar surrogatePair = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\nvar StringScanner = class {\n constructor(string) {\n this.k = this.u(string, true);\n this.d = 0;\n this.length = string.length;\n this.l = this.k !== this.length;\n this.h = string;\n if (this.l) {\n let charsToBytes = [];\n for (let byteIndex = 0, charIndex = 0; charIndex < this.k; ++charIndex) {\n charsToBytes[charIndex] = byteIndex;\n byteIndex += string.codePointAt(byteIndex) > 65535 ? 2 : 1;\n }\n this.A = charsToBytes;\n }\n }\n /**\n * Whether the current character index is at the end of the input string.\n */\n get B() {\n return this.d >= this.k;\n }\n // -- Protected Methods ------------------------------------------------------\n /**\n * Returns the number of characters in the given string, which may differ from\n * the byte length if the string contains multibyte characters.\n */\n u(string, multiByteSafe = this.l) {\n return multiByteSafe ? string.replace(surrogatePair, \"_\").length : string.length;\n }\n // -- Public Methods ---------------------------------------------------------\n /**\n * Advances the scanner by the given number of characters, stopping if the end\n * of the string is reached.\n */\n p(count = 1) {\n this.d = Math.min(this.k, this.d + count);\n }\n /**\n * Returns the byte index of the given character index in the string. The two\n * may differ in strings that contain multibyte characters.\n */\n f(charIndex = this.d) {\n var _a;\n return this.l ? (_a = this.A[charIndex]) != null ? _a : Infinity : charIndex;\n }\n /**\n * Consumes and returns the given number of characters if possible, advancing\n * the scanner and stopping if the end of the string is reached.\n *\n * If no characters could be consumed, an empty string will be returned.\n */\n G(charCount = 1) {\n let chars = this.m(charCount);\n this.p(charCount);\n return chars;\n }\n /**\n * Consumes and returns the given number of bytes if possible, advancing the\n * scanner and stopping if the end of the string is reached.\n *\n * It's up to the caller to ensure that the given byte count doesn't split a\n * multibyte character.\n *\n * If no bytes could be consumed, an empty string will be returned.\n */\n v(byteCount) {\n let byteIndex = this.f();\n let result = this.h.slice(byteIndex, byteIndex + byteCount);\n this.p(this.u(result));\n return result;\n }\n /**\n * Consumes and returns all characters for which the given function returns\n * `true`, stopping when `false` is returned or the end of the input is\n * reached.\n */\n w(fn) {\n let { length, l: multiByteMode, h: string } = this;\n let startByteIndex = this.f();\n let endByteIndex = startByteIndex;\n if (multiByteMode) {\n while (endByteIndex < length) {\n let char = string[endByteIndex];\n let isSurrogatePair = char >= \"\\uD800\" && char <= \"\\uDBFF\";\n if (isSurrogatePair) {\n char += string[endByteIndex + 1];\n }\n if (!fn(char)) {\n break;\n }\n endByteIndex += isSurrogatePair ? 2 : 1;\n }\n } else {\n while (endByteIndex < length && fn(string[endByteIndex])) {\n ++endByteIndex;\n }\n }\n return this.v(endByteIndex - startByteIndex);\n }\n /**\n * Consumes the given string if it exists at the current character index, and\n * advances the scanner.\n *\n * If the given string doesn't exist at the current character index, an empty\n * string will be returned and the scanner will not be advanced.\n */\n b(stringToConsume) {\n let { length } = stringToConsume;\n let byteIndex = this.f();\n if (stringToConsume === this.h.slice(byteIndex, byteIndex + length)) {\n this.p(length === 1 ? 1 : this.u(stringToConsume));\n return stringToConsume;\n }\n return emptyString;\n }\n /**\n * Consumes characters until the given global regex is matched, advancing the\n * scanner up to (but not beyond) the beginning of the match. If the regex\n * doesn't match, nothing will be consumed.\n *\n * Returns the consumed string, or an empty string if nothing was consumed.\n */\n x(regex) {\n let matchByteIndex = this.h.slice(this.f()).search(regex);\n return matchByteIndex > 0 ? this.v(matchByteIndex) : emptyString;\n }\n /**\n * Consumes characters until the given string is found, advancing the scanner\n * up to (but not beyond) that point. If the string is never found, nothing\n * will be consumed.\n *\n * Returns the consumed string, or an empty string if nothing was consumed.\n */\n s(searchString) {\n let byteIndex = this.f();\n let matchByteIndex = this.h.indexOf(searchString, byteIndex);\n return matchByteIndex > 0 ? this.v(matchByteIndex - byteIndex) : emptyString;\n }\n /**\n * Returns the given number of characters starting at the current character\n * index, without advancing the scanner and without exceeding the end of the\n * input string.\n */\n m(count = 1) {\n let { d: charIndex, h: string } = this;\n return this.l ? string.slice(this.f(charIndex), this.f(charIndex + count)) : string.slice(charIndex, charIndex + count);\n }\n /**\n * Resets the scanner position to the given character _index_, or to the start\n * of the input string if no index is given.\n *\n * If _index_ is negative, the scanner position will be moved backward by that\n * many characters, stopping if the beginning of the string is reached.\n */\n n(index = 0) {\n this.d = index >= 0 ? Math.min(this.k, index) : Math.max(0, this.d + index);\n }\n};\n\n// src/lib/syntax.ts\nvar attValueCharDoubleQuote = /[\"&<]/;\nvar attValueCharSingleQuote = /['&<]/;\nvar attValueNormalizedWhitespace = /\\r\\n|[\\n\\r\\t]/g;\nvar endCharData = /<|&|]]>/;\nvar predefinedEntities = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), {\n amp: \"&\",\n apos: \"'\",\n gt: \">\",\n lt: \"<\",\n quot: '\"'\n}));\nfunction isNameChar(char) {\n let cp = char.codePointAt(0);\n return cp >= 97 && cp <= 122 || cp >= 65 && cp <= 90 || cp >= 48 && cp <= 57 || cp === 45 || cp === 46 || cp === 183 || cp >= 768 && cp <= 879 || cp === 8255 || cp === 8256 || isNameStartChar(char, cp);\n}\nfunction isNameStartChar(char, cp = char.codePointAt(0)) {\n return cp >= 97 && cp <= 122 || cp >= 65 && cp <= 90 || cp === 58 || cp === 95 || cp >= 192 && cp <= 214 || cp >= 216 && cp <= 246 || cp >= 248 && cp <= 767 || cp >= 880 && cp <= 893 || cp >= 895 && cp <= 8191 || cp === 8204 || cp === 8205 || cp >= 8304 && cp <= 8591 || cp >= 11264 && cp <= 12271 || cp >= 12289 && cp <= 55295 || cp >= 63744 && cp <= 64975 || cp >= 65008 && cp <= 65533 || cp >= 65536 && cp <= 983039;\n}\nfunction isReferenceChar(char) {\n return char === \"#\" || isNameChar(char);\n}\nfunction isWhitespace(char) {\n let cp = char.codePointAt(0);\n return cp === 32 || cp === 9 || cp === 10 || cp === 13;\n}\nfunction isXmlCodePoint(cp) {\n return cp >= 32 && cp <= 55295 || cp === 10 || cp === 9 || cp === 13 || cp >= 57344 && cp <= 65533 || cp >= 65536 && cp <= 1114111;\n}\n\n// src/lib/XmlNode.ts\nvar _XmlNode = class _XmlNode {\n constructor() {\n /**\n * Parent node of this node, or `null` if this node has no parent.\n */\n this.parent = null;\n /**\n * Starting byte offset of this node in the original XML string, or `-1` if\n * the offset is unknown.\n */\n this.start = -1;\n /**\n * Ending byte offset of this node in the original XML string, or `-1` if the\n * offset is unknown.\n */\n this.end = -1;\n }\n /**\n * Document that contains this node, or `null` if this node is not associated\n * with a document.\n */\n get document() {\n var _a, _b;\n return (_b = (_a = this.parent) == null ? void 0 : _a.document) != null ? _b : null;\n }\n /**\n * Whether this node is the root node of the document (also known as the\n * document element).\n */\n get isRootNode() {\n return this.parent !== null && this.parent === this.document && this.type === _XmlNode.TYPE_ELEMENT;\n }\n /**\n * Whether whitespace should be preserved in the content of this element and\n * its children.\n *\n * This is influenced by the value of the special `xml:space` attribute, and\n * will be `true` for any node whose `xml:space` attribute is set to\n * \"preserve\". If a node has no such attribute, it will inherit the value of\n * the nearest ancestor that does (if any).\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-white-space\n */\n get preserveWhitespace() {\n var _a;\n return !!((_a = this.parent) == null ? void 0 : _a.preserveWhitespace);\n }\n /**\n * Type of this node.\n *\n * The value of this property is a string that matches one of the static\n * `TYPE_*` properties on the `XmlNode` class (e.g. `TYPE_ELEMENT`,\n * `TYPE_TEXT`, etc.).\n *\n * The `XmlNode` class itself is a base class and doesn't have its own type\n * name.\n */\n get type() {\n return \"\";\n }\n /**\n * Returns a JSON-serializable object representing this node, minus properties\n * that could result in circular references.\n */\n toJSON() {\n let json = {\n type: this.type\n };\n if (this.isRootNode) {\n json.isRootNode = true;\n }\n if (this.preserveWhitespace) {\n json.preserveWhitespace = true;\n }\n if (this.start !== -1) {\n json.start = this.start;\n json.end = this.end;\n }\n return json;\n }\n};\n/**\n * Type value for an `XmlCdata` node.\n */\n_XmlNode.TYPE_CDATA = \"cdata\";\n/**\n * Type value for an `XmlComment` node.\n */\n_XmlNode.TYPE_COMMENT = \"comment\";\n/**\n * Type value for an `XmlDocument` node.\n */\n_XmlNode.TYPE_DOCUMENT = \"document\";\n/**\n * Type value for an `XmlDocumentType` node.\n */\n_XmlNode.TYPE_DOCUMENT_TYPE = \"doctype\";\n/**\n * Type value for an `XmlElement` node.\n */\n_XmlNode.TYPE_ELEMENT = \"element\";\n/**\n * Type value for an `XmlProcessingInstruction` node.\n */\n_XmlNode.TYPE_PROCESSING_INSTRUCTION = \"pi\";\n/**\n * Type value for an `XmlText` node.\n */\n_XmlNode.TYPE_TEXT = \"text\";\n/**\n * Type value for an `XmlDeclaration` node.\n */\n_XmlNode.TYPE_XML_DECLARATION = \"xmldecl\";\nvar XmlNode = _XmlNode;\n\n// src/lib/XmlText.ts\nvar XmlText = class extends XmlNode {\n constructor(text = \"\") {\n super();\n this.text = text;\n }\n get type() {\n return XmlNode.TYPE_TEXT;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n text: this.text\n });\n }\n};\n\n// src/lib/XmlCdata.ts\nvar XmlCdata = class extends XmlText {\n get type() {\n return XmlNode.TYPE_CDATA;\n }\n};\n\n// src/lib/XmlComment.ts\nvar XmlComment = class extends XmlNode {\n constructor(content = \"\") {\n super();\n this.content = content;\n }\n get type() {\n return XmlNode.TYPE_COMMENT;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n content: this.content\n });\n }\n};\n\n// src/lib/XmlDeclaration.ts\nvar XmlDeclaration = class extends XmlNode {\n constructor(version, encoding, standalone) {\n super();\n this.version = version;\n this.encoding = encoding != null ? encoding : null;\n this.standalone = standalone != null ? standalone : null;\n }\n get type() {\n return XmlNode.TYPE_XML_DECLARATION;\n }\n toJSON() {\n let json = XmlNode.prototype.toJSON.call(this);\n json.version = this.version;\n for (let key of [\"encoding\", \"standalone\"]) {\n if (this[key] !== null) {\n json[key] = this[key];\n }\n }\n return json;\n }\n};\n\n// src/lib/XmlElement.ts\nvar XmlElement = class _XmlElement extends XmlNode {\n constructor(name, attributes = /* @__PURE__ */ Object.create(null), children = []) {\n super();\n this.name = name;\n this.attributes = attributes;\n this.children = children;\n }\n /**\n * Whether this element is empty (meaning it has no children).\n */\n get isEmpty() {\n return this.children.length === 0;\n }\n get preserveWhitespace() {\n let node = this;\n while (node instanceof _XmlElement) {\n if (\"xml:space\" in node.attributes) {\n return node.attributes[\"xml:space\"] === \"preserve\";\n }\n node = node.parent;\n }\n return false;\n }\n /**\n * Text content of this element and all its descendants.\n */\n get text() {\n return this.children.map((child) => \"text\" in child ? child.text : \"\").join(\"\");\n }\n get type() {\n return XmlNode.TYPE_ELEMENT;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n name: this.name,\n attributes: this.attributes,\n children: this.children.map((child) => child.toJSON())\n });\n }\n};\n\n// src/lib/XmlDocument.ts\nvar XmlDocument = class extends XmlNode {\n constructor(children = []) {\n super();\n this.children = children;\n }\n get document() {\n return this;\n }\n /**\n * Root element of this document, or `null` if this document is empty.\n */\n get root() {\n for (let child of this.children) {\n if (child instanceof XmlElement) {\n return child;\n }\n }\n return null;\n }\n /**\n * Text content of this document and all its descendants.\n */\n get text() {\n return this.children.map((child) => \"text\" in child ? child.text : \"\").join(\"\");\n }\n get type() {\n return XmlNode.TYPE_DOCUMENT;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n children: this.children.map((child) => child.toJSON())\n });\n }\n};\n\n// src/lib/XmlDocumentType.ts\nvar XmlDocumentType = class extends XmlNode {\n constructor(name, publicId, systemId, internalSubset) {\n super();\n this.name = name;\n this.publicId = publicId != null ? publicId : null;\n this.systemId = systemId != null ? systemId : null;\n this.internalSubset = internalSubset != null ? internalSubset : null;\n }\n get type() {\n return XmlNode.TYPE_DOCUMENT_TYPE;\n }\n toJSON() {\n let json = XmlNode.prototype.toJSON.call(this);\n json.name = this.name;\n for (let key of [\"publicId\", \"systemId\", \"internalSubset\"]) {\n if (this[key] !== null) {\n json[key] = this[key];\n }\n }\n return json;\n }\n};\n\n// src/lib/XmlError.ts\nvar XmlError = class extends Error {\n constructor(message, charIndex, xml) {\n let column = 1;\n let excerpt = \"\";\n let line = 1;\n for (let i = 0; i < charIndex; ++i) {\n let char = xml[i];\n if (char === \"\\n\") {\n column = 1;\n excerpt = \"\";\n line += 1;\n } else {\n column += 1;\n excerpt += char;\n }\n }\n let eol = xml.indexOf(\"\\n\", charIndex);\n excerpt += eol === -1 ? xml.slice(charIndex) : xml.slice(charIndex, eol);\n let excerptStart = 0;\n if (excerpt.length > 50) {\n if (column < 40) {\n excerpt = excerpt.slice(0, 50);\n } else {\n excerptStart = column - 20;\n excerpt = excerpt.slice(excerptStart, column + 30);\n }\n }\n super(\n `${message} (line ${line}, column ${column})\n ${excerpt}\n` + \" \".repeat(column - excerptStart + 1) + \"^\\n\"\n );\n this.column = column;\n this.excerpt = excerpt;\n this.line = line;\n this.name = \"XmlError\";\n this.pos = charIndex;\n }\n};\n\n// src/lib/XmlProcessingInstruction.ts\nvar XmlProcessingInstruction = class extends XmlNode {\n constructor(name, content = \"\") {\n super();\n this.name = name;\n this.content = content;\n }\n get type() {\n return XmlNode.TYPE_PROCESSING_INSTRUCTION;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n name: this.name,\n content: this.content\n });\n }\n};\n\n// src/lib/Parser.ts\nvar emptyString2 = \"\";\nvar Parser = class {\n /**\n * @param xml XML string to parse.\n * @param options Parser options.\n */\n constructor(xml, options = {}) {\n let doc = this.document = new XmlDocument();\n this.j = doc;\n this.g = options;\n this.c = new StringScanner(xml);\n if (this.g.includeOffsets) {\n doc.start = 0;\n doc.end = xml.length;\n }\n this.parse();\n }\n /**\n * Adds the given `XmlNode` as a child of `this.currentNode`.\n */\n i(node, charIndex) {\n node.parent = this.j;\n if (this.g.includeOffsets) {\n node.start = this.c.f(charIndex);\n node.end = this.c.f();\n }\n this.j.children.push(node);\n return true;\n }\n /**\n * Adds the given _text_ to the document, either by appending it to a\n * preceding `XmlText` node (if possible) or by creating a new `XmlText` node.\n *\n * When _normalize_ is `true` (the default), line breaks in _text_ are\n * normalized per section 2.11 of the XML spec. This must be `false` for text\n * that comes from a character or entity reference, since references aren't\n * subject to line break normalization.\n */\n y(text, charIndex, normalize = true) {\n let { children } = this.j;\n let { length } = children;\n if (normalize) {\n text = normalizeLineBreaks(text);\n }\n if (length > 0) {\n let prevNode = children[length - 1];\n if ((prevNode == null ? void 0 : prevNode.type) === XmlNode.TYPE_TEXT) {\n let textNode = prevNode;\n textNode.text += text;\n if (this.g.includeOffsets) {\n textNode.end = this.c.f();\n }\n return true;\n }\n }\n return this.i(new XmlText(text), charIndex);\n }\n /**\n * Consumes element attributes.\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-starttags\n */\n H() {\n let attributes = /* @__PURE__ */ Object.create(null);\n while (this.e()) {\n let attrName = this.q();\n if (!attrName) {\n break;\n }\n let attrValue = this.t() && this.I();\n if (attrValue === false) {\n throw this.a(\"Attribute value expected\");\n }\n if (attrName in attributes) {\n throw this.a(`Duplicate attribute: ${attrName}`);\n }\n if (attrName === \"xml:space\" && attrValue !== \"default\" && attrValue !== \"preserve\") {\n throw this.a('Value of the `xml:space` attribute must be \"default\" or \"preserve\"');\n }\n attributes[attrName] = attrValue;\n }\n if (this.g.sortAttributes) {\n let attrNames = Object.keys(attributes).sort();\n let sortedAttributes = /* @__PURE__ */ Object.create(null);\n for (let i = 0; i < attrNames.length; ++i) {\n let attrName = attrNames[i];\n sortedAttributes[attrName] = attributes[attrName];\n }\n attributes = sortedAttributes;\n }\n return attributes;\n }\n /**\n * Consumes an `AttValue` (attribute value) if possible.\n *\n * @returns\n * Contents of the `AttValue` minus quotes, or `false` if nothing was\n * consumed. An empty string indicates that an `AttValue` was consumed but\n * was empty.\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-AttValue\n */\n I() {\n let { c: scanner } = this;\n let quote = scanner.m();\n if (quote !== '\"' && quote !== \"'\") {\n return false;\n }\n scanner.p();\n let chars;\n let isClosed = false;\n let value = emptyString2;\n let regex = quote === '\"' ? attValueCharDoubleQuote : attValueCharSingleQuote;\n matchLoop: while (!scanner.B) {\n chars = scanner.x(regex);\n if (chars) {\n this.o(chars);\n value += chars.replace(attValueNormalizedWhitespace, \" \");\n }\n switch (scanner.m()) {\n case quote:\n isClosed = true;\n break matchLoop;\n case \"&\":\n value += this.C();\n continue;\n case \"<\":\n throw this.a(\"Unescaped `<` is not allowed in an attribute value\");\n default:\n break matchLoop;\n }\n }\n if (!isClosed) {\n throw this.a(\"Unclosed attribute\");\n }\n scanner.p();\n return value;\n }\n /**\n * Consumes a CDATA section if possible.\n *\n * @returns Whether a CDATA section was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-cdata-sect\n */\n J() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<![CDATA[\")) {\n return false;\n }\n let text = scanner.s(\"]]>\");\n this.o(text);\n if (!scanner.b(\"]]>\")) {\n throw this.a(\"Unclosed CDATA section\");\n }\n return this.g.preserveCdata ? this.i(new XmlCdata(normalizeLineBreaks(text)), startIndex) : this.y(text, startIndex);\n }\n /**\n * Consumes character data if possible.\n *\n * @returns Whether character data was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#dt-chardata\n */\n K() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n let charData = scanner.x(endCharData);\n if (!charData) {\n return false;\n }\n this.o(charData);\n if (scanner.m(3) === \"]]>\") {\n throw this.a(\"Element content may not contain the CDATA section close delimiter `]]>`\");\n }\n return this.y(charData, startIndex);\n }\n /**\n * Consumes a comment if possible.\n *\n * @returns Whether a comment was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Comment\n */\n D() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<!--\")) {\n return false;\n }\n let content = scanner.s(\"--\");\n this.o(content);\n if (!scanner.b(\"-->\")) {\n if (scanner.m(2) === \"--\") {\n throw this.a(\"The string `--` isn't allowed inside a comment\");\n }\n throw this.a(\"Unclosed comment\");\n }\n return this.g.preserveComments ? this.i(new XmlComment(normalizeLineBreaks(content)), startIndex) : true;\n }\n /**\n * Consumes a reference in a content context if possible.\n *\n * This differs from `consumeReference()` in that a consumed reference will be\n * added to the document as a text node instead of returned.\n *\n * @returns Whether a reference was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#entproc\n */\n L() {\n let startIndex = this.c.d;\n let ref = this.C();\n return ref ? this.y(ref, startIndex, false) : false;\n }\n /**\n * Consumes a doctype declaration if possible.\n *\n * This is a loose implementation since doctype declarations are currently\n * discarded without further parsing.\n *\n * @returns Whether a doctype declaration was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#dtd\n */\n M() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<!DOCTYPE\")) {\n return false;\n }\n let name = this.e() && this.q();\n if (!name) {\n throw this.a(\"Expected a name\");\n }\n let publicId;\n let systemId;\n if (this.e()) {\n if (scanner.b(\"PUBLIC\")) {\n publicId = this.e() && this.N();\n if (publicId === false) {\n throw this.a(\"Expected a public identifier\");\n }\n this.e();\n }\n if (publicId !== void 0 || scanner.b(\"SYSTEM\")) {\n this.e();\n systemId = this.r();\n if (systemId === false) {\n throw this.a(\"Expected a system identifier\");\n }\n this.e();\n }\n }\n let internalSubset;\n if (scanner.b(\"[\")) {\n internalSubset = scanner.x(/\\][\\x20\\t\\r\\n]*>/);\n if (!scanner.b(\"]\")) {\n throw this.a(\"Unclosed internal subset\");\n }\n this.e();\n }\n if (!scanner.b(\">\")) {\n throw this.a(\"Unclosed doctype declaration\");\n }\n return this.g.preserveDocumentType ? this.i(new XmlDocumentType(name, publicId, systemId, internalSubset), startIndex) : true;\n }\n /**\n * Consumes an element if possible.\n *\n * @returns Whether an element was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-element\n */\n E() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<\")) {\n return false;\n }\n let name = this.q();\n if (!name) {\n scanner.n(startIndex);\n return false;\n }\n let attributes = this.H();\n let isEmpty = !!scanner.b(\"/>\");\n let element = new XmlElement(name, attributes);\n element.parent = this.j;\n if (!isEmpty) {\n if (!scanner.b(\">\")) {\n throw this.a(`Unclosed start tag for element \\`${name}\\``);\n }\n this.j = element;\n do {\n this.K();\n } while (this.E() || this.L() || this.J() || this.F() || this.D());\n let endTagMark = scanner.d;\n let endTagName;\n if (!scanner.b(\"</\") || !(endTagName = this.q()) || endTagName !== name) {\n scanner.n(endTagMark);\n throw this.a(`Missing end tag for element ${name}`);\n }\n this.e();\n if (!scanner.b(\">\")) {\n throw this.a(`Unclosed end tag for element ${name}`);\n }\n this.j = element.parent;\n }\n return this.i(element, startIndex);\n }\n /**\n * Consumes an `Eq` production if possible.\n *\n * @returns Whether an `Eq` production was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Eq\n */\n t() {\n this.e();\n if (this.c.b(\"=\")) {\n this.e();\n return true;\n }\n return false;\n }\n /**\n * Consumes `Misc` content if possible.\n *\n * @returns Whether anything was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Misc\n */\n z() {\n return this.D() || this.F() || this.e();\n }\n /**\n * Consumes one or more `Name` characters if possible.\n *\n * @returns `Name` characters, or an empty string if none were consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Name\n */\n q() {\n return isNameStartChar(this.c.m()) ? this.c.w(isNameChar) : emptyString2;\n }\n /**\n * Consumes a processing instruction if possible.\n *\n * @returns Whether a processing instruction was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-pi\n */\n F() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<?\")) {\n return false;\n }\n let name = this.q();\n if (name) {\n if (name.toLowerCase() === \"xml\") {\n scanner.n(startIndex);\n throw this.a(\"XML declaration isn't allowed here\");\n }\n } else {\n throw this.a(\"Invalid processing instruction\");\n }\n if (!this.e()) {\n if (scanner.b(\"?>\")) {\n return this.i(new XmlProcessingInstruction(name), startIndex);\n }\n throw this.a(\"Whitespace is required after a processing instruction name\");\n }\n let content = scanner.s(\"?>\");\n this.o(content);\n if (!scanner.b(\"?>\")) {\n throw this.a(\"Unterminated processing instruction\");\n }\n return this.i(new XmlProcessingInstruction(name, normalizeLineBreaks(content)), startIndex);\n }\n /**\n * Consumes a prolog if possible.\n *\n * @returns Whether a prolog was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-prolog-dtd\n */\n O() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n this.P();\n while (this.z()) {\n }\n if (this.M()) {\n while (this.z()) {\n }\n }\n return startIndex < scanner.d;\n }\n /**\n * Consumes a public identifier literal if possible.\n *\n * @returns\n * Value of the public identifier literal minus quotes, or `false` if\n * nothing was consumed. An empty string indicates that a public id literal\n * was consumed but was empty.\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-PubidLiteral\n */\n N() {\n let startIndex = this.c.d;\n let value = this.r();\n if (value !== false && !/^[-\\x20\\r\\na-zA-Z0-9'()+,./:=?;!*#@$_%]*$/.test(value)) {\n this.c.n(startIndex);\n throw this.a(\"Invalid character in public identifier\");\n }\n return value;\n }\n /**\n * Consumes a reference if possible.\n *\n * This differs from `consumeContentReference()` in that a consumed reference\n * will be returned rather than added to the document.\n *\n * @returns\n * Parsed reference value, or `false` if nothing was consumed (to\n * distinguish from a reference that resolves to an empty string).\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Reference\n */\n C() {\n let { c: scanner } = this;\n if (!scanner.b(\"&\")) {\n return false;\n }\n let ref = scanner.w(isReferenceChar);\n if (scanner.G() !== \";\") {\n throw this.a(\"Unterminated reference (a reference must end with `;`)\");\n }\n let parsedValue;\n if (ref[0] === \"#\") {\n let codePoint = ref[1] === \"x\" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);\n if (isNaN(codePoint)) {\n throw this.a(\"Invalid character reference\");\n }\n if (!isXmlCodePoint(codePoint)) {\n throw this.a(\"Character reference resolves to an invalid character\");\n }\n parsedValue = String.fromCodePoint(codePoint);\n } else {\n parsedValue = predefinedEntities[ref];\n if (parsedValue === void 0) {\n let {\n ignoreUndefinedEntities,\n resolveUndefinedEntity\n } = this.g;\n let wrappedRef = `&${ref};`;\n if (resolveUndefinedEntity) {\n let resolvedValue = resolveUndefinedEntity(wrappedRef);\n if (resolvedValue !== null && resolvedValue !== void 0) {\n let type = typeof resolvedValue;\n if (type !== \"string\") {\n throw new TypeError(`\\`resolveUndefinedEntity()\\` must return a string, \\`null\\`, or \\`undefined\\`, but returned a value of type ${type}`);\n }\n return resolvedValue;\n }\n }\n if (ignoreUndefinedEntities) {\n return wrappedRef;\n }\n scanner.n(-wrappedRef.length);\n throw this.a(`Named entity isn't defined: ${wrappedRef}`);\n }\n }\n return parsedValue;\n }\n /**\n * Consumes a `SystemLiteral` if possible.\n *\n * A `SystemLiteral` is similar to an attribute value, but allows the\n * characters `<` and `&` and doesn't replace references.\n *\n * @returns\n * Value of the `SystemLiteral` minus quotes, or `false` if nothing was\n * consumed. An empty string indicates that a `SystemLiteral` was consumed\n * but was empty.\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-SystemLiteral\n */\n r() {\n let { c: scanner } = this;\n let quote = scanner.b('\"') || scanner.b(\"'\");\n if (!quote) {\n return false;\n }\n let value = scanner.s(quote);\n this.o(value);\n if (!scanner.b(quote)) {\n throw this.a(\"Missing end quote\");\n }\n return value;\n }\n /**\n * Consumes one or more whitespace characters if possible.\n *\n * @returns Whether any whitespace characters were consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#white\n */\n e() {\n return !!this.c.w(isWhitespace);\n }\n /**\n * Consumes an XML declaration if possible.\n *\n * @returns Whether an XML declaration was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-XMLDecl\n */\n P() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<?xml\")) {\n return false;\n }\n if (!this.e()) {\n throw this.a(\"Invalid XML declaration\");\n }\n let version = !!scanner.b(\"version\") && this.t() && this.r();\n if (version === false) {\n throw this.a(\"XML version is missing or invalid\");\n } else if (!/^1\\.[0-9]+$/.test(version)) {\n throw this.a(\"Invalid character in version number\");\n }\n let encoding;\n let standalone;\n if (this.e()) {\n encoding = !!scanner.b(\"encoding\") && this.t() && this.r();\n if (encoding) {\n if (!/^[A-Za-z][\\w.-]*$/.test(encoding)) {\n throw this.a(\"Invalid character in encoding name\");\n }\n this.e();\n }\n standalone = !!scanner.b(\"standalone\") && this.t() && this.r();\n if (standalone) {\n if (standalone !== \"yes\" && standalone !== \"no\") {\n throw this.a('Only \"yes\" and \"no\" are permitted as values of `standalone`');\n }\n this.e();\n }\n }\n if (!scanner.b(\"?>\")) {\n throw this.a(\"Invalid or unclosed XML declaration\");\n }\n return this.g.preserveXmlDeclaration ? this.i(new XmlDeclaration(\n version,\n encoding || void 0,\n standalone || void 0\n ), startIndex) : true;\n }\n /**\n * Returns an `XmlError` for the current scanner position.\n */\n a(message) {\n let { c: scanner } = this;\n return new XmlError(message, scanner.d, scanner.h);\n }\n /**\n * Parses the XML input.\n */\n parse() {\n this.c.b(\"\\uFEFF\");\n this.O();\n if (!this.E()) {\n throw this.a(\"Root element is missing or invalid\");\n }\n while (this.z()) {\n }\n if (!this.c.B) {\n throw this.a(\"Extra content at the end of the document\");\n }\n }\n /**\n * Throws an invalid character error if any character in the given _string_\n * isn't a valid XML character.\n */\n o(string) {\n let { length } = string;\n for (let i = 0; i < length; ++i) {\n let cp = string.codePointAt(i);\n if (!isXmlCodePoint(cp)) {\n this.c.n(-([...string].length - i));\n throw this.a(\"Invalid character\");\n }\n if (cp > 65535) {\n i += 1;\n }\n }\n }\n};\nfunction normalizeLineBreaks(text) {\n let i = 0;\n while ((i = text.indexOf(\"\\r\", i)) !== -1) {\n text = text[i + 1] === \"\\n\" ? text.slice(0, i) + text.slice(i + 1) : text.slice(0, i) + \"\\n\" + text.slice(i + 1);\n }\n return text;\n}\n\n// src/index.ts\nfunction parseXml(xml, options) {\n return new Parser(xml, options).document;\n}\n//# sourceMappingURL=browser.js.map\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { parseXml, type XmlDocument, type XmlElement, type XmlText } from \"@rgrove/parse-xml\";\n\n/**\n * Subset of S3's `ListObjectsV2CommandOutput` produced by\n * {@link parseListObjectsV2CommandOutput}. Field names mirror the\n * S3 REST API exactly (PascalCase) so the parser stays a thin shape\n * over the wire format.\n */\nexport interface ParsedListObjectsV2Output {\n Contents?: Array<{ ETag?: string; Key?: string; LastModified?: Date }>;\n NextContinuationToken?: string;\n}\n\n/**\n * `<Code>` / `<Message>` extracted from an S3\n * `<Error>…</Error>` response body by {@link parseS3Error}. Field\n * names mirror the S3 REST API (PascalCase), matching the convention\n * of {@link ParsedListObjectsV2Output}.\n */\nexport interface ParsedS3Error {\n Code?: string;\n Message?: string;\n}\n\n// --- parse-xml helpers ---\n\n// Strip any namespace prefix: \"s3:Contents\" -> \"Contents\", \"Contents\" -> \"Contents\".\n// The `includes(\":\")` guard makes the `split(\":\")[1]!` non-null assertion safe.\nconst localName = (name: string): string => (name.includes(\":\") ? name.split(\":\")[1]! : name);\n\n// Type predicates narrowing an XmlNode child to a concrete node class.\n// @rgrove/parse-xml types the `type` discriminant as `string` (not a string\n// literal), so `node.type === \"element\"` does NOT narrow the child union on its\n// own. These localize the one unavoidable assertion behind a checked predicate\n// instead of scattering `as XmlElement` / `as XmlText` casts at each use site.\nconst isElement = (node: XmlElement[\"children\"][number]): node is XmlElement =>\n node.type === \"element\";\nconst isText = (node: XmlElement[\"children\"][number]): node is XmlText => node.type === \"text\";\n\n// Return the first XmlElement child of a document or element whose local name\n// (after any namespace prefix) matches `name`. This makes traversal\n// namespace-agnostic: both `<Error>` and `<ns:Error>` match name \"Error\".\nconst child = (el: XmlElement, name: string): XmlElement | undefined => {\n for (const node of el.children) {\n if (isElement(node) && localName(node.name) === name) {\n return node;\n }\n }\n return undefined;\n};\n\n// Concatenate the direct text child node text values of an element.\n// @rgrove/parse-xml resolves the 5 predefined XML entities (&amp; &lt; &gt;\n// &quot; &apos;) and decimal/hex numeric character references (e.g. Minio's\n// &#34; ETags) by default. Under the default `preserveCdata: false` (which is\n// how we call parseXml), any CDATA section is merged into the element's adjacent\n// text nodes and surfaces as an XmlText (type \"text\"), so the \"text\" branch\n// captures it — there is never a standalone \"cdata\" node. Entities inside a\n// CDATA section are NOT decoded (CDATA is literal), which is the correct S3\n// behavior. We intentionally do NOT decode HTML named entities (&nbsp; etc.) —\n// S3 wire data is XML, not HTML, so this is more spec-correct.\nconst textOf = (el: XmlElement | undefined): string | undefined => {\n if (el === undefined) {\n return undefined;\n }\n let result = \"\";\n for (const node of el.children) {\n if (isText(node)) {\n result += node.text;\n }\n }\n return result === \"\" ? undefined : result;\n};\n\n// Return the first-element-child of an XmlDocument. Unlike `XmlDocument.root`\n// (which is an XmlElement | null getter), this avoids potential null handling\n// confusion by returning undefined on an empty document.\nconst docRoot = (doc: XmlDocument): XmlElement | undefined => doc.root ?? undefined;\n\n// The list request sets `encoding-type=url`, so S3 URL-encodes the **key\n// family only** (Key/Prefix/Delimiter/StartAfter) in the response,\n// including spaces as `+`. Use this to reverse both steps. Do NOT apply it\n// to ETag or NextContinuationToken — S3 leaves those verbatim, and a\n// continuation token routinely contains literal `+` that the `.replace`\n// step would mangle into a space (corrupting pagination on large buckets).\nconst xmlVal = (el: XmlElement | undefined, name: string): string | undefined => {\n const v = el !== undefined ? textOf(child(el, name)) : undefined;\n if (v === undefined || v === \"\") {\n return undefined;\n }\n // A well-formed encoding-type=url response only ever contains valid\n // percent-escapes. A bare `%` or an invalid pair (`%ZZ`) makes\n // decodeURIComponent throw a raw URIError — catch it and re-raise as a\n // typed BaerlyError so the storage layer surfaces a catchable error rather\n // than an unhandled runtime exception. See docs/spec/s3-xml-escaping-cases.md.\n try {\n return decodeURIComponent(v.replace(/\\+/g, \" \"));\n } catch {\n throw new BaerlyError(\"InvalidResponse\", `Malformed percent-escape in S3 <${name}>: ${v}`);\n }\n};\n\n// Read a field verbatim. Used for everything S3 does NOT URL-encode:\n// error-body `Code`/`Message`, list `ETag`/`LastModified`, and\n// `NextContinuationToken` — running any of these through `xmlVal`'s\n// `decodeURIComponent` / `+`→space would corrupt literal `+` and `%`.\nconst rawXmlVal = (el: XmlElement | undefined, name: string): string | undefined => {\n return el !== undefined ? textOf(child(el, name)) : undefined;\n};\n\n/**\n * Build a {@link ParsedS3Error} from the element that directly carries\n * the `<Code>` / `<Message>` children — `<Error>` for S3, the inner\n * `<Error>` for STS. Returns `undefined` when neither child is present\n * so callers can fall back to the raw status. Shared by\n * {@link parseS3Error} and {@link parseStsError}, which differ only in\n * how they locate that element.\n */\nconst codeMessageFrom = (el: XmlElement): ParsedS3Error | undefined => {\n const code = rawXmlVal(el, \"Code\");\n const message = rawXmlVal(el, \"Message\");\n if (code === undefined && message === undefined) {\n return undefined;\n }\n return {\n ...(code !== undefined && { Code: code }),\n ...(message !== undefined && { Message: message }),\n };\n};\n\n/**\n * Parse an S3 `<Error><Code>…</Code><Message>…</Message></Error>`\n * body. Returns `undefined` when the body is not a recognizable S3\n * error document (empty, HTML, a success payload, or a DTD), so\n * callers can fall back to the raw response text. This never throws:\n * it runs on a path that is already reporting an error.\n */\nexport const parseS3Error = (xml: string): ParsedS3Error | undefined => {\n // Skip non-error bodies; refuse DTDs before parsing — see the DTD-guard\n // note above parseListObjectsV2CommandOutput.\n if (!/<Error\\b/i.test(xml) || /<!DOCTYPE\\b/i.test(xml)) {\n return undefined;\n }\n let root: XmlElement | undefined;\n try {\n root = docRoot(parseXml(xml));\n } catch {\n return undefined;\n }\n // The root element must be <Error> (possibly namespace-prefixed).\n if (root === undefined) {\n return undefined;\n }\n if (localName(root.name) !== \"Error\") {\n return undefined;\n }\n return codeMessageFrom(root);\n};\n\n/**\n * Parse an STS `<ErrorResponse><Error><Code>…</Code><Message>…</Message>\n * </Error></ErrorResponse>` body (the shape STS returns on a failed\n * `AssumeRoleWithWebIdentity` — e.g. `InvalidIdentityToken`,\n * `ExpiredTokenException`, `AccessDenied`). Returns `undefined` when the body\n * is not a recognizable STS error document (empty, HTML, a success payload, or\n * a DTD), so callers can fall back to the bare status. Like {@link parseS3Error}\n * this never throws — it runs on a path that is already reporting an error.\n *\n * Note the nesting differs from S3: STS wraps `<Error>` inside `<ErrorResponse>`.\n */\nexport const parseStsError = (xml: string): ParsedS3Error | undefined => {\n if (!/<Error\\b/i.test(xml) || /<!DOCTYPE\\b/i.test(xml)) {\n return undefined;\n }\n let root: XmlElement | undefined;\n try {\n root = docRoot(parseXml(xml));\n } catch {\n return undefined;\n }\n if (root === undefined) {\n return undefined;\n }\n // STS wraps <Error> inside <ErrorResponse>; locate the inner <Error> child.\n const errorEl = child(root, \"Error\");\n if (errorEl === undefined) {\n return undefined;\n }\n return codeMessageFrom(errorEl);\n};\n\n/**\n * `<Credentials>` extracted from an STS\n * `<AssumeRoleWithWebIdentityResponse>` body by\n * {@link parseAssumeRoleWithWebIdentity}. Field names mirror the STS REST\n * API (PascalCase), matching the convention of {@link ParsedS3Error}.\n */\nexport interface ParsedWebIdentityCredentials {\n AccessKeyId?: string;\n SecretAccessKey?: string;\n SessionToken?: string;\n Expiration?: string;\n}\n\n/**\n * Parse an STS `AssumeRoleWithWebIdentity` success body, returning the\n * `<Credentials>` block. Reuses the hardened, DTD-guarded parser;\n * throws `InvalidResponse` on a DTD or unparseable XML. Missing fields come\n * back `undefined` so the caller can map them to its own `InvalidResponse`.\n *\n * Unlike {@link parseListObjectsV2CommandOutput}, the error on unparseable\n * XML must NOT echo the body: a success-shaped STS body carries the plaintext\n * `SecretAccessKey`/`SessionToken`, so folding it into a thrown-then-logged\n * error would leak live credentials.\n */\nexport const parseAssumeRoleWithWebIdentity = (xml: string): ParsedWebIdentityCredentials => {\n if (/<!DOCTYPE\\b/i.test(xml)) {\n throw new BaerlyError(\"InvalidResponse\", \"DTD not allowed in STS XML responses\");\n }\n let root: XmlElement | undefined;\n try {\n root = docRoot(parseXml(xml));\n } catch {\n // No body in the message — see the note above; it may contain live creds.\n throw new BaerlyError(\"InvalidResponse\", \"unparseable STS credentials response\");\n }\n // Traverse: <AssumeRoleWithWebIdentityResponse>\n // <AssumeRoleWithWebIdentityResult>\n // <Credentials>\n const resultEl = root !== undefined ? child(root, \"AssumeRoleWithWebIdentityResult\") : undefined;\n const credsEl = resultEl !== undefined ? child(resultEl, \"Credentials\") : undefined;\n return {\n AccessKeyId: rawXmlVal(credsEl, \"AccessKeyId\"),\n SecretAccessKey: rawXmlVal(credsEl, \"SecretAccessKey\"),\n SessionToken: rawXmlVal(credsEl, \"SessionToken\"),\n Expiration: rawXmlVal(credsEl, \"Expiration\"),\n };\n};\n\n// `new Date(badString)` yields an Invalid Date (a non-null Date whose\n// getTime() is NaN) rather than throwing — surface `undefined` for a\n// malformed `LastModified` so it never leaks into a `StorageListEntry`.\n// GC then falls back to `now()` for the tombstone `due_at` anchor.\nconst parseLastModified = (lm: string | undefined): Date | undefined => {\n if (lm === undefined) {\n return undefined;\n }\n const d = new Date(lm);\n return Number.isNaN(d.getTime()) ? undefined : d;\n};\n\n// DTD guard: reject any DOCTYPE before @rgrove/parse-xml sees the bytes. S3/R2/\n// MinIO/GCS never emit a DOCTYPE here, so one is always a bug or an attack —\n// this defangs the DOCTYPE entity vectors (XXE, billion-laughs, the\n// CVE-2026-25896 entity-shadow). @rgrove/parse-xml is safe-by-design (refuses\n// DTD entity definitions), but the regex guard is parser-independent\n// defense-in-depth and independently covers the entity-expansion CVE class.\nexport const parseListObjectsV2CommandOutput = (xml: string): ParsedListObjectsV2Output => {\n if (/<!DOCTYPE\\b/i.test(xml)) {\n throw new BaerlyError(\"InvalidResponse\", \"DTD not allowed in S3 XML responses\");\n }\n let root: XmlElement | undefined;\n try {\n root = docRoot(parseXml(xml));\n } catch {\n throw new BaerlyError(\"InvalidResponse\", `Invalid XML: ${xml}`);\n }\n if (root === undefined) {\n return {};\n }\n // The root element must be <ListBucketResult> (possibly namespace-prefixed).\n // This restores main's `result.ListBucketResult ?? {}` structural guard and\n // matches the sibling error parsers' root checks: a non-list body returns {}.\n if (localName(root.name) !== \"ListBucketResult\") {\n return {};\n }\n // Force-array for Contents: collect all direct <Contents> element children.\n // This replaces the old `isArray: (name) => name === \"Contents\"` config.\n // Namespace-agnostic (matches `child()`), so `<s3:Contents>` also collects.\n const contentEls = root.children\n .filter(isElement)\n .filter((c) => localName(c.name) === \"Contents\");\n\n return {\n Contents: contentEls.map((contentEl) => {\n return {\n ETag: rawXmlVal(contentEl, \"ETag\"),\n Key: xmlVal(contentEl, \"Key\"),\n LastModified: parseLastModified(rawXmlVal(contentEl, \"LastModified\")),\n };\n }),\n NextContinuationToken: rawXmlVal(root, \"NextContinuationToken\"),\n };\n};\n","import {\n BaerlyError,\n LIST_OBJECT_MAX_RETRIES,\n RATE_LIMIT_BACKOFF_MILLIS,\n RETRY_AFTER_MAX_SECONDS,\n S3_REQUEST_MAX_RETRIES,\n assertValidStorageKey,\n delay,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\nimport { parseListObjectsV2CommandOutput, parseS3Error } from \"./xml.ts\";\n\n/**\n * Permanent {@link BaerlyError} codes that must short-circuit `retry`.\n * These represent caller- or environment-level faults where retrying\n * cannot succeed: `AccessDenied` (403 — credentials/policy),\n * `InvalidConfig` (bad bucket / unsupported credential type),\n * `InvalidResponse` (server returned unparseable data), and\n * `Conflict` (CAS guard lost — retrying would just re-lose against\n * the same state). `NetworkError` is intentionally absent — it covers\n * transient transport faults and stays retryable.\n *\n * Transport-layer set, distinct from `RETRIABLE_CODES` in `@baerly/protocol`'s\n * `errors.ts` (the default wire `retriable` hint). `Conflict` is \"permanent\"\n * here (a blind re-PUT re-loses the CAS race) yet retryable for logical CAS\n * callers that can fresh-read + re-apply. Same code, two different questions.\n */\nconst PERMANENT_ERROR_CODES: ReadonlySet<string> = new Set([\n \"AccessDenied\",\n \"InvalidConfig\",\n \"InvalidResponse\",\n \"Conflict\",\n]);\n\n/**\n * Parse an HTTP `Retry-After` header into a non-negative seconds value,\n * clamped to {@link RETRY_AFTER_MAX_SECONDS}. Returns `undefined` if\n * the header is absent, malformed, or whitespace.\n *\n * RFC 7231 §7.1.3 admits two forms: delta-seconds (non-negative\n * integer) and HTTP-date. Both are accepted; dates in the past return\n * `0`. Fractional seconds, negatives, and arbitrary strings reject.\n *\n * The `now` injection point exists for the unit test; production\n * callers should pass nothing.\n */\nfunction parseRetryAfter(header: string | null, now: () => number = Date.now): number | undefined {\n if (header === null) {\n return undefined;\n }\n const trimmed = header.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n if (/^\\d+$/.test(trimmed)) {\n const n = Number.parseInt(trimmed, 10);\n return Number.isFinite(n) ? Math.min(n, RETRY_AFTER_MAX_SECONDS) : undefined;\n }\n // RFC 7231 §7.1.1.1 HTTP-date formats (IMF-fixdate, RFC 850, asctime)\n // all contain alphabetic month/day-of-week tokens. Gating on a letter\n // avoids V8's lenient `Date.parse` accepting things like \"5.5\".\n if (!/[a-z]/i.test(trimmed)) {\n return undefined;\n }\n const t = Date.parse(trimmed);\n if (Number.isNaN(t)) {\n return undefined;\n }\n const seconds = Math.max(0, Math.ceil((t - now()) / 1000));\n return Math.min(seconds, RETRY_AFTER_MAX_SECONDS);\n}\n\nconst retryAfterCause = (res: Response): { retryAfterSeconds?: number } => {\n const hint = parseRetryAfter(res.headers.get(\"Retry-After\"));\n return hint !== undefined ? { retryAfterSeconds: hint } : {};\n};\n\n// Detail suffix for a non-status-mapped S3 error response. When the\n// body is a parseable `<Error><Code>…</Error>` document, surface S3's\n// own error code (and message) instead of concatenating the raw XML\n// blob into the thrown message; otherwise fall back to the raw text.\nconst s3ErrorDetail = (status: number, body: string): string => {\n const parsed = parseS3Error(body);\n if (parsed !== undefined) {\n const code = parsed.Code ?? \"UnknownError\";\n return parsed.Message !== undefined\n ? `${status} ${code}: ${parsed.Message}`\n : `${status} ${code}`;\n }\n return `${status} ${body}`;\n};\n\nconst retry = async <T>(\n fn: () => Promise<T>,\n { retries = S3_REQUEST_MAX_RETRIES, backoffMs = 100, maxDelayMs = 10_000 } = {},\n): Promise<T> => {\n let wait = backoffMs;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof BaerlyError && PERMANENT_ERROR_CODES.has(error.code)) {\n throw error;\n }\n if (attempt === retries) {\n throw error;\n }\n const hintMs = retryAfterHintMs(error, maxDelayMs);\n await delay(hintMs ?? wait);\n if (hintMs === undefined) {\n wait = Math.min(wait * 1.5, maxDelayMs);\n } else {\n // A server-driven pause is new information about server state;\n // reset the exponential ladder so a subsequent non-hinted\n // transient starts fresh from `backoffMs`.\n wait = backoffMs;\n }\n }\n }\n throw new BaerlyError(\"Internal\", \"s3-http retry loop exited without returning or throwing\");\n};\n\nconst retryAfterHintMs = (e: unknown, maxDelayMs: number): number | undefined => {\n if (!(e instanceof BaerlyError)) {\n return undefined;\n }\n const cause = e.cause as { retryAfterSeconds?: number } | undefined;\n if (cause?.retryAfterSeconds === undefined) {\n return undefined;\n }\n return Math.min(cause.retryAfterSeconds * 1000, maxDelayMs);\n};\n\n/**\n * Construction-time options for {@link S3HttpStorage}. Everything is\n * optional except `endpoint` and `bucket`; the consumer chooses how\n * to satisfy `fetch` (browser/Node global vs. injected) and `sign`\n * (anonymous Minio vs. SigV4-signed via aws4fetch).\n */\nexport interface S3HttpStorageOptions {\n /**\n * S3 endpoint URL, e.g. `https://s3.us-east-1.amazonaws.com` or\n * `http://127.0.0.1:9102` (Minio). Trailing slashes are trimmed.\n */\n endpoint: string;\n /** S3 bucket name. */\n bucket: string;\n /**\n * `fetch` implementation. Defaults to `globalThis.fetch.bind(globalThis)`.\n * Tests pass a `vi.fn()` stub.\n */\n fetch?: typeof fetch;\n /**\n * Signs requests before send. Pass `undefined` for anonymous\n * (Minio without creds). The seam is `(req) => Promise<req>` so\n * SigV4 implementations like `aws4fetch.AwsClient.sign` plug in\n * directly.\n */\n sign?: (req: Request) => Promise<Request>;\n /** Max retries for transient (non-permanent) failures. */\n retries?: number;\n /** Initial backoff in ms. */\n backoffMs?: number;\n}\n\n/**\n * `Storage` impl that speaks the S3 REST API directly. Works against\n * any S3-compatible endpoint — AWS S3, R2 (S3-compat), GCS (S3-compat),\n * Minio. Does not depend on any AWS SDK.\n *\n * Authentication is plugged in via the `sign` callback; this class\n * itself does no SigV4. For Cloudflare Workers, the R2 binding fast\n * path lives in `@baerly/adapter-cloudflare`.\n */\nexport class S3HttpStorage implements Storage {\n readonly #endpoint: string;\n readonly #bucket: string;\n readonly #fetch: typeof fetch;\n readonly #sign?: (req: Request) => Promise<Request>;\n readonly #retries: number;\n readonly #backoffMs: number;\n\n constructor(options: S3HttpStorageOptions) {\n this.#endpoint = options.endpoint.replace(/\\/+$/, \"\");\n this.#bucket = options.bucket;\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#sign = options.sign;\n this.#retries = options.retries ?? S3_REQUEST_MAX_RETRIES;\n this.#backoffMs = options.backoffMs ?? 100;\n }\n\n #objectUrl(key: string, versionId?: string): string {\n // Choke point for every key-addressing verb — reject unaddressable\n // `.`/`..`/empty keys before URL normalization turns them into a\n // bucket-root 403. @see storage-compatibility.md \"Key namespace\".\n assertValidStorageKey(key);\n const base = `${this.#endpoint}/${this.#bucket}/${encodeURIComponent(key)}`;\n return versionId !== undefined ? `${base}?versionId=${encodeURIComponent(versionId)}` : base;\n }\n\n async #dispatch(req: Request): Promise<Response> {\n const signed = this.#sign ? await this.#sign(req) : req;\n try {\n return await this.#fetch(signed);\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n const msg = error instanceof Error ? error.message : String(error);\n throw new BaerlyError(\"NetworkError\", msg, error);\n }\n }\n\n #retry<T>(fn: () => Promise<T>): Promise<T> {\n return retry(fn, { retries: this.#retries, backoffMs: this.#backoffMs });\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key, opts?.versionId);\n const headers = new Headers();\n if (opts?.ifNoneMatch !== undefined) {\n headers.set(\"If-None-Match\", opts.ifNoneMatch);\n }\n return this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"GET\", headers, signal: opts?.signal ?? null }),\n );\n switch (res.status) {\n case 200: {\n const etag = res.headers.get(\"ETag\");\n if (etag === null) {\n throw new BaerlyError(\"InvalidResponse\", `GET ${key}: missing ETag`);\n }\n const body = new Uint8Array(await res.arrayBuffer());\n const versionId = res.headers.get(\"x-amz-version-id\") ?? undefined;\n return versionId !== undefined ? { body, etag, versionId } : { body, etag };\n }\n case 304:\n case 404: {\n return null;\n }\n case 403: {\n throw new BaerlyError(\"AccessDenied\", `GET ${key}: 403`);\n }\n default: {\n if (res.status === 429 || res.status >= 500) {\n throw new BaerlyError(\"NetworkError\", `GET ${key}: ${res.status} ${await res.text()}`, {\n status: res.status,\n ...retryAfterCause(res),\n });\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `GET ${key}: ${s3ErrorDetail(res.status, await res.text())}`,\n );\n }\n }\n });\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n const headers = new Headers();\n headers.set(\"Content-Type\", opts?.contentType ?? \"application/octet-stream\");\n if (opts?.ifMatch !== undefined) {\n headers.set(\"If-Match\", opts.ifMatch);\n }\n if (opts?.ifNoneMatch === \"*\") {\n headers.set(\"If-None-Match\", \"*\");\n }\n return this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, {\n method: \"PUT\",\n headers,\n // TS lib.dom narrows BodyInit and a generic `Uint8Array<ArrayBufferLike>`\n // is not assignable; the runtime accepts it.\n body: body as BodyInit,\n signal: opts?.signal ?? null,\n }),\n );\n if (res.status === 412) {\n throw new BaerlyError(\"Conflict\", `PUT ${key}: precondition failed`);\n }\n // AWS S3 returns 409 ConditionalRequestConflict when a concurrent\n // conditional create (If-None-Match:\"*\") races; Minio returns 412.\n // 409 means the write was contended and may NOT have landed, so it\n // maps to a retryable NetworkError — the single-write-commit writer\n // re-issues the same-seq PUT, which resolves deterministically to 200\n // (we win) or 412 (key now present → Conflict → adopt/re-probe). A\n // direct Conflict here would adopt-read a possibly-absent entry.\n if (res.status === 409 && opts?.ifNoneMatch === \"*\") {\n throw new BaerlyError(\n \"NetworkError\",\n `PUT ${key}: 409 ConditionalRequestConflict (contended conditional create; retryable)`,\n { status: res.status, ...retryAfterCause(res) },\n );\n }\n // S3-compatible servers diverge on `If-Match` against a missing\n // key: AWS S3 returns 412, Minio returns 404 (NoSuchKey). Map\n // 404-with-ifMatch to the same `Conflict` semantic so consumers\n // don't have to special-case the wire reply.\n if (res.status === 404 && opts?.ifMatch !== undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (res.status === 403) {\n throw new BaerlyError(\"AccessDenied\", `PUT ${key}: 403`);\n }\n if (res.status === 429 || res.status >= 500) {\n throw new BaerlyError(\"NetworkError\", `PUT ${key}: ${res.status} ${await res.text()}`, {\n status: res.status,\n ...retryAfterCause(res),\n });\n }\n if (res.status !== 200 && res.status !== 204) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `PUT ${key}: ${s3ErrorDetail(res.status, await res.text())}`,\n );\n }\n const etag = res.headers.get(\"ETag\");\n if (etag === null) {\n throw new BaerlyError(\"InvalidResponse\", `PUT ${key}: missing ETag`);\n }\n const dateStr = res.headers.get(\"Date\");\n const versionId = res.headers.get(\"x-amz-version-id\") ?? undefined;\n const result: { etag: string; serverDate?: Date; versionId?: string } = { etag };\n if (dateStr !== null) {\n result.serverDate = new Date(dateStr);\n }\n if (versionId !== undefined) {\n result.versionId = versionId;\n }\n return result;\n });\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n await this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"DELETE\", signal: opts?.signal ?? null }),\n );\n if (res.status === 403) {\n throw new BaerlyError(\"AccessDenied\", `DELETE ${key}: 403`);\n }\n if (res.status === 429 || res.status >= 500) {\n throw new BaerlyError(\"NetworkError\", `DELETE ${key}: ${res.status} ${await res.text()}`, {\n status: res.status,\n ...retryAfterCause(res),\n });\n }\n // 200 / 204 / 404 → success (idempotent).\n });\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n let yielded = 0;\n let continuationToken: string | undefined;\n const startAfter = opts?.startAfter ?? \"\";\n while (true) {\n opts?.signal?.throwIfAborted();\n const params = new URLSearchParams();\n params.set(\"list-type\", \"2\");\n params.set(\"prefix\", prefix);\n // Force S3 to URL-encode object keys in the response so keys\n // containing XML-hostile or whitespace bytes survive the round trip.\n // The XML parser (`xmlVal` in ./xml.ts) reverses this on `Key`; only\n // the key family (Key/Prefix/Delimiter/StartAfter) is encoded — ETag\n // and NextContinuationToken come back verbatim.\n params.set(\"encoding-type\", \"url\");\n if (continuationToken !== undefined) {\n params.set(\"continuation-token\", continuationToken);\n } else if (startAfter !== \"\") {\n params.set(\"start-after\", startAfter);\n }\n if (opts?.maxKeys !== undefined) {\n const remaining = opts.maxKeys - yielded;\n params.set(\"max-keys\", String(Math.min(remaining, 1000)));\n }\n const url = `${this.#endpoint}/${this.#bucket}/?${params.toString()}`;\n\n // Per-page 429 retry budget separate from the inner #retry budget:\n // 429 means \"rate-limited, back off and retry the same page\", and\n // a single hot page shouldn't burn the overall transient-failure\n // budget.\n let parsed: Awaited<ReturnType<typeof parseListObjectsV2CommandOutput>> | undefined;\n let lastHint: number | undefined;\n for (let attempt = 0; attempt < LIST_OBJECT_MAX_RETRIES; attempt++) {\n const outcome = await this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"GET\", signal: opts?.signal ?? null }),\n );\n if (res.status === 200) {\n return { kind: \"ok\" as const, body: await res.text() };\n }\n if (res.status === 429) {\n return {\n kind: \"ratelimited\" as const,\n retryAfterSeconds: parseRetryAfter(res.headers.get(\"Retry-After\")),\n };\n }\n if (res.status === 403) {\n throw new BaerlyError(\"AccessDenied\", `LIST ${prefix}: 403`);\n }\n if (res.status >= 500) {\n throw new BaerlyError(\n \"NetworkError\",\n `LIST ${prefix}: ${res.status} ${await res.text()}`,\n { status: res.status, ...retryAfterCause(res) },\n );\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LIST ${prefix}: ${s3ErrorDetail(res.status, await res.text())}`,\n );\n });\n if (outcome.kind === \"ok\") {\n parsed = parseListObjectsV2CommandOutput(outcome.body);\n break;\n }\n lastHint = outcome.retryAfterSeconds;\n const hintMs =\n outcome.retryAfterSeconds !== undefined ? outcome.retryAfterSeconds * 1000 : 0;\n await delay(Math.max(hintMs, RATE_LIMIT_BACKOFF_MILLIS));\n }\n if (parsed === undefined) {\n throw new BaerlyError(\"NetworkError\", `LIST ${prefix}: rate-limited`, {\n status: 429,\n ...(lastHint !== undefined ? { retryAfterSeconds: lastHint } : {}),\n });\n }\n\n for (const entry of parsed.Contents ?? []) {\n if (entry.Key === undefined) {\n continue;\n }\n yield {\n key: entry.Key,\n etag: entry.ETag ?? \"\",\n ...(entry.LastModified !== undefined && { lastModified: entry.LastModified }),\n };\n yielded += 1;\n if (opts?.maxKeys !== undefined && yielded >= opts.maxKeys) {\n return;\n }\n }\n continuationToken = parsed.NextContinuationToken;\n if (continuationToken === undefined || continuationToken === \"\") {\n return;\n }\n }\n }\n}\n","/**\n * @license MIT <https://opensource.org/licenses/MIT>\n * @copyright Michael Hart 2024\n */\nconst encoder = new TextEncoder();\nconst HOST_SERVICES = {\n appstream2: 'appstream',\n cloudhsmv2: 'cloudhsm',\n email: 'ses',\n marketplace: 'aws-marketplace',\n mobile: 'AWSMobileHubService',\n pinpoint: 'mobiletargeting',\n queue: 'sqs',\n 'git-codecommit': 'codecommit',\n 'mturk-requester-sandbox': 'mturk-requester',\n 'personalize-runtime': 'personalize',\n};\nconst UNSIGNABLE_HEADERS = new Set([\n 'authorization',\n 'content-type',\n 'content-length',\n 'user-agent',\n 'presigned-expires',\n 'expect',\n 'x-amzn-trace-id',\n 'range',\n 'connection',\n]);\nclass AwsClient {\n constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n this.service = service;\n this.region = region;\n this.cache = cache || new Map();\n this.retries = retries != null ? retries : 10;\n this.initRetryMs = initRetryMs || 50;\n }\n async sign(input, init) {\n if (input instanceof Request) {\n const { method, url, headers, body } = input;\n init = Object.assign({ method, url, headers }, init);\n if (init.body == null && headers.has('Content-Type')) {\n init.body = body != null && headers.has('X-Amz-Content-Sha256') ? body : await input.clone().arrayBuffer();\n }\n input = url;\n }\n const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));\n const signed = Object.assign({}, init, await signer.sign());\n delete signed.aws;\n try {\n return new Request(signed.url.toString(), signed)\n } catch (e) {\n if (e instanceof TypeError) {\n return new Request(signed.url.toString(), Object.assign({ duplex: 'half' }, signed))\n }\n throw e\n }\n }\n async fetch(input, init) {\n for (let i = 0; i <= this.retries; i++) {\n const fetched = fetch(await this.sign(input, init));\n if (i === this.retries) {\n return fetched\n }\n const res = await fetched;\n if (res.status < 500 && res.status !== 429) {\n return res\n }\n await new Promise(resolve => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));\n }\n throw new Error('An unknown error occurred, ensure retries is not negative')\n }\n}\nclass AwsV4Signer {\n constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {\n if (url == null) throw new TypeError('url is a required option')\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.method = method || (body ? 'POST' : 'GET');\n this.url = new URL(url);\n this.headers = new Headers(headers || {});\n this.body = body;\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n let guessedService, guessedRegion;\n if (!service || !region) {\n[guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);\n }\n this.service = service || guessedService || '';\n this.region = region || guessedRegion || 'us-east-1';\n this.cache = cache || new Map();\n this.datetime = datetime || new Date().toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n this.signQuery = signQuery;\n this.appendSessionToken = appendSessionToken || this.service === 'iotdevicegateway';\n this.headers.delete('Host');\n if (this.service === 's3' && !this.signQuery && !this.headers.has('X-Amz-Content-Sha256')) {\n this.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD');\n }\n const params = this.signQuery ? this.url.searchParams : this.headers;\n params.set('X-Amz-Date', this.datetime);\n if (this.sessionToken && !this.appendSessionToken) {\n params.set('X-Amz-Security-Token', this.sessionToken);\n }\n this.signableHeaders = ['host', ...this.headers.keys()]\n .filter(header => allHeaders || !UNSIGNABLE_HEADERS.has(header))\n .sort();\n this.signedHeaders = this.signableHeaders.join(';');\n this.canonicalHeaders = this.signableHeaders\n .map(header => header + ':' + (header === 'host' ? this.url.host : (this.headers.get(header) || '').replace(/\\s+/g, ' ')))\n .join('\\n');\n this.credentialString = [this.datetime.slice(0, 8), this.region, this.service, 'aws4_request'].join('/');\n if (this.signQuery) {\n if (this.service === 's3' && !params.has('X-Amz-Expires')) {\n params.set('X-Amz-Expires', '86400');\n }\n params.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256');\n params.set('X-Amz-Credential', this.accessKeyId + '/' + this.credentialString);\n params.set('X-Amz-SignedHeaders', this.signedHeaders);\n }\n if (this.service === 's3') {\n try {\n this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\\+/g, ' '));\n } catch (e) {\n this.encodedPath = this.url.pathname;\n }\n } else {\n this.encodedPath = this.url.pathname.replace(/\\/+/g, '/');\n }\n if (!singleEncode) {\n this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, '/');\n }\n this.encodedPath = encodeRfc3986(this.encodedPath);\n const seenKeys = new Set();\n this.encodedSearch = [...this.url.searchParams]\n .filter(([k]) => {\n if (!k) return false\n if (this.service === 's3') {\n if (seenKeys.has(k)) return false\n seenKeys.add(k);\n }\n return true\n })\n .map(pair => pair.map(p => encodeRfc3986(encodeURIComponent(p))))\n .sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0)\n .map(pair => pair.join('='))\n .join('&');\n }\n async sign() {\n if (this.signQuery) {\n this.url.searchParams.set('X-Amz-Signature', await this.signature());\n if (this.sessionToken && this.appendSessionToken) {\n this.url.searchParams.set('X-Amz-Security-Token', this.sessionToken);\n }\n } else {\n this.headers.set('Authorization', await this.authHeader());\n }\n return {\n method: this.method,\n url: this.url,\n headers: this.headers,\n body: this.body,\n }\n }\n async authHeader() {\n return [\n 'AWS4-HMAC-SHA256 Credential=' + this.accessKeyId + '/' + this.credentialString,\n 'SignedHeaders=' + this.signedHeaders,\n 'Signature=' + (await this.signature()),\n ].join(', ')\n }\n async signature() {\n const date = this.datetime.slice(0, 8);\n const cacheKey = [this.secretAccessKey, date, this.region, this.service].join();\n let kCredentials = this.cache.get(cacheKey);\n if (!kCredentials) {\n const kDate = await hmac('AWS4' + this.secretAccessKey, date);\n const kRegion = await hmac(kDate, this.region);\n const kService = await hmac(kRegion, this.service);\n kCredentials = await hmac(kService, 'aws4_request');\n this.cache.set(cacheKey, kCredentials);\n }\n return buf2hex(await hmac(kCredentials, await this.stringToSign()))\n }\n async stringToSign() {\n return [\n 'AWS4-HMAC-SHA256',\n this.datetime,\n this.credentialString,\n buf2hex(await hash(await this.canonicalString())),\n ].join('\\n')\n }\n async canonicalString() {\n return [\n this.method.toUpperCase(),\n this.encodedPath,\n this.encodedSearch,\n this.canonicalHeaders + '\\n',\n this.signedHeaders,\n await this.hexBodyHash(),\n ].join('\\n')\n }\n async hexBodyHash() {\n let hashHeader = this.headers.get('X-Amz-Content-Sha256') || (this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null);\n if (hashHeader == null) {\n if (this.body && typeof this.body !== 'string' && !('byteLength' in this.body)) {\n throw new Error('body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header')\n }\n hashHeader = buf2hex(await hash(this.body || ''));\n }\n return hashHeader\n }\n}\nasync function hmac(key, string) {\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n typeof key === 'string' ? encoder.encode(key) : key,\n { name: 'HMAC', hash: { name: 'SHA-256' } },\n false,\n ['sign'],\n );\n return crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string))\n}\nasync function hash(content) {\n return crypto.subtle.digest('SHA-256', typeof content === 'string' ? encoder.encode(content) : content)\n}\nconst HEX_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nfunction buf2hex(arrayBuffer) {\n const buffer = new Uint8Array(arrayBuffer);\n let out = '';\n for (let idx = 0; idx < buffer.length; idx++) {\n const n = buffer[idx];\n out += HEX_CHARS[(n >>> 4) & 0xF];\n out += HEX_CHARS[n & 0xF];\n }\n return out\n}\nfunction encodeRfc3986(urlEncodedStr) {\n return urlEncodedStr.replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n}\nfunction guessServiceRegion(url, headers) {\n const { hostname, pathname } = url;\n if (hostname.endsWith('.on.aws')) {\n const match = hostname.match(/^[^.]{1,63}\\.lambda-url\\.([^.]{1,63})\\.on\\.aws$/);\n return match != null ? ['lambda', match[1] || ''] : ['', '']\n }\n if (hostname.endsWith('.r2.cloudflarestorage.com')) {\n return ['s3', 'auto']\n }\n if (hostname.endsWith('.backblazeb2.com')) {\n const match = hostname.match(/^(?:[^.]{1,63}\\.)?s3\\.([^.]{1,63})\\.backblazeb2\\.com$/);\n return match != null ? ['s3', match[1] || ''] : ['', '']\n }\n const match = hostname.replace('dualstack.', '').match(/([^.]{1,63})\\.(?:([^.]{0,63})\\.)?amazonaws\\.com(?:\\.cn)?$/);\n let service = (match && match[1]) || '';\n let region = match && match[2];\n if (region === 'us-gov') {\n region = 'us-gov-west-1';\n } else if (region === 's3' || region === 's3-accelerate') {\n region = 'us-east-1';\n service = 's3';\n } else if (service === 'iot') {\n if (hostname.startsWith('iot.')) {\n service = 'execute-api';\n } else if (hostname.startsWith('data.jobs.iot.')) {\n service = 'iot-jobs-data';\n } else {\n service = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata';\n }\n } else if (service === 'autoscaling') {\n const targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0];\n if (targetPrefix === 'AnyScaleFrontendService') {\n service = 'application-autoscaling';\n } else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') {\n service = 'autoscaling-plans';\n }\n } else if (region == null && service.startsWith('s3-')) {\n region = service.slice(3).replace(/^fips-|^external-1/, '');\n service = 's3';\n } else if (service.endsWith('-fips')) {\n service = service.slice(0, -5);\n } else if (region && /-\\d$/.test(service) && !/-\\d$/.test(region)) {\n[service, region] = [region, service];\n }\n return [HOST_SERVICES[service] || service, region || '']\n}\n\nexport { AwsClient, AwsV4Signer };\n","import { AwsClient } from \"aws4fetch\";\nimport type { Credentials, CredentialsProvider } from \"./types.ts\";\n\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\nfunction buildAwsClient(creds: Credentials, region: string): AwsClient {\n return new AwsClient({\n accessKeyId: creds.accessKeyId,\n secretAccessKey: creds.secretAccessKey,\n sessionToken: creds.sessionToken,\n region,\n service: \"s3\",\n });\n}\n\nexport function refreshingSigner(opts: {\n region: string;\n credentials: Credentials | CredentialsProvider;\n now?: () => number;\n}): (req: Request) => Promise<Request> {\n const region = opts.region;\n const now = opts.now ?? (() => Date.now());\n\n if (typeof opts.credentials !== \"function\") {\n const aws = buildAwsClient(opts.credentials, region);\n return (req) => aws.sign(req);\n }\n\n const provider = opts.credentials;\n let cached: { aws: AwsClient; expiresAt: number } | null = null;\n let inFlight: Promise<AwsClient> | null = null;\n\n const resolve = async (): Promise<AwsClient> => {\n if (cached !== null && cached.expiresAt - REFRESH_BUFFER_MS > now()) {\n return cached.aws;\n }\n if (inFlight !== null) {\n return inFlight;\n }\n inFlight = (async () => {\n try {\n const creds = await provider();\n const aws = buildAwsClient(creds, region);\n const expiresAt = creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY;\n cached = { aws, expiresAt };\n return aws;\n } finally {\n inFlight = null;\n }\n })();\n return inFlight;\n };\n\n return async (req) => {\n const aws = await resolve();\n return aws.sign(req);\n };\n}\n","import type { Storage } from \"@baerly/protocol\";\nimport { S3HttpStorage } from \"./s3-http.ts\";\nimport { refreshingSigner } from \"./credentials/signer.ts\";\nimport type { Credentials, CredentialsProvider } from \"./credentials/types.ts\";\n\nfunction buildS3Storage(opts: {\n endpoint: string;\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n const sign = refreshingSigner({ region: opts.region, credentials: opts.credentials });\n return new S3HttpStorage({ endpoint: opts.endpoint, bucket: opts.bucket, sign });\n}\n\n/**\n * AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard\n * `aws4fetch` SigV4 signer. The endpoint is derived from the region as\n * `https://s3.<region>.amazonaws.com`.\n *\n * @example Static credentials\n * ```ts\n * import { s3Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n *\n * @example EKS (refreshing) — auto-detects Pod Identity or IRSA\n * ```ts\n * import { s3Storage, fromEks } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: fromEks(),\n * });\n * ```\n */\nexport function s3Storage(opts: {\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://s3.${opts.region}.amazonaws.com`,\n region: opts.region,\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Cloudflare R2 `Storage` factory (S3-compat endpoint). Derives the\n * endpoint from `accountId` as\n * `https://<accountId>.r2.cloudflarestorage.com` and pins region\n * `\"auto\"` — R2 ignores region but `aws4fetch`'s signer requires\n * the field to be set.\n *\n * For Workers that have a native R2 binding (no HTTP hop), see\n * `r2BindingStorage` in `@baerly/adapter-cloudflare`. This factory\n * is for Node hosts that talk to R2 over its public S3-compat URL.\n *\n * @example\n * ```ts\n * import { r2Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = r2Storage({\n * accountId: process.env[\"R2_ACCOUNT_ID\"]!,\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function r2Storage(opts: {\n accountId: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,\n region: \"auto\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Minio `Storage` factory — for local-dev / self-hosted S3-compat.\n * Endpoint is fully caller-supplied (e.g. `http://localhost:9102`)\n * because Minio deployments don't follow a URL template. Region is\n * pinned to `\"us-east-1\"`; Minio ignores it but `aws4fetch` requires\n * a value.\n *\n * @example\n * ```ts\n * import { minioStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = minioStorage({\n * endpoint: process.env[\"BAERLY_S3_ENDPOINT\"] ?? \"http://localhost:9102\",\n * bucket: \"baerly\",\n * credentials: {\n * accessKeyId: process.env[\"MINIO_ACCESS_KEY\"]!,\n * secretAccessKey: process.env[\"MINIO_SECRET_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function minioStorage(opts: {\n endpoint: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: opts.endpoint,\n region: \"us-east-1\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Google Cloud Storage `Storage` factory via the S3-compat endpoint\n * at `https://storage.googleapis.com`. Authentication uses GCS HMAC\n * keys (Console → Settings → Interoperability) — the HMAC access key\n * goes into `credentials.accessKeyId` and the HMAC secret goes into\n * `credentials.secretAccessKey`. Region is pinned to `\"auto\"`.\n *\n * GCS's S3-compat surface covers the four `Storage` methods\n * (`get`/`put`/`delete`/`list`), but Google documents the\n * `If-Match`/`If-None-Match` headers this kernel coordinates on as\n * read-only (native conditional writes use `x-goog-if-generation-match`).\n * Whether GCS's interop layer enforces S3-style conditional *writes* is\n * unverified — run `baerly doctor --bucket=<your-gcs-bucket>` before\n * relying on it; a backend that fails the CAS probe is not a safe baerly\n * store. See ADR-002.\n *\n * @example\n * ```ts\n * import { gcsStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = gcsStorage({\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"GCS_HMAC_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"GCS_HMAC_SECRET\"]!,\n * },\n * });\n * ```\n */\nexport function gcsStorage(opts: {\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: \"https://storage.googleapis.com\",\n region: \"auto\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n","/**\n * Bucket URI parsing for the CLI surface. Consumed by every\n * `baerly admin <cmd>`, `baerly inspect`, and `baerly export`.\n *\n * Grammar:\n * - `s3://<bucket>[/<prefix>]` — S3-compatible HTTP. Creds via env\n * vars (`BAERLY_S3_ENDPOINT`, `BAERLY_S3_ACCESS_KEY_ID`,\n * `BAERLY_S3_SECRET_ACCESS_KEY`, `BAERLY_S3_REGION` — region\n * defaults to `us-east-1`).\n * - `file:///<absolute-path>` — `LocalFsStorage` rooted at the path.\n * Relative paths are rejected by the three-slash prefix.\n * - `memory://<bucket>` — `MemoryStorage` keyed via\n * `getOrCreateMemoryStorageForBucket`. Test-only.\n */\n\nimport { LocalFsStorage } from \"@baerly/dev\";\nimport { minioStorage, r2Storage, s3Storage } from \"@baerly/adapter-node\";\nimport { BaerlyError, getOrCreateMemoryStorageForBucket, type Storage } from \"@baerly/protocol\";\n\n/**\n * Result of `parseBucketUri`. `storage` is a constructed `Storage`\n * handle; `keyPrefix` is \"\" for an unprefixed bucket, or a non-empty\n * string ending in `/` for a prefixed one. The target side prepends\n * this to every emitted key.\n */\nexport interface ParsedBucketUri {\n storage: Storage;\n /** Empty for no-prefix; non-empty always ends with \"/\". */\n keyPrefix: string;\n}\n\n/**\n * Parse a bucket URI into a constructed `Storage` handle + optional\n * key prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — unsupported scheme, or an\n * `s3://` URI with a missing env var.\n */\nexport const parseBucketUri = async (uri: string): Promise<ParsedBucketUri> => {\n if (uri.startsWith(\"s3://\")) {\n const rest = uri.slice(5);\n const slash = rest.indexOf(\"/\");\n const bucket = slash === -1 ? rest : rest.slice(0, slash);\n const prefix = slash === -1 ? \"\" : rest.slice(slash + 1);\n if (bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `bucket URI: s3:// URI requires a bucket name (got ${JSON.stringify(uri)})`,\n );\n }\n const accessKeyId = requireEnv(\"BAERLY_S3_ACCESS_KEY_ID\");\n const secretAccessKey = requireEnv(\"BAERLY_S3_SECRET_ACCESS_KEY\");\n const region = process.env[\"BAERLY_S3_REGION\"] ?? \"us-east-1\";\n const endpoint = requireEnv(\"BAERLY_S3_ENDPOINT\");\n // Endpoint-pattern dispatch. AWS-shaped → `s3Storage`; R2-shaped →\n // `r2Storage`; anything else (user-supplied / Minio) → `minioStorage`\n // so the full endpoint flows through verbatim.\n const r2Host = endpoint.match(/^https?:\\/\\/([^./]+)\\.r2\\.cloudflarestorage\\.com\\b/i);\n const isAws = /^https?:\\/\\/s3(\\.[^.]+)?\\.amazonaws\\.com\\b/i.test(endpoint);\n const storage: Storage = pickS3Storage({\n r2Host,\n isAws,\n endpoint,\n bucket,\n accessKeyId,\n secretAccessKey,\n region,\n });\n return {\n storage,\n keyPrefix: normalizeKeyPrefix(prefix),\n };\n }\n if (uri.startsWith(\"file:///\")) {\n return { storage: new LocalFsStorage({ root: uri.slice(7) }), keyPrefix: \"\" };\n }\n if (uri.startsWith(\"memory://\")) {\n const bucket = uri.slice(9);\n if (bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `bucket URI: memory:// URI requires a bucket name (got ${JSON.stringify(uri)})`,\n );\n }\n return { storage: getOrCreateMemoryStorageForBucket(bucket), keyPrefix: \"\" };\n }\n throw new BaerlyError(\"InvalidConfig\", `bucket URI: unsupported URI ${JSON.stringify(uri)}`);\n};\n\nconst requireEnv = (name: string): string => {\n const v = process.env[name];\n if (v === undefined || v === \"\") {\n throw new BaerlyError(\"InvalidConfig\", `bucket URI: env var ${name} unset`);\n }\n return v;\n};\n\n// Endpoint-shape dispatch for `s3://...` URIs. Extracted so the parser\n// doesn't carry an inline nested ternary.\ninterface S3StoragePick {\n readonly r2Host: RegExpMatchArray | null;\n readonly isAws: boolean;\n readonly endpoint: string;\n readonly bucket: string;\n readonly accessKeyId: string;\n readonly secretAccessKey: string;\n readonly region: string;\n}\nconst pickS3Storage = (opts: S3StoragePick): Storage => {\n const { r2Host, isAws, endpoint, bucket, accessKeyId, secretAccessKey, region } = opts;\n if (r2Host !== null) {\n return r2Storage({\n accountId: r2Host[1]!,\n bucket,\n credentials: { accessKeyId, secretAccessKey },\n });\n }\n if (isAws) {\n return s3Storage({ region, bucket, credentials: { accessKeyId, secretAccessKey } });\n }\n return minioStorage({ endpoint, bucket, credentials: { accessKeyId, secretAccessKey } });\n};\n\n// \"/foo\" → \"foo/\"; \"\" → \"\"; \"foo/\" stays \"foo/\". S3 prefixes are\n// keystroke-significant; canonicalize to ensure the manifest pointer\n// at the target matches its source's encoding.\nconst normalizeKeyPrefix = (prefix: string): string => {\n if (prefix === \"\") {\n return \"\";\n }\n if (prefix.endsWith(\"/\")) {\n return prefix;\n }\n return `${prefix}/`;\n};\n","/**\n * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.\n *\n * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`\n * but lives in `@baerly/cli` so the validator/loader doesn't depend on\n * the rolldown'd umbrella bundle. The scaffolder emits the config file;\n * the CLI reads it. Both sides agree on the wire shape (informally —\n * the duplication is small and intentional).\n *\n * Resolution order:\n * 1. `<cwd>/baerly.config.ts`\n * 2. `<cwd>/baerly.config.js`\n * 3. `<cwd>/baerly.config.mjs`\n * 4. `<cwd>/baerly.config.json`\n *\n * The `.ts` form requires the user to have a TS-aware Node entry\n * point (`tsx`, `--experimental-strip-types`, or a build step that\n * produced the `.js` alongside). If `import()` throws on the `.ts`\n * file, we re-wrap as `InvalidConfig` with a hint pointing at the\n * `.js` / `.json` fallbacks.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n AUTH_CONFIG_VALUES,\n type AuthConfig,\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n} from \"@baerly/protocol\";\n\nexport interface AppConfig {\n readonly app: string;\n readonly tenant: string;\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Required. See `AuthConfig` for the per-value semantics. The loader\n * throws `BaerlyError(\"InvalidConfig\", ...)` when `auth` is missing or\n * not a member of `AUTH_CONFIG_VALUES`.\n */\n readonly auth: AuthConfig;\n readonly domain?: string;\n readonly requiredSecrets?: readonly string[];\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /** Absolute path to the repo root that contained the config. */\n readonly repoRoot: string;\n}\n\nconst CONFIG_BASENAMES: readonly string[] = [\n \"baerly.config.ts\",\n \"baerly.config.js\",\n \"baerly.config.mjs\",\n \"baerly.config.json\",\n];\n\n/**\n * Locate the first `baerly.config.*` file under `cwd`. Returns the\n * absolute path or `null` if none exists.\n *\n * Exported so the collection-aware loader (and future consumers) can\n * reuse the same resolution order without re-implementing it.\n */\nconst locateConfig = (cwd: string): string | null => {\n for (const base of CONFIG_BASENAMES) {\n const abs = resolve(cwd, base);\n if (existsSync(abs)) {\n return abs;\n }\n }\n return null;\n};\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to\n * `process.cwd()`). Validates the required fields and the\n * locked-shape optionals; returns an `AppConfig` decorated with the\n * `repoRoot` it was loaded from.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, default\n * export missing, or any field has the wrong shape / type.\n */\nexport const loadAppConfig = async (cwd: string = process.cwd()): Promise<AppConfig> => {\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`,\n );\n }\n\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to read ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n try {\n raw = JSON.parse(text) as unknown;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to parse ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n } else {\n let mod: { default?: unknown };\n try {\n mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n } catch (error) {\n const hint = cfgPath.endsWith(\".ts\")\n ? \" (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)\"\n : \"\";\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to load ${cfgPath}: ${(error as Error).message}${hint}`,\n error,\n );\n }\n raw = mod.default;\n }\n\n if (raw === undefined || typeof raw !== \"object\" || raw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`,\n );\n }\n\n const obj = raw as Record<string, unknown>;\n const app = obj[\"app\"];\n const tenant = obj[\"tenant\"];\n const target = obj[\"target\"];\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`app\\` must be a non-empty string`,\n );\n }\n if (typeof tenant !== \"string\" || tenant.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`tenant\\` must be a non-empty string`,\n );\n }\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`target\\` must be \"cloudflare\" or \"node\" (got ${JSON.stringify(target)})`,\n );\n }\n\n // `auth` is a required typed posture as of the graduated-auth\n // redesign. The widening cast to `readonly string[]` is needed\n // because `.includes` on a tuple narrows its parameter to the\n // tuple's element type; widening locally is the standard idiom.\n const authRaw = obj[\"auth\"];\n if (typeof authRaw !== \"string\" || !(AUTH_CONFIG_VALUES as readonly string[]).includes(authRaw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`auth\\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`,\n );\n }\n const auth = authRaw as AuthConfig;\n\n const domainRaw = obj[\"domain\"];\n if (domainRaw !== undefined && typeof domainRaw !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`domain\\` must be a string when set`,\n );\n }\n\n const secretsRaw = obj[\"requiredSecrets\"];\n let requiredSecrets: readonly string[] | undefined;\n if (secretsRaw !== undefined) {\n if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === \"string\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`requiredSecrets\\` must be an array of strings`,\n );\n }\n requiredSecrets = secretsRaw as readonly string[];\n }\n\n const cfaRaw = obj[\"cloudflareAccess\"];\n let cloudflareAccess: AppConfig[\"cloudflareAccess\"];\n if (cfaRaw !== undefined) {\n if (typeof cfaRaw !== \"object\" || cfaRaw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess\\` must be an object when set`,\n );\n }\n const cfa = cfaRaw as Record<string, unknown>;\n const td = cfa[\"teamDomain\"];\n const aud = cfa[\"audienceTag\"];\n if (typeof td !== \"string\" || td.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.teamDomain\\` must be a non-empty string`,\n );\n }\n if (typeof aud !== \"string\" || aud.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.audienceTag\\` must be a non-empty string`,\n );\n }\n cloudflareAccess = { teamDomain: td, audienceTag: aud };\n }\n\n return {\n app,\n tenant,\n target,\n auth,\n ...(domainRaw !== undefined && { domain: domainRaw }),\n ...(requiredSecrets !== undefined && { requiredSecrets }),\n ...(cloudflareAccess !== undefined && { cloudflareAccess }),\n repoRoot: cwd,\n };\n};\n\n/**\n * Load the declared `IndexDefinition[]` for a single collection from a\n * `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count\n * probes) and `baerly admin rebuild-index` (resolving the `on` field).\n *\n * `.ts` configs are rejected — Node can't `import` them without a TS\n * loader; point at the compiled `.js` output instead.\n *\n * `commandName` is woven into thrown error messages so the operator\n * sees the calling command name in the prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `.ts` extension, JSON\n * parse error, missing default export, or missing\n * `collections[collection]`.\n */\nexport const loadCollectionIndexes = async (\n configPath: string,\n collection: string,\n commandName: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const abs = configPath.startsWith(\"file://\") ? fileURLToPath(configPath) : resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n return cfg.collections?.[collection]?.indexes ?? [];\n};\n"],"x_google_ignoreList":[7,10],"mappings":";;;;;;;;;;;;;AAKA,MAAa,gBAAgB;;;;;AAuG7B,MAAa,4BAAoC;;;;;;;;;;AAoDjD,MAAa,wBAAgC;;;;;;;;AAsB7C,MAAa,4BAAoC;;;;;;AAiCjD,MAAa,0BAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC/C,MAAa,yBAAiC,QAAc,KAAK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