@gusto/baerly-storage 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +9 -14
  53. package/dist/dev-vite.js +11 -10
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,24 +1,27 @@
1
- import { c as configureObservability, n as flushCanonicalLine, o as deriveOutcome, r as flushUnauthorizedAndRespond, t as observableStorage, u as errorEnvelope } from "./observability-Ch-VQJyE.js";
2
- import { d as MAINTENANCE_PROFILE_NODE } from "./constants-CfeMWQWk.js";
3
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
4
- import { o as parseMaintenanceEnv } from "./maintenance-DULFcpd1.js";
5
- import { a as isDeployedEnv, n as resolveVerifier, t as Db } from "./src-DvbTEya2.js";
6
- import { a as uuid } from "./time-DUqvFMHq.js";
7
- import { n as createRouter, o as Hono, r as mapError, t as MAX_BODY_BYTES } from "./http-7zT29K3P.js";
8
- import { r as runWithContext, t as createObservabilityContext } from "./context-DRZ3tZ5l.js";
9
- import { a as require_picocolors_browser, r as renderDevLanding, t as LocalFsStorage } from "./src-DYZ4H1aF.js";
10
- import { t as handleSpecRequest } from "./runtime-spec--LykAdl1.js";
11
- import { a as parseAssumeRoleWithWebIdentity, s as parseStsError } from "./http-transport-BTgVCY5r.js";
12
- import { n as S3HttpStorage, t as AwsClient } from "./aws4fetch.esm-CXE5ZbAa.js";
13
- import { r as GcsHttpStorage, t as goog4Signer } from "./goog4-signer-Z7KnJ1su.js";
14
- import { readFile, stat } from "node:fs/promises";
15
- import { extname, relative, resolve, sep } from "node:path";
16
- import { STATUS_CODES, createServer } from "node:http";
1
+ import { i as withCredentialInvalidation, n as AwsClient, r as S3HttpStorage, t as signHeadersOnly } from "./sigv4-sign-5IUflUD_.js";
2
+ import { i as GcsHttpStorage, n as credentialResolver, t as goog4Signer } from "./goog4-signer-CeLIABoE.js";
3
+ import { r as LocalFsStorage } from "./src-D0MQfvOp.js";
4
+ import { i as isWriteConflict, t as BaerlyError } from "./errors-7Rk1HGCE.js";
5
+ import { r as isDeployedEnv, t as Db } from "./src-Dr9uo3dc.js";
6
+ import { o as uuid } from "./time-DRxTP9iv.js";
7
+ import { a as parseAssumeRoleWithWebIdentity, s as parseStsError } from "./http-transport-DNUM8kU-.js";
8
+ import { n as withNosniff, r as resolveVerifier, t as handleSpecRequest } from "./runtime-spec-B5mg3pHF.js";
9
+ import { n as createRouter, o as Hono, r as mapError, t as MAX_BODY_BYTES } from "./http-Z5rZyYMX.js";
10
+ import { a as flushUnauthorizedAndRespond, c as requestIdFrom, d as configureObservability, i as flushCanonicalLine, l as deriveOutcome, m as errorEnvelope, p as logMaintenanceWarning, r as observableStorage } from "./observability-C-ISCCLE.js";
11
+ import { t as renderDevLanding } from "./dev-landing-CD-si4dW.js";
12
+ import { _ as MAINTENANCE_PROFILE_NODE } from "./constants-D3GSH3tc.js";
13
+ import { t as RequestLedger } from "./ledger-Dj_bGgo0.js";
14
+ import { r as parseMaintenanceEnv } from "./maintenance-DevB6z4e.js";
15
+ import { i as runWithContext, t as createObservabilityContext } from "./context-rlpSnHFA.js";
16
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
17
+ import { readFile } from "node:fs/promises";
18
+ import { STATUS_CODES, ServerResponse, createServer } from "node:http";
17
19
  import { Http2ServerRequest, constants } from "node:http2";
18
20
  import { Readable } from "node:stream";
19
- import { createReadStream } from "node:fs";
20
- //#region packages/protocol/src/storage/probe-cas.ts
21
- const isConflict = (error) => error instanceof BaerlyError && error.code === "Conflict";
21
+ import { styleText } from "node:util";
22
+ import { createReadStream, existsSync, realpathSync, statSync } from "node:fs";
23
+ import { versions } from "node:process";
24
+ // packages/protocol/src/storage/probe-cas.ts
22
25
  /**
23
26
  * Runtime probe that a live `Storage` backend honours the conditional
24
27
  * writes the protocol depends on. The storage conformance suite asserts
@@ -36,16 +39,16 @@ const isConflict = (error) => error instanceof BaerlyError && error.code === "Co
36
39
  * Writes throwaway sentinels under `keyPrefix` and deletes them on
37
40
  * the way out (even on failure). Three checks, mirroring the conformance
38
41
  * suite:
39
- * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).
42
+ * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (WriteConflict).
40
43
  * - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:"*"` over an existing
41
- * key must reject (Conflict).
44
+ * key must reject (WriteConflict).
42
45
  * - `ifNoneMatch-concurrent`: at most one of N concurrent create-if-absent
43
46
  * writes on a fresh key wins — the linearizability the writer's log-append
44
47
  * commit already relies on (`writer.ts`).
45
48
  *
46
- * A rejected write surfaces as a `BaerlyError` with `code === "Conflict"`
49
+ * A rejected write surfaces as a `BaerlyError` with `code === "WriteConflict"`
47
50
  * (the contract `Storage.put` documents); anything else — a resolved
48
- * promise, or a non-Conflict error — is reported as a failed or
51
+ * promise, or a non-WriteConflict error — is reported as a failed or
49
52
  * inconclusive check rather than thrown.
50
53
  */
51
54
  const probeCas = async (storage, opts) => {
@@ -68,14 +71,14 @@ const probeCas = async (storage, opts) => {
68
71
  detail: "PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk)."
69
72
  });
70
73
  } catch (error) {
71
- checks.push(isConflict(error) ? {
74
+ checks.push(isWriteConflict(error) ? {
72
75
  name: "ifMatch-stale",
73
76
  ok: true,
74
- detail: "stale If-Match rejected (Conflict), as required."
77
+ detail: "stale If-Match rejected (WriteConflict), as required."
75
78
  } : {
76
79
  name: "ifMatch-stale",
77
80
  ok: false,
78
- detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
81
+ detail: `stale If-Match raised a non-WriteConflict error: ${error instanceof Error ? error.message : String(error)}`
79
82
  });
80
83
  }
81
84
  try {
@@ -89,14 +92,14 @@ const probeCas = async (storage, opts) => {
89
92
  detail: "PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe)."
90
93
  });
91
94
  } catch (error) {
92
- checks.push(isConflict(error) ? {
95
+ checks.push(isWriteConflict(error) ? {
93
96
  name: "ifNoneMatch-exists",
94
97
  ok: true,
95
- detail: "If-None-Match:\"*\" over an existing key rejected (Conflict), as required."
98
+ detail: "If-None-Match:\"*\" over an existing key rejected (WriteConflict), as required."
96
99
  } : {
97
100
  name: "ifNoneMatch-exists",
98
101
  ok: false,
99
- detail: `If-None-Match:"*" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
102
+ detail: `If-None-Match:"*" raised a non-WriteConflict error: ${error instanceof Error ? error.message : String(error)}`
100
103
  });
101
104
  }
102
105
  const raceKey = `${prefix}__baerly_cas_probe__/${uuid()}`;
@@ -107,23 +110,24 @@ const probeCas = async (storage, opts) => {
107
110
  signal
108
111
  })));
109
112
  const winners = outcomes.filter((o) => o.status === "fulfilled").length;
110
- const transient = outcomes.filter((o) => o.status === "rejected" && !isConflict(o.reason)).length;
113
+ const transient = outcomes.filter((o) => o.status === "rejected" && !isWriteConflict(o.reason)).length;
111
114
  if (winners > 1) checks.push({
112
115
  name: "ifNoneMatch-concurrent",
113
116
  ok: false,
114
117
  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.`
115
118
  });
116
- else if (winners === 1) if (transient === 0) checks.push({
117
- name: "ifNoneMatch-concurrent",
118
- ok: true,
119
- detail: `exactly one of ${RACERS} concurrent create-if-absent writes won; the rest rejected (Conflict), as required.`
120
- });
121
- else checks.push({
122
- name: "ifNoneMatch-concurrent",
123
- ok: false,
124
- 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.`
125
- });
126
- else checks.push({
119
+ else if (winners === 1) {
120
+ if (transient === 0) checks.push({
121
+ name: "ifNoneMatch-concurrent",
122
+ ok: true,
123
+ detail: `exactly one of ${RACERS} concurrent create-if-absent writes won; the rest rejected (WriteConflict), as required.`
124
+ });
125
+ else checks.push({
126
+ name: "ifNoneMatch-concurrent",
127
+ ok: false,
128
+ detail: `exactly one of ${RACERS} concurrent create-if-absent writes won, but ${transient} loser(s) returned a transient non-WriteConflict error — inconclusive; retry for a clean race.`
129
+ });
130
+ } else checks.push({
127
131
  name: "ifNoneMatch-concurrent",
128
132
  ok: false,
129
133
  detail: `no create-if-absent write succeeded across ${RACERS} attempts — inconclusive (transient failure or outage), not a linearizability verdict; retry.`
@@ -143,8 +147,7 @@ const probeCas = async (storage, opts) => {
143
147
  checks
144
148
  };
145
149
  };
146
- //#endregion
147
- //#region packages/adapter-node/src/gcs-admin.ts
150
+ // packages/adapter-node/src/gcs-admin.ts
148
151
  /**
149
152
  * GCS bucket-administration probes over the native XML API — read-only
150
153
  * config checks that fall outside the four-verb `Storage` interface.
@@ -181,9 +184,7 @@ async function gcsVersioningStatus(opts) {
181
184
  };
182
185
  }
183
186
  }
184
- //#endregion
185
- //#region packages/adapter-node/src/credentials/signer.ts
186
- const REFRESH_BUFFER_MS = 300 * 1e3;
187
+ // packages/adapter-node/src/credentials/signer.ts
187
188
  function buildAwsClient(creds, region) {
188
189
  return new AwsClient({
189
190
  accessKeyId: creds.accessKeyId,
@@ -198,45 +199,33 @@ function refreshingSigner(opts) {
198
199
  const now = opts.now ?? (() => Date.now());
199
200
  if (typeof opts.credentials !== "function") {
200
201
  const aws = buildAwsClient(opts.credentials, region);
201
- return (req) => aws.sign(req);
202
- }
203
- const provider = opts.credentials;
204
- let cached = null;
205
- let inFlight = null;
206
- const resolve = async () => {
207
- if (cached !== null && cached.expiresAt - REFRESH_BUFFER_MS > now()) return cached.aws;
208
- if (inFlight !== null) return inFlight;
209
- inFlight = (async () => {
210
- try {
211
- const creds = await provider();
212
- const aws = buildAwsClient(creds, region);
213
- cached = {
214
- aws,
215
- expiresAt: creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY
216
- };
217
- return aws;
218
- } finally {
219
- inFlight = null;
220
- }
221
- })();
222
- return inFlight;
223
- };
224
- return async (req) => {
225
- return (await resolve()).sign(req);
202
+ return (req) => signHeadersOnly(aws, req);
203
+ }
204
+ const resolve = credentialResolver(opts.credentials, now, (creds) => buildAwsClient(creds, region));
205
+ const signedBy = /* @__PURE__ */ new WeakMap();
206
+ const sign = async (req) => {
207
+ const aws = await resolve();
208
+ const signed = await signHeadersOnly(aws, req);
209
+ signedBy.set(signed, aws);
210
+ return signed;
226
211
  };
212
+ return Object.assign(sign, { invalidate(signed) {
213
+ const aws = signedBy.get(signed);
214
+ if (aws !== void 0) resolve.invalidate(aws);
215
+ } });
227
216
  }
228
- //#endregion
229
- //#region packages/adapter-node/src/storage-factories.ts
217
+ // packages/adapter-node/src/storage-factories.ts
230
218
  function buildS3Storage(opts) {
231
219
  const sign = refreshingSigner({
232
220
  region: opts.region,
233
221
  credentials: opts.credentials
234
222
  });
235
- return new S3HttpStorage({
223
+ const storage = new S3HttpStorage({
236
224
  endpoint: opts.endpoint,
237
225
  bucket: opts.bucket,
238
226
  sign
239
227
  });
228
+ return sign.invalidate === void 0 ? storage : withCredentialInvalidation(storage, sign.invalidate);
240
229
  }
241
230
  /**
242
231
  * AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard
@@ -374,8 +363,7 @@ function gcsStorage(opts) {
374
363
  ...opts.endpoint !== void 0 && { endpoint: opts.endpoint }
375
364
  });
376
365
  }
377
- //#endregion
378
- //#region packages/adapter-node/src/local-fs-storage.ts
366
+ // packages/adapter-node/src/local-fs-storage.ts
379
367
  /**
380
368
  * Zero-config local `Storage` for single-node dev / self-hosted runs.
381
369
  * Persists to the filesystem (content-addressed, atomic writes), so data
@@ -383,10 +371,12 @@ function gcsStorage(opts) {
383
371
  * and lost on exit.
384
372
  *
385
373
  * NOT for multi-instance production: `LocalFsStorage`'s `ifMatch` CAS is
386
- * in-process TOCTOU only (cross-process `current.json` CAS-advance is not
387
- * atomic — see its class JSDoc). For horizontally-scaled deploys use
388
- * `s3Storage` / `r2Storage`, whose cross-process guarantee the no-lease
389
- * maintenance fold relies on.
374
+ * serialized within one process only, so a `current.json` CAS-advance is
375
+ * not atomic against a second process on the same directory (see its class
376
+ * JSDoc). Every call here returns a fresh instance, which is fine — the
377
+ * lock is keyed by resolved root, so instances sharing a directory share
378
+ * it. For horizontally-scaled deploys use `s3Storage` / `r2Storage`, whose
379
+ * cross-process guarantee the no-lease maintenance fold relies on.
390
380
  *
391
381
  * @example
392
382
  * ```ts
@@ -398,8 +388,7 @@ function gcsStorage(opts) {
398
388
  * ```
399
389
  */
400
390
  const localFsStorage = (opts) => new LocalFsStorage({ root: opts?.dataDir ?? process.env["BAERLY_DATA_DIR"] ?? resolve(process.cwd(), ".baerly-data") });
401
- //#endregion
402
- //#region packages/adapter-node/src/resolve-storage.ts
391
+ // packages/adapter-node/src/resolve-storage.ts
403
392
  /**
404
393
  * Choose a Node `Storage` backend from environment variables, in priority
405
394
  * order:
@@ -476,8 +465,7 @@ const resolveStorageFromEnv = (env = process.env) => {
476
465
  "use SQLite + Litestream for a single-instance app."
477
466
  ].join("\n"));
478
467
  };
479
- //#endregion
480
- //#region packages/adapter-node/src/assert-storage-reachable.ts
468
+ // packages/adapter-node/src/assert-storage-reachable.ts
481
469
  /**
482
470
  * Boot-time readiness check: confirm a live `Storage` backend is both
483
471
  * reachable and honours the conditional writes the protocol depends on.
@@ -515,12 +503,14 @@ const assertStorageReachable = async (storage, opts) => {
515
503
  try {
516
504
  result = await probeCas(storage, opts);
517
505
  } catch (error) {
518
- throw new BaerlyError("NetworkError", `Storage readiness check failed: the backend could not be reached. Verify the bucket name, region/endpoint, and credentials. Cause: ${error instanceof Error ? error.message : String(error)}`, error);
506
+ throw new BaerlyError("NetworkError", `Storage readiness check failed: the backend could not be reached. Verify the bucket name, region/endpoint, and credentials. Cause: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
507
+ }
508
+ if (!result.ok) {
509
+ const failed = result.checks.filter((c) => !c.ok).map((c) => ` - ${c.name}: ${c.detail}`).join("\n");
510
+ throw new BaerlyError("InvalidConfig", `Storage readiness check failed — the backend does not honour the conditional writes baerly requires (data corruption risk). Use a store that honours them: AWS S3 or Cloudflare R2 (If-Match / If-None-Match), or native Google Cloud Storage via \`gcsStorage\` (x-goog-if-generation-match). GCS's S3-interop endpoint is not supported.\n${failed}`);
519
511
  }
520
- if (!result.ok) throw new BaerlyError("InvalidConfig", `Storage readiness check failed — the backend does not honour the conditional writes baerly requires (data corruption risk). Use a store that honours them: AWS S3 or Cloudflare R2 (If-Match / If-None-Match), or native Google Cloud Storage via \`gcsStorage\` (x-goog-if-generation-match). GCS's S3-interop endpoint is not supported.\n${result.checks.filter((c) => !c.ok).map((c) => ` - ${c.name}: ${c.detail}`).join("\n")}`);
521
512
  };
522
- //#endregion
523
- //#region packages/adapter-node/src/credentials/token-file.ts
513
+ // packages/adapter-node/src/credentials/token-file.ts
524
514
  /**
525
515
  * Read and validate an EKS-projected service-account token file, shared by
526
516
  * {@link fromWebIdentity} and {@link fromEksPodIdentity}. Reads the file,
@@ -529,7 +519,7 @@ const assertStorageReachable = async (storage, opts) => {
529
519
  *
530
520
  * A missing / unreadable / empty projected token is a deploy misconfig, not a
531
521
  * transient fault — so every failure is `InvalidConfig`, which short-circuits
532
- * the retry loop (see `PERMANENT_ERROR_CODES` in `http-transport.ts`) instead of
522
+ * the retry loop (see `PERMANENT_STORAGE_ERROR_CODES` in `@baerly/protocol`'s `storage/retry.ts`) instead of
533
523
  * hammering the credential source. Error messages name the specific env var
534
524
  * so the misconfig is debuggable.
535
525
  */
@@ -544,10 +534,33 @@ async function readProjectedToken(doReadFile, tokenPath, ctx) {
544
534
  if (token === "") throw new BaerlyError("InvalidConfig", `${ctx.provider}: ${ctx.envVar} (${tokenPath}) is empty`);
545
535
  return token;
546
536
  }
547
- //#endregion
548
- //#region packages/adapter-node/src/credentials/from-eks-pod-identity.ts
537
+ // packages/adapter-node/src/credentials/from-eks-pod-identity.ts
549
538
  const FETCH_TIMEOUT_MS$1 = 2e3;
550
539
  /**
540
+ * Hosts the agent can live on: the ECS agent, the EKS Pod Identity agent
541
+ * (IPv4 and IPv6), and loopback. `127.0.0.0/8` is matched separately.
542
+ * WHATWG URL parsing canonicalizes the hostname first, so alternate
543
+ * spellings (`[0:0:0:0:0:0:0:1]`, `2130706433`) compare equal.
544
+ */
545
+ const AGENT_HOSTS = /* @__PURE__ */ new Set([
546
+ "169.254.170.2",
547
+ "169.254.170.23",
548
+ "[fd00:ec2::23]",
549
+ "localhost",
550
+ "[::1]"
551
+ ]);
552
+ const LOOPBACK_V4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
553
+ function isAgentUri(uri) {
554
+ let url;
555
+ try {
556
+ url = new URL(uri);
557
+ } catch {
558
+ return false;
559
+ }
560
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
561
+ return AGENT_HOSTS.has(url.hostname) || LOOPBACK_V4.test(url.hostname);
562
+ }
563
+ /**
551
564
  * Resolve AWS credentials from the EKS Pod Identity agent (the 2023
552
565
  * successor to IRSA). The agent runs on each EKS node and exchanges
553
566
  * the pod's projected service-account token for short-lived AWS
@@ -561,6 +574,11 @@ const FETCH_TIMEOUT_MS$1 = 2e3;
561
574
  *
562
575
  * Both are required. Agent should respond instantly on the node-local
563
576
  * link — 2 s timeout protects against hangs.
577
+ *
578
+ * The URI must name the agent: loopback, or the ECS / EKS link-local
579
+ * addresses (the AWS SDK's container-credentials allow-list). Anything
580
+ * else throws `InvalidConfig` before the token file is read, so a
581
+ * misconfigured or injected env var never sends the token off-node.
564
582
  */
565
583
  function fromEksPodIdentity(opts = {}) {
566
584
  const doFetch = opts.fetch ?? fetch;
@@ -569,6 +587,7 @@ function fromEksPodIdentity(opts = {}) {
569
587
  const uri = process.env["AWS_CONTAINER_CREDENTIALS_FULL_URI"];
570
588
  const tokenPath = process.env["AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"];
571
589
  if (uri === void 0 || uri === "") throw new BaerlyError("InvalidConfig", "fromEksPodIdentity: AWS_CONTAINER_CREDENTIALS_FULL_URI not set");
590
+ if (!isAgentUri(uri)) throw new BaerlyError("InvalidConfig", "fromEksPodIdentity: AWS_CONTAINER_CREDENTIALS_FULL_URI must be an http(s) URL on loopback, 169.254.170.2, 169.254.170.23 or [fd00:ec2::23]");
572
591
  if (tokenPath === void 0 || tokenPath === "") throw new BaerlyError("InvalidConfig", "fromEksPodIdentity: AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE not set");
573
592
  const token = await readProjectedToken(doReadFile, tokenPath, {
574
593
  provider: "fromEksPodIdentity",
@@ -604,8 +623,7 @@ function fromEksPodIdentity(opts = {}) {
604
623
  };
605
624
  };
606
625
  }
607
- //#endregion
608
- //#region packages/adapter-node/src/credentials/from-web-identity.ts
626
+ // packages/adapter-node/src/credentials/from-web-identity.ts
609
627
  const FETCH_TIMEOUT_MS = 5e3;
610
628
  const DEFAULT_SESSION_NAME = "baerly-storage";
611
629
  /**
@@ -681,8 +699,7 @@ function fromWebIdentity(opts = {}) {
681
699
  };
682
700
  };
683
701
  }
684
- //#endregion
685
- //#region packages/adapter-node/src/credentials/from-eks.ts
702
+ // packages/adapter-node/src/credentials/from-eks.ts
686
703
  /**
687
704
  * Resolve AWS credentials on EKS regardless of which identity mechanism the
688
705
  * cluster uses, so callers don't have to know. EKS injects credentials one of
@@ -709,27 +726,185 @@ function fromEks(opts = {}) {
709
726
  throw new BaerlyError("InvalidConfig", "fromEks: no EKS credentials in env — set AWS_CONTAINER_CREDENTIALS_FULL_URI (Pod Identity) or AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN (IRSA)");
710
727
  };
711
728
  }
712
- //#endregion
713
- //#region node_modules/.pnpm/@hono+node-server@2.0.6_hono@4.12.27/node_modules/@hono/node-server/dist/index.mjs
729
+ // node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/index.mjs
714
730
  var RequestError = class extends Error {
715
731
  constructor(message, options) {
716
732
  super(message, options);
717
733
  this.name = "RequestError";
718
734
  }
719
735
  };
736
+ const nonJoinedHeaders = /* @__PURE__ */ new Set([
737
+ "age",
738
+ "authorization",
739
+ "content-length",
740
+ "content-type",
741
+ "etag",
742
+ "expires",
743
+ "from",
744
+ "host",
745
+ "if-modified-since",
746
+ "if-unmodified-since",
747
+ "last-modified",
748
+ "location",
749
+ "max-forwards",
750
+ "proxy-authorization",
751
+ "referer",
752
+ "retry-after",
753
+ "server",
754
+ "user-agent"
755
+ ]);
756
+ const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;
757
+ const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;
758
+ const normalizeHeaderValue = (value) => {
759
+ if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value;
760
+ let start = 0;
761
+ let end = value.length;
762
+ while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++;
763
+ while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--;
764
+ return value.slice(start, end);
765
+ };
766
+ const forbiddenHeaderValue = /[\0\r\n]/;
767
+ const GlobalHeaders = globalThis.Headers;
768
+ const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => {
769
+ const headers = new HeadersCtor();
770
+ for (let i = 0; i < rawHeaders.length; i += 2) {
771
+ const name = rawHeaders[i];
772
+ if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]);
773
+ }
774
+ return headers;
775
+ };
776
+ var RequestHeaders = class {
777
+ #incoming;
778
+ #rawHeaders;
779
+ #headers;
780
+ #invalidValue;
781
+ constructor(incoming) {
782
+ this.#incoming = incoming;
783
+ if (incoming instanceof Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice();
784
+ }
785
+ get #lazyRawHeaders() {
786
+ return this.#rawHeaders ??= this.#incoming.rawHeaders.slice();
787
+ }
788
+ get #native() {
789
+ if (!this.#headers) {
790
+ this.#headers = materializeHeaders(this.#lazyRawHeaders);
791
+ this.#rawHeaders = void 0;
792
+ }
793
+ return this.#headers;
794
+ }
795
+ #normalizedName(name) {
796
+ if (typeof name !== "string") return;
797
+ if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`);
798
+ return name.toLowerCase();
799
+ }
800
+ #lookupHttp1(lowerName) {
801
+ const headers = this.#incoming instanceof Http2ServerRequest ? void 0 : this.#incoming.headers;
802
+ if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return;
803
+ if (!Object.hasOwn(headers, lowerName)) return null;
804
+ const rawValue = headers[lowerName];
805
+ if (typeof rawValue === "string") {
806
+ const value = normalizeHeaderValue(rawValue);
807
+ return forbiddenHeaderValue.test(value) ? void 0 : value;
808
+ }
809
+ }
810
+ #lookup(rawHeaders, lowerName) {
811
+ const separator = lowerName === "cookie" ? "; " : ", ";
812
+ let value = null;
813
+ for (let i = 0; i < rawHeaders.length; i += 2) {
814
+ const rawName = rawHeaders[i];
815
+ if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) {
816
+ const rawValue = normalizeHeaderValue(rawHeaders[i + 1]);
817
+ if (forbiddenHeaderValue.test(rawValue)) {
818
+ this.#invalidValue = true;
819
+ return;
820
+ }
821
+ value = value === null ? rawValue : value + separator + rawValue;
822
+ }
823
+ }
824
+ return value;
825
+ }
826
+ append(name, value) {
827
+ this.#native.append(name, value);
828
+ }
829
+ delete(name) {
830
+ this.#native.delete(name);
831
+ }
832
+ get(name) {
833
+ const lowerName = this.#normalizedName(name);
834
+ if (lowerName && !this.#headers && !this.#invalidValue) {
835
+ const http1Value = this.#lookupHttp1(lowerName);
836
+ if (http1Value !== void 0) return http1Value;
837
+ const value = this.#lookup(this.#lazyRawHeaders, lowerName);
838
+ if (value !== void 0) return value;
839
+ }
840
+ return this.#native.get(name);
841
+ }
842
+ has(name) {
843
+ const lowerName = this.#normalizedName(name);
844
+ if (lowerName && !this.#headers && !this.#invalidValue) {
845
+ const http1Value = this.#lookupHttp1(lowerName);
846
+ if (http1Value !== void 0) return http1Value !== null;
847
+ const value = this.#lookup(this.#lazyRawHeaders, lowerName);
848
+ if (value !== void 0) return value !== null;
849
+ }
850
+ return this.#native.has(name);
851
+ }
852
+ set(name, value) {
853
+ this.#native.set(name, value);
854
+ }
855
+ getSetCookie() {
856
+ return this.#native.getSetCookie();
857
+ }
858
+ keys() {
859
+ return this.#native.keys();
860
+ }
861
+ values() {
862
+ return this.#native.values();
863
+ }
864
+ entries() {
865
+ return this.#native.entries();
866
+ }
867
+ forEach(callback, thisArg) {
868
+ this.#native.forEach((value, key) => {
869
+ callback.call(thisArg, value, key, this);
870
+ });
871
+ }
872
+ [Symbol.iterator]() {
873
+ return this.entries();
874
+ }
875
+ };
876
+ Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
877
+ return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), {
878
+ ...options,
879
+ depth: depth == null ? null : depth - 1
880
+ })}`;
881
+ } });
882
+ Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);
883
+ const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
720
884
  const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
721
885
  const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
722
886
  const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
887
+ const validateRequestTarget = (target) => {
888
+ const backslash = target.indexOf("\\");
889
+ if (backslash !== -1) {
890
+ const query = target.indexOf("?");
891
+ if (query === -1 || backslash < query) throw new RequestError("Backslash in request path");
892
+ }
893
+ };
723
894
  const buildUrl = (scheme, host, incomingUrl) => {
724
895
  const url = `${scheme}://${host}${incomingUrl}`;
725
896
  if (!reValidHost.test(host)) {
897
+ validateRequestTarget(incomingUrl);
726
898
  const urlObj = new URL(url);
727
899
  if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
728
900
  return urlObj.href;
729
901
  } else if (incomingUrl.length === 0) return url + "/";
730
902
  else {
731
903
  if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
732
- if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
904
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) {
905
+ validateRequestTarget(incomingUrl);
906
+ return new URL(url).href;
907
+ }
733
908
  return url;
734
909
  }
735
910
  };
@@ -749,16 +924,55 @@ var Request$1 = class extends GlobalRequest {
749
924
  super(input, options);
750
925
  }
751
926
  };
752
- const newHeadersFromIncoming = (incoming) => {
753
- const headerRecord = [];
754
- const rawHeaders = incoming.rawHeaders;
755
- for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
756
- const key = rawHeaders[i];
757
- if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
927
+ const wrapBodyStream = Symbol("wrapBodyStream");
928
+ const byteExactEncodings = /* @__PURE__ */ new Set([
929
+ "latin1",
930
+ "binary",
931
+ "hex",
932
+ "base64",
933
+ "base64url"
934
+ ]);
935
+ const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
936
+ const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
937
+ const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
938
+ const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
939
+ const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
940
+ const recordBodyBufferedBeforeDisconnect = (incoming) => {
941
+ if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
942
+ const incomingWithRecovery = incoming;
943
+ incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
944
+ };
945
+ const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
946
+ if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
947
+ const incomingWithRecovery = incoming;
948
+ if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
949
+ let result;
950
+ const errored = incoming.errored;
951
+ if (errored && errored.code !== "ECONNRESET") result = errored;
952
+ else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
953
+ else {
954
+ const bodyChunks = chunks ?? [];
955
+ const chunk = incoming.read();
956
+ if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
957
+ const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
958
+ result = buffer;
959
+ const contentLength = incoming.headers["content-length"];
960
+ if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
961
+ const expectedLength = Number(contentLength);
962
+ if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
963
+ }
758
964
  }
759
- return new Headers(headerRecord);
965
+ incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
966
+ return result;
967
+ };
968
+ const enqueueBufferedBody = (controller, buffered) => {
969
+ if (buffered instanceof Error) {
970
+ controller.error(buffered);
971
+ return;
972
+ }
973
+ if (buffered.length > 0) controller.enqueue(buffered);
974
+ controller.close();
760
975
  };
761
- const wrapBodyStream = Symbol("wrapBodyStream");
762
976
  const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
763
977
  const init = {
764
978
  method,
@@ -781,6 +995,13 @@ const newRequestFromIncoming = (method, url, headers, incoming, abortController)
781
995
  let reader;
782
996
  init.body = new ReadableStream({ async pull(controller) {
783
997
  try {
998
+ if (!reader) {
999
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
1000
+ if (buffered !== void 0) {
1001
+ enqueueBufferedBody(controller, buffered);
1002
+ return;
1003
+ }
1004
+ }
784
1005
  reader ||= Readable.toWeb(incoming).getReader();
785
1006
  const { done, value } = await reader.read();
786
1007
  if (done) controller.close();
@@ -789,7 +1010,13 @@ const newRequestFromIncoming = (method, url, headers, incoming, abortController)
789
1010
  controller.error(error);
790
1011
  }
791
1012
  } });
792
- } else init.body = Readable.toWeb(incoming);
1013
+ } else {
1014
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
1015
+ if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
1016
+ enqueueBufferedBody(controller, buffered);
1017
+ } });
1018
+ else init.body = Readable.toWeb(incoming);
1019
+ }
793
1020
  return new Request$1(url, init);
794
1021
  };
795
1022
  const getRequestCache = Symbol("getRequestCache");
@@ -831,8 +1058,10 @@ const normalizeIncomingMethod = (method) => {
831
1058
  case "GET":
832
1059
  case "HEAD":
833
1060
  case "OPTIONS":
1061
+ case "PATCH":
834
1062
  case "POST":
835
- case "PUT": return method;
1063
+ case "PUT":
1064
+ case "QUERY": return method;
836
1065
  }
837
1066
  const upper = method.toUpperCase();
838
1067
  switch (upper) {
@@ -877,11 +1106,23 @@ const readRawBodyIfAvailable = (request) => {
877
1106
  const incoming = request[incomingKey];
878
1107
  if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
879
1108
  };
1109
+ const normalizeAbortError = (request, incoming) => {
1110
+ if (incoming.errored) return incoming.errored;
1111
+ const reason = request[abortReasonKey];
1112
+ if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
1113
+ return /* @__PURE__ */ new Error("Client connection prematurely closed.");
1114
+ };
880
1115
  const readBodyDirect = (request) => {
881
1116
  if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
882
1117
  if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
883
1118
  const incoming = request[incomingKey];
884
- if (Readable.isDisturbed(incoming)) return rejectBodyUnusable();
1119
+ if (incoming.readableDidRead) return rejectBodyUnusable();
1120
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
1121
+ if (buffered !== void 0) {
1122
+ if (buffered instanceof Error) return Promise.reject(buffered);
1123
+ request[bodyBufferKey] = buffered;
1124
+ return Promise.resolve(buffered);
1125
+ }
885
1126
  const promise = new Promise((resolve, reject) => {
886
1127
  const chunks = [];
887
1128
  let settled = false;
@@ -891,8 +1132,22 @@ const readBodyDirect = (request) => {
891
1132
  cleanup();
892
1133
  callback();
893
1134
  };
1135
+ const recoverCompleteBodyAfterDisconnect = (error) => {
1136
+ const streamError = incoming.errored ?? error;
1137
+ if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
1138
+ finish(() => {
1139
+ const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
1140
+ if (recovered instanceof Error) reject(recovered);
1141
+ else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
1142
+ else {
1143
+ request[bodyBufferKey] = recovered;
1144
+ resolve(recovered);
1145
+ }
1146
+ });
1147
+ return true;
1148
+ };
894
1149
  const onData = (chunk) => {
895
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1150
+ chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
896
1151
  };
897
1152
  const onEnd = () => {
898
1153
  finish(() => {
@@ -902,6 +1157,7 @@ const readBodyDirect = (request) => {
902
1157
  });
903
1158
  };
904
1159
  const onError = (error) => {
1160
+ if (recoverCompleteBodyAfterDisconnect(error)) return;
905
1161
  finish(() => {
906
1162
  reject(error);
907
1163
  });
@@ -911,17 +1167,9 @@ const readBodyDirect = (request) => {
911
1167
  onEnd();
912
1168
  return;
913
1169
  }
1170
+ if (recoverCompleteBodyAfterDisconnect()) return;
914
1171
  finish(() => {
915
- if (incoming.errored) {
916
- reject(incoming.errored);
917
- return;
918
- }
919
- const reason = request[abortReasonKey];
920
- if (reason !== void 0) {
921
- reject(reason instanceof Error ? reason : new Error(String(reason)));
922
- return;
923
- }
924
- reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
1172
+ reject(normalizeAbortError(request, incoming));
925
1173
  });
926
1174
  };
927
1175
  const cleanup = () => {
@@ -1009,6 +1257,7 @@ Object.defineProperty(requestPrototype, "signal", { get() {
1009
1257
  "cache",
1010
1258
  "credentials",
1011
1259
  "destination",
1260
+ "duplex",
1012
1261
  "integrity",
1013
1262
  "mode",
1014
1263
  "redirect",
@@ -1065,6 +1314,7 @@ const newRequest = (incoming, defaultHostname) => {
1065
1314
  if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
1066
1315
  if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
1067
1316
  try {
1317
+ validateRequestTarget(incomingUrl);
1068
1318
  req[urlKey] = new URL(incomingUrl).href;
1069
1319
  } catch (e) {
1070
1320
  throw new RequestError("Invalid absolute URL", { cause: e });
@@ -1107,16 +1357,15 @@ var Response$1 = class Response$1 {
1107
1357
  constructor(body, init) {
1108
1358
  let headers;
1109
1359
  this.#body = body;
1110
- if (init instanceof Response$1) {
1360
+ if (init instanceof GlobalResponse) {
1111
1361
  const cachedGlobalResponse = init[responseCache];
1112
1362
  if (cachedGlobalResponse) {
1113
1363
  this.#init = cachedGlobalResponse;
1114
1364
  this[getResponseCache]();
1115
1365
  return;
1116
- } else {
1117
- this.#init = init.#init;
1118
- headers = new Headers(init.headers);
1119
1366
  }
1367
+ this.#init = init instanceof Response$1 ? init.#init : init;
1368
+ headers = new Headers(init.headers);
1120
1369
  } else this.#init = init;
1121
1370
  if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
1122
1371
  init?.status || 200,
@@ -1228,6 +1477,11 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
1228
1477
  const cancel = (error) => {
1229
1478
  reader.cancel(error).catch(() => {});
1230
1479
  };
1480
+ const stream = writable.stream;
1481
+ if (writable.destroyed || stream?.closed || stream?.destroyed) {
1482
+ cancel();
1483
+ return reader.closed;
1484
+ }
1231
1485
  writable.on("close", cancel);
1232
1486
  writable.on("error", cancel);
1233
1487
  (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
@@ -1245,7 +1499,7 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
1245
1499
  try {
1246
1500
  if (done) writable.end();
1247
1501
  else if (!writable.write(value)) writable.once("drain", onDrain);
1248
- else return reader.read().then(flow, handleStreamError);
1502
+ else reader.read().then(flow, handleStreamError);
1249
1503
  } catch (e) {
1250
1504
  handleStreamError(e);
1251
1505
  }
@@ -1253,7 +1507,10 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
1253
1507
  }
1254
1508
  function writeFromReadableStream(stream, writable) {
1255
1509
  if (stream.locked) throw new TypeError("ReadableStream is locked.");
1256
- else if (writable.destroyed) return;
1510
+ else if (writable.destroyed) {
1511
+ stream.cancel().catch(() => {});
1512
+ return;
1513
+ }
1257
1514
  return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
1258
1515
  }
1259
1516
  const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
@@ -1271,7 +1528,7 @@ const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
1271
1528
  const outgoingEnded = Symbol("outgoingEnded");
1272
1529
  const incomingDraining = Symbol("incomingDraining");
1273
1530
  const DRAIN_TIMEOUT_MS = 500;
1274
- const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
1531
+ const MAX_DRAIN_BYTES = 67108864;
1275
1532
  const drainIncoming = (incoming) => {
1276
1533
  const incomingWithDrainState = incoming;
1277
1534
  if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
@@ -1292,7 +1549,10 @@ const drainIncoming = (incoming) => {
1292
1549
  const forceClose = () => {
1293
1550
  cleanup();
1294
1551
  const socket = incoming.socket;
1295
- if (socket && !socket.destroyed) socket.destroySoon();
1552
+ if (socket && !socket.destroyed) {
1553
+ if (typeof socket.destroySoon === "function") socket.destroySoon();
1554
+ else if (typeof socket.destroy === "function") socket.destroy();
1555
+ }
1296
1556
  };
1297
1557
  const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
1298
1558
  timer.unref?.();
@@ -1306,8 +1566,13 @@ const drainIncoming = (incoming) => {
1306
1566
  incoming.resume();
1307
1567
  };
1308
1568
  const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
1309
- if (incoming.errored) req[abortRequest](incoming.errored.toString());
1310
- else if (!outgoing.writableFinished) req[abortRequest]("Client connection prematurely closed.");
1569
+ if (incoming.errored) {
1570
+ recordBodyBufferedBeforeDisconnect(incoming);
1571
+ req[abortRequest](incoming.errored.toString());
1572
+ } else if (!outgoing.writableFinished || incoming instanceof Http2ServerRequest && incoming.aborted) {
1573
+ recordBodyBufferedBeforeDisconnect(incoming);
1574
+ req[abortRequest]("Client connection prematurely closed.");
1575
+ }
1311
1576
  if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
1312
1577
  if (!incoming.readableEnded) setTimeout(() => {
1313
1578
  drainIncoming(incoming);
@@ -1326,7 +1591,10 @@ const handleResponseError = (e, outgoing) => {
1326
1591
  if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
1327
1592
  else {
1328
1593
  console.error(e);
1329
- if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
1594
+ if (!outgoing.headersSent) {
1595
+ if (outgoing instanceof ServerResponse) outgoing._contentLength = null;
1596
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
1597
+ }
1330
1598
  outgoing.end(`Error: ${err.message}`);
1331
1599
  outgoing.destroy(err);
1332
1600
  }
@@ -1334,6 +1602,21 @@ const handleResponseError = (e, outgoing) => {
1334
1602
  const flushHeaders = (outgoing) => {
1335
1603
  if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
1336
1604
  };
1605
+ const trySetContentLength = (outgoing, status, length) => {
1606
+ const http1 = outgoing;
1607
+ if (http1._contentLength === null && http1._hasBody && http1.useChunkedEncodingByDefault && !http1._removedContLen && status >= 200 && status !== 204 && status !== 304 && !outgoing.hasHeader("content-length") && !outgoing.hasHeader("transfer-encoding") && !outgoing.hasHeader("trailer")) {
1608
+ http1._contentLength = length;
1609
+ return true;
1610
+ }
1611
+ return false;
1612
+ };
1613
+ const writeDefaultHeaders = (outgoing, status, length) => {
1614
+ if (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { "Content-Type": defaultContentType });
1615
+ else outgoing.writeHead(status, {
1616
+ "Content-Type": defaultContentType,
1617
+ "Content-Length": length
1618
+ });
1619
+ };
1337
1620
  const responseViaCache = async (res, outgoing) => {
1338
1621
  let [status, body, header] = res[cacheKey];
1339
1622
  if (!header) {
@@ -1341,22 +1624,13 @@ const responseViaCache = async (res, outgoing) => {
1341
1624
  outgoing.writeHead(status);
1342
1625
  outgoing.end();
1343
1626
  } else if (typeof body === "string") {
1344
- outgoing.writeHead(status, {
1345
- "Content-Type": defaultContentType,
1346
- "Content-Length": Buffer.byteLength(body)
1347
- });
1627
+ writeDefaultHeaders(outgoing, status, Buffer.byteLength(body));
1348
1628
  outgoing.end(body);
1349
1629
  } else if (body instanceof Uint8Array) {
1350
- outgoing.writeHead(status, {
1351
- "Content-Type": defaultContentType,
1352
- "Content-Length": body.byteLength
1353
- });
1630
+ writeDefaultHeaders(outgoing, status, body.byteLength);
1354
1631
  outgoing.end(body);
1355
1632
  } else if (body instanceof Blob) {
1356
- outgoing.writeHead(status, {
1357
- "Content-Type": defaultContentType,
1358
- "Content-Length": body.size
1359
- });
1633
+ writeDefaultHeaders(outgoing, status, body.size);
1360
1634
  outgoing.end(new Uint8Array(await body.arrayBuffer()));
1361
1635
  } else {
1362
1636
  outgoing.writeHead(status, { "Content-Type": defaultContentType });
@@ -1367,6 +1641,8 @@ const responseViaCache = async (res, outgoing) => {
1367
1641
  return;
1368
1642
  }
1369
1643
  let hasContentLength = false;
1644
+ let plainHeaders = false;
1645
+ let canAutoLength = true;
1370
1646
  if (header instanceof Headers) {
1371
1647
  hasContentLength = header.has("content-length");
1372
1648
  header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
@@ -1374,14 +1650,25 @@ const responseViaCache = async (res, outgoing) => {
1374
1650
  const headerObj = new Headers(header);
1375
1651
  hasContentLength = headerObj.has("content-length");
1376
1652
  header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
1377
- } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
1378
- hasContentLength = true;
1379
- break;
1653
+ } else {
1654
+ plainHeaders = true;
1655
+ for (const key in header) {
1656
+ if (key.length === 14 && key.toLowerCase() === "content-length") {
1657
+ hasContentLength = true;
1658
+ break;
1659
+ }
1660
+ if (key.length === 17 && key.toLowerCase() === "transfer-encoding" || key.length === 7 && key.toLowerCase() === "trailer") canAutoLength = false;
1661
+ }
1380
1662
  }
1381
1663
  if (!hasContentLength) {
1382
- if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
1383
- else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
1384
- else if (body instanceof Blob) header["Content-Length"] = body.size;
1664
+ let length;
1665
+ if (typeof body === "string") length = Buffer.byteLength(body);
1666
+ else if (body instanceof Uint8Array) length = body.byteLength;
1667
+ else if (body instanceof Blob) length = body.size;
1668
+ if (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) {
1669
+ if (plainHeaders) header = { ...header };
1670
+ header["Content-Length"] = length;
1671
+ }
1385
1672
  }
1386
1673
  outgoing.writeHead(status, header);
1387
1674
  if (body == null) outgoing.end();
@@ -1414,10 +1701,7 @@ const responseViaResponseObject = async (res, outgoing, options = {}) => {
1414
1701
  let maxReadCount = 2;
1415
1702
  for (let i = 0; i < maxReadCount; i++) {
1416
1703
  currentReadPromise ||= reader.read();
1417
- const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
1418
- console.error(e);
1419
- done = true;
1420
- });
1704
+ const chunk = await readWithoutBlocking(currentReadPromise);
1421
1705
  if (!chunk) {
1422
1706
  if (i === 1) {
1423
1707
  await new Promise((resolve) => setTimeout(resolve));
@@ -1507,6 +1791,7 @@ const getRequestListener = (fetchCallback, options = {}) => {
1507
1791
  };
1508
1792
  };
1509
1793
  globalThis.CloseEvent;
1794
+ globalThis.ErrorEvent;
1510
1795
  const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
1511
1796
  const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
1512
1797
  const responseHeadersToSkip = /* @__PURE__ */ new Set([
@@ -1531,6 +1816,7 @@ const appendResponseHeaders = (headers, responseHeaders) => {
1531
1816
  });
1532
1817
  };
1533
1818
  const rejectUpgradeRequest = (socket, status, responseHeaders) => {
1819
+ if (socket.destroyed) return;
1534
1820
  const responseLines = ["Connection: close", "Content-Length: 0"];
1535
1821
  appendResponseHeaders(responseLines, responseHeaders);
1536
1822
  socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
@@ -1538,7 +1824,12 @@ const rejectUpgradeRequest = (socket, status, responseHeaders) => {
1538
1824
  };
1539
1825
  const createUpgradeRequest = (request) => {
1540
1826
  const protocol = request.socket.encrypted ? "https" : "http";
1541
- const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
1827
+ const incomingUrl = request.url ?? "/";
1828
+ let url;
1829
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
1830
+ validateRequestTarget(incomingUrl);
1831
+ url = new URL(incomingUrl).href;
1832
+ } else url = buildUrl(protocol, request.headers.host ?? "localhost", incomingUrl);
1542
1833
  const headers = new Headers();
1543
1834
  for (const key in request.headers) {
1544
1835
  const value = request.headers[key];
@@ -1557,16 +1848,28 @@ const setupWebSocket = (options) => {
1557
1848
  waiterMap.delete(request);
1558
1849
  }
1559
1850
  });
1851
+ const rejectWaiter = (request) => {
1852
+ const waiter = waiterMap.get(request);
1853
+ if (waiter) {
1854
+ waiterMap.delete(request);
1855
+ waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted"));
1856
+ }
1857
+ };
1560
1858
  const waitForWebSocket = (request, connectionSymbol) => {
1561
- return new Promise((resolve) => {
1859
+ return new Promise((resolve, reject) => {
1562
1860
  waiterMap.set(request, {
1563
1861
  resolve,
1862
+ reject,
1564
1863
  connectionSymbol
1565
1864
  });
1566
1865
  });
1567
1866
  };
1568
1867
  server.on("upgrade", async (request, socket, head) => {
1569
1868
  if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
1869
+ const ignoreSocketError = () => {};
1870
+ const reclaimWaiterOnClose = () => rejectWaiter(request);
1871
+ socket.on("error", ignoreSocketError);
1872
+ socket.once("close", reclaimWaiterOnClose);
1570
1873
  const env = {
1571
1874
  incoming: request,
1572
1875
  outgoing: void 0,
@@ -1581,13 +1884,17 @@ const setupWebSocket = (options) => {
1581
1884
  status = response.status;
1582
1885
  responseHeaders = response.headers;
1583
1886
  }
1584
- } catch {
1585
- if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
1887
+ } catch (error) {
1888
+ if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, error instanceof RequestError ? 400 : 500);
1889
+ return;
1890
+ }
1891
+ if (socket.destroyed) {
1892
+ rejectWaiter(request);
1586
1893
  return;
1587
1894
  }
1588
1895
  const waiter = waiterMap.get(request);
1589
1896
  if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
1590
- waiterMap.delete(request);
1897
+ rejectWaiter(request);
1591
1898
  if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
1592
1899
  return;
1593
1900
  }
@@ -1597,6 +1904,8 @@ const setupWebSocket = (options) => {
1597
1904
  wss.on("headers", addResponseHeaders);
1598
1905
  try {
1599
1906
  wss.handleUpgrade(request, socket, head, (ws) => {
1907
+ socket.off("close", reclaimWaiterOnClose);
1908
+ socket.off("error", ignoreSocketError);
1600
1909
  wss.emit("connection", ws, request);
1601
1910
  });
1602
1911
  } finally {
@@ -1625,24 +1934,15 @@ const createAdaptorServer = (options) => {
1625
1934
  }
1626
1935
  return server;
1627
1936
  };
1628
- const serve = (options, listeningListener) => {
1629
- const server = createAdaptorServer(options);
1630
- server.listen(options?.port ?? 3e3, options.hostname, () => {
1631
- const serverInfo = server.address();
1632
- listeningListener && listeningListener(serverInfo);
1633
- });
1634
- return server;
1635
- };
1636
- //#endregion
1637
- //#region packages/adapter-node/src/middleware/body-cap.ts
1937
+ // packages/adapter-node/src/middleware/body-cap.ts
1638
1938
  /**
1639
1939
  * Body-cap enforcement for Node-hosted requests. Replaces the
1640
1940
  * pre-pivot `bodyCapMiddleware` that attached `incoming.on("data",
1641
1941
  * ...)` — that listener raced with `@hono/node-server`'s own body
1642
1942
  * reader and dropped the first chunks of every POST. Wrapping
1643
1943
  * `req.body` with a counting `TransformStream` puts the cap in the
1644
- * same reader chain as the kernel router's `c.req.arrayBuffer()`
1645
- * consumer, so there is no race.
1944
+ * same reader chain as the kernel router's `readJsonBody`, which
1945
+ * reads `c.req.raw.body` itself, so there is no race.
1646
1946
  *
1647
1947
  * Two cap-trip paths, both drain the upstream `IncomingMessage`
1648
1948
  * (`resume()`) so the client's body write completes and the 413
@@ -1702,8 +2002,7 @@ function cap413(max) {
1702
2002
  headers: { "content-type": "application/json" }
1703
2003
  });
1704
2004
  }
1705
- //#endregion
1706
- //#region packages/adapter-node/src/middleware/dev-landing.ts
2005
+ // packages/adapter-node/src/middleware/dev-landing.ts
1707
2006
  /**
1708
2007
  * Opt-in dev landing-page short-circuit. Serves `GET /` with a
1709
2008
  * human-readable HTML page that links to the configured UI URL, and
@@ -1714,10 +2013,6 @@ function cap413(max) {
1714
2013
  * by {@link createApp} (in `app.ts`) ahead of `staticAssetsMiddleware`
1715
2014
  * so the dev short-circuit wins over any on-disk `index.html` /
1716
2015
  * `favicon.ico` that might live in `webRoot`.
1717
- *
1718
- * Mirrors the imperative dev-landing block in
1719
- * `packages/adapter-node/src/server.ts` (which the hand-rolled
1720
- * `handle()` bridge still uses until the bridge cutover).
1721
2016
  */
1722
2017
  function devLandingMiddleware(opts) {
1723
2018
  return async (c, next) => {
@@ -1737,159 +2032,369 @@ function devLandingMiddleware(opts) {
1737
2032
  return next();
1738
2033
  };
1739
2034
  }
1740
- //#endregion
1741
- //#region packages/adapter-node/src/middleware/static-assets.ts
2035
+ // node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/utils/stream.mjs
2036
+ const pr54206Applied = () => {
2037
+ const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
2038
+ return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
2039
+ };
2040
+ const useReadableToWeb = pr54206Applied();
2041
+ const createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {
2042
+ if (useNativeReadableToWeb) return Readable.toWeb(stream);
2043
+ let controller;
2044
+ let settled = false;
2045
+ const cleanup = () => {
2046
+ stream.off("data", onData);
2047
+ stream.off("error", onError);
2048
+ stream.off("end", onTerminate);
2049
+ stream.off("close", onTerminate);
2050
+ };
2051
+ const settle = (callback) => {
2052
+ if (settled) return;
2053
+ settled = true;
2054
+ cleanup();
2055
+ callback?.();
2056
+ };
2057
+ const onData = (chunk) => {
2058
+ if (settled || !controller) return;
2059
+ controller.enqueue(chunk);
2060
+ if ((controller.desiredSize ?? 0) <= 0) stream.pause();
2061
+ };
2062
+ const onError = (error) => {
2063
+ settle(() => {
2064
+ controller?.error(error);
2065
+ });
2066
+ };
2067
+ const onTerminate = () => {
2068
+ settle(() => {
2069
+ controller?.close();
2070
+ });
2071
+ };
2072
+ return new ReadableStream({
2073
+ start(streamController) {
2074
+ controller = streamController;
2075
+ stream.on("data", onData);
2076
+ stream.on("error", onError);
2077
+ stream.on("end", onTerminate);
2078
+ stream.on("close", onTerminate);
2079
+ stream.pause();
2080
+ },
2081
+ pull() {
2082
+ if (!settled) stream.resume();
2083
+ },
2084
+ cancel() {
2085
+ settle();
2086
+ const ignoreError = () => {};
2087
+ stream.on("error", ignoreError);
2088
+ stream.once("close", () => stream.off("error", ignoreError));
2089
+ stream.destroy();
2090
+ }
2091
+ });
2092
+ };
2093
+ // node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/mime.js
1742
2094
  /**
1743
- * Map a file extension to its `Content-Type`. The set is deliberately
1744
- * small — every entry corresponds to something Vite or a typical SPA
1745
- * pipeline actually emits. Unknown extensions fall back to
1746
- * `application/octet-stream`, which keeps the browser from sniffing
1747
- * untrusted bytes as HTML.
2095
+ * @module
2096
+ * MIME utility.
1748
2097
  */
1749
- const MIME_TYPES = {
1750
- ".html": "text/html; charset=utf-8",
1751
- ".js": "text/javascript; charset=utf-8",
1752
- ".mjs": "text/javascript; charset=utf-8",
1753
- ".css": "text/css; charset=utf-8",
1754
- ".json": "application/json; charset=utf-8",
1755
- ".svg": "image/svg+xml",
1756
- ".png": "image/png",
1757
- ".jpg": "image/jpeg",
1758
- ".jpeg": "image/jpeg",
1759
- ".gif": "image/gif",
1760
- ".webp": "image/webp",
1761
- ".ico": "image/x-icon",
1762
- ".woff": "font/woff",
1763
- ".woff2": "font/woff2",
1764
- ".ttf": "font/ttf",
1765
- ".txt": "text/plain; charset=utf-8",
1766
- ".map": "application/json; charset=utf-8"
2098
+ const getMimeType = (filename, mimes = baseMimes) => {
2099
+ const match = filename.match(/\.([a-zA-Z0-9]+?)$/);
2100
+ if (!match) return;
2101
+ return mimes[match[1].toLowerCase()];
2102
+ };
2103
+ const baseMimes = {
2104
+ aac: "audio/aac",
2105
+ avi: "video/x-msvideo",
2106
+ avif: "image/avif",
2107
+ av1: "video/av1",
2108
+ bin: "application/octet-stream",
2109
+ bmp: "image/bmp",
2110
+ css: "text/css; charset=utf-8",
2111
+ csv: "text/csv; charset=utf-8",
2112
+ eot: "application/vnd.ms-fontobject",
2113
+ epub: "application/epub+zip",
2114
+ gif: "image/gif",
2115
+ gz: "application/gzip",
2116
+ htm: "text/html; charset=utf-8",
2117
+ html: "text/html; charset=utf-8",
2118
+ ico: "image/x-icon",
2119
+ ics: "text/calendar; charset=utf-8",
2120
+ jpeg: "image/jpeg",
2121
+ jpg: "image/jpeg",
2122
+ js: "text/javascript; charset=utf-8",
2123
+ json: "application/json",
2124
+ jsonld: "application/ld+json",
2125
+ map: "application/json",
2126
+ mid: "audio/x-midi",
2127
+ midi: "audio/x-midi",
2128
+ mjs: "text/javascript; charset=utf-8",
2129
+ mp3: "audio/mpeg",
2130
+ mp4: "video/mp4",
2131
+ mpeg: "video/mpeg",
2132
+ oga: "audio/ogg",
2133
+ ogv: "video/ogg",
2134
+ ogx: "application/ogg",
2135
+ opus: "audio/opus",
2136
+ otf: "font/otf",
2137
+ pdf: "application/pdf",
2138
+ png: "image/png",
2139
+ rtf: "application/rtf",
2140
+ svg: "image/svg+xml; charset=utf-8",
2141
+ tif: "image/tiff",
2142
+ tiff: "image/tiff",
2143
+ ts: "video/mp2t",
2144
+ ttf: "font/ttf",
2145
+ txt: "text/plain; charset=utf-8",
2146
+ wasm: "application/wasm",
2147
+ webm: "video/webm",
2148
+ weba: "audio/webm",
2149
+ webmanifest: "application/manifest+json",
2150
+ webp: "image/webp",
2151
+ woff: "font/woff",
2152
+ woff2: "font/woff2",
2153
+ xhtml: "application/xhtml+xml; charset=utf-8",
2154
+ xml: "application/xml; charset=utf-8",
2155
+ zip: "application/zip",
2156
+ "3gp": "video/3gpp",
2157
+ "3g2": "video/3gpp2",
2158
+ gltf: "model/gltf+json",
2159
+ glb: "model/gltf-binary"
2160
+ };
2161
+ // node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/serve-static.mjs
2162
+ const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
2163
+ const ENCODINGS = {
2164
+ br: ".br",
2165
+ zstd: ".zst",
2166
+ gzip: ".gz"
2167
+ };
2168
+ const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
2169
+ const getStats = (path) => {
2170
+ let stats;
2171
+ try {
2172
+ stats = statSync(path);
2173
+ } catch {}
2174
+ return stats;
2175
+ };
2176
+ const BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\d*)-(\d*)$/;
2177
+ const parseByteRange = (range) => {
2178
+ const match = range.match(BYTE_RANGE_PATTERN);
2179
+ if (!match) return;
2180
+ const [, start, end] = match;
2181
+ if (start === "") return {
2182
+ type: "suffix",
2183
+ length: Number(end)
2184
+ };
2185
+ if (end === "") return {
2186
+ type: "open-ended",
2187
+ start: Number(start)
2188
+ };
2189
+ return {
2190
+ type: "bounded",
2191
+ start: Number(start),
2192
+ end: Number(end)
2193
+ };
2194
+ };
2195
+ const resolveByteRange = (spec, size) => {
2196
+ if (size === 0) return;
2197
+ if (spec.type === "suffix") {
2198
+ if (spec.length === 0) return;
2199
+ return {
2200
+ start: Math.max(size - spec.length, 0),
2201
+ end: size - 1
2202
+ };
2203
+ }
2204
+ const end = spec.type === "bounded" ? Math.min(spec.end, size - 1) : size - 1;
2205
+ if (spec.start >= size || spec.start > end) return;
2206
+ return {
2207
+ start: spec.start,
2208
+ end
2209
+ };
2210
+ };
2211
+ const tryDecode = (str, decoder) => {
2212
+ try {
2213
+ return decoder(str);
2214
+ } catch {
2215
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
2216
+ try {
2217
+ return decoder(match);
2218
+ } catch {
2219
+ return match;
2220
+ }
2221
+ });
2222
+ }
1767
2223
  };
2224
+ const tryDecodeURI = (str) => tryDecode(str, decodeURI);
2225
+ const serveStatic = (options = { root: "" }) => {
2226
+ const root = options.root || "";
2227
+ const optionPath = options.path;
2228
+ if (root !== "" && !existsSync(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
2229
+ return async (c, next) => {
2230
+ if (c.finalized) return next();
2231
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") return next();
2232
+ let filename;
2233
+ if (optionPath) filename = optionPath;
2234
+ else try {
2235
+ filename = tryDecodeURI(c.req.path);
2236
+ if (c.req.path.includes("%") && (!options.allowPercentInPath || filename !== c.req.path.replace(/%25/g, "%"))) throw new Error();
2237
+ if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) throw new Error();
2238
+ } catch {
2239
+ await options.onNotFound?.(c.req.path, c);
2240
+ return next();
2241
+ }
2242
+ let path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);
2243
+ let stats = getStats(path);
2244
+ if (stats && stats.isDirectory()) {
2245
+ const indexFile = options.index ?? "index.html";
2246
+ path = join(path, indexFile);
2247
+ stats = getStats(path);
2248
+ }
2249
+ if (!stats) {
2250
+ await options.onNotFound?.(path, c);
2251
+ return next();
2252
+ }
2253
+ const mimeType = getMimeType(path);
2254
+ c.header("Content-Type", mimeType || "application/octet-stream");
2255
+ if (options.precompressed && (!mimeType || mimeType === "application/octet-stream" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
2256
+ const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
2257
+ for (const encoding of ENCODINGS_ORDERED_KEYS) {
2258
+ if (!acceptEncodingSet.has(encoding)) continue;
2259
+ const precompressedStats = getStats(path + ENCODINGS[encoding]);
2260
+ if (precompressedStats) {
2261
+ c.header("Content-Encoding", encoding);
2262
+ c.header("Vary", "Accept-Encoding", { append: true });
2263
+ stats = precompressedStats;
2264
+ path = path + ENCODINGS[encoding];
2265
+ break;
2266
+ }
2267
+ }
2268
+ }
2269
+ let result;
2270
+ const size = stats.size;
2271
+ const range = c.req.header("range") || "";
2272
+ c.header("Last-Modified", stats.mtime.toUTCString());
2273
+ if (c.req.method === "HEAD") {
2274
+ c.header("Content-Length", size.toString());
2275
+ c.status(200);
2276
+ result = c.body(null);
2277
+ } else if (!range) {
2278
+ c.header("Content-Length", size.toString());
2279
+ result = c.body(createStreamBody(createReadStream(path)), 200);
2280
+ } else {
2281
+ c.header("Accept-Ranges", "bytes");
2282
+ const resolvedRange = resolveByteRange(parseByteRange(range) ?? {
2283
+ type: "open-ended",
2284
+ start: 0
2285
+ }, size);
2286
+ if (!resolvedRange) {
2287
+ c.header("Content-Range", `bytes */${size}`);
2288
+ result = c.body(null, 416);
2289
+ } else {
2290
+ const { start, end } = resolvedRange;
2291
+ const chunkSize = end - start + 1;
2292
+ const stream = createReadStream(path, {
2293
+ start,
2294
+ end
2295
+ });
2296
+ c.header("Content-Length", chunkSize.toString());
2297
+ c.header("Content-Range", `bytes ${start}-${end}/${size}`);
2298
+ result = c.body(createStreamBody(stream), 206);
2299
+ }
2300
+ }
2301
+ await options.onFound?.(path, c);
2302
+ return result;
2303
+ };
2304
+ };
2305
+ // packages/adapter-node/src/middleware/static-assets.ts
1768
2306
  /**
1769
- * Serve files from `webRoot` for GET/HEAD requests that miss `/v1/*`.
1770
- *
1771
- * HTML navigation (`Accept: text/html`) that misses an on-disk file
1772
- * falls back to `<webRoot>/index.html` (SPA shell). Non-HTML misses
1773
- * pass through `next()` so the cascade emits its 404 envelope.
2307
+ * Serve files from `webRoot` for GET/HEAD requests that miss `/v1/*`,
2308
+ * via `@hono/node-server/serve-static`.
1774
2309
  *
1775
- * Path resolution rejects `..` segments and absolute paths so the
1776
- * middleware can't escape `webRoot`. Pure `node:fs` + `node:path` —
1777
- * no new dependency.
2310
+ * That handler owns MIME types, `Content-Length`, `Last-Modified`,
2311
+ * Range requests, and request-path validation, falling through to the
2312
+ * cascade's 404 envelope on a rejected path. Hono hands it the path
2313
+ * already `decodeURI`'d, so `%20` and UTF-8 escapes name ordinary
2314
+ * files. What still holds a `%` after that decode is an encoded
2315
+ * reserved character (`%2F`, `%3F`, `%23`) or a literal `%` (`%25`),
2316
+ * and those are rejected, as are `.`/`..` segments and repeated or
2317
+ * back-slashes. This wrapper adds what it does not:
1778
2318
  *
1779
- * The response body is built as
1780
- * `new Response(Readable.toWeb(createReadStream(...)))`, keeping the
1781
- * middleware Fetch-shaped so it composes cleanly with other Hono
1782
- * middleware. The actual byte pump runs through
1783
- * `@hono/node-server`'s response writer, which handles backpressure +
1784
- * client-disconnect cleanly.
1785
- *
1786
- * Mirrors the imperative `serveStaticAsset` in
1787
- * `packages/adapter-node/src/server.ts` (which the hand-rolled
1788
- * `handle()` bridge still uses until T04 cuts over).
2319
+ * - Dotfiles and dot-directories (`/.env`, `/.git/config`) fall
2320
+ * through, except `/.well-known/*`.
2321
+ * - A file whose real path (after symlinks) leaves `webRoot` falls
2322
+ * through.
2323
+ * - HTML navigation (`Accept: text/html`) that misses on disk gets
2324
+ * `<webRoot>/index.html` (SPA shell). Other misses fall through.
2325
+ * - `Cache-Control`: `public, max-age=3600` under `assets/` (Vite's
2326
+ * hashed bundles), `no-cache` everywhere else.
1789
2327
  */
1790
2328
  function staticAssetsMiddleware(opts) {
2329
+ const root = resolve(opts.webRoot);
2330
+ const onFound = (path, c) => {
2331
+ const rel = relative(root, resolve(path)).split(sep).join("/");
2332
+ c.header("Cache-Control", rel.startsWith("assets/") ? "public, max-age=3600" : "no-cache");
2333
+ };
2334
+ const files = serveStatic({
2335
+ root,
2336
+ rewriteRequestPath: (path) => servesFromRoot(root, path) ? path : UNSERVABLE,
2337
+ onFound
2338
+ });
2339
+ const shell = serveStatic({
2340
+ root,
2341
+ path: "index.html",
2342
+ onFound
2343
+ });
1791
2344
  return async (c, next) => {
1792
2345
  const method = c.req.method;
1793
- if (method !== "GET" && method !== "HEAD") return next();
1794
- const path = new URL(c.req.url).pathname;
1795
- if (path.startsWith("/v1/")) return next();
1796
- const resolved = resolveUnderWebRoot(path, opts.webRoot);
1797
- if (resolved === null) return next();
1798
- const resolution = await resolveStaticTarget(resolved, opts.webRoot, c.req.header("accept"));
1799
- if (resolution === null) return next();
1800
- const { target, stats } = resolution;
1801
- const contentType = MIME_TYPES[extname(target).toLowerCase()] ?? "application/octet-stream";
1802
- const cacheControl = relative(opts.webRoot, target).split(sep).join("/").startsWith("assets/") && target !== resolve(opts.webRoot, "index.html") ? "public, max-age=3600" : "no-cache";
1803
- const headers = {
1804
- "content-type": contentType,
1805
- "content-length": String(stats.size),
1806
- "cache-control": cacheControl
1807
- };
1808
- if (method === "HEAD") return new Response(null, {
1809
- status: 200,
1810
- headers
1811
- });
1812
- const nodeWeb = Readable.toWeb(createReadStream(target));
1813
- return new Response(nodeWeb, {
1814
- status: 200,
1815
- headers
2346
+ if (method !== "GET" && method !== "HEAD" || c.req.path.startsWith("/v1/")) return next();
2347
+ if (hasDotSegment(c.req.path)) return next();
2348
+ return files(c, async () => {
2349
+ if (c.req.header("accept")?.includes("text/html") !== true || !servesFromRoot(root, "index.html")) {
2350
+ await next();
2351
+ return;
2352
+ }
2353
+ const res = await shell(c, next);
2354
+ if (res !== void 0) c.res = res;
1816
2355
  });
1817
2356
  };
1818
2357
  }
1819
- /**
1820
- * Resolve a request path under `webRoot` without allowing `..` escape
1821
- * or absolute-segment hijacking. Returns the resolved absolute path on
1822
- * success, or `null` when the request should fall through (traversal
1823
- * attempt, NUL byte, malformed URL encoding).
1824
- */
1825
- function resolveUnderWebRoot(reqPath, webRoot) {
1826
- let relative$1 = reqPath;
1827
- if (relative$1 === "" || relative$1 === "/") relative$1 = "/index.html";
1828
- else if (relative$1.endsWith("/")) relative$1 = `${relative$1}index.html`;
1829
- if (relative$1.includes("\0")) return null;
1830
- const segments = [];
1831
- for (const raw of relative$1.split("/")) {
1832
- if (raw === "") continue;
1833
- let decoded;
1834
- try {
1835
- decoded = decodeURIComponent(raw);
1836
- } catch {
1837
- return null;
1838
- }
1839
- if (decoded === "" || decoded === ".") continue;
1840
- if (decoded === "..") return null;
1841
- if (decoded.includes("\0")) return null;
1842
- if (decoded.includes("/") || decoded.includes("\\")) return null;
1843
- segments.push(decoded);
1844
- }
1845
- const resolved = resolve(webRoot, ...segments);
1846
- const rel = relative(webRoot, resolved);
1847
- if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) return null;
1848
- return resolved;
2358
+ /** A path `statSync` rejects (NUL byte), so `serveStatic` treats it as a miss. */
2359
+ const UNSERVABLE = "/\0";
2360
+ /** `.well-known` is the one dot-directory a web app is expected to publish (RFC 8615). */
2361
+ function hasDotSegment(path) {
2362
+ return path.split("/").some((segment) => segment.startsWith(".") && segment !== ".well-known");
1849
2363
  }
1850
2364
  /**
1851
- * Determine whether the request should fall back to `index.html` on a
1852
- * filesystem miss. Browsers send `Accept: text/html,...` for SPA
1853
- * navigations; programmatic `fetch()` calls for missing JSON / image
1854
- * assets do not, and they get the kernel's 404 envelope instead.
2365
+ * True when `requestPath` (already validated by `serveStatic`) names a
2366
+ * missing file, or an existing file or directory whose real path stays
2367
+ * inside `root`. For a directory, its `index.html` is checked too,
2368
+ * since that is what `serveStatic` opens.
1855
2369
  */
1856
- function wantsHtmlFallback(accept) {
1857
- if (typeof accept !== "string") return false;
1858
- return accept.includes("text/html");
2370
+ function servesFromRoot(root, requestPath) {
2371
+ const target = join(root, requestPath);
2372
+ const realRoot = realpathOrNull(root);
2373
+ if (realRoot === null) return true;
2374
+ const candidates = [target];
2375
+ if (isDirectory(target)) candidates.push(join(target, "index.html"));
2376
+ return candidates.every((candidate) => {
2377
+ const real = realpathOrNull(candidate);
2378
+ if (real === null) return true;
2379
+ const rel = relative(realRoot, real);
2380
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
2381
+ });
1859
2382
  }
1860
- async function resolveStaticTarget(resolved, webRoot, accept) {
1861
- const primary = await statFile(resolved);
1862
- if (primary !== null) return {
1863
- target: resolved,
1864
- stats: primary
1865
- };
1866
- if (!wantsHtmlFallback(accept)) return null;
1867
- const indexPath = resolve(webRoot, "index.html");
1868
- const fallback = await statFile(indexPath);
1869
- if (fallback === null) return null;
1870
- return {
1871
- target: indexPath,
1872
- stats: fallback
1873
- };
2383
+ function realpathOrNull(path) {
2384
+ try {
2385
+ return realpathSync(path);
2386
+ } catch {
2387
+ return null;
2388
+ }
1874
2389
  }
1875
- /**
1876
- * `fs.stat` that returns `null` for the missing-file cases that this
1877
- * handler treats as a fall-through (ENOENT / ENOTDIR / non-file).
1878
- * Other errors (EACCES, EIO, ...) propagate.
1879
- */
1880
- async function statFile(target) {
2390
+ function isDirectory(path) {
1881
2391
  try {
1882
- const stats = await stat(target);
1883
- return stats.isFile() ? stats : null;
1884
- } catch (error) {
1885
- const code = error.code;
1886
- if (code === "ENOENT" || code === "ENOTDIR") return null;
1887
- throw error;
2392
+ return statSync(path).isDirectory();
2393
+ } catch {
2394
+ return false;
1888
2395
  }
1889
2396
  }
1890
- //#endregion
1891
- //#region packages/adapter-node/src/logger-pretty.ts
1892
- var import_picocolors_browser = require_picocolors_browser();
2397
+ // packages/adapter-node/src/logger-pretty.ts
1893
2398
  /**
1894
2399
  * Metric keys the pretty sink reads off the canonical-line record.
1895
2400
  * These names match `RequestScopedMetricsRecorder.summarize()` output
@@ -1901,8 +2406,7 @@ const CANONICAL_KEYS = {
1901
2406
  classB: "db.storage.class_b_ops_total",
1902
2407
  wamp: "db.write.class_a_ops_per_logical_write_sum",
1903
2408
  put412: "db.r2.put.412_total",
1904
- put429: "db.r2.put.429_total",
1905
- cacheStatus: "cache_status"
2409
+ put429: "db.r2.put.429_total"
1906
2410
  };
1907
2411
  /**
1908
2412
  * Fixed-width column sizes for the pretty sink's HTTP line.
@@ -1916,6 +2420,15 @@ const numProp = (props, key) => {
1916
2420
  const v = pickProp(props, key);
1917
2421
  return typeof v === "number" ? v : void 0;
1918
2422
  };
2423
+ const createColors = (enabled) => {
2424
+ const paint = (format) => (s) => enabled ? styleText(format, s, { validateStream: false }) : s;
2425
+ return {
2426
+ red: paint("red"),
2427
+ yellow: paint("yellow"),
2428
+ cyan: paint("cyan"),
2429
+ dim: paint("dim")
2430
+ };
2431
+ };
1919
2432
  const colorStatus = (statusStr, status, plain, pc) => {
1920
2433
  if (plain || status === void 0) return statusStr;
1921
2434
  if (status >= 500) return pc.red(statusStr);
@@ -1932,7 +2445,7 @@ const renderCanonical = (record, pc, plain) => {
1932
2445
  const status = numProp(props, "status");
1933
2446
  const method = typeof pickProp(props, "method") === "string" ? String(pickProp(props, "method")) : "";
1934
2447
  const path = typeof pickProp(props, "path") === "string" ? String(pickProp(props, "path")) : "";
1935
- const prefix = `${method.padEnd(METHOD_W)}${path.length > PATH_W ? `${path.slice(0, PATH_W - 1)}…` : path.padEnd(PATH_W)} ${colorStatus(status === void 0 ? " " : String(status), status, plain, pc)} ${durationStr}`;
2448
+ const prefix = `${method.padEnd(METHOD_W)}${path.length > PATH_W ? `${path.slice(0, 27)}…` : path.padEnd(PATH_W)} ${colorStatus(status === void 0 ? " " : String(status), status, plain, pc)} ${durationStr}`;
1936
2449
  const tail = [];
1937
2450
  if (reqId) tail.push(`req=${reqId}`);
1938
2451
  const classA = numProp(props, CANONICAL_KEYS.classA);
@@ -1945,8 +2458,6 @@ const renderCanonical = (record, pc, plain) => {
1945
2458
  if (c412 !== void 0 && c412 > 0) tail.push(`412=${c412}`);
1946
2459
  const c429 = numProp(props, CANONICAL_KEYS.put429);
1947
2460
  if (c429 !== void 0 && c429 > 0) tail.push(`429=${c429}`);
1948
- const cacheStatus = pickProp(props, CANONICAL_KEYS.cacheStatus);
1949
- if (typeof cacheStatus === "string") tail.push(`cache=${cacheStatus}`);
1950
2461
  if (status !== void 0 && status >= 400) {
1951
2462
  const outcome = pickProp(props, "outcome");
1952
2463
  if (typeof outcome === "string") tail.push(`outcome=${outcome}`);
@@ -1974,7 +2485,7 @@ const isPlainEnv = () => {
1974
2485
  */
1975
2486
  const prettyConsoleSink = () => {
1976
2487
  const plain = isPlainEnv();
1977
- const pc = (0, import_picocolors_browser.createColors)(!plain);
2488
+ const pc = createColors(!plain);
1978
2489
  return (record) => {
1979
2490
  if (isCanonicalRecord(record)) {
1980
2491
  console.log(renderCanonical(record, pc, plain));
@@ -1987,8 +2498,7 @@ const prettyConsoleSink = () => {
1987
2498
  console.log(`${ts} ${record.level.toUpperCase()} ${cat} ${msg}${props}`);
1988
2499
  };
1989
2500
  };
1990
- //#endregion
1991
- //#region packages/adapter-node/src/server.ts
2501
+ // packages/adapter-node/src/server.ts
1992
2502
  /**
1993
2503
  * Assemble the per-request {@link MaintenanceDispatch} for a Node host.
1994
2504
  *
@@ -2016,9 +2526,13 @@ const prettyConsoleSink = () => {
2016
2526
  * in tests — and a real process env in production — is observed:
2017
2527
  *
2018
2528
  * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (the snapshot
2019
- * ceiling `C`). Parsed as a number; ignored when unset / NaN.
2020
- * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Truthy
2021
- * when set to a non-empty value other than `"0"` / `"false"`.
2529
+ * ceiling `C`). A plain positive decimal integer; unset or `""` falls
2530
+ * back to the profile default; any other value throws
2531
+ * `BaerlyError{code:"InvalidConfig"}`.
2532
+ * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Closed,
2533
+ * case-insensitive vocabulary: unset/`""`/`"0"`/`"false"` → `false`;
2534
+ * `"1"`/`"true"` → `true`; anything else throws
2535
+ * `BaerlyError{code:"InvalidConfig"}`.
2022
2536
  *
2023
2537
  * `readEnv` defaults to `process.env`; the parameter exists for direct
2024
2538
  * unit coverage.
@@ -2028,12 +2542,23 @@ const nodeMaintenanceDispatch = (readEnv = (k) => process.env[k]) => {
2028
2542
  return {
2029
2543
  ...disabled && { disabled: true },
2030
2544
  ...maxFoldBytes !== void 0 && { maxFoldBytes },
2545
+ warn: logMaintenanceWarning,
2031
2546
  options: {
2032
2547
  phasesPerTick: "both",
2033
2548
  profile: MAINTENANCE_PROFILE_NODE
2034
2549
  }
2035
2550
  };
2036
2551
  };
2552
+ const mappedErrorResponse = (error) => {
2553
+ const { status, envelope } = mapError(error);
2554
+ return {
2555
+ status,
2556
+ response: new Response(JSON.stringify(envelope), {
2557
+ status,
2558
+ headers: { "content-type": "application/json" }
2559
+ })
2560
+ };
2561
+ };
2037
2562
  /**
2038
2563
  * Build a `(req: Request) => Promise<Response>` handler that runs the
2039
2564
  * baerly `/v1/*` cascade: healthz short-circuit → observability context
@@ -2063,36 +2588,72 @@ function createFetchHandler(opts) {
2063
2588
  verifier: opts.verifier,
2064
2589
  config: opts.config
2065
2590
  }));
2591
+ const requestId = requestIdFrom(request.headers);
2592
+ let maintenance;
2593
+ try {
2594
+ maintenance = nodeMaintenanceDispatch();
2595
+ } catch (error) {
2596
+ const obsCtx = createObservabilityContext({ request_id: requestId });
2597
+ return await runWithContext(obsCtx, async () => {
2598
+ const { status, response } = mappedErrorResponse(error);
2599
+ flushCanonicalLine(obsCtx, obsCtx.recorder, {
2600
+ unit: "http",
2601
+ status,
2602
+ outcome: deriveOutcome(request.method, status, error),
2603
+ error,
2604
+ extra: {
2605
+ method: request.method,
2606
+ path
2607
+ }
2608
+ });
2609
+ return response;
2610
+ });
2611
+ }
2066
2612
  const obsCtx = createObservabilityContext({
2067
- request_id: request.headers.get("x-request-id") ?? crypto.randomUUID(),
2068
- maintenance: nodeMaintenanceDispatch()
2613
+ request_id: requestId,
2614
+ maintenance,
2615
+ ledger: new RequestLedger()
2069
2616
  });
2070
- const result = await opts.verifier(request);
2071
- if (result === null) return await runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, request));
2072
2617
  return await runWithContext(obsCtx, async () => {
2618
+ let result;
2619
+ try {
2620
+ result = await opts.verifier(request);
2621
+ } catch (error) {
2622
+ const { status, response } = mappedErrorResponse(error);
2623
+ flushCanonicalLine(obsCtx, obsCtx.recorder, {
2624
+ unit: "http",
2625
+ status,
2626
+ outcome: deriveOutcome(request.method, status, error),
2627
+ error,
2628
+ extra: {
2629
+ method: request.method,
2630
+ path
2631
+ }
2632
+ });
2633
+ return response;
2634
+ }
2635
+ if (result === null) return flushUnauthorizedAndRespond(obsCtx, request);
2073
2636
  let outboundStatus = 500;
2074
2637
  let caughtError;
2075
2638
  let response;
2076
2639
  try {
2640
+ const db = Db.create({
2641
+ storage: wrappedStorage,
2642
+ app: opts.app,
2643
+ tenant: result.tenantPrefix,
2644
+ config: opts.config
2645
+ });
2077
2646
  response = await createRouter({
2078
- db: Db.create({
2079
- storage: wrappedStorage,
2080
- app: opts.app,
2081
- tenant: result.tenantPrefix,
2082
- config: opts.config
2083
- }),
2647
+ db,
2084
2648
  ...opts.sinceTimeoutMs !== void 0 && { sinceTimeoutMs: opts.sinceTimeoutMs },
2085
2649
  ...opts.sincePollIntervalMs !== void 0 && { sincePollIntervalMs: opts.sincePollIntervalMs }
2086
2650
  }).fetch(request);
2087
2651
  outboundStatus = response.status;
2088
2652
  } catch (error) {
2089
2653
  caughtError = error;
2090
- const { status, envelope } = mapError(error);
2654
+ const { status, response: mappedResponse } = mappedErrorResponse(error);
2091
2655
  outboundStatus = status;
2092
- response = new Response(JSON.stringify(envelope), {
2093
- status,
2094
- headers: { "content-type": "application/json" }
2095
- });
2656
+ response = mappedResponse;
2096
2657
  } finally {
2097
2658
  flushCanonicalLine(obsCtx, obsCtx.recorder, {
2098
2659
  unit: "http",
@@ -2132,8 +2693,7 @@ const resolveDefaultSink = (config) => {
2132
2693
  sink: isTty ? prettyConsoleSink() : "console-json"
2133
2694
  };
2134
2695
  };
2135
- //#endregion
2136
- //#region packages/adapter-node/src/app.ts
2696
+ // packages/adapter-node/src/app.ts
2137
2697
  /**
2138
2698
  * Build a Hono app that serves the baerly cascade plus Node-host
2139
2699
  * middleware (dev-landing when `dev` is set, then static-assets when
@@ -2160,6 +2720,11 @@ const resolveDefaultSink = (config) => {
2160
2720
  function createApp(opts) {
2161
2721
  const fetchHandler = createFetchHandler(opts);
2162
2722
  const app = new Hono();
2723
+ app.use("*", async (c, next) => {
2724
+ await next();
2725
+ const res = withNosniff(c.res);
2726
+ if (res !== c.res) c.res = res;
2727
+ });
2163
2728
  if (opts.dev !== void 0) app.use("*", devLandingMiddleware({ dev: opts.dev }));
2164
2729
  if (opts.webRoot !== void 0) app.use("*", staticAssetsMiddleware({ webRoot: opts.webRoot }));
2165
2730
  app.all("*", async (c) => {
@@ -2169,15 +2734,14 @@ function createApp(opts) {
2169
2734
  });
2170
2735
  return app;
2171
2736
  }
2172
- //#endregion
2173
- //#region packages/adapter-node/src/baerly-node.ts
2737
+ // packages/adapter-node/src/baerly-node.ts
2174
2738
  /**
2175
2739
  * Mount baerly on `node:http` with one call. Mirrors `baerlyWorker`
2176
2740
  * from `@baerly/adapter-cloudflare`.
2177
2741
  *
2178
2742
  * Composes:
2179
2743
  * - {@link createApp} → exposed as `handle.fetch` for in-process
2180
- * embedding; wrapped in `@hono/node-server.serve({ fetch, createServer })`
2744
+ * embedding; wrapped in `@hono/node-server.createAdaptorServer({ fetch, createServer })`
2181
2745
  * lazily when `listen()` is called.
2182
2746
  * - SIGTERM + SIGINT handlers installed on `listen()` that call
2183
2747
  * `close()` and `process.exit(0)`. On any error during close,
@@ -2191,8 +2755,16 @@ function createApp(opts) {
2191
2755
  * onto the per-request observability context, which the writer reads at
2192
2756
  * its post-commit dispatch point. Reads never tick. Tune via the
2193
2757
  * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` / `BAERLY_MAINTENANCE_DISABLE`
2194
- * env vars; for an explicit out-of-band sweep, call
2195
- * `runScheduledMaintenance` from `@gusto/baerly-storage` directly.
2758
+ * env vars. `BAERLY_MAINTENANCE_DISABLE` accepts unset / `""` / `"0"` /
2759
+ * `"false"` (enabled) or `"1"` / `"true"` (disabled), case-insensitively;
2760
+ * anything else throws `BaerlyError{code:"InvalidConfig"}`.
2761
+ * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` uses a plain positive decimal
2762
+ * integer as the override; unset or empty values use the Node profile
2763
+ * default, and any other value throws `InvalidConfig`. These
2764
+ * values are re-read for API/database requests that reach maintenance
2765
+ * dispatch; health/spec and configured dev/static short-circuits bypass
2766
+ * them. For an explicit out-of-band sweep, call
2767
+ * `runScheduledMaintenance` from `@gusto/baerly-storage/maintenance`.
2196
2768
  *
2197
2769
  * @example
2198
2770
  * ```ts
@@ -2215,13 +2787,26 @@ function createApp(opts) {
2215
2787
  * await handle.listen(Number(process.env["PORT"] ?? 8080));
2216
2788
  * ```
2217
2789
  */
2790
+ /**
2791
+ * Host used to build the request URL when a request carries no Host
2792
+ * header (HTTP/1.0): the bound address, with an IPv6 literal bracketed
2793
+ * so the URL parses, or `0.0.0.0` for an all-interfaces bind.
2794
+ */
2795
+ function fallbackHost(hostname) {
2796
+ if (hostname === void 0) return "0.0.0.0";
2797
+ return hostname.includes(":") ? `[${hostname}]` : hostname;
2798
+ }
2218
2799
  function baerlyNode(opts) {
2219
2800
  const verifier = resolveVerifier({
2220
2801
  factoryVerifier: opts.verifier,
2221
2802
  config: opts.config,
2222
2803
  readEnv: (k) => process.env[k]
2223
2804
  });
2224
- if (opts.verifier === void 0 && opts.config.auth === "none") console.log(`[baerly] auth=none — all requests resolve to tenant=${JSON.stringify(opts.config.tenant)}`);
2805
+ if (opts.verifier === void 0 && opts.config.auth === "none") {
2806
+ const tenant = JSON.stringify(opts.config.tenant);
2807
+ if (isDeployedEnv(process.env)) console.warn(`[baerly] auth=none in a deployed environment — every request, from any caller, gets full access to tenant=${tenant}`);
2808
+ else console.log(`[baerly] auth=none — all requests resolve to tenant=${tenant}`);
2809
+ }
2225
2810
  const app = createApp({
2226
2811
  app: opts.config.app,
2227
2812
  storage: opts.storage,
@@ -2234,16 +2819,16 @@ function baerlyNode(opts) {
2234
2819
  ...opts.sincePollIntervalMs !== void 0 && { sincePollIntervalMs: opts.sincePollIntervalMs }
2235
2820
  });
2236
2821
  let server;
2822
+ let bind;
2237
2823
  let signalHandler;
2238
- let closed = false;
2239
- const close = async () => {
2240
- if (closed) return;
2241
- closed = true;
2824
+ let closing;
2825
+ const shutdown = async () => {
2242
2826
  if (signalHandler !== void 0) {
2243
2827
  process.off("SIGTERM", signalHandler);
2244
2828
  process.off("SIGINT", signalHandler);
2245
2829
  signalHandler = void 0;
2246
2830
  }
2831
+ await bind?.catch(() => void 0);
2247
2832
  await new Promise((resolve, reject) => {
2248
2833
  if (server === void 0) {
2249
2834
  resolve();
@@ -2259,36 +2844,38 @@ function baerlyNode(opts) {
2259
2844
  });
2260
2845
  });
2261
2846
  };
2262
- const listen = async (port) => {
2263
- server = serve({
2847
+ const close = () => {
2848
+ closing ??= shutdown();
2849
+ return closing;
2850
+ };
2851
+ const listen = async (port, options) => {
2852
+ if (closing !== void 0) throw new BaerlyError("InvalidConfig", "baerlyNode: listen() called after close(); create a new handle");
2853
+ const hostname = options?.hostname;
2854
+ server = createAdaptorServer({
2264
2855
  fetch: app.fetch,
2265
- port: 0,
2266
- hostname: "0.0.0.0",
2856
+ hostname: fallbackHost(hostname),
2267
2857
  createServer
2268
2858
  });
2269
2859
  const httpServer = server;
2270
- await new Promise((resolve, reject) => {
2860
+ bind = new Promise((resolve, reject) => {
2271
2861
  const onError = (err) => {
2272
2862
  httpServer.off("listening", onListening);
2273
- httpServer.off("close", onClose);
2274
2863
  reject(err);
2275
2864
  };
2276
2865
  const onListening = () => {
2277
2866
  httpServer.off("error", onError);
2278
- httpServer.off("close", onClose);
2279
- resolve();
2280
- };
2281
- const onClose = () => {
2282
- httpServer.off("error", onError);
2283
- httpServer.off("listening", onListening);
2284
2867
  resolve();
2285
2868
  };
2286
2869
  httpServer.once("error", onError);
2287
2870
  httpServer.once("listening", onListening);
2288
- httpServer.once("close", onClose);
2289
- httpServer.listen(port);
2871
+ if (hostname === void 0) httpServer.listen(port);
2872
+ else httpServer.listen(port, hostname);
2290
2873
  });
2291
- if (closed) return;
2874
+ await bind;
2875
+ if (closing !== void 0) {
2876
+ await close();
2877
+ return;
2878
+ }
2292
2879
  signalHandler = (sig) => {
2293
2880
  console.log(`Received ${sig}; closing baerlyNode server`);
2294
2881
  close().then(() => process.exit(0)).catch((error) => {
@@ -2305,7 +2892,6 @@ function baerlyNode(opts) {
2305
2892
  close
2306
2893
  };
2307
2894
  }
2308
- //#endregion
2309
2895
  export { fromEksPodIdentity as a, localFsStorage as c, r2Storage as d, s3Storage as f, fromWebIdentity as i, gcsStorage as l, getRequestListener as n, assertStorageReachable as o, gcsVersioningStatus as p, fromEks as r, resolveStorageFromEnv as s, baerlyNode as t, minioStorage as u };
2310
2896
 
2311
- //# sourceMappingURL=src-BMFfDUI2.js.map
2897
+ //# sourceMappingURL=src-Actga-bO.js.map