@gusto/baerly-storage 0.6.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 (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  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-ypCm3zjt.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-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  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-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  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 +9 -14
  53. package/dist/dev-vite.js +11 -10
  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-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.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-DP3ClvcA.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 +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  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-C4qgiXSg.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--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  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-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  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/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  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-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  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-BV68pqwJ.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-BMZR8o6U.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 +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,14 +1,16 @@
1
- import { c as configureObservability, l as getLogger, n as flushCanonicalLine, o as deriveOutcome, r as flushUnauthorizedAndRespond, s as CATEGORY, t as observableStorage } from "./observability-Ch-VQJyE.js";
2
- import { l as MAINTENANCE_PROFILE_CF_FREE, t as CF_FREE_MAX_SAFE_FOLD_BYTES, u as MAINTENANCE_PROFILE_CF_PAID } from "./constants-CfeMWQWk.js";
3
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
4
- import { o as parseMaintenanceEnv } from "./maintenance-DULFcpd1.js";
5
- import { n as resolveVerifier, t as Db } from "./src-DvbTEya2.js";
6
- import { t as assertValidStorageKey } from "./key-Di6yyxFu.js";
7
- import { n as createRouter } from "./http-7zT29K3P.js";
8
- import { r as runWithContext, t as createObservabilityContext } from "./context-DRZ3tZ5l.js";
9
- import { r as renderDevLanding } from "./src-DYZ4H1aF.js";
10
- import { t as handleSpecRequest } from "./runtime-spec--LykAdl1.js";
11
- //#region packages/adapter-cloudflare/src/r2-binding-storage.ts
1
+ import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
2
+ import { t as assertValidStorageKey } from "./key-C4FPZ9Io.js";
3
+ import { t as retryStorageCall } from "./retry-OBtLB2GC.js";
4
+ import { t as renderDevLanding } from "./dev-landing-CD-si4dW.js";
5
+ import { g as MAINTENANCE_PROFILE_CF_PAID, h as MAINTENANCE_PROFILE_CF_FREE, i as CF_PAID_REQUEST_LIMIT, n as CF_FREE_MAX_SAFE_FOLD_BYTES } from "./constants-D3GSH3tc.js";
6
+ import { t as RequestLedger } from "./ledger-Dj_bGgo0.js";
7
+ import { t as Db } from "./src-Dr9uo3dc.js";
8
+ import { n as withNosniff, r as resolveVerifier, t as handleSpecRequest } from "./runtime-spec-B5mg3pHF.js";
9
+ import { n as createRouter, r as mapError } from "./http-Z5rZyYMX.js";
10
+ import { r as parseMaintenanceEnv } from "./maintenance-DevB6z4e.js";
11
+ import { a as flushUnauthorizedAndRespond, c as requestIdFrom, d as configureObservability, f as getLogger, i as flushCanonicalLine, l as deriveOutcome, p as logMaintenanceWarning, r as observableStorage, u as CATEGORY } from "./observability-C-ISCCLE.js";
12
+ import { i as runWithContext, t as createObservabilityContext } from "./context-rlpSnHFA.js";
13
+ // packages/adapter-cloudflare/src/r2-binding-storage.ts
12
14
  /**
13
15
  * R2's binding API returns bare-hex ETags (`R2Object.etag`). The
14
16
  * `Storage` contract follows S3's wire format — quoted (`"<hex>"`).
@@ -17,6 +19,16 @@ import { t as handleSpecRequest } from "./runtime-spec--LykAdl1.js";
17
19
  */
18
20
  const stripQuotes = (etag) => etag.startsWith("\"") && etag.endsWith("\"") ? etag.slice(1, -1) : etag;
19
21
  const quoteEtag = (hex) => `"${hex}"`;
22
+ /** R2 error `10058` `TooManyRequests` at the end of a binding error message. */
23
+ const R2_TOO_MANY_REQUESTS = /\(10058\)\s*$/;
24
+ /**
25
+ * workerd's per-invocation subrequest limit. An R2 binding call past the
26
+ * 1,000 internal calls throws "Too many API requests by single Worker
27
+ * invocation" (observed on Workers Free, 2026-11-18); "Too many
28
+ * subrequests …" is the `fetch` cap's wording, matched in case a runtime
29
+ * reports the binding cap that way.
30
+ */
31
+ const WORKERS_SUBREQUEST_LIMIT = /too many (?:api requests|subrequests) by single worker invocation/i;
20
32
  var R2BindingStorageImpl = class {
21
33
  #bucket;
22
34
  constructor(bucket) {
@@ -26,11 +38,8 @@ var R2BindingStorageImpl = class {
26
38
  async get(key, opts) {
27
39
  assertValidStorageKey(key);
28
40
  opts?.signal?.throwIfAborted();
29
- const getOpts = {};
30
- if (opts?.ifNoneMatch !== void 0) getOpts.onlyIf = { etagDoesNotMatch: stripQuotes(opts.ifNoneMatch) };
31
- const obj = await this.#callBinding(() => this.#bucket.get(key, getOpts), `GET ${key}`);
41
+ const obj = await this.#callBinding(() => this.#bucket.get(key), `GET ${key}`, { signal: opts?.signal });
32
42
  if (obj === null) return null;
33
- if (!("body" in obj) || obj.body === null) return null;
34
43
  return {
35
44
  body: new Uint8Array(await obj.arrayBuffer()),
36
45
  etag: quoteEtag(obj.etag)
@@ -43,8 +52,12 @@ var R2BindingStorageImpl = class {
43
52
  if (opts?.contentType !== void 0) putOpts.httpMetadata = { contentType: opts.contentType };
44
53
  if (opts?.ifMatch !== void 0) putOpts.onlyIf = { etagMatches: stripQuotes(opts.ifMatch) };
45
54
  else if (opts?.ifNoneMatch === "*") putOpts.onlyIf = { etagDoesNotMatch: "*" };
46
- const result = await this.#callBinding(() => this.#bucket.put(key, body, putOpts), `PUT ${key}`);
47
- if (result === null) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed`);
55
+ const result = await this.#callBinding(() => this.#bucket.put(key, body, putOpts), `PUT ${key}`, {
56
+ conditionalCreate: opts?.ifNoneMatch === "*",
57
+ compareAndSwap: opts?.ifMatch !== void 0,
58
+ signal: opts?.signal
59
+ });
60
+ if (result === null) throw new BaerlyError("WriteConflict", `PUT ${key}: precondition failed`);
48
61
  return {
49
62
  etag: quoteEtag(result.etag),
50
63
  serverDate: result.uploaded
@@ -53,28 +66,27 @@ var R2BindingStorageImpl = class {
53
66
  async delete(key, opts) {
54
67
  assertValidStorageKey(key);
55
68
  opts?.signal?.throwIfAborted();
56
- await this.#callBinding(() => this.#bucket.delete(key), `DELETE ${key}`);
69
+ await this.#callBinding(() => this.#bucket.delete(key), `DELETE ${key}`, { signal: opts?.signal });
57
70
  }
58
71
  async *list(prefix, opts) {
59
72
  opts?.signal?.throwIfAborted();
60
73
  let cursor = void 0;
61
74
  let yielded = 0;
62
75
  const startAfter = opts?.startAfter ?? "";
63
- const cap = opts?.maxKeys ?? Infinity;
76
+ const cap = opts?.maxKeys ?? 1e400;
64
77
  while (true) {
65
78
  opts?.signal?.throwIfAborted();
66
79
  if (yielded >= cap) return;
67
80
  const listOpts = { prefix };
68
81
  if (cursor !== void 0) listOpts.cursor = cursor;
69
82
  else if (startAfter !== "") listOpts.startAfter = startAfter;
70
- if (cap !== Infinity) listOpts.limit = Math.min(cap - yielded, 1e3);
71
- const page = await this.#callBinding(() => this.#bucket.list(listOpts), `LIST ${prefix}`);
83
+ if (cap !== 1e400) listOpts.limit = Math.min(cap - yielded, 1e3);
84
+ const page = await this.#callBinding(() => this.#bucket.list(listOpts), `LIST ${prefix}`, { signal: opts?.signal });
72
85
  for (const obj of page.objects) {
73
86
  if (yielded >= cap) return;
74
87
  yield {
75
88
  key: obj.key,
76
- etag: quoteEtag(obj.etag),
77
- lastModified: obj.uploaded
89
+ etag: quoteEtag(obj.etag)
78
90
  };
79
91
  yielded += 1;
80
92
  }
@@ -84,21 +96,66 @@ var R2BindingStorageImpl = class {
84
96
  }
85
97
  }
86
98
  /**
87
- * Map binding-layer errors to `BaerlyError` codes. The R2 binding
88
- * surfaces failures as plain `Error` with messages; sniff the
89
- * common ones. If the binding ever adds typed errors, tighten the
90
- * sniff and keep the message fallback for older runtimes.
99
+ * Run one binding call under the shared storage retry policy
100
+ * (`retryStorageCall`: 3 attempts, full-jitter backoff), mapping
101
+ * binding-layer errors to `BaerlyError` codes. The R2 binding surfaces
102
+ * failures as plain `Error` with messages; sniff the common ones. If
103
+ * the binding ever adds typed errors, tighten the sniff and keep the
104
+ * message fallback for older runtimes.
105
+ *
106
+ * `AccessDenied` and `InvalidConfig` are permanent and not retried, and
107
+ * no attempt follows the caller's abort, whatever its reason. An
108
+ * `ifMatch` put (`compareAndSwap`) gets one attempt and no retry at all.
109
+ * Two `NetworkError`s have distinct retry behavior:
110
+ *
111
+ * - R2 error `10058` (`TooManyRequests`, 429: "limit: 1 write/second
112
+ * per key") is tagged `throttled`, so it is retried from the throttle
113
+ * backoff base. Its `mayHaveApplied` flag preserves create uncertainty:
114
+ * Cloudflare does not document that this error proves an unapplied write.
115
+ * R2 binding errors end `message` with the
116
+ * error code in parentheses
117
+ * (https://developers.cloudflare.com/r2/api/error-codes/).
118
+ * - The Workers per-invocation limit ("Too many API requests" on a
119
+ * binding call) is tagged `refused`: not
120
+ * retried, since every later call in the invocation is refused too,
121
+ * and `notApplied` on a create when no earlier attempt is uncertain.
122
+ * The message match is a backstop, not the primary guard.
123
+ *
124
+ * The Writer reads back a failed create: an own entry is adopted, a
125
+ * foreign entry advances to the next slot, and an unknown outcome stays
126
+ * `AmbiguousCommit` even when the slot is currently empty. A negative
127
+ * read cannot prove that an unresolved write will never land.
128
+ *
129
+ * Everything else is a `NetworkError` with an unknown outcome, so an
130
+ * exhausted conditional create does not report `notApplied`.
91
131
  */
92
- async #callBinding(fn, op) {
93
- try {
94
- return await fn();
95
- } catch (error) {
96
- if (error instanceof BaerlyError) throw error;
97
- const msg = error instanceof Error ? error.message : String(error);
98
- if (/auth|permission|forbidden/i.test(msg)) throw new BaerlyError("AccessDenied", `${op}: ${msg}`, error);
99
- if (/not.*found|no.*such.*bucket/i.test(msg)) throw new BaerlyError("InvalidConfig", `${op}: ${msg}`, error);
100
- throw new BaerlyError("NetworkError", `${op}: ${msg}`, error);
101
- }
132
+ #callBinding(fn, op, mode = {}) {
133
+ const { signal, ...retryMode } = mode;
134
+ return retryStorageCall(async () => {
135
+ try {
136
+ return await fn();
137
+ } catch (error) {
138
+ if (error instanceof BaerlyError) throw error;
139
+ const msg = error instanceof Error ? error.message : String(error);
140
+ if (R2_TOO_MANY_REQUESTS.test(msg)) throw new BaerlyError("NetworkError", `${op}: ${msg}`, { cause: {
141
+ status: 429,
142
+ throttled: true,
143
+ mayHaveApplied: true,
144
+ error
145
+ } });
146
+ if (WORKERS_SUBREQUEST_LIMIT.test(msg)) throw new BaerlyError("NetworkError", `${op}: ${msg}`, { cause: {
147
+ refused: true,
148
+ error
149
+ } });
150
+ if (/auth|permission|forbidden/i.test(msg)) throw new BaerlyError("AccessDenied", `${op}: ${msg}`, { cause: error });
151
+ if (/not.*found|no.*such.*bucket/i.test(msg)) throw new BaerlyError("InvalidConfig", `${op}: ${msg}`, { cause: error });
152
+ throw new BaerlyError("NetworkError", `${op}: ${msg}`, { cause: error });
153
+ }
154
+ }, {
155
+ ...retryMode,
156
+ pool: "internal",
157
+ ...signal !== void 0 && { signal }
158
+ });
102
159
  }
103
160
  };
104
161
  /**
@@ -117,14 +174,17 @@ var R2BindingStorageImpl = class {
117
174
  * binding returns bare hex. CAS round-trips strip and re-apply
118
175
  * the quotes.
119
176
  * - `serverDate` from `R2Object.uploaded` — a real server clock,
120
- * suitable for the kernel's adaptive-clock-skew loop.
121
- * - `StorageListEntry.lastModified` from the same clock.
177
+ * suitable for the kernel's adaptive-clock-skew loop. `list()`
178
+ * yields `key` + `etag` only; `StorageListEntry` carries no
179
+ * per-entry timestamp.
122
180
  *
123
181
  * Errors map to `BaerlyError` via the same convention as
124
182
  * `S3HttpStorage`: `AccessDenied` for binding-level permission
125
183
  * failures, `NetworkError` for transient R2 platform failures,
126
184
  * `InvalidResponse` for precondition (CAS) failures, `InvalidConfig`
127
- * if the caller hands in a null/undefined binding.
185
+ * if the caller hands in a null/undefined binding. A failing binding
186
+ * call is retried under the same policy as `S3HttpStorage`: at most 3
187
+ * calls per `get` / `put` / `delete` and per `list` page.
128
188
  *
129
189
  * @example
130
190
  * ```ts
@@ -141,166 +201,15 @@ var R2BindingStorageImpl = class {
141
201
  function r2BindingStorage(bucket) {
142
202
  return new R2BindingStorageImpl(bucket);
143
203
  }
144
- //#endregion
145
- //#region packages/adapter-cloudflare/src/cache.ts
146
- /**
147
- * Cloudflare Cache API integration for the Worker read path.
148
- * Worker-only; Node has no equivalent and runs cache-less.
149
- *
150
- * Contract:
151
- * - Only `GET /v1/c/:collection/:id` is cached. LIST URLs
152
- * (`GET /v1/c/:collection`, with or without filters) bypass the cache.
153
- * The Cloudflare Cache API exposes no enumeration primitive, so
154
- * filtered-LIST variants (`?where=...`) cannot be safely
155
- * invalidated on writes; rather than ship a per-isolate index
156
- * that only partially survives across the colo-shared cache, we
157
- * skip list caching entirely. If LIST caching ever becomes a
158
- * bottleneck, revisit with a cross-isolate primitive (CF Cache
159
- * Tags, KV-backed invalidation, etc).
160
- * - `GET /v1/since` and `GET /v1/healthz` also bypass the cache
161
- * (the long-poll's mutating cursor is not cacheable; healthz is
162
- * trivially fast and must never go stale).
163
- * - Cache key is the request URL + a synthetic `__t=<tenantPrefix>`
164
- * query param. This is the load-bearing correctness invariant:
165
- * the HTTP contract derives `tenant` from the `Verifier`, not the
166
- * URL, so two different Verifier outcomes against the same URL
167
- * must NOT share a cache entry. See `packages/server/src/contract.ts`.
168
- * - Only 200 responses with non-empty bodies are stored. 401/403/
169
- * 404/409/500 always bypass `cache.put`. Negative caching is out
170
- * of scope.
171
- * - `PATCH` / `DELETE` that return 2xx call `cache.delete()` on the
172
- * per-doc URL they hit. `POST` targets a LIST URL (uncached), so
173
- * nothing to bust. Best-effort — failures are swallowed.
174
- * - No `Cache-Control` header is added on the wire. We rely on
175
- * explicit invalidation, not TTLs.
176
- */
177
- /**
178
- * Methods we treat as mutating for invalidation purposes. Keep this
179
- * list narrow — adding a method to `WRITE_METHODS` doubles the
180
- * invalidation surface and matters for correctness.
181
- */
182
- const WRITE_METHODS = /* @__PURE__ */ new Set([
183
- "POST",
184
- "PATCH",
185
- "DELETE"
186
- ]);
187
- /** Pathname prefixes that bypass the cache entirely. */
188
- const BYPASS_PREFIXES = ["/v1/since", "/v1/healthz"];
189
- /**
190
- * `Cache-Control: max-age=<n>` value we set on the cacheable response
191
- * handed to `cache.put`. workerd's `caches.default.put` silently
192
- * no-ops on responses without a cacheable directive, so we synthesize
193
- * one. The value is large because we rely on explicit per-doc
194
- * invalidation, not expiry — see `invalidateOnWrite`.
195
- */
196
- const CACHE_TTL_SECONDS = 3600;
197
- /**
198
- * Build the canonical cache-key `Request` for a given `(req,
199
- * tenantPrefix)`. The synthetic `__t` query parameter scopes the
200
- * cache per-tenant; without it, two tenants with overlapping URLs
201
- * would share entries — a security bug.
202
- *
203
- * The returned `Request` is GET-only by construction — even when
204
- * `req.method` is POST/PATCH/DELETE we use the GET form for
205
- * `cache.delete()` so the read-side write and the write-side bust
206
- * land on the same key.
207
- */
208
- function cacheKeyFor(req, tenantPrefix) {
209
- const url = new URL(req.url);
210
- url.searchParams.set("__t", tenantPrefix);
211
- return new Request(url.toString(), { method: "GET" });
212
- }
213
- /**
214
- * Should this request bypass the cache layer entirely (both read and
215
- * invalidate sides)? Healthz + long-poll + anything that isn't a
216
- * per-doc URL (`/v1/c/:collection/:id`).
217
- */
218
- function bypassesCache(url) {
219
- if (BYPASS_PREFIXES.some((p) => url.pathname.startsWith(p))) return true;
220
- if (!url.pathname.startsWith("/v1/c/")) return true;
221
- if (url.pathname.split("/").filter(Boolean).length < 4) return true;
222
- return false;
223
- }
224
- /**
225
- * Read-path wrapper. Call this in place of invoking the router
226
- * directly for `GET` requests. Returns `{ response, cache_status }`
227
- * so the adapter can stamp `cache_status` on the canonical line:
228
- *
229
- * - `cache_status: "bypass"` — non-GET method, LIST URL, or a path
230
- * under {@link BYPASS_PREFIXES} (`/v1/since`, `/v1/healthz`), or
231
- * a path outside `/v1/c/`. The handler runs verbatim and its
232
- * response is returned untouched.
233
- * - `cache_status: "hit"` — the cache had an entry. Returns
234
- * either a synthesized 304 (when `If-None-Match` matches the
235
- * cached ETag) or the cached body (200). The handler does NOT
236
- * run.
237
- * - `cache_status: "miss"` — the cache had no entry. The handler
238
- * runs and, if the response is a cacheable 200 with no
239
- * `Set-Cookie`, the response is stored before being returned.
240
- */
241
- async function withReadCache(req, tenantPrefix, handler) {
242
- const url = new URL(req.url);
243
- if (req.method !== "GET" || bypassesCache(url)) return {
244
- response: await handler(),
245
- cache_status: "bypass"
246
- };
247
- const cache = caches.default;
248
- const key = cacheKeyFor(req, tenantPrefix);
249
- const cached = await cache.match(key);
250
- if (cached !== void 0) {
251
- const etag = cached.headers.get("etag");
252
- const ifNoneMatch = req.headers.get("if-none-match");
253
- if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) return {
254
- response: new Response(null, {
255
- status: 304,
256
- headers: { etag }
257
- }),
258
- cache_status: "hit"
259
- };
260
- const cloned = cached.clone();
261
- const outHeaders = new Headers(cloned.headers);
262
- outHeaders.delete("cache-control");
263
- return {
264
- response: new Response(cloned.body, {
265
- status: cloned.status,
266
- statusText: cloned.statusText,
267
- headers: outHeaders
268
- }),
269
- cache_status: "hit"
270
- };
271
- }
272
- const fresh = await handler();
273
- if (fresh.status === 200 && !fresh.headers.has("set-cookie")) {
274
- const headers = new Headers(fresh.headers);
275
- headers.set("cache-control", `max-age=${CACHE_TTL_SECONDS}`);
276
- const cacheable = new Response(fresh.clone().body, {
277
- status: fresh.status,
278
- statusText: fresh.statusText,
279
- headers
280
- });
281
- await cache.put(key, cacheable);
282
- }
283
- return {
284
- response: fresh,
285
- cache_status: "miss"
286
- };
287
- }
288
204
  /**
289
- * Write-path companion. Call this AFTER the handler returns a 2xx
290
- * for `PATCH` / `DELETE` on a per-doc URL — busts the cache entry
291
- * for that URL. `POST` targets a LIST URL (uncached), so nothing to
292
- * bust; this function returns without touching the cache. Failures
293
- * are swallowed; a stale entry is recoverable via the 304 path on
294
- * the next read.
205
+ * Whether `storage` is the R2 binding itself (from {@link r2BindingStorage}).
206
+ * R2 binding calls do not count toward Workers Free's 50 external
207
+ * subrequests; anything else a Worker is given (`S3HttpStorage`, or a
208
+ * wrapper around either) is assumed to reach the bucket through `fetch`,
209
+ * where every call does.
295
210
  */
296
- async function invalidateOnWrite(req, tenantPrefix, responseStatus) {
297
- if (!WRITE_METHODS.has(req.method)) return;
298
- if (responseStatus < 200 || responseStatus >= 300) return;
299
- if (bypassesCache(new URL(req.url))) return;
300
- await caches.default.delete(cacheKeyFor(req, tenantPrefix));
301
- }
302
- //#endregion
303
- //#region packages/adapter-cloudflare/src/resolve-storage.ts
211
+ const isR2BindingStorage = (storage) => storage instanceof R2BindingStorageImpl;
212
+ // packages/adapter-cloudflare/src/resolve-storage.ts
304
213
  /**
305
214
  * Resolve the request-time {@link Storage} for a Worker.
306
215
  *
@@ -314,8 +223,7 @@ function resolveWorkerStorage(options, env) {
314
223
  if (!env.BUCKET) throw new BaerlyError("InvalidConfig", "baerlyWorker: no storage available. Bind an R2 bucket as `BUCKET`, or pass `storage` in the factory options — e.g. new S3HttpStorage(...) from \"@gusto/baerly-storage/s3\".");
315
224
  return r2BindingStorage(env.BUCKET);
316
225
  }
317
- //#endregion
318
- //#region packages/adapter-cloudflare/src/worker.ts
226
+ // packages/adapter-cloudflare/src/worker.ts
319
227
  /**
320
228
  * Cloudflare Workers have no TTY, so the default sink is always
321
229
  * the JSON console sink — log-aggregator-shaped out of the box.
@@ -329,15 +237,87 @@ const resolveCfSink = (config) => {
329
237
  };
330
238
  };
331
239
  /**
240
+ * Non-throwing parse of a `BAERLY_MAINTENANCE_PROFILE` value: the tier it
241
+ * names (`undefined` and `""` mean `cf-free`), or `undefined` when the
242
+ * value is not a recognized selector.
243
+ */
244
+ const parseCfProfileTier = (raw) => {
245
+ if (raw === void 0 || raw === "" || raw === "cf-free") return "cf-free";
246
+ return raw === "cf-paid" ? "cf-paid" : void 0;
247
+ };
248
+ /**
332
249
  * Resolve the maintenance profile from the opt-in operator env var.
333
- * Default (unset / unknown) is the CPU-killable CF-free profile, so
334
- * zero-config behavior is unchanged. `cf-paid` raises the per-pass
335
- * caps to exploit the paid 10,000-subrequest budget; it does NOT change
336
- * the snapshot ceilings. Used by BOTH the write-tick dispatch and the
337
- * cron path so the two maintenance triggers stay coherent when the
338
- * operator wires the recipe below into their scheduled handler.
250
+ * Unset, `""`, and `"cf-free"` select the CPU-limited CF-free profile, so
251
+ * zero-config behavior is unchanged. `cf-paid` raises the per-pass caps
252
+ * to exploit the paid 10,000-subrequest budget AND the snapshot ceilings
253
+ * to `C` = 8 MiB / `E` = 32,768, measured against the paid isolate's own
254
+ * memory wall rather than free's CPU wall. Used by the write-tick
255
+ * dispatch and the request ledger; a cron handler passes the same value
256
+ * as `runScheduledMaintenance`'s `tier`. Unpublished: in-repo callers
257
+ * import it from `@baerly/adapter-cloudflare/worker`.
258
+ *
259
+ * @throws {BaerlyError} `InvalidConfig` for any other value (`"cf_paid"`,
260
+ * `"CF-PAID"`, `"cf-paid "`): a misspelled opt-in would otherwise leave a
261
+ * paid Worker on free caps and ceilings without any signal.
262
+ */
263
+ const resolveCfMaintenanceProfile = (readEnv) => {
264
+ const raw = readEnv("BAERLY_MAINTENANCE_PROFILE");
265
+ const tier = parseCfProfileTier(raw);
266
+ if (tier === "cf-free") return MAINTENANCE_PROFILE_CF_FREE;
267
+ if (tier === "cf-paid") return MAINTENANCE_PROFILE_CF_PAID;
268
+ throw new BaerlyError("InvalidConfig", `BAERLY_MAINTENANCE_PROFILE must be one of "", "cf-free", "cf-paid", got ${JSON.stringify(raw)}`);
269
+ };
270
+ /** Read a string var off the `env` binding (CF `vars` are always strings). */
271
+ const envReader = (env) => (key) => {
272
+ const value = env[key];
273
+ return typeof value === "string" ? value : void 0;
274
+ };
275
+ /**
276
+ * A fresh request ledger for one Worker invocation (a `fetch` or a
277
+ * `scheduled` call), with the limits of the `BAERLY_MAINTENANCE_PROFILE`
278
+ * tier. The profile, not the account's billing plan, selects them:
279
+ * `cf-free` (the default) allows {@link CF_FREE_INTERNAL_REQUEST_LIMIT}
280
+ * storage calls, of which at most {@link CF_FREE_EXTERNAL_REQUEST_LIMIT}
281
+ * leave through `fetch`; `cf-paid` allows
282
+ * {@link CF_PAID_REQUEST_LIMIT} of either. A storage call past the limit
283
+ * is refused with `CapacityExceeded` before it is sent, where the
284
+ * platform would otherwise throw on it.
285
+ *
286
+ * Never throws. Only the exact value `"cf-paid"` raises the limits; any
287
+ * other value, valid or not, gets the free limits, which are safe on
288
+ * every plan. Validation stays with {@link resolveCfMaintenanceProfile}
289
+ * at the maintenance dispatch build, so an invalid value fails API
290
+ * requests there and does not reach a cron callback that never reads it.
291
+ */
292
+ const cfRequestLedger = (readEnv) => new RequestLedger(parseCfProfileTier(readEnv("BAERLY_MAINTENANCE_PROFILE")) === "cf-paid" ? {
293
+ internal: CF_PAID_REQUEST_LIMIT,
294
+ external: CF_PAID_REQUEST_LIMIT
295
+ } : {
296
+ internal: 900,
297
+ external: 45
298
+ });
299
+ /**
300
+ * The Worker's read envelope: the request pool its storage charges, so a
301
+ * read the ledger certainly cannot fit is refused from `current.json`
302
+ * alone (the R2 binding charges `internal`; anything else, reached through
303
+ * `fetch`, charges `external`). The data bounds (snapshot, tail, output)
304
+ * are left unbounded on every profile until cold CPU measurements size
305
+ * them; the ledger bounds every read's storage calls today.
339
306
  */
340
- const resolveCfMaintenanceProfile = (readEnv) => readEnv("BAERLY_MAINTENANCE_PROFILE") === "cf-paid" ? MAINTENANCE_PROFILE_CF_PAID : MAINTENANCE_PROFILE_CF_FREE;
307
+ const cfReadEnvelope = (storage) => ({ requestPool: isR2BindingStorage(storage) ? "internal" : "external" });
308
+ /**
309
+ * Write-tick options on the free profile for storage reached through
310
+ * `fetch`: the GC sweep capped, and the server's unpublished host trigger
311
+ * `foldAtTailEntries` (`InternalBoundedMaintenanceOptions`), spread into
312
+ * the public options bag. `worker-maintenance.test.ts` pins the result.
313
+ */
314
+ const CF_FREE_FETCH_TICK = {
315
+ profile: {
316
+ ...MAINTENANCE_PROFILE_CF_FREE,
317
+ gcMaxSweeps: 3
318
+ },
319
+ foldAtTailEntries: 7
320
+ };
341
321
  /**
342
322
  * Assemble the per-request {@link MaintenanceDispatch} for a Cloudflare
343
323
  * Worker.
@@ -351,36 +331,63 @@ const resolveCfMaintenanceProfile = (readEnv) => readEnv("BAERLY_MAINTENANCE_PRO
351
331
  * On Cloudflare the fold runs in a `ctx.waitUntil` continuation — FIRE
352
332
  * AND FORGET off the response ack, so the commit never blocks on it. The
353
333
  * isolate stays alive long enough to drain the continuation; the
354
- * per-pass caps are the TESTED CF-free `WRITE_TICK_*` defaults
355
- * (`phasesPerTick: "single"` — a CPU-killable free isolate does ONE of
356
- * fold/GC per request, never both), sized so a single pass stays well
357
- * under the free-tier 50-subrequest budget. An operator on CF **paid**
358
- * raises the ceiling via `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; the
359
- * per-pass entry/sweep caps stay fixed here (raising them toward the
360
- * 10,000-subrequest paid budget — the default since 2026-02-11, up from
361
- * 1,000, and configurable to 10M — is a future graduation knob, not a
362
- * var). Free stays at 50 external / 1,000 internal-service subrequests.
334
+ * per-pass caps default to the TESTED CF-free `WRITE_TICK_*` values
335
+ * (`phasesPerTick: "single"` — a CPU-limited free isolate does ONE of
336
+ * fold/GC per request, never both). Every storage call is charged to the
337
+ * invocation's request ledger (`cfRequestLedger`): on Free, 900 calls
338
+ * through the R2 binding and 45 through `fetch`, below the platform's
339
+ * 1,000 internal-service and 50 external subrequests. An operator on CF **paid** opts
340
+ * into the whole paid tier — per-pass caps AND snapshot ceilings — with
341
+ * `BAERLY_MAINTENANCE_PROFILE=cf-paid`, which is what exploits the
342
+ * 10,000-subrequest paid budget (the default since 2026-02-11, up from
343
+ * 1,000, and configurable to 10M).
363
344
  *
364
- * The two ops-plane vars are read off the `env` BINDING (a string map),
345
+ * The three ops-plane vars are read off the `env` BINDING (a string map),
365
346
  * NOT `process.env` — Workers have no process env:
366
347
  *
367
- * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (`C`). Parsed
368
- * as a number; ignored when unset / NaN.
369
- * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Truthy
370
- * when set to a non-empty value other than `"0"` / `"false"`.
348
+ * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (`C`), which
349
+ * overrides the resolved profile's ceiling. A plain positive decimal
350
+ * integer; ignored when unset / `""`; any other value throws
351
+ * `BaerlyError{code:"InvalidConfig"}`.
352
+ * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Closed,
353
+ * case-insensitive vocabulary: unset/`""`/`"0"`/`"false"` → `false`;
354
+ * `"1"`/`"true"` → `true`; anything else throws
355
+ * `BaerlyError{code:"InvalidConfig"}`. Covers automatic maintenance
356
+ * only; it does not stop `runScheduledMaintenance`.
357
+ * - `BAERLY_MAINTENANCE_PROFILE` → `options.profile`, via
358
+ * {@link resolveCfMaintenanceProfile} (closed vocabulary; anything
359
+ * outside it throws `BaerlyError{code:"InvalidConfig"}`).
371
360
  *
372
361
  * `readEnv` defaults to reading off the bound `env`; the parameter
373
362
  * exists for direct unit coverage.
363
+ *
364
+ * `storage` is the Worker's base storage. On the free profile, storage
365
+ * other than the R2 binding (`S3HttpStorage`, or any wrapper) is charged
366
+ * to the 45-call `external` pool, so the write tick folds as soon as the
367
+ * live tail reaches {@link CF_FREE_FETCH_FOLD_AT_TAIL_ENTRIES} entries,
368
+ * and a GC slice sweeps at most {@link CF_FREE_FETCH_GC_MAX_SWEEPS}
369
+ * snapshots: a write replays the tail, and on a longer tail or a larger
370
+ * sweep the write plus the tick it dispatches no longer fit in one
371
+ * request. Workers Free + S3 is not a supported host, but the Worker
372
+ * cannot tell Free from Paid: `cf-free` caps fetch storage at 45 calls so
373
+ * a request past Free's 50 gets a typed `CapacityExceeded` instead of the
374
+ * platform throwing at call 51, and this tick keeps ordinary requests
375
+ * inside that cap (a Paid Worker on S3 that has not set `cf-paid` runs
376
+ * here). Detected from the storage itself, so it needs no configuration.
377
+ * Absent ⇒ treated as the R2 binding.
374
378
  */
375
- const cfMaintenanceDispatch = (ctx, readEnv) => {
379
+ const cfMaintenanceDispatch = (ctx, readEnv, storage) => {
376
380
  const { maxFoldBytes, disabled } = parseMaintenanceEnv(readEnv);
381
+ const profile = resolveCfMaintenanceProfile(readEnv);
382
+ const fetchBudgeted = profile === MAINTENANCE_PROFILE_CF_FREE && storage !== void 0 && !isR2BindingStorage(storage);
377
383
  return {
378
384
  dispatch: (task) => ctx.waitUntil(task()),
379
385
  ...disabled && { disabled: true },
380
386
  ...maxFoldBytes !== void 0 && { maxFoldBytes },
387
+ warn: logMaintenanceWarning,
381
388
  options: {
382
389
  phasesPerTick: "single",
383
- profile: resolveCfMaintenanceProfile(readEnv)
390
+ ...fetchBudgeted ? CF_FREE_FETCH_TICK : { profile }
384
391
  }
385
392
  };
386
393
  };
@@ -391,15 +398,11 @@ const cfMaintenanceDispatch = (ctx, readEnv) => {
391
398
  * don't pay for a Db construction; an auth challenge stops a bad
392
399
  * request before any Storage I/O; the router catches everything else.
393
400
  *
394
- * Observability: every HTTP request that flows past the verifier
395
- * runs inside a single `runWithContext` scope created up front in
396
- * this adapter — including the read-cache wrapper. The canonical
397
- * line emitted at end-of-request carries a top-level
398
- * `cache_status: "hit" | "miss" | "bypass"` field so operators can
399
- * split hit/miss/bypass directly from the log stream without
400
- * consulting a CDN dashboard. The router's observability middleware
401
- * detects the ambient context and passes through — the adapter owns
402
- * the flush.
401
+ * Observability: every HTTP request that passes healthz — the
402
+ * verifier included — runs inside a single `runWithContext` scope
403
+ * created up front in this adapter. Every point read reaches storage;
404
+ * response bodies are never cached. The canonical line includes the
405
+ * storage work of each read; the adapter owns the flush.
403
406
  *
404
407
  * Cron Triggers are opt-in. Pass `options.scheduled` to wire one;
405
408
  * `wrangler.jsonc:triggers.crons` controls the firing cadence.
@@ -426,7 +429,7 @@ function baerlyWorker(factory) {
426
429
  let resolved;
427
430
  let resolutionError;
428
431
  let observabilityConfigured = false;
429
- let maintenanceCeilingWarned = false;
432
+ let maintenanceCeilingChecked = false;
430
433
  const ensureResolved = async (env) => {
431
434
  if (resolutionError !== void 0) throw resolutionError;
432
435
  if (resolved === void 0) try {
@@ -452,15 +455,25 @@ function baerlyWorker(factory) {
452
455
  observabilityConfigured = true;
453
456
  if (resolved.options.verifier === void 0 && resolved.options.config.auth === "none") getLogger(CATEGORY.http).info(`[baerly] auth=none — all requests resolve to tenant=${JSON.stringify(resolved.options.config.tenant)}`);
454
457
  }
455
- if (!maintenanceCeilingWarned) {
456
- maintenanceCeilingWarned = true;
457
- const rawFoldBytes = env["BAERLY_MAINTENANCE_MAX_FOLD_BYTES"];
458
- const { maxFoldBytes } = parseMaintenanceEnv((k) => typeof rawFoldBytes === "string" && k === "BAERLY_MAINTENANCE_MAX_FOLD_BYTES" ? rawFoldBytes : void 0);
459
- if (maxFoldBytes !== void 0 && maxFoldBytes > 1048576) console.warn(`[baerly] BAERLY_MAINTENANCE_MAX_FOLD_BYTES=${rawFoldBytes} exceeds the CF free-tier safe ceiling (${CF_FREE_MAX_SAFE_FOLD_BYTES} bytes). On a free Worker a fold this large risks a mid-rebuild CPU kill (the ~10 ms limit): the current.json CAS never lands, so the fold silently does NOT advance and the tail grows unbounded. Safe remedies: run on CF PAID (raised CPU limits), self-host on NODE, or wait for §11 chunked snapshots. Leave this var unset on free CF.`);
458
+ if (!maintenanceCeilingChecked) {
459
+ const readMaintenanceEnv = (k) => {
460
+ const v = env[k];
461
+ return typeof v === "string" ? v : void 0;
462
+ };
463
+ const rawFoldBytes = readMaintenanceEnv("BAERLY_MAINTENANCE_MAX_FOLD_BYTES");
464
+ let overFreeCeiling;
465
+ try {
466
+ const { maxFoldBytes } = parseMaintenanceEnv((k) => k === "BAERLY_MAINTENANCE_MAX_FOLD_BYTES" ? rawFoldBytes : void 0);
467
+ overFreeCeiling = maxFoldBytes !== void 0 && maxFoldBytes > 1048576 && resolveCfMaintenanceProfile(readMaintenanceEnv) === MAINTENANCE_PROFILE_CF_FREE;
468
+ } catch {
469
+ return resolved;
470
+ }
471
+ if (overFreeCeiling) console.warn(`[baerly] BAERLY_MAINTENANCE_MAX_FOLD_BYTES=${rawFoldBytes} exceeds the CF free-tier safe ceiling (${CF_FREE_MAX_SAFE_FOLD_BYTES} bytes). On a free Worker a fold this large may exceed the invocation's CPU or memory resources (the ~10 ms CPU limit); if it is terminated mid-rebuild the current.json CAS does not land, so that fold does not advance and the tail can grow. Remedies: run on CF PAID (raised CPU limits) or self-host on NODE. Leave this var unset on free CF.`);
472
+ maintenanceCeilingChecked = true;
460
473
  }
461
474
  return resolved;
462
475
  };
463
- return {
476
+ const exported = {
464
477
  async fetch(req, env, ctx) {
465
478
  const url = new URL(req.url);
466
479
  if (req.method === "GET" && url.pathname === "/v1/spec") return handleSpecRequest(req, async () => {
@@ -470,7 +483,30 @@ function baerlyWorker(factory) {
470
483
  config: options.config
471
484
  };
472
485
  });
473
- const { options, verifier, storage: baseStorage } = await ensureResolved(env);
486
+ let resolvedState;
487
+ try {
488
+ resolvedState = await ensureResolved(env);
489
+ } catch (error) {
490
+ console.error(`[baerly] config resolution failed: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
491
+ const fault = new BaerlyError("Internal", "internal error", { cause: error });
492
+ const { status, envelope } = mapError(fault);
493
+ const failedCtx = createObservabilityContext({ request_id: requestIdFrom(req.headers) });
494
+ flushCanonicalLine(failedCtx, failedCtx.recorder, {
495
+ unit: "http",
496
+ status,
497
+ outcome: deriveOutcome(req.method, status, fault),
498
+ error: fault,
499
+ extra: {
500
+ method: req.method,
501
+ path: url.pathname
502
+ }
503
+ });
504
+ return new Response(JSON.stringify(envelope), {
505
+ status,
506
+ headers: { "content-type": "application/json" }
507
+ });
508
+ }
509
+ const { options, verifier, storage: baseStorage } = resolvedState;
474
510
  if (options.dev !== void 0 && req.method === "GET") {
475
511
  if (url.pathname === "/") return new Response(renderDevLanding(options.dev), {
476
512
  status: 200,
@@ -482,63 +518,90 @@ function baerlyWorker(factory) {
482
518
  status: 200,
483
519
  headers: { "content-type": "application/json" }
484
520
  });
521
+ const requestId = requestIdFrom(req.headers);
522
+ const readEnv = envReader(env);
485
523
  const obsCtx = createObservabilityContext({
486
- request_id: req.headers.get("x-request-id") ?? crypto.randomUUID(),
487
- maintenance: cfMaintenanceDispatch(ctx, (k) => {
488
- const value = env[k];
489
- return typeof value === "string" ? value : void 0;
490
- })
524
+ request_id: requestId,
525
+ maintenance: cfMaintenanceDispatch(ctx, readEnv, baseStorage),
526
+ ledger: cfRequestLedger(readEnv),
527
+ readEnvelope: cfReadEnvelope(baseStorage)
491
528
  });
492
- const result = await verifier(req);
493
- if (result === null) return runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, req));
494
- const tenantPrefix = result.tenantPrefix;
495
529
  return runWithContext(obsCtx, async () => {
530
+ let result;
531
+ try {
532
+ result = await verifier(req);
533
+ } catch (error) {
534
+ const { status, envelope } = mapError(error);
535
+ flushCanonicalLine(obsCtx, obsCtx.recorder, {
536
+ unit: "http",
537
+ status,
538
+ outcome: deriveOutcome(req.method, status, error),
539
+ error,
540
+ extra: {
541
+ method: req.method,
542
+ path: url.pathname
543
+ }
544
+ });
545
+ return new Response(JSON.stringify(envelope), {
546
+ status,
547
+ headers: { "content-type": "application/json" }
548
+ });
549
+ }
550
+ if (result === null) return flushUnauthorizedAndRespond(obsCtx, req);
551
+ const tenantPrefix = result.tenantPrefix;
496
552
  const storage = observableStorage(baseStorage);
497
- const app = createRouter({
498
- db: Db.create({
553
+ let outboundStatus = 500;
554
+ let caughtError;
555
+ let response;
556
+ try {
557
+ const db = Db.create({
499
558
  storage,
500
559
  app: env.APP,
501
560
  tenant: tenantPrefix,
502
561
  config: options.config
503
- }),
504
- sinceTimeoutMs: options.sinceTimeoutMs,
505
- sincePollIntervalMs: options.sincePollIntervalMs
506
- });
507
- let cacheStatus = "bypass";
508
- let response;
509
- let caughtError;
510
- try {
511
- const cacheResult = await withReadCache(req, tenantPrefix, () => Promise.resolve(app.fetch(req, env, ctx)));
512
- cacheStatus = cacheResult.cache_status;
513
- response = cacheResult.response;
562
+ });
563
+ response = await createRouter({
564
+ db,
565
+ sinceTimeoutMs: options.sinceTimeoutMs,
566
+ sincePollIntervalMs: options.sincePollIntervalMs
567
+ }).fetch(req, env, ctx);
568
+ outboundStatus = response.status;
514
569
  } catch (error) {
515
570
  caughtError = error;
516
- throw error;
571
+ const mapped = mapError(error);
572
+ outboundStatus = mapped.status;
573
+ response = new Response(JSON.stringify(mapped.envelope), {
574
+ status: mapped.status,
575
+ headers: { "content-type": "application/json" }
576
+ });
517
577
  } finally {
518
- const status = caughtError !== void 0 ? 500 : response?.status ?? 500;
519
578
  flushCanonicalLine(obsCtx, obsCtx.recorder, {
520
579
  unit: "http",
521
- status,
522
- outcome: deriveOutcome(req.method, status, caughtError),
580
+ status: outboundStatus,
581
+ outcome: deriveOutcome(req.method, outboundStatus, caughtError),
523
582
  ...caughtError !== void 0 && { error: caughtError },
524
583
  extra: {
525
584
  method: req.method,
526
- path: new URL(req.url).pathname,
527
- cache_status: cacheStatus
585
+ path: url.pathname
528
586
  }
529
587
  });
530
588
  }
531
- ctx.waitUntil(invalidateOnWrite(req, tenantPrefix, response.status));
532
589
  return response;
533
590
  });
534
591
  },
535
592
  async scheduled(event, env, ctx) {
536
593
  const { options } = await ensureResolved(env);
537
- if (options.scheduled !== void 0) await options.scheduled(event, env, ctx);
594
+ const handler = options.scheduled;
595
+ if (handler !== void 0) {
596
+ const cronCtx = createObservabilityContext({ ledger: cfRequestLedger(envReader(env)) });
597
+ await runWithContext(cronCtx, () => handler(event, env, ctx));
598
+ }
538
599
  }
539
600
  };
601
+ const route = exported.fetch;
602
+ exported.fetch = async (req, env, ctx) => withNosniff(await route(req, env, ctx));
603
+ return exported;
540
604
  }
541
- //#endregion
542
- export { baerlyWorker, r2BindingStorage, resolveCfMaintenanceProfile };
605
+ export { baerlyWorker, r2BindingStorage };
543
606
 
544
607
  //# sourceMappingURL=cloudflare.js.map