@gusto/baerly-storage 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +38 -39
  53. package/dist/dev-vite.js +67 -36
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/sha256-4FfGQNPw.js +22 -0
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/sigv4-sign-5IUflUD_.js +507 -0
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-BL_JoPTn.js","names":["FETCH_TIMEOUT_MS","fsReadFile","fsReadFile","#body","#init","#eventInitDict","relativePath","pathSep","resolvePath","relative"],"sources":["../packages/protocol/src/storage/probe-cas.ts","../packages/adapter-node/src/credentials/signer.ts","../packages/adapter-node/src/storage-factories.ts","../packages/adapter-node/src/local-fs-storage.ts","../packages/adapter-node/src/resolve-storage.ts","../packages/adapter-node/src/assert-storage-reachable.ts","../packages/adapter-node/src/credentials/token-file.ts","../packages/adapter-node/src/credentials/from-eks-pod-identity.ts","../packages/adapter-node/src/credentials/from-web-identity.ts","../packages/adapter-node/src/credentials/from-eks.ts","../node_modules/.pnpm/@hono+node-server@2.0.6_hono@4.12.27/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/helper/websocket/index.js","../node_modules/.pnpm/@hono+node-server@2.0.6_hono@4.12.27/node_modules/@hono/node-server/dist/index.mjs","../packages/adapter-node/src/middleware/body-cap.ts","../packages/adapter-node/src/middleware/dev-landing.ts","../packages/adapter-node/src/middleware/static-assets.ts","../packages/adapter-node/src/logger-pretty.ts","../packages/adapter-node/src/server.ts","../packages/adapter-node/src/app.ts","../packages/adapter-node/src/baerly-node.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.ts\";\nimport { uuid } from \"../types.ts\";\nimport type { Storage } from \"./types.ts\";\n\nconst isConflict = (error: unknown): boolean =>\n error instanceof BaerlyError && error.code === \"Conflict\";\n\n/** One CAS sub-check's outcome. */\nexport interface CasProbeCheck {\n /** Stable identifier (`ifMatch-stale` / `ifNoneMatch-exists` / `ifNoneMatch-concurrent`). */\n readonly name: string;\n /** `true` iff the backend rejected the conditional write as required. */\n readonly ok: boolean;\n /** Human-readable detail — what was expected vs. observed. */\n readonly detail: string;\n}\n\n/** Aggregate result of {@link probeCas}. `ok` iff every sub-check passed. */\nexport interface CasProbeResult {\n readonly ok: boolean;\n readonly checks: readonly CasProbeCheck[];\n}\n\n/**\n * Runtime probe that a live `Storage` backend honours the conditional\n * writes the protocol depends on. The storage conformance suite asserts\n * the same semantics in CI for every shipped adapter, but a deployment\n * may point baerly at an arbitrary S3-compatible store; a backend that\n * silently *ignores* these conditionals causes silent corruption — the\n * log-append commit relies on `If-None-Match:\"*\"` create-if-absent\n * being exactly-one-winner under concurrency (the winning create IS the\n * commit; two winners produce split-brain commit), and the compactor\n * CAS-advances `current.json` with `If-Match` under the no-lease\n * maintenance fold (a backend that returns 200 instead of rejecting a\n * stale `If-Match` causes lost-update corruption). This is the\n * fail-loud, deploy-time analogue of the conformance CAS block.\n *\n * Writes throwaway sentinels under `keyPrefix` and deletes them on\n * the way out (even on failure). Three checks, mirroring the conformance\n * suite:\n * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).\n * - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:\"*\"` over an existing\n * key must reject (Conflict).\n * - `ifNoneMatch-concurrent`: at most one of N concurrent create-if-absent\n * writes on a fresh key wins — the linearizability the writer's log-append\n * commit already relies on (`writer.ts`).\n *\n * A rejected write surfaces as a `BaerlyError` with `code === \"Conflict\"`\n * (the contract `Storage.put` documents); anything else — a resolved\n * promise, or a non-Conflict error — is reported as a failed or\n * inconclusive check rather than thrown.\n */\nexport const probeCas = async (\n storage: Storage,\n opts?: { keyPrefix?: string; signal?: AbortSignal },\n): Promise<CasProbeResult> => {\n const prefix = opts?.keyPrefix ?? \"\";\n const key = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const enc = new TextEncoder();\n const signal = opts?.signal;\n\n const checks: CasProbeCheck[] = [];\n try {\n const first = await storage.put(key, enc.encode(\"v1\"), { signal });\n\n // ── Check 1: a stale ifMatch must be rejected. ──────────────────\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v2\"), { ifMatch: '\"baerly-cas-probe-stale\"', signal });\n checks.push({\n name: \"ifMatch-stale\",\n ok: false,\n detail:\n \"PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk).\",\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifMatch-stale\",\n ok: true,\n detail: \"stale If-Match rejected (Conflict), as required.\",\n }\n : {\n name: \"ifMatch-stale\",\n ok: false,\n detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // ── Check 2: ifNoneMatch:\"*\" over an existing key must reject. ──\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v3\"), { ifNoneMatch: \"*\", signal });\n checks.push({\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail:\n 'PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe).',\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifNoneMatch-exists\",\n ok: true,\n detail: 'If-None-Match:\"*\" over an existing key rejected (Conflict), as required.',\n }\n : {\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail: `If-None-Match:\"*\" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // ── Check 3: at most one of N concurrent ifNoneMatch:\"*\" creates wins. ──\n // The writer already depends on this today: log entries are PUT with\n // ifNoneMatch:\"*\", and a 412 means a peer won that seq (writer.ts). Two\n // winners ⇒ two writers believe they appended the same log seq.\n // Transient non-Conflict losers (e.g. an S3 409\n // ConditionalRequestConflict, which the adapter maps to a retryable\n // NetworkError) are inconclusive — the writer re-issues the same-seq\n // PUT and resolves to 200/412 — not proof of a broken backend. The\n // deploy-time probe still fails closed so operators retry for a clean race.\n const raceKey = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const RACERS = 16;\n try {\n const outcomes = await Promise.allSettled(\n Array.from({ length: RACERS }, (_unused, i) =>\n // Stryker disable next-line StringLiteral: body content irrelevant; only the conditional header + winner count is tested\n storage.put(raceKey, enc.encode(`r${i}`), { ifNoneMatch: \"*\", signal }),\n ),\n );\n const winners = outcomes.filter((o) => o.status === \"fulfilled\").length;\n const transient = outcomes.filter(\n (o) => o.status === \"rejected\" && !isConflict(o.reason),\n ).length;\n if (winners > 1) {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `${winners} of ${RACERS} concurrent create-if-absent writes won (expected at most 1) — create-if-absent is NOT linearizable; the log-append commit would split-brain.`,\n });\n } else if (winners === 1) {\n if (transient === 0) {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: true,\n detail: `exactly one of ${RACERS} concurrent create-if-absent writes won; the rest rejected (Conflict), as required.`,\n });\n } else {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `exactly one of ${RACERS} concurrent create-if-absent writes won, but ${transient} loser(s) returned a transient non-Conflict error — inconclusive; retry for a clean race.`,\n });\n }\n } else {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `no create-if-absent write succeeded across ${RACERS} attempts — inconclusive (transient failure or outage), not a linearizability verdict; retry.`,\n });\n }\n } finally {\n try {\n await storage.delete(raceKey, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n void first;\n } finally {\n // Best-effort cleanup — never let a delete failure mask the verdict.\n try {\n await storage.delete(key, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n return { ok: checks.every((c) => c.ok), checks };\n};\n","import { AwsClient } from \"aws4fetch\";\nimport type { Credentials, CredentialsProvider } from \"./types.ts\";\n\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\nfunction buildAwsClient(creds: Credentials, region: string): AwsClient {\n return new AwsClient({\n accessKeyId: creds.accessKeyId,\n secretAccessKey: creds.secretAccessKey,\n sessionToken: creds.sessionToken,\n region,\n service: \"s3\",\n });\n}\n\nexport function refreshingSigner(opts: {\n region: string;\n credentials: Credentials | CredentialsProvider;\n now?: () => number;\n}): (req: Request) => Promise<Request> {\n const region = opts.region;\n const now = opts.now ?? (() => Date.now());\n\n if (typeof opts.credentials !== \"function\") {\n const aws = buildAwsClient(opts.credentials, region);\n return (req) => aws.sign(req);\n }\n\n const provider = opts.credentials;\n let cached: { aws: AwsClient; expiresAt: number } | null = null;\n let inFlight: Promise<AwsClient> | null = null;\n\n const resolve = async (): Promise<AwsClient> => {\n if (cached !== null && cached.expiresAt - REFRESH_BUFFER_MS > now()) {\n return cached.aws;\n }\n if (inFlight !== null) {\n return inFlight;\n }\n inFlight = (async () => {\n try {\n const creds = await provider();\n const aws = buildAwsClient(creds, region);\n const expiresAt = creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY;\n cached = { aws, expiresAt };\n return aws;\n } finally {\n inFlight = null;\n }\n })();\n return inFlight;\n };\n\n return async (req) => {\n const aws = await resolve();\n return aws.sign(req);\n };\n}\n","import type { Storage } from \"@baerly/protocol\";\nimport { S3HttpStorage } from \"./s3-http.ts\";\nimport { refreshingSigner } from \"./credentials/signer.ts\";\nimport type { Credentials, CredentialsProvider } from \"./credentials/types.ts\";\n\nfunction buildS3Storage(opts: {\n endpoint: string;\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n const sign = refreshingSigner({ region: opts.region, credentials: opts.credentials });\n return new S3HttpStorage({ endpoint: opts.endpoint, bucket: opts.bucket, sign });\n}\n\n/**\n * AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard\n * `aws4fetch` SigV4 signer. The endpoint is derived from the region as\n * `https://s3.<region>.amazonaws.com`.\n *\n * @example Static credentials\n * ```ts\n * import { s3Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n *\n * @example EKS (refreshing) — auto-detects Pod Identity or IRSA\n * ```ts\n * import { s3Storage, fromEks } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: fromEks(),\n * });\n * ```\n */\nexport function s3Storage(opts: {\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://s3.${opts.region}.amazonaws.com`,\n region: opts.region,\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Cloudflare R2 `Storage` factory (S3-compat endpoint). Derives the\n * endpoint from `accountId` as\n * `https://<accountId>.r2.cloudflarestorage.com` and pins region\n * `\"auto\"` — R2 ignores region but `aws4fetch`'s signer requires\n * the field to be set.\n *\n * For Workers that have a native R2 binding (no HTTP hop), see\n * `r2BindingStorage` in `@baerly/adapter-cloudflare`. This factory\n * is for Node hosts that talk to R2 over its public S3-compat URL.\n *\n * @example\n * ```ts\n * import { r2Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = r2Storage({\n * accountId: process.env[\"R2_ACCOUNT_ID\"]!,\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function r2Storage(opts: {\n accountId: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,\n region: \"auto\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Minio `Storage` factory — for local-dev / self-hosted S3-compat.\n * Endpoint is fully caller-supplied (e.g. `http://localhost:9102`)\n * because Minio deployments don't follow a URL template. Region is\n * pinned to `\"us-east-1\"`; Minio ignores it but `aws4fetch` requires\n * a value.\n *\n * @example\n * ```ts\n * import { minioStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = minioStorage({\n * endpoint: process.env[\"BAERLY_S3_ENDPOINT\"] ?? \"http://localhost:9102\",\n * bucket: \"baerly\",\n * credentials: {\n * accessKeyId: process.env[\"MINIO_ACCESS_KEY\"]!,\n * secretAccessKey: process.env[\"MINIO_SECRET_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function minioStorage(opts: {\n endpoint: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: opts.endpoint,\n region: \"us-east-1\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Google Cloud Storage `Storage` factory via the S3-compat endpoint\n * at `https://storage.googleapis.com`. Authentication uses GCS HMAC\n * keys (Console → Settings → Interoperability) — the HMAC access key\n * goes into `credentials.accessKeyId` and the HMAC secret goes into\n * `credentials.secretAccessKey`. Region is pinned to `\"auto\"`.\n *\n * GCS's S3-compat surface covers the four `Storage` methods\n * (`get`/`put`/`delete`/`list`), but Google documents the\n * `If-Match`/`If-None-Match` headers this kernel coordinates on as\n * read-only (native conditional writes use `x-goog-if-generation-match`).\n * Whether GCS's interop layer enforces S3-style conditional *writes* is\n * unverified — run `baerly doctor --bucket=<your-gcs-bucket>` before\n * relying on it; a backend that fails the CAS probe is not a safe baerly\n * store. See ADR-002.\n *\n * @example\n * ```ts\n * import { gcsStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = gcsStorage({\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"GCS_HMAC_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"GCS_HMAC_SECRET\"]!,\n * },\n * });\n * ```\n */\nexport function gcsStorage(opts: {\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: \"https://storage.googleapis.com\",\n region: \"auto\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n","import { resolve } from \"node:path\";\nimport type { Storage } from \"@baerly/protocol\";\nimport { LocalFsStorage } from \"@baerly/dev/local-fs\";\n\nexport interface LocalFsStorageFactoryOptions {\n /**\n * Root data directory. Resolution order: this option →\n * `$BAERLY_DATA_DIR` → `<cwd>/.baerly-data`.\n */\n readonly dataDir?: string;\n}\n\n/**\n * Zero-config local `Storage` for single-node dev / self-hosted runs.\n * Persists to the filesystem (content-addressed, atomic writes), so data\n * survives process restarts — unlike `MemoryStorage`, which is per-process\n * and lost on exit.\n *\n * NOT for multi-instance production: `LocalFsStorage`'s `ifMatch` CAS is\n * in-process TOCTOU only (cross-process `current.json` CAS-advance is not\n * atomic — see its class JSDoc). For horizontally-scaled deploys use\n * `s3Storage` / `r2Storage`, whose cross-process guarantee the no-lease\n * maintenance fold relies on.\n *\n * @example\n * ```ts\n * import { baerlyNode, localFsStorage } from \"@gusto/baerly-storage/node\";\n * import config from \"./baerly.config.ts\";\n *\n * // Runs with zero credentials; persists to ./.baerly-data.\n * await baerlyNode({ config, storage: localFsStorage() }).listen(8080);\n * ```\n */\nexport const localFsStorage = (opts?: LocalFsStorageFactoryOptions): Storage =>\n new LocalFsStorage({\n root: opts?.dataDir ?? process.env[\"BAERLY_DATA_DIR\"] ?? resolve(process.cwd(), \".baerly-data\"),\n });\n","import { BaerlyError, isDeployedEnv, type Storage } from \"@baerly/protocol\";\nimport { localFsStorage } from \"./local-fs-storage.ts\";\nimport { r2Storage, s3Storage } from \"./storage-factories.ts\";\n\n/** Result of {@link resolveStorageFromEnv}. */\nexport interface ResolvedStorage {\n readonly storage: Storage;\n /** Human-readable backend label for a startup log line. */\n readonly label: string;\n}\n\n/**\n * Choose a Node `Storage` backend from environment variables, in priority\n * order:\n * 1. `R2_ACCOUNT_ID` set → Cloudflare R2 (S3-compat endpoint)\n * 2. `BUCKET` set → AWS S3\n * 3. neither, local dev → `localFsStorage` (zero credentials)\n * 4. neither, deployed → throw\n *\n * This is the safe default the example scaffolds use, exported so apps\n * don't hand-roll their own selector and reintroduce the silent\n * in-memory / local-fs fallback this library exists to prevent. There is\n * deliberately **no** fallback to a non-durable store in a deployment:\n * local-fs is single-process with no cross-process CAS and no crash\n * durability, and in-memory storage loses all data on restart, so a\n * deployed environment with no bucket fails loud instead.\n *\n * `env` is injectable for testing; it defaults to `process.env`.\n *\n * @throws BaerlyError `InvalidConfig` when {@link isDeployedEnv} is true\n * and no bucket is configured, or when a configured bucket is missing its\n * credentials.\n *\n * @example\n * ```ts\n * import { baerlyNode, resolveStorageFromEnv } from \"@gusto/baerly-storage/node\";\n * import config from \"./baerly.config.ts\";\n *\n * const { storage, label } = resolveStorageFromEnv();\n * console.log(`[baerly] storage=${label}`);\n * await baerlyNode({ config, storage }).listen(Number(process.env[\"PORT\"] ?? 8080));\n * ```\n */\nexport const resolveStorageFromEnv = (\n env: Record<string, string | undefined> = process.env,\n): ResolvedStorage => {\n // An env var set to \"\" is treated as unset for backend selection, so an\n // exported-but-empty BUCKET / R2_ACCOUNT_ID falls through to the local-dev\n // fallback (or the deployment fail-closed) rather than entering a branch\n // and then throwing a confusing \"missing required env var\" for a var that\n // is, technically, set.\n const isSet = (name: string): boolean => (env[name] ?? \"\") !== \"\";\n const reqEnv = (name: string): string => {\n const v = env[name];\n if (v === undefined || v === \"\") {\n throw new BaerlyError(\"InvalidConfig\", `Missing required env var: ${name}`);\n }\n return v;\n };\n\n if (isSet(\"R2_ACCOUNT_ID\")) {\n return {\n storage: r2Storage({\n accountId: reqEnv(\"R2_ACCOUNT_ID\"),\n bucket: reqEnv(\"BUCKET\"),\n credentials: {\n accessKeyId: reqEnv(\"AWS_ACCESS_KEY_ID\"),\n secretAccessKey: reqEnv(\"AWS_SECRET_ACCESS_KEY\"),\n },\n }),\n label: `r2 (bucket=${env[\"BUCKET\"]})`,\n };\n }\n if (isSet(\"BUCKET\")) {\n return {\n storage: s3Storage({\n region: env[\"AWS_REGION\"] ?? \"us-east-1\",\n bucket: reqEnv(\"BUCKET\"),\n credentials: {\n accessKeyId: reqEnv(\"AWS_ACCESS_KEY_ID\"),\n secretAccessKey: reqEnv(\"AWS_SECRET_ACCESS_KEY\"),\n },\n }),\n label: `s3 (bucket=${env[\"BUCKET\"]})`,\n };\n }\n if (!isDeployedEnv(env)) {\n return {\n storage: localFsStorage(),\n label: `local-fs (${env[\"BAERLY_DATA_DIR\"] ?? \"./.baerly-data\"}) — local dev only, not a production store`,\n };\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n [\n \"[baerly] Refusing to start: no durable storage configured in a deployed environment.\",\n \"Local filesystem storage is a local-dev convenience only — single-process, with no\",\n \"cross-process CAS and no crash durability — so it is never used in production.\",\n \"Configure a real bucket:\",\n \" • AWS S3: BUCKET + AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY (+ optional AWS_REGION)\",\n \" • Cloudflare R2: R2_ACCOUNT_ID + BUCKET + AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY\",\n \"Self-hosting without a cloud bucket? Run MinIO on the box for real S3 semantics, or\",\n \"use SQLite + Litestream for a single-instance app.\",\n ].join(\"\\n\"),\n );\n};\n","import { BaerlyError, probeCas, type Storage } from \"@baerly/protocol\";\n\n/** Options for {@link assertStorageReachable}. */\nexport interface AssertStorageReachableOptions {\n /** Key prefix for the throwaway probe sentinels. Default `\"\"`. */\n keyPrefix?: string;\n signal?: AbortSignal;\n}\n\n/**\n * Boot-time readiness check: confirm a live `Storage` backend is both\n * reachable and honours the conditional writes the protocol depends on.\n * `await` it at startup (or from a `/readyz` handler wired to your\n * platform's readiness probe) to fail closed on a misconfigured backend —\n * an unreachable or non-existent bucket, denied/missing credentials (wrong\n * endpoint/region), or an S3-compatible store that silently ignores\n * `If-Match`/`If-None-Match` (the CAS the protocol depends on) — instead\n * of discovering it on the first user write. It cannot detect a\n * wrong-but-writable bucket: a typo to another reachable bucket you own\n * boots clean, because the probe can only tell that *a* bucket is reachable\n * and CAS-correct, not that it is the *intended* one. This complements\n * `resolveStorageFromEnv`, which catches a *missing* configuration:\n * `assertStorageReachable` additionally catches an\n * unreachable/access-denied/CAS-broken backend at boot instead of on the\n * first write.\n *\n * Opt-in by design: it performs a handful of live round-trips (writes and\n * deletes throwaway sentinels under `keyPrefix`), so it is never run\n * automatically on every boot. Reuses the same `probeCas` machinery as\n * `baerly doctor --bucket`.\n *\n * @throws BaerlyError `NetworkError` if the backend is unreachable, or\n * `InvalidConfig` if it is reachable but fails a required CAS check.\n *\n * @example\n * ```ts\n * const { storage, label } = resolveStorageFromEnv();\n * await assertStorageReachable(storage); // throws before we serve traffic\n * console.log(`[baerly] storage=${label} (reachable)`);\n * ```\n */\nexport const assertStorageReachable = async (\n storage: Storage,\n opts?: AssertStorageReachableOptions,\n): Promise<void> => {\n let result;\n try {\n result = await probeCas(storage, opts);\n } catch (error) {\n throw new BaerlyError(\n \"NetworkError\",\n \"Storage readiness check failed: the backend could not be reached. Verify the bucket name, \" +\n `region/endpoint, and credentials. Cause: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n if (!result.ok) {\n const failed = result.checks\n .filter((c) => !c.ok)\n .map((c) => ` - ${c.name}: ${c.detail}`)\n .join(\"\\n\");\n throw new BaerlyError(\n \"InvalidConfig\",\n \"Storage readiness check failed — the backend does not honour the conditional writes baerly \" +\n `requires (data corruption risk). Use a fully S3-conditional-compatible store:\\n${failed}`,\n );\n }\n};\n","import { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * Read and validate an EKS-projected service-account token file, shared by\n * {@link fromWebIdentity} and {@link fromEksPodIdentity}. Reads the file,\n * trims surrounding whitespace (the projected token has a trailing newline),\n * and rejects an empty result.\n *\n * A missing / unreadable / empty projected token is a deploy misconfig, not a\n * transient fault — so every failure is `InvalidConfig`, which short-circuits\n * the retry loop (see `PERMANENT_ERROR_CODES` in `s3-http.ts`) instead of\n * hammering the credential source. Error messages name the specific env var\n * so the misconfig is debuggable.\n */\nexport async function readProjectedToken(\n doReadFile: (path: string, encoding: \"utf8\") => Promise<string>,\n tokenPath: string,\n ctx: { provider: string; envVar: string },\n): Promise<string> {\n let rawToken: string;\n try {\n rawToken = await doReadFile(tokenPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${ctx.provider}: cannot read ${ctx.envVar} (${tokenPath}): ${(error as Error).message}`,\n );\n }\n const token = rawToken.trim();\n if (token === \"\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${ctx.provider}: ${ctx.envVar} (${tokenPath}) is empty`,\n );\n }\n return token;\n}\n","import { readFile as fsReadFile } from \"node:fs/promises\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport type { CredentialsProvider } from \"./types.ts\";\nimport { readProjectedToken } from \"./token-file.ts\";\n\nconst FETCH_TIMEOUT_MS = 2_000;\n\n/**\n * Resolve AWS credentials from the EKS Pod Identity agent (the 2023\n * successor to IRSA). The agent runs on each EKS node and exchanges\n * the pod's projected service-account token for short-lived AWS\n * credentials, so the app just reads the token and asks the agent.\n *\n * Env vars (set by EKS when the pod has an associated IAM role):\n * - `AWS_CONTAINER_CREDENTIALS_FULL_URI` — the agent endpoint\n * (typically `http://169.254.170.23/v1/credentials`).\n * - `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` — path to the\n * projected SA token used to authorize the agent request.\n *\n * Both are required. Agent should respond instantly on the node-local\n * link — 2 s timeout protects against hangs.\n */\nexport function fromEksPodIdentity(\n opts: {\n fetch?: typeof fetch;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n } = {},\n): CredentialsProvider {\n const doFetch = opts.fetch ?? fetch;\n const doReadFile = opts.readFile ?? fsReadFile;\n\n return async () => {\n const uri = process.env[\"AWS_CONTAINER_CREDENTIALS_FULL_URI\"];\n const tokenPath = process.env[\"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\"];\n if (uri === undefined || uri === \"\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"fromEksPodIdentity: AWS_CONTAINER_CREDENTIALS_FULL_URI not set\",\n );\n }\n if (tokenPath === undefined || tokenPath === \"\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"fromEksPodIdentity: AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE not set\",\n );\n }\n\n const token = await readProjectedToken(doReadFile, tokenPath, {\n provider: \"fromEksPodIdentity\",\n envVar: \"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\",\n });\n\n let res: Response;\n try {\n res = await doFetch(uri, {\n method: \"GET\",\n headers: { Authorization: token },\n // The token rides in the Authorization header; a redirect would resend\n // it to the 3xx target. The node-local agent never redirects — refuse\n // rather than follow, so a redirect surfaces as a NetworkError.\n redirect: \"error\",\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n } catch (error) {\n throw new BaerlyError(\n \"NetworkError\",\n `fromEksPodIdentity: agent fetch failed (${(error as Error).message})`,\n );\n }\n\n // 5xx + 429 are transient — bucket as NetworkError so callers /\n // chained providers can retry. Other 4xx are permanent —\n // AccessDenied so retry loops short-circuit (see\n // PERMANENT_ERROR_CODES in s3-http.ts).\n if (res.status >= 500 || res.status === 429) {\n throw new BaerlyError(\"NetworkError\", `fromEksPodIdentity: agent responded ${res.status}`);\n }\n if (!res.ok) {\n throw new BaerlyError(\"AccessDenied\", `fromEksPodIdentity: agent responded ${res.status}`);\n }\n\n let json: {\n AccessKeyId?: string;\n SecretAccessKey?: string;\n Token?: string;\n Expiration?: string;\n };\n try {\n json = await res.json();\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `fromEksPodIdentity: agent returned non-JSON body (${(error as Error).message})`,\n );\n }\n if (\n json.AccessKeyId === undefined ||\n json.SecretAccessKey === undefined ||\n json.Token === undefined ||\n json.Expiration === undefined\n ) {\n throw new BaerlyError(\"InvalidResponse\", \"fromEksPodIdentity: malformed agent response\");\n }\n // A present-but-unparseable Expiration is as malformed as a missing field:\n // `new Date(bad)` yields an Invalid Date (getTime() → NaN) rather than\n // throwing, and the signer's `expiresAt - buffer > now()` refresh check is\n // false for NaN — so a bad timestamp would silently defeat credential\n // caching/rotation. Reject it here instead.\n const expiration = new Date(json.Expiration);\n if (Number.isNaN(expiration.getTime())) {\n throw new BaerlyError(\"InvalidResponse\", \"fromEksPodIdentity: malformed agent response\");\n }\n return {\n accessKeyId: json.AccessKeyId,\n secretAccessKey: json.SecretAccessKey,\n sessionToken: json.Token,\n expiration,\n };\n };\n}\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { readFile as fsReadFile } from \"node:fs/promises\";\nimport type { CredentialsProvider } from \"./types.ts\";\nimport { readProjectedToken } from \"./token-file.ts\";\nimport { parseAssumeRoleWithWebIdentity, parseStsError } from \"../xml.ts\";\n\n// STS is a regional (not node-local) service, so allow more headroom than the\n// 2 s Pod Identity agent budget — but still bound it against hangs.\nconst FETCH_TIMEOUT_MS = 5_000;\nconst DEFAULT_SESSION_NAME = \"baerly-storage\";\n\n/**\n * Resolve AWS credentials via IRSA (IAM Roles for Service Accounts) — the\n * web-identity-token flow, distinct from the EKS Pod Identity agent that\n * {@link fromEksPodIdentity} handles. EKS projects a signed service-account\n * token into the pod and the app exchanges it for short-lived credentials by\n * calling STS `AssumeRoleWithWebIdentity` directly (the token *is* the auth, so\n * the call is unsigned — no chicken-and-egg credential bootstrap).\n *\n * Env vars (set by EKS when the pod's service account is annotated with a role):\n * - `AWS_ROLE_ARN` — the role to assume.\n * - `AWS_WEB_IDENTITY_TOKEN_FILE` — path to the projected SA token.\n * - `AWS_ROLE_SESSION_NAME` — optional session name (defaults to `baerly-storage`).\n * - `AWS_REGION` / `AWS_DEFAULT_REGION` — optional; selects the regional STS\n * endpoint (falls back to the global endpoint).\n *\n * STS credentials expire (~1 h); the returned provider reports `expiration`, so\n * the signing layer re-resolves before they lapse.\n */\nexport function fromWebIdentity(\n opts: {\n fetch?: typeof fetch;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n } = {},\n): CredentialsProvider {\n const doFetch = opts.fetch ?? fetch;\n const doReadFile = opts.readFile ?? fsReadFile;\n\n return async () => {\n const roleArn = process.env[\"AWS_ROLE_ARN\"];\n const tokenPath = process.env[\"AWS_WEB_IDENTITY_TOKEN_FILE\"];\n const sessionName = process.env[\"AWS_ROLE_SESSION_NAME\"] || DEFAULT_SESSION_NAME;\n const region = process.env[\"AWS_REGION\"] || process.env[\"AWS_DEFAULT_REGION\"];\n if (roleArn === undefined || roleArn === \"\") {\n throw new BaerlyError(\"InvalidConfig\", \"fromWebIdentity: AWS_ROLE_ARN not set\");\n }\n if (tokenPath === undefined || tokenPath === \"\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"fromWebIdentity: AWS_WEB_IDENTITY_TOKEN_FILE not set\",\n );\n }\n\n const token = await readProjectedToken(doReadFile, tokenPath, {\n provider: \"fromWebIdentity\",\n envVar: \"AWS_WEB_IDENTITY_TOKEN_FILE\",\n });\n\n // Regional endpoint when a region is known (lower latency, and required in\n // non-default partitions); otherwise the global endpoint.\n const endpoint =\n region !== undefined && region !== \"\"\n ? `https://sts.${region}.amazonaws.com/`\n : \"https://sts.amazonaws.com/\";\n const body = new URLSearchParams({\n Action: \"AssumeRoleWithWebIdentity\",\n Version: \"2011-06-15\",\n RoleArn: roleArn,\n RoleSessionName: sessionName,\n WebIdentityToken: token,\n }).toString();\n\n let res: Response;\n try {\n res = await doFetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/xml\",\n },\n body,\n // The POST carries the web-identity token as its only auth and is\n // unsigned, so a redirect would resend the token to the 3xx target.\n // STS never legitimately redirects this call — refuse rather than\n // follow, so a redirect surfaces as a NetworkError instead of leaking.\n redirect: \"error\",\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n } catch (error) {\n throw new BaerlyError(\n \"NetworkError\",\n `fromWebIdentity: STS fetch failed (${(error as Error).message})`,\n );\n }\n\n // 5xx + 429 are transient — NetworkError so callers / chained providers can\n // retry. Other 4xx (expired/invalid token, role trust mismatch) are\n // permanent — AccessDenied so retry loops short-circuit (see\n // PERMANENT_ERROR_CODES in s3-http.ts). Either way, fold the STS\n // <ErrorResponse> Code/Message into the message — a bare status turns the\n // exact misconfig this provider exists to debug (bad role trust policy,\n // token audience mismatch, clock skew, expired token) into a guessing game.\n if (!res.ok) {\n const stsErr = parseStsError(await res.text());\n const detail =\n stsErr?.Code !== undefined\n ? ` (${stsErr.Code}${stsErr.Message !== undefined ? `: ${stsErr.Message}` : \"\"})`\n : \"\";\n if (res.status >= 500 || res.status === 429) {\n throw new BaerlyError(\n \"NetworkError\",\n `fromWebIdentity: STS responded ${res.status}${detail}`,\n );\n }\n throw new BaerlyError(\n \"AccessDenied\",\n `fromWebIdentity: STS responded ${res.status}${detail}`,\n );\n }\n\n const parsed = parseAssumeRoleWithWebIdentity(await res.text());\n if (\n parsed.AccessKeyId === undefined ||\n parsed.SecretAccessKey === undefined ||\n parsed.SessionToken === undefined ||\n parsed.Expiration === undefined\n ) {\n throw new BaerlyError(\"InvalidResponse\", \"fromWebIdentity: malformed STS response\");\n }\n // A present-but-unparseable Expiration is as malformed as a missing field:\n // `new Date(bad)` yields an Invalid Date (getTime() → NaN) rather than\n // throwing, and the signer's `expiresAt - buffer > now()` refresh check is\n // false for NaN — so a bad timestamp would silently defeat credential\n // caching/rotation. Reject it here instead.\n const expiration = new Date(parsed.Expiration);\n if (Number.isNaN(expiration.getTime())) {\n throw new BaerlyError(\"InvalidResponse\", \"fromWebIdentity: malformed STS response\");\n }\n return {\n accessKeyId: parsed.AccessKeyId,\n secretAccessKey: parsed.SecretAccessKey,\n sessionToken: parsed.SessionToken,\n expiration,\n };\n };\n}\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { fromEksPodIdentity } from \"./from-eks-pod-identity.ts\";\nimport { fromWebIdentity } from \"./from-web-identity.ts\";\nimport type { CredentialsProvider } from \"./types.ts\";\n\n/**\n * Resolve AWS credentials on EKS regardless of which identity mechanism the\n * cluster uses, so callers don't have to know. EKS injects credentials one of\n * two ways:\n *\n * - **Pod Identity** (2023+): `AWS_CONTAINER_CREDENTIALS_FULL_URI` +\n * `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` → {@link fromEksPodIdentity}.\n * - **IRSA** (web-identity token): `AWS_ROLE_ARN` +\n * `AWS_WEB_IDENTITY_TOKEN_FILE` → {@link fromWebIdentity}.\n *\n * Detection runs on every resolve (Pod Identity preferred when both are\n * present), so the right mechanism is picked even if the env is populated late\n * and re-checked on each refresh. Use this instead of the mechanism-specific\n * providers unless you have a reason to pin one.\n */\nexport function fromEks(\n opts: {\n fetch?: typeof fetch;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n } = {},\n): CredentialsProvider {\n const podIdentity = fromEksPodIdentity(opts);\n const webIdentity = fromWebIdentity(opts);\n\n return async () => {\n const uri = process.env[\"AWS_CONTAINER_CREDENTIALS_FULL_URI\"];\n const tokenFile = process.env[\"AWS_WEB_IDENTITY_TOKEN_FILE\"];\n if (uri !== undefined && uri !== \"\") {\n return podIdentity();\n }\n if (tokenFile !== undefined && tokenFile !== \"\") {\n return webIdentity();\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n \"fromEks: no EKS credentials in env — set AWS_CONTAINER_CREDENTIALS_FULL_URI \" +\n \"(Pod Identity) or AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN (IRSA)\",\n );\n };\n}\n","//#region src/utils/response/constants.ts\nconst X_ALREADY_SENT = \"x-hono-already-sent\";\n\n//#endregion\nexport { X_ALREADY_SENT as t };","// src/helper/websocket/index.ts\nvar WSContext = class {\n #init;\n constructor(init) {\n this.#init = init;\n this.raw = init.raw;\n this.url = init.url ? new URL(init.url) : null;\n this.protocol = init.protocol ?? null;\n }\n send(source, options) {\n this.#init.send(source, options ?? {});\n }\n raw;\n binaryType = \"arraybuffer\";\n get readyState() {\n return this.#init.readyState;\n }\n url;\n protocol;\n close(code, reason) {\n this.#init.close(code, reason);\n }\n};\nvar createWSMessageEvent = (source) => {\n return new MessageEvent(\"message\", {\n data: source\n });\n};\nvar defineWebSocketHelper = (handler) => {\n return ((...args) => {\n if (typeof args[0] === \"function\") {\n const [createEvents, options] = args;\n return async function upgradeWebSocket(c, next) {\n const events = await createEvents(c);\n const result = await handler(c, events, options);\n if (result) {\n return result;\n }\n await next();\n };\n } else {\n const [c, events, options] = args;\n return (async () => {\n const upgraded = await handler(c, events, options);\n if (!upgraded) {\n throw new Error(\"Failed to upgrade WebSocket\");\n }\n return upgraded;\n })();\n }\n });\n};\nexport {\n WSContext,\n createWSMessageEvent,\n defineWebSocketHelper\n};\n","import { t as X_ALREADY_SENT } from \"./constants-BLSFu_RU.mjs\";\nimport { STATUS_CODES, createServer } from \"node:http\";\nimport { Http2ServerRequest, constants } from \"node:http2\";\nimport { Readable } from \"node:stream\";\nimport { defineWebSocketHelper } from \"hono/ws\";\n\n//#region src/error.ts\nvar RequestError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"RequestError\";\n\t}\n};\n\n//#endregion\n//#region src/url.ts\nconst reValidRequestUrl = /^\\/[!#$&-;=?-\\[\\]_a-z~]*$/;\nconst reDotSegment = /\\/\\.\\.?(?:[/?#]|$)/;\nconst reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\\d{3,4}|[6-9]\\d{3}))?$/;\nconst buildUrl = (scheme, host, incomingUrl) => {\n\tconst url = `${scheme}://${host}${incomingUrl}`;\n\tif (!reValidHost.test(host)) {\n\t\tconst urlObj = new URL(url);\n\t\tif (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(\":\") ? host.replace(/:\\d+$/, \"\") : host).toLowerCase()) throw new RequestError(\"Invalid host header\");\n\t\treturn urlObj.href;\n\t} else if (incomingUrl.length === 0) return url + \"/\";\n\telse {\n\t\tif (incomingUrl.charCodeAt(0) !== 47) throw new RequestError(\"Invalid URL\");\n\t\tif (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;\n\t\treturn url;\n\t}\n};\n\n//#endregion\n//#region src/request.ts\nconst toRequestError = (e) => {\n\tif (e instanceof RequestError) return e;\n\treturn new RequestError(e.message, { cause: e });\n};\nconst GlobalRequest = global.Request;\nvar Request$1 = class extends GlobalRequest {\n\tconstructor(input, options) {\n\t\tif (typeof input === \"object\" && getRequestCache in input) {\n\t\t\tconst hasReplacementBody = options !== void 0 && \"body\" in options && options.body != null;\n\t\t\tif (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError(\"Cannot construct a Request with a Request object that has already been used.\");\n\t\t\tinput = input[getRequestCache]();\n\t\t}\n\t\tif (typeof (options?.body)?.getReader !== \"undefined\") options.duplex ??= \"half\";\n\t\tsuper(input, options);\n\t}\n};\nconst newHeadersFromIncoming = (incoming) => {\n\tconst headerRecord = [];\n\tconst rawHeaders = incoming.rawHeaders;\n\tfor (let i = 0, len = rawHeaders.length; i < len; i += 2) {\n\t\tconst key = rawHeaders[i];\n\t\tif (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);\n\t}\n\treturn new Headers(headerRecord);\n};\nconst wrapBodyStream = Symbol(\"wrapBodyStream\");\nconst newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n\tconst init = {\n\t\tmethod,\n\t\theaders,\n\t\tsignal: abortController.signal\n\t};\n\tif (method === \"TRACE\") {\n\t\tinit.method = \"GET\";\n\t\tconst req = new Request$1(url, init);\n\t\tObject.defineProperty(req, \"method\", { get() {\n\t\t\treturn \"TRACE\";\n\t\t} });\n\t\treturn req;\n\t}\n\tif (!(method === \"GET\" || method === \"HEAD\")) if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {\n\t\tcontroller.enqueue(incoming.rawBody);\n\t\tcontroller.close();\n\t} });\n\telse if (incoming[wrapBodyStream]) {\n\t\tlet reader;\n\t\tinit.body = new ReadableStream({ async pull(controller) {\n\t\t\ttry {\n\t\t\t\treader ||= Readable.toWeb(incoming).getReader();\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t} });\n\t} else init.body = Readable.toWeb(incoming);\n\treturn new Request$1(url, init);\n};\nconst getRequestCache = Symbol(\"getRequestCache\");\nconst requestCache = Symbol(\"requestCache\");\nconst incomingKey = Symbol(\"incomingKey\");\nconst urlKey = Symbol(\"urlKey\");\nconst methodKey = Symbol(\"methodKey\");\nconst headersKey = Symbol(\"headersKey\");\nconst abortControllerKey = Symbol(\"abortControllerKey\");\nconst getAbortController = Symbol(\"getAbortController\");\nconst abortRequest = Symbol(\"abortRequest\");\nconst bodyBufferKey = Symbol(\"bodyBuffer\");\nconst bodyReadPromiseKey = Symbol(\"bodyReadPromise\");\nconst bodyConsumedDirectlyKey = Symbol(\"bodyConsumedDirectly\");\nconst bodyLockReaderKey = Symbol(\"bodyLockReader\");\nconst abortReasonKey = Symbol(\"abortReason\");\nconst newBodyUnusableError = () => {\n\treturn /* @__PURE__ */ new TypeError(\"Body is unusable\");\n};\nconst rejectBodyUnusable = () => {\n\treturn Promise.reject(newBodyUnusableError());\n};\nconst textDecoder = new TextDecoder();\nconst consumeBodyDirectOnce = (request) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\trequest[bodyConsumedDirectlyKey] = true;\n};\nconst toArrayBuffer = (buf) => {\n\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n};\nconst contentType = (request) => {\n\treturn (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get(\"content-type\") || \"\";\n};\nconst methodTokenRegExp = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst normalizeIncomingMethod = (method) => {\n\tif (typeof method !== \"string\" || method.length === 0) return \"GET\";\n\tswitch (method) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return method;\n\t}\n\tconst upper = method.toUpperCase();\n\tswitch (upper) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return upper;\n\t\tdefault: return method;\n\t}\n};\nconst validateDirectReadMethod = (method) => {\n\tif (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);\n\tconst normalized = method.toUpperCase();\n\tif (normalized === \"CONNECT\" || normalized === \"TRACK\" || normalized === \"TRACE\" && method !== \"TRACE\") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);\n};\nconst readBodyWithFastPath = (request, method, fromBuffer) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\tconst methodName = request.method;\n\tif (methodName === \"GET\" || methodName === \"HEAD\") return request[getRequestCache]()[method]();\n\tconst methodValidationError = validateDirectReadMethod(methodName);\n\tif (methodValidationError) return Promise.reject(methodValidationError);\n\tif (request[requestCache]) {\n\t\tif (methodName !== \"TRACE\") return request[requestCache][method]();\n\t}\n\tconst alreadyUsedError = consumeBodyDirectOnce(request);\n\tif (alreadyUsedError) return alreadyUsedError;\n\tconst raw = readRawBodyIfAvailable(request);\n\tif (raw) {\n\t\tconst result = Promise.resolve(fromBuffer(raw, request));\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t}\n\treturn readBodyDirect(request).then((buf) => {\n\t\tconst result = fromBuffer(buf, request);\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t});\n};\nconst readRawBodyIfAvailable = (request) => {\n\tconst incoming = request[incomingKey];\n\tif (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;\n};\nconst readBodyDirect = (request) => {\n\tif (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);\n\tif (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];\n\tconst incoming = request[incomingKey];\n\tif (Readable.isDisturbed(incoming)) return rejectBodyUnusable();\n\tconst promise = new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\tlet settled = false;\n\t\tconst finish = (callback) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tcallback();\n\t\t};\n\t\tconst onData = (chunk) => {\n\t\t\tchunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\t};\n\t\tconst onEnd = () => {\n\t\t\tfinish(() => {\n\t\t\t\tconst buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);\n\t\t\t\trequest[bodyBufferKey] = buffer;\n\t\t\t\tresolve(buffer);\n\t\t\t});\n\t\t};\n\t\tconst onError = (error) => {\n\t\t\tfinish(() => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t};\n\t\tconst onClose = () => {\n\t\t\tif (incoming.readableEnded) {\n\t\t\t\tonEnd();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfinish(() => {\n\t\t\t\tif (incoming.errored) {\n\t\t\t\t\treject(incoming.errored);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst reason = request[abortReasonKey];\n\t\t\t\tif (reason !== void 0) {\n\t\t\t\t\treject(reason instanceof Error ? reason : new Error(String(reason)));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treject(/* @__PURE__ */ new Error(\"Client connection prematurely closed.\"));\n\t\t\t});\n\t\t};\n\t\tconst cleanup = () => {\n\t\t\tincoming.off(\"data\", onData);\n\t\t\tincoming.off(\"end\", onEnd);\n\t\t\tincoming.off(\"error\", onError);\n\t\t\tincoming.off(\"close\", onClose);\n\t\t\trequest[bodyReadPromiseKey] = void 0;\n\t\t};\n\t\tincoming.on(\"data\", onData);\n\t\tincoming.on(\"end\", onEnd);\n\t\tincoming.on(\"error\", onError);\n\t\tincoming.on(\"close\", onClose);\n\t\tqueueMicrotask(() => {\n\t\t\tif (settled) return;\n\t\t\tif (incoming.readableEnded) onEnd();\n\t\t\telse if (incoming.errored) onError(incoming.errored);\n\t\t\telse if (incoming.destroyed) onClose();\n\t\t});\n\t});\n\trequest[bodyReadPromiseKey] = promise;\n\treturn promise;\n};\nconst requestPrototype = {\n\tget method() {\n\t\treturn this[methodKey];\n\t},\n\tget url() {\n\t\treturn this[urlKey];\n\t},\n\tget headers() {\n\t\treturn this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n\t},\n\t[abortRequest](reason) {\n\t\tif (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;\n\t\tconst abortController = this[abortControllerKey];\n\t\tif (abortController && !abortController.signal.aborted) abortController.abort(reason);\n\t},\n\t[getAbortController]() {\n\t\tthis[abortControllerKey] ||= new AbortController();\n\t\tif (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);\n\t\treturn this[abortControllerKey];\n\t},\n\t[getRequestCache]() {\n\t\tconst abortController = this[getAbortController]();\n\t\tif (this[requestCache]) return this[requestCache];\n\t\tconst method = this.method;\n\t\tif (this[bodyConsumedDirectlyKey] && !(method === \"GET\" || method === \"HEAD\")) {\n\t\t\tthis[bodyBufferKey] = void 0;\n\t\t\tconst init = {\n\t\t\t\tmethod: method === \"TRACE\" ? \"GET\" : method,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: abortController.signal\n\t\t\t};\n\t\t\tif (method !== \"TRACE\") {\n\t\t\t\tinit.body = new ReadableStream({ start(c) {\n\t\t\t\t\tc.close();\n\t\t\t\t} });\n\t\t\t\tinit.duplex = \"half\";\n\t\t\t}\n\t\t\tconst req = new Request$1(this[urlKey], init);\n\t\t\tif (method === \"TRACE\") Object.defineProperty(req, \"method\", { get() {\n\t\t\t\treturn \"TRACE\";\n\t\t\t} });\n\t\t\treturn this[requestCache] = req;\n\t\t}\n\t\treturn this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);\n\t},\n\tget body() {\n\t\tif (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;\n\t\tconst request = this[getRequestCache]();\n\t\tif (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();\n\t\treturn request.body;\n\t},\n\tget bodyUsed() {\n\t\tif (this[bodyConsumedDirectlyKey]) return true;\n\t\tif (this[requestCache]) return this[requestCache].bodyUsed;\n\t\treturn false;\n\t}\n};\nObject.defineProperty(requestPrototype, \"signal\", { get() {\n\treturn this[getAbortController]().signal;\n} });\n[\n\t\"cache\",\n\t\"credentials\",\n\t\"destination\",\n\t\"integrity\",\n\t\"mode\",\n\t\"redirect\",\n\t\"referrer\",\n\t\"referrerPolicy\",\n\t\"keepalive\"\n].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { get() {\n\t\treturn this[getRequestCache]()[k];\n\t} });\n});\n[\"clone\", \"formData\"].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { value: function() {\n\t\tif (this[bodyConsumedDirectlyKey]) {\n\t\t\tif (k === \"clone\") throw newBodyUnusableError();\n\t\t\treturn rejectBodyUnusable();\n\t\t}\n\t\treturn this[getRequestCache]()[k]();\n\t} });\n});\nObject.defineProperty(requestPrototype, \"text\", { value: function() {\n\treturn readBodyWithFastPath(this, \"text\", (buf) => textDecoder.decode(buf));\n} });\nObject.defineProperty(requestPrototype, \"arrayBuffer\", { value: function() {\n\treturn readBodyWithFastPath(this, \"arrayBuffer\", (buf) => toArrayBuffer(buf));\n} });\nObject.defineProperty(requestPrototype, \"blob\", { value: function() {\n\treturn readBodyWithFastPath(this, \"blob\", (buf, request) => {\n\t\tconst type = contentType(request);\n\t\tconst init = type ? { headers: { \"content-type\": type } } : void 0;\n\t\treturn new Response(buf, init).blob();\n\t});\n} });\nObject.defineProperty(requestPrototype, \"json\", { value: function() {\n\tif (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\treturn this.text().then(JSON.parse);\n} });\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Request (lightweight) ${inspectFn({\n\t\tmethod: this.method,\n\t\turl: this.url,\n\t\theaders: this.headers,\n\t\tnativeRequest: this[requestCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(requestPrototype, Request$1.prototype);\nconst newRequest = (incoming, defaultHostname) => {\n\tconst req = Object.create(requestPrototype);\n\treq[incomingKey] = incoming;\n\treq[methodKey] = normalizeIncomingMethod(incoming.method);\n\tconst incomingUrl = incoming.url || \"\";\n\tif (incomingUrl[0] !== \"/\" && (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n\t\tif (incoming instanceof Http2ServerRequest) throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n\t\ttry {\n\t\t\treq[urlKey] = new URL(incomingUrl).href;\n\t\t} catch (e) {\n\t\t\tthrow new RequestError(\"Invalid absolute URL\", { cause: e });\n\t\t}\n\t\treturn req;\n\t}\n\tconst host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n\tif (!host) throw new RequestError(\"Missing host header\");\n\tlet scheme;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\tscheme = incoming.scheme;\n\t\tif (!(scheme === \"http\" || scheme === \"https\")) throw new RequestError(\"Unsupported scheme\");\n\t} else scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n\ttry {\n\t\treq[urlKey] = buildUrl(scheme, host, incomingUrl);\n\t} catch (e) {\n\t\tif (e instanceof RequestError) throw e;\n\t\telse throw new RequestError(\"Invalid URL\", { cause: e });\n\t}\n\treturn req;\n};\n\n//#endregion\n//#region src/response.ts\nconst defaultContentType = \"text/plain; charset=UTF-8\";\nconst responseCache = Symbol(\"responseCache\");\nconst getResponseCache = Symbol(\"getResponseCache\");\nconst cacheKey = Symbol(\"cache\");\nconst GlobalResponse = global.Response;\nvar Response$1 = class Response$1 {\n\t#body;\n\t#init;\n\t[getResponseCache]() {\n\t\tconst cache = this[cacheKey];\n\t\tconst liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;\n\t\tdelete this[cacheKey];\n\t\treturn this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {\n\t\t\tstatus: this.#init?.status,\n\t\t\tstatusText: this.#init?.statusText,\n\t\t\theaders: liveHeaders\n\t\t} : this.#init);\n\t}\n\tconstructor(body, init) {\n\t\tlet headers;\n\t\tthis.#body = body;\n\t\tif (init instanceof Response$1) {\n\t\t\tconst cachedGlobalResponse = init[responseCache];\n\t\t\tif (cachedGlobalResponse) {\n\t\t\t\tthis.#init = cachedGlobalResponse;\n\t\t\t\tthis[getResponseCache]();\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tthis.#init = init.#init;\n\t\t\t\theaders = new Headers(init.headers);\n\t\t\t}\n\t\t} else this.#init = init;\n\t\tif (body == null || typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [\n\t\t\tinit?.status || 200,\n\t\t\tbody ?? null,\n\t\t\theaders || init?.headers\n\t\t];\n\t}\n\tget headers() {\n\t\tconst cache = this[cacheKey];\n\t\tif (cache) {\n\t\t\tif (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { \"content-type\": defaultContentType }));\n\t\t\treturn cache[2];\n\t\t}\n\t\treturn this[getResponseCache]().headers;\n\t}\n\tget status() {\n\t\treturn this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n\t}\n\tget ok() {\n\t\tconst status = this.status;\n\t\treturn status >= 200 && status < 300;\n\t}\n};\n[\n\t\"body\",\n\t\"bodyUsed\",\n\t\"redirected\",\n\t\"statusText\",\n\t\"trailers\",\n\t\"type\",\n\t\"url\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { get() {\n\t\treturn this[getResponseCache]()[k];\n\t} });\n});\n[\n\t\"arrayBuffer\",\n\t\"blob\",\n\t\"clone\",\n\t\"formData\",\n\t\"json\",\n\t\"text\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { value: function() {\n\t\treturn this[getResponseCache]()[k]();\n\t} });\n});\nObject.defineProperty(Response$1.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Response (lightweight) ${inspectFn({\n\t\tstatus: this.status,\n\t\theaders: this.headers,\n\t\tok: this.ok,\n\t\tnativeResponse: this[responseCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(Response$1, GlobalResponse);\nObject.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);\nconst validRedirectUrl = /^https?:\\/\\/[!#-;=?-[\\]_a-z~A-Z]+$/;\nconst parseRedirectUrl = (url) => {\n\tif (url instanceof URL) return url.href;\n\tif (validRedirectUrl.test(url)) return url;\n\treturn new URL(url).href;\n};\nconst validRedirectStatuses = new Set([\n\t301,\n\t302,\n\t303,\n\t307,\n\t308\n]);\nObject.defineProperty(Response$1, \"redirect\", {\n\tvalue: function redirect(url, status = 302) {\n\t\tif (!validRedirectStatuses.has(status)) throw new RangeError(\"Invalid status code\");\n\t\treturn new Response$1(null, {\n\t\t\tstatus,\n\t\t\theaders: { location: parseRedirectUrl(url) }\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\nObject.defineProperty(Response$1, \"json\", {\n\tvalue: function json(data, init) {\n\t\tconst body = JSON.stringify(data);\n\t\tif (body === void 0) throw new TypeError(\"The data is not JSON serializable\");\n\t\tconst initHeaders = init?.headers;\n\t\tlet headers;\n\t\tif (initHeaders) {\n\t\t\theaders = new Headers(initHeaders);\n\t\t\tif (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n\t\t} else headers = { \"content-type\": \"application/json\" };\n\t\treturn new Response$1(body, {\n\t\t\tstatus: init?.status ?? 200,\n\t\t\tstatusText: init?.statusText,\n\t\t\theaders\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\n\n//#endregion\n//#region src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n\treturn Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n\tconst cancel = (error) => {\n\t\treader.cancel(error).catch(() => {});\n\t};\n\twritable.on(\"close\", cancel);\n\twritable.on(\"error\", cancel);\n\t(currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n\treturn reader.closed.finally(() => {\n\t\twritable.off(\"close\", cancel);\n\t\twritable.off(\"error\", cancel);\n\t});\n\tfunction handleStreamError(error) {\n\t\tif (error) writable.destroy(error);\n\t}\n\tfunction onDrain() {\n\t\treader.read().then(flow, handleStreamError);\n\t}\n\tfunction flow({ done, value }) {\n\t\ttry {\n\t\t\tif (done) writable.end();\n\t\t\telse if (!writable.write(value)) writable.once(\"drain\", onDrain);\n\t\t\telse return reader.read().then(flow, handleStreamError);\n\t\t} catch (e) {\n\t\t\thandleStreamError(e);\n\t\t}\n\t}\n}\nfunction writeFromReadableStream(stream, writable) {\n\tif (stream.locked) throw new TypeError(\"ReadableStream is locked.\");\n\telse if (writable.destroyed) return;\n\treturn writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nconst buildOutgoingHttpHeaders = (headers, defaultContentType) => {\n\tconst res = {};\n\tif (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);\n\tif (headers.has(\"set-cookie\")) {\n\t\tconst cookies = [];\n\t\tfor (const [k, v] of headers) if (k === \"set-cookie\") cookies.push(v);\n\t\telse res[k] = v;\n\t\tif (cookies.length > 0) res[\"set-cookie\"] = cookies;\n\t} else for (const [k, v] of headers) res[k] = v;\n\tif (defaultContentType) res[\"content-type\"] ??= defaultContentType;\n\treturn res;\n};\n\n//#endregion\n//#region src/listener.ts\nconst outgoingEnded = Symbol(\"outgoingEnded\");\nconst incomingDraining = Symbol(\"incomingDraining\");\nconst DRAIN_TIMEOUT_MS = 500;\nconst MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nconst drainIncoming = (incoming) => {\n\tconst incomingWithDrainState = incoming;\n\tif (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;\n\tincomingWithDrainState[incomingDraining] = true;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\ttry {\n\t\t\tincoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tlet bytesRead = 0;\n\tconst cleanup = () => {\n\t\tclearTimeout(timer);\n\t\tincoming.off(\"data\", onData);\n\t\tincoming.off(\"end\", cleanup);\n\t\tincoming.off(\"error\", cleanup);\n\t};\n\tconst forceClose = () => {\n\t\tcleanup();\n\t\tconst socket = incoming.socket;\n\t\tif (socket && !socket.destroyed) socket.destroySoon();\n\t};\n\tconst timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n\ttimer.unref?.();\n\tconst onData = (chunk) => {\n\t\tbytesRead += chunk.length;\n\t\tif (bytesRead > MAX_DRAIN_BYTES) forceClose();\n\t};\n\tincoming.on(\"data\", onData);\n\tincoming.on(\"end\", cleanup);\n\tincoming.on(\"error\", cleanup);\n\tincoming.resume();\n};\nconst makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {\n\tif (incoming.errored) req[abortRequest](incoming.errored.toString());\n\telse if (!outgoing.writableFinished) req[abortRequest](\"Client connection prematurely closed.\");\n\tif (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {\n\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\tdrainIncoming(incoming);\n\t\t});\n\t});\n};\nconst isImmediateCacheableResponse = (res) => {\n\tif (!(cacheKey in res)) return false;\n\tconst body = res[cacheKey][1];\n\treturn body === null || typeof body === \"string\" || body instanceof Uint8Array;\n};\nconst handleRequestError = () => new Response(null, { status: 400 });\nconst handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500 });\nconst handleResponseError = (e, outgoing) => {\n\tconst err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n\tif (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") console.info(\"The user aborted a request.\");\n\telse {\n\t\tconsole.error(e);\n\t\tif (!outgoing.headersSent) outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n\t\toutgoing.end(`Error: ${err.message}`);\n\t\toutgoing.destroy(err);\n\t}\n};\nconst flushHeaders = (outgoing) => {\n\tif (\"flushHeaders\" in outgoing && outgoing.writable) outgoing.flushHeaders();\n};\nconst responseViaCache = async (res, outgoing) => {\n\tlet [status, body, header] = res[cacheKey];\n\tif (!header) {\n\t\tif (body === null) {\n\t\t\toutgoing.writeHead(status);\n\t\t\toutgoing.end();\n\t\t} else if (typeof body === \"string\") {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": Buffer.byteLength(body)\n\t\t\t});\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Uint8Array) {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": body.byteLength\n\t\t\t});\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Blob) {\n\t\t\toutgoing.writeHead(status, {\n\t\t\t\t\"Content-Type\": defaultContentType,\n\t\t\t\t\"Content-Length\": body.size\n\t\t\t});\n\t\t\toutgoing.end(new Uint8Array(await body.arrayBuffer()));\n\t\t} else {\n\t\t\toutgoing.writeHead(status, { \"Content-Type\": defaultContentType });\n\t\t\tflushHeaders(outgoing);\n\t\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t\t}\n\t\toutgoing[outgoingEnded]?.();\n\t\treturn;\n\t}\n\tlet hasContentLength = false;\n\tif (header instanceof Headers) {\n\t\thasContentLength = header.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);\n\t} else if (Array.isArray(header)) {\n\t\tconst headerObj = new Headers(header);\n\t\thasContentLength = headerObj.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);\n\t} else for (const key in header) if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n\t\thasContentLength = true;\n\t\tbreak;\n\t}\n\tif (!hasContentLength) {\n\t\tif (typeof body === \"string\") header[\"Content-Length\"] = Buffer.byteLength(body);\n\t\telse if (body instanceof Uint8Array) header[\"Content-Length\"] = body.byteLength;\n\t\telse if (body instanceof Blob) header[\"Content-Length\"] = body.size;\n\t}\n\toutgoing.writeHead(status, header);\n\tif (body == null) outgoing.end();\n\telse if (typeof body === \"string\" || body instanceof Uint8Array) outgoing.end(body);\n\telse if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));\n\telse {\n\t\tflushHeaders(outgoing);\n\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst isPromise = (res) => typeof res.then === \"function\";\nconst responseViaResponseObject = async (res, outgoing, options = {}) => {\n\tif (isPromise(res)) if (options.errorHandler) try {\n\t\tres = await res;\n\t} catch (err) {\n\t\tconst errRes = await options.errorHandler(err);\n\t\tif (!errRes) return;\n\t\tres = errRes;\n\t}\n\telse res = await res.catch(handleFetchError);\n\tif (cacheKey in res) return responseViaCache(res, outgoing);\n\tconst resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);\n\tif (res.body) {\n\t\tconst reader = res.body.getReader();\n\t\tconst values = [];\n\t\tlet done = false;\n\t\tlet currentReadPromise = void 0;\n\t\tif (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n\t\t\tlet maxReadCount = 2;\n\t\t\tfor (let i = 0; i < maxReadCount; i++) {\n\t\t\t\tcurrentReadPromise ||= reader.read();\n\t\t\t\tconst chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t\tdone = true;\n\t\t\t\t});\n\t\t\t\tif (!chunk) {\n\t\t\t\t\tif (i === 1) {\n\t\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve));\n\t\t\t\t\t\tmaxReadCount = 3;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcurrentReadPromise = void 0;\n\t\t\t\tif (chunk.value) values.push(chunk.value);\n\t\t\t\tif (chunk.done) {\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (done && !(\"content-length\" in resHeaderRecord)) resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n\t\t}\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\tvalues.forEach((value) => {\n\t\t\toutgoing.write(value);\n\t\t});\n\t\tif (done) outgoing.end();\n\t\telse {\n\t\t\tif (values.length === 0) flushHeaders(outgoing);\n\t\t\tawait writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n\t\t}\n\t} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\toutgoing.end();\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst getRequestListener = (fetchCallback, options = {}) => {\n\tconst autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n\tif (options.overrideGlobalObjects !== false && global.Request !== Request$1) {\n\t\tObject.defineProperty(global, \"Request\", { value: Request$1 });\n\t\tObject.defineProperty(global, \"Response\", { value: Response$1 });\n\t}\n\treturn async (incoming, outgoing) => {\n\t\tlet res, req;\n\t\tlet needsBodyCleanup = false;\n\t\tlet closeHandlerAttached = false;\n\t\tconst ensureCloseHandler = () => {\n\t\t\tif (!req || closeHandlerAttached) return;\n\t\t\tcloseHandlerAttached = true;\n\t\t\toutgoing.on(\"close\", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));\n\t\t};\n\t\ttry {\n\t\t\treq = newRequest(incoming, options.hostname);\n\t\t\tneedsBodyCleanup = autoCleanupIncoming && !(incoming.method === \"GET\" || incoming.method === \"HEAD\");\n\t\t\tif (needsBodyCleanup) {\n\t\t\t\tincoming[wrapBodyStream] = true;\n\t\t\t\tif (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {\n\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\t\tincoming.destroy();\n\t\t\t\t\t\t\toutgoing.destroy();\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}\n\t\t\tres = fetchCallback(req, {\n\t\t\t\tincoming,\n\t\t\t\toutgoing\n\t\t\t});\n\t\t\tif (!isPromise(res) && isImmediateCacheableResponse(res)) {\n\t\t\t\tif (needsBodyCleanup && !incoming.readableEnded) outgoing.once(\"finish\", () => {\n\t\t\t\t\tif (!incoming.readableEnded) drainIncoming(incoming);\n\t\t\t\t});\n\t\t\t\treturn responseViaCache(res, outgoing);\n\t\t\t}\n\t\t\tensureCloseHandler();\n\t\t} catch (e) {\n\t\t\tif (!res) if (options.errorHandler) {\n\t\t\t\tensureCloseHandler();\n\t\t\t\tres = await options.errorHandler(req ? e : toRequestError(e));\n\t\t\t\tif (!res) return;\n\t\t\t} else if (!req) res = handleRequestError();\n\t\t\telse res = handleFetchError(e);\n\t\t\telse return handleResponseError(e, outgoing);\n\t\t}\n\t\ttry {\n\t\t\treturn await responseViaResponseObject(res, outgoing, options);\n\t\t} catch (e) {\n\t\t\treturn handleResponseError(e, outgoing);\n\t\t}\n\t};\n};\n\n//#endregion\n//#region src/websocket.ts\n/**\n* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n*/\nconst CloseEvent = globalThis.CloseEvent ?? class extends Event {\n\t#eventInitDict;\n\tconstructor(type, eventInitDict = {}) {\n\t\tsuper(type, eventInitDict);\n\t\tthis.#eventInitDict = eventInitDict;\n\t}\n\tget wasClean() {\n\t\treturn this.#eventInitDict.wasClean ?? false;\n\t}\n\tget code() {\n\t\treturn this.#eventInitDict.code ?? 0;\n\t}\n\tget reason() {\n\t\treturn this.#eventInitDict.reason ?? \"\";\n\t}\n};\nconst generateConnectionSymbol = () => Symbol(\"connection\");\nconst CONNECTION_SYMBOL_KEY = Symbol(\"CONNECTION_SYMBOL_KEY\");\nconst WAIT_FOR_WEBSOCKET_SYMBOL = Symbol(\"WAIT_FOR_WEBSOCKET_SYMBOL\");\nconst responseHeadersToSkip = new Set([\n\t\"connection\",\n\t\"content-length\",\n\t\"keep-alive\",\n\t\"proxy-authenticate\",\n\t\"proxy-authorization\",\n\t\"te\",\n\t\"trailer\",\n\t\"transfer-encoding\",\n\t\"upgrade\",\n\t\"sec-websocket-accept\",\n\t\"sec-websocket-extensions\",\n\t\"sec-websocket-protocol\"\n]);\nconst appendResponseHeaders = (headers, responseHeaders) => {\n\tif (!responseHeaders) return;\n\tresponseHeaders.forEach((value, key) => {\n\t\tif (responseHeadersToSkip.has(key.toLowerCase())) return;\n\t\theaders.push(`${key}: ${value}`);\n\t});\n};\nconst rejectUpgradeRequest = (socket, status, responseHeaders) => {\n\tconst responseLines = [\"Connection: close\", \"Content-Length: 0\"];\n\tappendResponseHeaders(responseLines, responseHeaders);\n\tsocket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? \"\"}\\r\\n${responseLines.join(\"\\r\\n\")}\\r\\n\\r\n`);\n};\nconst createUpgradeRequest = (request) => {\n\tconst protocol = request.socket.encrypted ? \"https\" : \"http\";\n\tconst url = new URL(request.url ?? \"/\", `${protocol}://${request.headers.host ?? \"localhost\"}`);\n\tconst headers = new Headers();\n\tfor (const key in request.headers) {\n\t\tconst value = request.headers[key];\n\t\tif (!value) continue;\n\t\theaders.append(key, Array.isArray(value) ? value[0] : value);\n\t}\n\treturn new Request(url, { headers });\n};\nconst setupWebSocket = (options) => {\n\tconst { server, fetchCallback, wss } = options;\n\tconst waiterMap = /* @__PURE__ */ new Map();\n\twss.on(\"connection\", (ws, request) => {\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (waiter) {\n\t\t\twaiter.resolve(ws);\n\t\t\twaiterMap.delete(request);\n\t\t}\n\t});\n\tconst waitForWebSocket = (request, connectionSymbol) => {\n\t\treturn new Promise((resolve) => {\n\t\t\twaiterMap.set(request, {\n\t\t\t\tresolve,\n\t\t\t\tconnectionSymbol\n\t\t\t});\n\t\t});\n\t};\n\tserver.on(\"upgrade\", async (request, socket, head) => {\n\t\tif (request.headers.upgrade?.toLowerCase() !== \"websocket\") return;\n\t\tconst env = {\n\t\t\tincoming: request,\n\t\t\toutgoing: void 0,\n\t\t\twss,\n\t\t\t[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket\n\t\t};\n\t\tlet status = 400;\n\t\tlet responseHeaders;\n\t\ttry {\n\t\t\tconst response = await fetchCallback(createUpgradeRequest(request), env);\n\t\t\tif (response instanceof Response) {\n\t\t\t\tstatus = response.status;\n\t\t\t\tresponseHeaders = response.headers;\n\t\t\t}\n\t\t} catch {\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, 500);\n\t\t\treturn;\n\t\t}\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {\n\t\t\twaiterMap.delete(request);\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, status, responseHeaders);\n\t\t\treturn;\n\t\t}\n\t\tconst addResponseHeaders = (headers) => {\n\t\t\tappendResponseHeaders(headers, responseHeaders);\n\t\t};\n\t\twss.on(\"headers\", addResponseHeaders);\n\t\ttry {\n\t\t\twss.handleUpgrade(request, socket, head, (ws) => {\n\t\t\t\twss.emit(\"connection\", ws, request);\n\t\t\t});\n\t\t} finally {\n\t\t\twss.off(\"headers\", addResponseHeaders);\n\t\t}\n\t});\n\tserver.on(\"close\", () => {\n\t\twss.close();\n\t});\n};\nconst upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {\n\tif (c.req.header(\"upgrade\")?.toLowerCase() !== \"websocket\") return;\n\tconst env = c.env;\n\tconst waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];\n\tif (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });\n\tconst connectionSymbol = generateConnectionSymbol();\n\tenv[CONNECTION_SYMBOL_KEY] = connectionSymbol;\n\t(async () => {\n\t\tconst ws = await waitForWebSocket(env.incoming, connectionSymbol);\n\t\tconst messagesReceivedInStarting = [];\n\t\tconst bufferMessage = (data, isBinary) => {\n\t\t\tmessagesReceivedInStarting.push([data, isBinary]);\n\t\t};\n\t\tws.on(\"message\", bufferMessage);\n\t\tconst ctx = {\n\t\t\tbinaryType: \"arraybuffer\",\n\t\t\tclose(code, reason) {\n\t\t\t\tws.close(code, reason);\n\t\t\t},\n\t\t\tprotocol: ws.protocol,\n\t\t\traw: ws,\n\t\t\tget readyState() {\n\t\t\t\treturn ws.readyState;\n\t\t\t},\n\t\t\tsend(source, opts) {\n\t\t\t\tws.send(source, { compress: opts?.compress });\n\t\t\t},\n\t\t\turl: new URL(c.req.url)\n\t\t};\n\t\ttry {\n\t\t\tevents?.onOpen?.(new Event(\"open\"), ctx);\n\t\t} catch (e) {\n\t\t\t(options?.onError ?? console.error)(e);\n\t\t}\n\t\tconst handleMessage = (data, isBinary) => {\n\t\t\tconst datas = Array.isArray(data) ? data : [data];\n\t\t\tfor (const data of datas) try {\n\t\t\t\tevents?.onMessage?.(new MessageEvent(\"message\", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === \"string\" ? data : Buffer.from(data).toString(\"utf-8\") }), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t};\n\t\tws.off(\"message\", bufferMessage);\n\t\tfor (const message of messagesReceivedInStarting) handleMessage(...message);\n\t\tws.on(\"message\", (data, isBinary) => {\n\t\t\thandleMessage(data, isBinary);\n\t\t});\n\t\tws.on(\"close\", (code, reason) => {\n\t\t\ttry {\n\t\t\t\tevents?.onClose?.(new CloseEvent(\"close\", {\n\t\t\t\t\tcode,\n\t\t\t\t\treason: reason.toString()\n\t\t\t\t}), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t\tws.on(\"error\", (error) => {\n\t\t\ttry {\n\t\t\t\tevents?.onError?.(new ErrorEvent(\"error\", { error }), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t})();\n\treturn new Response();\n});\n\n//#endregion\n//#region src/server.ts\nconst createAdaptorServer = (options) => {\n\tconst fetchCallback = options.fetch;\n\tconst requestListener = getRequestListener(fetchCallback, {\n\t\thostname: options.hostname,\n\t\toverrideGlobalObjects: options.overrideGlobalObjects,\n\t\tautoCleanupIncoming: options.autoCleanupIncoming\n\t});\n\tconst server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);\n\tif (options.websocket && options.websocket.server) {\n\t\tif (options.websocket.server.options.noServer !== true) throw new Error(\"WebSocket server must be created with { noServer: true } option\");\n\t\tsetupWebSocket({\n\t\t\tserver,\n\t\t\tfetchCallback,\n\t\t\twss: options.websocket.server\n\t\t});\n\t}\n\treturn server;\n};\nconst serve = (options, listeningListener) => {\n\tconst server = createAdaptorServer(options);\n\tserver.listen(options?.port ?? 3e3, options.hostname, () => {\n\t\tconst serverInfo = server.address();\n\t\tlisteningListener && listeningListener(serverInfo);\n\t});\n\treturn server;\n};\n\n//#endregion\nexport { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };","import type { HttpBindings } from \"@hono/node-server\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { errorEnvelope } from \"@baerly/server/http\";\n\n/**\n * Body-cap enforcement for Node-hosted requests. Replaces the\n * pre-pivot `bodyCapMiddleware` that attached `incoming.on(\"data\",\n * ...)` — that listener raced with `@hono/node-server`'s own body\n * reader and dropped the first chunks of every POST. Wrapping\n * `req.body` with a counting `TransformStream` puts the cap in the\n * same reader chain as the kernel router's `c.req.arrayBuffer()`\n * consumer, so there is no race.\n *\n * Two cap-trip paths, both drain the upstream `IncomingMessage`\n * (`resume()`) so the client's body write completes and the 413\n * envelope reaches it cleanly (without drain, closing the response\n * mid-upload surfaces client-side as \"socket hang up\"):\n *\n * - Content-Length fast path → returns a 413 `Response` directly.\n * - Chunked slow path → wraps `req.body` with a counting\n * `TransformStream` that errors with `BaerlyError{code:\n * \"PayloadTooLarge\"}` when the running count exceeds `max`.\n * The kernel router's `readJsonBody` recognises the\n * `BaerlyError` and re-throws it verbatim; `mapToResponse`\n * surfaces the same 413 envelope as the fast path.\n *\n * Returns the original `Request` unchanged for `GET`/`HEAD`/\n * `OPTIONS` (no body to cap) and for hosts that don't expose an\n * `IncomingMessage` on the Hono context's env binding — defence-in-\n * depth lives in the kernel router's `readJsonBody`.\n */\nexport function applyBodyCap(req: Request, env: unknown, max: number): Request | Response {\n if (req.method === \"GET\" || req.method === \"HEAD\" || req.method === \"OPTIONS\") {\n return req;\n }\n const incoming = (env as HttpBindings | undefined)?.incoming;\n if (incoming === undefined) {\n return req;\n }\n\n const lenHeader = req.headers.get(\"content-length\");\n if (lenHeader !== null) {\n const parsed = Number.parseInt(lenHeader, 10);\n if (Number.isFinite(parsed) && parsed > max) {\n incoming.resume();\n return cap413(max);\n }\n }\n\n const body = req.body;\n if (body === null) {\n return req;\n }\n\n let count = 0;\n let tripped = false;\n const counter = new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n if (tripped) {\n return;\n }\n count += chunk.byteLength;\n if (count > max) {\n tripped = true;\n incoming.resume();\n controller.error(new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${max} bytes`));\n return;\n }\n controller.enqueue(chunk);\n },\n });\n\n return new Request(req.url, {\n method: req.method,\n headers: req.headers,\n body: body.pipeThrough(counter),\n // `duplex` is required by Node/undici for streaming request bodies; the\n // standard DOM `RequestInit` doesn't surface it yet.\n duplex: \"half\",\n } as RequestInit & { duplex: \"half\" });\n}\n\nfunction cap413(max: number): Response {\n return new Response(\n JSON.stringify(errorEnvelope(\"PayloadTooLarge\", `Body exceeds ${max} bytes`)),\n {\n status: 413,\n headers: { \"content-type\": \"application/json\" },\n },\n );\n}\n","import { type DevLandingOptions, renderDevLanding } from \"@baerly/dev\";\nimport type { MiddlewareHandler } from \"hono\";\n\ninterface Options {\n readonly dev: DevLandingOptions;\n}\n\n/**\n * Opt-in dev landing-page short-circuit. Serves `GET /` with a\n * human-readable HTML page that links to the configured UI URL, and\n * `GET /favicon.ico` with 204 No Content. Bypasses verifier and\n * observability so it doesn't flood logs in dev.\n *\n * Other methods and other paths fall through to the cascade. Mounted\n * by {@link createApp} (in `app.ts`) ahead of `staticAssetsMiddleware`\n * so the dev short-circuit wins over any on-disk `index.html` /\n * `favicon.ico` that might live in `webRoot`.\n *\n * Mirrors the imperative dev-landing block in\n * `packages/adapter-node/src/server.ts` (which the hand-rolled\n * `handle()` bridge still uses until the bridge cutover).\n */\nexport function devLandingMiddleware(opts: Options): MiddlewareHandler {\n return async (c, next) => {\n if (c.req.method !== \"GET\") {\n return next();\n }\n const path = new URL(c.req.url).pathname;\n if (path === \"/\") {\n const body = renderDevLanding(opts.dev);\n return new Response(body, {\n status: 200,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n // Buffer.byteLength (not body.length) — the rendered HTML\n // may contain multi-byte UTF-8 characters.\n \"content-length\": String(Buffer.byteLength(body)),\n },\n });\n }\n if (path === \"/favicon.ico\") {\n return new Response(null, { status: 204 });\n }\n return next();\n };\n}\n","import { createReadStream, type Stats } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport {\n extname,\n relative as relativePath,\n resolve as resolvePath,\n sep as pathSep,\n} from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport type { ReadableStream as NodeReadableStream } from \"node:stream/web\";\nimport type { MiddlewareHandler } from \"hono\";\n\n/**\n * Map a file extension to its `Content-Type`. The set is deliberately\n * small — every entry corresponds to something Vite or a typical SPA\n * pipeline actually emits. Unknown extensions fall back to\n * `application/octet-stream`, which keeps the browser from sniffing\n * untrusted bytes as HTML.\n */\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".ico\": \"image/x-icon\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".txt\": \"text/plain; charset=utf-8\",\n \".map\": \"application/json; charset=utf-8\",\n};\n\ninterface Options {\n readonly webRoot: string;\n}\n\n/**\n * Serve files from `webRoot` for GET/HEAD requests that miss `/v1/*`.\n *\n * HTML navigation (`Accept: text/html`) that misses an on-disk file\n * falls back to `<webRoot>/index.html` (SPA shell). Non-HTML misses\n * pass through `next()` so the cascade emits its 404 envelope.\n *\n * Path resolution rejects `..` segments and absolute paths so the\n * middleware can't escape `webRoot`. Pure `node:fs` + `node:path` —\n * no new dependency.\n *\n * The response body is built as\n * `new Response(Readable.toWeb(createReadStream(...)))`, keeping the\n * middleware Fetch-shaped so it composes cleanly with other Hono\n * middleware. The actual byte pump runs through\n * `@hono/node-server`'s response writer, which handles backpressure +\n * client-disconnect cleanly.\n *\n * Mirrors the imperative `serveStaticAsset` in\n * `packages/adapter-node/src/server.ts` (which the hand-rolled\n * `handle()` bridge still uses until T04 cuts over).\n */\nexport function staticAssetsMiddleware(opts: Options): MiddlewareHandler {\n return async (c, next) => {\n const method = c.req.method;\n if (method !== \"GET\" && method !== \"HEAD\") {\n return next();\n }\n const path = new URL(c.req.url).pathname;\n if (path.startsWith(\"/v1/\")) {\n return next();\n }\n\n const resolved = resolveUnderWebRoot(path, opts.webRoot);\n if (resolved === null) {\n // Traversal / absolute path / NUL byte / malformed encoding.\n // Fall through to the cascade.\n return next();\n }\n\n const resolution = await resolveStaticTarget(resolved, opts.webRoot, c.req.header(\"accept\"));\n if (resolution === null) {\n return next();\n }\n const { target, stats } = resolution;\n\n const ext = extname(target).toLowerCase();\n const contentType = MIME_TYPES[ext] ?? \"application/octet-stream\";\n // Vite emits long-lived hashed bundles under `assets/`; everything\n // else (including `index.html`, which is fetched on every nav)\n // wants a fresh copy.\n const relForCache = relativePath(opts.webRoot, target).split(pathSep).join(\"/\");\n const cacheControl =\n relForCache.startsWith(\"assets/\") && target !== resolvePath(opts.webRoot, \"index.html\")\n ? \"public, max-age=3600\"\n : \"no-cache\";\n\n const headers: Record<string, string> = {\n \"content-type\": contentType,\n \"content-length\": String(stats.size),\n \"cache-control\": cacheControl,\n };\n\n if (method === \"HEAD\") {\n return new Response(null, { status: 200, headers });\n }\n\n const nodeWeb = Readable.toWeb(\n createReadStream(target),\n ) as unknown as NodeReadableStream<Uint8Array>;\n return new Response(nodeWeb as unknown as ReadableStream<Uint8Array>, {\n status: 200,\n headers,\n });\n };\n}\n\n/**\n * Resolve a request path under `webRoot` without allowing `..` escape\n * or absolute-segment hijacking. Returns the resolved absolute path on\n * success, or `null` when the request should fall through (traversal\n * attempt, NUL byte, malformed URL encoding).\n */\nfunction resolveUnderWebRoot(reqPath: string, webRoot: string): string | null {\n let relative = reqPath;\n if (relative === \"\" || relative === \"/\") {\n relative = \"/index.html\";\n } else if (relative.endsWith(\"/\")) {\n relative = `${relative}index.html`;\n }\n\n // Reject NUL bytes immediately — no filesystem call should ever see\n // one.\n if (relative.includes(\"\\0\")) {\n return null;\n }\n\n // Walk the segments, URL-decoding each one in isolation. Decoding\n // the whole path string would let `%2F` (`/`) sneak through as a\n // segment separator that bypasses the per-segment `..` check.\n const segments: string[] = [];\n for (const raw of relative.split(\"/\")) {\n if (raw === \"\") {\n continue;\n }\n let decoded: string;\n try {\n decoded = decodeURIComponent(raw);\n } catch {\n return null;\n }\n if (decoded === \"\" || decoded === \".\") {\n continue;\n }\n if (decoded === \"..\") {\n return null;\n }\n if (decoded.includes(\"\\0\")) {\n return null;\n }\n if (decoded.includes(\"/\") || decoded.includes(\"\\\\\")) {\n return null;\n }\n segments.push(decoded);\n }\n\n const resolved = resolvePath(webRoot, ...segments);\n const rel = relativePath(webRoot, resolved);\n // `path.relative` returns `\"\"` when `resolved === webRoot` (the\n // directory itself) and a `..`-prefixed path when `resolved` escapes\n // `webRoot`. Both are rejected.\n if (rel === \"\" || rel.startsWith(\"..\") || rel.startsWith(`..${pathSep}`)) {\n return null;\n }\n return resolved;\n}\n\n/**\n * Determine whether the request should fall back to `index.html` on a\n * filesystem miss. Browsers send `Accept: text/html,...` for SPA\n * navigations; programmatic `fetch()` calls for missing JSON / image\n * assets do not, and they get the kernel's 404 envelope instead.\n */\nfunction wantsHtmlFallback(accept: string | undefined): boolean {\n if (typeof accept !== \"string\") {\n return false;\n }\n return accept.includes(\"text/html\");\n}\n\nasync function resolveStaticTarget(\n resolved: string,\n webRoot: string,\n accept: string | undefined,\n): Promise<{ target: string; stats: Stats } | null> {\n const primary = await statFile(resolved);\n if (primary !== null) {\n return { target: resolved, stats: primary };\n }\n if (!wantsHtmlFallback(accept)) {\n return null;\n }\n const indexPath = resolvePath(webRoot, \"index.html\");\n const fallback = await statFile(indexPath);\n if (fallback === null) {\n return null;\n }\n return { target: indexPath, stats: fallback };\n}\n\n/**\n * `fs.stat` that returns `null` for the missing-file cases that this\n * handler treats as a fall-through (ENOENT / ENOTDIR / non-file).\n * Other errors (EACCES, EIO, ...) propagate.\n */\nasync function statFile(target: string): Promise<Stats | null> {\n try {\n const stats = await stat(target);\n return stats.isFile() ? stats : null;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\" || code === \"ENOTDIR\") {\n return null;\n }\n throw error;\n }\n}\n","/**\n * Pretty console sink for the `baerlyDev()` Vite-mount boot path.\n *\n * Lives in `@baerly/adapter-node` so the `@baerly/server` kernel\n * doesn't pull `picocolors` or the canonical-line column renderer\n * into its bundle. The kernel's `configureObservability` accepts any\n * `Sink` function directly; callers in TTY-friendly environments\n * (the Node adapter's `baerlyNode`) constructs this sink\n * and passes it in.\n */\n\nimport { type LogRecord, type Sink } from \"@logtape/logtape\";\nimport { createColors } from \"picocolors\";\n\n/**\n * Metric keys the pretty sink reads off the canonical-line record.\n * These names match `RequestScopedMetricsRecorder.summarize()` output\n * in `packages/server/src/observability/recorder.ts`. If the recorder\n * renames a key, update both sides here.\n */\nconst CANONICAL_KEYS = {\n classA: \"db.storage.class_a_ops_total\",\n classB: \"db.storage.class_b_ops_total\",\n wamp: \"db.write.class_a_ops_per_logical_write_sum\",\n put412: \"db.r2.put.412_total\",\n put429: \"db.r2.put.429_total\",\n cacheStatus: \"cache_status\",\n} as const;\n\n/**\n * Fixed-width column sizes for the pretty sink's HTTP line.\n * Local to the renderer — these are presentation defaults, not\n * protocol invariants, so they don't belong in `@baerly/protocol`.\n */\nconst METHOD_W = 6;\nconst PATH_W = 28;\n\nconst pickProp = (props: Record<string, unknown>, key: string): unknown =>\n Object.prototype.hasOwnProperty.call(props, key) ? props[key] : undefined;\n\nconst numProp = (props: Record<string, unknown>, key: string): number | undefined => {\n const v = pickProp(props, key);\n return typeof v === \"number\" ? v : undefined;\n};\n\ntype PicoColors = ReturnType<typeof createColors>;\n\n// Color the status column by class: 5xx red, 4xx yellow, 3xx cyan,\n// 2xx/unset dim. Extracted so the canonical-line renderer doesn't carry\n// a 5-level nested ternary.\nconst colorStatus = (\n statusStr: string,\n status: number | undefined,\n plain: boolean,\n pc: PicoColors,\n): string => {\n if (plain || status === undefined) {\n return statusStr;\n }\n if (status >= 500) {\n return pc.red(statusStr);\n }\n if (status >= 400) {\n return pc.yellow(statusStr);\n }\n if (status >= 300) {\n return pc.cyan(statusStr);\n }\n return pc.dim(statusStr);\n};\n\nconst renderCanonical = (record: LogRecord, pc: PicoColors, plain: boolean): string => {\n const props = record.properties as Record<string, unknown>;\n const ts = new Date(record.timestamp).toISOString().slice(11, 19);\n const reqId = String(pickProp(props, \"request_id\") ?? \"\").slice(0, 8);\n const duration = numProp(props, \"duration_ms\") ?? 0;\n const durationStr = `${Math.round(duration)}ms`.padStart(5);\n\n const status = numProp(props, \"status\");\n const method =\n typeof pickProp(props, \"method\") === \"string\" ? String(pickProp(props, \"method\")) : \"\";\n const path = typeof pickProp(props, \"path\") === \"string\" ? String(pickProp(props, \"path\")) : \"\";\n\n const m = method.padEnd(METHOD_W);\n const p = path.length > PATH_W ? `${path.slice(0, PATH_W - 1)}…` : path.padEnd(PATH_W);\n const statusStr = status === undefined ? \" \" : String(status);\n const coloredStatus = colorStatus(statusStr, status, plain, pc);\n const prefix = `${m}${p} ${coloredStatus} ${durationStr}`;\n\n const tail: string[] = [];\n if (reqId) {\n tail.push(`req=${reqId}`);\n }\n const classA = numProp(props, CANONICAL_KEYS.classA);\n const classB = numProp(props, CANONICAL_KEYS.classB);\n if (classA !== undefined) {\n tail.push(`class_a=${classA}`);\n }\n if (classB !== undefined) {\n tail.push(`class_b=${classB}`);\n }\n const wamp = numProp(props, CANONICAL_KEYS.wamp);\n if (wamp !== undefined) {\n tail.push(`wamp=${wamp}`);\n }\n const c412 = numProp(props, CANONICAL_KEYS.put412);\n if (c412 !== undefined && c412 > 0) {\n tail.push(`412=${c412}`);\n }\n const c429 = numProp(props, CANONICAL_KEYS.put429);\n if (c429 !== undefined && c429 > 0) {\n tail.push(`429=${c429}`);\n }\n const cacheStatus = pickProp(props, CANONICAL_KEYS.cacheStatus);\n if (typeof cacheStatus === \"string\") {\n tail.push(`cache=${cacheStatus}`);\n }\n if (status !== undefined && status >= 400) {\n const outcome = pickProp(props, \"outcome\");\n if (typeof outcome === \"string\") {\n tail.push(`outcome=${outcome}`);\n }\n }\n\n const tailStr = tail.length ? ` ${tail.join(\" \")}` : \"\";\n const tsCol = plain ? `${ts} ` : `${pc.dim(ts)} `;\n return `${tsCol}${prefix}${tailStr}`;\n};\n\nconst isCanonicalRecord = (record: LogRecord): boolean =>\n record.message.length === 1 && record.message[0] === \"canonical\";\n\nconst isPlainEnv = (): boolean => {\n const proc = (\n globalThis as {\n process?: {\n stdout?: { isTTY?: boolean };\n env?: Record<string, string | undefined>;\n };\n }\n ).process;\n return proc?.stdout?.isTTY !== true || proc?.env?.[\"CI\"] !== undefined;\n};\n\n/**\n * Built-in pretty sink. Renders canonical-line records (the\n * single-emit/unit-of-work records produced by `flushCanonicalLine`\n * in `@baerly/server/observability`) in a column-aligned cost-aware\n * format intended for local dev; falls back to a generic\n * `<ts> <LEVEL> <category> <msg> <jsonProps>` layout for every\n * other record (warn-line `verifier_rejected`, debug storage\n * emits, etc.).\n *\n * Color is enabled when stderr is a TTY and `CI` is unset. Under\n * vitest, stderr is non-TTY so color is off — tests can assert\n * substring matches without stripping ANSI escapes.\n */\nexport const prettyConsoleSink = (): Sink => {\n const plain = isPlainEnv();\n const pc = createColors(!plain);\n return (record) => {\n if (isCanonicalRecord(record)) {\n // eslint-disable-next-line no-console -- intentional sink target\n console.log(renderCanonical(record, pc, plain));\n return;\n }\n const ts = new Date(record.timestamp).toISOString();\n const cat = record.category.join(\".\");\n const msg = record.message.map((m) => (typeof m === \"string\" ? m : JSON.stringify(m))).join(\"\");\n const props = Object.keys(record.properties).length\n ? ` ${JSON.stringify(record.properties)}`\n : \"\";\n // eslint-disable-next-line no-console -- intentional sink target\n console.log(`${ts} ${record.level.toUpperCase()} ${cat} ${msg}${props}`);\n };\n};\n","import {\n type BaerlyConfig,\n MAINTENANCE_PROFILE_NODE,\n type Storage,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { Db } from \"@baerly/server\";\nimport { createRouter, mapError } from \"@baerly/server/http\";\nimport { handleSpecRequest } from \"@baerly/server/spec\";\nimport { type MaintenanceDispatch, parseMaintenanceEnv } from \"@baerly/server/maintenance\";\nimport { prettyConsoleSink } from \"./logger-pretty.ts\";\nimport {\n type ObservabilityConfig,\n configureObservability,\n createObservabilityContext,\n deriveOutcome,\n flushCanonicalLine,\n flushUnauthorizedAndRespond,\n observableStorage,\n runWithContext,\n} from \"@baerly/server/observability\";\n\n/**\n * Options for {@link createFetchHandler}.\n *\n * Host-agnostic Fetch-shaped cascade entry point. The Node-host-specific\n * options (`webRoot`, `dev`) live on {@link CreateAppOptions} so they\n * only reach the middleware stack that consumes them.\n *\n * @internal — public consumers see {@link CreateAppOptions} from\n * `./app.ts` instead. Exported for intra-package re-use.\n */\nexport interface CreateFetchHandlerOptions {\n readonly app: string;\n readonly storage: Storage;\n readonly verifier: Verifier;\n /**\n * Your `baerly.config.ts`. When set, the adapter forwards it to\n * {@link Db.create} on every request — so server-side schema\n * validation fires on commits and the auto-planner sees declared\n * indexes. Without this option, declared collections have no\n * effect on the `/v1/c/*` surface.\n *\n * Only `collections` is read — deploy-time fields (`target`,\n * `domain`, `requiredSecrets`, …) are ignored here.\n */\n readonly config?: BaerlyConfig;\n /**\n * LogTape config (level/sink) with `LOG_LEVEL` envvar fallback.\n * When the field is unset (or `{}`), baerly auto-configures LogTape:\n * the default sink is the local `prettyConsoleSink()` when\n * `process.stdout.isTTY === true` (developer terminals),\n * `\"console-json\"` otherwise (production hosts where stdout is piped\n * to a log aggregator). The typed `sink` field always wins.\n *\n * Pass `false` to skip `configureObservability` entirely — the\n * escape hatch for apps that embed baerly and own the process-wide\n * LogTape configuration themselves. (baerly also never clobbers a\n * host config it detects at boot; `false` additionally suppresses the\n * boot-time configure attempt and its meta-logger notice.)\n */\n readonly observability?: ObservabilityConfig | false;\n /** Override the long-poll budget. Forwarded to `createRouter`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `createRouter`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Assemble the per-request {@link MaintenanceDispatch} for a Node host.\n *\n * baerly maintains IN-BAND: the writer reads\n * `getCurrentContext()?.maintenance` at its post-commit dispatch point and\n * runs one bounded compact + GC slice on the (rare) write that crosses a\n * maintenance trigger. Reads stay pure — they never tick. There is no\n * `setInterval`, no cron, no operator-installed scheduler: the kernel\n * maintains itself on a bare bucket with zero operator infrastructure.\n *\n * On Node v1 maintenance runs INLINE on the commit path (no\n * `dispatch` override — serverful Node has no `waitUntil`, and inline is\n * deterministic + correct here), so this returns no `dispatch` field;\n * the writer falls back to its inline-awaited default dispatch.\n *\n * The caps (`options`) are a MODERATE multiple of the CF-free defaults —\n * Node has no Cloudflare subrequest wall, but because v1 runs inline the\n * per-pass work is still BOUNDED by worst-case single-write added\n * latency, not unbounded. We thread `phasesPerTick: \"both\"` (a capable\n * host can fold AND GC in one tick) plus the Node-tier `WRITE_TICK_*`\n * overrides from `@baerly/protocol`'s `NODE_MAINTENANCE_*` constants\n * (10× CF-free, with a shorter GC interval so the sweep budget keeps up).\n *\n * The two ops-plane env vars are read here (per call) so a `vi.stubEnv`\n * in tests — and a real process env in production — is observed:\n *\n * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (the snapshot\n * ceiling `C`). Parsed as a number; ignored when unset / NaN.\n * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Truthy\n * when set to a non-empty value other than `\"0\"` / `\"false\"`.\n *\n * `readEnv` defaults to `process.env`; the parameter exists for direct\n * unit coverage.\n */\nexport const nodeMaintenanceDispatch = (\n readEnv: (key: string) => string | undefined = (k) => process.env[k],\n): MaintenanceDispatch => {\n const { maxFoldBytes, disabled } = parseMaintenanceEnv(readEnv);\n\n return {\n // No `dispatch` override: inline on serverful Node (the writer\n // falls back to `dispatchInlineAwaited`).\n ...(disabled && { disabled: true }),\n ...(maxFoldBytes !== undefined && { maxFoldBytes }),\n options: {\n phasesPerTick: \"both\",\n profile: MAINTENANCE_PROFILE_NODE,\n },\n };\n};\n\n/**\n * Build a `(req: Request) => Promise<Response>` handler that runs the\n * baerly `/v1/*` cascade: healthz short-circuit → observability context\n * → verifier → `Db.create` → `createRouter({db}).fetch(req)` →\n * canonical-line flush. The handler is host-agnostic; mount it under\n * `/v1/*` in your Fetch framework.\n *\n * Non-`/v1/*` paths fall through to the Hono router, which renders the\n * kernel's 404 envelope. To compose static-asset or dev-landing\n * handlers, dispatch those upstream of this factory — see the\n * internal Hono-app factory in `./app.ts` for the production composition.\n *\n * @internal — public consumers reach this via `baerlyNode` from\n * `./baerly-node.ts`. Exported for intra-package re-use and direct unit\n * coverage in `server.test.ts`.\n */\nexport function createFetchHandler(\n opts: CreateFetchHandlerOptions,\n): (req: Request) => Promise<Response> {\n // Factory-time, idempotent. `observability: false` opts out entirely\n // (embedder owns LogTape config); otherwise auto-configure — this is a\n // no-op when a host config is already present (see configureObservability).\n if (opts.observability !== false) {\n void configureObservability(resolveDefaultSink(opts.observability ?? {}));\n }\n const wrappedStorage = observableStorage(opts.storage);\n\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const path = url.pathname;\n\n // /v1/healthz is anonymous; the deploy-probe contract bypasses\n // verifier AND observability so probes don't flood logs. Matches\n // adapter-cloudflare/src/worker.ts.\n if (request.method === \"GET\" && path === \"/v1/healthz\") {\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // /v1/spec is anonymous (like healthz): the static contract IR is\n // non-sensitive (same info as the public .d.ts). Per-tenant\n // collection names are appended ONLY when the verifier accepts —\n // we run it here tolerantly (null → anonymous, no 401), so an\n // unauthenticated probe still gets the static contract. Verifier\n // throws also degrade to anonymous: the static contract is public\n // and should stay available when the auth backend is unhealthy.\n if (request.method === \"GET\" && path === \"/v1/spec\") {\n return handleSpecRequest(request, async () => ({\n verifier: opts.verifier,\n config: opts.config,\n }));\n }\n\n const requestId = request.headers.get(\"x-request-id\") ?? crypto.randomUUID();\n // In-band maintenance: the writer reads `getCurrentContext()?.maintenance`\n // at its post-commit dispatch point. Read per request so the ops-plane env\n // vars (and any `vi.stubEnv` in tests) are observed at call time.\n const obsCtx = createObservabilityContext({\n request_id: requestId,\n maintenance: nodeMaintenanceDispatch(),\n });\n\n const result = await opts.verifier(request);\n if (result === null) {\n return await runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, request));\n }\n\n return await runWithContext(obsCtx, async () => {\n let outboundStatus = 500;\n let caughtError: unknown;\n let response: Response;\n try {\n const db = Db.create({\n storage: wrappedStorage,\n app: opts.app,\n tenant: result.tenantPrefix,\n config: opts.config,\n });\n const router = createRouter({\n db,\n ...(opts.sinceTimeoutMs !== undefined && { sinceTimeoutMs: opts.sinceTimeoutMs }),\n ...(opts.sincePollIntervalMs !== undefined && {\n sincePollIntervalMs: opts.sincePollIntervalMs,\n }),\n });\n response = await router.fetch(request);\n outboundStatus = response.status;\n } catch (error) {\n caughtError = error;\n const { status, envelope } = mapError(error);\n outboundStatus = status;\n response = new Response(JSON.stringify(envelope), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n } finally {\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status: outboundStatus,\n outcome: deriveOutcome(request.method, outboundStatus, caughtError),\n ...(caughtError !== undefined && { error: caughtError }),\n extra: { method: request.method, path },\n });\n }\n return response;\n });\n };\n}\n\n/**\n * Auto-pick the default sink when the caller passed an\n * {@link ObservabilityConfig} without a `sink` field. On a TTY\n * (developer terminals) we prefer pretty output; otherwise JSON\n * (production hosts pipe stdout to a log aggregator).\n *\n * Returns a new config with `sink` defaulted; if the caller already\n * supplied a `sink` (function or shorthand string) we pass the\n * config through verbatim. Either way the caller's `level` (when\n * set) reaches LogTape unchanged.\n *\n * Exported for the test suite — the TTY check is otherwise a pure\n * read of `process.stdout.isTTY` and a default lookup, neither\n * worth a black-box round-trip.\n */\nexport const resolveDefaultSink = (config: ObservabilityConfig): ObservabilityConfig => {\n if (config.sink !== undefined) {\n return config;\n }\n // `process.stdout.isTTY` is `true` only on real terminals. CI\n // pipelines, docker logs, systemd, and pm2 cluster mode all\n // pipe stdout — `isTTY` is `undefined` (falsy) there. The kernel\n // only ships `\"console-json\"`; we construct the pretty sink\n // locally and pass it as a function so picocolors stays off the\n // kernel closure.\n const isTty = Boolean(process.stdout.isTTY);\n return { ...config, sink: isTty ? prettyConsoleSink() : \"console-json\" };\n};\n","import { type DevLandingOptions } from \"@baerly/dev\";\nimport { MAX_BODY_BYTES } from \"@baerly/server/http\";\nimport { Hono } from \"hono/tiny\";\nimport { applyBodyCap } from \"./middleware/body-cap.ts\";\nimport { devLandingMiddleware } from \"./middleware/dev-landing.ts\";\nimport { staticAssetsMiddleware } from \"./middleware/static-assets.ts\";\nimport { type CreateFetchHandlerOptions, createFetchHandler } from \"./server.ts\";\n\n/**\n * Options for {@link createApp}.\n *\n * Extends {@link CreateFetchHandlerOptions} with the Node-host\n * affordances mounted ahead of the cascade.\n */\nexport interface CreateAppOptions extends CreateFetchHandlerOptions {\n /**\n * Optional static-asset root. When set, the app serves files from\n * this directory for any GET/HEAD request that misses `/v1/*`. See\n * {@link staticAssetsMiddleware} for details (MIME mapping, SPA\n * fallback, traversal rejection).\n */\n readonly webRoot?: string;\n /**\n * Opt-in dev affordance. When set, `GET /` returns a human-readable\n * HTML landing page linking to the configured UI URL, and\n * `GET /favicon.ico` returns 204 No Content. Bypasses verifier and\n * observability so it doesn't flood logs. Leave unset in production.\n */\n readonly dev?: DevLandingOptions;\n}\n\n/**\n * Build a Hono app that serves the baerly cascade plus Node-host\n * middleware (dev-landing when `dev` is set, then static-assets when\n * `webRoot` is set, then the cascade).\n *\n * The returned app's `.fetch` is `(req: Request) => Promise<Response>`\n * — feed it to `@hono/node-server`'s `serve({ fetch })`, mount under\n * another Hono app via `app.route(prefix, baerlyApp)`, or convert\n * to a Node listener via `getRequestListener(baerlyApp.fetch)`.\n *\n * Body size enforcement: every non-`GET`/`HEAD`/`OPTIONS` request\n * passes through {@link applyBodyCap} before reaching the cascade.\n * The helper short-circuits with a 413 envelope when `Content-\n * Length` advertises an over-cap body, and otherwise wraps\n * `req.body` with a counting `TransformStream` that errors with\n * `BaerlyError{code:\"PayloadTooLarge\"}` once the running byte\n * count exceeds {@link MAX_BODY_BYTES}. On cap-trip in either\n * path the upstream `IncomingMessage` is drained (`resume()`) so\n * the client's body write completes and the 413 reaches it\n * cleanly. The kernel router's defence-in-depth\n * (`packages/server/src/http/router.ts:464-501`) remains the\n * backstop for hosts without an `incoming` binding.\n */\nexport function createApp(opts: CreateAppOptions): Hono {\n const fetchHandler = createFetchHandler(opts);\n const app = new Hono();\n\n // Order: dev-landing → static-assets → cascade. The dev\n // short-circuit must precede static-assets so a `webRoot` that\n // happens to contain `index.html` / `favicon.ico` doesn't shadow\n // the dev affordance.\n if (opts.dev !== undefined) {\n app.use(\"*\", devLandingMiddleware({ dev: opts.dev }));\n }\n if (opts.webRoot !== undefined) {\n app.use(\"*\", staticAssetsMiddleware({ webRoot: opts.webRoot }));\n }\n\n app.all(\"*\", async (c) => {\n const capped = applyBodyCap(c.req.raw, c.env, MAX_BODY_BYTES);\n if (capped instanceof Response) {\n return capped;\n }\n return fetchHandler(capped);\n });\n\n return app;\n}\n","import { createServer, type Server } from \"node:http\";\nimport { serve } from \"@hono/node-server\";\nimport type { DevLandingOptions } from \"@baerly/dev\";\nimport type { BaerlyAppConfig, Storage, Verifier } from \"@baerly/protocol\";\nimport { resolveVerifier } from \"@baerly/server\";\nimport type { ObservabilityConfig } from \"@baerly/server/observability\";\nimport { createApp } from \"./app.ts\";\n\n/**\n * Options for {@link baerlyNode}. Composes the {@link createApp}\n * surface (same `app` / `storage` / `verifier` / `webRoot` / etc.)\n * with a `node:http` server lifecycle (`listen` / `close` +\n * SIGTERM/SIGINT handling).\n *\n * Mirrors `baerlyWorker` in `@baerly/adapter-cloudflare`.\n */\nexport interface BaerlyNodeOptions {\n /**\n * Your `baerly.config.ts`. **Required.** Carries `auth`, `tenant`,\n * `app`, and the declared `collections` (their schemas/indexes flow\n * through to per-request `Db.create` automatically).\n *\n * The adapter resolves the per-request `Verifier` from\n * `config.auth` when no `verifier:` override is supplied — see\n * resolution order on {@link verifier} below. Only\n * `app` / `tenant` / `auth` / `collections` are read for runtime\n * kernel wiring; deploy-time fields (`target`, `domain`,\n * `requiredSecrets`) are ignored here.\n */\n readonly config: BaerlyAppConfig;\n readonly storage: Storage;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides\n * `config.auth` (the \"dev default in config, prod override via env\"\n * recipe). When unset, the adapter synthesizes one from\n * `config.auth`:\n *\n * - `\"shared-secret\"` → `sharedSecret({ secret:\n * process.env.SHARED_SECRET, tenantPrefix: config.tenant })`.\n * Throws `BaerlyError(\"InvalidConfig\", ...)` at factory time\n * when `SHARED_SECRET` is missing/empty (Node can throw at\n * startup unlike CF Workers).\n * - `\"none\"` → pins every request to `config.tenant` with no\n * header check.\n *\n * `GET /v1/healthz` always bypasses the verifier.\n */\n readonly verifier?: Verifier;\n readonly observability?: ObservabilityConfig | false;\n readonly dev?: DevLandingOptions;\n readonly webRoot?: string;\n readonly sinceTimeoutMs?: number;\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Handle returned by {@link baerlyNode}. Composes a running\n * `node:http` server lifecycle.\n *\n * - `fetch(request)` is the web-standard request handler. Use\n * directly for in-process embedding (Vite middleware via\n * `@hono/node-server.getRequestListener`, custom servers, tests).\n * Calling `fetch` does not start the `node:http` server; the\n * server lifecycle is owned by `listen(port)` / `close()`.\n * Hono's optional `env`/`executionCtx` parameters are intentionally\n * omitted from the signature — this is a Node-host handle, and\n * those parameters are Workers-only.\n * - `listen(port)` binds the server, installs SIGTERM/SIGINT\n * handlers that call `close()` and exit `0`, and resolves once\n * the server is actually listening (after Node's `'listening'`\n * event fires). Throws on `'error'` from the server.\n * - `close()` closes the server and removes the signal handlers.\n * Resolves once `Server.close` callback fires. Safe to call\n * multiple times.\n */\nexport interface BaerlyNodeHandle {\n readonly fetch: (request: Request) => Response | Promise<Response>;\n listen(port: number): Promise<void>;\n close(): Promise<void>;\n}\n\n/**\n * Mount baerly on `node:http` with one call. Mirrors `baerlyWorker`\n * from `@baerly/adapter-cloudflare`.\n *\n * Composes:\n * - {@link createApp} → exposed as `handle.fetch` for in-process\n * embedding; wrapped in `@hono/node-server.serve({ fetch, createServer })`\n * lazily when `listen()` is called.\n * - SIGTERM + SIGINT handlers installed on `listen()` that call\n * `close()` and `process.exit(0)`. On any error during close,\n * `process.exit(1)`.\n *\n * **Maintenance is in-band, not scheduled.** There is no `setInterval`,\n * no cron, and no `maintenance:` option: the kernel maintains itself on\n * a bare bucket with zero operator infrastructure. Compaction + GC run\n * INLINE on the (rare) write that crosses a maintenance trigger —\n * `createFetchHandler` threads a Node-tier `MaintenanceDispatch`\n * onto the per-request observability context, which the writer reads at\n * its post-commit dispatch point. Reads never tick. Tune via the\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` / `BAERLY_MAINTENANCE_DISABLE`\n * env vars; for an explicit out-of-band sweep, call\n * `runScheduledMaintenance` from `@gusto/baerly-storage` directly.\n *\n * @example\n * ```ts\n * import { baerlyNode, s3Storage } from \"@gusto/baerly-storage/node\";\n * import config from \"./baerly.config.ts\";\n *\n * const handle = baerlyNode({\n * config,\n * storage: s3Storage({\n * region: \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * }),\n * // No verifier needed when config.auth is \"none\" or \"shared-secret\".\n * webRoot: \"./dist/client\",\n * });\n * await handle.listen(Number(process.env[\"PORT\"] ?? 8080));\n * ```\n */\nexport function baerlyNode(opts: BaerlyNodeOptions): BaerlyNodeHandle {\n // Node can `await` / throw at top level (unlike CF Workers), so\n // verifier resolution lives here at factory time. An unset\n // `SHARED_SECRET` for `auth: \"shared-secret\"` fails the process\n // startup with a locked `InvalidConfig` message rather than\n // surprising the first inbound request.\n const verifier = resolveVerifier({\n factoryVerifier: opts.verifier,\n config: opts.config,\n readEnv: (k) => process.env[k],\n });\n // auth=none startup banner: emit one info line when the operator\n // opted into no-auth via config (not when they passed a real\n // verifier override). Suppressed for shared-secret — operator\n // already knows.\n if (opts.verifier === undefined && opts.config.auth === \"none\") {\n console.log(\n `[baerly] auth=none — all requests resolve to tenant=${JSON.stringify(opts.config.tenant)}`,\n );\n }\n const app = createApp({\n app: opts.config.app,\n storage: opts.storage,\n verifier,\n config: opts.config,\n ...(opts.observability !== undefined && { observability: opts.observability }),\n ...(opts.dev !== undefined && { dev: opts.dev }),\n ...(opts.webRoot !== undefined && { webRoot: opts.webRoot }),\n ...(opts.sinceTimeoutMs !== undefined && { sinceTimeoutMs: opts.sinceTimeoutMs }),\n ...(opts.sincePollIntervalMs !== undefined && {\n sincePollIntervalMs: opts.sincePollIntervalMs,\n }),\n });\n // `serve()` is deferred to `listen()` so calling `baerlyNode(opts)`\n // without `.listen()` does NOT create an `http.Server` or install\n // signal handlers. The `fetch` handler is exposed on the returned\n // handle for in-process embedding (Vite middleware, tests). `server`\n // stays `undefined` until `listen()` runs; `close()` guards against\n // the \"constructed but never listened\" branch.\n let server: Server | undefined;\n\n let signalHandler: ((sig: NodeJS.Signals) => void) | undefined;\n let closed = false;\n\n const close = async (): Promise<void> => {\n if (closed) {\n return;\n }\n closed = true;\n if (signalHandler !== undefined) {\n process.off(\"SIGTERM\", signalHandler);\n process.off(\"SIGINT\", signalHandler);\n signalHandler = undefined;\n }\n await new Promise<void>((resolve, reject) => {\n // Factory was called but `listen()` never ran — there's no\n // `http.Server` to close. Resolve immediately.\n if (server === undefined) {\n resolve();\n return;\n }\n // Node throws ERR_SERVER_NOT_RUNNING on close() of a non-listening server.\n if (!server.listening) {\n resolve();\n return;\n }\n server.close((err) => {\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n });\n });\n };\n\n const listen = async (port: number): Promise<void> => {\n // `serve()` builds an `http.Server` via the supplied `createServer`\n // factory and wires the Hono `fetch` handler into it (handling\n // backpressure, client-abort → AbortController, and stream\n // cleanup natively). The `port` / `hostname` here are placeholders —\n // the actual bind happens via the explicit `server.listen(port)`\n // call below, which overrides them.\n server = serve({\n fetch: app.fetch,\n port: 0,\n hostname: \"0.0.0.0\",\n createServer,\n }) as Server;\n const httpServer = server;\n await new Promise<void>((resolve, reject) => {\n const onError = (err: Error): void => {\n httpServer.off(\"listening\", onListening);\n httpServer.off(\"close\", onClose);\n reject(err);\n };\n const onListening = (): void => {\n httpServer.off(\"error\", onError);\n httpServer.off(\"close\", onClose);\n resolve();\n };\n // close() called between `server.listen(port)` and the\n // `'listening'` event cancels the bind: `'listening'` never\n // fires; only `'close'` does. Resolve so we observe `closed`\n // below and skip handler install.\n const onClose = (): void => {\n httpServer.off(\"error\", onError);\n httpServer.off(\"listening\", onListening);\n resolve();\n };\n httpServer.once(\"error\", onError);\n httpServer.once(\"listening\", onListening);\n httpServer.once(\"close\", onClose);\n httpServer.listen(port);\n });\n\n // close() may have run while we were awaiting `'listening'`. Skip\n // handler install so we don't leak a SIGTERM/SIGINT listener onto a\n // closed handle.\n if (closed) {\n return;\n }\n\n // Shared handler so a double-signal (SIGINT then SIGTERM) keeps\n // the listener count predictable for the close() cleanup path.\n signalHandler = (sig): void => {\n console.log(`Received ${sig}; closing baerlyNode server`);\n close()\n .then(() => process.exit(0))\n .catch((error: unknown) => {\n console.error(\"baerlyNode close failed\", error);\n process.exit(1);\n });\n };\n process.on(\"SIGTERM\", signalHandler);\n process.on(\"SIGINT\", signalHandler);\n };\n\n return { fetch: app.fetch, listen, close };\n}\n"],"x_google_ignoreList":[10,11,12],"mappings":";;;;;;;;;;;;;;;;;;AAIA,MAAM,cAAc,UAClB,iBAAiB,eAAe,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CjD,MAAa,WAAW,OACtB,SACA,SAC4B;CAC5B,MAAM,SAAS,MAAM,aAAa;CAClC,MAAM,MAAM,GAAG,OAAO,uBAAuB,KAAK;CAClD,MAAM,MAAM,IAAI,YAAY;CAC5B,MAAM,SAAS,MAAM;CAErB,MAAM,SAA0B,CAAC;CACjC,IAAI;EACY,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG,EAAE,OAAO,CAAC;EAGjE,IAAI;GAEF,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG;IAAE,SAAS;IAA4B;GAAO,CAAC;GACxF,OAAO,KAAK;IACV,MAAM;IACN,IAAI;IACJ,QACE;GACJ,CAAC;EACH,SAAS,OAAO;GACd,OAAO,KACL,WAAW,KAAK,IACZ;IACE,MAAM;IACN,IAAI;IACJ,QAAQ;GACV,IACA;IACE,MAAM;IACN,IAAI;IACJ,QAAQ,+CAA+C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAC9G,CACN;EACF;EAGA,IAAI;GAEF,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG;IAAE,aAAa;IAAK;GAAO,CAAC;GACrE,OAAO,KAAK;IACV,MAAM;IACN,IAAI;IACJ,QACE;GACJ,CAAC;EACH,SAAS,OAAO;GACd,OAAO,KAC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