@gusto/baerly-storage 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -124
- package/dist/API.md +161 -511
- package/dist/CHANGELOG.md +1148 -307
- package/dist/RECIPES.md +398 -80
- package/dist/THIRD-PARTY-LICENSES.txt +5 -26
- package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
- package/dist/app-config.d.ts +31 -1
- package/dist/app-config.js +1 -2
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +33 -28
- package/dist/auth.js +549 -985
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +130 -138
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +97 -22
- package/dist/capacity-warning-header-BlVopyiI.js +16 -0
- package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
- package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
- package/dist/client-react.d.ts +67 -20
- package/dist/client-react.js +240 -54
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +51 -16
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
- package/dist/cloudflare-CKHYXccw.js.map +1 -0
- package/dist/cloudflare.d.ts +106 -71
- package/dist/cloudflare.js +334 -271
- package/dist/cloudflare.js.map +1 -1
- package/dist/code-resolution-CL_7L0wS.js +22 -0
- package/dist/code-resolution-CL_7L0wS.js.map +1 -0
- package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
- package/dist/config-DEzInG6M.js +4035 -0
- package/dist/config-DEzInG6M.js.map +1 -0
- package/dist/constants-D3GSH3tc.js +469 -0
- package/dist/constants-D3GSH3tc.js.map +1 -0
- package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
- package/dist/context-rlpSnHFA.js.map +1 -0
- package/dist/cost-B52llVDx.js +330 -0
- package/dist/cost-B52llVDx.js.map +1 -0
- package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
- package/dist/current-json-CC6lE4Aj.js.map +1 -0
- package/dist/db-plFUNTSF.d.ts +130 -0
- package/dist/db-read-seams-BSs0m1z1.js +3261 -0
- package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
- package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
- package/dist/deploy-Obj4nE-Z.js.map +1 -0
- package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
- package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
- package/dist/dev-landing-CD-si4dW.js +50 -0
- package/dist/dev-landing-CD-si4dW.js.map +1 -0
- package/dist/dev-vite.d.ts +38 -39
- package/dist/dev-vite.js +67 -36
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +3 -2
- package/dist/dev.js +2 -1
- package/dist/doctor-BA0i-YAN.js +270 -0
- package/dist/doctor-BA0i-YAN.js.map +1 -0
- package/dist/dump-D1vX8ozg.js +133 -0
- package/dist/dump-D1vX8ozg.js.map +1 -0
- package/dist/errors-7Rk1HGCE.js +160 -0
- package/dist/errors-7Rk1HGCE.js.map +1 -0
- package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
- package/dist/export-BVL2EvYE.js.map +1 -0
- package/dist/fsck-BWkPgov4.js +145 -0
- package/dist/fsck-BWkPgov4.js.map +1 -0
- package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
- package/dist/gcs.d.ts +30 -0
- package/dist/gcs.js +1 -0
- package/dist/goog4-signer-CeLIABoE.js +331 -0
- package/dist/goog4-signer-CeLIABoE.js.map +1 -0
- package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
- package/dist/http-Z5rZyYMX.js.map +1 -0
- package/dist/http-transport-DNUM8kU-.js +1299 -0
- package/dist/http-transport-DNUM8kU-.js.map +1 -0
- package/dist/http.d.ts +366 -294
- package/dist/http.js +2 -2
- package/dist/index-JJrIu1pO.d.ts +135 -0
- package/dist/index-LEgHN0qJ.d.ts +50 -0
- package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
- package/dist/index.d.ts +27 -6
- package/dist/index.js +3 -5
- package/dist/inspect-BTsVYZKd.js +196 -0
- package/dist/inspect-BTsVYZKd.js.map +1 -0
- package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
- package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
- package/dist/ledger-Dj_bGgo0.js +192 -0
- package/dist/ledger-Dj_bGgo0.js.map +1 -0
- package/dist/legacy-names-DgZBtgOh.js +47 -0
- package/dist/legacy-names-DgZBtgOh.js.map +1 -0
- package/dist/log-C9W15Dfo.d.ts +94 -0
- package/dist/log-tail-DWJbneBF.js +142 -0
- package/dist/log-tail-DWJbneBF.js.map +1 -0
- package/dist/log-walk-C-vA-WGJ.js +111 -0
- package/dist/log-walk-C-vA-WGJ.js.map +1 -0
- package/dist/maintenance-Dd-Yakqj.js +1709 -0
- package/dist/maintenance-Dd-Yakqj.js.map +1 -0
- package/dist/maintenance-DevB6z4e.js +2237 -0
- package/dist/maintenance-DevB6z4e.js.map +1 -0
- package/dist/maintenance.d.ts +100 -3
- package/dist/maintenance.js +1 -3
- package/dist/node.d.ts +130 -142
- package/dist/node.js +4 -3
- package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
- package/dist/observability-C-ISCCLE.js.map +1 -0
- package/dist/observability.d.ts +27 -3
- package/dist/observability.js +3 -3
- package/dist/path-segment-DBXG26PW.js +363 -0
- package/dist/path-segment-DBXG26PW.js.map +1 -0
- package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
- package/dist/plan-BvQbaNMe.js.map +1 -0
- package/dist/request-CRWiTrza.js +272 -0
- package/dist/request-CRWiTrza.js.map +1 -0
- package/dist/restore-U6Im8V1V.js +1467 -0
- package/dist/restore-U6Im8V1V.js.map +1 -0
- package/dist/retry-OBtLB2GC.js +126 -0
- package/dist/retry-OBtLB2GC.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
- package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
- package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
- package/dist/s3.d.ts +20 -7
- package/dist/s3.js +4 -5
- package/dist/s3.js.map +1 -1
- package/dist/sha256-4FfGQNPw.js +22 -0
- package/dist/sha256-4FfGQNPw.js.map +1 -0
- package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
- package/dist/shared-secret-Vkur-8r0.js.map +1 -0
- package/dist/sigv4-sign-5IUflUD_.js +507 -0
- package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
- package/dist/snapshot-CknzkDM0.js +148 -0
- package/dist/snapshot-CknzkDM0.js.map +1 -0
- package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
- package/dist/src-Actga-bO.js.map +1 -0
- package/dist/src-D0MQfvOp.js +812 -0
- package/dist/src-D0MQfvOp.js.map +1 -0
- package/dist/src-Dr9uo3dc.js +501 -0
- package/dist/src-Dr9uo3dc.js.map +1 -0
- package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
- package/dist/subcommand-BLoF66dG.js.map +1 -0
- package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
- package/dist/time-DRxTP9iv.js.map +1 -0
- package/dist/types-suVbsEWS.d.ts +116 -0
- package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
- package/dist/usage-CPzVhrQr.js.map +1 -0
- package/dist/uuid-BuT_c404.js +333 -0
- package/dist/uuid-BuT_c404.js.map +1 -0
- package/dist/verifier-Bmlmndzo.d.ts +95 -0
- package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
- package/dist/wire-DndvKU-K.js.map +1 -0
- package/package.json +96 -69
- package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
- package/dist/bytes-BXdamO3L.js +0 -11
- package/dist/bytes-BXdamO3L.js.map +0 -1
- package/dist/cloudflare-DzKBrUlg.js.map +0 -1
- package/dist/config-1tv0-Yzm.js +0 -2693
- package/dist/config-1tv0-Yzm.js.map +0 -1
- package/dist/constants-CfeMWQWk.js +0 -222
- package/dist/constants-CfeMWQWk.js.map +0 -1
- package/dist/context-DRZ3tZ5l.js.map +0 -1
- package/dist/cost-DSMIVqzL.js +0 -203
- package/dist/cost-DSMIVqzL.js.map +0 -1
- package/dist/current-json-C6nhPOm1.js.map +0 -1
- package/dist/db-DsPkOVEH.d.ts +0 -254
- package/dist/deploy-DonTr-CV.js.map +0 -1
- package/dist/doctor-DSIyCDg_.js +0 -346
- package/dist/doctor-DSIyCDg_.js.map +0 -1
- package/dist/dump-Bh5k26VQ.js +0 -94
- package/dist/dump-Bh5k26VQ.js.map +0 -1
- package/dist/errors-Dfa3p78c.js +0 -78
- package/dist/errors-Dfa3p78c.js.map +0 -1
- package/dist/export-DtF5tDIM.js +0 -401
- package/dist/export-DtF5tDIM.js.map +0 -1
- package/dist/fsck-D_djMO5D.js +0 -279
- package/dist/fsck-D_djMO5D.js.map +0 -1
- package/dist/http-DGd5tbNs.js.map +0 -1
- package/dist/index-0rZcMBwy.d.ts +0 -115
- package/dist/index-BNRh23K9.d.ts +0 -162
- package/dist/index-BYk9oCNf.d.ts +0 -1112
- package/dist/indexes-Dn9hbGQG.d.ts +0 -22
- package/dist/inspect-6WZ-pC7-.js +0 -133
- package/dist/inspect-6WZ-pC7-.js.map +0 -1
- package/dist/log-tail-D98U1JBo.js +0 -522
- package/dist/log-tail-D98U1JBo.js.map +0 -1
- package/dist/maintenance-B4Dki6Ig.js +0 -2157
- package/dist/maintenance-B4Dki6Ig.js.map +0 -1
- package/dist/maintenance-B_e0T99L.d.ts +0 -537
- package/dist/maintenance-C7coQp4c.js +0 -1418
- package/dist/maintenance-C7coQp4c.js.map +0 -1
- package/dist/normalize-rjnZLwS4.js +0 -133
- package/dist/normalize-rjnZLwS4.js.map +0 -1
- package/dist/observability-BmflLCdF.js.map +0 -1
- package/dist/plan-a7PJHBCy.js.map +0 -1
- package/dist/query-rAtXNQQB.js +0 -1773
- package/dist/query-rAtXNQQB.js.map +0 -1
- package/dist/rebuild-index-BVzQSZlm.js +0 -81
- package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
- package/dist/request-u0M51mhJ.js +0 -72
- package/dist/request-u0M51mhJ.js.map +0 -1
- package/dist/restore-R-4rbciV.js +0 -778
- package/dist/restore-R-4rbciV.js.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
- package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
- package/dist/shared-secret-DgEicd3x.js.map +0 -1
- package/dist/src-BL_JoPTn.js.map +0 -1
- package/dist/src-CYHFDrKz.js +0 -536
- package/dist/src-CYHFDrKz.js.map +0 -1
- package/dist/src-DYZ4H1aF.js +0 -392
- package/dist/src-DYZ4H1aF.js.map +0 -1
- package/dist/subcommand-DoDA-K7d.js.map +0 -1
- package/dist/time-DUqvFMHq.js.map +0 -1
- package/dist/usage-DBV1eQHC.js.map +0 -1
- package/dist/validate-DtljsCh1.js.map +0 -1
- package/dist/wire-izfGZDvr.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-Actga-bO.js","names":["FETCH_TIMEOUT_MS","fsReadFile","fsReadFile"],"sources":["../packages/protocol/src/storage/probe-cas.ts","../packages/adapter-node/src/gcs-admin.ts","../packages/adapter-node/src/credentials/signer.ts","../packages/adapter-node/src/storage-factories.ts","../packages/adapter-node/src/local-fs-storage.ts","../packages/adapter-node/src/resolve-storage.ts","../packages/adapter-node/src/assert-storage-reachable.ts","../packages/adapter-node/src/credentials/token-file.ts","../packages/adapter-node/src/credentials/from-eks-pod-identity.ts","../packages/adapter-node/src/credentials/from-web-identity.ts","../packages/adapter-node/src/credentials/from-eks.ts","../node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/helper/websocket/index.js","../node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/index.mjs","../packages/adapter-node/src/middleware/body-cap.ts","../packages/adapter-node/src/middleware/dev-landing.ts","../node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/utils/stream.mjs","../node_modules/.pnpm/hono@4.13.19/node_modules/hono/dist/utils/mime.js","../node_modules/.pnpm/@hono+node-server@2.1.8_hono@4.13.19/node_modules/@hono/node-server/dist/serve-static.mjs","../packages/adapter-node/src/middleware/static-assets.ts","../packages/adapter-node/src/logger-pretty.ts","../packages/adapter-node/src/server.ts","../packages/adapter-node/src/app.ts","../packages/adapter-node/src/baerly-node.ts"],"sourcesContent":["import { isWriteConflict } from \"../errors.ts\";\nimport { uuid } from \"../types.ts\";\nimport type { Storage } from \"./types.ts\";\n\n/** One CAS sub-check's outcome. */\nexport interface CasProbeCheck {\n /** Stable identifier (`ifMatch-stale` / `ifNoneMatch-exists` / `ifNoneMatch-concurrent`). */\n readonly name: string;\n /** `true` iff the backend rejected the conditional write as required. */\n readonly ok: boolean;\n /** Human-readable detail — what was expected vs. observed. */\n readonly detail: string;\n}\n\n/** Aggregate result of {@link probeCas}. `ok` iff every sub-check passed. */\nexport interface CasProbeResult {\n readonly ok: boolean;\n readonly checks: readonly CasProbeCheck[];\n}\n\n/**\n * Runtime probe that a live `Storage` backend honours the conditional\n * writes the protocol depends on. The storage conformance suite asserts\n * the same semantics in CI for every shipped adapter, but a deployment\n * may point baerly at an arbitrary S3-compatible store; a backend that\n * silently *ignores* these conditionals causes silent corruption — the\n * log-append commit relies on `If-None-Match:\"*\"` create-if-absent\n * being exactly-one-winner under concurrency (the winning create IS the\n * commit; two winners produce split-brain commit), and the compactor\n * CAS-advances `current.json` with `If-Match` under the no-lease\n * maintenance fold (a backend that returns 200 instead of rejecting a\n * stale `If-Match` causes lost-update corruption). This is the\n * fail-loud, deploy-time analogue of the conformance CAS block.\n *\n * Writes throwaway sentinels under `keyPrefix` and deletes them on\n * the way out (even on failure). Three checks, mirroring the conformance\n * suite:\n * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (WriteConflict).\n * - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:\"*\"` over an existing\n * key must reject (WriteConflict).\n * - `ifNoneMatch-concurrent`: at most one of N concurrent create-if-absent\n * writes on a fresh key wins — the linearizability the writer's log-append\n * commit already relies on (`writer.ts`).\n *\n * A rejected write surfaces as a `BaerlyError` with `code === \"WriteConflict\"`\n * (the contract `Storage.put` documents); anything else — a resolved\n * promise, or a non-WriteConflict error — is reported as a failed or\n * inconclusive check rather than thrown.\n */\nexport const probeCas = async (\n storage: Storage,\n opts?: { keyPrefix?: string; signal?: AbortSignal; staleEtag?: string },\n): Promise<CasProbeResult> => {\n const prefix = opts?.keyPrefix ?? \"\";\n const key = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const enc = new TextEncoder();\n const signal = opts?.signal;\n // A well-formed etag guaranteed *not* to be the current version of any\n // key. Defaults to the S3/R2-shaped quoted-string sentinel, which every\n // ETag-versioned backend treats as a non-matching-but-valid token. GCS's\n // version token is an int64 generation, so a quoted-string value is a\n // *malformed* precondition there (400 InvalidArgument, not a 412\n // conflict) — callers on the native GCS path must override this with a\n // well-formed-but-stale generation (mirrors the conformance suite's\n // `staleEtag` option; see `storage/conformance.ts`).\n const staleEtag = opts?.staleEtag ?? '\"baerly-cas-probe-stale\"';\n\n const checks: CasProbeCheck[] = [];\n try {\n const first = await storage.put(key, enc.encode(\"v1\"), { signal });\n\n // Check 1\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v2\"), { ifMatch: staleEtag, signal });\n checks.push({\n name: \"ifMatch-stale\",\n ok: false,\n detail:\n \"PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk).\",\n });\n } catch (error) {\n checks.push(\n isWriteConflict(error)\n ? {\n name: \"ifMatch-stale\",\n ok: true,\n detail: \"stale If-Match rejected (WriteConflict), as required.\",\n }\n : {\n name: \"ifMatch-stale\",\n ok: false,\n detail: `stale If-Match raised a non-WriteConflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // Check 2\n try {\n // Stryker disable next-line StringLiteral: same rationale as ifMatch-stale above\n await storage.put(key, enc.encode(\"v3\"), { ifNoneMatch: \"*\", signal });\n checks.push({\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail:\n 'PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe).',\n });\n } catch (error) {\n checks.push(\n isWriteConflict(error)\n ? {\n name: \"ifNoneMatch-exists\",\n ok: true,\n detail:\n 'If-None-Match:\"*\" over an existing key rejected (WriteConflict), as required.',\n }\n : {\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail: `If-None-Match:\"*\" raised a non-WriteConflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // Check 3\n // The writer already depends on this today: log entries are PUT with\n // ifNoneMatch:\"*\", and a 412 means a peer won that seq (writer.ts). Two\n // winners ⇒ two writers believe they appended the same log seq.\n // Transient non-WriteConflict losers (e.g. an S3 409\n // ConditionalRequestConflict, which the adapter maps to a retryable\n // NetworkError) are inconclusive — the adapter's retry re-issues the\n // PUT and resolves to 200/412 — not proof of a broken backend. The\n // deploy-time probe still fails closed so operators retry for a clean race.\n const raceKey = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const RACERS = 16;\n try {\n const outcomes = await Promise.allSettled(\n Array.from({ length: RACERS }, (_unused, i) =>\n // Stryker disable next-line StringLiteral: same rationale as ifMatch-stale above (plus winner count)\n storage.put(raceKey, enc.encode(`r${i}`), { ifNoneMatch: \"*\", signal }),\n ),\n );\n const winners = outcomes.filter((o) => o.status === \"fulfilled\").length;\n const transient = outcomes.filter(\n (o) => o.status === \"rejected\" && !isWriteConflict(o.reason),\n ).length;\n if (winners > 1) {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `${winners} of ${RACERS} concurrent create-if-absent writes won (expected at most 1) — create-if-absent is NOT linearizable; the log-append commit would split-brain.`,\n });\n } else if (winners === 1) {\n if (transient === 0) {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: true,\n detail: `exactly one of ${RACERS} concurrent create-if-absent writes won; the rest rejected (WriteConflict), as required.`,\n });\n } else {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `exactly one of ${RACERS} concurrent create-if-absent writes won, but ${transient} loser(s) returned a transient non-WriteConflict error — inconclusive; retry for a clean race.`,\n });\n }\n } else {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `no create-if-absent write succeeded across ${RACERS} attempts — inconclusive (transient failure or outage), not a linearizability verdict; retry.`,\n });\n }\n } finally {\n try {\n await storage.delete(raceKey, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n void first;\n } finally {\n // Best-effort cleanup — never let a delete failure mask the verdict.\n try {\n await storage.delete(key, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n return { ok: checks.every((c) => c.ok), checks };\n};\n","/**\n * GCS bucket-administration probes over the native XML API — read-only\n * config checks that fall outside the four-verb `Storage` interface.\n * Kept in the adapter so GCS wire details (endpoint/URL shape, the\n * `?versioning` sub-resource, the XML response, GOOG4 signing) live\n * behind the adapter boundary rather than leaking into the CLI.\n */\n\nimport { DEFAULT_GCS_ENDPOINT } from \"./gcs-http.ts\";\nimport { goog4Signer } from \"./credentials/goog4-signer.ts\";\nimport type { Credentials, CredentialsProvider } from \"./credentials/types.ts\";\n\n/** Case-sensitive per the GCS `?versioning` XML shape; tolerate surrounding whitespace. */\nconst VERSIONING_ENABLED_RE = /<Status>\\s*Enabled\\s*<\\/Status>/;\n\n/**\n * Result of {@link gcsVersioningStatus}. `inconclusive` carries a\n * human-readable `reason` (an `HTTP <status>` string, or a thrown\n * error's message) so a diagnostic caller can explain why the probe\n * couldn't decide without re-deriving it.\n */\nexport type GcsVersioningStatus =\n | { readonly kind: \"enabled\" }\n | { readonly kind: \"disabled\" }\n | { readonly kind: \"inconclusive\"; readonly reason: string };\n\n/**\n * Read a GCS bucket's Object Versioning setting over the native XML API\n * (`GET <endpoint>/<bucket>?versioning`), signed with GOOG4-HMAC-SHA256.\n * Never throws — a non-2xx response or a network error resolves to\n * `{ kind: \"inconclusive\", reason }`, so callers (e.g. `baerly doctor`)\n * can degrade gracefully instead of aborting.\n */\nexport async function gcsVersioningStatus(opts: {\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n /** Defaults to the native GCS host. */\n endpoint?: string;\n /** Injected in tests; defaults to global fetch. */\n fetch?: typeof fetch;\n}): Promise<GcsVersioningStatus> {\n const endpoint = (opts.endpoint ?? DEFAULT_GCS_ENDPOINT).replace(/\\/+$/, \"\");\n const fetchImpl = opts.fetch ?? globalThis.fetch.bind(globalThis);\n const sign = goog4Signer({ credentials: opts.credentials });\n const url = `${endpoint}/${opts.bucket}?versioning`;\n try {\n const signed = await sign(new Request(url, { method: \"GET\" }));\n const res = await fetchImpl(signed);\n if (!res.ok) {\n return { kind: \"inconclusive\", reason: `HTTP ${res.status}` };\n }\n const body = await res.text();\n return VERSIONING_ENABLED_RE.test(body) ? { kind: \"enabled\" } : { kind: \"disabled\" };\n } catch (error) {\n return {\n kind: \"inconclusive\",\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n}\n","import { AwsClient } from \"aws4fetch\";\nimport type { Credentials, CredentialsProvider } from \"./types.ts\";\nimport { credentialResolver } from \"./resolve.ts\";\nimport { signHeadersOnly } from \"../sigv4-sign.ts\";\n\nfunction buildAwsClient(creds: Credentials, region: string): AwsClient {\n return new AwsClient({\n accessKeyId: creds.accessKeyId,\n secretAccessKey: creds.secretAccessKey,\n sessionToken: creds.sessionToken,\n region,\n service: \"s3\",\n });\n}\n\n/**\n * A SigV4 signer. `invalidate` is present only for a credentials provider:\n * given a request this signer returned, it drops the credentials that signed\n * it so the next `sign` calls the provider again.\n */\nexport type RefreshingSigner = ((req: Request) => Promise<Request>) & {\n invalidate?: (signed: Request) => void;\n};\n\nexport function refreshingSigner(opts: {\n region: string;\n credentials: Credentials | CredentialsProvider;\n now?: () => number;\n}): RefreshingSigner {\n const region = opts.region;\n const now = opts.now ?? (() => Date.now());\n\n if (typeof opts.credentials !== \"function\") {\n const aws = buildAwsClient(opts.credentials, region);\n return (req) => signHeadersOnly(aws, req);\n }\n\n const resolve = credentialResolver(opts.credentials, now, (creds) =>\n buildAwsClient(creds, region),\n );\n\n const signedBy = new WeakMap<Request, AwsClient>();\n const sign = async (req: Request): Promise<Request> => {\n const aws = await resolve();\n const signed = await signHeadersOnly(aws, req);\n signedBy.set(signed, aws);\n return signed;\n };\n return Object.assign(sign, {\n invalidate(signed: Request) {\n const aws = signedBy.get(signed);\n if (aws !== undefined) {\n resolve.invalidate(aws);\n }\n },\n });\n}\n","import type { Storage } from \"@baerly/protocol\";\nimport { S3HttpStorage, withCredentialInvalidation } from \"./s3-http.ts\";\nimport { GcsHttpStorage } from \"./gcs-http.ts\";\nimport { refreshingSigner } from \"./credentials/signer.ts\";\nimport { goog4Signer } from \"./credentials/goog4-signer.ts\";\nimport type { Credentials, CredentialsProvider } from \"./credentials/types.ts\";\n\nfunction buildS3Storage(opts: {\n endpoint: string;\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n const sign = refreshingSigner({ region: opts.region, credentials: opts.credentials });\n const storage = new S3HttpStorage({ endpoint: opts.endpoint, bucket: opts.bucket, sign });\n return sign.invalidate === undefined\n ? storage\n : withCredentialInvalidation(storage, sign.invalidate);\n}\n\n/**\n * AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard\n * `aws4fetch` SigV4 signer. The endpoint is derived from the region as\n * `https://s3.<region>.amazonaws.com`.\n *\n * @example Static credentials\n * ```ts\n * import { s3Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n *\n * @example EKS (refreshing) — auto-detects Pod Identity or IRSA\n * ```ts\n * import { s3Storage, fromEks } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: fromEks(),\n * });\n * ```\n */\nexport function s3Storage(opts: {\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://s3.${opts.region}.amazonaws.com`,\n region: opts.region,\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Cloudflare R2 `Storage` factory (S3-compat endpoint). Derives the\n * endpoint from `accountId` as\n * `https://<accountId>.r2.cloudflarestorage.com` and pins region\n * `\"auto\"` — R2 ignores region but `aws4fetch`'s signer requires\n * the field to be set.\n *\n * For Workers that have a native R2 binding (no HTTP hop), see\n * `r2BindingStorage` in `@baerly/adapter-cloudflare`. This factory\n * is for Node hosts that talk to R2 over its public S3-compat URL.\n *\n * @example\n * ```ts\n * import { r2Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = r2Storage({\n * accountId: process.env[\"R2_ACCOUNT_ID\"]!,\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function r2Storage(opts: {\n accountId: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,\n region: \"auto\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Minio `Storage` factory — for local-dev / self-hosted S3-compat.\n * Endpoint is fully caller-supplied (e.g. `http://localhost:9102`)\n * because Minio deployments don't follow a URL template. Region is\n * pinned to `\"us-east-1\"`; Minio ignores it but `aws4fetch` requires\n * a value.\n *\n * @example\n * ```ts\n * import { minioStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = minioStorage({\n * endpoint: process.env[\"BAERLY_S3_ENDPOINT\"] ?? \"http://localhost:9102\",\n * bucket: \"baerly\",\n * credentials: {\n * accessKeyId: process.env[\"MINIO_ACCESS_KEY\"]!,\n * secretAccessKey: process.env[\"MINIO_SECRET_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function minioStorage(opts: {\n endpoint: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: opts.endpoint,\n region: \"us-east-1\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Google Cloud Storage `Storage` factory over the native GCS XML API\n * at `https://storage.googleapis.com`. Wraps {@link GcsHttpStorage} with\n * a GOOG4-HMAC-SHA256 signer, driving GCS's own generation-precondition\n * conditional writes (`x-goog-if-generation-match: 0` for create-if-absent,\n * `x-goog-if-generation-match: <generation>` for compare-and-swap), which\n * return `412` on a lost write. The object `generation` is carried verbatim\n * as the opaque `Storage` etag. This is the sanctioned GCS path — the\n * S3-interop endpoint treats `If-Match`/`If-None-Match` as read-scoped only\n * and cannot linearize the log, so it is not supported.\n *\n * Authentication uses GCS HMAC keys (Console → Settings → Interoperability)\n * — mint an interop key, put the HMAC access key in `credentials.accessKeyId`\n * and the HMAC secret in `credentials.secretAccessKey`.\n *\n * @example\n * ```ts\n * import { gcsStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = gcsStorage({\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"GCS_HMAC_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"GCS_HMAC_SECRET\"]!,\n * },\n * });\n * ```\n */\nexport function gcsStorage(opts: {\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n /** GCS endpoint. Defaults to `https://storage.googleapis.com`. */\n endpoint?: string;\n}): Storage {\n const sign = goog4Signer({ credentials: opts.credentials });\n return new GcsHttpStorage({\n bucket: opts.bucket,\n sign,\n ...(opts.endpoint !== undefined && { endpoint: opts.endpoint }),\n });\n}\n","import { resolve } from \"node:path\";\nimport type { Storage } from \"@baerly/protocol\";\nimport { LocalFsStorage } from \"@baerly/dev/local-fs\";\n\nexport interface LocalFsStorageFactoryOptions {\n /**\n * Root data directory. Resolution order: this option →\n * `$BAERLY_DATA_DIR` → `<cwd>/.baerly-data`.\n */\n readonly dataDir?: string;\n}\n\n/**\n * Zero-config local `Storage` for single-node dev / self-hosted runs.\n * Persists to the filesystem (content-addressed, atomic writes), so data\n * survives process restarts — unlike `MemoryStorage`, which is per-process\n * and lost on exit.\n *\n * NOT for multi-instance production: `LocalFsStorage`'s `ifMatch` CAS is\n * serialized within one process only, so a `current.json` CAS-advance is\n * not atomic against a second process on the same directory (see its class\n * JSDoc). Every call here returns a fresh instance, which is fine — the\n * lock is keyed by resolved root, so instances sharing a directory share\n * it. For horizontally-scaled deploys use `s3Storage` / `r2Storage`, whose\n * cross-process guarantee the no-lease maintenance fold relies on.\n *\n * @example\n * ```ts\n * import { baerlyNode, localFsStorage } from \"@gusto/baerly-storage/node\";\n * import config from \"./baerly.config.ts\";\n *\n * // Runs with zero credentials; persists to ./.baerly-data.\n * await baerlyNode({ config, storage: localFsStorage() }).listen(8080);\n * ```\n */\nexport const localFsStorage = (opts?: LocalFsStorageFactoryOptions): Storage =>\n new LocalFsStorage({\n root: opts?.dataDir ?? process.env[\"BAERLY_DATA_DIR\"] ?? resolve(process.cwd(), \".baerly-data\"),\n });\n","import { BaerlyError, isDeployedEnv, type Storage } from \"@baerly/protocol\";\nimport { localFsStorage } from \"./local-fs-storage.ts\";\nimport { r2Storage, s3Storage } from \"./storage-factories.ts\";\n\n/** Result of {@link resolveStorageFromEnv}. */\nexport interface ResolvedStorage {\n readonly storage: Storage;\n /** Human-readable backend label for a startup log line. */\n readonly label: string;\n}\n\n/**\n * Choose a Node `Storage` backend from environment variables, in priority\n * order:\n * 1. `R2_ACCOUNT_ID` set → Cloudflare R2 (S3-compat endpoint)\n * 2. `BUCKET` set → AWS S3\n * 3. neither, local dev → `localFsStorage` (zero credentials)\n * 4. neither, deployed → throw\n *\n * This is the safe default the example scaffolds use, exported so apps\n * don't hand-roll their own selector and reintroduce the silent\n * in-memory / local-fs fallback this library exists to prevent. There is\n * deliberately **no** fallback to a non-durable store in a deployment:\n * local-fs is single-process with no cross-process CAS and no crash\n * durability, and in-memory storage loses all data on restart, so a\n * deployed environment with no bucket fails loud instead.\n *\n * `env` is injectable for testing; it defaults to `process.env`.\n *\n * @throws BaerlyError `InvalidConfig` when {@link isDeployedEnv} is true\n * and no bucket is configured, or when a configured bucket is missing its\n * credentials.\n *\n * @example\n * ```ts\n * import { baerlyNode, resolveStorageFromEnv } from \"@gusto/baerly-storage/node\";\n * import config from \"./baerly.config.ts\";\n *\n * const { storage, label } = resolveStorageFromEnv();\n * console.log(`[baerly] storage=${label}`);\n * await baerlyNode({ config, storage }).listen(Number(process.env[\"PORT\"] ?? 8080));\n * ```\n */\nexport const resolveStorageFromEnv = (\n env: Record<string, string | undefined> = process.env,\n): ResolvedStorage => {\n // An env var set to \"\" is treated as unset for backend selection, so an\n // exported-but-empty BUCKET / R2_ACCOUNT_ID falls through to the local-dev\n // fallback (or the deployment fail-closed) rather than entering a branch\n // and then throwing a confusing \"missing required env var\" for a var that\n // is, technically, set.\n const isSet = (name: string): boolean => (env[name] ?? \"\") !== \"\";\n const reqEnv = (name: string): string => {\n const v = env[name];\n if (v === undefined || v === \"\") {\n throw new BaerlyError(\"InvalidConfig\", `Missing required env var: ${name}`);\n }\n return v;\n };\n\n if (isSet(\"R2_ACCOUNT_ID\")) {\n return {\n storage: r2Storage({\n accountId: reqEnv(\"R2_ACCOUNT_ID\"),\n bucket: reqEnv(\"BUCKET\"),\n credentials: {\n accessKeyId: reqEnv(\"AWS_ACCESS_KEY_ID\"),\n secretAccessKey: reqEnv(\"AWS_SECRET_ACCESS_KEY\"),\n },\n }),\n label: `r2 (bucket=${env[\"BUCKET\"]})`,\n };\n }\n if (isSet(\"BUCKET\")) {\n return {\n storage: s3Storage({\n region: env[\"AWS_REGION\"] ?? \"us-east-1\",\n bucket: reqEnv(\"BUCKET\"),\n credentials: {\n accessKeyId: reqEnv(\"AWS_ACCESS_KEY_ID\"),\n secretAccessKey: reqEnv(\"AWS_SECRET_ACCESS_KEY\"),\n },\n }),\n label: `s3 (bucket=${env[\"BUCKET\"]})`,\n };\n }\n if (!isDeployedEnv(env)) {\n return {\n storage: localFsStorage(),\n label: `local-fs (${env[\"BAERLY_DATA_DIR\"] ?? \"./.baerly-data\"}) — local dev only, not a production store`,\n };\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n [\n \"[baerly] Refusing to start: no durable storage configured in a deployed environment.\",\n \"Local filesystem storage is a local-dev convenience only — single-process, with no\",\n \"cross-process CAS and no crash durability — so it is never used in production.\",\n \"Configure a real bucket:\",\n \" • AWS S3: BUCKET + AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY (+ optional AWS_REGION)\",\n \" • Cloudflare R2: R2_ACCOUNT_ID + BUCKET + AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY\",\n \"Self-hosting without a cloud bucket? Run MinIO on the box for real S3 semantics, or\",\n \"use SQLite + Litestream for a single-instance app.\",\n ].join(\"\\n\"),\n );\n};\n","import { BaerlyError, probeCas, type Storage } from \"@baerly/protocol\";\n\n/** Options for {@link assertStorageReachable}. */\nexport interface AssertStorageReachableOptions {\n /** Key prefix for the throwaway probe sentinels. Default `\"\"`. */\n keyPrefix?: string;\n signal?: AbortSignal;\n}\n\n/**\n * Boot-time readiness check: confirm a live `Storage` backend is both\n * reachable and honours the conditional writes the protocol depends on.\n * `await` it at startup (or from a `/readyz` handler wired to your\n * platform's readiness probe) to fail closed on a misconfigured backend —\n * an unreachable or non-existent bucket, denied/missing credentials (wrong\n * endpoint/region), or an S3-compatible store that silently ignores\n * `If-Match`/`If-None-Match` (the CAS the protocol depends on) — instead\n * of discovering it on the first user write. It cannot detect a\n * wrong-but-writable bucket: a typo to another reachable bucket you own\n * boots clean, because the probe can only tell that *a* bucket is reachable\n * and CAS-correct, not that it is the *intended* one. This complements\n * `resolveStorageFromEnv`, which catches a *missing* configuration:\n * `assertStorageReachable` additionally catches an\n * unreachable/access-denied/CAS-broken backend at boot instead of on the\n * first write.\n *\n * Opt-in by design: it performs a handful of live round-trips (writes and\n * deletes throwaway sentinels under `keyPrefix`), so it is never run\n * automatically on every boot. Reuses the same `probeCas` machinery as\n * `baerly doctor --bucket`.\n *\n * @throws BaerlyError `NetworkError` if the backend is unreachable, or\n * `InvalidConfig` if it is reachable but fails a required CAS check.\n *\n * @example\n * ```ts\n * const { storage, label } = resolveStorageFromEnv();\n * await assertStorageReachable(storage); // throws before we serve traffic\n * console.log(`[baerly] storage=${label} (reachable)`);\n * ```\n */\nexport const assertStorageReachable = async (\n storage: Storage,\n opts?: AssertStorageReachableOptions,\n): Promise<void> => {\n let result;\n try {\n result = await probeCas(storage, opts);\n } catch (error) {\n throw new BaerlyError(\n \"NetworkError\",\n \"Storage readiness check failed: the backend could not be reached. Verify the bucket name, \" +\n `region/endpoint, and credentials. Cause: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (!result.ok) {\n const failed = result.checks\n .filter((c) => !c.ok)\n .map((c) => ` - ${c.name}: ${c.detail}`)\n .join(\"\\n\");\n throw new BaerlyError(\n \"InvalidConfig\",\n \"Storage readiness check failed — the backend does not honour the conditional writes baerly \" +\n \"requires (data corruption risk). Use a store that honours them: AWS S3 or Cloudflare R2 \" +\n \"(If-Match / If-None-Match), or native Google Cloud Storage via `gcsStorage` \" +\n `(x-goog-if-generation-match). GCS's S3-interop endpoint is not supported.\\n${failed}`,\n );\n }\n};\n","import { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * Read and validate an EKS-projected service-account token file, shared by\n * {@link fromWebIdentity} and {@link fromEksPodIdentity}. Reads the file,\n * trims surrounding whitespace (the projected token has a trailing newline),\n * and rejects an empty result.\n *\n * A missing / unreadable / empty projected token is a deploy misconfig, not a\n * transient fault — so every failure is `InvalidConfig`, which short-circuits\n * the retry loop (see `PERMANENT_STORAGE_ERROR_CODES` in `@baerly/protocol`'s `storage/retry.ts`) instead of\n * hammering the credential source. Error messages name the specific env var\n * so the misconfig is debuggable.\n */\nexport async function readProjectedToken(\n doReadFile: (path: string, encoding: \"utf8\") => Promise<string>,\n tokenPath: string,\n ctx: { provider: string; envVar: string },\n): Promise<string> {\n let rawToken: string;\n try {\n rawToken = await doReadFile(tokenPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${ctx.provider}: cannot read ${ctx.envVar} (${tokenPath}): ${(error as Error).message}`,\n );\n }\n const token = rawToken.trim();\n if (token === \"\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${ctx.provider}: ${ctx.envVar} (${tokenPath}) is empty`,\n );\n }\n return token;\n}\n","import { readFile as fsReadFile } from \"node:fs/promises\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport type { CredentialsProvider } from \"./types.ts\";\nimport { readProjectedToken } from \"./token-file.ts\";\n\nconst FETCH_TIMEOUT_MS = 2_000;\n\n/**\n * Hosts the agent can live on: the ECS agent, the EKS Pod Identity agent\n * (IPv4 and IPv6), and loopback. `127.0.0.0/8` is matched separately.\n * WHATWG URL parsing canonicalizes the hostname first, so alternate\n * spellings (`[0:0:0:0:0:0:0:1]`, `2130706433`) compare equal.\n */\nconst AGENT_HOSTS: ReadonlySet<string> = new Set([\n \"169.254.170.2\",\n \"169.254.170.23\",\n \"[fd00:ec2::23]\",\n \"localhost\",\n \"[::1]\",\n]);\n\nconst LOOPBACK_V4 = /^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\n\nfunction isAgentUri(uri: string): boolean {\n let url: URL;\n try {\n url = new URL(uri);\n } catch {\n return false;\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return false;\n }\n return AGENT_HOSTS.has(url.hostname) || LOOPBACK_V4.test(url.hostname);\n}\n\n/**\n * Resolve AWS credentials from the EKS Pod Identity agent (the 2023\n * successor to IRSA). The agent runs on each EKS node and exchanges\n * the pod's projected service-account token for short-lived AWS\n * credentials, so the app just reads the token and asks the agent.\n *\n * Env vars (set by EKS when the pod has an associated IAM role):\n * - `AWS_CONTAINER_CREDENTIALS_FULL_URI` — the agent endpoint\n * (typically `http://169.254.170.23/v1/credentials`).\n * - `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` — path to the\n * projected SA token used to authorize the agent request.\n *\n * Both are required. Agent should respond instantly on the node-local\n * link — 2 s timeout protects against hangs.\n *\n * The URI must name the agent: loopback, or the ECS / EKS link-local\n * addresses (the AWS SDK's container-credentials allow-list). Anything\n * else throws `InvalidConfig` before the token file is read, so a\n * misconfigured or injected env var never sends the token off-node.\n */\nexport function fromEksPodIdentity(\n opts: {\n fetch?: typeof fetch;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n } = {},\n): CredentialsProvider {\n const doFetch = opts.fetch ?? fetch;\n const doReadFile = opts.readFile ?? fsReadFile;\n\n return async () => {\n const uri = process.env[\"AWS_CONTAINER_CREDENTIALS_FULL_URI\"];\n const tokenPath = process.env[\"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\"];\n if (uri === undefined || uri === \"\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"fromEksPodIdentity: AWS_CONTAINER_CREDENTIALS_FULL_URI not set\",\n );\n }\n if (!isAgentUri(uri)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"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]\",\n );\n }\n if (tokenPath === undefined || tokenPath === \"\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"fromEksPodIdentity: AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE not set\",\n );\n }\n\n const token = await readProjectedToken(doReadFile, tokenPath, {\n provider: \"fromEksPodIdentity\",\n envVar: \"AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE\",\n });\n\n let res: Response;\n try {\n res = await doFetch(uri, {\n method: \"GET\",\n headers: { Authorization: token },\n // The token rides in the Authorization header; a redirect would resend\n // it to the 3xx target. The node-local agent never redirects — refuse\n // rather than follow, so a redirect surfaces as a NetworkError.\n redirect: \"error\",\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n } catch (error) {\n throw new BaerlyError(\n \"NetworkError\",\n `fromEksPodIdentity: agent fetch failed (${(error as Error).message})`,\n );\n }\n\n // 5xx + 429 are transient — bucket as NetworkError so callers /\n // chained providers can retry. Other 4xx are permanent —\n // AccessDenied so retry loops short-circuit (see\n // PERMANENT_STORAGE_ERROR_CODES in @baerly/protocol's storage/retry.ts).\n if (res.status >= 500 || res.status === 429) {\n throw new BaerlyError(\"NetworkError\", `fromEksPodIdentity: agent responded ${res.status}`);\n }\n if (!res.ok) {\n throw new BaerlyError(\"AccessDenied\", `fromEksPodIdentity: agent responded ${res.status}`);\n }\n\n let json: {\n AccessKeyId?: string;\n SecretAccessKey?: string;\n Token?: string;\n Expiration?: string;\n };\n try {\n json = await res.json();\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `fromEksPodIdentity: agent returned non-JSON body (${(error as Error).message})`,\n );\n }\n if (\n json.AccessKeyId === undefined ||\n json.SecretAccessKey === undefined ||\n json.Token === undefined ||\n json.Expiration === undefined\n ) {\n throw new BaerlyError(\"InvalidResponse\", \"fromEksPodIdentity: malformed agent response\");\n }\n // A present-but-unparseable Expiration is as malformed as a missing field:\n // `new Date(bad)` yields an Invalid Date (getTime() → NaN) rather than\n // throwing, and the signer's `expiresAt - buffer > now()` refresh check is\n // false for NaN — so a bad timestamp would silently defeat credential\n // caching/rotation. Reject it here instead.\n const expiration = new Date(json.Expiration);\n if (Number.isNaN(expiration.getTime())) {\n throw new BaerlyError(\"InvalidResponse\", \"fromEksPodIdentity: malformed agent response\");\n }\n return {\n accessKeyId: json.AccessKeyId,\n secretAccessKey: json.SecretAccessKey,\n sessionToken: json.Token,\n expiration,\n };\n };\n}\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { readFile as fsReadFile } from \"node:fs/promises\";\nimport type { CredentialsProvider } from \"./types.ts\";\nimport { readProjectedToken } from \"./token-file.ts\";\nimport { parseAssumeRoleWithWebIdentity, parseStsError } from \"../xml.ts\";\n\n// STS is a regional (not node-local) service, so allow more headroom than the\n// 2 s Pod Identity agent budget — but still bound it against hangs.\nconst FETCH_TIMEOUT_MS = 5_000;\nconst DEFAULT_SESSION_NAME = \"baerly-storage\";\n\n/**\n * Resolve AWS credentials via IRSA (IAM Roles for Service Accounts) — the\n * web-identity-token flow, distinct from the EKS Pod Identity agent that\n * {@link fromEksPodIdentity} handles. EKS projects a signed service-account\n * token into the pod and the app exchanges it for short-lived credentials by\n * calling STS `AssumeRoleWithWebIdentity` directly (the token *is* the auth, so\n * the call is unsigned — no chicken-and-egg credential bootstrap).\n *\n * Env vars (set by EKS when the pod's service account is annotated with a role):\n * - `AWS_ROLE_ARN` — the role to assume.\n * - `AWS_WEB_IDENTITY_TOKEN_FILE` — path to the projected SA token.\n * - `AWS_ROLE_SESSION_NAME` — optional session name (defaults to `baerly-storage`).\n * - `AWS_REGION` / `AWS_DEFAULT_REGION` — optional; selects the regional STS\n * endpoint (falls back to the global endpoint).\n *\n * STS credentials expire (~1 h); the returned provider reports `expiration`, so\n * the signing layer re-resolves before they lapse.\n */\nexport function fromWebIdentity(\n opts: {\n fetch?: typeof fetch;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n } = {},\n): CredentialsProvider {\n const doFetch = opts.fetch ?? fetch;\n const doReadFile = opts.readFile ?? fsReadFile;\n\n return async () => {\n const roleArn = process.env[\"AWS_ROLE_ARN\"];\n const tokenPath = process.env[\"AWS_WEB_IDENTITY_TOKEN_FILE\"];\n const sessionName = process.env[\"AWS_ROLE_SESSION_NAME\"] || DEFAULT_SESSION_NAME;\n const region = process.env[\"AWS_REGION\"] || process.env[\"AWS_DEFAULT_REGION\"];\n if (roleArn === undefined || roleArn === \"\") {\n throw new BaerlyError(\"InvalidConfig\", \"fromWebIdentity: AWS_ROLE_ARN not set\");\n }\n if (tokenPath === undefined || tokenPath === \"\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"fromWebIdentity: AWS_WEB_IDENTITY_TOKEN_FILE not set\",\n );\n }\n\n const token = await readProjectedToken(doReadFile, tokenPath, {\n provider: \"fromWebIdentity\",\n envVar: \"AWS_WEB_IDENTITY_TOKEN_FILE\",\n });\n\n // Regional endpoint when a region is known (lower latency, and required in\n // non-default partitions); otherwise the global endpoint.\n const endpoint =\n region !== undefined && region !== \"\"\n ? `https://sts.${region}.amazonaws.com/`\n : \"https://sts.amazonaws.com/\";\n const body = new URLSearchParams({\n Action: \"AssumeRoleWithWebIdentity\",\n Version: \"2011-06-15\",\n RoleArn: roleArn,\n RoleSessionName: sessionName,\n WebIdentityToken: token,\n }).toString();\n\n let res: Response;\n try {\n res = await doFetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/xml\",\n },\n body,\n // The POST carries the web-identity token as its only auth and is\n // unsigned, so a redirect would resend the token to the 3xx target.\n // STS never legitimately redirects this call — refuse rather than\n // follow, so a redirect surfaces as a NetworkError instead of leaking.\n redirect: \"error\",\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n } catch (error) {\n throw new BaerlyError(\n \"NetworkError\",\n `fromWebIdentity: STS fetch failed (${(error as Error).message})`,\n );\n }\n\n // 5xx + 429 are transient — NetworkError so callers / chained providers can\n // retry. Other 4xx (expired/invalid token, role trust mismatch) are\n // permanent — AccessDenied so retry loops short-circuit (see\n // PERMANENT_STORAGE_ERROR_CODES in @baerly/protocol's storage/retry.ts). Either way, fold the STS\n // <ErrorResponse> Code/Message into the message — a bare status turns the\n // exact misconfig this provider exists to debug (bad role trust policy,\n // token audience mismatch, clock skew, expired token) into a guessing game.\n if (!res.ok) {\n const stsErr = parseStsError(await res.text());\n const detail =\n stsErr?.Code !== undefined\n ? ` (${stsErr.Code}${stsErr.Message !== undefined ? `: ${stsErr.Message}` : \"\"})`\n : \"\";\n if (res.status >= 500 || res.status === 429) {\n throw new BaerlyError(\n \"NetworkError\",\n `fromWebIdentity: STS responded ${res.status}${detail}`,\n );\n }\n throw new BaerlyError(\n \"AccessDenied\",\n `fromWebIdentity: STS responded ${res.status}${detail}`,\n );\n }\n\n const parsed = parseAssumeRoleWithWebIdentity(await res.text());\n if (\n parsed.AccessKeyId === undefined ||\n parsed.SecretAccessKey === undefined ||\n parsed.SessionToken === undefined ||\n parsed.Expiration === undefined\n ) {\n throw new BaerlyError(\"InvalidResponse\", \"fromWebIdentity: malformed STS response\");\n }\n // A present-but-unparseable Expiration is as malformed as a missing field:\n // `new Date(bad)` yields an Invalid Date (getTime() → NaN) rather than\n // throwing, and the signer's `expiresAt - buffer > now()` refresh check is\n // false for NaN — so a bad timestamp would silently defeat credential\n // caching/rotation. Reject it here instead.\n const expiration = new Date(parsed.Expiration);\n if (Number.isNaN(expiration.getTime())) {\n throw new BaerlyError(\"InvalidResponse\", \"fromWebIdentity: malformed STS response\");\n }\n return {\n accessKeyId: parsed.AccessKeyId,\n secretAccessKey: parsed.SecretAccessKey,\n sessionToken: parsed.SessionToken,\n expiration,\n };\n };\n}\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { fromEksPodIdentity } from \"./from-eks-pod-identity.ts\";\nimport { fromWebIdentity } from \"./from-web-identity.ts\";\nimport type { CredentialsProvider } from \"./types.ts\";\n\n/**\n * Resolve AWS credentials on EKS regardless of which identity mechanism the\n * cluster uses, so callers don't have to know. EKS injects credentials one of\n * two ways:\n *\n * - **Pod Identity** (2023+): `AWS_CONTAINER_CREDENTIALS_FULL_URI` +\n * `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` → {@link fromEksPodIdentity}.\n * - **IRSA** (web-identity token): `AWS_ROLE_ARN` +\n * `AWS_WEB_IDENTITY_TOKEN_FILE` → {@link fromWebIdentity}.\n *\n * Detection runs on every resolve (Pod Identity preferred when both are\n * present), so the right mechanism is picked even if the env is populated late\n * and re-checked on each refresh. Use this instead of the mechanism-specific\n * providers unless you have a reason to pin one.\n */\nexport function fromEks(\n opts: {\n fetch?: typeof fetch;\n readFile?: (path: string, encoding: \"utf8\") => Promise<string>;\n } = {},\n): CredentialsProvider {\n const podIdentity = fromEksPodIdentity(opts);\n const webIdentity = fromWebIdentity(opts);\n\n return async () => {\n const uri = process.env[\"AWS_CONTAINER_CREDENTIALS_FULL_URI\"];\n const tokenFile = process.env[\"AWS_WEB_IDENTITY_TOKEN_FILE\"];\n if (uri !== undefined && uri !== \"\") {\n return podIdentity();\n }\n if (tokenFile !== undefined && tokenFile !== \"\") {\n return webIdentity();\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n \"fromEks: no EKS credentials in env — set AWS_CONTAINER_CREDENTIALS_FULL_URI \" +\n \"(Pod Identity) or AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN (IRSA)\",\n );\n };\n}\n","//#region src/utils/response/constants.ts\nconst X_ALREADY_SENT = \"x-hono-already-sent\";\n\n//#endregion\nexport { X_ALREADY_SENT as t };","//#region src/helper/websocket/index.ts\n/**\n* A context for controlling WebSockets\n*/\nvar WSContext = class {\n\t#init;\n\tconstructor(init) {\n\t\tthis.#init = init;\n\t\tthis.raw = init.raw;\n\t\tthis.url = init.url ? new URL(init.url) : null;\n\t\tthis.protocol = init.protocol ?? null;\n\t}\n\tsend(source, options) {\n\t\tthis.#init.send(source, options ?? {});\n\t}\n\traw;\n\tbinaryType = \"arraybuffer\";\n\tget readyState() {\n\t\treturn this.#init.readyState;\n\t}\n\turl;\n\tprotocol;\n\tclose(code, reason) {\n\t\tthis.#init.close(code, reason);\n\t}\n};\nconst createWSMessageEvent = (source) => {\n\treturn new MessageEvent(\"message\", { data: source });\n};\n/**\n* Create a WebSocket adapter/helper\n*/\nconst defineWebSocketHelper = (handler) => {\n\treturn ((...args) => {\n\t\tif (typeof args[0] === \"function\") {\n\t\t\tconst [createEvents, options] = args;\n\t\t\treturn async function upgradeWebSocket(c, next) {\n\t\t\t\tconst result = await handler(c, await createEvents(c), options);\n\t\t\t\tif (result) return result;\n\t\t\t\tawait next();\n\t\t\t};\n\t\t} else {\n\t\t\tconst [c, events, options] = args;\n\t\t\treturn (async () => {\n\t\t\t\tconst upgraded = await handler(c, events, options);\n\t\t\t\tif (!upgraded) throw new Error(\"Failed to upgrade WebSocket\");\n\t\t\t\treturn upgraded;\n\t\t\t})();\n\t\t}\n\t});\n};\n//#endregion\nexport { WSContext, createWSMessageEvent, defineWebSocketHelper };\n","import { t as X_ALREADY_SENT } from \"./constants-BLSFu_RU.mjs\";\nimport { STATUS_CODES, ServerResponse, createServer } from \"node:http\";\nimport { Http2ServerRequest, constants } from \"node:http2\";\nimport { Readable } from \"node:stream\";\nimport { defineWebSocketHelper } from \"hono/ws\";\n\n//#region src/error.ts\nvar RequestError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"RequestError\";\n\t}\n};\n\n//#endregion\n//#region src/headers.ts\nconst nonJoinedHeaders = new Set([\n\t\"age\",\n\t\"authorization\",\n\t\"content-length\",\n\t\"content-type\",\n\t\"etag\",\n\t\"expires\",\n\t\"from\",\n\t\"host\",\n\t\"if-modified-since\",\n\t\"if-unmodified-since\",\n\t\"last-modified\",\n\t\"location\",\n\t\"max-forwards\",\n\t\"proxy-authorization\",\n\t\"referer\",\n\t\"retry-after\",\n\t\"server\",\n\t\"user-agent\"\n]);\nconst validHeaderName = /^[!#$%&'*+\\-.^_`|~\\dA-Za-z]+$/;\nconst isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;\nconst normalizeHeaderValue = (value) => {\n\tif (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value;\n\tlet start = 0;\n\tlet end = value.length;\n\twhile (start < end && isHttpWhitespace(value.charCodeAt(start))) start++;\n\twhile (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--;\n\treturn value.slice(start, end);\n};\nconst forbiddenHeaderValue = /[\\0\\r\\n]/;\nconst GlobalHeaders = globalThis.Headers;\nconst materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => {\n\tconst headers = new HeadersCtor();\n\tfor (let i = 0; i < rawHeaders.length; i += 2) {\n\t\tconst name = rawHeaders[i];\n\t\tif (!name.startsWith(\":\")) headers.append(name, rawHeaders[i + 1]);\n\t}\n\treturn headers;\n};\nvar RequestHeaders = class {\n\t#incoming;\n\t#rawHeaders;\n\t#headers;\n\t#invalidValue;\n\tconstructor(incoming) {\n\t\tthis.#incoming = incoming;\n\t\tif (incoming instanceof Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice();\n\t}\n\tget #lazyRawHeaders() {\n\t\treturn this.#rawHeaders ??= this.#incoming.rawHeaders.slice();\n\t}\n\tget #native() {\n\t\tif (!this.#headers) {\n\t\t\tthis.#headers = materializeHeaders(this.#lazyRawHeaders);\n\t\t\tthis.#rawHeaders = void 0;\n\t\t}\n\t\treturn this.#headers;\n\t}\n\t#normalizedName(name) {\n\t\tif (typeof name !== \"string\") return;\n\t\tif (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`);\n\t\treturn name.toLowerCase();\n\t}\n\t#lookupHttp1(lowerName) {\n\t\tconst headers = this.#incoming instanceof Http2ServerRequest ? void 0 : this.#incoming.headers;\n\t\tif (!headers || nonJoinedHeaders.has(lowerName) || lowerName === \"set-cookie\" || lowerName === \"__proto__\") return;\n\t\tif (!Object.hasOwn(headers, lowerName)) return null;\n\t\tconst rawValue = headers[lowerName];\n\t\tif (typeof rawValue === \"string\") {\n\t\t\tconst value = normalizeHeaderValue(rawValue);\n\t\t\treturn forbiddenHeaderValue.test(value) ? void 0 : value;\n\t\t}\n\t}\n\t#lookup(rawHeaders, lowerName) {\n\t\tconst separator = lowerName === \"cookie\" ? \"; \" : \", \";\n\t\tlet value = null;\n\t\tfor (let i = 0; i < rawHeaders.length; i += 2) {\n\t\t\tconst rawName = rawHeaders[i];\n\t\t\tif (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) {\n\t\t\t\tconst rawValue = normalizeHeaderValue(rawHeaders[i + 1]);\n\t\t\t\tif (forbiddenHeaderValue.test(rawValue)) {\n\t\t\t\t\tthis.#invalidValue = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tvalue = value === null ? rawValue : value + separator + rawValue;\n\t\t\t}\n\t\t}\n\t\treturn value;\n\t}\n\tappend(name, value) {\n\t\tthis.#native.append(name, value);\n\t}\n\tdelete(name) {\n\t\tthis.#native.delete(name);\n\t}\n\tget(name) {\n\t\tconst lowerName = this.#normalizedName(name);\n\t\tif (lowerName && !this.#headers && !this.#invalidValue) {\n\t\t\tconst http1Value = this.#lookupHttp1(lowerName);\n\t\t\tif (http1Value !== void 0) return http1Value;\n\t\t\tconst value = this.#lookup(this.#lazyRawHeaders, lowerName);\n\t\t\tif (value !== void 0) return value;\n\t\t}\n\t\treturn this.#native.get(name);\n\t}\n\thas(name) {\n\t\tconst lowerName = this.#normalizedName(name);\n\t\tif (lowerName && !this.#headers && !this.#invalidValue) {\n\t\t\tconst http1Value = this.#lookupHttp1(lowerName);\n\t\t\tif (http1Value !== void 0) return http1Value !== null;\n\t\t\tconst value = this.#lookup(this.#lazyRawHeaders, lowerName);\n\t\t\tif (value !== void 0) return value !== null;\n\t\t}\n\t\treturn this.#native.has(name);\n\t}\n\tset(name, value) {\n\t\tthis.#native.set(name, value);\n\t}\n\tgetSetCookie() {\n\t\treturn this.#native.getSetCookie();\n\t}\n\tkeys() {\n\t\treturn this.#native.keys();\n\t}\n\tvalues() {\n\t\treturn this.#native.values();\n\t}\n\tentries() {\n\t\treturn this.#native.entries();\n\t}\n\tforEach(callback, thisArg) {\n\t\tthis.#native.forEach((value, key) => {\n\t\t\tcallback.call(thisArg, value, key, this);\n\t\t});\n\t}\n\t[Symbol.iterator]() {\n\t\treturn this.entries();\n\t}\n};\nObject.defineProperty(RequestHeaders.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Headers (lightweight) ${inspectFn(Object.fromEntries(this), {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);\nconst newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);\n\n//#endregion\n//#region src/url.ts\nconst reValidRequestUrl = /^\\/[!#$&-;=?-\\[\\]_a-z~]*$/;\nconst reDotSegment = /\\/\\.\\.?(?:[/?#]|$)/;\nconst reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\\d{3,4}|[6-9]\\d{3}))?$/;\nconst validateRequestTarget = (target) => {\n\tconst backslash = target.indexOf(\"\\\\\");\n\tif (backslash !== -1) {\n\t\tconst query = target.indexOf(\"?\");\n\t\tif (query === -1 || backslash < query) throw new RequestError(\"Backslash in request path\");\n\t}\n};\nconst buildUrl = (scheme, host, incomingUrl) => {\n\tconst url = `${scheme}://${host}${incomingUrl}`;\n\tif (!reValidHost.test(host)) {\n\t\tvalidateRequestTarget(incomingUrl);\n\t\tconst urlObj = new URL(url);\n\t\tif (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(\":\") ? host.replace(/:\\d+$/, \"\") : host).toLowerCase()) throw new RequestError(\"Invalid host header\");\n\t\treturn urlObj.href;\n\t} else if (incomingUrl.length === 0) return url + \"/\";\n\telse {\n\t\tif (incomingUrl.charCodeAt(0) !== 47) throw new RequestError(\"Invalid URL\");\n\t\tif (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) {\n\t\t\tvalidateRequestTarget(incomingUrl);\n\t\t\treturn new URL(url).href;\n\t\t}\n\t\treturn url;\n\t}\n};\n\n//#endregion\n//#region src/request.ts\nconst toRequestError = (e) => {\n\tif (e instanceof RequestError) return e;\n\treturn new RequestError(e.message, { cause: e });\n};\nconst GlobalRequest = global.Request;\nvar Request$1 = class extends GlobalRequest {\n\tconstructor(input, options) {\n\t\tif (typeof input === \"object\" && getRequestCache in input) {\n\t\t\tconst hasReplacementBody = options !== void 0 && \"body\" in options && options.body != null;\n\t\t\tif (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError(\"Cannot construct a Request with a Request object that has already been used.\");\n\t\t\tinput = input[getRequestCache]();\n\t\t}\n\t\tif (typeof (options?.body)?.getReader !== \"undefined\") options.duplex ??= \"half\";\n\t\tsuper(input, options);\n\t}\n};\nconst wrapBodyStream = Symbol(\"wrapBodyStream\");\nconst byteExactEncodings = new Set([\n\t\"latin1\",\n\t\"binary\",\n\t\"hex\",\n\t\"base64\",\n\t\"base64url\"\n]);\nconst isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);\nconst bodyBufferedBeforeDisconnectKey = Symbol(\"bodyBufferedBeforeDisconnect\");\nconst bodyBufferedLengthBeforeDisconnectKey = Symbol(\"bodyBufferedLengthBeforeDisconnect\");\nconst toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? \"utf8\");\nconst isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === \"function\" && isByteExactEncoding(incoming.readableEncoding);\nconst recordBodyBufferedBeforeDisconnect = (incoming) => {\n\tif (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;\n\tconst incomingWithRecovery = incoming;\n\tincomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;\n};\nconst readBodyBufferedBeforeDisconnect = (incoming, chunks) => {\n\tif (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;\n\tconst incomingWithRecovery = incoming;\n\tif (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];\n\tlet result;\n\tconst errored = incoming.errored;\n\tif (errored && errored.code !== \"ECONNRESET\") result = errored;\n\telse if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();\n\telse {\n\t\tconst bodyChunks = chunks ?? [];\n\t\tconst chunk = incoming.read();\n\t\tif (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));\n\t\tconst buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);\n\t\tresult = buffer;\n\t\tconst contentLength = incoming.headers[\"content-length\"];\n\t\tif (typeof contentLength === \"string\" && /^\\d+$/.test(contentLength)) {\n\t\t\tconst expectedLength = Number(contentLength);\n\t\t\tif (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();\n\t\t}\n\t}\n\tincomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;\n\treturn result;\n};\nconst enqueueBufferedBody = (controller, buffered) => {\n\tif (buffered instanceof Error) {\n\t\tcontroller.error(buffered);\n\t\treturn;\n\t}\n\tif (buffered.length > 0) controller.enqueue(buffered);\n\tcontroller.close();\n};\nconst newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n\tconst init = {\n\t\tmethod,\n\t\theaders,\n\t\tsignal: abortController.signal\n\t};\n\tif (method === \"TRACE\") {\n\t\tinit.method = \"GET\";\n\t\tconst req = new Request$1(url, init);\n\t\tObject.defineProperty(req, \"method\", { get() {\n\t\t\treturn \"TRACE\";\n\t\t} });\n\t\treturn req;\n\t}\n\tif (!(method === \"GET\" || method === \"HEAD\")) if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {\n\t\tcontroller.enqueue(incoming.rawBody);\n\t\tcontroller.close();\n\t} });\n\telse if (incoming[wrapBodyStream]) {\n\t\tlet reader;\n\t\tinit.body = new ReadableStream({ async pull(controller) {\n\t\t\ttry {\n\t\t\t\tif (!reader) {\n\t\t\t\t\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\t\t\t\t\tif (buffered !== void 0) {\n\t\t\t\t\t\tenqueueBufferedBody(controller, buffered);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treader ||= Readable.toWeb(incoming).getReader();\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t} });\n\t} else {\n\t\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\t\tif (buffered !== void 0) init.body = new ReadableStream({ start(controller) {\n\t\t\tenqueueBufferedBody(controller, buffered);\n\t\t} });\n\t\telse init.body = Readable.toWeb(incoming);\n\t}\n\treturn new Request$1(url, init);\n};\nconst getRequestCache = Symbol(\"getRequestCache\");\nconst requestCache = Symbol(\"requestCache\");\nconst incomingKey = Symbol(\"incomingKey\");\nconst urlKey = Symbol(\"urlKey\");\nconst methodKey = Symbol(\"methodKey\");\nconst headersKey = Symbol(\"headersKey\");\nconst abortControllerKey = Symbol(\"abortControllerKey\");\nconst getAbortController = Symbol(\"getAbortController\");\nconst abortRequest = Symbol(\"abortRequest\");\nconst bodyBufferKey = Symbol(\"bodyBuffer\");\nconst bodyReadPromiseKey = Symbol(\"bodyReadPromise\");\nconst bodyConsumedDirectlyKey = Symbol(\"bodyConsumedDirectly\");\nconst bodyLockReaderKey = Symbol(\"bodyLockReader\");\nconst abortReasonKey = Symbol(\"abortReason\");\nconst newBodyUnusableError = () => {\n\treturn /* @__PURE__ */ new TypeError(\"Body is unusable\");\n};\nconst rejectBodyUnusable = () => {\n\treturn Promise.reject(newBodyUnusableError());\n};\nconst textDecoder = new TextDecoder();\nconst consumeBodyDirectOnce = (request) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\trequest[bodyConsumedDirectlyKey] = true;\n};\nconst toArrayBuffer = (buf) => {\n\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n};\nconst contentType = (request) => {\n\treturn (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get(\"content-type\") || \"\";\n};\nconst methodTokenRegExp = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst normalizeIncomingMethod = (method) => {\n\tif (typeof method !== \"string\" || method.length === 0) return \"GET\";\n\tswitch (method) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"PATCH\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\":\n\t\tcase \"QUERY\": return method;\n\t}\n\tconst upper = method.toUpperCase();\n\tswitch (upper) {\n\t\tcase \"DELETE\":\n\t\tcase \"GET\":\n\t\tcase \"HEAD\":\n\t\tcase \"OPTIONS\":\n\t\tcase \"POST\":\n\t\tcase \"PUT\": return upper;\n\t\tdefault: return method;\n\t}\n};\nconst validateDirectReadMethod = (method) => {\n\tif (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);\n\tconst normalized = method.toUpperCase();\n\tif (normalized === \"CONNECT\" || normalized === \"TRACK\" || normalized === \"TRACE\" && method !== \"TRACE\") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);\n};\nconst readBodyWithFastPath = (request, method, fromBuffer) => {\n\tif (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\tconst methodName = request.method;\n\tif (methodName === \"GET\" || methodName === \"HEAD\") return request[getRequestCache]()[method]();\n\tconst methodValidationError = validateDirectReadMethod(methodName);\n\tif (methodValidationError) return Promise.reject(methodValidationError);\n\tif (request[requestCache]) {\n\t\tif (methodName !== \"TRACE\") return request[requestCache][method]();\n\t}\n\tconst alreadyUsedError = consumeBodyDirectOnce(request);\n\tif (alreadyUsedError) return alreadyUsedError;\n\tconst raw = readRawBodyIfAvailable(request);\n\tif (raw) {\n\t\tconst result = Promise.resolve(fromBuffer(raw, request));\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t}\n\treturn readBodyDirect(request).then((buf) => {\n\t\tconst result = fromBuffer(buf, request);\n\t\trequest[bodyBufferKey] = void 0;\n\t\treturn result;\n\t});\n};\nconst readRawBodyIfAvailable = (request) => {\n\tconst incoming = request[incomingKey];\n\tif (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;\n};\nconst normalizeAbortError = (request, incoming) => {\n\tif (incoming.errored) return incoming.errored;\n\tconst reason = request[abortReasonKey];\n\tif (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));\n\treturn /* @__PURE__ */ new Error(\"Client connection prematurely closed.\");\n};\nconst readBodyDirect = (request) => {\n\tif (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);\n\tif (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];\n\tconst incoming = request[incomingKey];\n\tif (incoming.readableDidRead) return rejectBodyUnusable();\n\tconst buffered = readBodyBufferedBeforeDisconnect(incoming);\n\tif (buffered !== void 0) {\n\t\tif (buffered instanceof Error) return Promise.reject(buffered);\n\t\trequest[bodyBufferKey] = buffered;\n\t\treturn Promise.resolve(buffered);\n\t}\n\tconst promise = new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\tlet settled = false;\n\t\tconst finish = (callback) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tcallback();\n\t\t};\n\t\tconst recoverCompleteBodyAfterDisconnect = (error) => {\n\t\t\tconst streamError = incoming.errored ?? error;\n\t\t\tif (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== \"ECONNRESET\") return false;\n\t\t\tfinish(() => {\n\t\t\t\tconst recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);\n\t\t\t\tif (recovered instanceof Error) reject(recovered);\n\t\t\t\telse if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));\n\t\t\t\telse {\n\t\t\t\t\trequest[bodyBufferKey] = recovered;\n\t\t\t\t\tresolve(recovered);\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn true;\n\t\t};\n\t\tconst onData = (chunk) => {\n\t\t\tchunks.push(toBufferChunk(chunk, incoming.readableEncoding));\n\t\t};\n\t\tconst onEnd = () => {\n\t\t\tfinish(() => {\n\t\t\t\tconst buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);\n\t\t\t\trequest[bodyBufferKey] = buffer;\n\t\t\t\tresolve(buffer);\n\t\t\t});\n\t\t};\n\t\tconst onError = (error) => {\n\t\t\tif (recoverCompleteBodyAfterDisconnect(error)) return;\n\t\t\tfinish(() => {\n\t\t\t\treject(error);\n\t\t\t});\n\t\t};\n\t\tconst onClose = () => {\n\t\t\tif (incoming.readableEnded) {\n\t\t\t\tonEnd();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (recoverCompleteBodyAfterDisconnect()) return;\n\t\t\tfinish(() => {\n\t\t\t\treject(normalizeAbortError(request, incoming));\n\t\t\t});\n\t\t};\n\t\tconst cleanup = () => {\n\t\t\tincoming.off(\"data\", onData);\n\t\t\tincoming.off(\"end\", onEnd);\n\t\t\tincoming.off(\"error\", onError);\n\t\t\tincoming.off(\"close\", onClose);\n\t\t\trequest[bodyReadPromiseKey] = void 0;\n\t\t};\n\t\tincoming.on(\"data\", onData);\n\t\tincoming.on(\"end\", onEnd);\n\t\tincoming.on(\"error\", onError);\n\t\tincoming.on(\"close\", onClose);\n\t\tqueueMicrotask(() => {\n\t\t\tif (settled) return;\n\t\t\tif (incoming.readableEnded) onEnd();\n\t\t\telse if (incoming.errored) onError(incoming.errored);\n\t\t\telse if (incoming.destroyed) onClose();\n\t\t});\n\t});\n\trequest[bodyReadPromiseKey] = promise;\n\treturn promise;\n};\nconst requestPrototype = {\n\tget method() {\n\t\treturn this[methodKey];\n\t},\n\tget url() {\n\t\treturn this[urlKey];\n\t},\n\tget headers() {\n\t\treturn this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n\t},\n\t[abortRequest](reason) {\n\t\tif (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;\n\t\tconst abortController = this[abortControllerKey];\n\t\tif (abortController && !abortController.signal.aborted) abortController.abort(reason);\n\t},\n\t[getAbortController]() {\n\t\tthis[abortControllerKey] ||= new AbortController();\n\t\tif (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);\n\t\treturn this[abortControllerKey];\n\t},\n\t[getRequestCache]() {\n\t\tconst abortController = this[getAbortController]();\n\t\tif (this[requestCache]) return this[requestCache];\n\t\tconst method = this.method;\n\t\tif (this[bodyConsumedDirectlyKey] && !(method === \"GET\" || method === \"HEAD\")) {\n\t\t\tthis[bodyBufferKey] = void 0;\n\t\t\tconst init = {\n\t\t\t\tmethod: method === \"TRACE\" ? \"GET\" : method,\n\t\t\t\theaders: this.headers,\n\t\t\t\tsignal: abortController.signal\n\t\t\t};\n\t\t\tif (method !== \"TRACE\") {\n\t\t\t\tinit.body = new ReadableStream({ start(c) {\n\t\t\t\t\tc.close();\n\t\t\t\t} });\n\t\t\t\tinit.duplex = \"half\";\n\t\t\t}\n\t\t\tconst req = new Request$1(this[urlKey], init);\n\t\t\tif (method === \"TRACE\") Object.defineProperty(req, \"method\", { get() {\n\t\t\t\treturn \"TRACE\";\n\t\t\t} });\n\t\t\treturn this[requestCache] = req;\n\t\t}\n\t\treturn this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);\n\t},\n\tget body() {\n\t\tif (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;\n\t\tconst request = this[getRequestCache]();\n\t\tif (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();\n\t\treturn request.body;\n\t},\n\tget bodyUsed() {\n\t\tif (this[bodyConsumedDirectlyKey]) return true;\n\t\tif (this[requestCache]) return this[requestCache].bodyUsed;\n\t\treturn false;\n\t}\n};\nObject.defineProperty(requestPrototype, \"signal\", { get() {\n\treturn this[getAbortController]().signal;\n} });\n[\n\t\"cache\",\n\t\"credentials\",\n\t\"destination\",\n\t\"duplex\",\n\t\"integrity\",\n\t\"mode\",\n\t\"redirect\",\n\t\"referrer\",\n\t\"referrerPolicy\",\n\t\"keepalive\"\n].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { get() {\n\t\treturn this[getRequestCache]()[k];\n\t} });\n});\n[\"clone\", \"formData\"].forEach((k) => {\n\tObject.defineProperty(requestPrototype, k, { value: function() {\n\t\tif (this[bodyConsumedDirectlyKey]) {\n\t\t\tif (k === \"clone\") throw newBodyUnusableError();\n\t\t\treturn rejectBodyUnusable();\n\t\t}\n\t\treturn this[getRequestCache]()[k]();\n\t} });\n});\nObject.defineProperty(requestPrototype, \"text\", { value: function() {\n\treturn readBodyWithFastPath(this, \"text\", (buf) => textDecoder.decode(buf));\n} });\nObject.defineProperty(requestPrototype, \"arrayBuffer\", { value: function() {\n\treturn readBodyWithFastPath(this, \"arrayBuffer\", (buf) => toArrayBuffer(buf));\n} });\nObject.defineProperty(requestPrototype, \"blob\", { value: function() {\n\treturn readBodyWithFastPath(this, \"blob\", (buf, request) => {\n\t\tconst type = contentType(request);\n\t\tconst init = type ? { headers: { \"content-type\": type } } : void 0;\n\t\treturn new Response(buf, init).blob();\n\t});\n} });\nObject.defineProperty(requestPrototype, \"json\", { value: function() {\n\tif (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();\n\treturn this.text().then(JSON.parse);\n} });\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Request (lightweight) ${inspectFn({\n\t\tmethod: this.method,\n\t\turl: this.url,\n\t\theaders: this.headers,\n\t\tnativeRequest: this[requestCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(requestPrototype, Request$1.prototype);\nconst newRequest = (incoming, defaultHostname) => {\n\tconst req = Object.create(requestPrototype);\n\treq[incomingKey] = incoming;\n\treq[methodKey] = normalizeIncomingMethod(incoming.method);\n\tconst incomingUrl = incoming.url || \"\";\n\tif (incomingUrl[0] !== \"/\" && (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n\t\tif (incoming instanceof Http2ServerRequest) throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n\t\ttry {\n\t\t\tvalidateRequestTarget(incomingUrl);\n\t\t\treq[urlKey] = new URL(incomingUrl).href;\n\t\t} catch (e) {\n\t\t\tthrow new RequestError(\"Invalid absolute URL\", { cause: e });\n\t\t}\n\t\treturn req;\n\t}\n\tconst host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n\tif (!host) throw new RequestError(\"Missing host header\");\n\tlet scheme;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\tscheme = incoming.scheme;\n\t\tif (!(scheme === \"http\" || scheme === \"https\")) throw new RequestError(\"Unsupported scheme\");\n\t} else scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n\ttry {\n\t\treq[urlKey] = buildUrl(scheme, host, incomingUrl);\n\t} catch (e) {\n\t\tif (e instanceof RequestError) throw e;\n\t\telse throw new RequestError(\"Invalid URL\", { cause: e });\n\t}\n\treturn req;\n};\n\n//#endregion\n//#region src/response.ts\nconst defaultContentType = \"text/plain; charset=UTF-8\";\nconst responseCache = Symbol(\"responseCache\");\nconst getResponseCache = Symbol(\"getResponseCache\");\nconst cacheKey = Symbol(\"cache\");\nconst GlobalResponse = global.Response;\nvar Response$1 = class Response$1 {\n\t#body;\n\t#init;\n\t[getResponseCache]() {\n\t\tconst cache = this[cacheKey];\n\t\tconst liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;\n\t\tdelete this[cacheKey];\n\t\treturn this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {\n\t\t\tstatus: this.#init?.status,\n\t\t\tstatusText: this.#init?.statusText,\n\t\t\theaders: liveHeaders\n\t\t} : this.#init);\n\t}\n\tconstructor(body, init) {\n\t\tlet headers;\n\t\tthis.#body = body;\n\t\tif (init instanceof GlobalResponse) {\n\t\t\tconst cachedGlobalResponse = init[responseCache];\n\t\t\tif (cachedGlobalResponse) {\n\t\t\t\tthis.#init = cachedGlobalResponse;\n\t\t\t\tthis[getResponseCache]();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#init = init instanceof Response$1 ? init.#init : init;\n\t\t\theaders = new Headers(init.headers);\n\t\t} else this.#init = init;\n\t\tif (body == null || typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [\n\t\t\tinit?.status || 200,\n\t\t\tbody ?? null,\n\t\t\theaders || init?.headers\n\t\t];\n\t}\n\tget headers() {\n\t\tconst cache = this[cacheKey];\n\t\tif (cache) {\n\t\t\tif (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { \"content-type\": defaultContentType }));\n\t\t\treturn cache[2];\n\t\t}\n\t\treturn this[getResponseCache]().headers;\n\t}\n\tget status() {\n\t\treturn this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n\t}\n\tget ok() {\n\t\tconst status = this.status;\n\t\treturn status >= 200 && status < 300;\n\t}\n};\n[\n\t\"body\",\n\t\"bodyUsed\",\n\t\"redirected\",\n\t\"statusText\",\n\t\"trailers\",\n\t\"type\",\n\t\"url\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { get() {\n\t\treturn this[getResponseCache]()[k];\n\t} });\n});\n[\n\t\"arrayBuffer\",\n\t\"blob\",\n\t\"clone\",\n\t\"formData\",\n\t\"json\",\n\t\"text\"\n].forEach((k) => {\n\tObject.defineProperty(Response$1.prototype, k, { value: function() {\n\t\treturn this[getResponseCache]()[k]();\n\t} });\n});\nObject.defineProperty(Response$1.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), { value: function(depth, options, inspectFn) {\n\treturn `Response (lightweight) ${inspectFn({\n\t\tstatus: this.status,\n\t\theaders: this.headers,\n\t\tok: this.ok,\n\t\tnativeResponse: this[responseCache]\n\t}, {\n\t\t...options,\n\t\tdepth: depth == null ? null : depth - 1\n\t})}`;\n} });\nObject.setPrototypeOf(Response$1, GlobalResponse);\nObject.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);\nconst validRedirectUrl = /^https?:\\/\\/[!#-;=?-[\\]_a-z~A-Z]+$/;\nconst parseRedirectUrl = (url) => {\n\tif (url instanceof URL) return url.href;\n\tif (validRedirectUrl.test(url)) return url;\n\treturn new URL(url).href;\n};\nconst validRedirectStatuses = new Set([\n\t301,\n\t302,\n\t303,\n\t307,\n\t308\n]);\nObject.defineProperty(Response$1, \"redirect\", {\n\tvalue: function redirect(url, status = 302) {\n\t\tif (!validRedirectStatuses.has(status)) throw new RangeError(\"Invalid status code\");\n\t\treturn new Response$1(null, {\n\t\t\tstatus,\n\t\t\theaders: { location: parseRedirectUrl(url) }\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\nObject.defineProperty(Response$1, \"json\", {\n\tvalue: function json(data, init) {\n\t\tconst body = JSON.stringify(data);\n\t\tif (body === void 0) throw new TypeError(\"The data is not JSON serializable\");\n\t\tconst initHeaders = init?.headers;\n\t\tlet headers;\n\t\tif (initHeaders) {\n\t\t\theaders = new Headers(initHeaders);\n\t\t\tif (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n\t\t} else headers = { \"content-type\": \"application/json\" };\n\t\treturn new Response$1(body, {\n\t\t\tstatus: init?.status ?? 200,\n\t\t\tstatusText: init?.statusText,\n\t\t\theaders\n\t\t});\n\t},\n\twritable: true,\n\tconfigurable: true\n});\n\n//#endregion\n//#region src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n\treturn Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n\tconst cancel = (error) => {\n\t\treader.cancel(error).catch(() => {});\n\t};\n\tconst stream = writable.stream;\n\tif (writable.destroyed || stream?.closed || stream?.destroyed) {\n\t\tcancel();\n\t\treturn reader.closed;\n\t}\n\twritable.on(\"close\", cancel);\n\twritable.on(\"error\", cancel);\n\t(currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n\treturn reader.closed.finally(() => {\n\t\twritable.off(\"close\", cancel);\n\t\twritable.off(\"error\", cancel);\n\t});\n\tfunction handleStreamError(error) {\n\t\tif (error) writable.destroy(error);\n\t}\n\tfunction onDrain() {\n\t\treader.read().then(flow, handleStreamError);\n\t}\n\tfunction flow({ done, value }) {\n\t\ttry {\n\t\t\tif (done) writable.end();\n\t\t\telse if (!writable.write(value)) writable.once(\"drain\", onDrain);\n\t\t\telse reader.read().then(flow, handleStreamError);\n\t\t} catch (e) {\n\t\t\thandleStreamError(e);\n\t\t}\n\t}\n}\nfunction writeFromReadableStream(stream, writable) {\n\tif (stream.locked) throw new TypeError(\"ReadableStream is locked.\");\n\telse if (writable.destroyed) {\n\t\tstream.cancel().catch(() => {});\n\t\treturn;\n\t}\n\treturn writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nconst buildOutgoingHttpHeaders = (headers, defaultContentType) => {\n\tconst res = {};\n\tif (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);\n\tif (headers.has(\"set-cookie\")) {\n\t\tconst cookies = [];\n\t\tfor (const [k, v] of headers) if (k === \"set-cookie\") cookies.push(v);\n\t\telse res[k] = v;\n\t\tif (cookies.length > 0) res[\"set-cookie\"] = cookies;\n\t} else for (const [k, v] of headers) res[k] = v;\n\tif (defaultContentType) res[\"content-type\"] ??= defaultContentType;\n\treturn res;\n};\n\n//#endregion\n//#region src/listener.ts\nconst outgoingEnded = Symbol(\"outgoingEnded\");\nconst incomingDraining = Symbol(\"incomingDraining\");\nconst DRAIN_TIMEOUT_MS = 500;\nconst MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nconst drainIncoming = (incoming) => {\n\tconst incomingWithDrainState = incoming;\n\tif (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;\n\tincomingWithDrainState[incomingDraining] = true;\n\tif (incoming instanceof Http2ServerRequest) {\n\t\ttry {\n\t\t\tincoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);\n\t\t} catch {}\n\t\treturn;\n\t}\n\tlet bytesRead = 0;\n\tconst cleanup = () => {\n\t\tclearTimeout(timer);\n\t\tincoming.off(\"data\", onData);\n\t\tincoming.off(\"end\", cleanup);\n\t\tincoming.off(\"error\", cleanup);\n\t};\n\tconst forceClose = () => {\n\t\tcleanup();\n\t\tconst socket = incoming.socket;\n\t\tif (socket && !socket.destroyed) {\n\t\t\tif (typeof socket.destroySoon === \"function\") socket.destroySoon();\n\t\t\telse if (typeof socket.destroy === \"function\") socket.destroy();\n\t\t}\n\t};\n\tconst timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n\ttimer.unref?.();\n\tconst onData = (chunk) => {\n\t\tbytesRead += chunk.length;\n\t\tif (bytesRead > MAX_DRAIN_BYTES) forceClose();\n\t};\n\tincoming.on(\"data\", onData);\n\tincoming.on(\"end\", cleanup);\n\tincoming.on(\"error\", cleanup);\n\tincoming.resume();\n};\nconst makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {\n\tif (incoming.errored) {\n\t\trecordBodyBufferedBeforeDisconnect(incoming);\n\t\treq[abortRequest](incoming.errored.toString());\n\t} else if (!outgoing.writableFinished || incoming instanceof Http2ServerRequest && incoming.aborted) {\n\t\trecordBodyBufferedBeforeDisconnect(incoming);\n\t\treq[abortRequest](\"Client connection prematurely closed.\");\n\t}\n\tif (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {\n\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\tdrainIncoming(incoming);\n\t\t});\n\t});\n};\nconst isImmediateCacheableResponse = (res) => {\n\tif (!(cacheKey in res)) return false;\n\tconst body = res[cacheKey][1];\n\treturn body === null || typeof body === \"string\" || body instanceof Uint8Array;\n};\nconst handleRequestError = () => new Response(null, { status: 400 });\nconst handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500 });\nconst handleResponseError = (e, outgoing) => {\n\tconst err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n\tif (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") console.info(\"The user aborted a request.\");\n\telse {\n\t\tconsole.error(e);\n\t\tif (!outgoing.headersSent) {\n\t\t\tif (outgoing instanceof ServerResponse) outgoing._contentLength = null;\n\t\t\toutgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n\t\t}\n\t\toutgoing.end(`Error: ${err.message}`);\n\t\toutgoing.destroy(err);\n\t}\n};\nconst flushHeaders = (outgoing) => {\n\tif (\"flushHeaders\" in outgoing && outgoing.writable) outgoing.flushHeaders();\n};\nconst trySetContentLength = (outgoing, status, length) => {\n\tconst http1 = outgoing;\n\tif (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\")) {\n\t\thttp1._contentLength = length;\n\t\treturn true;\n\t}\n\treturn false;\n};\nconst writeDefaultHeaders = (outgoing, status, length) => {\n\tif (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { \"Content-Type\": defaultContentType });\n\telse outgoing.writeHead(status, {\n\t\t\"Content-Type\": defaultContentType,\n\t\t\"Content-Length\": length\n\t});\n};\nconst responseViaCache = async (res, outgoing) => {\n\tlet [status, body, header] = res[cacheKey];\n\tif (!header) {\n\t\tif (body === null) {\n\t\t\toutgoing.writeHead(status);\n\t\t\toutgoing.end();\n\t\t} else if (typeof body === \"string\") {\n\t\t\twriteDefaultHeaders(outgoing, status, Buffer.byteLength(body));\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Uint8Array) {\n\t\t\twriteDefaultHeaders(outgoing, status, body.byteLength);\n\t\t\toutgoing.end(body);\n\t\t} else if (body instanceof Blob) {\n\t\t\twriteDefaultHeaders(outgoing, status, body.size);\n\t\t\toutgoing.end(new Uint8Array(await body.arrayBuffer()));\n\t\t} else {\n\t\t\toutgoing.writeHead(status, { \"Content-Type\": defaultContentType });\n\t\t\tflushHeaders(outgoing);\n\t\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t\t}\n\t\toutgoing[outgoingEnded]?.();\n\t\treturn;\n\t}\n\tlet hasContentLength = false;\n\tlet plainHeaders = false;\n\tlet canAutoLength = true;\n\tif (header instanceof Headers) {\n\t\thasContentLength = header.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);\n\t} else if (Array.isArray(header)) {\n\t\tconst headerObj = new Headers(header);\n\t\thasContentLength = headerObj.has(\"content-length\");\n\t\theader = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);\n\t} else {\n\t\tplainHeaders = true;\n\t\tfor (const key in header) {\n\t\t\tif (key.length === 14 && key.toLowerCase() === \"content-length\") {\n\t\t\t\thasContentLength = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (key.length === 17 && key.toLowerCase() === \"transfer-encoding\" || key.length === 7 && key.toLowerCase() === \"trailer\") canAutoLength = false;\n\t\t}\n\t}\n\tif (!hasContentLength) {\n\t\tlet length;\n\t\tif (typeof body === \"string\") length = Buffer.byteLength(body);\n\t\telse if (body instanceof Uint8Array) length = body.byteLength;\n\t\telse if (body instanceof Blob) length = body.size;\n\t\tif (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) {\n\t\t\tif (plainHeaders) header = { ...header };\n\t\t\theader[\"Content-Length\"] = length;\n\t\t}\n\t}\n\toutgoing.writeHead(status, header);\n\tif (body == null) outgoing.end();\n\telse if (typeof body === \"string\" || body instanceof Uint8Array) outgoing.end(body);\n\telse if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));\n\telse {\n\t\tflushHeaders(outgoing);\n\t\tawait writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst isPromise = (res) => typeof res.then === \"function\";\nconst responseViaResponseObject = async (res, outgoing, options = {}) => {\n\tif (isPromise(res)) if (options.errorHandler) try {\n\t\tres = await res;\n\t} catch (err) {\n\t\tconst errRes = await options.errorHandler(err);\n\t\tif (!errRes) return;\n\t\tres = errRes;\n\t}\n\telse res = await res.catch(handleFetchError);\n\tif (cacheKey in res) return responseViaCache(res, outgoing);\n\tconst resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);\n\tif (res.body) {\n\t\tconst reader = res.body.getReader();\n\t\tconst values = [];\n\t\tlet done = false;\n\t\tlet currentReadPromise = void 0;\n\t\tif (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n\t\t\tlet maxReadCount = 2;\n\t\t\tfor (let i = 0; i < maxReadCount; i++) {\n\t\t\t\tcurrentReadPromise ||= reader.read();\n\t\t\t\tconst chunk = await readWithoutBlocking(currentReadPromise);\n\t\t\t\tif (!chunk) {\n\t\t\t\t\tif (i === 1) {\n\t\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve));\n\t\t\t\t\t\tmaxReadCount = 3;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcurrentReadPromise = void 0;\n\t\t\t\tif (chunk.value) values.push(chunk.value);\n\t\t\t\tif (chunk.done) {\n\t\t\t\t\tdone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (done && !(\"content-length\" in resHeaderRecord)) resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n\t\t}\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\tvalues.forEach((value) => {\n\t\t\toutgoing.write(value);\n\t\t});\n\t\tif (done) outgoing.end();\n\t\telse {\n\t\t\tif (values.length === 0) flushHeaders(outgoing);\n\t\t\tawait writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n\t\t}\n\t} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {\n\t\toutgoing.writeHead(res.status, resHeaderRecord);\n\t\toutgoing.end();\n\t}\n\toutgoing[outgoingEnded]?.();\n};\nconst getRequestListener = (fetchCallback, options = {}) => {\n\tconst autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n\tif (options.overrideGlobalObjects !== false && global.Request !== Request$1) {\n\t\tObject.defineProperty(global, \"Request\", { value: Request$1 });\n\t\tObject.defineProperty(global, \"Response\", { value: Response$1 });\n\t}\n\treturn async (incoming, outgoing) => {\n\t\tlet res, req;\n\t\tlet needsBodyCleanup = false;\n\t\tlet closeHandlerAttached = false;\n\t\tconst ensureCloseHandler = () => {\n\t\t\tif (!req || closeHandlerAttached) return;\n\t\t\tcloseHandlerAttached = true;\n\t\t\toutgoing.on(\"close\", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));\n\t\t};\n\t\ttry {\n\t\t\treq = newRequest(incoming, options.hostname);\n\t\t\tneedsBodyCleanup = autoCleanupIncoming && !(incoming.method === \"GET\" || incoming.method === \"HEAD\");\n\t\t\tif (needsBodyCleanup) {\n\t\t\t\tincoming[wrapBodyStream] = true;\n\t\t\t\tif (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {\n\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\tif (!incoming.readableEnded) setTimeout(() => {\n\t\t\t\t\t\t\tincoming.destroy();\n\t\t\t\t\t\t\toutgoing.destroy();\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}\n\t\t\tres = fetchCallback(req, {\n\t\t\t\tincoming,\n\t\t\t\toutgoing\n\t\t\t});\n\t\t\tif (!isPromise(res) && isImmediateCacheableResponse(res)) {\n\t\t\t\tif (needsBodyCleanup && !incoming.readableEnded) outgoing.once(\"finish\", () => {\n\t\t\t\t\tif (!incoming.readableEnded) drainIncoming(incoming);\n\t\t\t\t});\n\t\t\t\treturn responseViaCache(res, outgoing);\n\t\t\t}\n\t\t\tensureCloseHandler();\n\t\t} catch (e) {\n\t\t\tif (!res) if (options.errorHandler) {\n\t\t\t\tensureCloseHandler();\n\t\t\t\tres = await options.errorHandler(req ? e : toRequestError(e));\n\t\t\t\tif (!res) return;\n\t\t\t} else if (!req) res = handleRequestError();\n\t\t\telse res = handleFetchError(e);\n\t\t\telse return handleResponseError(e, outgoing);\n\t\t}\n\t\ttry {\n\t\t\treturn await responseViaResponseObject(res, outgoing, options);\n\t\t} catch (e) {\n\t\t\treturn handleResponseError(e, outgoing);\n\t\t}\n\t};\n};\n\n//#endregion\n//#region src/websocket.ts\n/**\n* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n*/\nconst CloseEvent = globalThis.CloseEvent ?? class extends Event {\n\t#eventInitDict;\n\tconstructor(type, eventInitDict = {}) {\n\t\tsuper(type, eventInitDict);\n\t\tthis.#eventInitDict = eventInitDict;\n\t}\n\tget wasClean() {\n\t\treturn this.#eventInitDict.wasClean ?? false;\n\t}\n\tget code() {\n\t\treturn this.#eventInitDict.code ?? 0;\n\t}\n\tget reason() {\n\t\treturn this.#eventInitDict.reason ?? \"\";\n\t}\n};\n/**\n* Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.\n* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent\n*/\nconst ErrorEvent = globalThis.ErrorEvent ?? class extends Event {\n\t#eventInitDict;\n\tconstructor(type, eventInitDict = {}) {\n\t\tsuper(type, eventInitDict);\n\t\tthis.#eventInitDict = eventInitDict;\n\t}\n\tget message() {\n\t\treturn this.#eventInitDict.message ?? \"\";\n\t}\n\tget filename() {\n\t\treturn this.#eventInitDict.filename ?? \"\";\n\t}\n\tget lineno() {\n\t\treturn this.#eventInitDict.lineno ?? 0;\n\t}\n\tget colno() {\n\t\treturn this.#eventInitDict.colno ?? 0;\n\t}\n\tget error() {\n\t\treturn this.#eventInitDict.error ?? null;\n\t}\n};\nconst generateConnectionSymbol = () => Symbol(\"connection\");\nconst CONNECTION_SYMBOL_KEY = Symbol(\"CONNECTION_SYMBOL_KEY\");\nconst WAIT_FOR_WEBSOCKET_SYMBOL = Symbol(\"WAIT_FOR_WEBSOCKET_SYMBOL\");\nconst responseHeadersToSkip = new Set([\n\t\"connection\",\n\t\"content-length\",\n\t\"keep-alive\",\n\t\"proxy-authenticate\",\n\t\"proxy-authorization\",\n\t\"te\",\n\t\"trailer\",\n\t\"transfer-encoding\",\n\t\"upgrade\",\n\t\"sec-websocket-accept\",\n\t\"sec-websocket-extensions\",\n\t\"sec-websocket-protocol\"\n]);\nconst appendResponseHeaders = (headers, responseHeaders) => {\n\tif (!responseHeaders) return;\n\tresponseHeaders.forEach((value, key) => {\n\t\tif (responseHeadersToSkip.has(key.toLowerCase())) return;\n\t\theaders.push(`${key}: ${value}`);\n\t});\n};\nconst rejectUpgradeRequest = (socket, status, responseHeaders) => {\n\tif (socket.destroyed) return;\n\tconst responseLines = [\"Connection: close\", \"Content-Length: 0\"];\n\tappendResponseHeaders(responseLines, responseHeaders);\n\tsocket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? \"\"}\\r\\n${responseLines.join(\"\\r\\n\")}\\r\\n\\r\n`);\n};\nconst createUpgradeRequest = (request) => {\n\tconst protocol = request.socket.encrypted ? \"https\" : \"http\";\n\tconst incomingUrl = request.url ?? \"/\";\n\tlet url;\n\tif (incomingUrl[0] !== \"/\" && (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n\t\tvalidateRequestTarget(incomingUrl);\n\t\turl = new URL(incomingUrl).href;\n\t} else url = buildUrl(protocol, request.headers.host ?? \"localhost\", incomingUrl);\n\tconst headers = new Headers();\n\tfor (const key in request.headers) {\n\t\tconst value = request.headers[key];\n\t\tif (!value) continue;\n\t\theaders.append(key, Array.isArray(value) ? value[0] : value);\n\t}\n\treturn new Request(url, { headers });\n};\nconst setupWebSocket = (options) => {\n\tconst { server, fetchCallback, wss } = options;\n\tconst waiterMap = /* @__PURE__ */ new Map();\n\twss.on(\"connection\", (ws, request) => {\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (waiter) {\n\t\t\twaiter.resolve(ws);\n\t\t\twaiterMap.delete(request);\n\t\t}\n\t});\n\tconst rejectWaiter = (request) => {\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (waiter) {\n\t\t\twaiterMap.delete(request);\n\t\t\twaiter.reject(/* @__PURE__ */ new Error(\"WebSocket handshake aborted\"));\n\t\t}\n\t};\n\tconst waitForWebSocket = (request, connectionSymbol) => {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\twaiterMap.set(request, {\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\tconnectionSymbol\n\t\t\t});\n\t\t});\n\t};\n\tserver.on(\"upgrade\", async (request, socket, head) => {\n\t\tif (request.headers.upgrade?.toLowerCase() !== \"websocket\") return;\n\t\tconst ignoreSocketError = () => {};\n\t\tconst reclaimWaiterOnClose = () => rejectWaiter(request);\n\t\tsocket.on(\"error\", ignoreSocketError);\n\t\tsocket.once(\"close\", reclaimWaiterOnClose);\n\t\tconst env = {\n\t\t\tincoming: request,\n\t\t\toutgoing: void 0,\n\t\t\twss,\n\t\t\t[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket\n\t\t};\n\t\tlet status = 400;\n\t\tlet responseHeaders;\n\t\ttry {\n\t\t\tconst response = await fetchCallback(createUpgradeRequest(request), env);\n\t\t\tif (response instanceof Response) {\n\t\t\t\tstatus = response.status;\n\t\t\t\tresponseHeaders = response.headers;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, error instanceof RequestError ? 400 : 500);\n\t\t\treturn;\n\t\t}\n\t\tif (socket.destroyed) {\n\t\t\trejectWaiter(request);\n\t\t\treturn;\n\t\t}\n\t\tconst waiter = waiterMap.get(request);\n\t\tif (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {\n\t\t\trejectWaiter(request);\n\t\t\tif (server.listenerCount(\"upgrade\") === 1) rejectUpgradeRequest(socket, status, responseHeaders);\n\t\t\treturn;\n\t\t}\n\t\tconst addResponseHeaders = (headers) => {\n\t\t\tappendResponseHeaders(headers, responseHeaders);\n\t\t};\n\t\twss.on(\"headers\", addResponseHeaders);\n\t\ttry {\n\t\t\twss.handleUpgrade(request, socket, head, (ws) => {\n\t\t\t\tsocket.off(\"close\", reclaimWaiterOnClose);\n\t\t\t\tsocket.off(\"error\", ignoreSocketError);\n\t\t\t\twss.emit(\"connection\", ws, request);\n\t\t\t});\n\t\t} finally {\n\t\t\twss.off(\"headers\", addResponseHeaders);\n\t\t}\n\t});\n\tserver.on(\"close\", () => {\n\t\twss.close();\n\t});\n};\nconst upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {\n\tif (c.req.header(\"upgrade\")?.toLowerCase() !== \"websocket\") return;\n\tconst env = c.env;\n\tconst waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];\n\tif (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });\n\tconst connectionSymbol = generateConnectionSymbol();\n\tenv[CONNECTION_SYMBOL_KEY] = connectionSymbol;\n\t(async () => {\n\t\tlet ws;\n\t\ttry {\n\t\t\tws = await waitForWebSocket(env.incoming, connectionSymbol);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tconst messagesReceivedInStarting = [];\n\t\tconst bufferMessage = (data, isBinary) => {\n\t\t\tmessagesReceivedInStarting.push([data, isBinary]);\n\t\t};\n\t\tws.on(\"message\", bufferMessage);\n\t\tconst ctx = {\n\t\t\tbinaryType: \"arraybuffer\",\n\t\t\tclose(code, reason) {\n\t\t\t\tws.close(code, reason);\n\t\t\t},\n\t\t\tprotocol: ws.protocol,\n\t\t\traw: ws,\n\t\t\tget readyState() {\n\t\t\t\treturn ws.readyState;\n\t\t\t},\n\t\t\tsend(source, opts) {\n\t\t\t\tws.send(source, { compress: opts?.compress });\n\t\t\t},\n\t\t\turl: new URL(c.req.url)\n\t\t};\n\t\ttry {\n\t\t\tevents?.onOpen?.(new Event(\"open\"), ctx);\n\t\t} catch (e) {\n\t\t\t(options?.onError ?? console.error)(e);\n\t\t}\n\t\tconst handleMessage = (data, isBinary) => {\n\t\t\tconst datas = Array.isArray(data) ? data : [data];\n\t\t\tfor (const data of datas) try {\n\t\t\t\tevents?.onMessage?.(new MessageEvent(\"message\", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === \"string\" ? data : Buffer.from(data).toString(\"utf-8\") }), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t};\n\t\tws.off(\"message\", bufferMessage);\n\t\tfor (const message of messagesReceivedInStarting) handleMessage(...message);\n\t\tws.on(\"message\", (data, isBinary) => {\n\t\t\thandleMessage(data, isBinary);\n\t\t});\n\t\tws.on(\"close\", (code, reason) => {\n\t\t\ttry {\n\t\t\t\tevents?.onClose?.(new CloseEvent(\"close\", {\n\t\t\t\t\tcode,\n\t\t\t\t\treason: reason.toString()\n\t\t\t\t}), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t\tws.on(\"error\", (error) => {\n\t\t\ttry {\n\t\t\t\tevents?.onError?.(new ErrorEvent(\"error\", { error }), ctx);\n\t\t\t} catch (e) {\n\t\t\t\t(options?.onError ?? console.error)(e);\n\t\t\t}\n\t\t});\n\t})();\n\treturn new Response();\n});\n\n//#endregion\n//#region src/server.ts\nconst createAdaptorServer = (options) => {\n\tconst fetchCallback = options.fetch;\n\tconst requestListener = getRequestListener(fetchCallback, {\n\t\thostname: options.hostname,\n\t\toverrideGlobalObjects: options.overrideGlobalObjects,\n\t\tautoCleanupIncoming: options.autoCleanupIncoming\n\t});\n\tconst server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);\n\tif (options.websocket && options.websocket.server) {\n\t\tif (options.websocket.server.options.noServer !== true) throw new Error(\"WebSocket server must be created with { noServer: true } option\");\n\t\tsetupWebSocket({\n\t\t\tserver,\n\t\t\tfetchCallback,\n\t\t\twss: options.websocket.server\n\t\t});\n\t}\n\treturn server;\n};\nconst serve = (options, listeningListener) => {\n\tconst server = createAdaptorServer(options);\n\tserver.listen(options?.port ?? 3e3, options.hostname, () => {\n\t\tconst serverInfo = server.address();\n\t\tlisteningListener && listeningListener(serverInfo);\n\t});\n\treturn server;\n};\n\n//#endregion\nexport { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };","import type { HttpBindings } from \"@hono/node-server\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { errorEnvelope } from \"@baerly/server/http\";\n\n/**\n * Body-cap enforcement for Node-hosted requests. Replaces the\n * pre-pivot `bodyCapMiddleware` that attached `incoming.on(\"data\",\n * ...)` — that listener raced with `@hono/node-server`'s own body\n * reader and dropped the first chunks of every POST. Wrapping\n * `req.body` with a counting `TransformStream` puts the cap in the\n * same reader chain as the kernel router's `readJsonBody`, which\n * reads `c.req.raw.body` itself, so there is no race.\n *\n * Two cap-trip paths, both drain the upstream `IncomingMessage`\n * (`resume()`) so the client's body write completes and the 413\n * envelope reaches it cleanly (without drain, closing the response\n * mid-upload surfaces client-side as \"socket hang up\"):\n *\n * - Content-Length fast path → returns a 413 `Response` directly.\n * - Chunked slow path → wraps `req.body` with a counting\n * `TransformStream` that errors with `BaerlyError{code:\n * \"PayloadTooLarge\"}` when the running count exceeds `max`.\n * The kernel router's `readJsonBody` recognises the\n * `BaerlyError` and re-throws it verbatim; `mapToResponse`\n * surfaces the same 413 envelope as the fast path.\n *\n * Returns the original `Request` unchanged for `GET`/`HEAD`/\n * `OPTIONS` (no body to cap) and for hosts that don't expose an\n * `IncomingMessage` on the Hono context's env binding — defence-in-\n * depth lives in the kernel router's `readJsonBody`.\n */\nexport function applyBodyCap(req: Request, env: unknown, max: number): Request | Response {\n if (req.method === \"GET\" || req.method === \"HEAD\" || req.method === \"OPTIONS\") {\n return req;\n }\n const incoming = (env as HttpBindings | undefined)?.incoming;\n if (incoming === undefined) {\n return req;\n }\n\n const lenHeader = req.headers.get(\"content-length\");\n if (lenHeader !== null) {\n const parsed = Number.parseInt(lenHeader, 10);\n if (Number.isFinite(parsed) && parsed > max) {\n incoming.resume();\n return cap413(max);\n }\n }\n\n const body = req.body;\n if (body === null) {\n return req;\n }\n\n let count = 0;\n let tripped = false;\n const counter = new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n if (tripped) {\n return;\n }\n count += chunk.byteLength;\n if (count > max) {\n tripped = true;\n incoming.resume();\n controller.error(new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${max} bytes`));\n return;\n }\n controller.enqueue(chunk);\n },\n });\n\n return new Request(req.url, {\n method: req.method,\n headers: req.headers,\n body: body.pipeThrough(counter),\n // `duplex` is required by Node/undici for streaming request bodies; the\n // standard DOM `RequestInit` doesn't surface it yet.\n duplex: \"half\",\n } as RequestInit & { duplex: \"half\" });\n}\n\nfunction cap413(max: number): Response {\n return new Response(\n JSON.stringify(errorEnvelope(\"PayloadTooLarge\", `Body exceeds ${max} bytes`)),\n {\n status: 413,\n headers: { \"content-type\": \"application/json\" },\n },\n );\n}\n","import { type DevLandingOptions, renderDevLanding } from \"@baerly/dev\";\nimport type { MiddlewareHandler } from \"hono\";\n\ninterface Options {\n readonly dev: DevLandingOptions;\n}\n\n/**\n * Opt-in dev landing-page short-circuit. Serves `GET /` with a\n * human-readable HTML page that links to the configured UI URL, and\n * `GET /favicon.ico` with 204 No Content. Bypasses verifier and\n * observability so it doesn't flood logs in dev.\n *\n * Other methods and other paths fall through to the cascade. Mounted\n * by {@link createApp} (in `app.ts`) ahead of `staticAssetsMiddleware`\n * so the dev short-circuit wins over any on-disk `index.html` /\n * `favicon.ico` that might live in `webRoot`.\n */\nexport function devLandingMiddleware(opts: Options): MiddlewareHandler {\n return async (c, next) => {\n if (c.req.method !== \"GET\") {\n return next();\n }\n const path = new URL(c.req.url).pathname;\n if (path === \"/\") {\n const body = renderDevLanding(opts.dev);\n return new Response(body, {\n status: 200,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n // Buffer.byteLength (not body.length) — the rendered HTML\n // may contain multi-byte UTF-8 characters.\n \"content-length\": String(Buffer.byteLength(body)),\n },\n });\n }\n if (path === \"/favicon.ico\") {\n return new Response(null, { status: 204 });\n }\n return next();\n };\n}\n","import { Readable } from \"node:stream\";\nimport { versions } from \"node:process\";\n\n//#region src/utils/stream.ts\nconst pr54206Applied = () => {\n\tconst [major, minor] = versions.node.split(\".\").map((component) => parseInt(component));\n\treturn major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;\n};\nconst useReadableToWeb = pr54206Applied();\nconst createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {\n\tif (useNativeReadableToWeb) return Readable.toWeb(stream);\n\tlet controller;\n\tlet settled = false;\n\tconst cleanup = () => {\n\t\tstream.off(\"data\", onData);\n\t\tstream.off(\"error\", onError);\n\t\tstream.off(\"end\", onTerminate);\n\t\tstream.off(\"close\", onTerminate);\n\t};\n\tconst settle = (callback) => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tcleanup();\n\t\tcallback?.();\n\t};\n\tconst onData = (chunk) => {\n\t\tif (settled || !controller) return;\n\t\tcontroller.enqueue(chunk);\n\t\tif ((controller.desiredSize ?? 0) <= 0) stream.pause();\n\t};\n\tconst onError = (error) => {\n\t\tsettle(() => {\n\t\t\tcontroller?.error(error);\n\t\t});\n\t};\n\tconst onTerminate = () => {\n\t\tsettle(() => {\n\t\t\tcontroller?.close();\n\t\t});\n\t};\n\treturn new ReadableStream({\n\t\tstart(streamController) {\n\t\t\tcontroller = streamController;\n\t\t\tstream.on(\"data\", onData);\n\t\t\tstream.on(\"error\", onError);\n\t\t\tstream.on(\"end\", onTerminate);\n\t\t\tstream.on(\"close\", onTerminate);\n\t\t\tstream.pause();\n\t\t},\n\t\tpull() {\n\t\t\tif (!settled) stream.resume();\n\t\t},\n\t\tcancel() {\n\t\t\tsettle();\n\t\t\tconst ignoreError = () => {};\n\t\t\tstream.on(\"error\", ignoreError);\n\t\t\tstream.once(\"close\", () => stream.off(\"error\", ignoreError));\n\t\t\tstream.destroy();\n\t\t}\n\t});\n};\n\n//#endregion\nexport { createStreamBody };","//#region src/utils/mime.ts\n/**\n* @module\n* MIME utility.\n*/\nconst getMimeType = (filename, mimes = baseMimes) => {\n\tconst match = filename.match(/\\.([a-zA-Z0-9]+?)$/);\n\tif (!match) return;\n\treturn mimes[match[1].toLowerCase()];\n};\nconst getExtension = (mimeType) => {\n\tconst baseType = mimeType.split(\";\", 1)[0].trim().toLowerCase();\n\tfor (const ext in baseMimes) {\n\t\tconst stored = baseMimes[ext];\n\t\tif (stored === mimeType || stored.split(\";\", 1)[0].trim() === baseType) return ext;\n\t}\n};\nconst baseMimes = {\n\taac: \"audio/aac\",\n\tavi: \"video/x-msvideo\",\n\tavif: \"image/avif\",\n\tav1: \"video/av1\",\n\tbin: \"application/octet-stream\",\n\tbmp: \"image/bmp\",\n\tcss: \"text/css; charset=utf-8\",\n\tcsv: \"text/csv; charset=utf-8\",\n\teot: \"application/vnd.ms-fontobject\",\n\tepub: \"application/epub+zip\",\n\tgif: \"image/gif\",\n\tgz: \"application/gzip\",\n\thtm: \"text/html; charset=utf-8\",\n\thtml: \"text/html; charset=utf-8\",\n\tico: \"image/x-icon\",\n\tics: \"text/calendar; charset=utf-8\",\n\tjpeg: \"image/jpeg\",\n\tjpg: \"image/jpeg\",\n\tjs: \"text/javascript; charset=utf-8\",\n\tjson: \"application/json\",\n\tjsonld: \"application/ld+json\",\n\tmap: \"application/json\",\n\tmid: \"audio/x-midi\",\n\tmidi: \"audio/x-midi\",\n\tmjs: \"text/javascript; charset=utf-8\",\n\tmp3: \"audio/mpeg\",\n\tmp4: \"video/mp4\",\n\tmpeg: \"video/mpeg\",\n\toga: \"audio/ogg\",\n\togv: \"video/ogg\",\n\togx: \"application/ogg\",\n\topus: \"audio/opus\",\n\totf: \"font/otf\",\n\tpdf: \"application/pdf\",\n\tpng: \"image/png\",\n\trtf: \"application/rtf\",\n\tsvg: \"image/svg+xml; charset=utf-8\",\n\ttif: \"image/tiff\",\n\ttiff: \"image/tiff\",\n\tts: \"video/mp2t\",\n\tttf: \"font/ttf\",\n\ttxt: \"text/plain; charset=utf-8\",\n\twasm: \"application/wasm\",\n\twebm: \"video/webm\",\n\tweba: \"audio/webm\",\n\twebmanifest: \"application/manifest+json\",\n\twebp: \"image/webp\",\n\twoff: \"font/woff\",\n\twoff2: \"font/woff2\",\n\txhtml: \"application/xhtml+xml; charset=utf-8\",\n\txml: \"application/xml; charset=utf-8\",\n\tzip: \"application/zip\",\n\t\"3gp\": \"video/3gpp\",\n\t\"3g2\": \"video/3gpp2\",\n\tgltf: \"model/gltf+json\",\n\tglb: \"model/gltf-binary\"\n};\n//#endregion\nexport { getExtension, getMimeType, baseMimes as mimes };\n","import { createStreamBody } from \"./utils/stream.mjs\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport { createReadStream, existsSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n//#region src/serve-static.ts\nconst 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;\nconst ENCODINGS = {\n\tbr: \".br\",\n\tzstd: \".zst\",\n\tgzip: \".gz\"\n};\nconst ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);\nconst getStats = (path) => {\n\tlet stats;\n\ttry {\n\t\tstats = statSync(path);\n\t} catch {}\n\treturn stats;\n};\nconst BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\\d*)-(\\d*)$/;\nconst parseByteRange = (range) => {\n\tconst match = range.match(BYTE_RANGE_PATTERN);\n\tif (!match) return;\n\tconst [, start, end] = match;\n\tif (start === \"\") return {\n\t\ttype: \"suffix\",\n\t\tlength: Number(end)\n\t};\n\tif (end === \"\") return {\n\t\ttype: \"open-ended\",\n\t\tstart: Number(start)\n\t};\n\treturn {\n\t\ttype: \"bounded\",\n\t\tstart: Number(start),\n\t\tend: Number(end)\n\t};\n};\nconst resolveByteRange = (spec, size) => {\n\tif (size === 0) return;\n\tif (spec.type === \"suffix\") {\n\t\tif (spec.length === 0) return;\n\t\treturn {\n\t\t\tstart: Math.max(size - spec.length, 0),\n\t\t\tend: size - 1\n\t\t};\n\t}\n\tconst end = spec.type === \"bounded\" ? Math.min(spec.end, size - 1) : size - 1;\n\tif (spec.start >= size || spec.start > end) return;\n\treturn {\n\t\tstart: spec.start,\n\t\tend\n\t};\n};\nconst tryDecode = (str, decoder) => {\n\ttry {\n\t\treturn decoder(str);\n\t} catch {\n\t\treturn str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n\t\t\ttry {\n\t\t\t\treturn decoder(match);\n\t\t\t} catch {\n\t\t\t\treturn match;\n\t\t\t}\n\t\t});\n\t}\n};\nconst tryDecodeURI = (str) => tryDecode(str, decodeURI);\nconst serveStatic = (options = { root: \"\" }) => {\n\tconst root = options.root || \"\";\n\tconst optionPath = options.path;\n\tif (root !== \"\" && !existsSync(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);\n\treturn async (c, next) => {\n\t\tif (c.finalized) return next();\n\t\tif (c.req.method !== \"GET\" && c.req.method !== \"HEAD\") return next();\n\t\tlet filename;\n\t\tif (optionPath) filename = optionPath;\n\t\telse try {\n\t\t\tfilename = tryDecodeURI(c.req.path);\n\t\t\tif (c.req.path.includes(\"%\") && (!options.allowPercentInPath || filename !== c.req.path.replace(/%25/g, \"%\"))) throw new Error();\n\t\t\tif (/(?:^|[\\/\\\\])\\.{1,2}(?:$|[\\/\\\\])|[\\/\\\\]{2,}|\\\\/.test(filename)) throw new Error();\n\t\t} catch {\n\t\t\tawait options.onNotFound?.(c.req.path, c);\n\t\t\treturn next();\n\t\t}\n\t\tlet path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);\n\t\tlet stats = getStats(path);\n\t\tif (stats && stats.isDirectory()) {\n\t\t\tconst indexFile = options.index ?? \"index.html\";\n\t\t\tpath = join(path, indexFile);\n\t\t\tstats = getStats(path);\n\t\t}\n\t\tif (!stats) {\n\t\t\tawait options.onNotFound?.(path, c);\n\t\t\treturn next();\n\t\t}\n\t\tconst mimeType = getMimeType(path);\n\t\tc.header(\"Content-Type\", mimeType || \"application/octet-stream\");\n\t\tif (options.precompressed && (!mimeType || mimeType === \"application/octet-stream\" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {\n\t\t\tconst acceptEncodingSet = new Set(c.req.header(\"Accept-Encoding\")?.split(\",\").map((encoding) => encoding.trim()));\n\t\t\tfor (const encoding of ENCODINGS_ORDERED_KEYS) {\n\t\t\t\tif (!acceptEncodingSet.has(encoding)) continue;\n\t\t\t\tconst precompressedStats = getStats(path + ENCODINGS[encoding]);\n\t\t\t\tif (precompressedStats) {\n\t\t\t\t\tc.header(\"Content-Encoding\", encoding);\n\t\t\t\t\tc.header(\"Vary\", \"Accept-Encoding\", { append: true });\n\t\t\t\t\tstats = precompressedStats;\n\t\t\t\t\tpath = path + ENCODINGS[encoding];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet result;\n\t\tconst size = stats.size;\n\t\tconst range = c.req.header(\"range\") || \"\";\n\t\tc.header(\"Last-Modified\", stats.mtime.toUTCString());\n\t\tif (c.req.method === \"HEAD\") {\n\t\t\tc.header(\"Content-Length\", size.toString());\n\t\t\tc.status(200);\n\t\t\tresult = c.body(null);\n\t\t} else if (!range) {\n\t\t\tc.header(\"Content-Length\", size.toString());\n\t\t\tresult = c.body(createStreamBody(createReadStream(path)), 200);\n\t\t} else {\n\t\t\tc.header(\"Accept-Ranges\", \"bytes\");\n\t\t\tconst resolvedRange = resolveByteRange(parseByteRange(range) ?? {\n\t\t\t\ttype: \"open-ended\",\n\t\t\t\tstart: 0\n\t\t\t}, size);\n\t\t\tif (!resolvedRange) {\n\t\t\t\tc.header(\"Content-Range\", `bytes */${size}`);\n\t\t\t\tresult = c.body(null, 416);\n\t\t\t} else {\n\t\t\t\tconst { start, end } = resolvedRange;\n\t\t\t\tconst chunkSize = end - start + 1;\n\t\t\t\tconst stream = createReadStream(path, {\n\t\t\t\t\tstart,\n\t\t\t\t\tend\n\t\t\t\t});\n\t\t\t\tc.header(\"Content-Length\", chunkSize.toString());\n\t\t\t\tc.header(\"Content-Range\", `bytes ${start}-${end}/${size}`);\n\t\t\t\tresult = c.body(createStreamBody(stream), 206);\n\t\t\t}\n\t\t}\n\t\tawait options.onFound?.(path, c);\n\t\treturn result;\n\t};\n};\n\n//#endregion\nexport { serveStatic };","import { realpathSync, statSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { serveStatic } from \"@hono/node-server/serve-static\";\nimport type { Context, MiddlewareHandler } from \"hono\";\n\ninterface Options {\n readonly webRoot: string;\n}\n\n/**\n * Serve files from `webRoot` for GET/HEAD requests that miss `/v1/*`,\n * via `@hono/node-server/serve-static`.\n *\n * That handler owns MIME types, `Content-Length`, `Last-Modified`,\n * Range requests, and request-path validation, falling through to the\n * cascade's 404 envelope on a rejected path. Hono hands it the path\n * already `decodeURI`'d, so `%20` and UTF-8 escapes name ordinary\n * files. What still holds a `%` after that decode is an encoded\n * reserved character (`%2F`, `%3F`, `%23`) or a literal `%` (`%25`),\n * and those are rejected, as are `.`/`..` segments and repeated or\n * back-slashes. This wrapper adds what it does not:\n *\n * - Dotfiles and dot-directories (`/.env`, `/.git/config`) fall\n * through, except `/.well-known/*`.\n * - A file whose real path (after symlinks) leaves `webRoot` falls\n * through.\n * - HTML navigation (`Accept: text/html`) that misses on disk gets\n * `<webRoot>/index.html` (SPA shell). Other misses fall through.\n * - `Cache-Control`: `public, max-age=3600` under `assets/` (Vite's\n * hashed bundles), `no-cache` everywhere else.\n */\nexport function staticAssetsMiddleware(opts: Options): MiddlewareHandler {\n const root = resolve(opts.webRoot);\n const onFound = (path: string, c: Context): void => {\n const rel = relative(root, resolve(path)).split(sep).join(\"/\");\n c.header(\"Cache-Control\", rel.startsWith(\"assets/\") ? \"public, max-age=3600\" : \"no-cache\");\n };\n const files = serveStatic({\n root,\n // `serveStatic` joins the validated request path onto `root`, so\n // rejecting here (with a path that cannot stat) is the one place\n // that sees the final filesystem target before it is opened.\n rewriteRequestPath: (path) => (servesFromRoot(root, path) ? path : UNSERVABLE),\n onFound,\n });\n const shell = serveStatic({ root, path: \"index.html\", onFound });\n\n return async (c, next) => {\n const method = c.req.method;\n if ((method !== \"GET\" && method !== \"HEAD\") || c.req.path.startsWith(\"/v1/\")) {\n return next();\n }\n if (hasDotSegment(c.req.path)) {\n return next();\n }\n // Hono's `Next` resolves to void, so a response produced inside it\n // has to land on `c.res` rather than be returned.\n return files(c, async () => {\n if (\n c.req.header(\"accept\")?.includes(\"text/html\") !== true ||\n !servesFromRoot(root, \"index.html\")\n ) {\n await next();\n return;\n }\n const res = await shell(c, next);\n if (res !== undefined) {\n c.res = res;\n }\n });\n };\n}\n\n/** A path `statSync` rejects (NUL byte), so `serveStatic` treats it as a miss. */\nconst UNSERVABLE = \"/\\0\";\n\n/** `.well-known` is the one dot-directory a web app is expected to publish (RFC 8615). */\nfunction hasDotSegment(path: string): boolean {\n return path.split(\"/\").some((segment) => segment.startsWith(\".\") && segment !== \".well-known\");\n}\n\n/**\n * True when `requestPath` (already validated by `serveStatic`) names a\n * missing file, or an existing file or directory whose real path stays\n * inside `root`. For a directory, its `index.html` is checked too,\n * since that is what `serveStatic` opens.\n */\nfunction servesFromRoot(root: string, requestPath: string): boolean {\n const target = join(root, requestPath);\n const realRoot = realpathOrNull(root);\n if (realRoot === null) {\n return true;\n }\n const candidates = [target];\n if (isDirectory(target)) {\n candidates.push(join(target, \"index.html\"));\n }\n return candidates.every((candidate) => {\n const real = realpathOrNull(candidate);\n if (real === null) {\n return true;\n }\n const rel = relative(realRoot, real);\n return rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n });\n}\n\nfunction realpathOrNull(path: string): string | null {\n try {\n return realpathSync(path);\n } catch {\n return null;\n }\n}\n\nfunction isDirectory(path: string): boolean {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n}\n","/**\n * Pretty console sink for the `baerlyDev()` Vite-mount boot path.\n *\n * Lives in `@baerly/adapter-node` so the `@baerly/server` kernel\n * doesn't pull the canonical-line column renderer\n * into its bundle. The kernel's `configureObservability` accepts any\n * `Sink` function directly; callers in TTY-friendly environments\n * (the Node adapter's `baerlyNode`) constructs this sink\n * and passes it in.\n */\n\nimport { type LogRecord, type Sink } from \"@logtape/logtape\";\nimport { styleText } from \"node:util\";\n\n/**\n * Metric keys the pretty sink reads off the canonical-line record.\n * These names match `RequestScopedMetricsRecorder.summarize()` output\n * in `packages/server/src/observability/recorder.ts`. If the recorder\n * renames a key, update both sides here.\n */\nconst CANONICAL_KEYS = {\n classA: \"db.storage.class_a_ops_total\",\n classB: \"db.storage.class_b_ops_total\",\n wamp: \"db.write.class_a_ops_per_logical_write_sum\",\n put412: \"db.r2.put.412_total\",\n put429: \"db.r2.put.429_total\",\n} as const;\n\n/**\n * Fixed-width column sizes for the pretty sink's HTTP line.\n * Local to the renderer — these are presentation defaults, not\n * protocol invariants, so they don't belong in `@baerly/protocol`.\n */\nconst METHOD_W = 6;\nconst PATH_W = 28;\n\nconst pickProp = (props: Record<string, unknown>, key: string): unknown =>\n Object.prototype.hasOwnProperty.call(props, key) ? props[key] : undefined;\n\nconst numProp = (props: Record<string, unknown>, key: string): number | undefined => {\n const v = pickProp(props, key);\n return typeof v === \"number\" ? v : undefined;\n};\n\ntype Colors = Readonly<Record<\"red\" | \"yellow\" | \"cyan\" | \"dim\", (s: string) => string>>;\n\n// `enabled` is the caller's own plain/TTY decision, so styling is forced\n// rather than re-detected from stdout.\nconst createColors = (enabled: boolean): Colors => {\n const paint =\n (format: \"red\" | \"yellow\" | \"cyan\" | \"dim\") =>\n (s: string): string =>\n enabled ? styleText(format, s, { validateStream: false }) : s;\n return { red: paint(\"red\"), yellow: paint(\"yellow\"), cyan: paint(\"cyan\"), dim: paint(\"dim\") };\n};\n\n// Color the status column by class: 5xx red, 4xx yellow, 3xx cyan,\n// 2xx/unset dim. Extracted so the canonical-line renderer doesn't carry\n// a 5-level nested ternary.\nconst colorStatus = (\n statusStr: string,\n status: number | undefined,\n plain: boolean,\n pc: Colors,\n): string => {\n if (plain || status === undefined) {\n return statusStr;\n }\n if (status >= 500) {\n return pc.red(statusStr);\n }\n if (status >= 400) {\n return pc.yellow(statusStr);\n }\n if (status >= 300) {\n return pc.cyan(statusStr);\n }\n return pc.dim(statusStr);\n};\n\nconst renderCanonical = (record: LogRecord, pc: Colors, plain: boolean): string => {\n const props = record.properties as Record<string, unknown>;\n const ts = new Date(record.timestamp).toISOString().slice(11, 19);\n const reqId = String(pickProp(props, \"request_id\") ?? \"\").slice(0, 8);\n const duration = numProp(props, \"duration_ms\") ?? 0;\n const durationStr = `${Math.round(duration)}ms`.padStart(5);\n\n const status = numProp(props, \"status\");\n const method =\n typeof pickProp(props, \"method\") === \"string\" ? String(pickProp(props, \"method\")) : \"\";\n const path = typeof pickProp(props, \"path\") === \"string\" ? String(pickProp(props, \"path\")) : \"\";\n\n const m = method.padEnd(METHOD_W);\n const p = path.length > PATH_W ? `${path.slice(0, PATH_W - 1)}…` : path.padEnd(PATH_W);\n const statusStr = status === undefined ? \" \" : String(status);\n const coloredStatus = colorStatus(statusStr, status, plain, pc);\n const prefix = `${m}${p} ${coloredStatus} ${durationStr}`;\n\n const tail: string[] = [];\n if (reqId) {\n tail.push(`req=${reqId}`);\n }\n const classA = numProp(props, CANONICAL_KEYS.classA);\n const classB = numProp(props, CANONICAL_KEYS.classB);\n if (classA !== undefined) {\n tail.push(`class_a=${classA}`);\n }\n if (classB !== undefined) {\n tail.push(`class_b=${classB}`);\n }\n const wamp = numProp(props, CANONICAL_KEYS.wamp);\n if (wamp !== undefined) {\n tail.push(`wamp=${wamp}`);\n }\n const c412 = numProp(props, CANONICAL_KEYS.put412);\n if (c412 !== undefined && c412 > 0) {\n tail.push(`412=${c412}`);\n }\n const c429 = numProp(props, CANONICAL_KEYS.put429);\n if (c429 !== undefined && c429 > 0) {\n tail.push(`429=${c429}`);\n }\n if (status !== undefined && status >= 400) {\n const outcome = pickProp(props, \"outcome\");\n if (typeof outcome === \"string\") {\n tail.push(`outcome=${outcome}`);\n }\n }\n\n const tailStr = tail.length ? ` ${tail.join(\" \")}` : \"\";\n const tsCol = plain ? `${ts} ` : `${pc.dim(ts)} `;\n return `${tsCol}${prefix}${tailStr}`;\n};\n\nconst isCanonicalRecord = (record: LogRecord): boolean =>\n record.message.length === 1 && record.message[0] === \"canonical\";\n\nconst isPlainEnv = (): boolean => {\n const proc = (\n globalThis as {\n process?: {\n stdout?: { isTTY?: boolean };\n env?: Record<string, string | undefined>;\n };\n }\n ).process;\n return proc?.stdout?.isTTY !== true || proc?.env?.[\"CI\"] !== undefined;\n};\n\n/**\n * Built-in pretty sink. Renders canonical-line records (the\n * single-emit/unit-of-work records produced by `flushCanonicalLine`\n * in `@baerly/server/observability`) in a column-aligned cost-aware\n * format intended for local dev; falls back to a generic\n * `<ts> <LEVEL> <category> <msg> <jsonProps>` layout for every\n * other record (warn-line `verifier_rejected`, debug storage\n * emits, etc.).\n *\n * Color is enabled when stderr is a TTY and `CI` is unset. Under\n * vitest, stderr is non-TTY so color is off — tests can assert\n * substring matches without stripping ANSI escapes.\n */\nexport const prettyConsoleSink = (): Sink => {\n const plain = isPlainEnv();\n const pc = createColors(!plain);\n return (record) => {\n if (isCanonicalRecord(record)) {\n console.log(renderCanonical(record, pc, plain));\n return;\n }\n const ts = new Date(record.timestamp).toISOString();\n const cat = record.category.join(\".\");\n const msg = record.message.map((m) => (typeof m === \"string\" ? m : JSON.stringify(m))).join(\"\");\n const props = Object.keys(record.properties).length\n ? ` ${JSON.stringify(record.properties)}`\n : \"\";\n console.log(`${ts} ${record.level.toUpperCase()} ${cat} ${msg}${props}`);\n };\n};\n","import {\n type BaerlyConfig,\n MAINTENANCE_PROFILE_NODE,\n RequestLedger,\n type Storage,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { Db } from \"@baerly/server\";\nimport { createRouter, mapError } from \"@baerly/server/http\";\nimport { handleSpecRequest } from \"@baerly/server/spec\";\nimport {\n type MaintenanceDispatch,\n parseMaintenanceEnv,\n} from \"@baerly/server/_internal/maintenance\";\nimport { prettyConsoleSink } from \"./logger-pretty.ts\";\nimport {\n type ObservabilityConfig,\n configureObservability,\n deriveOutcome,\n flushCanonicalLine,\n observableStorage,\n runWithContext,\n} from \"@baerly/server/observability\";\nimport {\n createObservabilityContext,\n flushUnauthorizedAndRespond,\n logMaintenanceWarning,\n requestIdFrom,\n} from \"@baerly/server/_internal/observability\";\n\n/**\n * Options for {@link createFetchHandler}.\n *\n * Host-agnostic Fetch-shaped cascade entry point. The Node-host-specific\n * options (`webRoot`, `dev`) live on {@link CreateAppOptions} so they\n * only reach the middleware stack that consumes them.\n *\n * @internal — public consumers see {@link CreateAppOptions} from\n * `./app.ts` instead. Exported for intra-package re-use.\n */\nexport interface CreateFetchHandlerOptions {\n readonly app: string;\n readonly storage: Storage;\n readonly verifier: Verifier;\n /**\n * Your `baerly.config.ts`. When set, the adapter forwards it to\n * {@link Db.create} on every request — so server-side schema\n * validation fires on commits and declared indexes are validated.\n * Without this option, declared collections have no\n * effect on the `/v1/c/*` surface.\n *\n * Only `collections` is read — deploy-time fields (`target`,\n * `domain`, `requiredSecrets`, …) are ignored here.\n */\n readonly config?: BaerlyConfig;\n /**\n * LogTape config (level/sink) with `LOG_LEVEL` envvar fallback.\n * When the field is unset (or `{}`), baerly auto-configures LogTape:\n * the default sink is the local `prettyConsoleSink()` when\n * `process.stdout.isTTY === true` (developer terminals),\n * `\"console-json\"` otherwise (production hosts where stdout is piped\n * to a log aggregator). The typed `sink` field always wins.\n *\n * Pass `false` to skip `configureObservability` entirely — the\n * escape hatch for apps that embed baerly and own the process-wide\n * LogTape configuration themselves. (baerly also never clobbers a\n * host config it detects at boot; `false` additionally suppresses the\n * boot-time configure attempt and its meta-logger notice.)\n */\n readonly observability?: ObservabilityConfig | false;\n /** Override the long-poll budget. Forwarded to `createRouter`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `createRouter`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Assemble the per-request {@link MaintenanceDispatch} for a Node host.\n *\n * baerly maintains IN-BAND: the writer reads\n * `getCurrentContext()?.maintenance` at its post-commit dispatch point and\n * runs one bounded compact + GC slice on the (rare) write that crosses a\n * maintenance trigger. Reads stay pure — they never tick. There is no\n * `setInterval`, no cron, no operator-installed scheduler: the kernel\n * maintains itself on a bare bucket with zero operator infrastructure.\n *\n * On Node v1 maintenance runs INLINE on the commit path (no\n * `dispatch` override — serverful Node has no `waitUntil`, and inline is\n * deterministic + correct here), so this returns no `dispatch` field;\n * the writer falls back to its inline-awaited default dispatch.\n *\n * The caps (`options`) are a MODERATE multiple of the CF-free defaults —\n * Node has no Cloudflare subrequest wall, but because v1 runs inline the\n * per-pass work is still BOUNDED by worst-case single-write added\n * latency, not unbounded. We thread `phasesPerTick: \"both\"` (a capable\n * host can fold AND GC in one tick) plus the Node-tier `WRITE_TICK_*`\n * overrides from `@baerly/protocol`'s `NODE_MAINTENANCE_*` constants\n * (10× CF-free, with a shorter GC interval so the sweep budget keeps up).\n *\n * The two ops-plane env vars are read here (per call) so a `vi.stubEnv`\n * in tests — and a real process env in production — is observed:\n *\n * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (the snapshot\n * ceiling `C`). A plain positive decimal integer; unset or `\"\"` falls\n * back to the profile default; any other value throws\n * `BaerlyError{code:\"InvalidConfig\"}`.\n * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Closed,\n * case-insensitive vocabulary: unset/`\"\"`/`\"0\"`/`\"false\"` → `false`;\n * `\"1\"`/`\"true\"` → `true`; anything else throws\n * `BaerlyError{code:\"InvalidConfig\"}`.\n *\n * `readEnv` defaults to `process.env`; the parameter exists for direct\n * unit coverage.\n */\nexport const nodeMaintenanceDispatch = (\n readEnv: (key: string) => string | undefined = (k) => process.env[k],\n): MaintenanceDispatch => {\n const { maxFoldBytes, disabled } = parseMaintenanceEnv(readEnv);\n\n return {\n // No `dispatch` override: inline on serverful Node (the writer\n // falls back to `dispatchInlineAwaited`).\n ...(disabled && { disabled: true }),\n ...(maxFoldBytes !== undefined && { maxFoldBytes }),\n // Structured `fold_deferred` (and future maintenance) warnings.\n warn: logMaintenanceWarning,\n options: {\n phasesPerTick: \"both\",\n profile: MAINTENANCE_PROFILE_NODE,\n },\n };\n};\n\nconst mappedErrorResponse = (error: unknown): { status: number; response: Response } => {\n const { status, envelope } = mapError(error);\n return {\n status,\n response: new Response(JSON.stringify(envelope), {\n status,\n headers: { \"content-type\": \"application/json\" },\n }),\n };\n};\n\n/**\n * Build a `(req: Request) => Promise<Response>` handler that runs the\n * baerly `/v1/*` cascade: healthz short-circuit → observability context\n * → verifier → `Db.create` → `createRouter({db}).fetch(req)` →\n * canonical-line flush. The handler is host-agnostic; mount it under\n * `/v1/*` in your Fetch framework.\n *\n * Non-`/v1/*` paths fall through to the Hono router, which renders the\n * kernel's 404 envelope. To compose static-asset or dev-landing\n * handlers, dispatch those upstream of this factory — see the\n * internal Hono-app factory in `./app.ts` for the production composition.\n *\n * @internal — public consumers reach this via `baerlyNode` from\n * `./baerly-node.ts`. Exported for intra-package re-use and direct unit\n * coverage in `server.test.ts`.\n */\nexport function createFetchHandler(\n opts: CreateFetchHandlerOptions,\n): (req: Request) => Promise<Response> {\n // Factory-time, idempotent. `observability: false` opts out entirely\n // (embedder owns LogTape config); otherwise auto-configure — this is a\n // no-op when a host config is already present (see configureObservability).\n if (opts.observability !== false) {\n void configureObservability(resolveDefaultSink(opts.observability ?? {}));\n }\n const wrappedStorage = observableStorage(opts.storage);\n\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const path = url.pathname;\n\n // /v1/healthz is anonymous; the deploy-probe contract bypasses\n // verifier AND observability so probes don't flood logs. Matches\n // adapter-cloudflare/src/worker.ts.\n if (request.method === \"GET\" && path === \"/v1/healthz\") {\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // /v1/spec is anonymous (like healthz): the static contract IR is\n // non-sensitive (same info as the public .d.ts). Per-tenant\n // collection names are appended ONLY when the verifier accepts —\n // we run it here tolerantly (null → anonymous, no 401), so an\n // unauthenticated probe still gets the static contract. Verifier\n // throws also degrade to anonymous: the static contract is public\n // and should stay available when the auth backend is unhealthy.\n if (request.method === \"GET\" && path === \"/v1/spec\") {\n return handleSpecRequest(request, async () => ({\n verifier: opts.verifier,\n config: opts.config,\n }));\n }\n\n const requestId = requestIdFrom(request.headers);\n // In-band maintenance: the writer reads `getCurrentContext()?.maintenance`\n // at its post-commit dispatch point. Read per request so the ops-plane env\n // vars (and any `vi.stubEnv` in tests) are observed at call time.\n let maintenance: MaintenanceDispatch;\n try {\n maintenance = nodeMaintenanceDispatch();\n } catch (error) {\n // Parsing runs before the normal verifier/router boundary because the\n // result belongs on the context itself. Re-open that same observability\n // boundary for config failures so they use the canonical HTTP envelope\n // and emit the request's canonical error line.\n const obsCtx = createObservabilityContext({ request_id: requestId });\n return await runWithContext(obsCtx, async () => {\n const { status, response } = mappedErrorResponse(error);\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status,\n outcome: deriveOutcome(request.method, status, error),\n error,\n extra: { method: request.method, path },\n });\n return response;\n });\n }\n const obsCtx = createObservabilityContext({\n request_id: requestId,\n maintenance,\n // Node has no per-request storage call cap: the ledger counts every\n // attempt and never refuses one.\n ledger: new RequestLedger(),\n });\n\n // The verifier runs inside the request context so work it does (e.g. a\n // JWKS fetch) sees `getCurrentContext()`.\n return await runWithContext(obsCtx, async () => {\n let result: Awaited<ReturnType<Verifier>>;\n try {\n result = await opts.verifier(request);\n } catch (error) {\n // A throwing verifier is an enveloped, mapped error with its own\n // canonical line — never a 401 (that would tell OAuth clients to\n // discard credentials during an IdP outage).\n const { status, response } = mappedErrorResponse(error);\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status,\n outcome: deriveOutcome(request.method, status, error),\n error,\n extra: { method: request.method, path },\n });\n return response;\n }\n if (result === null) {\n return flushUnauthorizedAndRespond(obsCtx, request);\n }\n\n let outboundStatus = 500;\n let caughtError: unknown;\n let response: Response;\n try {\n const db = Db.create({\n storage: wrappedStorage,\n app: opts.app,\n tenant: result.tenantPrefix,\n config: opts.config,\n });\n const router = createRouter({\n db,\n ...(opts.sinceTimeoutMs !== undefined && { sinceTimeoutMs: opts.sinceTimeoutMs }),\n ...(opts.sincePollIntervalMs !== undefined && {\n sincePollIntervalMs: opts.sincePollIntervalMs,\n }),\n });\n response = await router.fetch(request);\n outboundStatus = response.status;\n } catch (error) {\n caughtError = error;\n const { status, response: mappedResponse } = mappedErrorResponse(error);\n outboundStatus = status;\n response = mappedResponse;\n } finally {\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status: outboundStatus,\n outcome: deriveOutcome(request.method, outboundStatus, caughtError),\n ...(caughtError !== undefined && { error: caughtError }),\n extra: { method: request.method, path },\n });\n }\n return response;\n });\n };\n}\n\n/**\n * Auto-pick the default sink when the caller passed an\n * {@link ObservabilityConfig} without a `sink` field. On a TTY\n * (developer terminals) we prefer pretty output; otherwise JSON\n * (production hosts pipe stdout to a log aggregator).\n *\n * Returns a new config with `sink` defaulted; if the caller already\n * supplied a `sink` (function or shorthand string) we pass the\n * config through verbatim. Either way the caller's `level` (when\n * set) reaches LogTape unchanged.\n *\n * Exported for the test suite — the TTY check is otherwise a pure\n * read of `process.stdout.isTTY` and a default lookup, neither\n * worth a black-box round-trip.\n */\nexport const resolveDefaultSink = (config: ObservabilityConfig): ObservabilityConfig => {\n if (config.sink !== undefined) {\n return config;\n }\n // `process.stdout.isTTY` is `true` only on real terminals. CI\n // pipelines, docker logs, systemd, and pm2 cluster mode all\n // pipe stdout — `isTTY` is `undefined` (falsy) there. The kernel\n // only ships `\"console-json\"`; we construct the pretty sink\n // locally and pass it as a function so the pretty renderer stays off the\n // kernel closure.\n const isTty = Boolean(process.stdout.isTTY);\n return { ...config, sink: isTty ? prettyConsoleSink() : \"console-json\" };\n};\n","import { type DevLandingOptions } from \"@baerly/dev\";\nimport { MAX_BODY_BYTES } from \"@baerly/server/http\";\nimport { withNosniff } from \"@baerly/server/_internal/kernel\";\nimport { Hono } from \"hono/tiny\";\nimport { applyBodyCap } from \"./middleware/body-cap.ts\";\nimport { devLandingMiddleware } from \"./middleware/dev-landing.ts\";\nimport { staticAssetsMiddleware } from \"./middleware/static-assets.ts\";\nimport { type CreateFetchHandlerOptions, createFetchHandler } from \"./server.ts\";\n\n/**\n * Options for {@link createApp}.\n *\n * Extends {@link CreateFetchHandlerOptions} with the Node-host\n * affordances mounted ahead of the cascade.\n */\nexport interface CreateAppOptions extends CreateFetchHandlerOptions {\n /**\n * Optional static-asset root. When set, the app serves files from\n * this directory for any GET/HEAD request that misses `/v1/*`. See\n * {@link staticAssetsMiddleware} for details (MIME mapping, SPA\n * fallback, traversal rejection).\n */\n readonly webRoot?: string;\n /**\n * Opt-in dev affordance. When set, `GET /` returns a human-readable\n * HTML landing page linking to the configured UI URL, and\n * `GET /favicon.ico` returns 204 No Content. Bypasses verifier and\n * observability so it doesn't flood logs. Leave unset in production.\n */\n readonly dev?: DevLandingOptions;\n}\n\n/**\n * Build a Hono app that serves the baerly cascade plus Node-host\n * middleware (dev-landing when `dev` is set, then static-assets when\n * `webRoot` is set, then the cascade).\n *\n * The returned app's `.fetch` is `(req: Request) => Promise<Response>`\n * — feed it to `@hono/node-server`'s `serve({ fetch })`, mount under\n * another Hono app via `app.route(prefix, baerlyApp)`, or convert\n * to a Node listener via `getRequestListener(baerlyApp.fetch)`.\n *\n * Body size enforcement: every non-`GET`/`HEAD`/`OPTIONS` request\n * passes through {@link applyBodyCap} before reaching the cascade.\n * The helper short-circuits with a 413 envelope when `Content-\n * Length` advertises an over-cap body, and otherwise wraps\n * `req.body` with a counting `TransformStream` that errors with\n * `BaerlyError{code:\"PayloadTooLarge\"}` once the running byte\n * count exceeds {@link MAX_BODY_BYTES}. On cap-trip in either\n * path the upstream `IncomingMessage` is drained (`resume()`) so\n * the client's body write completes and the 413 reaches it\n * cleanly. The kernel router's defence-in-depth\n * (`packages/server/src/http/router.ts:464-501`) remains the\n * backstop for hosts without an `incoming` binding.\n */\nexport function createApp(opts: CreateAppOptions): Hono {\n const fetchHandler = createFetchHandler(opts);\n const app = new Hono();\n\n // First, so every response below it (dev landing, static assets, the\n // body-cap 413, the cascade) carries `X-Content-Type-Options: nosniff`.\n app.use(\"*\", async (c, next) => {\n await next();\n const res = withNosniff(c.res);\n if (res !== c.res) {\n c.res = res;\n }\n });\n\n // Order: dev-landing → static-assets → cascade. The dev\n // short-circuit must precede static-assets so a `webRoot` that\n // happens to contain `index.html` / `favicon.ico` doesn't shadow\n // the dev affordance.\n if (opts.dev !== undefined) {\n app.use(\"*\", devLandingMiddleware({ dev: opts.dev }));\n }\n if (opts.webRoot !== undefined) {\n app.use(\"*\", staticAssetsMiddleware({ webRoot: opts.webRoot }));\n }\n\n app.all(\"*\", async (c) => {\n const capped = applyBodyCap(c.req.raw, c.env, MAX_BODY_BYTES);\n if (capped instanceof Response) {\n return capped;\n }\n return fetchHandler(capped);\n });\n\n return app;\n}\n","import { createServer, type Server } from \"node:http\";\nimport { createAdaptorServer } from \"@hono/node-server\";\nimport type { DevLandingOptions } from \"@baerly/dev\";\nimport {\n BaerlyError,\n type BaerlyAppConfig,\n isDeployedEnv,\n type Storage,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { resolveVerifier } from \"@baerly/server/_internal/kernel\";\nimport type { ObservabilityConfig } from \"@baerly/server/observability\";\nimport { createApp } from \"./app.ts\";\n\n/**\n * Options for {@link baerlyNode}. Composes the {@link createApp}\n * surface (same `app` / `storage` / `verifier` / `webRoot` / etc.)\n * with a `node:http` server lifecycle (`listen` / `close` +\n * SIGTERM/SIGINT handling).\n *\n * Mirrors `baerlyWorker` in `@baerly/adapter-cloudflare`.\n */\nexport interface BaerlyNodeOptions {\n /**\n * Your `baerly.config.ts`. **Required.** Carries `auth`, `tenant`,\n * `app`, and the declared `collections` (their schemas/indexes flow\n * through to per-request `Db.create` automatically).\n *\n * The adapter resolves the per-request `Verifier` from\n * `config.auth` when no `verifier:` override is supplied — see\n * resolution order on {@link verifier} below. Only\n * `app` / `tenant` / `auth` / `collections` are read for runtime\n * kernel wiring; deploy-time fields (`target`, `domain`,\n * `requiredSecrets`) are ignored here.\n */\n readonly config: BaerlyAppConfig;\n readonly storage: Storage;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides\n * `config.auth` (the \"dev default in config, prod override via env\"\n * recipe). When unset, the adapter synthesizes one from\n * `config.auth`:\n *\n * - `\"shared-secret\"` → `sharedSecret({ secret:\n * process.env.SHARED_SECRET, tenantPrefix: config.tenant })`.\n * Throws `BaerlyError(\"InvalidConfig\", ...)` at factory time\n * when `SHARED_SECRET` is missing/empty (Node can throw at\n * startup unlike CF Workers).\n * - `\"none\"` → pins every request to `config.tenant` with no\n * header check.\n *\n * `GET /v1/healthz` always bypasses the verifier.\n */\n readonly verifier?: Verifier;\n readonly observability?: ObservabilityConfig | false;\n readonly dev?: DevLandingOptions;\n readonly webRoot?: string;\n readonly sinceTimeoutMs?: number;\n readonly sincePollIntervalMs?: number;\n}\n\n/** Options for {@link BaerlyNodeHandle.listen}. */\nexport interface BaerlyNodeListenOptions {\n /**\n * Address to bind, passed to Node's `server.listen(port, host)`.\n * Omit to bind every interface.\n */\n readonly hostname?: string;\n}\n\n/**\n * Handle returned by {@link baerlyNode}. Composes a running\n * `node:http` server lifecycle.\n *\n * - `fetch(request)` is the web-standard request handler. Use\n * directly for in-process embedding (Vite middleware via\n * `@hono/node-server.getRequestListener`, custom servers, tests).\n * Calling `fetch` does not start the `node:http` server; the\n * server lifecycle is owned by `listen()` / `close()`.\n * Hono's optional `env`/`executionCtx` parameters are intentionally\n * omitted from the signature — this is a Node-host handle, and\n * those parameters are Workers-only.\n * - `listen(port, { hostname })` binds the server, installs\n * SIGTERM/SIGINT handlers that call `close()` and exit `0`, and\n * resolves once the server is actually listening (after Node's\n * `'listening'` event fires). Throws on `'error'` from the server.\n * Without `hostname` it binds every interface (Node's default:\n * `::` dual-stack, or `0.0.0.0` without IPv6), which is what a\n * container wants; pass `\"127.0.0.1\"` to accept loopback only.\n * - `close()` closes the server and removes the signal handlers.\n * Resolves once `Server.close` callback fires. Safe to call\n * multiple times; every call returns the same promise. A closed\n * handle is final: `listen()` after `close()` rejects with\n * `BaerlyError(\"InvalidConfig\")`; create a new handle instead.\n */\nexport interface BaerlyNodeHandle {\n readonly fetch: (request: Request) => Response | Promise<Response>;\n /**\n * Bind the server on `port`, every interface unless `hostname` is set.\n * Rejects with `BaerlyError(\"InvalidConfig\")` once `close()` has been\n * called.\n *\n * @example\n * ```ts\n * // Loopback only, e.g. behind a reverse proxy on the same host.\n * await handle.listen(8080, { hostname: \"127.0.0.1\" });\n * ```\n */\n listen(port: number, options?: BaerlyNodeListenOptions): Promise<void>;\n /**\n * Close the server and remove the signal handlers.\n *\n * If a `listen()` bind is still pending, `close()` waits for it to\n * settle and then closes the resulting listener. That pending\n * `listen()` resolves without installing signal handlers, or rejects\n * with the bind error.\n */\n close(): Promise<void>;\n}\n\n/**\n * Mount baerly on `node:http` with one call. Mirrors `baerlyWorker`\n * from `@baerly/adapter-cloudflare`.\n *\n * Composes:\n * - {@link createApp} → exposed as `handle.fetch` for in-process\n * embedding; wrapped in `@hono/node-server.createAdaptorServer({ fetch, createServer })`\n * lazily when `listen()` is called.\n * - SIGTERM + SIGINT handlers installed on `listen()` that call\n * `close()` and `process.exit(0)`. On any error during close,\n * `process.exit(1)`.\n *\n * **Maintenance is in-band, not scheduled.** There is no `setInterval`,\n * no cron, and no `maintenance:` option: the kernel maintains itself on\n * a bare bucket with zero operator infrastructure. Compaction + GC run\n * INLINE on the (rare) write that crosses a maintenance trigger —\n * `createFetchHandler` threads a Node-tier `MaintenanceDispatch`\n * onto the per-request observability context, which the writer reads at\n * its post-commit dispatch point. Reads never tick. Tune via the\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` / `BAERLY_MAINTENANCE_DISABLE`\n * env vars. `BAERLY_MAINTENANCE_DISABLE` accepts unset / `\"\"` / `\"0\"` /\n * `\"false\"` (enabled) or `\"1\"` / `\"true\"` (disabled), case-insensitively;\n * anything else throws `BaerlyError{code:\"InvalidConfig\"}`.\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` uses a plain positive decimal\n * integer as the override; unset or empty values use the Node profile\n * default, and any other value throws `InvalidConfig`. These\n * values are re-read for API/database requests that reach maintenance\n * dispatch; health/spec and configured dev/static short-circuits bypass\n * them. For an explicit out-of-band sweep, call\n * `runScheduledMaintenance` from `@gusto/baerly-storage/maintenance`.\n *\n * @example\n * ```ts\n * import { baerlyNode, s3Storage } from \"@gusto/baerly-storage/node\";\n * import config from \"./baerly.config.ts\";\n *\n * const handle = baerlyNode({\n * config,\n * storage: s3Storage({\n * region: \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * }),\n * // No verifier needed when config.auth is \"none\" or \"shared-secret\".\n * webRoot: \"./dist/client\",\n * });\n * await handle.listen(Number(process.env[\"PORT\"] ?? 8080));\n * ```\n */\n/**\n * Host used to build the request URL when a request carries no Host\n * header (HTTP/1.0): the bound address, with an IPv6 literal bracketed\n * so the URL parses, or `0.0.0.0` for an all-interfaces bind.\n */\nfunction fallbackHost(hostname: string | undefined): string {\n if (hostname === undefined) {\n return \"0.0.0.0\";\n }\n return hostname.includes(\":\") ? `[${hostname}]` : hostname;\n}\n\nexport function baerlyNode(opts: BaerlyNodeOptions): BaerlyNodeHandle {\n // Node can `await` / throw at top level (unlike CF Workers), so\n // verifier resolution lives here at factory time. An unset\n // `SHARED_SECRET` for `auth: \"shared-secret\"` fails the process\n // startup with a locked `InvalidConfig` message rather than\n // surprising the first inbound request.\n const verifier = resolveVerifier({\n factoryVerifier: opts.verifier,\n config: opts.config,\n readEnv: (k) => process.env[k],\n });\n // auth=none startup banner: one line when the operator opted into\n // no-auth via config (not when they passed a real verifier override).\n // Suppressed for shared-secret — operator already knows. Raised to\n // warn when the process looks deployed; never refused, because\n // auth=none is the zero-config default.\n if (opts.verifier === undefined && opts.config.auth === \"none\") {\n const tenant = JSON.stringify(opts.config.tenant);\n if (isDeployedEnv(process.env)) {\n console.warn(\n `[baerly] auth=none in a deployed environment — every request, from any caller, gets full access to tenant=${tenant}`,\n );\n } else {\n console.log(`[baerly] auth=none — all requests resolve to tenant=${tenant}`);\n }\n }\n const app = createApp({\n app: opts.config.app,\n storage: opts.storage,\n verifier,\n config: opts.config,\n ...(opts.observability !== undefined && { observability: opts.observability }),\n ...(opts.dev !== undefined && { dev: opts.dev }),\n ...(opts.webRoot !== undefined && { webRoot: opts.webRoot }),\n ...(opts.sinceTimeoutMs !== undefined && { sinceTimeoutMs: opts.sinceTimeoutMs }),\n ...(opts.sincePollIntervalMs !== undefined && {\n sincePollIntervalMs: opts.sincePollIntervalMs,\n }),\n });\n // Server construction is deferred to `listen()` so calling `baerlyNode(opts)`\n // without `.listen()` does NOT create an `http.Server` or install\n // signal handlers. The `fetch` handler is exposed on the returned\n // handle for in-process embedding (Vite middleware, tests). `server`\n // stays `undefined` until `listen()` runs; `close()` guards against\n // the \"constructed but never listened\" branch.\n let server: Server | undefined;\n\n // The in-flight `server.listen()`. A hostname bind is asynchronous\n // (address lookup first), and Node cannot cancel it, so `close()`\n // waits for it to settle before closing what it bound.\n let bind: Promise<void> | undefined;\n\n let signalHandler: ((sig: NodeJS.Signals) => void) | undefined;\n let closing: Promise<void> | undefined;\n\n const shutdown = async (): Promise<void> => {\n if (signalHandler !== undefined) {\n process.off(\"SIGTERM\", signalHandler);\n process.off(\"SIGINT\", signalHandler);\n signalHandler = undefined;\n }\n // A failed bind leaves nothing to close; `listen()` reports its error.\n await bind?.catch(() => undefined);\n await new Promise<void>((resolve, reject) => {\n // Factory was called but `listen()` never ran — there's no\n // `http.Server` to close. Resolve immediately.\n if (server === undefined) {\n resolve();\n return;\n }\n // Node throws ERR_SERVER_NOT_RUNNING on close() of a non-listening server.\n if (!server.listening) {\n resolve();\n return;\n }\n server.close((err) => {\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n });\n });\n };\n\n const close = (): Promise<void> => {\n closing ??= shutdown();\n return closing;\n };\n\n const listen = async (port: number, options?: BaerlyNodeListenOptions): Promise<void> => {\n // A closed handle can never be closed again (`close()` returns the\n // settled promise), so a bind here would leak the port.\n if (closing !== undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerlyNode: listen() called after close(); create a new handle\",\n );\n }\n // `createAdaptorServer()` builds an `http.Server` via the supplied\n // `createServer` factory and wires the Hono `fetch` handler into it\n // (backpressure, client-abort → AbortController, stream cleanup)\n // without binding; the single bind is the `listen()` below.\n // `createAdaptorServer`'s `hostname` is only the fallback Host (see\n // `fallbackHost`); it does not affect the bind.\n const hostname = options?.hostname;\n server = createAdaptorServer({\n fetch: app.fetch,\n hostname: fallbackHost(hostname),\n createServer,\n }) as Server;\n const httpServer = server;\n bind = new Promise<void>((resolve, reject) => {\n const onError = (err: Error): void => {\n httpServer.off(\"listening\", onListening);\n reject(err);\n };\n const onListening = (): void => {\n httpServer.off(\"error\", onError);\n resolve();\n };\n httpServer.once(\"error\", onError);\n httpServer.once(\"listening\", onListening);\n if (hostname === undefined) {\n httpServer.listen(port);\n } else {\n httpServer.listen(port, hostname);\n }\n });\n await bind;\n\n // close() may have run while the bind was pending; it closes the\n // listener once this bind settles. Skip handler install so we don't\n // leak a SIGTERM/SIGINT listener onto a closed handle.\n if (closing !== undefined) {\n await close();\n return;\n }\n\n // Shared handler so a double-signal (SIGINT then SIGTERM) keeps\n // the listener count predictable for the close() cleanup path.\n signalHandler = (sig): void => {\n console.log(`Received ${sig}; closing baerlyNode server`);\n close()\n .then(() => process.exit(0))\n .catch((error: unknown) => {\n console.error(\"baerlyNode close failed\", error);\n process.exit(1);\n });\n };\n process.on(\"SIGTERM\", signalHandler);\n process.on(\"SIGINT\", signalHandler);\n };\n\n return { fetch: app.fetch, listen, close };\n}\n"],"ignoreList":[11,12,13,16,17,18],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAa,WAAW,OACtB,SACA,SAC4B;CAC5B,MAAM,SAAS,MAAM,aAAa;CAClC,MAAM,MAAM,GAAG,OAAO,uBAAuB,KAAK;CAClD,MAAM,MAAM,IAAI,YAAY;CAC5B,MAAM,SAAS,MAAM;CASrB,MAAM,YAAY,MAAM,aAAa;CAErC,MAAM,SAA0B,CAAC;CACjC,IAAI;EACY,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG,EAAE,OAAO,CAAC;EAGjE,IAAI;GAEF,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG;IAAE,SAAS;IAAW;GAAO,CAAC;GACvE,OAAO,KAAK;IACV,MAAM;IACN,IAAI;IACJ,QACE;GACJ,CAAC;EACH,SAAS,OAAO;GACd,OAAO,KACL,gBAAgB,KAAK,IACjB;IACE,MAAM;IACN,I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