@gusto/baerly-storage 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +38 -39
  53. package/dist/dev-vite.js +67 -36
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/sha256-4FfGQNPw.js +22 -0
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/sigv4-sign-5IUflUD_.js +507 -0
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,222 +0,0 @@
1
- //#region packages/protocol/src/constants.ts
2
- /**
3
- * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key
4
- * over this fails the PUT with an opaque provider 400; baerly surfaces
5
- * it early as InvalidConfig. See docs/spec/storage-compatibility.md.
6
- */
7
- const MAX_KEY_BYTES = 1024;
8
- /**
9
- * Backoff (in milliseconds) inserted between LIST attempts when S3
10
- * returns 429 (rate-limited).
11
- */
12
- const RATE_LIMIT_BACKOFF_MILLIS = 1e3;
13
- /**
14
- * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):
15
- * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`
16
- * (rather than silently truncating reads). A runaway alarm only — the
17
- * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means
18
- * maintenance is off or the collection is far past graduation.
19
- *
20
- * @see packages/server/src/log-tail.ts (`probeTailFrom`)
21
- */
22
- const LOG_FORWARD_PROBE_CAP = 1e5;
23
- /**
24
- * MIME type written for `current.json` PUTs. S3 round-trips this on
25
- * subsequent GETs; useful for diagnostics when staring at a bucket
26
- * via the AWS console.
27
- *
28
- * @see packages/protocol/src/coordination/current-json.ts
29
- */
30
- const CURRENT_JSON_CONTENT_TYPE = "application/json";
31
- /**
32
- * MIME type written for `gc/pending.json` PUTs.
33
- *
34
- * @see packages/protocol/src/coordination/gc-pending.ts
35
- */
36
- const GC_PENDING_CONTENT_TYPE = "application/json";
37
- /**
38
- * Default grace period between "marking" a key for GC and "sweeping"
39
- * (deleting) it. 7 days, chosen to span the worst plausible writer-
40
- * retry window (a paused-process writer that resumes hours later
41
- * should still find its idempotency anchor on the bucket). The
42
- * `runGc()` function accepts an override for tests.
43
- *
44
- * Why 7 days specifically:
45
- * - **1 day is too aggressive for batch workloads.** Worker isolate
46
- * scheduling pauses, cross-region replication lag, and
47
- * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly
48
- * exceed an hour under pathological conditions.
49
- * - **30 days is conservative beyond the worst plausible pause.**
50
- * Doubles `gc/pending.json` size at steady state and slows
51
- * visibility into "did GC actually run?" by 4×.
52
- * - **7 days spans the realistic upper bound** — long-running batch
53
- * jobs, multi-region propagation delays, queue backlogs, and
54
- * downstream outages the writer is retrying through. The protocol
55
- * is unaffected by the choice of value within the [hours, weeks]
56
- * range; this constant is the operator-tunable knob.
57
- *
58
- * Production code MUST NOT call `runGc` with `graceMillis` below the
59
- * default outside maintenance windows — going below the longest
60
- * plausible writer-retry latency risks deleting an anchor a writer
61
- * is about to find on retry. Test code that sets `graceMillis: 0` is
62
- * exercising the sweep path deliberately, not modelling production.
63
- *
64
- * @see packages/server/src/gc.ts
65
- */
66
- const GC_GRACE_PERIOD_MILLIS = 10080 * 60 * 1e3;
67
- /**
68
- * Cap on candidates kept in `gc/pending.json` to bound the size of
69
- * the file. The compactor marks at most this many candidates per
70
- * pass; subsequent passes pick up the rest. Larger collections will
71
- * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which
72
- * is acceptable.
73
- *
74
- * @see packages/server/src/gc.ts
75
- */
76
- const GC_MAX_PENDING_CANDIDATES = 1e3;
77
- /**
78
- * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also
79
- * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.
80
- *
81
- * @see packages/server/src/maintenance.ts
82
- */
83
- const MAINTENANCE_MIN_LIVE_BYTES = 64 * 1024;
84
- /**
85
- * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized
86
- * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable
87
- * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).
88
- *
89
- * @see docs/about/graduation.md
90
- * @see packages/server/src/maintenance.ts
91
- */
92
- const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT = 512 * 1024;
93
- /**
94
- * The largest snapshot a Cloudflare **free-tier** isolate can safely
95
- * rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN
96
- * THRESHOLD, not a runtime cap: an operator who raises
97
- * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker
98
- * risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets
99
- * CPU-killed MID-REBUILD — the CAS never lands, so the fold silently
100
- * never advances `log_seq_start` and the tail grows unbounded.
101
- *
102
- * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default
103
- * (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget
104
- * (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the
105
- * point where one-shot rebuild fills the budget with little margin, so
106
- * anything strictly larger is no longer free-tier-safe. On CF **paid**
107
- * (raised CPU limits), Node, or once §11 chunked snapshots land, a
108
- * larger ceiling is fine — hence this is a one-time `console.warn` at
109
- * handler init, NOT a hard rejection.
110
- *
111
- * @see packages/adapter-cloudflare/src/worker.ts
112
- * @see packages/server/src/maintenance.ts
113
- * @see docs/about/graduation.md
114
- */
115
- const CF_FREE_MAX_SAFE_FOLD_BYTES = 1024 * 1024;
116
- /**
117
- * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry
118
- * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021
119
- * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — bench
120
- * landed; paid recalibration deferred.
121
- *
122
- * @see docs/about/graduation.md
123
- * @see packages/server/src/maintenance.ts
124
- */
125
- const MAINTENANCE_MAX_FOLD_ROWS = 2048;
126
- /** CF-free profile; the absent-context default. */
127
- const MAINTENANCE_PROFILE_CF_FREE = {
128
- gcInterval: 4,
129
- gcMaxMarks: 20,
130
- gcMaxSweeps: 10,
131
- maxFoldEntriesPerPass: 20,
132
- maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
133
- maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
134
- };
135
- /** Node profile; 10× CF-free caps. */
136
- const MAINTENANCE_PROFILE_NODE = {
137
- gcInterval: 2,
138
- gcMaxMarks: 200,
139
- gcMaxSweeps: 100,
140
- maxFoldEntriesPerPass: 200,
141
- maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
142
- maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
143
- };
144
- /**
145
- * CF-paid profile — opt-in via `BAERLY_MAINTENANCE_PROFILE=cf-paid`. A paid
146
- * isolate keeps the CPU-killable single-phase shape but has the 10,000-
147
- * subrequest budget (vs free's 50), so it reuses the `NODE_MAINTENANCE_*`
148
- * per-pass caps. CRITICAL: snapshot ceilings `maxFoldBytes` (`C`) /
149
- * `maxFoldRows` (`E`) are UNCHANGED — a profile moves rate, never correctness
150
- * (the equivalence invariant); the memory wall is raised via
151
- * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`.
152
- *
153
- * @see packages/adapter-cloudflare/src/worker.ts
154
- * @see docs/about/graduation.md
155
- */
156
- const MAINTENANCE_PROFILE_CF_PAID = {
157
- gcInterval: 2,
158
- gcMaxMarks: 200,
159
- gcMaxSweeps: 100,
160
- maxFoldEntriesPerPass: 200,
161
- maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
162
- maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
163
- };
164
- /**
165
- * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate
166
- * memory — CF recycles isolates). ~once per this many writes.
167
- *
168
- * @see packages/protocol/src/coordination/current-json.ts
169
- * @see packages/server/src/maintenance.ts
170
- */
171
- const MAINTENANCE_WARN_INTERVAL_WRITES = 1e3;
172
- /**
173
- * Stable seed for `CurrentJson.snapshot === null` when building the
174
- * opaque `_meta.manifest_pointer` cursor emitted on read responses.
175
- * The literal no longer appears by itself on the wire; it is folded
176
- * into the server-side digest so the cursor never exposes physical
177
- * snapshot keys.
178
- *
179
- * @see packages/server/src/contract.ts (HttpOkMeta)
180
- */
181
- const MANIFEST_POINTER_EMPTY_SNAPSHOT = "none";
182
- /**
183
- * Keys that must never propagate through {@link merge}: assigning to
184
- * them on a plain object pollutes the prototype chain. The literal
185
- * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)
186
- * and bypasses `Object.keys`, but `JSON.parse('{"__proto__":...}')`
187
- * produces a real own property — which is exactly how a malicious
188
- * HTTP PATCH body would arrive on the wire.
189
- *
190
- * Lifted to a constant so every iteration path that touches a
191
- * caller-supplied object can re-use the same defence without
192
- * duplicating the keyword list.
193
- *
194
- * @see packages/protocol/src/json.ts (merge)
195
- * @see docs/spec/json-merge-patch.md
196
- */
197
- const FORBIDDEN_MERGE_KEYS = /* @__PURE__ */ new Set([
198
- "__proto__",
199
- "constructor",
200
- "prototype"
201
- ]);
202
- /**
203
- * Locked error wording for the "no auth configured" failure mode. The
204
- * adapter throws this when neither `config.auth` nor `verifier:`
205
- * resolves a real `Verifier`. Pinned via a regression test so future
206
- * refactors do not drift the operator-facing wording.
207
- *
208
- * Consumed by:
209
- * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)
210
- * - `packages/adapter-node/src/server.ts` (first-fetch throw)
211
- * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)
212
- */
213
- const NO_AUTH_CONFIGURED_MESSAGE = "baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.";
214
- /**
215
- * Locked error wording for `auth: "shared-secret"` + missing env var.
216
- * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.
217
- */
218
- const SHARED_SECRET_MISSING_MESSAGE = "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.";
219
- //#endregion
220
- export { SHARED_SECRET_MISSING_MESSAGE as _, GC_MAX_PENDING_CANDIDATES as a, MAINTENANCE_MIN_LIVE_BYTES as c, MAINTENANCE_PROFILE_NODE as d, MAINTENANCE_WARN_INTERVAL_WRITES as f, RATE_LIMIT_BACKOFF_MILLIS as g, NO_AUTH_CONFIGURED_MESSAGE as h, GC_GRACE_PERIOD_MILLIS as i, MAINTENANCE_PROFILE_CF_FREE as l, MAX_KEY_BYTES as m, CURRENT_JSON_CONTENT_TYPE as n, GC_PENDING_CONTENT_TYPE as o, MANIFEST_POINTER_EMPTY_SNAPSHOT as p, FORBIDDEN_MERGE_KEYS as r, LOG_FORWARD_PROBE_CAP as s, CF_FREE_MAX_SAFE_FOLD_BYTES as t, MAINTENANCE_PROFILE_CF_PAID as u };
221
-
222
- //# sourceMappingURL=constants-CfeMWQWk.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants-CfeMWQWk.js","names":[],"sources":["../packages/protocol/src/constants.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"],"mappings":";;;;;;AAKA,MAAa,gBAAgB;;;;;AAuG7B,MAAa,4BAAoC;;;;;;;;;;AAoDjD,MAAa,wBAAgC;;;;;;;;AAsB7C,MAAa,4BAAoC;;;;;;AAiCjD,MAAa,0BAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC/C,MAAa,yBAAiC,QAAc,KAAK;;;;;;;;;;AAWjE,MAAa,4BAAoC;;;;;;;AAqCjD,MAAa,6BAAqC,KAAK;;;;;;;;;AAqHvD,MAAa,qCAA6C,MAAM;;;;;;;;;;;;;;;;;;;;;;;AAyBhE,MAAa,8BAAsC,OAAO;;;;;;;;;;AAW1D,MAAa,4BAAoC;;AAajD,MAAa,8BAAuD;CAClE,YAAA;CACA,YAAA;CACA,aAAA;CACA,uBAAA;CACA,cAAc;CACd,aAAa;AACf;;AAGA,MAAa,2BAAoD;CAC/D,YAAA;CACA,YAAA;CACA,aAAA;CACA,uBAAA;CACA,cAAc;CACd,aAAa;AACf;;;;;;;;;;;;;AAcA,MAAa,8BAAuD;CAClE,YAAA;CACA,YAAA;CACA,aAAA;CACA,uBAAA;CACA,cAAc;CACd,aAAa;AACf;;;;;;;;AASA,MAAa,mCAA2C;;;;;;;;;;AAmCxD,MAAa,kCAA0C;;;;;;;;;;;;;;;;AAiBvD,MAAa,uCAA4C,IAAI,IAAI;CAC/D;CACA;CACA;AACF,CAAC;;;;;;;;;;;;AA6CD,MAAa,6BACX;;;;;AAMF,MAAa,gCACX"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-DRZ3tZ5l.js","names":["#counters","#gauges","#histograms"],"sources":["../packages/protocol/src/metrics.ts","../packages/server/src/observability/recorder.ts","../packages/server/src/observability/context.ts"],"sourcesContent":["/**\n * `MetricsRecorder` — internal emission contract for the six\n * load-bearing kernel metrics. Writer / compactor / GC emit through\n * an instance of this interface; in production the instance is the\n * per-request `RequestScopedMetricsRecorder` on the active\n * `ObservabilityContext`, and emissions flow onto the canonical line\n * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and\n * wrap their workload in `runWithContext` to attach it.\n *\n * Operators do not wire a custom sink against this interface — the\n * operator's view of kernel emissions is the canonical line on\n * stdout (one JSON object per HTTP request).\n *\n * **Naming convention** matches the load-bearing metrics:\n * - `db.write.class_a_ops_per_logical_write` — histogram (recommend p99 alert ~5; not gated).\n * Includes one Class A op per index PUT + index DELETE emitted\n * in the commit's fence. Idle-reader cost is unchanged.\n * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)\n * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)\n * - `db.write.index_ops_per_logical_write` — histogram.\n * `K (PUT) + L (DELETE)` per commit. Per-collection label.\n * - `db.manifest.lag_window_depth` — gauge (alert at >100)\n * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)\n * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)\n * - `db.compact.entries_folded` — histogram (entries folded per run)\n * - `db.gc.swept_total` — counter (labelled by reason)\n *\n * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase\n * snake_case segments. Labels are flat\n * `Readonly<Record<string, string>>` — no numbers, no nested objects.\n *\n * Metric emissions never throw on the hot path; the default\n * `noopMetricsRecorder` cannot throw.\n */\nexport interface MetricsRecorder {\n /** Monotonically-incrementing event count. */\n counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Point-in-time value. */\n gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n /** Distribution sample. */\n histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;\n}\n\n/**\n * No-op recorder. Safe default when no operator sink is wired —\n * emission sites that read `getCurrentContext()?.recorder` fall\n * back to this outside an active `runWithContext` scope.\n */\nexport const noopMetricsRecorder: MetricsRecorder = {\n counter: (): void => {},\n gauge: (): void => {},\n histogram: (): void => {},\n};\n","/**\n * Per-request `MetricsRecorder` whose primary product is the\n * canonical-line attribute set.\n *\n * `RequestScopedMetricsRecorder` is a deliberately tiny extension to\n * the {@link MetricsRecorder} interface that adds two readers\n * (`snapshot()` for tests / debug, `summarize()` for the canonical\n * log line). Every method just appends a row to a flat array — no\n * sorting, no JSON, no aggregation on the hot path. The work happens\n * once at end-of-request inside `summarize()`.\n *\n * The shape mirrors {@link InMemoryMetricsRecorder} from\n * `../_internal/in-memory-metrics.ts` but adds the per-request product. We do\n * NOT extend that class — composition over inheritance, and the\n * observability layer wants `summarize()` to be the only side-channel.\n */\n\nimport type { MetricsRecorder } from \"@baerly/protocol\";\n\n/** One observation row, kept in insertion order. */\nexport interface ObservationRow {\n readonly name: string;\n readonly value: number;\n readonly labels: Readonly<Record<string, string>>;\n}\n\n/** Result of {@link RequestScopedMetricsRecorder.snapshot}. */\nexport interface MetricsSnapshot {\n readonly counters: readonly ObservationRow[];\n readonly gauges: readonly ObservationRow[];\n readonly histograms: readonly ObservationRow[];\n}\n\n/** Flat per-metric aggregation as consumed by the canonical line. */\nexport type MetricsSummary = Record<string, number>;\n\n/**\n * Implementation. Allocations:\n *\n * - Three arrays at construction time, grown on each emission.\n * - On `summarize()` we materialize one extra `Map` per metric-\n * family (counter / gauge / histogram) plus a copy of each\n * histogram's values for sorting.\n *\n * CPU-ms budget on Workers is tight; we deliberately defer all of\n * that to flush time.\n */\nexport class RequestScopedMetricsRecorder implements MetricsRecorder {\n readonly #counters: ObservationRow[] = [];\n readonly #gauges: ObservationRow[] = [];\n readonly #histograms: ObservationRow[] = [];\n\n counter(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#counters.push({ name, value, labels });\n }\n gauge(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#gauges.push({ name, value, labels });\n }\n histogram(name: string, value: number, labels: Readonly<Record<string, string>> = {}): void {\n this.#histograms.push({ name, value, labels });\n }\n\n /**\n * Read-only view of every observation seen so far. Intended for\n * tests + structured debugging; the canonical-line flusher uses\n * {@link summarize} instead.\n *\n * @internal Not part of the published observability surface; tests\n * import via relative path. Production reads via {@link summarize}.\n */\n snapshot(): MetricsSnapshot {\n return {\n counters: this.#counters.slice(),\n gauges: this.#gauges.slice(),\n histograms: this.#histograms.slice(),\n };\n }\n\n /**\n * Flat aggregation, keyed by metric name with suffixes baked in:\n *\n * - Counter `db.foo.bar` → `db.foo.bar_total` (sum of all observations)\n * - Gauge `db.foo.bar` → `db.foo.bar` (last value seen)\n * - Histogram `db.foo.bar` → `db.foo.bar_count` (number of observations)\n * + `db.foo.bar_sum` (sum of values)\n *\n * Histogram aggregation is a single pass in insertion order — no\n * sort. Returns numbers only — labels are NOT collapsed into keys;\n * if a metric is emitted with different label sets, its\n * observations are aggregated together by `name` alone. The\n * canonical line is per-request anyway; per-label fan-out belongs\n * to the operator's long-term recorder.\n */\n summarize(): MetricsSummary {\n const out: MetricsSummary = {};\n\n // Counters: sum.\n for (const row of this.#counters) {\n // Counter convention: prefer the emitter's name verbatim. If the\n // emitter already namespaced its counter with `_total` (Prometheus\n // convention — see packages/server/src/observability/storage.ts),\n // do not double-append. Otherwise append for canonical-line\n // consumers that key off the `_total` suffix.\n const key = row.name.endsWith(\"_total\") ? row.name : `${row.name}_total`;\n out[key] = (out[key] ?? 0) + row.value;\n }\n\n // Gauges: last write wins per name (observations are in\n // insertion order; iterate forward and overwrite).\n for (const row of this.#gauges) {\n out[row.name] = row.value;\n }\n\n // Histograms: bucket-by-name, then emit `_count` + `_sum`.\n const buckets = new Map<string, { count: number; sum: number }>();\n for (const row of this.#histograms) {\n let agg = buckets.get(row.name);\n if (agg === undefined) {\n agg = { count: 0, sum: 0 };\n buckets.set(row.name, agg);\n }\n agg.count += 1;\n agg.sum += row.value;\n }\n for (const [name, { count, sum }] of buckets) {\n out[`${name}_count`] = count;\n out[`${name}_sum`] = sum;\n }\n\n return out;\n }\n}\n","/**\n * Per-request observability context.\n *\n * One `ObservabilityContext` is created at the entry of each unit-of-\n * work (HTTP request, maintenance tick, GC sweep, rebuild run) and\n * carried through the call tree via {@link runWithContext} /\n * {@link getCurrentContext}, which delegates to a single module-level\n * `AsyncLocalStorage` instance.\n *\n * The context is intentionally tiny: an externally-set\n * {@link request_id}, a high-resolution `started_at`, and a mutable\n * {@link fields} bag used to accumulate canonical-line attributes\n * during the unit's lifecycle.\n *\n * The context shape is `readonly` everywhere it can be — only the\n * contents of `fields` are intended to mutate during a request. The\n * {@link fields} map itself is not `readonly` because callers (the\n * canonical-line emitter, middleware, the collection API once Dispatch\n * 3+ wires it up) need to set entries.\n *\n * The context carries no sampling state — every unit-of-work emits\n * one canonical line unconditionally; there is nothing to gate.\n *\n * ## Time source\n *\n * `started_at` uses `performance.now()` so durations can be\n * computed without worrying about wall-clock skew (NTP step,\n * leap-second smearing). `performance.now()` is part of both Node\n * 18+ and the Workers Runtime; we don't fall back to `Date.now()`.\n *\n * @example\n * ```ts\n * const ctx = createObservabilityContext({});\n * await runWithContext(ctx, async () => {\n * const inner = getCurrentContext();\n * inner?.fields.set(\"collection\", \"tickets\");\n * await doWork();\n * });\n * ```\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n// Type-only import — `maintenance.ts` imports this module's runtime\n// values (`getCurrentContext`), so a value import here would form a\n// runtime cycle. A type-only edge erases at build time, so tsgo /\n// rolldown see no cycle.\nimport type { MaintenanceDispatch } from \"../maintenance.ts\";\nimport { RequestScopedMetricsRecorder } from \"./recorder.ts\";\n\n/** Read-mostly per-request observability state. */\nexport interface ObservabilityContext {\n /** Externally-correlatable request identifier (UUID-ish). */\n readonly request_id: string;\n /** Monotonic `performance.now()` reading captured at construction. */\n readonly started_at: number;\n /**\n * Mutable bag for canonical-line attributes. Callers `obs.fields.set(\"k\", v)`;\n * the canonical-line flusher spreads this onto the emitted properties at\n * end-of-request.\n */\n readonly fields: Map<string, unknown>;\n /**\n * Per-request metrics bag. Lives on the context so adapters can\n * reach it from inside the `Db`'s `MetricsRecorder` callback via\n * `getCurrentContext()?.recorder` — no parallel `AsyncLocalStorage`\n * lookup. The canonical-line flusher reads its `summarize()` at\n * end-of-request and spreads the result onto the emitted line.\n */\n readonly recorder: RequestScopedMetricsRecorder;\n /**\n * Per-request write-tick maintenance dispatch config. Set by the\n * adapter (NOT `Db.create`) so the inherently-per-request\n * `dispatch = ctx.waitUntil` and the env-var-derived caps ride the\n * same scope the kernel write-tick reads from. The {@link Writer}\n * consults `getCurrentContext()?.maintenance` at the post-commit\n * dispatch point. Absent ⇒ inline dispatch + CF-free-safe caps.\n */\n readonly maintenance?: MaintenanceDispatch;\n}\n\n/**\n * Optional construction inputs. All fields are optional so callers in\n * unit-of-work entry middleware (HTTP router, maintenance scheduler)\n * can pass only what they have. Defaults:\n *\n * - `request_id`: a fresh `crypto.randomUUID()`. Pass an externally-\n * supplied id (`X-Request-Id` header, scheduler-supplied tag) to\n * propagate correlation downstream.\n * - `recorder`: a fresh {@link RequestScopedMetricsRecorder}. Tests can\n * pass an externally-constructed recorder to assert on its\n * `snapshot()` after the unit-of-work completes; production callers\n * should accept the default.\n */\nexport interface ObservabilityContextInit {\n readonly request_id?: string;\n readonly recorder?: RequestScopedMetricsRecorder;\n /** Write-tick maintenance dispatch config. See {@link ObservabilityContext.maintenance}. */\n readonly maintenance?: MaintenanceDispatch;\n}\n\n/**\n * Factory for {@link ObservabilityContext}. We use a factory rather\n * than a class so consumers can structural-type the result and so\n * the `AsyncLocalStorage` slot type stays a plain interface — no\n * surprises around `instanceof` across realms (Workers vs Node).\n */\nexport const createObservabilityContext = (\n init: ObservabilityContextInit = {},\n): ObservabilityContext => ({\n request_id: init.request_id ?? crypto.randomUUID(),\n started_at: performance.now(),\n fields: new Map(),\n recorder: init.recorder ?? new RequestScopedMetricsRecorder(),\n ...(init.maintenance !== undefined && { maintenance: init.maintenance }),\n});\n\n/**\n * Module-level slot. One instance per process — the Workers\n * Runtime's `nodejs_compat` flag wires `node:async_hooks` to a\n * per-request scope, so cross-request bleed is impossible there.\n */\nconst als = new AsyncLocalStorage<ObservabilityContext>();\n\n/**\n * Run `fn` with `ctx` active as the current observability context.\n * Inside `fn` (and any `await`-chained continuation rooted in `fn`),\n * {@link getCurrentContext} returns `ctx`. Outside, it returns the\n * previously-active context (or `undefined`).\n *\n * `runWithContext` is async-safe via `AsyncLocalStorage`; it propagates\n * through `await`, `Promise.all`, `setTimeout`, and `queueMicrotask`.\n *\n * Returns `fn`'s return value verbatim — including its promise\n * identity, so callers can `await` or chain off it without extra\n * indirection.\n */\nexport const runWithContext = <T>(\n ctx: ObservabilityContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> => als.run(ctx, fn);\n\n/** Returns the currently-active context, or `undefined` outside one. */\nexport const getCurrentContext = (): ObservabilityContext | undefined => als.getStore();\n"],"mappings":";;;;;;;AAgDA,MAAa,sBAAuC;CAClD,eAAqB,CAAC;CACtB,aAAmB,CAAC;CACpB,iBAAuB,CAAC;AAC1B;;;;;;;;;;;;;;ACLA,IAAa,+BAAb,MAAqE;CACnE,YAAuC,CAAC;CACxC,UAAqC,CAAC;CACtC,cAAyC,CAAC;CAE1C,QAAQ,MAAc,OAAe,SAA2C,CAAC,GAAS;EACxF,KAAKA,UAAU,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC7C;CACA,MAAM,MAAc,OAAe,SAA2C,CAAC,GAAS;EACtF,KAAKC,QAAQ,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC3C;CACA,UAAU,MAAc,OAAe,SAA2C,CAAC,GAAS;EAC1F,KAAKC,YAAY,KAAK;GAAE;GAAM;GAAO;EAAO,CAAC;CAC/C;;;;;;;;;CAUA,WAA4B;EAC1B,OAAO;GACL,UAAU,KAAKF,UAAU,MAAM;GAC/B,QAAQ,KAAKC,QAAQ,MAAM;GAC3B,YAAY,KAAKC,YAAY,MAAM;EACrC;CACF;;;;;;;;;;;;;;;;CAiBA,YAA4B;EAC1B,MAAM,MAAsB,CAAC;EAG7B,KAAK,MAAM,OAAO,KAAKF,WAAW;GAMhC,MAAM,MAAM,IAAI,KAAK,SAAS,QAAQ,IAAI,IAAI,OAAO,GAAG,IAAI,KAAK;GACjE,IAAI,QAAQ,IAAI,QAAQ,KAAK,IAAI;EACnC;EAIA,KAAK,MAAM,OAAO,KAAKC,SACrB,IAAI,IAAI,QAAQ,IAAI;EAItB,MAAM,0BAAU,IAAI,IAA4C;EAChE,KAAK,MAAM,OAAO,KAAKC,aAAa;GAClC,IAAI,MAAM,QAAQ,IAAI,IAAI,IAAI;GAC9B,IAAI,QAAQ,KAAA,GAAW;IACrB,MAAM;KAAE,OAAO;KAAG,KAAK;IAAE;IACzB,QAAQ,IAAI,IAAI,MAAM,GAAG;GAC3B;GACA,IAAI,SAAS;GACb,IAAI,OAAO,IAAI;EACjB;EACA,KAAK,MAAM,CAAC,MAAM,EAAE,OAAO,UAAU,SAAS;GAC5C,IAAI,GAAG,KAAK,WAAW;GACvB,IAAI,GAAG,KAAK,SAAS;EACvB;EAEA,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzBA,MAAa,8BACX,OAAiC,CAAC,OACR;CAC1B,YAAY,KAAK,cAAc,OAAO,WAAW;CACjD,YAAY,YAAY,IAAI;CAC5B,wBAAQ,IAAI,IAAI;CAChB,UAAU,KAAK,YAAY,IAAI,6BAA6B;CAC5D,GAAI,KAAK,gBAAgB,KAAA,KAAa,EAAE,aAAa,KAAK,YAAY;AACxE;;;;;;AAOA,MAAM,MAAM,IAAI,kBAAwC;;;;;;;;;;;;;;AAexD,MAAa,kBACX,KACA,OACmB,IAAI,IAAI,KAAK,EAAE;;AAGpC,MAAa,0BAA4D,IAAI,SAAS"}
@@ -1,203 +0,0 @@
1
- import { r as parseBucketUri } from "./config-1tv0-Yzm.js";
2
- import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
3
- import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
4
- import { estimateWritesPerMin } from "./usage-DBV1eQHC.js";
5
- //#region src/cost/provider.ts
6
- const detectProvider = (args) => {
7
- if (args.override !== void 0) return args.override;
8
- if (args.bucketUri.startsWith("file://")) return "dev";
9
- if (args.bucketUri.startsWith("memory://")) return "dev";
10
- if (!args.bucketUri.startsWith("s3://")) return "self-hosted";
11
- const endpoint = args.s3Endpoint ?? "";
12
- if (endpoint === "") return "aws-s3";
13
- if (/\.r2\.cloudflarestorage\.com(:\d+)?\/?$/i.test(endpoint)) return "r2";
14
- if (/\.amazonaws\.com(:\d+)?\/?$/i.test(endpoint)) return "aws-s3";
15
- return "self-hosted";
16
- };
17
- /**
18
- * R2 price table.
19
- * Source: <https://developers.cloudflare.com/r2/pricing/> (review date 2026-05-17).
20
- * Change-control: pair every edit with a `docs/about/pricing-log.md` entry.
21
- */
22
- const R2_PRICING = {
23
- provider: "r2",
24
- freeClassAPerMonth: 1e6,
25
- usdPerMillionClassA: 4.5,
26
- freeStorageGb: 10,
27
- usdPerGbMonth: .015,
28
- effectiveWriteAmp: 3
29
- };
30
- /**
31
- * AWS S3 (Standard) price table.
32
- * Source: <https://aws.amazon.com/s3/pricing/> (review date 2026-05-17).
33
- * The 12-month new-account free tier is intentionally excluded
34
- * (most operators are past it; reporting $0 to them would lie).
35
- */
36
- const AWS_S3_PRICING = {
37
- provider: "aws-s3",
38
- freeClassAPerMonth: 0,
39
- usdPerMillionClassA: 5,
40
- freeStorageGb: 0,
41
- usdPerGbMonth: .023,
42
- effectiveWriteAmp: 4
43
- };
44
- const SELF_HOSTED_PRICING = {
45
- provider: "self-hosted",
46
- freeClassAPerMonth: 0,
47
- usdPerMillionClassA: NaN,
48
- freeStorageGb: 0,
49
- usdPerGbMonth: NaN,
50
- effectiveWriteAmp: 4
51
- };
52
- const DEV_PRICING = {
53
- provider: "dev",
54
- freeClassAPerMonth: 0,
55
- usdPerMillionClassA: NaN,
56
- freeStorageGb: 0,
57
- usdPerGbMonth: NaN,
58
- effectiveWriteAmp: 4
59
- };
60
- const pricingFor = (provider) => {
61
- switch (provider) {
62
- case "r2": return R2_PRICING;
63
- case "aws-s3": return AWS_S3_PRICING;
64
- case "self-hosted": return SELF_HOSTED_PRICING;
65
- case "dev": return DEV_PRICING;
66
- }
67
- };
68
- //#endregion
69
- //#region src/cost/project.ts
70
- /**
71
- * Graduation triggers — sustained for 7 days, any one of these
72
- * means the workload has outgrown baerly-storage's positioning.
73
- *
74
- * Source: `docs/about/cost-model.md:159-163`.
75
- */
76
- const GRADUATION_CLASS_A_PER_MONTH = 5e7;
77
- /**
78
- * Project a `writesPerMin` rate (typically from
79
- * `estimateWritesPerMin`) into a monthly cost trajectory.
80
- *
81
- * Returns `null` when `writesPerMin` is non-finite. The caller
82
- * (inspect) renders no footer in that case.
83
- */
84
- const project = (writesPerMin, storedBytes, pricing) => {
85
- if (!Number.isFinite(writesPerMin)) return null;
86
- const classAPerMonth = writesPerMin * 60 * 24 * 30 * pricing.effectiveWriteAmp;
87
- const percentOfGraduation = classAPerMonth / GRADUATION_CLASS_A_PER_MONTH * 100;
88
- const percentOfAdvisory = writesPerMin / 100 * 100;
89
- const percentOfFreeTier = pricing.freeClassAPerMonth > 0 ? classAPerMonth / pricing.freeClassAPerMonth * 100 : null;
90
- const storedGb = storedBytes / (1024 * 1024 * 1024);
91
- const withinFreeTier = pricing.freeClassAPerMonth > 0 && classAPerMonth <= pricing.freeClassAPerMonth && storedGb <= pricing.freeStorageGb;
92
- let projectedUsdPerMonth;
93
- if (Number.isNaN(pricing.usdPerMillionClassA)) projectedUsdPerMonth = null;
94
- else if (withinFreeTier) projectedUsdPerMonth = 0;
95
- else {
96
- const classAOverage = Math.max(0, classAPerMonth - pricing.freeClassAPerMonth);
97
- const storageOverage = Math.max(0, storedGb - pricing.freeStorageGb);
98
- projectedUsdPerMonth = classAOverage / 1e6 * pricing.usdPerMillionClassA + storageOverage * pricing.usdPerGbMonth;
99
- }
100
- return {
101
- writesPerMin,
102
- classAPerMonth,
103
- percentOfFreeTier,
104
- percentOfGraduation,
105
- percentOfAdvisory,
106
- projectedUsdPerMonth,
107
- withinFreeTier,
108
- provider: pricing.provider
109
- };
110
- };
111
- //#endregion
112
- //#region src/cost.ts
113
- const COST_ARGS = {
114
- bucket: BUCKET_ARG,
115
- app: APP_ARG,
116
- tenant: TENANT_ARG,
117
- collection: COLLECTION_ARG,
118
- provider: {
119
- type: "string",
120
- required: false,
121
- description: "Override pricing provider (r2|aws-s3|self-hosted|dev). Auto-detected from bucket URI + BAERLY_S3_ENDPOINT.",
122
- valueHint: "r2|aws-s3|self-hosted|dev"
123
- },
124
- json: JSON_ARG
125
- };
126
- /** Compact "1.5M" / "22k" / "842" rendering for Class A op counts. */
127
- const formatOps = (n) => {
128
- if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
129
- if (n >= 1e3) return `${(n / 1e3).toFixed(0)}k`;
130
- return n.toFixed(0);
131
- };
132
- /** Advisory line rendered when past 100 writes/min but under the 50M/mo graduation trigger. */
133
- const renderAdvisoryLine = (t) => {
134
- if (t.percentOfAdvisory < 100 || t.percentOfGraduation >= 100) return "";
135
- if (t.projectedUsdPerMonth === null) return " advisory: ~100 writes/min crossed. Object storage buys zero ops, no on-call,\n no migration; a managed DB trades those dollars for schema + SQL + ops.\n Hard graduation trigger: 50M Class A/mo. Self-hosted — bill model not modelled.\n";
136
- return ` advisory: ~100 writes/min crossed (${t.provider === "r2" ? "~$54/mo on R2" : "~$86/mo on S3"}, object-storage ops). Object storage buys\n zero ops, no on-call, and no migration for your bytes. A managed DB trades those\n dollars for a schema, SQL, and an ops surface. Review if that tradeoff\n makes sense for your workload. Hard graduation trigger: 50M Class A/mo.\n`;
137
- };
138
- /** Two-line trajectory block. Three output states per design spec §4.2. */
139
- const renderTrajectory = (t) => {
140
- const wpm = t.writesPerMin.toFixed(t.writesPerMin < 10 ? 1 : 0);
141
- const classA = formatOps(t.classAPerMonth);
142
- if (t.projectedUsdPerMonth === null) {
143
- const advisory = renderAdvisoryLine(t);
144
- return [
145
- ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo`,
146
- ` ${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger. Self-hosted — bill model not modelled.`,
147
- ...advisory ? [advisory] : []
148
- ].join("\n");
149
- }
150
- const usd = t.withinFreeTier ? `~$0 (R2 free tier)` : `~$${t.projectedUsdPerMonth.toFixed(2)}/mo`;
151
- const tail = t.withinFreeTier ? `${t.percentOfFreeTier.toFixed(0)}% of free-tier Class A budget. ${t.percentOfFreeTier < 50 ? "Well inside the promise." : "Approaching free-tier ceiling."}` : `${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger.`;
152
- const advisory = renderAdvisoryLine(t);
153
- return [
154
- ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo → ${usd}`,
155
- ` ${tail}`,
156
- ...advisory ? [advisory] : []
157
- ].join("\n");
158
- };
159
- const PROVIDER_TAGS = /* @__PURE__ */ new Set([
160
- "r2",
161
- "aws-s3",
162
- "self-hosted",
163
- "dev"
164
- ]);
165
- const bundle = defineBaerlySubcommand({
166
- name: "cost",
167
- meta: { description: "Project a collection's monthly Class A + storage cost trajectory." },
168
- args: COST_ARGS,
169
- handler: async (args, ctx) => {
170
- if (typeof args.provider === "string" && args.provider.length > 0) {
171
- if (!PROVIDER_TAGS.has(args.provider)) throw new BaerlyError("InvalidConfig", `baerly cost: --provider must be one of r2|aws-s3|self-hosted|dev (got ${JSON.stringify(args.provider)})`);
172
- }
173
- const bucket = await parseBucketUri(args.bucket);
174
- const { app, tenant } = await ctx.resolveAppTenant({
175
- app: args.app,
176
- tenant: args.tenant
177
- });
178
- assertCollectionArg(args.collection, "baerly cost");
179
- const override = typeof args.provider === "string" && args.provider.length > 0 ? args.provider : void 0;
180
- const provider = detectProvider({
181
- bucketUri: args.bucket,
182
- s3Endpoint: process.env["BAERLY_S3_ENDPOINT"],
183
- override
184
- });
185
- if (provider === "dev") throw new BaerlyError("InvalidConfig", `baerly cost: dev backends (file://, memory://) have no $ model; pass --provider=r2|aws-s3|self-hosted to project against one.`);
186
- const trajectory = project((await estimateWritesPerMin(bucket.storage, app, tenant, args.collection, { keyPrefix: bucket.keyPrefix })).writesPerMin, 0, pricingFor(provider));
187
- if (trajectory === null) throw new BaerlyError("InvalidConfig", `baerly cost: not enough log entries under ${args.collection} to estimate writes/min (need >= 2)`);
188
- if (isJsonMode()) emitSuccess({
189
- command: "cost",
190
- collection: args.collection,
191
- trajectory
192
- });
193
- else process.stdout.write(`baerly cost ${args.collection}\n${renderTrajectory(trajectory)}\n`);
194
- return 0;
195
- }
196
- });
197
- /** citty `defineCommand` block for `baerly cost`. */
198
- const cost = bundle.cmd;
199
- bundle.run;
200
- //#endregion
201
- export { cost };
202
-
203
- //# sourceMappingURL=cost-DSMIVqzL.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cost-DSMIVqzL.js","names":[],"sources":["../packages/cli/src/cost/provider.ts","../packages/cli/src/cost/project.ts","../packages/cli/src/cost.ts"],"sourcesContent":["/**\n * Provider sniffer: maps a bucket URI + optional S3 endpoint into a\n * pricing tag, and resolves that tag into a `ProviderPricing`\n * record. Pure — zero I/O.\n *\n * Detection rules (first match wins):\n * - `file://*` → \"dev\"\n * - `memory://*` → \"dev\"\n * - `s3://*` + endpoint matching `*.r2.cloudflarestorage.com` → \"r2\"\n * - `s3://*` + endpoint matching `*.amazonaws.com` → \"aws-s3\"\n * - `s3://*` + no endpoint → \"aws-s3\"\n * - everything else (Minio, Backblaze, on-prem, unknown s3 endpoint) → \"self-hosted\"\n *\n * `override` skips detection entirely — used by the\n * `baerly inspect --provider=...` CLI flag when auto-detection picks\n * wrong (e.g., a self-hosted S3 gateway in front of R2).\n */\n\nimport type { ProviderPricing } from \"./project.ts\";\n\nexport type ProviderTag = ProviderPricing[\"provider\"];\n\nexport interface DetectArgs {\n /** Raw bucket URI as passed on the CLI (s3://, file://, memory://). */\n readonly bucketUri: string;\n /** Effective S3 endpoint at parse time (typically `process.env[\"BAERLY_S3_ENDPOINT\"]`). */\n readonly s3Endpoint?: string;\n /** When set, skip detection and return this tag. */\n readonly override?: ProviderTag;\n}\n\nexport const detectProvider = (args: DetectArgs): ProviderTag => {\n if (args.override !== undefined) {\n return args.override;\n }\n if (args.bucketUri.startsWith(\"file://\")) {\n return \"dev\";\n }\n if (args.bucketUri.startsWith(\"memory://\")) {\n return \"dev\";\n }\n if (!args.bucketUri.startsWith(\"s3://\")) {\n return \"self-hosted\";\n }\n // s3:// branch — look at the endpoint.\n const endpoint = args.s3Endpoint ?? \"\";\n if (endpoint === \"\") {\n return \"aws-s3\";\n } // default AWS\n if (/\\.r2\\.cloudflarestorage\\.com(:\\d+)?\\/?$/i.test(endpoint)) {\n return \"r2\";\n }\n if (/\\.amazonaws\\.com(:\\d+)?\\/?$/i.test(endpoint)) {\n return \"aws-s3\";\n }\n return \"self-hosted\";\n};\n\n/**\n * R2 price table.\n * Source: <https://developers.cloudflare.com/r2/pricing/> (review date 2026-05-17).\n * Change-control: pair every edit with a `docs/about/pricing-log.md` entry.\n */\nconst R2_PRICING: ProviderPricing = {\n provider: \"r2\",\n freeClassAPerMonth: 1_000_000,\n usdPerMillionClassA: 4.5,\n freeStorageGb: 10,\n usdPerGbMonth: 0.015,\n effectiveWriteAmp: 3,\n};\n\n/**\n * AWS S3 (Standard) price table.\n * Source: <https://aws.amazon.com/s3/pricing/> (review date 2026-05-17).\n * The 12-month new-account free tier is intentionally excluded\n * (most operators are past it; reporting $0 to them would lie).\n */\nconst AWS_S3_PRICING: ProviderPricing = {\n provider: \"aws-s3\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: 5,\n freeStorageGb: 0,\n usdPerGbMonth: 0.023,\n effectiveWriteAmp: 4,\n};\n\nconst SELF_HOSTED_PRICING: ProviderPricing = {\n provider: \"self-hosted\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: Number.NaN,\n freeStorageGb: 0,\n usdPerGbMonth: Number.NaN,\n effectiveWriteAmp: 4,\n};\n\nconst DEV_PRICING: ProviderPricing = {\n provider: \"dev\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: Number.NaN,\n freeStorageGb: 0,\n usdPerGbMonth: Number.NaN,\n effectiveWriteAmp: 4,\n};\n\nexport const pricingFor = (provider: ProviderTag): ProviderPricing => {\n switch (provider) {\n case \"r2\": {\n return R2_PRICING;\n }\n case \"aws-s3\": {\n return AWS_S3_PRICING;\n }\n case \"self-hosted\": {\n return SELF_HOSTED_PRICING;\n }\n case \"dev\": {\n return DEV_PRICING;\n }\n }\n};\n","/**\n * Pure projection math for the `baerly inspect` cost-trajectory\n * footer. Zero I/O. Price tables live as top-level constants; every\n * change MUST be paired with a `docs/about/pricing-log.md` entry.\n *\n * Three rules:\n * 1. `classAPerMonth = writesPerMin × 60 × 24 × 30 × effectiveWriteAmp`\n * where `effectiveWriteAmp` (≈3 on Cloudflare, ≈4 on Node) is the\n * measured Class A ops/write INCLUDING in-band maintenance — see\n * `docs/spec/attachments/amortized-write-cost-baseline.json`. The\n * old \"× 2\" was the commit FLOOR only and undercounted maintenance.\n * 2. `projectedUsdPerMonth = 0` exactly when both `classAPerMonth\n * ≤ pricing.freeClassAPerMonth` AND `storedBytes ≤\n * pricing.freeStorageGb × 1GB`. Say `$0`, not `$0.00`. `null`\n * for self-hosted/dev (no $ model).\n * 3. Returns `null` when `writesPerMin` is non-finite (no-data case\n * from `estimateWritesPerMin`); inspect renders no footer.\n */\n\n/** R2 / AWS S3 / self-hosted / dev price table. */\nexport interface ProviderPricing {\n readonly provider: \"r2\" | \"aws-s3\" | \"self-hosted\" | \"dev\";\n /** Free-tier Class A ops per month; 0 if no free tier. */\n readonly freeClassAPerMonth: number;\n /** $/1M Class A above free tier. NaN for \"self-hosted\" / \"dev\". */\n readonly usdPerMillionClassA: number;\n /** Free-tier stored GB; 0 if no free tier. */\n readonly freeStorageGb: number;\n /** $/GB-month above free tier. NaN for \"self-hosted\" / \"dev\". */\n readonly usdPerGbMonth: number;\n /**\n * Effective Class A ops per logical write, INCLUDING in-band\n * maintenance (folds + GC) — NOT just the 2-op commit floor.\n * Empirically measured: ~3 on Cloudflare (cf-free profile), ~4 on\n * serverful Node (gcInterval=2 ⇒ ~2× the GC LISTs). Source:\n * docs/spec/attachments/amortized-write-cost-baseline.json (bench\n * `pnpm bench:amortized-write-cost`). Provider is the host proxy:\n * r2 ⇒ Cloudflare ⇒ 3; aws-s3 ⇒ Node ⇒ 4.\n */\n readonly effectiveWriteAmp: number;\n}\n\n/**\n * Graduation triggers — sustained for 7 days, any one of these\n * means the workload has outgrown baerly-storage's positioning.\n *\n * Source: `docs/about/cost-model.md:159-163`.\n */\nexport const GRADUATION_CLASS_A_PER_MONTH = 50_000_000;\n/**\n * Advisory crossing — eyes-open signal, NOT a hard stop.\n *\n * Keyed to a sustained WRITE RATE (100 writes/min, account-wide), not an\n * absolute Class A count, so it fires at the same workload on every\n * provider regardless of write-amp. On R2 (×3) that is ~13M Class A/mo\n * (~$54/mo object-storage ops); on S3 (×4) ~17.3M Class A/mo (~$86/mo).\n * The previous absolute 13M-Class-A threshold was R2-derived and, applied\n * to S3, fired at ~75 writes/min (~$65/mo) while the rendered note quoted\n * the 100-writes/min figure (~$86) — provider-inconsistent. Fires before\n * the 50M hard trigger to surface the ops-vs-cost tradeoff: object storage\n * buys zero ops / no on-call / no migration; a managed DB trades those\n * dollars for a schema, SQL, and an ops surface. Does NOT change the 50M\n * hard trigger.\n */\nexport const GRADUATION_ADVISORY_WRITES_PER_MIN = 100;\n// Storage graduation is a COST SIGNAL at the ~10 GB R2 free-tier line,\n// not a hard trigger — intentionally not represented as a graduation\n// constant. `storedBytes` feeds the dollar projection (storage overage)\n// but the projection surfaces no storage graduation %; the tooling\n// tracks only the 50M Class A/mo trigger. See cost-model.md. (The\n// historic `effective write-amp > 6` trigger is retired — see\n// pricing-log.md 2026-06-22 — and is not represented here either.)\n\n/** What the inspect footer renders from. */\nexport interface Trajectory {\n readonly writesPerMin: number;\n readonly classAPerMonth: number;\n /** Percent of provider's free-tier Class A budget. `null` when the provider has no free tier (aws-s3) or no $ model (self-hosted/dev). */\n readonly percentOfFreeTier: number | null;\n /** Percent of the 50M/mo graduation trigger. Always a finite number. */\n readonly percentOfGraduation: number;\n /** Percent of the 100-writes/min advisory threshold (provider-agnostic). Always a finite number. */\n readonly percentOfAdvisory: number;\n /** Projected USD/month. `0` when fully inside the free tier. `null` when the provider has no $ model (self-hosted/dev). */\n readonly projectedUsdPerMonth: number | null;\n readonly withinFreeTier: boolean;\n readonly provider: ProviderPricing[\"provider\"];\n}\n\n/**\n * Project a `writesPerMin` rate (typically from\n * `estimateWritesPerMin`) into a monthly cost trajectory.\n *\n * Returns `null` when `writesPerMin` is non-finite. The caller\n * (inspect) renders no footer in that case.\n */\nexport const project = (\n writesPerMin: number,\n storedBytes: number,\n pricing: ProviderPricing,\n): Trajectory | null => {\n if (!Number.isFinite(writesPerMin)) {\n return null;\n }\n\n const classAPerMonth = writesPerMin * 60 * 24 * 30 * pricing.effectiveWriteAmp;\n\n const percentOfGraduation = (classAPerMonth / GRADUATION_CLASS_A_PER_MONTH) * 100;\n // Advisory is a write-RATE crossing (provider-agnostic), not an absolute\n // Class A count — so it fires at the same 100 writes/min on R2 and S3\n // alike, rather than at a lower S3 rate where the rendered cost note\n // would be wrong. See GRADUATION_ADVISORY_WRITES_PER_MIN.\n const percentOfAdvisory = (writesPerMin / GRADUATION_ADVISORY_WRITES_PER_MIN) * 100;\n\n const percentOfFreeTier =\n pricing.freeClassAPerMonth > 0 ? (classAPerMonth / pricing.freeClassAPerMonth) * 100 : null;\n\n const storedGb = storedBytes / (1024 * 1024 * 1024);\n const withinFreeTier =\n pricing.freeClassAPerMonth > 0 &&\n classAPerMonth <= pricing.freeClassAPerMonth &&\n storedGb <= pricing.freeStorageGb;\n\n let projectedUsdPerMonth: number | null;\n if (Number.isNaN(pricing.usdPerMillionClassA)) {\n projectedUsdPerMonth = null;\n } else if (withinFreeTier) {\n projectedUsdPerMonth = 0;\n } else {\n const classAOverage = Math.max(0, classAPerMonth - pricing.freeClassAPerMonth);\n const storageOverage = Math.max(0, storedGb - pricing.freeStorageGb);\n projectedUsdPerMonth =\n (classAOverage / 1_000_000) * pricing.usdPerMillionClassA +\n storageOverage * pricing.usdPerGbMonth;\n }\n\n return {\n writesPerMin,\n classAPerMonth,\n percentOfFreeTier,\n percentOfGraduation,\n percentOfAdvisory,\n projectedUsdPerMonth,\n withinFreeTier,\n provider: pricing.provider,\n };\n};\n","/**\n * `baerly cost` — projected cost trajectory for one collection.\n *\n * Sniffs the writes/min rate over the trailing log sample for one\n * collection and projects it into a free-tier-aware monthly Class A\n * + storage cost projection vs. the M-size graduation trigger\n * (50M Class A/mo). Read-only; never mutates anything.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --provider Optional. r2 | aws-s3 | self-hosted | dev. Overrides\n * the auto-detected provider (bucket URI +\n * BAERLY_S3_ENDPOINT).\n * --json JSON envelope.\n *\n * Cost shape:\n * ceil(logKeys/1000) LIST pages over the log/ prefix (1 for typical\n * logs; more only for deep, uncompacted logs — R2/S3 list pages cap\n * at 1000 keys)\n * + up to 120 GETs for trailing log entries (`SAMPLE_SIZE`)\n *\n * Exit codes:\n * 0 — projection rendered.\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag,\n * insufficient log entries to estimate, dev backend).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"./output.ts\";\nimport { detectProvider, pricingFor, type ProviderTag } from \"./cost/provider.ts\";\nimport { project, type Trajectory } from \"./cost/project.ts\";\nimport { estimateWritesPerMin } from \"./admin/usage.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"./subcommand.ts\";\n\nconst COST_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\n provider: {\n type: \"string\",\n required: false,\n description:\n \"Override pricing provider (r2|aws-s3|self-hosted|dev). Auto-detected from bucket URI + BAERLY_S3_ENDPOINT.\",\n valueHint: \"r2|aws-s3|self-hosted|dev\",\n },\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\n/** Compact \"1.5M\" / \"22k\" / \"842\" rendering for Class A op counts. */\nconst formatOps = (n: number): string => {\n if (n >= 1_000_000) {\n return `${(n / 1_000_000).toFixed(1)}M`;\n }\n if (n >= 1_000) {\n return `${(n / 1_000).toFixed(0)}k`;\n }\n return n.toFixed(0);\n};\n\n/** Advisory line rendered when past 100 writes/min but under the 50M/mo graduation trigger. */\nconst renderAdvisoryLine = (t: Trajectory): string => {\n if (t.percentOfAdvisory < 100 || t.percentOfGraduation >= 100) {\n return \"\";\n }\n if (t.projectedUsdPerMonth === null) {\n return (\n ` advisory: ~100 writes/min crossed. Object storage buys zero ops, no on-call,\\n` +\n ` no migration; a managed DB trades those dollars for schema + SQL + ops.\\n` +\n ` Hard graduation trigger: 50M Class A/mo. Self-hosted — bill model not modelled.\\n`\n );\n }\n const costNote = t.provider === \"r2\" ? \"~$54/mo on R2\" : \"~$86/mo on S3\";\n return (\n ` advisory: ~100 writes/min crossed (${costNote}, object-storage ops). Object storage buys\\n` +\n ` zero ops, no on-call, and no migration for your bytes. A managed DB trades those\\n` +\n ` dollars for a schema, SQL, and an ops surface. Review if that tradeoff\\n` +\n ` makes sense for your workload. Hard graduation trigger: 50M Class A/mo.\\n`\n );\n};\n\n/** Two-line trajectory block. Three output states per design spec §4.2. */\nconst renderTrajectory = (t: Trajectory): string => {\n const wpm = t.writesPerMin.toFixed(t.writesPerMin < 10 ? 1 : 0);\n const classA = formatOps(t.classAPerMonth);\n // State 2: ops-only — provider known but no $ model. Today only\n // self-hosted reaches this (dev is filtered out upstream).\n if (t.projectedUsdPerMonth === null) {\n const advisory = renderAdvisoryLine(t);\n return [\n ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo`,\n ` ${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger. Self-hosted — bill model not modelled.`,\n ...(advisory ? [advisory] : []),\n ].join(\"\\n\");\n }\n // Only \"r2\" can reach withinFreeTier===true (aws-s3 has freeClassAPerMonth: 0).\n // self-hosted/dev are filtered upstream.\n const usd = t.withinFreeTier\n ? `~$0 (R2 free tier)`\n : `~$${t.projectedUsdPerMonth!.toFixed(2)}/mo`;\n // Invariant: withinFreeTier===true implies pricing.freeClassAPerMonth>0,\n // which in turn implies percentOfFreeTier!==null (see project.ts).\n const tail = t.withinFreeTier\n ? `${t.percentOfFreeTier!.toFixed(0)}% of free-tier Class A budget. ${t.percentOfFreeTier! < 50 ? \"Well inside the promise.\" : \"Approaching free-tier ceiling.\"}`\n : `${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger.`;\n const advisory = renderAdvisoryLine(t);\n return [\n ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo → ${usd}`,\n ` ${tail}`,\n ...(advisory ? [advisory] : []),\n ].join(\"\\n\");\n};\n\nconst PROVIDER_TAGS: ReadonlySet<string> = new Set([\"r2\", \"aws-s3\", \"self-hosted\", \"dev\"]);\n\nconst bundle = defineBaerlySubcommand({\n name: \"cost\",\n meta: {\n description: \"Project a collection's monthly Class A + storage cost trajectory.\",\n },\n args: COST_ARGS,\n handler: async (args, ctx) => {\n if (typeof args.provider === \"string\" && args.provider.length > 0) {\n if (!PROVIDER_TAGS.has(args.provider)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: --provider must be one of r2|aws-s3|self-hosted|dev (got ${JSON.stringify(args.provider)})`,\n );\n }\n }\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly cost\");\n\n const override =\n typeof args.provider === \"string\" && args.provider.length > 0\n ? (args.provider as ProviderTag)\n : undefined;\n const provider = detectProvider({\n bucketUri: args.bucket,\n s3Endpoint: process.env[\"BAERLY_S3_ENDPOINT\"],\n override,\n });\n if (provider === \"dev\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: dev backends (file://, memory://) have no $ model; pass --provider=r2|aws-s3|self-hosted to project against one.`,\n );\n }\n\n const verdict = await estimateWritesPerMin(bucket.storage, app, tenant, args.collection, {\n keyPrefix: bucket.keyPrefix,\n });\n const trajectory = project(verdict.writesPerMin, 0, pricingFor(provider));\n if (trajectory === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: not enough log entries under ${args.collection} to estimate writes/min (need >= 2)`,\n );\n }\n\n if (isJsonMode()) {\n emitSuccess({ command: \"cost\", collection: args.collection, trajectory });\n } else {\n process.stdout.write(`baerly cost ${args.collection}\\n${renderTrajectory(trajectory)}\\n`);\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly cost`. */\nexport const cost = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runCost = bundle.run;\n"],"mappings":";;;;;AA+BA,MAAa,kBAAkB,SAAkC;CAC/D,IAAI,KAAK,aAAa,KAAA,GACpB,OAAO,KAAK;CAEd,IAAI,KAAK,UAAU,WAAW,SAAS,GACrC,OAAO;CAET,IAAI,KAAK,UAAU,WAAW,WAAW,GACvC,OAAO;CAET,IAAI,CAAC,KAAK,UAAU,WAAW,OAAO,GACpC,OAAO;CAGT,MAAM,WAAW,KAAK,cAAc;CACpC,IAAI,aAAa,IACf,OAAO;CAET,IAAI,2CAA2C,KAAK,QAAQ,GAC1D,OAAO;CAET,IAAI,+BAA+B,KAAK,QAAQ,GAC9C,OAAO;CAET,OAAO;AACT;;;;;;AAOA,MAAM,aAA8B;CAClC,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;CACf,mBAAmB;AACrB;;;;;;;AAQA,MAAM,iBAAkC;CACtC,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;CACf,mBAAmB;AACrB;AAEA,MAAM,sBAAuC;CAC3C,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;CACf,mBAAmB;AACrB;AAEA,MAAM,cAA+B;CACnC,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;CACf,mBAAmB;AACrB;AAEA,MAAa,cAAc,aAA2C;CACpE,QAAQ,UAAR;EACE,KAAK,MACH,OAAO;EAET,KAAK,UACH,OAAO;EAET,KAAK,eACH,OAAO;EAET,KAAK,OACH,OAAO;CAEX;AACF;;;;;;;;;ACxEA,MAAa,+BAA+B;;;;;;;;AAgD5C,MAAa,WACX,cACA,aACA,YACsB;CACtB,IAAI,CAAC,OAAO,SAAS,YAAY,GAC/B,OAAO;CAGT,MAAM,iBAAiB,eAAe,KAAK,KAAK,KAAK,QAAQ;CAE7D,MAAM,sBAAuB,iBAAiB,+BAAgC;CAK9E,MAAM,oBAAqB,eAAA,MAAqD;CAEhF,MAAM,oBACJ,QAAQ,qBAAqB,IAAK,iBAAiB,QAAQ,qBAAsB,MAAM;CAEzF,MAAM,WAAW,eAAe,OAAO,OAAO;CAC9C,MAAM,iBACJ,QAAQ,qBAAqB,KAC7B,kBAAkB,QAAQ,sBAC1B,YAAY,QAAQ;CAEtB,IAAI;CACJ,IAAI,OAAO,MAAM,QAAQ,mBAAmB,GAC1C,uBAAuB;MAClB,IAAI,gBACT,uBAAuB;MAClB;EACL,MAAM,gBAAgB,KAAK,IAAI,GAAG,iBAAiB,QAAQ,kBAAkB;EAC7E,MAAM,iBAAiB,KAAK,IAAI,GAAG,WAAW,QAAQ,aAAa;EACnE,uBACG,gBAAgB,MAAa,QAAQ,sBACtC,iBAAiB,QAAQ;CAC7B;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA,UAAU,QAAQ;CACpB;AACF;;;ACjGA,MAAM,YAAY;CAChB,QAAQ;CACR,KAAK;CACL,QAAQ;CACR,YAAY;CACZ,UAAU;EACR,MAAM;EACN,UAAU;EACV,aACE;EACF,WAAW;CACb;CACA,MAAM;AACR;;AAGA,MAAM,aAAa,MAAsB;CACvC,IAAI,KAAK,KACP,OAAO,IAAI,IAAI,IAAA,CAAW,QAAQ,CAAC,EAAE;CAEvC,IAAI,KAAK,KACP,OAAO,IAAI,IAAI,IAAA,CAAO,QAAQ,CAAC,EAAE;CAEnC,OAAO,EAAE,QAAQ,CAAC;AACpB;;AAGA,MAAM,sBAAsB,MAA0B;CACpD,IAAI,EAAE,oBAAoB,OAAO,EAAE,uBAAuB,KACxD,OAAO;CAET,IAAI,EAAE,yBAAyB,MAC7B,OACE;CAMJ,OACE,mDAFe,EAAE,aAAa,OAAO,kBAAkB,gBAEK;AAKhE;;AAGA,MAAM,oBAAoB,MAA0B;CAClD,MAAM,MAAM,EAAE,aAAa,QAAQ,EAAE,eAAe,KAAK,IAAI,CAAC;CAC9D,MAAM,SAAS,UAAU,EAAE,cAAc;CAGzC,IAAI,EAAE,yBAAyB,MAAM;EACnC,MAAM,WAAW,mBAAmB,CAAC;EACrC,OAAO;GACL,2BAA2B,IAAI,mBAAmB,OAAO;GACzD,0BAA0B,EAAE,oBAAoB,QAAQ,CAAC,EAAE;GAC3D,GAAI,WAAW,CAAC,QAAQ,IAAI,CAAC;EAC/B,CAAC,CAAC,KAAK,IAAI;CACb;CAGA,MAAM,MAAM,EAAE,iBACV,uBACA,KAAK,EAAE,qBAAsB,QAAQ,CAAC,EAAE;CAG5C,MAAM,OAAO,EAAE,iBACX,GAAG,EAAE,kBAAmB,QAAQ,CAAC,EAAE,iCAAiC,EAAE,oBAAqB,KAAK,6BAA6B,qCAC7H,GAAG,EAAE,oBAAoB,QAAQ,CAAC,EAAE;CACxC,MAAM,WAAW,mBAAmB,CAAC;CACrC,OAAO;EACL,2BAA2B,IAAI,mBAAmB,OAAO,kBAAkB;EAC3E,0BAA0B;EAC1B,GAAI,WAAW,CAAC,QAAQ,IAAI,CAAC;CAC/B,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,MAAM,gCAAqC,IAAI,IAAI;CAAC;CAAM;CAAU;CAAe;AAAK,CAAC;AAEzF,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aAAa,oEACf;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAC5B,IAAI,OAAO,KAAK,aAAa,YAAY,KAAK,SAAS,SAAS;OAC1D,CAAC,cAAc,IAAI,KAAK,QAAQ,GAClC,MAAM,IAAI,YACR,iBACA,yEAAyE,KAAK,UAAU,KAAK,QAAQ,EAAE,EACzG;EAAA;EAGJ,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EACzF,oBAAoB,KAAK,YAAY,aAAa;EAElD,MAAM,WACJ,OAAO,KAAK,aAAa,YAAY,KAAK,SAAS,SAAS,IACvD,KAAK,WACN,KAAA;EACN,MAAM,WAAW,eAAe;GAC9B,WAAW,KAAK;GAChB,YAAY,QAAQ,IAAI;GACxB;EACF,CAAC;EACD,IAAI,aAAa,OACf,MAAM,IAAI,YACR,iBACA,+HACF;EAMF,MAAM,aAAa,SAAQ,MAHL,qBAAqB,OAAO,SAAS,KAAK,QAAQ,KAAK,YAAY,EACvF,WAAW,OAAO,UACpB,CAAC,EAAA,CACkC,cAAc,GAAG,WAAW,QAAQ,CAAC;EACxE,IAAI,eAAe,MACjB,MAAM,IAAI,YACR,iBACA,6CAA6C,KAAK,WAAW,oCAC/D;EAGF,IAAI,WAAW,GACb,YAAY;GAAE,SAAS;GAAQ,YAAY,KAAK;GAAY;EAAW,CAAC;OAExE,QAAQ,OAAO,MAAM,eAAe,KAAK,WAAW,IAAI,iBAAiB,UAAU,EAAE,GAAG;EAE1F,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,OAAO,OAAO;AAOJ,OAAO"}