@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-Z5rZyYMX.js","names":["Hono"],"sources":["../packages/protocol/src/cursor.ts","../packages/protocol/src/log.ts","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/compose.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/url.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/http-exception.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/request/constants.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/buffer.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/body.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/request.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/html.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/context.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/helper/route/index.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/constants.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/mount.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/hono-base.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/router/pattern-router/router.js","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/preset/tiny.js","../packages/server/src/http/since.ts","../packages/server/src/http/router.ts"],"sourcesContent":["/**\n * `/v1/since` cursor codec — the composite `<generation>.<lsn>` token a\n * long-poll client acks and resumes from.\n *\n * Kept separate from `log.ts` for the same reason as `log-key.ts`:\n * `log.ts` carries the heavier `lsn` parsing runtime, and consumers that\n * only need to split a cursor shouldn't drag it into their bundle\n * closure. This module imports only `BaerlyError` and the\n * `NO_GENERATION` sentinel from the zero-import `constants.ts`.\n *\n * ## Why the cursor is not just the LSN\n *\n * The seq embedded in an LSN identifies a `log/<seq>` slot, and slots\n * are reused. `baerly admin restore --force` truncates a collection and\n * reseeds `log_seq_start` to one past the highest *surviving* log\n * object, which can land BELOW the old floor (the deliberate floor\n * exemption — see invariant 12 in `docs/spec/sync-protocol.md`). A\n * pre-restore cursor then passes `/v1/since`'s `cursorSeq <\n * log_seq_start` gate and resumes into the new generation, silently\n * skipping every restored row beneath it. The stream is gapped, not\n * broken, which is the worst failure mode for a sync cursor.\n *\n * Pairing the LSN with the generation that minted it turns that silent\n * gap into a `CursorExpired` telling the client to re-bootstrap.\n *\n * The token is opaque on the wire: clients ack and echo it, never parse\n * it. `LogEntry.lsn` is unchanged — this shape exists only at the\n * `/v1/since` boundary.\n */\n\nimport { NO_GENERATION } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\n\n/**\n * Separator between the generation and the LSN. The LSN is\n * `_`-delimited (`<base32-time>_<session>_<seq>`) and a generation is\n * lowercase hex, so `.` cannot occur in either half.\n */\nconst CURSOR_SEPARATOR = \".\";\n\n/**\n * Re-exported from the zero-import `constants.ts`, where the sentinel\n * now lives so `runGc` can reach it without dragging this module's\n * codec into the `index.js` / `maintenance.js` closures. Kept exported\n * here because `/v1/since` is still its primary consumer.\n */\nexport { NO_GENERATION };\n\n/**\n * Build the wire cursor for an entry's `lsn` under a manifest's\n * `generation`.\n *\n * A manifest predating the field emits the LSN **bare**, not\n * `-.<lsn>` — {@link parseCursor} maps both to {@link NO_GENERATION},\n * so the comparison is unchanged either way. Keeping it bare confines\n * the wire-shape change to collections that actually carry a nonce,\n * instead of changing every cursor in the bucket on upgrade.\n */\nexport const formatCursor = (generation: string | undefined, lsn: string): string =>\n generation === undefined ? lsn : `${generation}${CURSOR_SEPARATOR}${lsn}`;\n\n/**\n * Split a wire cursor into its generation and LSN halves.\n *\n * A cursor with no separator is a bare LSN from a build that predates\n * the composite shape; it decodes to {@link NO_GENERATION} rather than\n * throwing, so an in-flight client is not forced to re-bootstrap across\n * a deploy that changed nothing about its collection.\n *\n * Throws `SchemaError` (→ HTTP 400) on more than one separator: that is\n * malformed caller input, not a shape this build ever minted, and\n * guessing which half is which would be worse than rejecting.\n */\nexport const parseCursor = (cursor: string): { generation: string; lsn: string } => {\n const parts = cursor.split(CURSOR_SEPARATOR);\n if (parts.length === 1) {\n return { generation: NO_GENERATION, lsn: cursor };\n }\n if (parts.length !== 2) {\n throw new BaerlyError(\n \"SchemaError\",\n `invalid cursor shape: ${JSON.stringify(cursor)} (expected \"<generation>.<lsn>\")`,\n );\n }\n return { generation: parts[0]!, lsn: parts[1]! };\n};\n","import { BaerlyError } from \"./errors.ts\";\nimport type { DocumentData, JSONValue } from \"./json.ts\";\nimport { COUNT_BIT_WIDTH } from \"./constants.ts\";\nimport { str2uintDesc } from \"./types.ts\";\n\n/**\n * Debezium-style JSON CDC envelope using pgoutput's message-tag (`I`/`U`/`D`) vocabulary. One per mutation.\n *\n * `LogEntry` is now a public, versionless/additive-only wire contract:\n * 0.3.0 is the public early-access baseline. It is still pre-1.0 and\n * soaking, so breaking changes remain possible, but only through an\n * explicit compatibility decision, changelog/migration notes, and a\n * versioned release. Assume external consumers may exist; do not\n * silently rename, remove, or repurpose fields. Consumers must ignore\n * unknown keys; new optional fields can be added in compatible releases.\n *\n * Field requirement matrix:\n * - Always: `lsn`, `commit_ts`, `op`, `collection`, `session`,\n * `seq`.\n * - For I/U/D: `doc_id`.\n * - For I/U: `after` (full post-image).\n * - Optional: `before` (when `replica_identity === \"FULL\"`), `key_old`\n * (U/D when `replica_identity !== \"PATCH_ONLY\"`), `origin`.\n *\n * @see docs/spec/log-entry-shape.md\n */\nexport interface LogEntry {\n /**\n * Opaque, monotonic, lex-asc cursor. Shape is\n * `<base32-time>_<session>_<seq>` — minted inside\n * `Writer.commit` (see\n * `packages/server/src/writer.ts`) from `timestamp()` +\n * the per-commit `session` + `countKey(seq)`.\n *\n * This is NOT what a `/v1/since` client acks: that boundary pairs\n * the LSN with the manifest's `generation` (see `cursor.ts`), so the\n * token may be `<generation>.<lsn>`. Treat `next_cursor` as opaque.\n *\n * When you have a `LogEntry` in hand, prefer the structured\n * `session` / `seq` fields below over parsing this string. The\n * one place that *does* need to crack it open is the\n * `/v1/since` boundary, where a client resumes from an opaque\n * `next_cursor` and no `LogEntry` is in scope — that path uses\n * `lsnParts` (the kernel-blessed parser) rather than ad-hoc\n * `split(\"_\")`.\n */\n lsn: string;\n\n /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */\n commit_ts: string;\n\n /** Insert / Update / Delete. */\n op: \"I\" | \"U\" | \"D\";\n\n /**\n * Collection name — the pgoutput RELATION analogue. Today this is\n * the collection bound to the `current.json` whose `tail_hint` minted\n * the entry. The table API makes collections first-class.\n */\n collection: string;\n\n /**\n * The document key (`ref.key`). Required for every op — `op` is\n * `I | U | D` and all three carry it — so the wire type is required,\n * not optional, matching `log-entry-shape.md`.\n */\n doc_id: string;\n\n /** Required for I, U. The post-image (Debezium's `after`). */\n after?: DocumentData;\n\n /**\n * The pre-image (Debezium's `before`). Present iff the\n * collection's `replica_identity` is `FULL`. ~2× log size on\n * update-heavy collections; off by default.\n */\n before?: DocumentData;\n\n /**\n * Pre-image of the primary key. U/D always carry this when\n * `replica_identity` is not `PATCH_ONLY`. (For baerly-storage today,\n * `_id` is the only PK.)\n */\n key_old?: { readonly [pk: string]: JSONValue };\n\n /** ORIGIN analogue — the writer session id. */\n origin?: string;\n\n /**\n * Causal metadata (baerly-storage-only; no pgoutput analogue). The\n * session id that built the `lsn`. Surfaces here so consumers\n * can dedupe / order without parsing the cursor.\n */\n session: string;\n\n /**\n * The `log/<seq>` slot this entry occupies — the integer in its\n * `log/<seq>.json` key, minted by `Writer.commit` as the forward-probed\n * collection-log tail (the winning `If-None-Match: \"*\"` create). One\n * entry per `session`, so this is a per-collection slot, not a\n * per-session counter. Also encoded (descending base-32) as the LSN's\n * third segment — see `lsnParts`.\n */\n seq: number;\n}\n\n/**\n * Per-collection setting controlling how much pre-image data each\n * `U` / `D` entry carries.\n *\n * - `PATCH_ONLY` (default today, applied unconditionally): `U`\n * carries `{ after }`; no `before`, no `key_old`.\n * Bandwidth-cheap. SQL consumers rebuilding before-images need\n * to maintain a shadow table.\n * - `FULL`: `U` additionally carries `before` and `key_old`. ~2× log\n * size on update-heavy collections; buys true 1:1 logical\n * replication and \"previous value\" answerable from the log\n * alone.\n *\n * Per-collection opt-in is not yet wired; every collection is\n * currently `PATCH_ONLY`.\n */\nexport type ReplicaIdentity = \"PATCH_ONLY\" | \"FULL\";\n\n// `LOG_KEY_PREFIX` + `logObjectKey` live in the zero-import `log-key.ts`\n// leaf so consumers that only need the key shape don't drag this module's\n// `lsn` parsing runtime into their bundle closure (it added +3.8 KB raw to\n// `maintenance.js` when the helper lived here).\n\n/** Canonical seq token: the fixed width `countKey` emits. */\nconst SEQ_TOKEN_RE = new RegExp(`^[0-9a-v]{${Math.ceil(COUNT_BIT_WIDTH / 5)}}$`);\n\n/**\n * Extract the `session` and `seq` embedded in an `lsn` of shape\n * `<base32-time>_<session>_<seq>`. The seq portion is decoded as a\n * descending base-32 integer (matches `countKey` in `./types`).\n *\n * Use this at the `/v1/since` cursor-decoding boundary, where a\n * client resumes from an opaque `SinceResponse.next_cursor` and no\n * `LogEntry` is in scope. When iterating `LogEntry` records, read\n * `entry.session` / `entry.seq` directly instead.\n *\n * Throws `BaerlyError{InvalidResponse}` on malformed input: a wrong\n * segment count, or a seq token that is not exactly the canonical\n * fixed-width base-32 string (`[0-9a-v]`, `ceil(COUNT_BIT_WIDTH / 5)`\n * chars) decoding to a non-negative safe integer. Callers should pass\n * only lsns minted by `Writer.commit` (see\n * `packages/server/src/writer.ts`).\n */\nexport const lsnParts = (lsn: string): { session: string; seq: number } => {\n const parts = lsn.split(\"_\");\n if (parts.length !== 3) {\n throw new BaerlyError(\"InvalidResponse\", `invalid lsn shape: ${lsn}`);\n }\n const token = parts[2]!;\n const seq = SEQ_TOKEN_RE.test(token) ? str2uintDesc(token, COUNT_BIT_WIDTH) : NaN;\n if (!Number.isSafeInteger(seq) || seq < 0) {\n throw new BaerlyError(\"InvalidResponse\", `invalid lsn seq: ${lsn}`);\n }\n return { session: parts[1]!, seq };\n};\n","//#region src/compose.ts\n/**\n* Compose middleware functions into a single function based on `koa-compose` package.\n*\n* @template E - The environment type.\n*\n* @param {[[Function, unknown], unknown][] | [[Function]][]} middleware - An array of middleware functions and their corresponding parameters.\n* @param {ErrorHandler<E>} [onError] - An optional error handler function.\n* @param {NotFoundHandler<E>} [onNotFound] - An optional not-found handler function.\n*\n* @returns {(context: Context, next?: Next) => Promise<Context>} - A composed middleware function.\n*/\nconst compose = (middleware, onError, onNotFound) => {\n\treturn (context, next) => {\n\t\tlet index = -1;\n\t\treturn dispatch(0);\n\t\t/**\n\t\t* Dispatch the middleware functions.\n\t\t*\n\t\t* @param {number} i - The current index in the middleware array.\n\t\t*\n\t\t* @returns {Promise<Context>} - A promise that resolves to the context.\n\t\t*/\n\t\tasync function dispatch(i) {\n\t\t\tif (i <= index) throw new Error(\"next() called multiple times\");\n\t\t\tindex = i;\n\t\t\tlet res;\n\t\t\tlet isError = false;\n\t\t\tlet handler;\n\t\t\tif (middleware[i]) {\n\t\t\t\thandler = middleware[i][0][0];\n\t\t\t\tcontext.req.routeIndex = i;\n\t\t\t} else handler = i === middleware.length && next || void 0;\n\t\t\tif (handler) try {\n\t\t\t\tres = await handler(context, () => dispatch(i + 1));\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof Error && onError) {\n\t\t\t\t\tcontext.error = err;\n\t\t\t\t\tres = await onError(err, context);\n\t\t\t\t\tisError = true;\n\t\t\t\t} else throw err;\n\t\t\t}\n\t\t\telse if (context.finalized === false && onNotFound) res = await onNotFound(context);\n\t\t\tif (res && (context.finalized === false || isError)) context.res = res;\n\t\t\treturn context;\n\t\t}\n\t};\n};\n//#endregion\nexport { compose };\n","//#region src/utils/url.ts\nconst splitPath = (path) => {\n\tconst paths = path.split(\"/\");\n\tif (paths[0] === \"\") paths.shift();\n\treturn paths;\n};\nconst splitRoutingPath = (routePath) => {\n\tconst { groups, path } = extractGroupsFromPath(routePath);\n\tconst paths = splitPath(path);\n\treturn replaceGroupMarks(paths, groups);\n};\nconst extractGroupsFromPath = (path) => {\n\tconst groups = [];\n\tpath = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n\t\tconst mark = `@${index}`;\n\t\tgroups.push([mark, match]);\n\t\treturn mark;\n\t});\n\treturn {\n\t\tgroups,\n\t\tpath\n\t};\n};\nconst replaceGroupMarks = (paths, groups) => {\n\tfor (let i = groups.length - 1; i >= 0; i--) {\n\t\tconst [mark] = groups[i];\n\t\tfor (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {\n\t\t\tpaths[j] = paths[j].replace(mark, groups[i][1]);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn paths;\n};\nconst patternCache = {};\nconst getPattern = (label, next) => {\n\tif (label === \"*\") return \"*\";\n\tconst match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n\tif (match) {\n\t\tconst cacheKey = `${label}#${next}`;\n\t\tif (!patternCache[cacheKey]) {\n\t\t\tif (match[2]) patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [\n\t\t\t\tcacheKey,\n\t\t\t\tmatch[1],\n\t\t\t\tnew RegExp(`^${match[2]}(?=/${next})`)\n\t\t\t] : [\n\t\t\t\tlabel,\n\t\t\t\tmatch[1],\n\t\t\t\tnew RegExp(`^${match[2]}$`)\n\t\t\t];\n\t\t\telse patternCache[cacheKey] = [\n\t\t\t\tlabel,\n\t\t\t\tmatch[1],\n\t\t\t\ttrue\n\t\t\t];\n\t\t}\n\t\treturn patternCache[cacheKey];\n\t}\n\treturn null;\n};\nconst tryDecode = (str, decoder) => {\n\ttry {\n\t\treturn decoder(str);\n\t} catch {\n\t\treturn str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n\t\t\ttry {\n\t\t\t\treturn decoder(match);\n\t\t\t} catch {\n\t\t\t\treturn match;\n\t\t\t}\n\t\t});\n\t}\n};\n/**\n* Try to apply decodeURI() to given string.\n* If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible.\n* @param str The string to decode.\n* @returns The decoded string that sometimes contains undecodable percent encoding.\n* @example\n* tryDecodeURI('Hello%20World') // 'Hello World'\n* tryDecodeURI('Hello%20World/%A4%A2') // 'Hello World/%A4%A2'\n*/\nconst tryDecodeURI = (str) => tryDecode(str, decodeURI);\nconst decodeURIWithPreservedPercent = (value) => decodeURI(value.includes(\"%25\") ? value.replace(/%25/g, \"%2525\") : value);\nconst getPath = (request) => {\n\tconst url = request.url;\n\tconst start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n\tlet i = start;\n\tfor (; i < url.length; i++) {\n\t\tconst charCode = url.charCodeAt(i);\n\t\tif (charCode === 37) {\n\t\t\tconst queryIndex = url.indexOf(\"?\", i);\n\t\t\tconst hashIndex = url.indexOf(\"#\", i);\n\t\t\tconst end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n\t\t\tconst path = url.slice(start, end);\n\t\t\tconst decoded = tryDecode(path, decodeURIWithPreservedPercent);\n\t\t\tif (/%(?![0-9A-Fa-f]{2})/.test(path)) {\n\t\t\t\tconst rewritten = new URL(\"http://localhost\");\n\t\t\t\trewritten.pathname = decoded.replace(/[\\\\\\t\\n\\r]/g, encodeURIComponent);\n\t\t\t\tif (tryDecode(rewritten.pathname, decodeURIWithPreservedPercent) !== decoded) return tryDecode(path.replace(/%(?![0-9A-Fa-f]{2})/g, \"%25\"), decodeURIWithPreservedPercent);\n\t\t\t}\n\t\t\treturn decoded;\n\t\t} else if (charCode === 63 || charCode === 35) break;\n\t}\n\treturn url.slice(start, i);\n};\n/**\n* @deprecated\n* Use the `URL` API instead.\n*/\nconst getQueryStrings = (url) => {\n\tconst queryIndex = url.indexOf(\"?\", 8);\n\tif (queryIndex === -1) return \"\";\n\tconst hashIndex = url.indexOf(\"#\", 8);\n\treturn hashIndex === -1 ? url.slice(queryIndex) : queryIndex < hashIndex ? url.slice(queryIndex, hashIndex) : \"\";\n};\nconst getPathNoStrict = (request) => {\n\tconst result = getPath(request);\n\treturn result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\n/**\n* Merge paths.\n* @param {string[]} ...paths - The paths to merge.\n* @returns {string} The merged path.\n* @example\n* mergePath('/api', '/users') // '/api/users'\n* mergePath('/api/', '/users') // '/api/users'\n* mergePath('/api', '/') // '/api'\n* mergePath('/api/', '/') // '/api/'\n*/\nconst mergePath = (base, sub, ...rest) => {\n\tif (rest.length) sub = mergePath(sub, ...rest);\n\treturn `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nconst checkOptionalParameter = (path) => {\n\tif (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) return null;\n\tconst segments = path.split(\"/\");\n\tconst results = [];\n\tlet basePath = \"\";\n\tsegments.forEach((segment) => {\n\t\tif (segment !== \"\" && !/\\:/.test(segment)) basePath += \"/\" + segment;\n\t\telse if (/\\:/.test(segment)) {\n\t\t\tif (segment.charCodeAt(segment.length - 1) === 63) {\n\t\t\t\tif (results.length === 0 && basePath === \"\") results.push(\"/\");\n\t\t\t\telse results.push(basePath);\n\t\t\t\tconst optionalSegment = segment.slice(0, -1);\n\t\t\t\tbasePath += \"/\" + optionalSegment;\n\t\t\t\tresults.push(basePath);\n\t\t\t} else basePath += \"/\" + segment;\n\t\t}\n\t});\n\treturn results.filter((v, i, a) => a.indexOf(v) === i);\n};\nconst tryDecodeURIComponent = (str) => str.indexOf(\"%\") !== -1 ? tryDecode(str, decodeURIComponent_) : str;\nconst _decodeURI = (value) => {\n\tif (value.indexOf(\"+\") !== -1) value = value.replace(/\\+/g, \" \");\n\treturn tryDecodeURIComponent(value);\n};\nconst _getQueryParam = (url, key, multiple) => {\n\tconst hashIndex = url.indexOf(\"#\", 8);\n\tif (hashIndex !== -1) url = url.slice(0, hashIndex);\n\tlet encoded;\n\tif (!multiple && key && !/[%+&=]/.test(key)) {\n\t\tconst queryIndex = url.indexOf(\"?\", 8);\n\t\tlet keyIndex = queryIndex;\n\t\tif (keyIndex === -1) return;\n\t\tif (!url.startsWith(key, keyIndex + 1)) keyIndex = url.indexOf(`&${key}`, keyIndex + 1);\n\t\twhile (keyIndex !== -1) {\n\t\t\tconst trailingKeyCode = url.charCodeAt(keyIndex + key.length + 1);\n\t\t\tif (trailingKeyCode === 61 || trailingKeyCode === 38 || isNaN(trailingKeyCode)) {\n\t\t\t\tif (keyIndex > queryIndex && /(?:^|&)[^=&]*[%+]/.test(url.slice(queryIndex + 1, keyIndex))) break;\n\t\t\t\tif (trailingKeyCode === 61) {\n\t\t\t\t\tconst valueIndex = keyIndex + key.length + 2;\n\t\t\t\t\tconst endIndex = url.indexOf(\"&\", valueIndex);\n\t\t\t\t\treturn _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n\t\t\t\t}\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\tkeyIndex = url.indexOf(`&${key}`, keyIndex + 1);\n\t\t}\n\t\tencoded = /[%+]/.test(url);\n\t\tif (!encoded) return;\n\t}\n\tconst results = Object.create(null);\n\tencoded ??= /[%+]/.test(url);\n\tlet keyIndex = url.indexOf(\"?\", 8);\n\twhile (keyIndex !== -1) {\n\t\tconst nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n\t\tlet valueIndex = url.indexOf(\"=\", keyIndex);\n\t\tif (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;\n\t\tlet name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);\n\t\tif (encoded) name = _decodeURI(name);\n\t\tkeyIndex = nextKeyIndex;\n\t\tif (name === \"\") continue;\n\t\tlet value;\n\t\tif (valueIndex === -1) value = \"\";\n\t\telse {\n\t\t\tvalue = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n\t\t\tif (encoded) value = _decodeURI(value);\n\t\t}\n\t\tif (multiple) {\n\t\t\tif (!(results[name] && Array.isArray(results[name]))) results[name] = [];\n\t\t\tresults[name].push(value);\n\t\t} else results[name] ??= value;\n\t}\n\treturn key ? results[key] : results;\n};\nconst getQueryParam = _getQueryParam;\nconst getQueryParams = (url, key) => {\n\treturn _getQueryParam(url, key, true);\n};\nconst decodeURIComponent_ = decodeURIComponent;\n//#endregion\nexport { checkOptionalParameter, decodeURIComponent_, getPath, getPathNoStrict, getPattern, getQueryParam, getQueryParams, getQueryStrings, mergePath, splitPath, splitRoutingPath, tryDecode, tryDecodeURI, tryDecodeURIComponent };\n","//#region src/http-exception.ts\n/**\n* `HTTPException` must be used when a fatal error such as authentication failure occurs.\n*\n* @see {@link https://hono.dev/docs/api/exception}\n*\n* @param {StatusCode} status - status code of HTTPException\n* @param {HTTPExceptionOptions} options - options of HTTPException\n* @param {HTTPExceptionOptions[\"res\"]} options.res - response of options of HTTPException\n* @param {HTTPExceptionOptions[\"message\"]} options.message - message of options of HTTPException\n* @param {HTTPExceptionOptions[\"cause\"]} options.cause - cause of options of HTTPException\n*\n* @example\n* ```ts\n* import { HTTPException } from 'hono/http-exception'\n*\n* // ...\n*\n* app.post('/auth', async (c, next) => {\n* // authentication\n* if (authorized === false) {\n* throw new HTTPException(401, { message: 'Custom error message' })\n* }\n* await next()\n* })\n* ```\n*/\nvar HTTPException = class extends Error {\n\tres;\n\tstatus;\n\t/**\n\t* Creates an instance of `HTTPException`.\n\t* @param status - HTTP status code for the exception. Defaults to 500.\n\t* @param options - Additional options for the exception.\n\t*/\n\tconstructor(status = 500, options) {\n\t\tsuper(options?.message, { cause: options?.cause });\n\t\tthis.res = options?.res;\n\t\tthis.status = status;\n\t}\n\t/**\n\t* Returns the response object associated with the exception.\n\t* If a response object is not provided, a new response is created with the error message and status code.\n\t* @returns The response object.\n\t*/\n\tgetResponse() {\n\t\tif (this.res) return new Response(this.res.body, {\n\t\t\tstatus: this.status,\n\t\t\theaders: this.res.headers\n\t\t});\n\t\treturn new Response(this.message, { status: this.status });\n\t}\n};\n//#endregion\nexport { HTTPException };\n","//#region src/request/constants.ts\nconst GET_MATCH_RESULT = Symbol();\n//#endregion\nexport { GET_MATCH_RESULT };\n","import { sha256 } from \"./crypto.js\";\n//#region src/utils/buffer.ts\n/**\n* @module\n* Buffer utility.\n*/\nconst equal = (a, b) => {\n\tif (a === b) return true;\n\tif (a.byteLength !== b.byteLength) return false;\n\tconst va = new DataView(a);\n\tconst vb = new DataView(b);\n\tlet i = va.byteLength;\n\twhile (i--) if (va.getUint8(i) !== vb.getUint8(i)) return false;\n\treturn true;\n};\nconst constantTimeEqualString = (a, b) => {\n\tconst aLen = a.length;\n\tconst bLen = b.length;\n\tconst maxLen = Math.max(aLen, bLen);\n\tlet out = aLen ^ bLen;\n\tfor (let i = 0; i < maxLen; i++) {\n\t\tconst aChar = i < aLen ? a.charCodeAt(i) : 0;\n\t\tconst bChar = i < bLen ? b.charCodeAt(i) : 0;\n\t\tout |= aChar ^ bChar;\n\t}\n\treturn out === 0;\n};\nconst timingSafeEqualString = async (a, b, hashFunction) => {\n\tif (!hashFunction) hashFunction = sha256;\n\tconst [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n\tif (sa == null || sb == null || typeof sa !== \"string\" || typeof sb !== \"string\") return false;\n\tconst hashEqual = constantTimeEqualString(sa, sb);\n\tconst originalEqual = constantTimeEqualString(a, b);\n\treturn hashEqual && originalEqual;\n};\nconst timingSafeEqual = async (a, b, hashFunction) => {\n\tif (typeof a === \"string\" && typeof b === \"string\") return timingSafeEqualString(a, b, hashFunction);\n\tif (!hashFunction) hashFunction = sha256;\n\tconst [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]);\n\tif (!sa || !sb || typeof sa !== \"string\" || typeof sb !== \"string\") return false;\n\treturn timingSafeEqualString(sa, sb);\n};\nconst bufferToString = (buffer) => {\n\tif (buffer instanceof ArrayBuffer) return new TextDecoder(\"utf-8\").decode(buffer);\n\treturn buffer;\n};\nconst bufferToFormData = (arrayBuffer, contentType) => {\n\treturn new Response(arrayBuffer, { headers: { \"Content-Type\": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase()) } }).formData();\n};\n//#endregion\nexport { bufferToFormData, bufferToString, equal, timingSafeEqual };\n","import { bufferToFormData } from \"./buffer.js\";\n//#region src/utils/body.ts\nconst MAX_NESTED_OBJECTS = 1e4;\nconst isRawRequest = (request) => \"headers\" in request;\nconst parseBody = async (request, options = Object.create(null)) => {\n\tconst { all = false, dot = false } = options;\n\tconst mediaType = (isRawRequest(request) ? request.headers : request.raw.headers).get(\"Content-Type\")?.split(\";\")[0].trim().toLowerCase();\n\tif (mediaType === \"multipart/form-data\" || mediaType === \"application/x-www-form-urlencoded\") return parseFormData(request, {\n\t\tall,\n\t\tdot\n\t});\n\treturn {};\n};\n/**\n* Parses form data from a request.\n*\n* @template T - The type of the parsed body data.\n* @param {HonoRequest | Request} request - The request object containing form data.\n* @param {ParseBodyOptions} options - Options for parsing the form data.\n* @returns {Promise<T>} The parsed body data.\n*/\nasync function parseFormData(request, options) {\n\tif (!isRawRequest(request) && request.bodyCache.formData) return convertFormDataToBodyData(await request.bodyCache.formData, options);\n\tconst headers = isRawRequest(request) ? request.headers : request.raw.headers;\n\tconst arrayBuffer = await request.arrayBuffer();\n\tconst formDataPromise = bufferToFormData(arrayBuffer, headers.get(\"Content-Type\") || \"\");\n\tif (!isRawRequest(request)) request.bodyCache.formData = formDataPromise;\n\tconst formData = await formDataPromise;\n\tif (formData) return convertFormDataToBodyData(formData, options);\n\treturn {};\n}\n/**\n* Converts form data to body data based on the provided options.\n*\n* @template T - The type of the parsed body data.\n* @param {FormData} formData - The form data to convert.\n* @param {ParseBodyOptions} options - Options for parsing the form data.\n* @returns {T} The converted body data.\n*/\nfunction convertFormDataToBodyData(formData, options) {\n\tconst form = Object.create(null);\n\tconst nestingState = { count: 0 };\n\tformData.forEach((value, key) => {\n\t\tif (!(options.all || key.endsWith(\"[]\"))) form[key] = value;\n\t\telse handleParsingAllValues(form, key, value);\n\t});\n\tif (options.dot) Object.entries(form).forEach(([key, value]) => {\n\t\tif (key.includes(\".\")) {\n\t\t\thandleParsingNestedValues(form, key, value, nestingState);\n\t\t\tdelete form[key];\n\t\t}\n\t});\n\treturn form;\n}\n/**\n* Handles parsing all values for a given key, supporting multiple values as arrays.\n*\n* @param {BodyData} form - The form data object.\n* @param {string} key - The key to parse.\n* @param {FormDataEntryValue} value - The value to assign.\n*/\nconst handleParsingAllValues = (form, key, value) => {\n\tif (form[key] !== void 0) {\n\t\tif (Array.isArray(form[key])) form[key].push(value);\n\t\telse form[key] = [form[key], value];\n\t} else if (!key.endsWith(\"[]\")) form[key] = value;\n\telse form[key] = [value];\n};\n/**\n* Handles parsing nested values using dot notation keys.\n*\n* @param {BodyData} form - The form data object.\n* @param {string} key - The dot notation key.\n* @param {BodyDataValue} value - The value to assign.\n* @param {{ count: number }} state - The state object tracking nesting depth.\n*/\nconst handleParsingNestedValues = (form, key, value, state) => {\n\tif (/(?:^|\\.)__proto__\\./.test(key)) return;\n\tlet nestedForm = form;\n\tconst keys = key.split(\".\", 34);\n\tif (keys.length > 33) throwNestingLimitExceeded();\n\tkeys.forEach((key, index) => {\n\t\tif (index === keys.length - 1) nestedForm[key] = value;\n\t\telse {\n\t\t\tif (!nestedForm[key] || typeof nestedForm[key] !== \"object\" || Array.isArray(nestedForm[key]) || nestedForm[key] instanceof File) {\n\t\t\t\tif (state.count++ >= MAX_NESTED_OBJECTS) throwNestingLimitExceeded();\n\t\t\t\tnestedForm[key] = Object.create(null);\n\t\t\t}\n\t\t\tnestedForm = nestedForm[key];\n\t\t}\n\t});\n};\nconst throwNestingLimitExceeded = () => {\n\tthrow new Error(\"Nesting limit exceeded\");\n};\n//#endregion\nexport { parseBody };\n","import { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { getQueryParam, getQueryParams, tryDecodeURIComponent } from \"./utils/url.js\";\n//#region src/request.ts\nvar HonoRequest = class {\n\t/**\n\t* `.raw` can get the raw Request object.\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#raw}\n\t*\n\t* @example\n\t* ```ts\n\t* // For Cloudflare Workers\n\t* app.post('/', async (c) => {\n\t* const metadata = c.req.raw.cf?.hostMetadata?\n\t* ...\n\t* })\n\t* ```\n\t*/\n\traw;\n\t#validatedData;\n\t#matchResult;\n\trouteIndex = 0;\n\t/**\n\t* `.path` can get the pathname of the request.\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#path}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/about/me', (c) => {\n\t* const pathname = c.req.path // `/about/me`\n\t* })\n\t* ```\n\t*/\n\tpath;\n\tbodyCache = {};\n\tconstructor(request, path = \"/\", matchResult = [[]]) {\n\t\tthis.raw = request;\n\t\tthis.path = path;\n\t\tthis.#matchResult = matchResult;\n\t}\n\tparam(key) {\n\t\treturn key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n\t}\n\t#getDecodedParam(key) {\n\t\tconst paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];\n\t\tconst param = this.#getParamValue(paramKey);\n\t\treturn param && tryDecodeURIComponent(param);\n\t}\n\t#getAllDecodedParams() {\n\t\tconst decoded = {};\n\t\tconst keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});\n\t\tfor (const key of keys) {\n\t\t\tconst value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n\t\t\tif (value !== void 0) decoded[key] = tryDecodeURIComponent(value);\n\t\t}\n\t\treturn decoded;\n\t}\n\t#getParamValue(paramKey) {\n\t\treturn this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n\t}\n\tquery(key) {\n\t\treturn getQueryParam(this.url, key);\n\t}\n\tqueries(key) {\n\t\treturn getQueryParams(this.url, key);\n\t}\n\theader(name) {\n\t\tif (name) return this.raw.headers.get(name) ?? void 0;\n\t\tconst headerData = Object.create(null);\n\t\tthis.raw.headers.forEach((value, key) => {\n\t\t\theaderData[key] = value;\n\t\t});\n\t\treturn headerData;\n\t}\n\tasync parseBody(options) {\n\t\treturn parseBody(this, options);\n\t}\n\t#cachedBody = (key) => {\n\t\tconst { bodyCache, raw } = this;\n\t\tconst cachedBody = bodyCache[key];\n\t\tif (cachedBody) return cachedBody;\n\t\tfor (const anyCachedKey in bodyCache) return bodyCache[anyCachedKey].then((body) => {\n\t\t\tif (anyCachedKey === \"json\") body = JSON.stringify(body);\n\t\t\tconst contentType = anyCachedKey === \"formData\" ? void 0 : raw.headers.get(\"content-type\");\n\t\t\treturn new Response(body, { headers: contentType ? { \"Content-Type\": contentType } : void 0 })[key]();\n\t\t});\n\t\treturn bodyCache[key] = raw[key]();\n\t};\n\t/**\n\t* `.json()` can parse Request body of type `application/json`\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#json}\n\t*\n\t* @example\n\t* ```ts\n\t* app.post('/entry', async (c) => {\n\t* const body = await c.req.json()\n\t* })\n\t* ```\n\t*/\n\tjson() {\n\t\treturn this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n\t}\n\t/**\n\t* `.text()` can parse Request body of type `text/plain`\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#text}\n\t*\n\t* @example\n\t* ```ts\n\t* app.post('/entry', async (c) => {\n\t* const body = await c.req.text()\n\t* })\n\t* ```\n\t*/\n\ttext() {\n\t\treturn this.#cachedBody(\"text\");\n\t}\n\t/**\n\t* `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#arraybuffer}\n\t*\n\t* @example\n\t* ```ts\n\t* app.post('/entry', async (c) => {\n\t* const body = await c.req.arrayBuffer()\n\t* })\n\t* ```\n\t*/\n\tarrayBuffer() {\n\t\treturn this.#cachedBody(\"arrayBuffer\");\n\t}\n\t/**\n\t* `.bytes()` parses the request body as a `Uint8Array`.\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#bytes}\n\t*\n\t* @example\n\t* ```ts\n\t* app.post('/entry', async (c) => {\n\t* const body = await c.req.bytes()\n\t* })\n\t* ```\n\t*/\n\tbytes() {\n\t\treturn this.#cachedBody(\"arrayBuffer\").then((buffer) => new Uint8Array(buffer));\n\t}\n\t/**\n\t* Parses the request body as a `Blob`.\n\t* @example\n\t* ```ts\n\t* app.post('/entry', async (c) => {\n\t* const body = await c.req.blob();\n\t* });\n\t* ```\n\t* @see https://hono.dev/docs/api/request#blob\n\t*/\n\tblob() {\n\t\treturn this.#cachedBody(\"blob\");\n\t}\n\t/**\n\t* Parses the request body as `FormData`.\n\t* @example\n\t* ```ts\n\t* app.post('/entry', async (c) => {\n\t* const body = await c.req.formData();\n\t* });\n\t* ```\n\t* @see https://hono.dev/docs/api/request#formdata\n\t*/\n\tformData() {\n\t\treturn this.#cachedBody(\"formData\");\n\t}\n\t/**\n\t* Adds validated data to the request.\n\t*\n\t* @param target - The target of the validation.\n\t* @param data - The validated data to add.\n\t*/\n\taddValidatedData(target, data) {\n\t\t(this.#validatedData ??= {})[target] = data;\n\t}\n\tvalid(target) {\n\t\treturn this.#validatedData?.[target];\n\t}\n\t/**\n\t* `.url` can get the request url strings.\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#url}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/about/me', (c) => {\n\t* const url = c.req.url // `http://localhost:8787/about/me`\n\t* ...\n\t* })\n\t* ```\n\t*/\n\tget url() {\n\t\treturn this.raw.url;\n\t}\n\t/**\n\t* `.method` can get the method name of the request.\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#method}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/about/me', (c) => {\n\t* const method = c.req.method // `GET`\n\t* })\n\t* ```\n\t*/\n\tget method() {\n\t\treturn this.raw.method;\n\t}\n\tget [GET_MATCH_RESULT]() {\n\t\treturn this.#matchResult;\n\t}\n\t/**\n\t* `.matchedRoutes` can return a matched route in the handler\n\t*\n\t* @deprecated\n\t*\n\t* Use matchedRoutes helper defined in \"hono/route\" instead.\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#matchedroutes}\n\t*\n\t* @example\n\t* ```ts\n\t* app.use('*', async function logger(c, next) {\n\t* await next()\n\t* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n\t* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n\t* console.log(\n\t* method,\n\t* ' ',\n\t* path,\n\t* ' '.repeat(Math.max(10 - path.length, 0)),\n\t* name,\n\t* i === c.req.routeIndex ? '<- respond from here' : ''\n\t* )\n\t* })\n\t* })\n\t* ```\n\t*/\n\tget matchedRoutes() {\n\t\treturn this.#matchResult[0].map(([[, route]]) => route);\n\t}\n\t/**\n\t* `.routePath` can retrieve the path registered within the handler\n\t*\n\t* @deprecated\n\t*\n\t* Use routePath helper defined in \"hono/route\" instead.\n\t*\n\t* @see {@link https://hono.dev/docs/api/request#routepath}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/posts/:id', (c) => {\n\t* return c.json({ path: c.req.routePath })\n\t* })\n\t* ```\n\t*/\n\tget routePath() {\n\t\treturn this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n\t}\n};\n/**\n* Clones a HonoRequest's underlying raw Request object.\n*\n* This utility handles both consumed and unconsumed request bodies:\n* - If the request body hasn't been consumed, it uses the native `clone()` method\n* - If the request body has been consumed, it reconstructs a new Request using cached body data\n*\n* This is particularly useful when you need to:\n* - Process the same request body multiple times\n* - Pass requests to external services after validation\n*\n* @param req - The HonoRequest object to clone\n* @returns A Promise that resolves to a new Request object with the same properties\n* @throws {HTTPException} If the request body was consumed directly via `req.raw`\n* without using HonoRequest methods (e.g., `req.json()`, `req.text()`), making it\n* impossible to reconstruct the body from cache\n*\n* @example\n* ```ts\n* // Clone after consuming the body (e.g., after validation)\n* app.post('/forward',\n* validator('json', (data) => data),\n* async (c) => {\n* const validated = c.req.valid('json')\n* // Body has been consumed, but cloneRawRequest still works\n* const clonedReq = await cloneRawRequest(c.req)\n* return fetch('http://backend-service.com', clonedReq)\n* }\n* )\n* ```\n*/\nconst cloneRawRequest = async (req) => {\n\tif (!req.raw.bodyUsed) return req.raw.clone();\n\tconst cacheKey = Object.keys(req.bodyCache)[0];\n\tif (!cacheKey) throw new HTTPException(500, { message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\" });\n\tlet body = await req[cacheKey]();\n\tconst headers = req.header();\n\tif (cacheKey === \"json\") {\n\t\tbody = JSON.stringify(body);\n\t\tdelete headers[\"content-length\"];\n\t} else if (body instanceof FormData) {\n\t\tdelete headers[\"content-type\"];\n\t\tdelete headers[\"content-length\"];\n\t}\n\tconst requestInit = {\n\t\tbody,\n\t\tcache: req.raw.cache,\n\t\tcredentials: req.raw.credentials,\n\t\theaders,\n\t\tintegrity: req.raw.integrity,\n\t\tkeepalive: req.raw.keepalive,\n\t\tmethod: req.method,\n\t\tmode: req.raw.mode,\n\t\tredirect: req.raw.redirect,\n\t\treferrer: req.raw.referrer,\n\t\treferrerPolicy: req.raw.referrerPolicy,\n\t\tsignal: req.raw.signal\n\t};\n\treturn new Request(req.url, requestInit);\n};\n//#endregion\nexport { HonoRequest, cloneRawRequest };\n","//#region src/utils/html.ts\n/**\n* @module\n* HTML utility.\n*/\nconst HtmlEscapedCallbackPhase = {\n\tStringify: 1,\n\tBeforeStream: 2,\n\tStream: 3\n};\nconst raw = (value, callbacks) => {\n\tconst escapedString = new String(value);\n\tescapedString.isEscaped = true;\n\tescapedString.callbacks = callbacks;\n\treturn escapedString;\n};\nconst escapeRe = /[&<>'\"]/;\nconst stringBufferToString = async (buffer, callbacks) => {\n\tlet str = \"\";\n\tcallbacks ||= [];\n\tconst resolvedBuffer = await Promise.all(buffer);\n\tfor (let i = resolvedBuffer.length - 1;; i--) {\n\t\tstr += resolvedBuffer[i];\n\t\ti--;\n\t\tif (i < 0) break;\n\t\tlet r = resolvedBuffer[i];\n\t\tif (r == null || typeof r === \"boolean\") continue;\n\t\tif (typeof r === \"number\") {\n\t\t\tstr += r;\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof r === \"object\") callbacks.push(...r.callbacks || []);\n\t\tconst isEscaped = r.isEscaped;\n\t\tr = await (typeof r === \"object\" ? r.toString() : r);\n\t\tif (typeof r === \"object\") callbacks.push(...r.callbacks || []);\n\t\tif (r.isEscaped ?? isEscaped) str += r;\n\t\telse {\n\t\t\tconst buf = [str];\n\t\t\tescapeToBuffer(r, buf);\n\t\t\tstr = buf[0];\n\t\t}\n\t}\n\treturn raw(str, callbacks);\n};\nconst escapeToBuffer = (str, buffer) => {\n\tconst match = str.search(escapeRe);\n\tif (match === -1) {\n\t\tbuffer[0] += str;\n\t\treturn;\n\t}\n\tlet escape;\n\tlet index;\n\tlet lastIndex = 0;\n\tfor (index = match; index < str.length; index++) {\n\t\tswitch (str.charCodeAt(index)) {\n\t\t\tcase 34:\n\t\t\t\tescape = \"&quot;\";\n\t\t\t\tbreak;\n\t\t\tcase 39:\n\t\t\t\tescape = \"&#39;\";\n\t\t\t\tbreak;\n\t\t\tcase 38:\n\t\t\t\tescape = \"&amp;\";\n\t\t\t\tbreak;\n\t\t\tcase 60:\n\t\t\t\tescape = \"&lt;\";\n\t\t\t\tbreak;\n\t\t\tcase 62:\n\t\t\t\tescape = \"&gt;\";\n\t\t\t\tbreak;\n\t\t\tdefault: continue;\n\t\t}\n\t\tbuffer[0] += str.substring(lastIndex, index) + escape;\n\t\tlastIndex = index + 1;\n\t}\n\tbuffer[0] += str.substring(lastIndex, index);\n};\nconst resolveCallbackSync = (str) => {\n\tconst callbacks = str.callbacks;\n\tif (!callbacks?.length) return str;\n\tconst buffer = [str];\n\tconst context = {};\n\tcallbacks.forEach((c) => c({\n\t\tphase: HtmlEscapedCallbackPhase.Stringify,\n\t\tbuffer,\n\t\tcontext\n\t}));\n\treturn buffer[0];\n};\nconst resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n\tif (typeof str === \"object\" && !(str instanceof String)) {\n\t\tif (!(str instanceof Promise)) str = str.toString();\n\t\tif (str instanceof Promise) str = await str;\n\t}\n\tconst callbacks = str.callbacks;\n\tif (!callbacks?.length) return Promise.resolve(str);\n\tif (buffer) buffer[0] += str;\n\telse buffer = [str];\n\tconst resStr = Promise.all(callbacks.map((c) => c({\n\t\tphase,\n\t\tbuffer,\n\t\tcontext\n\t}))).then((res) => Promise.all(res.filter(Boolean).map((str) => resolveCallback(str, phase, false, context, buffer))).then(() => buffer[0]));\n\tif (preserveCallbacks) return raw(await resStr, callbacks);\n\telse return resStr;\n};\n//#endregion\nexport { HtmlEscapedCallbackPhase, escapeToBuffer, raw, resolveCallback, resolveCallbackSync, stringBufferToString };\n","import { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\n//#region src/context.ts\nconst TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nconst setDefaultContentType = (contentType, headers) => {\n\treturn {\n\t\t\"Content-Type\": contentType,\n\t\t...headers\n\t};\n};\nconst createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n\t#rawRequest;\n\t#req;\n\t/**\n\t* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#env}\n\t*\n\t* @example\n\t* ```ts\n\t* // Environment object for Cloudflare Workers\n\t* app.get('*', async c => {\n\t* const counter = c.env.COUNTER\n\t* })\n\t* ```\n\t*/\n\tenv = {};\n\t#var;\n\tfinalized = false;\n\t/**\n\t* `.error` can get the error object from the middleware if the Handler throws an error.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#error}\n\t*\n\t* @example\n\t* ```ts\n\t* app.use('*', async (c, next) => {\n\t* await next()\n\t* if (c.error) {\n\t* // do something...\n\t* }\n\t* })\n\t* ```\n\t*/\n\terror;\n\t#status;\n\t#executionCtx;\n\t#res;\n\t#layout;\n\t#renderer;\n\t#notFoundHandler;\n\t#preparedHeaders;\n\t#matchResult;\n\t#path;\n\t/**\n\t* Creates an instance of the Context class.\n\t*\n\t* @param req - The Request object.\n\t* @param options - Optional configuration options for the context.\n\t*/\n\tconstructor(req, options) {\n\t\tthis.#rawRequest = req;\n\t\tif (options) {\n\t\t\tthis.#executionCtx = options.executionCtx;\n\t\t\tthis.env = options.env;\n\t\t\tthis.#notFoundHandler = options.notFoundHandler;\n\t\t\tthis.#path = options.path;\n\t\t\tthis.#matchResult = options.matchResult;\n\t\t}\n\t}\n\t/**\n\t* `.req` is the instance of {@link HonoRequest}.\n\t*/\n\tget req() {\n\t\tthis.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n\t\treturn this.#req;\n\t}\n\t/**\n\t* @see {@link https://hono.dev/docs/api/context#event}\n\t* The FetchEvent associated with the current request.\n\t*\n\t* @throws Will throw an error if the context does not have a FetchEvent.\n\t*/\n\tget event() {\n\t\tif (this.#executionCtx && \"respondWith\" in this.#executionCtx) return this.#executionCtx;\n\t\telse throw Error(\"This context has no FetchEvent\");\n\t}\n\t/**\n\t* @see {@link https://hono.dev/docs/api/context#executionctx}\n\t* The ExecutionContext associated with the current request.\n\t*\n\t* @throws Will throw an error if the context does not have an ExecutionContext.\n\t*/\n\tget executionCtx() {\n\t\tif (this.#executionCtx) return this.#executionCtx;\n\t\telse throw Error(\"This context has no ExecutionContext\");\n\t}\n\t/**\n\t* @see {@link https://hono.dev/docs/api/context#res}\n\t* The Response object for the current request.\n\t*/\n\tget res() {\n\t\treturn this.#res ||= createResponseInstance(null, { headers: this.#preparedHeaders ??= new Headers() });\n\t}\n\t/**\n\t* Sets the Response object for the current request.\n\t*\n\t* @param _res - The Response object to set.\n\t*/\n\tset res(_res) {\n\t\tif (this.#res && _res) {\n\t\t\t_res = createResponseInstance(_res.body, _res);\n\t\t\tfor (const [k, v] of this.#res.headers.entries()) {\n\t\t\t\tif (k === \"content-type\") continue;\n\t\t\t\tif (k === \"set-cookie\") {\n\t\t\t\t\tconst cookies = this.#res.headers.getSetCookie();\n\t\t\t\t\t_res.headers.delete(\"set-cookie\");\n\t\t\t\t\tfor (const cookie of cookies) _res.headers.append(\"set-cookie\", cookie);\n\t\t\t\t} else _res.headers.set(k, v);\n\t\t\t}\n\t\t}\n\t\tthis.#res = _res;\n\t\tthis.finalized = true;\n\t}\n\t/**\n\t* `.render()` can create a response within a layout.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/', (c) => {\n\t* return c.render('Hello!')\n\t* })\n\t* ```\n\t*/\n\trender = (...args) => {\n\t\tthis.#renderer ??= (content) => this.html(content);\n\t\treturn this.#renderer(...args);\n\t};\n\t/**\n\t* Sets the layout for the response.\n\t*\n\t* @param layout - The layout to set.\n\t* @returns The layout function.\n\t*/\n\tsetLayout = (layout) => this.#layout = layout;\n\t/**\n\t* Gets the current layout for the response.\n\t*\n\t* @returns The current layout function.\n\t*/\n\tgetLayout = () => this.#layout;\n\t/**\n\t* `.setRenderer()` can set the layout in the custom middleware.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n\t*\n\t* @example\n\t* ```tsx\n\t* app.use('*', async (c, next) => {\n\t* c.setRenderer((content) => {\n\t* return c.html(\n\t* <html>\n\t* <body>\n\t* <p>{content}</p>\n\t* </body>\n\t* </html>\n\t* )\n\t* })\n\t* await next()\n\t* })\n\t* ```\n\t*/\n\tsetRenderer = (renderer) => {\n\t\tthis.#renderer = renderer;\n\t};\n\t/**\n\t* `.header()` can set headers.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#header}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/welcome', (c) => {\n\t* // Set headers\n\t* c.header('X-Message', 'Hello!')\n\t* c.header('Content-Type', 'text/plain')\n\t*\n\t* // Append multiple headers using the append option (e.g. Vary)\n\t* c.header('Vary', 'Accept-Encoding', { append: true })\n\t* c.header('Vary', 'User-Agent', { append: true })\n\t*\n\t* return c.body('Thank you for coming')\n\t* })\n\t* ```\n\t*/\n\theader = (name, value, options) => {\n\t\tif (this.finalized && !this.#res.bodyUsed) this.#res = createResponseInstance(this.#res.body, this.#res);\n\t\tconst headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n\t\tif (value === void 0) headers.delete(name);\n\t\telse if (options?.append) headers.append(name, value);\n\t\telse headers.set(name, value);\n\t};\n\tstatus = (status) => {\n\t\tthis.#status = status;\n\t};\n\t/**\n\t* `.set()` can set the value specified by the key.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#set-get}\n\t*\n\t* @example\n\t* ```ts\n\t* app.use('*', async (c, next) => {\n\t* c.set('message', 'Hono is hot!!')\n\t* await next()\n\t* })\n\t* ```\n\t*/\n\tset = (key, value) => {\n\t\tthis.#var ??= /* @__PURE__ */ new Map();\n\t\tthis.#var.set(key, value);\n\t};\n\t/**\n\t* `.get()` can use the value specified by the key.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#set-get}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/', (c) => {\n\t* const message = c.get('message')\n\t* return c.text(`The message is \"${message}\"`)\n\t* })\n\t* ```\n\t*/\n\tget = (key) => {\n\t\treturn this.#var ? this.#var.get(key) : void 0;\n\t};\n\t/**\n\t* `.var` can access the value of a variable.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#var}\n\t*\n\t* @example\n\t* ```ts\n\t* const result = c.var.client.oneMethod()\n\t* ```\n\t*/\n\tget var() {\n\t\tif (!this.#var) return {};\n\t\treturn Object.fromEntries(this.#var);\n\t}\n\t#newResponse(data, arg, headers) {\n\t\tlet responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;\n\t\tif (typeof arg === \"object\" && arg.headers) {\n\t\t\tresponseHeaders ??= new Headers();\n\t\t\tfor (const [key, value] of new Headers(arg.headers)) if (key === \"set-cookie\") responseHeaders.append(key, value);\n\t\t\telse responseHeaders.set(key, value);\n\t\t}\n\t\tif (headers) {\n\t\t\tif (!responseHeaders) {\n\t\t\t\tlet count = 0;\n\t\t\t\tfor (const k in headers) if (++count > 1 || typeof headers[k] !== \"string\") {\n\t\t\t\t\tresponseHeaders = new Headers();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (responseHeaders) for (const k in headers) {\n\t\t\t\tconst v = headers[k];\n\t\t\t\tif (typeof v === \"string\") responseHeaders.set(k, v);\n\t\t\t\telse {\n\t\t\t\t\tresponseHeaders.delete(k);\n\t\t\t\t\tfor (const v2 of v) responseHeaders.append(k, v2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n\t\treturn createResponseInstance(data, {\n\t\t\tstatus,\n\t\t\theaders: responseHeaders ?? headers\n\t\t});\n\t}\n\tnewResponse = (...args) => this.#newResponse(...args);\n\t/**\n\t* `.body()` can return the HTTP response.\n\t* You can set headers with `.header()` and set HTTP status code with `.status`.\n\t* This can also be set in `.text()`, `.json()` and so on.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#body}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/welcome', (c) => {\n\t* // Set headers\n\t* c.header('X-Message', 'Hello!')\n\t* c.header('Content-Type', 'text/plain')\n\t* // Set HTTP status code\n\t* c.status(201)\n\t*\n\t* // Return the response body\n\t* return c.body('Thank you for coming')\n\t* })\n\t* ```\n\t*/\n\tbody = (data, arg, headers) => this.#newResponse(data, arg, headers);\n\t/**\n\t* `.text()` can render text as `Content-Type:text/plain`.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#text}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/say', (c) => {\n\t* return c.text('Hello!')\n\t* })\n\t* ```\n\t*/\n\ttext = (text, arg, headers) => {\n\t\treturn !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));\n\t};\n\t/**\n\t* `.json()` can render JSON as `Content-Type:application/json`.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#json}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/api', (c) => {\n\t* return c.json({ message: 'Hello!' })\n\t* })\n\t* ```\n\t*/\n\tjson = (object, arg, headers) => {\n\t\treturn this.#newResponse(JSON.stringify(object), arg, setDefaultContentType(\"application/json\", headers));\n\t};\n\thtml = (html, arg, headers) => {\n\t\tconst res = (html) => this.#newResponse(html, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n\t\treturn typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n\t};\n\t/**\n\t* `.redirect()` can Redirect, default status code is 302.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#redirect}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/redirect', (c) => {\n\t* return c.redirect('/')\n\t* })\n\t* app.get('/redirect-permanently', (c) => {\n\t* return c.redirect('/', 301)\n\t* })\n\t* ```\n\t*/\n\tredirect = (location, status) => {\n\t\tconst locationString = String(location);\n\t\tthis.header(\"Location\", !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString));\n\t\treturn this.newResponse(null, status ?? 302);\n\t};\n\t/**\n\t* `.notFound()` can return the Not Found Response.\n\t*\n\t* @see {@link https://hono.dev/docs/api/context#notfound}\n\t*\n\t* @example\n\t* ```ts\n\t* app.get('/notfound', (c) => {\n\t* return c.notFound()\n\t* })\n\t* ```\n\t*/\n\tnotFound = () => {\n\t\tthis.#notFoundHandler ??= () => createResponseInstance();\n\t\treturn this.#notFoundHandler(this);\n\t};\n};\n//#endregion\nexport { Context, TEXT_PLAIN };\n","import { GET_MATCH_RESULT } from \"../../request/constants.js\";\nimport { getPattern, splitRoutingPath } from \"../../utils/url.js\";\n//#region src/helper/route/index.ts\n/**\n* Get matched routes in the handler\n*\n* @param {Context} c - The context object\n* @returns An array of matched routes\n*\n* @example\n* ```ts\n* import { matchedRoutes } from 'hono/route'\n*\n* app.use('*', async function logger(c, next) {\n* await next()\n* matchedRoutes(c).forEach(({ handler, method, path }, i) => {\n* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n* console.log(\n* method,\n* ' ',\n* path,\n* ' '.repeat(Math.max(10 - path.length, 0)),\n* name,\n* i === c.req.routeIndex ? '<- respond from here' : ''\n* )\n* })\n* })\n* ```\n*/\nconst matchedRoutes = (c) => c.req[GET_MATCH_RESULT][0].map(([[, route]]) => route);\n/**\n* Get the route path registered within the handler\n*\n* @param {Context} c - The context object\n* @param {number} index - The index of the route from which to retrieve the path, similar to Array.prototype.at(), where a negative number is the index counted from the end of the matching route. Defaults to the current route index.\n* @returns The route path registered within the handler\n*\n* @example\n* ```ts\n* import { routePath } from 'hono/route'\n*\n* app.use('*', (c, next) => {\n* console.log(routePath(c)) // '*'\n* console.log(routePath(c, -1)) // '/posts/:id'\n* return next()\n* })\n*\n* app.get('/posts/:id', (c) => {\n* return c.text(routePath(c)) // '/posts/:id'\n* })\n* ```\n*/\nconst routePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? \"\";\n/**\n* Get the basePath of the as-is route specified by routing.\n*\n* @param {Context} c - The context object\n* @param {number} index - The index of the route from which to retrieve the path, similar to Array.prototype.at(), where a negative number is the index counted from the end of the matching route. Defaults to the current route index.\n* @returns The basePath of the as-is route specified by routing.\n*\n* @example\n* ```ts\n* import { baseRoutePath } from 'hono/route'\n*\n* const app = new Hono()\n*\n* const subApp = new Hono()\n* subApp.get('/posts/:id', (c) => {\n* return c.text(baseRoutePath(c)) // '/:sub'\n* })\n*\n* app.route('/:sub', subApp)\n* ```\n*/\nconst baseRoutePath = (c, index) => matchedRoutes(c).at(index ?? c.req.routeIndex)?.basePath ?? \"\";\n/**\n* Get the basePath with embedded parameters\n*\n* @param {Context} c - The context object\n* @param {number} index - The index of the route from which to retrieve the path, similar to Array.prototype.at(), where a negative number is the index counted from the end of the matching route. Defaults to the current route index.\n* @returns The basePath with embedded parameters.\n*\n* @example\n* ```ts\n* import { basePath } from 'hono/route'\n*\n* const app = new Hono()\n*\n* const subApp = new Hono()\n* subApp.get('/posts/:id', (c) => {\n* return c.text(basePath(c)) // '/requested-sub-app-path'\n* })\n*\n* app.route('/:sub', subApp)\n* ```\n*/\nconst basePathCacheMap = /* @__PURE__ */ new WeakMap();\nconst basePath = (c, index) => {\n\tindex ??= c.req.routeIndex;\n\tconst cache = basePathCacheMap.get(c) || [];\n\tif (typeof cache[index] === \"string\") return cache[index];\n\tlet result;\n\tconst rp = baseRoutePath(c, index);\n\tif (!/[:*]/.test(rp)) result = rp;\n\telse {\n\t\tconst paths = splitRoutingPath(rp);\n\t\tconst reqPath = c.req.path;\n\t\tlet basePathLength = 0;\n\t\tfor (let i = 0, len = paths.length; i < len; i++) {\n\t\t\tconst pattern = getPattern(paths[i], paths[i + 1]);\n\t\t\tif (pattern) {\n\t\t\t\tconst re = pattern[2] === true || pattern === \"*\" ? /[^\\/]+/ : pattern[2];\n\t\t\t\tconst restPath = reqPath.substring(basePathLength + 1);\n\t\t\t\tconst segment = restPath.split(\"/\", 1)[0];\n\t\t\t\tbasePathLength += (restPath.match(re)?.[0] ?? (re.test(segment) ? segment : \"\")).length;\n\t\t\t} else basePathLength += paths[i].length;\n\t\t\tbasePathLength += 1;\n\t\t}\n\t\tresult = reqPath.substring(0, basePathLength);\n\t}\n\tcache[index] = result;\n\tbasePathCacheMap.set(c, cache);\n\treturn result;\n};\n//#endregion\nexport { basePath, baseRoutePath, matchedRoutes, routePath };\n","//#region src/router.ts\n/**\n* @module\n* This module provides types definitions and variables for the routers.\n*/\n/**\n* Constant representing all HTTP methods in uppercase.\n*/\nconst METHOD_NAME_ALL = \"ALL\";\n/**\n* Constant representing all HTTP methods in lowercase.\n*/\nconst METHOD_NAME_ALL_LOWERCASE = \"all\";\n/**\n* Array of supported HTTP methods.\n*/\nconst METHODS = [\n\t\"get\",\n\t\"post\",\n\t\"put\",\n\t\"delete\",\n\t\"options\",\n\t\"patch\",\n\t\"query\"\n];\n/**\n* Error message indicating that a route cannot be added because the matcher is already built.\n*/\nconst MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\n/**\n* Error class representing an unsupported path error.\n*/\nvar UnsupportedPathError = class extends Error {};\n//#endregion\nexport { MESSAGE_MATCHER_IS_ALREADY_BUILT, METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, UnsupportedPathError };\n","//#region src/utils/constants.ts\n/**\n* Constant used to mark a composed handler.\n*/\nconst COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\n//#endregion\nexport { COMPOSED_HANDLER };\n","import { HTTPException } from \"../http-exception.js\";\nimport { GET_MATCH_RESULT } from \"../request/constants.js\";\nimport { getPattern, splitRoutingPath } from \"./url.js\";\n//#region src/utils/mount.ts\nconst countTrailingSlashes = (path) => {\n\tlet index = path.length;\n\twhile (index > 0 && path.charCodeAt(index - 1) === 47) index--;\n\treturn path.length - index;\n};\nconst getPathPrefixLength = (c, pathPrefix, routePath) => {\n\tif (!/[:*]/.test(pathPrefix)) return pathPrefix.length;\n\tconst path = c.req.path;\n\tconst matchResult = c.req[GET_MATCH_RESULT];\n\tconst paramNames = /* @__PURE__ */ new Set();\n\tlet length = 0;\n\tfor (const part of splitRoutingPath(pathPrefix)) {\n\t\tif (part[0] === \":\" && part.endsWith(\"}?\")) throw new Error(`mount(): Optional regular expression parameters are not supported in \"${routePath}\".`);\n\t\tconst pattern = getPattern(part);\n\t\tif (pattern && pattern !== \"*\") {\n\t\t\tconst name = pattern[1];\n\t\t\tif (paramNames.has(name)) throw new Error(`mount(): Duplicate path parameter \"${name}\" in \"${routePath}\".`);\n\t\t\tparamNames.add(name);\n\t\t}\n\t\tif (pattern && pattern !== \"*\" && pattern[2] !== true) {\n\t\t\tconst value = matchResult.length === 2 ? matchResult[1][matchResult[0][c.req.routeIndex][1][pattern[1]]] : matchResult[0][c.req.routeIndex][1][pattern[1]];\n\t\t\tlength += value.length + 1;\n\t\t} else if (pattern || part.endsWith(\"*\")) {\n\t\t\tconst end = path.indexOf(\"/\", length + 1);\n\t\t\tlength = end === -1 ? path.length : end;\n\t\t} else length += part.length + 1;\n\t}\n\treturn length;\n};\nconst createMountedRequest = (c, pathPrefix, routePath) => {\n\tif (/[^/]\\*$/.test(routePath)) throw new Error(`mount(): Wildcard must follow \"/\" in \"${routePath}\".`);\n\tconst prefixLength = getPathPrefixLength(c, pathPrefix, routePath);\n\tconst path = c.req.path.slice(prefixLength) || \"/\";\n\tif (prefixLength > c.req.path.length || path[0] !== \"/\" || /\\/(?:\\.|%2e){1,2}(?:\\/|$)/i.test(path)) throw new HTTPException(400, { message: \"Invalid mounted path\" });\n\tconst rawUrl = c.req.raw.url;\n\tif (/^[^/?#]*\\/\\/[^/?#\\\\]*[?#\\\\]/.test(rawUrl)) throw new HTTPException(400, { message: \"Invalid mounted path\" });\n\tconst rawPathEnd = rawUrl.search(/[?#]/);\n\tconst rawTrailingSlashes = countTrailingSlashes(rawPathEnd === -1 ? rawUrl : rawUrl.slice(0, rawPathEnd));\n\tif (rawTrailingSlashes > 1 && countTrailingSlashes(c.req.path) === rawTrailingSlashes - 1) throw new HTTPException(400, { message: \"Invalid mounted path\" });\n\tconst url = new URL(rawUrl);\n\turl.pathname = path.replace(/[\\\\\\t\\n\\r]/g, encodeURIComponent);\n\tif (path.includes(\"%\")) {}\n\treturn new Request(url, c.req.raw);\n};\n//#endregion\nexport { createMountedRequest };\n","import { compose } from \"./compose.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nimport { Context } from \"./context.js\";\nimport { routePath } from \"./helper/route/index.js\";\nimport { METHODS } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { createMountedRequest } from \"./utils/mount.js\";\n//#region src/hono-base.ts\n/**\n* @module\n* This module is the base module for the Hono object.\n*/\nconst notFoundHandler = (c) => {\n\treturn c.text(\"404 Not Found\", 404);\n};\nconst errorHandler = (err, c) => {\n\tif (\"getResponse\" in err) {\n\t\tconst res = err.getResponse();\n\t\treturn c.newResponse(res.body, res);\n\t}\n\tconsole.error(err);\n\treturn c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class Hono {\n\tget;\n\tpost;\n\tput;\n\tdelete;\n\toptions;\n\tpatch;\n\tquery;\n\tall;\n\ton;\n\tuse;\n\trouter;\n\tgetPath;\n\t_basePath = \"/\";\n\t#path = \"/\";\n\troutes = [];\n\tconstructor(options = {}) {\n\t\t[...METHODS, \"all\"].forEach((method) => {\n\t\t\tthis[method] = (args1, ...args) => {\n\t\t\t\tconst methodName = method.toUpperCase();\n\t\t\t\tif (typeof args1 === \"string\") this.#path = args1;\n\t\t\t\telse this.#addRoute(methodName, this.#path, args1);\n\t\t\t\targs.forEach((handler) => {\n\t\t\t\t\tthis.#addRoute(methodName, this.#path, handler);\n\t\t\t\t});\n\t\t\t\treturn this;\n\t\t\t};\n\t\t});\n\t\tthis.on = (method, path, ...handlers) => {\n\t\t\tfor (const p of [path].flat()) {\n\t\t\t\tthis.#path = p;\n\t\t\t\tfor (const m of [method].flat()) {\n\t\t\t\t\tconst methodName = m.toUpperCase();\n\t\t\t\t\tfor (const handler of handlers) this.#addRoute(methodName, this.#path, handler);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn this;\n\t\t};\n\t\tthis.use = (arg1, ...handlers) => {\n\t\t\tif (typeof arg1 === \"string\") this.#path = arg1;\n\t\t\telse {\n\t\t\t\tthis.#path = \"*\";\n\t\t\t\thandlers.unshift(arg1);\n\t\t\t}\n\t\t\thandlers.forEach((handler) => {\n\t\t\t\tthis.#addRoute(\"ALL\", this.#path, handler);\n\t\t\t});\n\t\t\treturn this;\n\t\t};\n\t\tconst { strict, ...optionsWithoutStrict } = options;\n\t\tObject.assign(this, optionsWithoutStrict);\n\t\tthis.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n\t}\n\t#clone() {\n\t\tconst clone = new Hono({\n\t\t\trouter: this.router,\n\t\t\tgetPath: this.getPath\n\t\t});\n\t\tclone.errorHandler = this.errorHandler;\n\t\tclone.#notFoundHandler = this.#notFoundHandler;\n\t\tclone.routes = this.routes;\n\t\treturn clone;\n\t}\n\t#notFoundHandler = notFoundHandler;\n\terrorHandler = errorHandler;\n\t/**\n\t* `.route()` allows grouping other Hono instance in routes.\n\t*\n\t* @see {@link https://hono.dev/docs/api/routing#grouping}\n\t*\n\t* @param {string} path - base Path\n\t* @param {Hono} app - other Hono instance\n\t* @returns {Hono} routed Hono instance\n\t*\n\t* @example\n\t* ```ts\n\t* const app = new Hono()\n\t* const app2 = new Hono()\n\t*\n\t* app2.get(\"/user\", (c) => c.text(\"user\"))\n\t* app.route(\"/api\", app2) // GET /api/user\n\t* ```\n\t*/\n\troute(path, app) {\n\t\tconst subApp = this.basePath(path);\n\t\tapp.routes.map((r) => {\n\t\t\tlet handler;\n\t\t\tif (app.errorHandler === errorHandler) handler = r.handler;\n\t\t\telse {\n\t\t\t\thandler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n\t\t\t\thandler[COMPOSED_HANDLER] = r.handler;\n\t\t\t}\n\t\t\tsubApp.#addRoute(r.method, r.path, handler, r.basePath);\n\t\t});\n\t\treturn this;\n\t}\n\t/**\n\t* `.basePath()` allows base paths to be specified.\n\t*\n\t* @see {@link https://hono.dev/docs/api/routing#base-path}\n\t*\n\t* @param {string} path - base Path\n\t* @returns {Hono} changed Hono instance\n\t*\n\t* @example\n\t* ```ts\n\t* const api = new Hono().basePath('/api')\n\t* ```\n\t*/\n\tbasePath(path) {\n\t\tconst subApp = this.#clone();\n\t\tsubApp._basePath = mergePath(this._basePath, path);\n\t\treturn subApp;\n\t}\n\t/**\n\t* `.onError()` handles an error and returns a customized Response.\n\t*\n\t* @see {@link https://hono.dev/docs/api/hono#error-handling}\n\t*\n\t* @param {ErrorHandler} handler - request Handler for error\n\t* @returns {Hono} changed Hono instance\n\t*\n\t* @example\n\t* ```ts\n\t* app.onError((err, c) => {\n\t* console.error(`${err}`)\n\t* return c.text('Custom Error Message', 500)\n\t* })\n\t* ```\n\t*/\n\tonError = (handler) => {\n\t\tthis.errorHandler = handler;\n\t\treturn this;\n\t};\n\t/**\n\t* `.notFound()` allows you to customize a Not Found Response.\n\t*\n\t* @see {@link https://hono.dev/docs/api/hono#not-found}\n\t*\n\t* @param {NotFoundHandler} handler - request handler for not-found\n\t* @returns {Hono} changed Hono instance\n\t*\n\t* @example\n\t* ```ts\n\t* app.notFound((c) => {\n\t* return c.text('Custom 404 Message', 404)\n\t* })\n\t* ```\n\t*/\n\tnotFound = (handler) => {\n\t\tthis.#notFoundHandler = handler;\n\t\treturn this;\n\t};\n\t/**\n\t* `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n\t*\n\t* @deprecated Use `mount()` from `hono/mount` instead. `.mount()` will be removed in v5.\n\t*\n\t* @see {@link https://hono.dev/docs/api/hono#mount}\n\t*\n\t* @param {string} path - base Path\n\t* @param {Function} applicationHandler - other Request Handler\n\t* @param {MountOptions} [options] - options of `.mount()`\n\t* @returns {Hono} mounted Hono instance\n\t* @throws {Error} If automatic request rewriting encounters duplicate path parameter names or an optional regular expression parameter.\n\t* @throws {HTTPException} With status 400 if automatic request rewriting cannot safely preserve the routed path.\n\t*\n\t* @example\n\t* ```ts\n\t* import { Router as IttyRouter } from 'itty-router'\n\t* import { Hono } from 'hono'\n\t* // Create itty-router application\n\t* const ittyRouter = IttyRouter()\n\t* // GET /itty-router/hello\n\t* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n\t*\n\t* const app = new Hono()\n\t* app.mount('/itty-router', ittyRouter.handle)\n\t* ```\n\t*\n\t* @example\n\t* ```ts\n\t* const app = new Hono()\n\t* // Send the request to another application without modification.\n\t* app.mount('/app', anotherApp, {\n\t* replaceRequest: (req) => req,\n\t* })\n\t* ```\n\t*/\n\tmount(path, applicationHandler, options) {\n\t\tlet replaceRequest;\n\t\tlet optionHandler;\n\t\tif (options) {\n\t\t\tif (typeof options === \"function\") optionHandler = options;\n\t\t\telse {\n\t\t\t\toptionHandler = options.optionHandler;\n\t\t\t\tif (options.replaceRequest === false) replaceRequest = (request) => request;\n\t\t\t\telse replaceRequest = options.replaceRequest;\n\t\t\t}\n\t\t}\n\t\tconst getOptions = optionHandler ? (c) => {\n\t\t\tconst options = optionHandler(c);\n\t\t\treturn Array.isArray(options) ? options : [options];\n\t\t} : (c) => {\n\t\t\tlet executionContext = void 0;\n\t\t\ttry {\n\t\t\t\texecutionContext = c.executionCtx;\n\t\t\t} catch {}\n\t\t\treturn [c.env, executionContext];\n\t\t};\n\t\tconst defaultReplaceRequest = (c) => {\n\t\t\tconst mountedRoutePath = routePath(c);\n\t\t\treturn createMountedRequest(c, mountedRoutePath.replace(/\\/?\\*$/, \"\"), mountedRoutePath);\n\t\t};\n\t\tconst handler = async (c, next) => {\n\t\t\tconst res = await applicationHandler(replaceRequest ? replaceRequest(c.req.raw) : defaultReplaceRequest(c), ...getOptions(c));\n\t\t\tif (res) return res;\n\t\t\tawait next();\n\t\t};\n\t\tthis.#addRoute(\"ALL\", mergePath(path, \"*\"), handler);\n\t\treturn this;\n\t}\n\t#addRoute(method, path, handler, baseRoutePath) {\n\t\tpath = mergePath(this._basePath, path);\n\t\tconst r = {\n\t\t\tbasePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,\n\t\t\tpath,\n\t\t\tmethod,\n\t\t\thandler\n\t\t};\n\t\tthis.router.add(method, path, [handler, r]);\n\t\tthis.routes.push(r);\n\t}\n\t#handleError(err, c) {\n\t\tif (err instanceof Error) return this.errorHandler(err, c);\n\t\tthrow err;\n\t}\n\t#dispatch(request, executionCtx, env, method) {\n\t\tif (method === \"HEAD\") return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n\t\tconst path = this.getPath(request, { env });\n\t\tconst matchResult = this.router.match(method, path);\n\t\tconst c = new Context(request, {\n\t\t\tpath,\n\t\t\tmatchResult,\n\t\t\tenv,\n\t\t\texecutionCtx,\n\t\t\tnotFoundHandler: this.#notFoundHandler\n\t\t});\n\t\tif (matchResult[0].length === 1) {\n\t\t\tlet res;\n\t\t\ttry {\n\t\t\t\tres = matchResult[0][0][0][0](c, async () => {\n\t\t\t\t\tc.res = await this.#notFoundHandler(c);\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\treturn this.#handleError(err, c);\n\t\t\t}\n\t\t\treturn res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n\t\t}\n\t\tconst composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n\t\treturn (async () => {\n\t\t\ttry {\n\t\t\t\tconst context = await composed(c);\n\t\t\t\tif (!context.finalized) throw new Error(\"Context is not finalized. Did you forget to return a Response object or `await next()`?\");\n\t\t\t\treturn context.res;\n\t\t\t} catch (err) {\n\t\t\t\treturn this.#handleError(err, c);\n\t\t\t}\n\t\t})();\n\t}\n\t/**\n\t* `.fetch()` will be entry point of your app.\n\t*\n\t* @see {@link https://hono.dev/docs/api/hono#fetch}\n\t*\n\t* @param {Request} request - request Object of request\n\t* @param {Env} env - env Object\n\t* @param {ExecutionContext} executionCtx - context of execution\n\t* @returns {Response | Promise<Response>} response of request\n\t*\n\t*/\n\tfetch = (request, ...rest) => {\n\t\treturn this.#dispatch(request, rest[1], rest[0], request.method);\n\t};\n\t/**\n\t* `.request()` is a useful method for testing.\n\t* You can pass a URL or pathname to send a GET request.\n\t* app will return a Response object.\n\t* ```ts\n\t* test('GET /hello is ok', async () => {\n\t* const res = await app.request('/hello')\n\t* expect(res.status).toBe(200)\n\t* })\n\t* ```\n\t* @see https://hono.dev/docs/api/hono#request\n\t*/\n\trequest = (input, requestInit, Env, executionCtx) => {\n\t\tif (input instanceof Request) return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n\t\tinput = input.toString();\n\t\treturn this.fetch(new Request(/^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`, requestInit), Env, executionCtx);\n\t};\n\t/**\n\t* `.fire()` automatically adds a global fetch event listener.\n\t* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n\t* @deprecated\n\t* Use `fire` from `hono/service-worker` instead.\n\t* ```ts\n\t* import { Hono } from 'hono'\n\t* import { fire } from 'hono/service-worker'\n\t*\n\t* const app = new Hono()\n\t* // ...\n\t* fire(app)\n\t* ```\n\t* @see https://hono.dev/docs/api/hono#fire\n\t* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n\t* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n\t*/\n\tfire = () => {\n\t\taddEventListener(\"fetch\", (event) => {\n\t\t\tevent.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n\t\t});\n\t};\n};\n//#endregion\nexport { Hono as HonoBase };\n","import { UnsupportedPathError } from \"../../router.js\";\n//#region src/router/pattern-router/router.ts\nconst emptyParams = Object.create(null);\nvar PatternRouter = class {\n\tname = \"PatternRouter\";\n\t#routes = [];\n\tadd(method, path, handler) {\n\t\tconst suffix = path.endsWith(\"/*\") ? \"(?:$|/)\" : path.endsWith(\"*\") ? \"\" : \"/?$\";\n\t\tpath = path.replace(/\\*$/, \"\");\n\t\tif (path.at(-1) === \"?\") {\n\t\t\tpath = path.slice(0, -1);\n\t\t\tthis.add(method, path.replace(/\\/[^/]+$/, \"\"), handler);\n\t\t}\n\t\tconst parts = (path.match(/\\/?(:\\w+(?:{(?:(?:{[\\d,]+})|[^}])+})?)|\\/?[^\\/\\?]+/g) || []).map((part) => {\n\t\t\tconst match = part.match(/^\\/:([^{]+)(?:{(.*)})?/);\n\t\t\treturn match ? `/(?<${match[1]}>${match[2] || \"[^/]+\"})` : part === \"/*\" ? \"/[^/]+\" : part.replace(/[.\\\\+*[^\\]$()]/g, \"\\\\$&\");\n\t\t});\n\t\ttry {\n\t\t\tthis.#routes.push([\n\t\t\t\tnew RegExp(`^${parts.join(\"\")}${suffix}`),\n\t\t\t\tmethod,\n\t\t\t\thandler\n\t\t\t]);\n\t\t} catch {\n\t\t\tthrow new UnsupportedPathError();\n\t\t}\n\t}\n\tmatch(method, path) {\n\t\tconst handlers = [];\n\t\tfor (let i = 0, len = this.#routes.length; i < len; i++) {\n\t\t\tconst [pattern, routeMethod, handler] = this.#routes[i];\n\t\t\tif (routeMethod === method || routeMethod === \"ALL\") {\n\t\t\t\tconst match = pattern.exec(path);\n\t\t\t\tif (match) handlers.push([handler, match.groups || emptyParams]);\n\t\t\t}\n\t\t}\n\t\treturn [handlers];\n\t}\n};\n//#endregion\nexport { PatternRouter };\n","import { HonoBase as Hono$1 } from \"../hono-base.js\";\nimport { PatternRouter } from \"../router/pattern-router/router.js\";\n//#region src/preset/tiny.ts\n/**\n* @module\n* The preset that uses `PatternRouter`.\n*/\nvar Hono = class extends Hono$1 {\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.router = new PatternRouter();\n\t}\n};\n//#endregion\nexport { Hono };\n","/**\n * Long-poll `GET /v1/since` handler core. Two exports:\n *\n * - {@link longPollSince} — the long-poll itself. Fast path first;\n * if `listEventsSince` already sees events, return immediately.\n * Otherwise race a poll loop against a 25 s wall-clock timeout and\n * return either the next batch of events or\n * `{ events: [], next_cursor: <same> }` (\"nothing changed within\n * the budget\").\n * - {@link listEventsSince} — one poll cycle. Reads `current.json`,\n * validates the caller's cursor against `log_seq_start`, discovers\n * the true tail by forward-probe, GETs each body by integer `seq`,\n * and returns the parsed `LogEntry`s in causal order.\n *\n * The handler is wired into the Hono router (`router.ts`); the\n * router itself owns request parsing and error → HTTP mapping. This\n * module owns the I/O + cursor semantics.\n *\n * Cost model. While a long-poll connection is active the per-poll\n * cost is one `Storage.get` of `current.json`, one GET per entry below\n * `tail_hint` the cursor has not seen, and the forward probe from the\n * later of `tail_hint` and the cursor: one GET per entry it yields plus\n * the GET that finds the tail. An idle poll is therefore two GETs.\n * These are Class B ops, not Class A. The `< 1 Class A op / writer /\n * hour` cost-model bound (see `docs/spec/sync-protocol.md`) still\n * holds; active long-poll subscribers pay repeated Class B reads for\n * lower-latency delivery.\n *\n * Request budget. On a host whose request ledger limits storage calls\n * (Workers Free: 45 through `fetch`), the long-poll reads the ambient\n * ledger and never runs past it. A cycle starts only when the ledger\n * has room for an idle one; inside a cycle, entry reads and the probe\n * are capped by what is left, and a refused call ends the cycle with\n * the entries read so far. Out of room, the poll resolves with those\n * entries (a prefix whose `next_cursor` resumes after the last one) or,\n * having waited at least one poll interval, an empty batch at the same\n * cursor. With no room for even the first cycle it refuses with a\n * retriable `MaintenancePending`, so an empty 200 never comes back\n * faster than one interval. A host that counts without refusing (Node)\n * polls as before.\n */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n CODE_RESOLUTIONS,\n COUNT_BIT_WIDTH,\n currentRequestLedger,\n formatCursor,\n type LogEntry,\n logSeqStartOf,\n lsnParts,\n MAINTENANCE_PENDING_RETRY_AFTER_SECONDS,\n NO_GENERATION,\n parseCursor,\n type RequestPool,\n} from \"@baerly/protocol\";\nimport type { Db } from \"../db.ts\";\nimport { getCurrentJson, getLogEntry, probeLogChunk } from \"../db-read-seams.ts\";\nimport type { SinceResponse } from \"../contract.ts\";\nimport { forwardProbeCap, isStorageRefusal } from \"../log-tail.ts\";\n\n/**\n * Validation regex for an opaque LSN cursor. Matches the shape minted\n * by `Writer.commit` (see `packages/server/src/writer.ts`) and described\n * on {@link LogEntry.lsn} — `<base32-time>_<session>_<seq>` where\n * base-32 is `[0-9a-v]` and the trailing seq is a fixed-width token.\n *\n * The seq width (`{11}`) is `Math.ceil(COUNT_BIT_WIDTH / 5)` chars, derived\n * automatically from the canonical `COUNT_BIT_WIDTH` constant in\n * `packages/protocol/src/constants.ts` via the `SEQ_CHARS` computed\n * constant below — no manual update needed when `COUNT_BIT_WIDTH` changes.\n * Currently: `Math.ceil(53 / 5) = 11`.\n */\n// COUNT_BIT_WIDTH is 53; Math.ceil(53 / 5) = 11.\nconst SEQ_CHARS = Math.ceil(COUNT_BIT_WIDTH / 5); // 11\nconst LSN_RE = new RegExp(`^[0-9a-v]+_[0-9a-v]+_[0-9a-v]{${SEQ_CHARS}}$`);\n\n/**\n * Generation half of a cursor: lowercase hex as minted by\n * `mintGeneration`, or the `NO_GENERATION` sentinel for a manifest that\n * predates the field.\n */\nconst GENERATION_RE = /^(?:[0-9a-f]+|-)$/;\n\n/** `LSN_RE` admits 55-bit seq tokens; `lsnParts` rejects those outside the safe range. */\nconst hasSafeSeq = (lsn: string): boolean => {\n try {\n lsnParts(lsn);\n return true;\n } catch {\n return false;\n }\n};\n\n/**\n * Reject a malformed cursor before it reaches storage, and return its\n * decoded halves.\n *\n * Shape validation lives here rather than in the codec because the\n * codec is a protocol leaf with no opinion about which LSN dialect a\n * given build mints — `LSN_RE` is that opinion, and it is derived from\n * `COUNT_BIT_WIDTH`.\n */\nconst decodeCursor = (cursor: string): { generation: string; lsn: string } => {\n const parts = parseCursor(cursor);\n if (!GENERATION_RE.test(parts.generation) || !LSN_RE.test(parts.lsn) || !hasSafeSeq(parts.lsn)) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor: invalid shape (expected a cursor returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`,\n );\n }\n return parts;\n};\n\n/**\n * Hard cap on log entries returned in a single poll cycle. 1024 is\n * comfortably above the largest expected per-poll batch under the\n * production 1 s poll interval and bounds the worst-case memory\n * footprint of the parsed-JSON array on a hostile workload.\n */\nconst DEFAULT_MAX_EVENTS = 1024;\n\n/**\n * Default 25 s long-poll budget. CF Workers cap fetch CPU at 30 s on\n * the free plan; 25 s leaves slack for header serialization plus the\n * platform's bookkeeping. Node / Bun / Deno have no comparable cap,\n * but the budget is still useful as a connection-cycling hint for\n * upstream load balancers (most idle-connection timeouts are 30-60 s).\n *\n * Per-request override is via the `timeoutMs` field on\n * {@link LongPollSinceOptions} (plumbed from `sinceTimeoutMs` on\n * `CreateRouterOptions` and both Node + Cloudflare adapters).\n */\nconst DEFAULT_TIMEOUT_MS = 25_000;\n\n/**\n * Default 1 s inner-poll interval. See module docstring for the\n * cost-model trade-off.\n *\n * Per-request override is via the `pollIntervalMs` field on\n * {@link LongPollSinceOptions} (plumbed from `sincePollIntervalMs`\n * on `CreateRouterOptions` and both Node + Cloudflare adapters).\n */\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\n\n/**\n * Storage calls one poll cycle that finds nothing costs: the\n * `current.json` GET and the probe GET that finds the tail at the\n * cursor. A cycle starts only with this much room on the ledger.\n */\nconst IDLE_POLL_CALLS = 2;\n\nexport interface LongPollSinceOptions {\n readonly db: Db<BaerlyConfig>;\n readonly collection: string;\n /** Opaque cursor; empty string = from `log_seq_start`. */\n readonly cursor: string;\n readonly signal?: AbortSignal;\n readonly timeoutMs?: number;\n readonly pollIntervalMs?: number;\n}\n\nexport interface ListEventsSinceOptions {\n readonly db: Db<BaerlyConfig>;\n readonly collection: string;\n /** Opaque cursor; empty string = from `log_seq_start`. */\n readonly cursor: string;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Long-poll wrapper around {@link listEventsSince}. Returns as soon\n * as the first non-empty poll lands, or when the wall-clock timeout\n * elapses (whichever comes first). On timeout the response is\n * `{ events: [], next_cursor: <same> }` — shipped as `200`, not `304`,\n * because the response body carries the unchanged cursor the client\n * needs for the next poll cycle.\n *\n * @throws BaerlyError{code:\"SchemaError\"} — invalid cursor shape.\n * @throws BaerlyError{code:\"CursorExpired\"} — the cursor sits below the\n * retained log, or was minted in a truncated generation.\n */\nexport async function longPollSince(opts: LongPollSinceOptions): Promise<SinceResponse> {\n const { db, collection, cursor, signal } = opts;\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n\n // Up-front cursor-shape validation. `listEventsSince` also checks,\n // but doing it here short-circuits the fast-path read on bad input.\n if (cursor.length > 0) {\n decodeCursor(cursor);\n }\n\n // Room for at least an idle cycle, or the request refuses: an empty\n // 200 here would come back at once and a client re-polling it would\n // spin. The next request has a fresh ledger.\n const budget = pollBudget();\n if (budget.left() < IDLE_POLL_CALLS) {\n throw new BaerlyError(\n \"MaintenancePending\",\n `collection ${JSON.stringify(collection)}: this request has too few storage calls left to poll the change feed, so it was not polled. Retry after ${MAINTENANCE_PENDING_RETRY_AFTER_SECONDS}s.`,\n {\n resolution:\n \"Retry after the delay in retryAfter (Retry-After header, seconds) with the same cursor: nothing was read and the cursor is still valid.\",\n retryAfter: MAINTENANCE_PENDING_RETRY_AFTER_SECONDS,\n },\n );\n }\n\n // Fast path: the first poll already sees new events.\n const initial = await pollOnce({ db, collection, cursor, signal }, budget);\n if (initial.events.length > 0) {\n return { events: initial.events, next_cursor: nextCursor(initial) };\n }\n\n // No events yet. Race a timeout against a polling loop.\n const start = Date.now();\n const deadline = start + timeoutMs;\n\n return new Promise<SinceResponse>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let settled = false;\n\n const cleanup = (): void => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n if (signal !== undefined) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n };\n\n const settleResolve = (value: SinceResponse): void => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n resolve(value);\n };\n const settleReject = (err: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n reject(err);\n };\n\n function onAbort(): void {\n // Treat client disconnect as \"no events, same cursor\" — the\n // socket is gone anyway; the resolve is a no-op for response\n // serialization but keeps the promise from leaking.\n settleResolve({ events: [], next_cursor: cursor });\n }\n\n if (signal !== undefined) {\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const tick = async (): Promise<void> => {\n if (settled) {\n return;\n }\n // Out of room for another cycle. At least one poll interval has\n // passed since the request began, so an empty batch is safe to\n // return: a client re-polling it waits that long per request.\n if (budget.left() < IDLE_POLL_CALLS) {\n settleResolve({ events: [], next_cursor: cursor });\n return;\n }\n try {\n const polled = await pollOnce({ db, collection, cursor, signal }, budget);\n if (settled) {\n return;\n }\n if (polled.events.length > 0) {\n settleResolve({ events: polled.events, next_cursor: nextCursor(polled) });\n return;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) {\n settleResolve({ events: [], next_cursor: cursor });\n return;\n }\n const delay = Math.min(pollIntervalMs, remaining);\n timer = setTimeout(() => {\n void tick();\n }, delay);\n } catch (error) {\n settleReject(error);\n }\n };\n\n // First tick scheduled after `pollIntervalMs` (the initial fast\n // path already covered \"events present at t=0\"). Cap by the\n // remaining deadline so an early-cutoff tester with\n // `timeoutMs < pollIntervalMs` still resolves on time.\n timer = setTimeout(\n () => {\n void tick();\n },\n Math.min(pollIntervalMs, timeoutMs),\n );\n });\n}\n\n/**\n * One poll cycle: read `current.json`, derive the `seq` range to\n * scan from the cursor's embedded seq, GET each log entry by `seq`,\n * return the parsed `LogEntry`s in causal order.\n *\n * On-bucket log keys are `log/<seq>.json` — the same shape\n * `compactor` / `gc` walk. Iterating\n * `[startSeq, endSeq)` and GET-ing each key directly avoids the\n * lex-`startAfter` hazard on integer filenames (`10.json` sorts\n * before `2.json` lex) and gives us the global causal ordering for\n * free — `seq` is monotonic across writer sessions.\n *\n * No `current.json` yet → `[]` (clients can poll a not-yet-existing\n * collection without erroring). Under a request ledger that runs out,\n * the result is a prefix of the entries past the cursor. Cursor inside `[0, log_seq_start)`, or\n * minted in a truncated generation → `BaerlyError{code:\"CursorExpired\"}`.\n */\nexport async function listEventsSince(opts: ListEventsSinceOptions): Promise<LogEntry[]> {\n const polled = await pollOnce(opts, pollBudget());\n return polled.events;\n}\n\n/**\n * The request ledger's room for the long-poll's storage calls, read\n * through {@link forwardProbeCap}, the same cap every read path sizes its\n * tail probe with. The pool the storage charges is not known up front\n * (the R2 binding charges `internal`, `fetch` storage `external` as\n * well), so until a poll has made a call the room is `external`'s, the\n * smaller of the two; after it, the room in whichever pool that call\n * charged. With no ledger, or one that never refuses (Node), the room is\n * the runaway cap `LOG_FORWARD_PROBE_CAP`, far above any cycle.\n */\ninterface PollBudget {\n /** Calls still allowed this request. */\n left(): number;\n /** Run `fn`, learning the storage's pool from what it charges. */\n observe<T>(fn: () => Promise<T>): Promise<T>;\n}\n\nconst pollBudget = (): PollBudget => {\n let pool: RequestPool | undefined;\n return {\n left: (): number => forwardProbeCap(pool ?? \"external\").slots,\n observe: async <T>(fn: () => Promise<T>): Promise<T> => {\n const ledger = currentRequestLedger();\n if (ledger === undefined || pool !== undefined) {\n return fn();\n }\n const before = ledger.charged;\n try {\n return await fn();\n } finally {\n const after = ledger.charged;\n if (after.external > before.external) {\n pool = \"external\";\n } else if (after.internal > before.internal) {\n pool = \"internal\";\n }\n }\n },\n };\n};\n\n/**\n * The body of {@link listEventsSince}, additionally surfacing the\n * manifest `generation` the poll read.\n *\n * `longPollSince` needs that generation to mint `next_cursor`, and\n * re-reading `current.json` to get it would add a Class A op to every\n * poll — the idle-reader cost bound this protocol is built around.\n * {@link listEventsSince} is public surface pinned by\n * `tests/integration/public-surface.test.ts`, so it keeps returning a\n * bare array and this internal variant carries the extra field.\n *\n * `generation` is `undefined` when the collection has no `current.json`\n * (no events either, so it is never consumed) or when the manifest\n * predates the field.\n *\n * Entry reads and the probe are capped by the budget's room, and a\n * refused storage call ends the cycle: the entries read so far come back\n * as a prefix, in order, which a cursor minted from the last one resumes.\n */\nasync function pollOnce(\n opts: ListEventsSinceOptions,\n budget: PollBudget,\n): Promise<{ events: LogEntry[]; generation: string | undefined }> {\n const { db, collection, cursor, signal } = opts;\n\n const decoded = cursor.length > 0 ? decodeCursor(cursor) : undefined;\n\n const entries: LogEntry[] = [];\n let generation: string | undefined;\n try {\n const read = await budget.observe(() => getCurrentJson(db, collection, signalOpt(signal)));\n if (read === null) {\n // No collection provisioned yet. Clients polling for a collection that\n // doesn't exist see an empty stream, NOT an error.\n return { events: [], generation: undefined };\n }\n generation = read.json.generation;\n const logSeqStart = logSeqStartOf(read.json);\n // Every entry below the hint is committed (`log_seq_start <=\n // tail_hint <= tail`); the true tail is at or past it.\n const hint = Math.max(logSeqStart, read.json.tail_hint);\n\n // Derive the seq range to scan. Empty cursor → start at\n // `log_seq_start` (the first un-snapshotted entry). Non-empty\n // cursor → start at `cursorSeq + 1`, after two rejections.\n let startSeq: number;\n if (decoded === undefined) {\n startSeq = logSeqStart;\n } else {\n const { generation: cursorGeneration, lsn } = decoded;\n // (1) Wrong generation. A seq identifies a `log/<seq>` slot, and\n // slots are REUSED: `restore --force` truncates and reseeds\n // `log_seq_start` to one past the highest surviving log object,\n // which can land below the old floor (the floor exemption —\n // invariant 12 in `docs/spec/sync-protocol.md`). A pre-restore\n // cursor would then clear check (2) below and resume into the new\n // generation, silently skipping every restored row beneath it —\n // gapped, not broken, which is the failure mode a sync client can't\n // detect for itself.\n //\n // Both spellings of \"no generation\" — a manifest predating the\n // field and a bare-LSN cursor predating the composite shape —\n // decode to `NO_GENERATION`, so this stays one comparison with no\n // fail-open branch. See the truth table in `sync-protocol.md`.\n const currentGeneration = read.json.generation ?? NO_GENERATION;\n if (cursorGeneration !== currentGeneration) {\n throw new BaerlyError(\n \"CursorExpired\",\n `cursor ${JSON.stringify(cursor)} was minted in a generation that no longer exists (the collection has been truncated and restored)`,\n { resolution: CODE_RESOLUTIONS.CursorExpired },\n );\n }\n // (2) Folded away. The entry is below the floor, so the compactor\n // folded it into the snapshot and the GC sweep deleted it.\n const cursorSeq = lsnParts(lsn).seq;\n if (cursorSeq < logSeqStart) {\n throw new BaerlyError(\n \"CursorExpired\",\n `cursor ${JSON.stringify(cursor)} is older than the oldest change this collection retains (log_seq_start=${logSeqStart}); the changes after it are no longer retained`,\n { resolution: CODE_RESOLUTIONS.CursorExpired },\n );\n }\n startSeq = cursorSeq + 1;\n }\n\n // At most `DEFAULT_MAX_EVENTS` per cycle (hard ceiling per the\n // module docstring), and at most what the budget has room for.\n const endSeq = startSeq + DEFAULT_MAX_EVENTS;\n\n // Entries below the hint the cursor has not seen: GET each by seq.\n // Sequential GETs (NOT Promise.all). Long-poll is latency-bound,\n // per-poll batch is typically 0-10 entries, sequential keeps\n // memory bounded under pathological workloads.\n let s = startSeq;\n for (; s < Math.min(hint, endSeq); s++) {\n if (budget.left() < 1) {\n return { events: entries, generation };\n }\n const entry = await getLogEntry(db, collection, s, read.json, signalOpt(signal));\n if (entry === null) {\n // Race: the GC sweeper deleted this entry between\n // `getCurrentJson` and the GET. Skip; don't error.\n continue;\n }\n entries.push(entry);\n }\n\n // The rest: probe forward from the later of the hint and the cursor,\n // taking each entry the probe passes. Starting at the cursor rather\n // than the hint skips re-reading entries the client already has, so\n // an idle poll costs one probe GET however far the hint lags. An\n // \"at least\" chunk (the cap was reached, or a slot GET was refused,\n // before the tail) is a delivered prefix; the next poll resumes\n // after its last entry.\n const cap = Math.min(endSeq - s, budget.left());\n if (cap >= 1) {\n const chunk = await probeLogChunk(db, collection, s, read.json, {\n cap,\n ...(signal !== undefined && { signal }),\n });\n entries.push(...chunk.entries);\n }\n } catch (error) {\n if (isStorageRefusal(error)) {\n return { events: entries, generation };\n }\n throw error;\n }\n\n return { events: entries, generation };\n}\n\n/**\n * Mint the `next_cursor` for a poll that produced events: the last\n * entry's `lsn`, paired with the generation the poll read it under.\n *\n * Only called when `events` is non-empty, which is exactly when the\n * poll saw a `current.json` — so the generation here is the manifest's,\n * not a stand-in.\n */\nconst nextCursor = (polled: { events: LogEntry[]; generation: string | undefined }): string =>\n formatCursor(polled.generation, polled.events[polled.events.length - 1]!.lsn);\n\n/** Pack an optional `signal` into the `{ signal? }` shape callers expect. */\nconst signalOpt = (signal: AbortSignal | undefined): { signal?: AbortSignal } | undefined =>\n signal === undefined ? undefined : { signal };\n","/**\n * HTTP dispatcher. A small Hono `app` that implements the\n * five locked CRUD routes from `contract.ts`. Mounted into both\n * adapters (`@baerly/adapter-cloudflare` and `@baerly/adapter-node`);\n * the router itself is platform-agnostic — it accepts a single\n * `Request`, dispatches against a per-request `Db`, and returns a\n * `Response` whose body follows the `HttpOkEnvelope` /\n * `HttpErrorEnvelope` shapes.\n *\n * The anonymous `GET /v1/healthz` liveness probe is served by the\n * adapters directly (see `worker.ts` / `server.ts`) — keeping it\n * upstream of the router avoids spending a `Db.create` on every\n * load-balancer probe.\n *\n * `GET /v1/since` is appended to the same factory (see `./since.ts`\n * for the long-poll core). No adapter caches responses: every read\n * this router serves, on every host, reaches storage.\n */\n\nimport { Hono } from \"hono/tiny\";\nimport type { Context } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport {\n type BaerlyConfig,\n BaerlyError,\n CAPACITY_WARNING_HEADER,\n type DocumentData,\n type BaerlyErrorCode,\n EMPTY_PREDICATE_WIRE,\n isUuidV7,\n type MergePatch,\n type OrderSpec,\n UNSUPPORTED_MEDIA_TYPE_ECHO_CHARS,\n type PredicateWire,\n validateWire,\n WHERE_ORDER_JSON_RESOLUTION,\n WRITE_BODY_SHAPE_RESOLUTION,\n} from \"@baerly/protocol\";\nimport { CAPACITY_WARNING_FIELD } from \"../capacity.ts\";\nimport { isCallerFacing, markCallerFacing } from \"../caller-facing-error.ts\";\nimport type { Db } from \"../db.ts\";\nimport { collectionReadContext } from \"../db-read-seams.ts\";\nimport {\n errorEnvelope,\n type HttpErrorEnvelope,\n type HttpOkEnvelope,\n type HttpStatus,\n type SinceResponse,\n} from \"../contract.ts\";\nimport { serializeError } from \"../observability/canonical.ts\";\nimport { CATEGORY, getCurrentContext, getLogger } from \"../observability/index.ts\";\nimport { runAllWithMeta, runByIdWithMeta, runInsert } from \"../query.ts\";\nimport { longPollSince } from \"./since.ts\";\n\n/**\n * Options for {@link createRouter}.\n *\n * - `db` — single-tenant `Db` instance. The CF/Node adapters build a\n * fresh `Db` per request (after the Verifier resolves the tenant)\n * and hand it to a freshly-constructed router. The router itself\n * is stateless and per-request — `app.fetch(req)` is the only\n * entry point. The Verifier runs in the adapter (see `worker.ts` /\n * `server.ts`) before `createRouter` is called; the router itself\n * has no auth seam, so it serves every request it receives as the\n * `db`'s tenant. A custom adapter authenticates first, derives the\n * tenant from the verified identity, and builds the `Db` from it.\n */\nexport interface CreateRouterOptions {\n readonly db: Db<BaerlyConfig>;\n /** Override the long-poll budget. Forwarded to `longPollSince`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `longPollSince`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Build a Hono `app` that serves the CRUD routes:\n *\n * - `GET /v1/c/:collection/:id` → read one document.\n * - `GET /v1/c/:collection?where=<json>&order=<json>&limit=<n>` → list rows\n * matching a predicate, optionally ordered and capped.\n * - `POST /v1/c/:collection` → insert. Body: `{ doc, mintedId? }`. → `201 { _id }`.\n * - `PATCH /v1/c/:collection/:id` → merge-patch. Body: `{ patch }`. → `200 { modified }`.\n * - `PUT /v1/c/:collection/:id` → whole-doc replace. Body: `{ doc }`. → `200 { modified }`.\n * - `DELETE /v1/c/:collection/:id` → delete row by id. → `204`.\n * - `GET /v1/count?collection=<name>&where=<json>&limit=<n>` → scalar `{ count: N }`, cut by `limit`.\n * - `GET /v1/since?collection=<name>&cursor=<opaque>` → long-poll log.\n *\n * Routes are matched at `/v1/...`: strip any mount prefix from the\n * request URL before `app.fetch(req)`. Bare `createRouter` adds no\n * auth, no `/v1/healthz` or `/v1/spec`, and no canonical log line;\n * writes still run write-tick maintenance, under the default profile\n * rather than the one a stock adapter selects for its host.\n *\n * @example\n * ```ts\n * import { Db, MemoryStorage } from \"@gusto/baerly-storage\";\n * import { createRouter } from \"@gusto/baerly-storage/http\";\n *\n * // Tests and local tools only: every request is served as tenant \"acme\".\n * const db = Db.create({ storage: new MemoryStorage(), app: \"tickets\", tenant: \"acme\" });\n * const app = createRouter({ db });\n * const res = await app.fetch(new Request(\"http://localhost/v1/c/tickets\"));\n * ```\n *\n * For a gated, per-request router see `dist/RECIPES.md` →\n * \"Recipe — authoring a gated adapter\".\n */\nexport function createRouter(options: CreateRouterOptions): Hono {\n const { db, sinceTimeoutMs, sincePollIntervalMs } = options;\n const app = new Hono();\n\n // The router intentionally does NOT mount an observability\n // middleware. Production adapters (`@baerly/adapter-cloudflare`,\n // `@baerly/adapter-node`) open their own `ObservabilityContext`\n // BEFORE calling `createRouter().fetch` so verifier and storage work\n // share the request's canonical line. Standalone callers wrap\n // their request via `withHttpObservability` from\n // `@baerly/server`. Either way, one unit-of-work → exactly one\n // canonical line.\n\n // Read one — GET /v1/c/:collection/:id\n app.get(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const { rows, manifestPointer, fresh } = await runByIdWithMeta(\n collectionReadContext(db, collection),\n id,\n );\n const row = rows[0];\n if (row === undefined) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return c.json(\n {\n data: row,\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<DocumentData>,\n 200,\n );\n });\n\n // List — GET /v1/c/:collection?where=<urlencoded-json>\n app.get(\"/v1/c/:collection\", async (c) => {\n const { collection } = c.req.param();\n const wire = parseWhereParam(c);\n const order = parseOrder(c.req.query(\"order\"));\n const limit = parseLimit(c.req.query(\"limit\"));\n const { rows, manifestPointer, fresh } = await runAllWithMeta(\n collectionReadContext(db, collection),\n {\n wire,\n order,\n limit,\n },\n );\n return c.json(\n {\n data: rows,\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<ReadonlyArray<DocumentData>>,\n 200,\n );\n });\n\n // Insert — POST /v1/c/:collection Body: { doc, mintedId? } → 201 { _id }\n // Drives `runInsert` directly (as the reads drive their runners) so the\n // internal `mintedId` replay flag can reach it; `Collection.insert`\n // carries no such option.\n app.post(\"/v1/c/:collection\", async (c) => {\n const { collection } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const doc = assertJsonBodyField(body, \"doc\");\n const mintedId = readMintedId(body, doc);\n const { _id } = await runInsert(\n collectionReadContext(db, collection),\n doc as Partial<DocumentData> & DocumentData,\n mintedId === undefined ? undefined : { mintedId },\n );\n stampCapacityWarning(c);\n return c.json({ _id }, 201);\n });\n\n // Patch — PATCH /v1/c/:collection/:id Body: { patch }\n app.patch(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const patch = assertJsonBodyField(body, \"patch\");\n const { modified } = await db\n .collection(collection)\n .update(id, patch as MergePatch<DocumentData>);\n if (modified === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n stampCapacityWarning(c);\n return c.json({ modified }, 200);\n });\n\n // Replace — PUT /v1/c/:collection/:id Body: { doc }\n // Whole-document overwrite (NOT merge-patch). Missing row → 404\n // (kernel throws `NotFound` directly via `runReplaceById`); row\n // matches → emits one `op:\"U\"` log entry with the post-image,\n // dropping fields absent from `doc`.\n app.put(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const doc = assertJsonBodyField(body, \"doc\");\n await db.collection(collection).replace(id, doc as DocumentData);\n stampCapacityWarning(c);\n return c.json({ modified: 1 }, 200);\n });\n\n // Delete — DELETE /v1/c/:collection/:id → 204\n app.delete(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const { deleted } = await db.collection(collection).delete(id);\n if (deleted === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n stampCapacityWarning(c);\n return c.body(null, 204);\n });\n\n // Count — GET /v1/count?collection=<name>&where=<json>&limit=<n>\n //\n // Returns a scalar row count for the matching predicate. Avoids the\n // client downloading every row just to take `.length` (silent egress\n // burn). The engine counts matches without materialising rows.\n app.get(\"/v1/count\", async (c) => {\n const collection = c.req.query(\"collection\");\n if (collection === undefined || collection.length === 0) {\n throw new BaerlyError(\"SchemaError\", \"GET /v1/count requires ?collection=<name>\", {\n resolution: \"Add ?collection=<name> to the request URL.\",\n });\n }\n const wire = parseWhereParam(c);\n const limit = parseLimit(c.req.query(\"limit\"));\n const { count, manifestPointer, fresh } = await runAllWithMeta(\n collectionReadContext(db, collection),\n {\n wire,\n order: undefined,\n limit,\n },\n { countOnly: true },\n );\n return c.json(\n {\n data: { count },\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<{ count: number }>,\n 200,\n );\n });\n\n // Long-poll — GET /v1/since?collection=<name>&cursor=<opaque>\n app.get(\"/v1/since\", async (c) => {\n // The router does NOT set `c.var.db`; the adapter resolves the\n // Verifier BEFORE `createRouter` is called and the resulting `db`\n // is captured in this closure. The handler reads it from the\n // outer scope, not from `c.var`.\n const collection = c.req.query(\"collection\");\n if (typeof collection !== \"string\" || collection.length === 0 || collection.includes(\"/\")) {\n throw new BaerlyError(\n \"SchemaError\",\n \"GET /v1/since requires a non-empty `collection` query parameter without `/`\",\n );\n }\n const cursor = c.req.query(\"cursor\") ?? \"\";\n const result = await longPollSince({\n db,\n collection,\n cursor,\n signal: c.req.raw.signal,\n timeoutMs: sinceTimeoutMs,\n pollIntervalMs: sincePollIntervalMs,\n });\n // 200 covers both \"new events present\" and \"timeout idle\" —\n // see `./since.ts` module JSDoc for why we don't use 304.\n return c.json(result satisfies SinceResponse, 200);\n });\n\n app.onError((err, c) => mapToResponse(c, err));\n\n return app;\n}\n\n/**\n * Hard cap on request-body bytes. 1 MiB — matches `S3HttpStorage`'s\n * conformance-suite default. Over-cap → `413 PayloadTooLarge`.\n *\n * The Node adapter (`@baerly/adapter-node`) imports this constant\n * and passes it to `applyBodyCap`, which wraps the request body\n * with a counting `TransformStream` so chunked uploads trip the cap\n * mid-stream and the upstream `IncomingMessage` is drained. The\n * router's `readJsonBody` enforces the same cap on every host\n * (Content-Length pre-check, then a counted streaming read), which is\n * the only cap on Workers.\n *\n * @internal — exported for tests and for the Node adapter's\n * `applyBodyCap` helper. Promote to\n * `packages/protocol/src/constants.ts` only on a third cross-\n * package consumer.\n */\nexport const MAX_BODY_BYTES = 1 << 20; // 1 MiB; matches `S3HttpStorage`'s conformance-suite default.\n\n/**\n * Assert that `body[field]` is a plain object (not undefined / null /\n * array / primitive). Returns the value typed as\n * `Record<string, unknown>` so the caller's next cast doesn't need\n * another guard. Throws `BaerlyError{code:\"SchemaError\"}` with the\n * locked wording `\"Request body must be { <field>: object }\"`.\n *\n * Used by POST `/v1/c/:collection` (`doc`), PATCH `/v1/c/:collection/:id`\n * (`patch`), and PUT `/v1/c/:collection/:id` (`doc`).\n *\n * @internal\n */\nconst assertJsonBodyField = (body: unknown, field: string): Record<string, unknown> => {\n const value =\n typeof body === \"object\" && body !== null\n ? (body as Record<string, unknown>)[field]\n : undefined;\n if (value === undefined || typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new BaerlyError(\"SchemaError\", `Request body must be { ${field}: object }`, {\n resolution: WRITE_BODY_SHAPE_RESOLUTION,\n });\n }\n return value as Record<string, unknown>;\n};\n\n/**\n * Read the optional `mintedId` of a `POST /v1/c/:collection` body. An SDK\n * that minted the doc's `_id` itself sends it in both `doc._id` and\n * `mintedId`; the flag lets a resend of the same insert replay as the\n * original `201 { _id }` (see `runInsert`). A server that predates the\n * field reads only `doc`, so it treats the id as caller-supplied and a\n * resend gets strict `409 AlreadyExists`, never a duplicate row.\n *\n * Validated before any I/O: `mintedId` must be a string with the\n * canonical UUIDv7 shape (`isUuidV7`, which also satisfies the `_id`\n * key-segment rule `assertDocId` applies) and must equal `doc._id`. The\n * UUIDv7 rule keeps a human-chosen id such as `\"migration-x\"` from\n * opting into replay. Absent → `undefined`.\n *\n * @throws BaerlyError code=\"SchemaError\" — `mintedId` is present and\n * fails any of those checks.\n *\n * @internal\n */\nconst readMintedId = (body: unknown, doc: Record<string, unknown>): string | undefined => {\n const raw = (body as Record<string, unknown>)[\"mintedId\"];\n if (raw === undefined) {\n return undefined;\n }\n if (typeof raw !== \"string\" || !isUuidV7(raw) || doc[\"_id\"] !== raw) {\n throw new BaerlyError(\n \"SchemaError\",\n \"Request body mintedId must be a UUIDv7 string equal to doc._id\",\n { resolution: WRITE_BODY_SHAPE_RESOLUTION },\n );\n }\n return raw;\n};\n\n/**\n * Parse the `?where=<urlencoded JSON>` query-string param. Absent or\n * empty → {@link EMPTY_PREDICATE_WIRE} (match-all). Malformed JSON →\n * `BaerlyError{code:\"SchemaError\"}` with the locked wording\n * `\"Invalid JSON in ?where=\"`. Returns the validated wire form\n * ({@link PredicateWire}).\n *\n * Wire-only validation: any clause with `field === \"_id\"` rejects\n * with `BaerlyError{code:\"InvalidConfig\"}` — agents zero-shot\n * writing `?where={\"clauses\":[{\"op\":\"eq\",\"field\":\"_id\",\"value\":\"x\"}]}`\n * against the list route get pointed at `GET /v1/c/:collection/:id`\n * instead. Kernel-internal `_id` wire construction\n * (`./collection.ts:byId`, `runByIdWithMeta`, `runInsert`) bypasses this\n * layer by design — those paths never come back through `?where=`\n * parsing.\n *\n * @internal\n */\nconst parseWhereParam = (c: Context): PredicateWire => {\n const whereParam = c.req.query(\"where\");\n if (whereParam === undefined || whereParam.length === 0) {\n return EMPTY_PREDICATE_WIRE;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(whereParam);\n } catch {\n throw new BaerlyError(\"SchemaError\", \"Invalid JSON in ?where=\", {\n resolution: WHERE_ORDER_JSON_RESOLUTION,\n });\n }\n try {\n return validateWire(parsed as PredicateWire);\n } catch (error) {\n throw markCallerFacingInvalidConfig(error);\n }\n};\n\n/**\n * Parse `?limit=<n>` as a non-negative safe integer. Returns\n * `undefined` when absent. Rejects floats, NaN, negatives, and\n * non-numeric input with `SchemaError`.\n *\n * @internal\n */\nfunction parseLimit(raw: string | undefined): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const n = Number(raw);\n if (!Number.isSafeInteger(n) || n < 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `?limit= must be a non-negative integer; got ${JSON.stringify(raw)}`,\n );\n }\n return n;\n}\n\n/**\n * Parse the `?order=<json>` query param. Mirrors the `?where=` parser\n * shape: undefined → no order, malformed JSON → `SchemaError`. The\n * engine (`runAllWithMeta` → `orderRows`) validates the shape\n * itself, so this only handles the wire-level JSON decode.\n *\n * @internal\n */\nfunction parseOrder(raw: string | undefined): OrderSpec<DocumentData> | undefined {\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new BaerlyError(\"SchemaError\", \"Invalid JSON in ?order=\", {\n resolution: WHERE_ORDER_JSON_RESOLUTION,\n });\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BaerlyError(\"SchemaError\", \"?order= must encode a JSON object\", {\n resolution: WHERE_ORDER_JSON_RESOLUTION,\n });\n }\n return parsed as OrderSpec<DocumentData>;\n}\n\n// Exported as the single source of truth for the error-code → HTTP-status\n// mapping: the runtime router (below) and the build-time spec generator\n// (`spec/ir.ts`, reached via the `_internal/spec-gen` subpath) both read it,\n// so the served `/v1/spec` contract cannot drift from real router behaviour —\n// that drift gate is the point. Deliberately NOT re-exported from the\n// `@baerly/server/http` barrel, so the published package surface is unchanged.\nexport const ERROR_TO_STATUS: ReadonlyMap<BaerlyErrorCode, HttpStatus> = new Map<\n BaerlyErrorCode,\n HttpStatus\n>([\n [\"Unauthorized\", 401],\n [\"AccessDenied\", 403],\n [\"NotFound\", 404],\n [\"WriteConflict\", 409],\n [\"AlreadyExists\", 409],\n [\"AmbiguousCommit\", 409],\n [\"CapacityExceeded\", 409],\n [\"MaintenancePending\", 503],\n [\"CursorExpired\", 410],\n [\"PayloadTooLarge\", 413],\n [\"UnsupportedMediaType\", 415],\n [\"SchemaError\", 400],\n [\"InvalidConfig\", 400],\n [\"UnsatisfiablePredicate\", 400],\n [\"NetworkError\", 502],\n [\"InvalidResponse\", 502],\n // Internal → 500\n]);\n\n/**\n * Machine-visible policy for whether an error code's thrown message is\n * safe to copy into the HTTP envelope. This is code-level metadata.\n * `InvalidConfig` is the one contextual code: predicate-wire validation\n * errors are caller-facing, but storage/adapter config errors may carry\n * internal layout.\n *\n * Deliberately NOT re-exported from the `@baerly/server/http` barrel.\n */\nexport type ErrorMessagePolicy = \"public\" | \"scrubbed\" | \"contextual\";\n\ntype ErrorCodePolicy =\n | { readonly messagePolicy: \"public\" }\n | {\n readonly messagePolicy: \"scrubbed\";\n readonly scrubbedMessage: string;\n }\n | {\n readonly messagePolicy: \"contextual\";\n readonly scrubbedMessage: string;\n readonly shouldExpose: (err: BaerlyError) => boolean;\n };\n\nconst ERROR_CODE_POLICY = {\n AccessDenied: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"access denied\",\n },\n AlreadyExists: {\n messagePolicy: \"public\",\n },\n CapacityExceeded: {\n messagePolicy: \"public\",\n },\n MaintenancePending: {\n messagePolicy: \"public\",\n },\n CursorExpired: {\n messagePolicy: \"public\",\n },\n AmbiguousCommit: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"commit outcome is ambiguous; the mutation may or may not have been applied\",\n },\n Internal: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n InvalidConfig: {\n messagePolicy: \"contextual\",\n scrubbedMessage: \"invalid server configuration\",\n shouldExpose: (err) => isCallerFacing(err),\n },\n InvalidResponse: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"upstream response error\",\n },\n MutationFailed: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n NetworkError: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"upstream network error\",\n },\n NotFound: {\n messagePolicy: \"public\",\n },\n PayloadTooLarge: {\n messagePolicy: \"public\",\n },\n UnsupportedMediaType: {\n messagePolicy: \"public\",\n },\n SchemaError: {\n messagePolicy: \"public\",\n },\n Unauthorized: {\n messagePolicy: \"public\",\n },\n UnexpectedWriteInQuery: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n UnsatisfiablePredicate: {\n messagePolicy: \"public\",\n },\n UseQueryAwaitedRecorder: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n WriteConflict: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage:\n \"write conflict: another write changed this data first; this commit did not land\",\n },\n} as const satisfies Record<BaerlyErrorCode, ErrorCodePolicy>;\n\nexport const errorMessagePolicyFor = (code: BaerlyErrorCode): ErrorMessagePolicy =>\n ERROR_CODE_POLICY[code].messagePolicy;\n\nconst markCallerFacingInvalidConfig = (err: unknown): unknown => {\n if (err instanceof BaerlyError && err.code === \"InvalidConfig\") {\n markCallerFacing(err);\n }\n return err;\n};\n\nconst shouldExposeErrorMessage = (err: BaerlyError): boolean => {\n const policy = ERROR_CODE_POLICY[err.code];\n if (policy.messagePolicy === \"public\") {\n return true;\n }\n if (policy.messagePolicy === \"scrubbed\") {\n return false;\n }\n return policy.shouldExpose(err);\n};\n\nconst scrubbedMessageFor = (code: BaerlyErrorCode): string => {\n const policy = ERROR_CODE_POLICY[code];\n return policy.messagePolicy === \"public\" ? \"internal error\" : policy.scrubbedMessage;\n};\n\nconst logScrubbedError = (err: BaerlyError, status: HttpStatus): void => {\n const ctx = getCurrentContext();\n getLogger(CATEGORY.http).error(\"scrubbed_error\", {\n error: serializeError(err),\n status,\n ...(ctx !== undefined ? { request_id: ctx.request_id } : {}),\n });\n};\n\n/**\n * Map an unknown thrown value onto the wire envelope plus an HTTP\n * status code. The mapping is keyed by `BaerlyError.code` so any future\n * code addition forces a re-check here. Unmapped server-side codes fall\n * through to 500 by design — currently only `Internal`.\n *\n * Public via `@gusto/baerly-storage/http` for the embed-by-hand recipe\n * (your own Hono / Express / Fastify app calling `Db` directly).\n * The `HttpErrorEnvelope` shape is locked; do not mutate it.\n */\nexport function mapError(err: unknown): { status: HttpStatus; envelope: HttpErrorEnvelope } {\n if (err instanceof BaerlyError) {\n const mappedStatus = ERROR_TO_STATUS.get(err.code);\n const status = mappedStatus ?? 500;\n const wireCode: BaerlyErrorCode = mappedStatus === undefined ? \"Internal\" : err.code;\n // Do not use HTTP status as the \"safe to expose\" signal: storage\n // and protocol errors mapped to 4xx/502 often carry physical bucket\n // keys, ETags, upstream response bodies, or provider binding text.\n // Preserve caller-facing messages, scrub server/storage diagnostics,\n // and keep the full detail in the server-side log.\n if (wireCode !== err.code || !shouldExposeErrorMessage(err)) {\n logScrubbedError(err, status);\n return {\n status,\n envelope: errorEnvelope(wireCode, scrubbedMessageFor(wireCode), {\n // The row id is caller-owned data, not a storage diagnostic, so\n // it survives the message scrub.\n _id: wireCode === err.code ? err._id : undefined,\n }),\n };\n }\n return {\n status,\n envelope: errorEnvelope(err.code, err.message, {\n issues: err.issues,\n resolution: err.resolution,\n _id: err._id,\n retryAfter: err.retryAfter,\n }),\n };\n }\n // Unknown thrown value: the message may carry internal detail\n // (file paths, bucket names, upstream response bodies). Log on the\n // server side via the observability channel (replaces the legacy\n // bare `console.error`) and return a generic envelope to the\n // client. The mapped-error wire shape itself is locked and does\n // NOT change here.\n getLogger(CATEGORY.http).error(\"unhandled_error\", { error: serializeError(err) });\n return { status: 500, envelope: errorEnvelope(\"Internal\", \"internal error\") };\n}\n\n// Early capacity warning (main-10 G7): a write the capacity check admitted\n// near the host's refusal point stamped its text on the request's\n// canonical-line fields; surface it as a response header on the success\n// path. A refusal already carries its own envelope.\nfunction stampCapacityWarning(c: Context): void {\n const warning = getCurrentContext()?.fields.get(CAPACITY_WARNING_FIELD);\n if (typeof warning === \"string\") {\n c.header(CAPACITY_WARNING_HEADER, warning);\n }\n}\n\n// Hono-context shortcut used by every handler's catch block.\nfunction mapToResponse(c: Context, err: unknown): Response {\n const { status, envelope } = mapError(err);\n // `mapError` only returns 4xx/5xx — all of which are\n // `ContentfulStatusCode`. The cast bridges the locked `HttpStatus`\n // union (which also includes 204/304 for the wider contract) to\n // Hono's narrower body-bearing subset.\n const { retryAfter } = envelope.error;\n if (retryAfter !== undefined) {\n c.header(\"Retry-After\", String(Math.ceil(retryAfter)));\n }\n return c.json(envelope, status as ContentfulStatusCode);\n}\n\n/**\n * Read and parse the JSON request body. Returns the parsed value\n * (an `unknown` — caller narrows). Throws `BaerlyError`:\n *\n * - `\"UnsupportedMediaType\"` (→ 415), before any read, unless the\n * `Content-Type` is `application/json` or a `+json` type\n * (parameters such as `charset` allowed). Requiring it keeps every\n * write route off the CORS-simple request list, so another origin\n * cannot forge a write under ambient auth (`auth: \"none\"`, cookie\n * sessions).\n * - `\"PayloadTooLarge\"` (→ 413) when the body exceeds `maxBytes`:\n * up front from `Content-Length`, else as soon as the running size\n * of a chunked body passes the cap. The read stops there and the\n * stream is cancelled, so no host buffers more than `maxBytes`\n * (workerd has no platform cap). A `BaerlyError` surfaced by an\n * upstream pump (the Node adapter's `applyBodyCap`) is re-thrown\n * verbatim.\n * - `\"SchemaError\"` (→ 400) for empty bodies, JSON parse failures,\n * and any other read failure.\n *\n * Hono's `app.onError` sink routes the throw through `mapToResponse`.\n */\nasync function readJsonBody(c: Context, maxBytes: number): Promise<unknown> {\n const [typeAndSubtype = \"\"] = (c.req.header(\"content-type\") ?? \"\").split(\";\");\n const mediaType = typeAndSubtype.trim().toLowerCase();\n if (mediaType !== \"application/json\" && !/^[a-z0-9.+-]+\\/[a-z0-9.+-]+\\+json$/.test(mediaType)) {\n let got = mediaType === \"\" ? \"no Content-Type\" : mediaType;\n if (got.length > UNSUPPORTED_MEDIA_TYPE_ECHO_CHARS) {\n got = `${got.slice(0, UNSUPPORTED_MEDIA_TYPE_ECHO_CHARS)}…`;\n }\n throw new BaerlyError(\n \"UnsupportedMediaType\",\n `${c.req.method} bodies must be sent as application/json; got ${got}`,\n );\n }\n const tooLarge = (): BaerlyError =>\n new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${maxBytes} bytes`);\n const lenHeader = c.req.header(\"content-length\");\n if (lenHeader !== undefined && Number.parseInt(lenHeader, 10) > maxBytes) {\n throw tooLarge();\n }\n let raw = \"\";\n try {\n const body = c.req.raw.body;\n if (body !== null) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n size += value.byteLength;\n if (size > maxBytes) {\n reader.cancel().catch(() => {});\n throw tooLarge();\n }\n raw += decoder.decode(value, { stream: true });\n }\n raw += decoder.decode();\n }\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"SchemaError\",\n `Failed to read request body: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (raw.length === 0) {\n throw new BaerlyError(\"SchemaError\", \"Empty request body\", {\n resolution: WRITE_BODY_SHAPE_RESOLUTION,\n });\n }\n try {\n return JSON.parse(raw);\n } catch {\n throw new BaerlyError(\"SchemaError\", \"Invalid JSON in request body\", {\n resolution: WRITE_BODY_SHAPE_RESOLUTION,\n });\n }\n}\n"],"ignoreList":[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,mBAAmB;;;;;;;;;;;AAoBzB,MAAa,gBAAgB,YAAgC,QAC3D,eAAe,KAAA,IAAY,MAAM,GAAG,aAAa,mBAAmB;;;;;;;;;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