@gusto/baerly-storage 0.3.0 → 0.4.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 +157 -92
- package/dist/API.md +64 -32
- package/dist/CHANGELOG.md +295 -5
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +22 -96
- package/dist/{app-config-BIzyAKzy.d.ts → app-config-DyiFK3_k.d.ts} +43 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +13 -13
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/{client-BJXF3XJA.d.ts → client-Fe8CwB73.d.ts} +3 -3
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/{cloudflare-Cn2ibODt.js → cloudflare-DzKBrUlg.js} +2 -2
- package/dist/{cloudflare-Cn2ibODt.js.map → cloudflare-DzKBrUlg.js.map} +1 -1
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +55 -21
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/{cost-BZ_MDBmn.js → cost-DSMIVqzL.js} +42 -43
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/{current-json-DsN7FNY1.js → current-json-C6nhPOm1.js} +6 -204
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-CCT6tDfY.d.ts → db-DsPkOVEH.d.ts} +3 -3
- package/dist/{deploy-BKKyGlSJ.js → deploy-DonTr-CV.js} +4 -4
- package/dist/{deploy-BKKyGlSJ.js.map → deploy-DonTr-CV.js.map} +1 -1
- package/dist/dev-vite.d.ts +9 -5
- package/dist/dev-vite.js +5 -4
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-BVU4GNXN.js → doctor-DSIyCDg_.js} +5 -8
- package/dist/{doctor-BVU4GNXN.js.map → doctor-DSIyCDg_.js.map} +1 -1
- package/dist/{dump-DPEAKub6.js → dump-Bh5k26VQ.js} +9 -32
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-BcuCLFFe.js → export-DtF5tDIM.js} +9 -32
- package/dist/{export-BcuCLFFe.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-RXgLOaJG.js → fsck-D_djMO5D.js} +10 -33
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Bd4byR4n.js → http-DxM9MflO.js} +123 -35
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DnBGSeuU.d.ts → index-0rZcMBwy.d.ts} +2 -2
- package/dist/{index-Cmsxx-ZN.d.ts → index-B6oexfOB.d.ts} +7 -7
- package/dist/{index-BDceQQi-.d.ts → index-BNRh23K9.d.ts} +4 -4
- package/dist/{index-DW7GT6M2.d.ts → index-BYk9oCNf.d.ts} +193 -163
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-Cx7uMXm0.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-DhI49PSi.js → inspect-6WZ-pC7-.js} +10 -33
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{log-tail-DXeDkWEp.js → log-tail-D98U1JBo.js} +31 -7
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-CWBQpZ2y.js → maintenance-B4Dki6Ig.js} +77 -22
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BkhUr72A.d.ts → maintenance-B_e0T99L.d.ts} +28 -5
- package/dist/{maintenance-C_KSkVjd.js → maintenance-C7coQp4c.js} +17 -16
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -3
- package/dist/maintenance.js +3 -3
- package/dist/node.d.ts +168 -65
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-BYd-RzEx.js → observability-wzs3-BL_.js} +233 -71
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +1 -1
- package/dist/{plan-DIu_B6fy.js → plan-a7PJHBCy.js} +2 -2
- package/dist/{plan-DIu_B6fy.js.map → plan-a7PJHBCy.js.map} +1 -1
- package/dist/{query-sQNO5vU_.js → query-rAtXNQQB.js} +96 -207
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DP4CqSSs.js → rebuild-index-BVzQSZlm.js} +9 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/{restore-DpQYef6r.js → restore-R-4rbciV.js} +73 -100
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/{subcommand-CP9NY2J4.js → subcommand-DoDA-K7d.js} +44 -6
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CTfDq9HR.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +52 -28
- package/dist/config-CGyBopy3.js +0 -5326
- package/dist/config-CGyBopy3.js.map +0 -1
- package/dist/cost-BZ_MDBmn.js.map +0 -1
- package/dist/current-json-DsN7FNY1.js.map +0 -1
- package/dist/dump-DPEAKub6.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-RXgLOaJG.js.map +0 -1
- package/dist/http-Bd4byR4n.js.map +0 -1
- package/dist/inspect-DhI49PSi.js.map +0 -1
- package/dist/log-tail-DXeDkWEp.js.map +0 -1
- package/dist/maintenance-CWBQpZ2y.js.map +0 -1
- package/dist/maintenance-C_KSkVjd.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-BYd-RzEx.js.map +0 -1
- package/dist/query-sQNO5vU_.js.map +0 -1
- package/dist/rebuild-index-DP4CqSSs.js.map +0 -1
- package/dist/restore-DpQYef6r.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/src-CWpkSbvJ.js.map +0 -1
- package/dist/src-D24wDpzR.js +0 -6247
- package/dist/src-D24wDpzR.js.map +0 -1
- package/dist/src-Db4-qVtM.js.map +0 -1
- package/dist/subcommand-CP9NY2J4.js.map +0 -1
- package/dist/usage-CTfDq9HR.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
|
@@ -0,0 +1,2271 @@
|
|
|
1
|
+
import { c as configureObservability, n as flushCanonicalLine, o as deriveOutcome, r as flushUnauthorizedAndRespond, t as observableStorage, u as errorEnvelope } from "./observability-wzs3-BL_.js";
|
|
2
|
+
import { d as MAINTENANCE_PROFILE_NODE } from "./constants-CfeMWQWk.js";
|
|
3
|
+
import { t as BaerlyError } from "./errors-Dfa3p78c.js";
|
|
4
|
+
import { o as parseMaintenanceEnv } from "./maintenance-B4Dki6Ig.js";
|
|
5
|
+
import { a as isDeployedEnv, n as resolveVerifier, t as Db } from "./src-CYHFDrKz.js";
|
|
6
|
+
import { a as uuid } from "./time-DUqvFMHq.js";
|
|
7
|
+
import { n as createRouter, o as Hono, r as mapError, t as MAX_BODY_BYTES } from "./http-DxM9MflO.js";
|
|
8
|
+
import { r as runWithContext, t as createObservabilityContext } from "./context-DRZ3tZ5l.js";
|
|
9
|
+
import { a as require_picocolors_browser, r as renderDevLanding, t as LocalFsStorage } from "./src-DYZ4H1aF.js";
|
|
10
|
+
import { t as handleSpecRequest } from "./runtime-spec-qL3_lTTU.js";
|
|
11
|
+
import { i as parseStsError, n as S3HttpStorage, r as parseAssumeRoleWithWebIdentity, t as AwsClient } from "./aws4fetch.esm-p7eEzLCs.js";
|
|
12
|
+
import { readFile, stat } from "node:fs/promises";
|
|
13
|
+
import { extname, relative, resolve, sep } from "node:path";
|
|
14
|
+
import { STATUS_CODES, createServer } from "node:http";
|
|
15
|
+
import { Http2ServerRequest, constants } from "node:http2";
|
|
16
|
+
import { Readable } from "node:stream";
|
|
17
|
+
import { createReadStream } from "node:fs";
|
|
18
|
+
//#region packages/protocol/src/storage/probe-cas.ts
|
|
19
|
+
const isConflict = (error) => error instanceof BaerlyError && error.code === "Conflict";
|
|
20
|
+
/**
|
|
21
|
+
* Runtime probe that a live `Storage` backend honours the conditional
|
|
22
|
+
* writes the protocol depends on. The storage conformance suite asserts
|
|
23
|
+
* the same semantics in CI for every shipped adapter, but a deployment
|
|
24
|
+
* may point baerly at an arbitrary S3-compatible store; a backend that
|
|
25
|
+
* silently *ignores* these conditionals causes silent corruption — the
|
|
26
|
+
* log-append commit relies on `If-None-Match:"*"` create-if-absent
|
|
27
|
+
* being exactly-one-winner under concurrency (the winning create IS the
|
|
28
|
+
* commit; two winners produce split-brain commit), and the compactor
|
|
29
|
+
* CAS-advances `current.json` with `If-Match` under the no-lease
|
|
30
|
+
* maintenance fold (a backend that returns 200 instead of rejecting a
|
|
31
|
+
* stale `If-Match` causes lost-update corruption). This is the
|
|
32
|
+
* fail-loud, deploy-time analogue of the conformance CAS block.
|
|
33
|
+
*
|
|
34
|
+
* Writes throwaway sentinels under `keyPrefix` and deletes them on
|
|
35
|
+
* the way out (even on failure). Three checks, mirroring the conformance
|
|
36
|
+
* suite:
|
|
37
|
+
* - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).
|
|
38
|
+
* - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:"*"` over an existing
|
|
39
|
+
* key must reject (Conflict).
|
|
40
|
+
* - `ifNoneMatch-concurrent`: at most one of N concurrent create-if-absent
|
|
41
|
+
* writes on a fresh key wins — the linearizability the writer's log-append
|
|
42
|
+
* commit already relies on (`writer.ts`).
|
|
43
|
+
*
|
|
44
|
+
* A rejected write surfaces as a `BaerlyError` with `code === "Conflict"`
|
|
45
|
+
* (the contract `Storage.put` documents); anything else — a resolved
|
|
46
|
+
* promise, or a non-Conflict error — is reported as a failed or
|
|
47
|
+
* inconclusive check rather than thrown.
|
|
48
|
+
*/
|
|
49
|
+
const probeCas = async (storage, opts) => {
|
|
50
|
+
const prefix = opts?.keyPrefix ?? "";
|
|
51
|
+
const key = `${prefix}__baerly_cas_probe__/${uuid()}`;
|
|
52
|
+
const enc = new TextEncoder();
|
|
53
|
+
const signal = opts?.signal;
|
|
54
|
+
const checks = [];
|
|
55
|
+
try {
|
|
56
|
+
await storage.put(key, enc.encode("v1"), { signal });
|
|
57
|
+
try {
|
|
58
|
+
await storage.put(key, enc.encode("v2"), {
|
|
59
|
+
ifMatch: "\"baerly-cas-probe-stale\"",
|
|
60
|
+
signal
|
|
61
|
+
});
|
|
62
|
+
checks.push({
|
|
63
|
+
name: "ifMatch-stale",
|
|
64
|
+
ok: false,
|
|
65
|
+
detail: "PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk)."
|
|
66
|
+
});
|
|
67
|
+
} catch (error) {
|
|
68
|
+
checks.push(isConflict(error) ? {
|
|
69
|
+
name: "ifMatch-stale",
|
|
70
|
+
ok: true,
|
|
71
|
+
detail: "stale If-Match rejected (Conflict), as required."
|
|
72
|
+
} : {
|
|
73
|
+
name: "ifMatch-stale",
|
|
74
|
+
ok: false,
|
|
75
|
+
detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
await storage.put(key, enc.encode("v3"), {
|
|
80
|
+
ifNoneMatch: "*",
|
|
81
|
+
signal
|
|
82
|
+
});
|
|
83
|
+
checks.push({
|
|
84
|
+
name: "ifNoneMatch-exists",
|
|
85
|
+
ok: false,
|
|
86
|
+
detail: "PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe)."
|
|
87
|
+
});
|
|
88
|
+
} catch (error) {
|
|
89
|
+
checks.push(isConflict(error) ? {
|
|
90
|
+
name: "ifNoneMatch-exists",
|
|
91
|
+
ok: true,
|
|
92
|
+
detail: "If-None-Match:\"*\" over an existing key rejected (Conflict), as required."
|
|
93
|
+
} : {
|
|
94
|
+
name: "ifNoneMatch-exists",
|
|
95
|
+
ok: false,
|
|
96
|
+
detail: `If-None-Match:"*" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const raceKey = `${prefix}__baerly_cas_probe__/${uuid()}`;
|
|
100
|
+
const RACERS = 16;
|
|
101
|
+
try {
|
|
102
|
+
const outcomes = await Promise.allSettled(Array.from({ length: RACERS }, (_unused, i) => storage.put(raceKey, enc.encode(`r${i}`), {
|
|
103
|
+
ifNoneMatch: "*",
|
|
104
|
+
signal
|
|
105
|
+
})));
|
|
106
|
+
const winners = outcomes.filter((o) => o.status === "fulfilled").length;
|
|
107
|
+
const transient = outcomes.filter((o) => o.status === "rejected" && !isConflict(o.reason)).length;
|
|
108
|
+
if (winners > 1) checks.push({
|
|
109
|
+
name: "ifNoneMatch-concurrent",
|
|
110
|
+
ok: false,
|
|
111
|
+
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.`
|
|
112
|
+
});
|
|
113
|
+
else if (winners === 1) if (transient === 0) checks.push({
|
|
114
|
+
name: "ifNoneMatch-concurrent",
|
|
115
|
+
ok: true,
|
|
116
|
+
detail: `exactly one of ${RACERS} concurrent create-if-absent writes won; the rest rejected (Conflict), as required.`
|
|
117
|
+
});
|
|
118
|
+
else checks.push({
|
|
119
|
+
name: "ifNoneMatch-concurrent",
|
|
120
|
+
ok: false,
|
|
121
|
+
detail: `exactly one of ${RACERS} concurrent create-if-absent writes won, but ${transient} loser(s) returned a transient non-Conflict error — inconclusive; retry for a clean race.`
|
|
122
|
+
});
|
|
123
|
+
else checks.push({
|
|
124
|
+
name: "ifNoneMatch-concurrent",
|
|
125
|
+
ok: false,
|
|
126
|
+
detail: `no create-if-absent write succeeded across ${RACERS} attempts — inconclusive (transient failure or outage), not a linearizability verdict; retry.`
|
|
127
|
+
});
|
|
128
|
+
} finally {
|
|
129
|
+
try {
|
|
130
|
+
await storage.delete(raceKey, signal === void 0 ? void 0 : { signal });
|
|
131
|
+
} catch {}
|
|
132
|
+
}
|
|
133
|
+
} finally {
|
|
134
|
+
try {
|
|
135
|
+
await storage.delete(key, signal === void 0 ? void 0 : { signal });
|
|
136
|
+
} catch {}
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
ok: checks.every((c) => c.ok),
|
|
140
|
+
checks
|
|
141
|
+
};
|
|
142
|
+
};
|
|
143
|
+
//#endregion
|
|
144
|
+
//#region packages/adapter-node/src/credentials/signer.ts
|
|
145
|
+
const REFRESH_BUFFER_MS = 300 * 1e3;
|
|
146
|
+
function buildAwsClient(creds, region) {
|
|
147
|
+
return new AwsClient({
|
|
148
|
+
accessKeyId: creds.accessKeyId,
|
|
149
|
+
secretAccessKey: creds.secretAccessKey,
|
|
150
|
+
sessionToken: creds.sessionToken,
|
|
151
|
+
region,
|
|
152
|
+
service: "s3"
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
function refreshingSigner(opts) {
|
|
156
|
+
const region = opts.region;
|
|
157
|
+
const now = opts.now ?? (() => Date.now());
|
|
158
|
+
if (typeof opts.credentials !== "function") {
|
|
159
|
+
const aws = buildAwsClient(opts.credentials, region);
|
|
160
|
+
return (req) => aws.sign(req);
|
|
161
|
+
}
|
|
162
|
+
const provider = opts.credentials;
|
|
163
|
+
let cached = null;
|
|
164
|
+
let inFlight = null;
|
|
165
|
+
const resolve = async () => {
|
|
166
|
+
if (cached !== null && cached.expiresAt - REFRESH_BUFFER_MS > now()) return cached.aws;
|
|
167
|
+
if (inFlight !== null) return inFlight;
|
|
168
|
+
inFlight = (async () => {
|
|
169
|
+
try {
|
|
170
|
+
const creds = await provider();
|
|
171
|
+
const aws = buildAwsClient(creds, region);
|
|
172
|
+
cached = {
|
|
173
|
+
aws,
|
|
174
|
+
expiresAt: creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY
|
|
175
|
+
};
|
|
176
|
+
return aws;
|
|
177
|
+
} finally {
|
|
178
|
+
inFlight = null;
|
|
179
|
+
}
|
|
180
|
+
})();
|
|
181
|
+
return inFlight;
|
|
182
|
+
};
|
|
183
|
+
return async (req) => {
|
|
184
|
+
return (await resolve()).sign(req);
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
//#endregion
|
|
188
|
+
//#region packages/adapter-node/src/storage-factories.ts
|
|
189
|
+
function buildS3Storage(opts) {
|
|
190
|
+
const sign = refreshingSigner({
|
|
191
|
+
region: opts.region,
|
|
192
|
+
credentials: opts.credentials
|
|
193
|
+
});
|
|
194
|
+
return new S3HttpStorage({
|
|
195
|
+
endpoint: opts.endpoint,
|
|
196
|
+
bucket: opts.bucket,
|
|
197
|
+
sign
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard
|
|
202
|
+
* `aws4fetch` SigV4 signer. The endpoint is derived from the region as
|
|
203
|
+
* `https://s3.<region>.amazonaws.com`.
|
|
204
|
+
*
|
|
205
|
+
* @example Static credentials
|
|
206
|
+
* ```ts
|
|
207
|
+
* import { s3Storage } from "@gusto/baerly-storage/node";
|
|
208
|
+
*
|
|
209
|
+
* const storage = s3Storage({
|
|
210
|
+
* region: process.env["AWS_REGION"] ?? "us-east-1",
|
|
211
|
+
* bucket: process.env["BUCKET"]!,
|
|
212
|
+
* credentials: {
|
|
213
|
+
* accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
|
|
214
|
+
* secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
|
|
215
|
+
* },
|
|
216
|
+
* });
|
|
217
|
+
* ```
|
|
218
|
+
*
|
|
219
|
+
* @example EKS (refreshing) — auto-detects Pod Identity or IRSA
|
|
220
|
+
* ```ts
|
|
221
|
+
* import { s3Storage, fromEks } from "@gusto/baerly-storage/node";
|
|
222
|
+
*
|
|
223
|
+
* const storage = s3Storage({
|
|
224
|
+
* region: process.env["AWS_REGION"] ?? "us-east-1",
|
|
225
|
+
* bucket: process.env["BUCKET"]!,
|
|
226
|
+
* credentials: fromEks(),
|
|
227
|
+
* });
|
|
228
|
+
* ```
|
|
229
|
+
*/
|
|
230
|
+
function s3Storage(opts) {
|
|
231
|
+
return buildS3Storage({
|
|
232
|
+
endpoint: `https://s3.${opts.region}.amazonaws.com`,
|
|
233
|
+
region: opts.region,
|
|
234
|
+
bucket: opts.bucket,
|
|
235
|
+
credentials: opts.credentials
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Cloudflare R2 `Storage` factory (S3-compat endpoint). Derives the
|
|
240
|
+
* endpoint from `accountId` as
|
|
241
|
+
* `https://<accountId>.r2.cloudflarestorage.com` and pins region
|
|
242
|
+
* `"auto"` — R2 ignores region but `aws4fetch`'s signer requires
|
|
243
|
+
* the field to be set.
|
|
244
|
+
*
|
|
245
|
+
* For Workers that have a native R2 binding (no HTTP hop), see
|
|
246
|
+
* `r2BindingStorage` in `@baerly/adapter-cloudflare`. This factory
|
|
247
|
+
* is for Node hosts that talk to R2 over its public S3-compat URL.
|
|
248
|
+
*
|
|
249
|
+
* @example
|
|
250
|
+
* ```ts
|
|
251
|
+
* import { r2Storage } from "@gusto/baerly-storage/node";
|
|
252
|
+
*
|
|
253
|
+
* const storage = r2Storage({
|
|
254
|
+
* accountId: process.env["R2_ACCOUNT_ID"]!,
|
|
255
|
+
* bucket: process.env["BUCKET"]!,
|
|
256
|
+
* credentials: {
|
|
257
|
+
* accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
|
|
258
|
+
* secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
|
|
259
|
+
* },
|
|
260
|
+
* });
|
|
261
|
+
* ```
|
|
262
|
+
*/
|
|
263
|
+
function r2Storage(opts) {
|
|
264
|
+
return buildS3Storage({
|
|
265
|
+
endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,
|
|
266
|
+
region: "auto",
|
|
267
|
+
bucket: opts.bucket,
|
|
268
|
+
credentials: opts.credentials
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Minio `Storage` factory — for local-dev / self-hosted S3-compat.
|
|
273
|
+
* Endpoint is fully caller-supplied (e.g. `http://localhost:9102`)
|
|
274
|
+
* because Minio deployments don't follow a URL template. Region is
|
|
275
|
+
* pinned to `"us-east-1"`; Minio ignores it but `aws4fetch` requires
|
|
276
|
+
* a value.
|
|
277
|
+
*
|
|
278
|
+
* @example
|
|
279
|
+
* ```ts
|
|
280
|
+
* import { minioStorage } from "@gusto/baerly-storage/node";
|
|
281
|
+
*
|
|
282
|
+
* const storage = minioStorage({
|
|
283
|
+
* endpoint: process.env["BAERLY_S3_ENDPOINT"] ?? "http://localhost:9102",
|
|
284
|
+
* bucket: "baerly",
|
|
285
|
+
* credentials: {
|
|
286
|
+
* accessKeyId: process.env["MINIO_ACCESS_KEY"]!,
|
|
287
|
+
* secretAccessKey: process.env["MINIO_SECRET_KEY"]!,
|
|
288
|
+
* },
|
|
289
|
+
* });
|
|
290
|
+
* ```
|
|
291
|
+
*/
|
|
292
|
+
function minioStorage(opts) {
|
|
293
|
+
return buildS3Storage({
|
|
294
|
+
endpoint: opts.endpoint,
|
|
295
|
+
region: "us-east-1",
|
|
296
|
+
bucket: opts.bucket,
|
|
297
|
+
credentials: opts.credentials
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Google Cloud Storage `Storage` factory via the S3-compat endpoint
|
|
302
|
+
* at `https://storage.googleapis.com`. Authentication uses GCS HMAC
|
|
303
|
+
* keys (Console → Settings → Interoperability) — the HMAC access key
|
|
304
|
+
* goes into `credentials.accessKeyId` and the HMAC secret goes into
|
|
305
|
+
* `credentials.secretAccessKey`. Region is pinned to `"auto"`.
|
|
306
|
+
*
|
|
307
|
+
* GCS's S3-compat surface covers the four `Storage` methods
|
|
308
|
+
* (`get`/`put`/`delete`/`list`), but Google documents the
|
|
309
|
+
* `If-Match`/`If-None-Match` headers this kernel coordinates on as
|
|
310
|
+
* read-only (native conditional writes use `x-goog-if-generation-match`).
|
|
311
|
+
* Whether GCS's interop layer enforces S3-style conditional *writes* is
|
|
312
|
+
* unverified — run `baerly doctor --bucket=<your-gcs-bucket>` before
|
|
313
|
+
* relying on it; a backend that fails the CAS probe is not a safe baerly
|
|
314
|
+
* store. See ADR-002.
|
|
315
|
+
*
|
|
316
|
+
* @example
|
|
317
|
+
* ```ts
|
|
318
|
+
* import { gcsStorage } from "@gusto/baerly-storage/node";
|
|
319
|
+
*
|
|
320
|
+
* const storage = gcsStorage({
|
|
321
|
+
* bucket: process.env["BUCKET"]!,
|
|
322
|
+
* credentials: {
|
|
323
|
+
* accessKeyId: process.env["GCS_HMAC_ACCESS_KEY_ID"]!,
|
|
324
|
+
* secretAccessKey: process.env["GCS_HMAC_SECRET"]!,
|
|
325
|
+
* },
|
|
326
|
+
* });
|
|
327
|
+
* ```
|
|
328
|
+
*/
|
|
329
|
+
function gcsStorage(opts) {
|
|
330
|
+
return buildS3Storage({
|
|
331
|
+
endpoint: "https://storage.googleapis.com",
|
|
332
|
+
region: "auto",
|
|
333
|
+
bucket: opts.bucket,
|
|
334
|
+
credentials: opts.credentials
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
//#endregion
|
|
338
|
+
//#region packages/adapter-node/src/local-fs-storage.ts
|
|
339
|
+
/**
|
|
340
|
+
* Zero-config local `Storage` for single-node dev / self-hosted runs.
|
|
341
|
+
* Persists to the filesystem (content-addressed, atomic writes), so data
|
|
342
|
+
* survives process restarts — unlike `MemoryStorage`, which is per-process
|
|
343
|
+
* and lost on exit.
|
|
344
|
+
*
|
|
345
|
+
* NOT for multi-instance production: `LocalFsStorage`'s `ifMatch` CAS is
|
|
346
|
+
* in-process TOCTOU only (cross-process `current.json` CAS-advance is not
|
|
347
|
+
* atomic — see its class JSDoc). For horizontally-scaled deploys use
|
|
348
|
+
* `s3Storage` / `r2Storage`, whose cross-process guarantee the no-lease
|
|
349
|
+
* maintenance fold relies on.
|
|
350
|
+
*
|
|
351
|
+
* @example
|
|
352
|
+
* ```ts
|
|
353
|
+
* import { baerlyNode, localFsStorage } from "@gusto/baerly-storage/node";
|
|
354
|
+
* import config from "./baerly.config.ts";
|
|
355
|
+
*
|
|
356
|
+
* // Runs with zero credentials; persists to ./.baerly-data.
|
|
357
|
+
* await baerlyNode({ config, storage: localFsStorage() }).listen(8080);
|
|
358
|
+
* ```
|
|
359
|
+
*/
|
|
360
|
+
const localFsStorage = (opts) => new LocalFsStorage({ root: opts?.dataDir ?? process.env["BAERLY_DATA_DIR"] ?? resolve(process.cwd(), ".baerly-data") });
|
|
361
|
+
//#endregion
|
|
362
|
+
//#region packages/adapter-node/src/resolve-storage.ts
|
|
363
|
+
/**
|
|
364
|
+
* Choose a Node `Storage` backend from environment variables, in priority
|
|
365
|
+
* order:
|
|
366
|
+
* 1. `R2_ACCOUNT_ID` set → Cloudflare R2 (S3-compat endpoint)
|
|
367
|
+
* 2. `BUCKET` set → AWS S3
|
|
368
|
+
* 3. neither, local dev → `localFsStorage` (zero credentials)
|
|
369
|
+
* 4. neither, deployed → throw
|
|
370
|
+
*
|
|
371
|
+
* This is the safe default the example scaffolds use, exported so apps
|
|
372
|
+
* don't hand-roll their own selector and reintroduce the silent
|
|
373
|
+
* in-memory / local-fs fallback this library exists to prevent. There is
|
|
374
|
+
* deliberately **no** fallback to a non-durable store in a deployment:
|
|
375
|
+
* local-fs is single-process with no cross-process CAS and no crash
|
|
376
|
+
* durability, and in-memory storage loses all data on restart, so a
|
|
377
|
+
* deployed environment with no bucket fails loud instead.
|
|
378
|
+
*
|
|
379
|
+
* `env` is injectable for testing; it defaults to `process.env`.
|
|
380
|
+
*
|
|
381
|
+
* @throws BaerlyError `InvalidConfig` when {@link isDeployedEnv} is true
|
|
382
|
+
* and no bucket is configured, or when a configured bucket is missing its
|
|
383
|
+
* credentials.
|
|
384
|
+
*
|
|
385
|
+
* @example
|
|
386
|
+
* ```ts
|
|
387
|
+
* import { baerlyNode, resolveStorageFromEnv } from "@gusto/baerly-storage/node";
|
|
388
|
+
* import config from "./baerly.config.ts";
|
|
389
|
+
*
|
|
390
|
+
* const { storage, label } = resolveStorageFromEnv();
|
|
391
|
+
* console.log(`[baerly] storage=${label}`);
|
|
392
|
+
* await baerlyNode({ config, storage }).listen(Number(process.env["PORT"] ?? 8080));
|
|
393
|
+
* ```
|
|
394
|
+
*/
|
|
395
|
+
const resolveStorageFromEnv = (env = process.env) => {
|
|
396
|
+
const isSet = (name) => (env[name] ?? "") !== "";
|
|
397
|
+
const reqEnv = (name) => {
|
|
398
|
+
const v = env[name];
|
|
399
|
+
if (v === void 0 || v === "") throw new BaerlyError("InvalidConfig", `Missing required env var: ${name}`);
|
|
400
|
+
return v;
|
|
401
|
+
};
|
|
402
|
+
if (isSet("R2_ACCOUNT_ID")) return {
|
|
403
|
+
storage: r2Storage({
|
|
404
|
+
accountId: reqEnv("R2_ACCOUNT_ID"),
|
|
405
|
+
bucket: reqEnv("BUCKET"),
|
|
406
|
+
credentials: {
|
|
407
|
+
accessKeyId: reqEnv("AWS_ACCESS_KEY_ID"),
|
|
408
|
+
secretAccessKey: reqEnv("AWS_SECRET_ACCESS_KEY")
|
|
409
|
+
}
|
|
410
|
+
}),
|
|
411
|
+
label: `r2 (bucket=${env["BUCKET"]})`
|
|
412
|
+
};
|
|
413
|
+
if (isSet("BUCKET")) return {
|
|
414
|
+
storage: s3Storage({
|
|
415
|
+
region: env["AWS_REGION"] ?? "us-east-1",
|
|
416
|
+
bucket: reqEnv("BUCKET"),
|
|
417
|
+
credentials: {
|
|
418
|
+
accessKeyId: reqEnv("AWS_ACCESS_KEY_ID"),
|
|
419
|
+
secretAccessKey: reqEnv("AWS_SECRET_ACCESS_KEY")
|
|
420
|
+
}
|
|
421
|
+
}),
|
|
422
|
+
label: `s3 (bucket=${env["BUCKET"]})`
|
|
423
|
+
};
|
|
424
|
+
if (!isDeployedEnv(env)) return {
|
|
425
|
+
storage: localFsStorage(),
|
|
426
|
+
label: `local-fs (${env["BAERLY_DATA_DIR"] ?? "./.baerly-data"}) — local dev only, not a production store`
|
|
427
|
+
};
|
|
428
|
+
throw new BaerlyError("InvalidConfig", [
|
|
429
|
+
"[baerly] Refusing to start: no durable storage configured in a deployed environment.",
|
|
430
|
+
"Local filesystem storage is a local-dev convenience only — single-process, with no",
|
|
431
|
+
"cross-process CAS and no crash durability — so it is never used in production.",
|
|
432
|
+
"Configure a real bucket:",
|
|
433
|
+
" • AWS S3: BUCKET + AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY (+ optional AWS_REGION)",
|
|
434
|
+
" • Cloudflare R2: R2_ACCOUNT_ID + BUCKET + AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY",
|
|
435
|
+
"Self-hosting without a cloud bucket? Run MinIO on the box for real S3 semantics, or",
|
|
436
|
+
"use SQLite + Litestream for a single-instance app."
|
|
437
|
+
].join("\n"));
|
|
438
|
+
};
|
|
439
|
+
//#endregion
|
|
440
|
+
//#region packages/adapter-node/src/assert-storage-reachable.ts
|
|
441
|
+
/**
|
|
442
|
+
* Boot-time readiness check: confirm a live `Storage` backend is both
|
|
443
|
+
* reachable and honours the conditional writes the protocol depends on.
|
|
444
|
+
* `await` it at startup (or from a `/readyz` handler wired to your
|
|
445
|
+
* platform's readiness probe) to fail closed on a misconfigured backend —
|
|
446
|
+
* an unreachable or non-existent bucket, denied/missing credentials (wrong
|
|
447
|
+
* endpoint/region), or an S3-compatible store that silently ignores
|
|
448
|
+
* `If-Match`/`If-None-Match` (the CAS the protocol depends on) — instead
|
|
449
|
+
* of discovering it on the first user write. It cannot detect a
|
|
450
|
+
* wrong-but-writable bucket: a typo to another reachable bucket you own
|
|
451
|
+
* boots clean, because the probe can only tell that *a* bucket is reachable
|
|
452
|
+
* and CAS-correct, not that it is the *intended* one. This complements
|
|
453
|
+
* `resolveStorageFromEnv`, which catches a *missing* configuration:
|
|
454
|
+
* `assertStorageReachable` additionally catches an
|
|
455
|
+
* unreachable/access-denied/CAS-broken backend at boot instead of on the
|
|
456
|
+
* first write.
|
|
457
|
+
*
|
|
458
|
+
* Opt-in by design: it performs a handful of live round-trips (writes and
|
|
459
|
+
* deletes throwaway sentinels under `keyPrefix`), so it is never run
|
|
460
|
+
* automatically on every boot. Reuses the same `probeCas` machinery as
|
|
461
|
+
* `baerly doctor --bucket`.
|
|
462
|
+
*
|
|
463
|
+
* @throws BaerlyError `NetworkError` if the backend is unreachable, or
|
|
464
|
+
* `InvalidConfig` if it is reachable but fails a required CAS check.
|
|
465
|
+
*
|
|
466
|
+
* @example
|
|
467
|
+
* ```ts
|
|
468
|
+
* const { storage, label } = resolveStorageFromEnv();
|
|
469
|
+
* await assertStorageReachable(storage); // throws before we serve traffic
|
|
470
|
+
* console.log(`[baerly] storage=${label} (reachable)`);
|
|
471
|
+
* ```
|
|
472
|
+
*/
|
|
473
|
+
const assertStorageReachable = async (storage, opts) => {
|
|
474
|
+
let result;
|
|
475
|
+
try {
|
|
476
|
+
result = await probeCas(storage, opts);
|
|
477
|
+
} catch (error) {
|
|
478
|
+
throw new BaerlyError("NetworkError", `Storage readiness check failed: the backend could not be reached. Verify the bucket name, region/endpoint, and credentials. Cause: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
479
|
+
}
|
|
480
|
+
if (!result.ok) throw new BaerlyError("InvalidConfig", `Storage readiness check failed — the backend does not honour the conditional writes baerly requires (data corruption risk). Use a fully S3-conditional-compatible store:\n${result.checks.filter((c) => !c.ok).map((c) => ` - ${c.name}: ${c.detail}`).join("\n")}`);
|
|
481
|
+
};
|
|
482
|
+
//#endregion
|
|
483
|
+
//#region packages/adapter-node/src/credentials/token-file.ts
|
|
484
|
+
/**
|
|
485
|
+
* Read and validate an EKS-projected service-account token file, shared by
|
|
486
|
+
* {@link fromWebIdentity} and {@link fromEksPodIdentity}. Reads the file,
|
|
487
|
+
* trims surrounding whitespace (the projected token has a trailing newline),
|
|
488
|
+
* and rejects an empty result.
|
|
489
|
+
*
|
|
490
|
+
* A missing / unreadable / empty projected token is a deploy misconfig, not a
|
|
491
|
+
* transient fault — so every failure is `InvalidConfig`, which short-circuits
|
|
492
|
+
* the retry loop (see `PERMANENT_ERROR_CODES` in `s3-http.ts`) instead of
|
|
493
|
+
* hammering the credential source. Error messages name the specific env var
|
|
494
|
+
* so the misconfig is debuggable.
|
|
495
|
+
*/
|
|
496
|
+
async function readProjectedToken(doReadFile, tokenPath, ctx) {
|
|
497
|
+
let rawToken;
|
|
498
|
+
try {
|
|
499
|
+
rawToken = await doReadFile(tokenPath, "utf8");
|
|
500
|
+
} catch (error) {
|
|
501
|
+
throw new BaerlyError("InvalidConfig", `${ctx.provider}: cannot read ${ctx.envVar} (${tokenPath}): ${error.message}`);
|
|
502
|
+
}
|
|
503
|
+
const token = rawToken.trim();
|
|
504
|
+
if (token === "") throw new BaerlyError("InvalidConfig", `${ctx.provider}: ${ctx.envVar} (${tokenPath}) is empty`);
|
|
505
|
+
return token;
|
|
506
|
+
}
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region packages/adapter-node/src/credentials/from-eks-pod-identity.ts
|
|
509
|
+
const FETCH_TIMEOUT_MS$1 = 2e3;
|
|
510
|
+
/**
|
|
511
|
+
* Resolve AWS credentials from the EKS Pod Identity agent (the 2023
|
|
512
|
+
* successor to IRSA). The agent runs on each EKS node and exchanges
|
|
513
|
+
* the pod's projected service-account token for short-lived AWS
|
|
514
|
+
* credentials, so the app just reads the token and asks the agent.
|
|
515
|
+
*
|
|
516
|
+
* Env vars (set by EKS when the pod has an associated IAM role):
|
|
517
|
+
* - `AWS_CONTAINER_CREDENTIALS_FULL_URI` — the agent endpoint
|
|
518
|
+
* (typically `http://169.254.170.23/v1/credentials`).
|
|
519
|
+
* - `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` — path to the
|
|
520
|
+
* projected SA token used to authorize the agent request.
|
|
521
|
+
*
|
|
522
|
+
* Both are required. Agent should respond instantly on the node-local
|
|
523
|
+
* link — 2 s timeout protects against hangs.
|
|
524
|
+
*/
|
|
525
|
+
function fromEksPodIdentity(opts = {}) {
|
|
526
|
+
const doFetch = opts.fetch ?? fetch;
|
|
527
|
+
const doReadFile = opts.readFile ?? readFile;
|
|
528
|
+
return async () => {
|
|
529
|
+
const uri = process.env["AWS_CONTAINER_CREDENTIALS_FULL_URI"];
|
|
530
|
+
const tokenPath = process.env["AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"];
|
|
531
|
+
if (uri === void 0 || uri === "") throw new BaerlyError("InvalidConfig", "fromEksPodIdentity: AWS_CONTAINER_CREDENTIALS_FULL_URI not set");
|
|
532
|
+
if (tokenPath === void 0 || tokenPath === "") throw new BaerlyError("InvalidConfig", "fromEksPodIdentity: AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE not set");
|
|
533
|
+
const token = await readProjectedToken(doReadFile, tokenPath, {
|
|
534
|
+
provider: "fromEksPodIdentity",
|
|
535
|
+
envVar: "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"
|
|
536
|
+
});
|
|
537
|
+
let res;
|
|
538
|
+
try {
|
|
539
|
+
res = await doFetch(uri, {
|
|
540
|
+
method: "GET",
|
|
541
|
+
headers: { Authorization: token },
|
|
542
|
+
redirect: "error",
|
|
543
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS$1)
|
|
544
|
+
});
|
|
545
|
+
} catch (error) {
|
|
546
|
+
throw new BaerlyError("NetworkError", `fromEksPodIdentity: agent fetch failed (${error.message})`);
|
|
547
|
+
}
|
|
548
|
+
if (res.status >= 500 || res.status === 429) throw new BaerlyError("NetworkError", `fromEksPodIdentity: agent responded ${res.status}`);
|
|
549
|
+
if (!res.ok) throw new BaerlyError("AccessDenied", `fromEksPodIdentity: agent responded ${res.status}`);
|
|
550
|
+
let json;
|
|
551
|
+
try {
|
|
552
|
+
json = await res.json();
|
|
553
|
+
} catch (error) {
|
|
554
|
+
throw new BaerlyError("InvalidResponse", `fromEksPodIdentity: agent returned non-JSON body (${error.message})`);
|
|
555
|
+
}
|
|
556
|
+
if (json.AccessKeyId === void 0 || json.SecretAccessKey === void 0 || json.Token === void 0 || json.Expiration === void 0) throw new BaerlyError("InvalidResponse", "fromEksPodIdentity: malformed agent response");
|
|
557
|
+
const expiration = new Date(json.Expiration);
|
|
558
|
+
if (Number.isNaN(expiration.getTime())) throw new BaerlyError("InvalidResponse", "fromEksPodIdentity: malformed agent response");
|
|
559
|
+
return {
|
|
560
|
+
accessKeyId: json.AccessKeyId,
|
|
561
|
+
secretAccessKey: json.SecretAccessKey,
|
|
562
|
+
sessionToken: json.Token,
|
|
563
|
+
expiration
|
|
564
|
+
};
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
//#endregion
|
|
568
|
+
//#region packages/adapter-node/src/credentials/from-web-identity.ts
|
|
569
|
+
const FETCH_TIMEOUT_MS = 5e3;
|
|
570
|
+
const DEFAULT_SESSION_NAME = "baerly-storage";
|
|
571
|
+
/**
|
|
572
|
+
* Resolve AWS credentials via IRSA (IAM Roles for Service Accounts) — the
|
|
573
|
+
* web-identity-token flow, distinct from the EKS Pod Identity agent that
|
|
574
|
+
* {@link fromEksPodIdentity} handles. EKS projects a signed service-account
|
|
575
|
+
* token into the pod and the app exchanges it for short-lived credentials by
|
|
576
|
+
* calling STS `AssumeRoleWithWebIdentity` directly (the token *is* the auth, so
|
|
577
|
+
* the call is unsigned — no chicken-and-egg credential bootstrap).
|
|
578
|
+
*
|
|
579
|
+
* Env vars (set by EKS when the pod's service account is annotated with a role):
|
|
580
|
+
* - `AWS_ROLE_ARN` — the role to assume.
|
|
581
|
+
* - `AWS_WEB_IDENTITY_TOKEN_FILE` — path to the projected SA token.
|
|
582
|
+
* - `AWS_ROLE_SESSION_NAME` — optional session name (defaults to `baerly-storage`).
|
|
583
|
+
* - `AWS_REGION` / `AWS_DEFAULT_REGION` — optional; selects the regional STS
|
|
584
|
+
* endpoint (falls back to the global endpoint).
|
|
585
|
+
*
|
|
586
|
+
* STS credentials expire (~1 h); the returned provider reports `expiration`, so
|
|
587
|
+
* the signing layer re-resolves before they lapse.
|
|
588
|
+
*/
|
|
589
|
+
function fromWebIdentity(opts = {}) {
|
|
590
|
+
const doFetch = opts.fetch ?? fetch;
|
|
591
|
+
const doReadFile = opts.readFile ?? readFile;
|
|
592
|
+
return async () => {
|
|
593
|
+
const roleArn = process.env["AWS_ROLE_ARN"];
|
|
594
|
+
const tokenPath = process.env["AWS_WEB_IDENTITY_TOKEN_FILE"];
|
|
595
|
+
const sessionName = process.env["AWS_ROLE_SESSION_NAME"] || DEFAULT_SESSION_NAME;
|
|
596
|
+
const region = process.env["AWS_REGION"] || process.env["AWS_DEFAULT_REGION"];
|
|
597
|
+
if (roleArn === void 0 || roleArn === "") throw new BaerlyError("InvalidConfig", "fromWebIdentity: AWS_ROLE_ARN not set");
|
|
598
|
+
if (tokenPath === void 0 || tokenPath === "") throw new BaerlyError("InvalidConfig", "fromWebIdentity: AWS_WEB_IDENTITY_TOKEN_FILE not set");
|
|
599
|
+
const token = await readProjectedToken(doReadFile, tokenPath, {
|
|
600
|
+
provider: "fromWebIdentity",
|
|
601
|
+
envVar: "AWS_WEB_IDENTITY_TOKEN_FILE"
|
|
602
|
+
});
|
|
603
|
+
const endpoint = region !== void 0 && region !== "" ? `https://sts.${region}.amazonaws.com/` : "https://sts.amazonaws.com/";
|
|
604
|
+
const body = new URLSearchParams({
|
|
605
|
+
Action: "AssumeRoleWithWebIdentity",
|
|
606
|
+
Version: "2011-06-15",
|
|
607
|
+
RoleArn: roleArn,
|
|
608
|
+
RoleSessionName: sessionName,
|
|
609
|
+
WebIdentityToken: token
|
|
610
|
+
}).toString();
|
|
611
|
+
let res;
|
|
612
|
+
try {
|
|
613
|
+
res = await doFetch(endpoint, {
|
|
614
|
+
method: "POST",
|
|
615
|
+
headers: {
|
|
616
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
617
|
+
Accept: "application/xml"
|
|
618
|
+
},
|
|
619
|
+
body,
|
|
620
|
+
redirect: "error",
|
|
621
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
|
|
622
|
+
});
|
|
623
|
+
} catch (error) {
|
|
624
|
+
throw new BaerlyError("NetworkError", `fromWebIdentity: STS fetch failed (${error.message})`);
|
|
625
|
+
}
|
|
626
|
+
if (!res.ok) {
|
|
627
|
+
const stsErr = parseStsError(await res.text());
|
|
628
|
+
const detail = stsErr?.Code !== void 0 ? ` (${stsErr.Code}${stsErr.Message !== void 0 ? `: ${stsErr.Message}` : ""})` : "";
|
|
629
|
+
if (res.status >= 500 || res.status === 429) throw new BaerlyError("NetworkError", `fromWebIdentity: STS responded ${res.status}${detail}`);
|
|
630
|
+
throw new BaerlyError("AccessDenied", `fromWebIdentity: STS responded ${res.status}${detail}`);
|
|
631
|
+
}
|
|
632
|
+
const parsed = parseAssumeRoleWithWebIdentity(await res.text());
|
|
633
|
+
if (parsed.AccessKeyId === void 0 || parsed.SecretAccessKey === void 0 || parsed.SessionToken === void 0 || parsed.Expiration === void 0) throw new BaerlyError("InvalidResponse", "fromWebIdentity: malformed STS response");
|
|
634
|
+
const expiration = new Date(parsed.Expiration);
|
|
635
|
+
if (Number.isNaN(expiration.getTime())) throw new BaerlyError("InvalidResponse", "fromWebIdentity: malformed STS response");
|
|
636
|
+
return {
|
|
637
|
+
accessKeyId: parsed.AccessKeyId,
|
|
638
|
+
secretAccessKey: parsed.SecretAccessKey,
|
|
639
|
+
sessionToken: parsed.SessionToken,
|
|
640
|
+
expiration
|
|
641
|
+
};
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
//#endregion
|
|
645
|
+
//#region packages/adapter-node/src/credentials/from-eks.ts
|
|
646
|
+
/**
|
|
647
|
+
* Resolve AWS credentials on EKS regardless of which identity mechanism the
|
|
648
|
+
* cluster uses, so callers don't have to know. EKS injects credentials one of
|
|
649
|
+
* two ways:
|
|
650
|
+
*
|
|
651
|
+
* - **Pod Identity** (2023+): `AWS_CONTAINER_CREDENTIALS_FULL_URI` +
|
|
652
|
+
* `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` → {@link fromEksPodIdentity}.
|
|
653
|
+
* - **IRSA** (web-identity token): `AWS_ROLE_ARN` +
|
|
654
|
+
* `AWS_WEB_IDENTITY_TOKEN_FILE` → {@link fromWebIdentity}.
|
|
655
|
+
*
|
|
656
|
+
* Detection runs on every resolve (Pod Identity preferred when both are
|
|
657
|
+
* present), so the right mechanism is picked even if the env is populated late
|
|
658
|
+
* and re-checked on each refresh. Use this instead of the mechanism-specific
|
|
659
|
+
* providers unless you have a reason to pin one.
|
|
660
|
+
*/
|
|
661
|
+
function fromEks(opts = {}) {
|
|
662
|
+
const podIdentity = fromEksPodIdentity(opts);
|
|
663
|
+
const webIdentity = fromWebIdentity(opts);
|
|
664
|
+
return async () => {
|
|
665
|
+
const uri = process.env["AWS_CONTAINER_CREDENTIALS_FULL_URI"];
|
|
666
|
+
const tokenFile = process.env["AWS_WEB_IDENTITY_TOKEN_FILE"];
|
|
667
|
+
if (uri !== void 0 && uri !== "") return podIdentity();
|
|
668
|
+
if (tokenFile !== void 0 && tokenFile !== "") return webIdentity();
|
|
669
|
+
throw new BaerlyError("InvalidConfig", "fromEks: no EKS credentials in env — set AWS_CONTAINER_CREDENTIALS_FULL_URI (Pod Identity) or AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN (IRSA)");
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
//#endregion
|
|
673
|
+
//#region node_modules/.pnpm/@hono+node-server@2.0.6_hono@4.12.27/node_modules/@hono/node-server/dist/index.mjs
|
|
674
|
+
var RequestError = class extends Error {
|
|
675
|
+
constructor(message, options) {
|
|
676
|
+
super(message, options);
|
|
677
|
+
this.name = "RequestError";
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
|
|
681
|
+
const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
|
|
682
|
+
const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
|
|
683
|
+
const buildUrl = (scheme, host, incomingUrl) => {
|
|
684
|
+
const url = `${scheme}://${host}${incomingUrl}`;
|
|
685
|
+
if (!reValidHost.test(host)) {
|
|
686
|
+
const urlObj = new URL(url);
|
|
687
|
+
if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
|
|
688
|
+
return urlObj.href;
|
|
689
|
+
} else if (incomingUrl.length === 0) return url + "/";
|
|
690
|
+
else {
|
|
691
|
+
if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
|
|
692
|
+
if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
|
|
693
|
+
return url;
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
const toRequestError = (e) => {
|
|
697
|
+
if (e instanceof RequestError) return e;
|
|
698
|
+
return new RequestError(e.message, { cause: e });
|
|
699
|
+
};
|
|
700
|
+
const GlobalRequest = global.Request;
|
|
701
|
+
var Request$1 = class extends GlobalRequest {
|
|
702
|
+
constructor(input, options) {
|
|
703
|
+
if (typeof input === "object" && getRequestCache in input) {
|
|
704
|
+
const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
|
|
705
|
+
if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
|
|
706
|
+
input = input[getRequestCache]();
|
|
707
|
+
}
|
|
708
|
+
if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
|
|
709
|
+
super(input, options);
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
const newHeadersFromIncoming = (incoming) => {
|
|
713
|
+
const headerRecord = [];
|
|
714
|
+
const rawHeaders = incoming.rawHeaders;
|
|
715
|
+
for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
|
|
716
|
+
const key = rawHeaders[i];
|
|
717
|
+
if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
|
|
718
|
+
}
|
|
719
|
+
return new Headers(headerRecord);
|
|
720
|
+
};
|
|
721
|
+
const wrapBodyStream = Symbol("wrapBodyStream");
|
|
722
|
+
const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
723
|
+
const init = {
|
|
724
|
+
method,
|
|
725
|
+
headers,
|
|
726
|
+
signal: abortController.signal
|
|
727
|
+
};
|
|
728
|
+
if (method === "TRACE") {
|
|
729
|
+
init.method = "GET";
|
|
730
|
+
const req = new Request$1(url, init);
|
|
731
|
+
Object.defineProperty(req, "method", { get() {
|
|
732
|
+
return "TRACE";
|
|
733
|
+
} });
|
|
734
|
+
return req;
|
|
735
|
+
}
|
|
736
|
+
if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
|
|
737
|
+
controller.enqueue(incoming.rawBody);
|
|
738
|
+
controller.close();
|
|
739
|
+
} });
|
|
740
|
+
else if (incoming[wrapBodyStream]) {
|
|
741
|
+
let reader;
|
|
742
|
+
init.body = new ReadableStream({ async pull(controller) {
|
|
743
|
+
try {
|
|
744
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
745
|
+
const { done, value } = await reader.read();
|
|
746
|
+
if (done) controller.close();
|
|
747
|
+
else controller.enqueue(value);
|
|
748
|
+
} catch (error) {
|
|
749
|
+
controller.error(error);
|
|
750
|
+
}
|
|
751
|
+
} });
|
|
752
|
+
} else init.body = Readable.toWeb(incoming);
|
|
753
|
+
return new Request$1(url, init);
|
|
754
|
+
};
|
|
755
|
+
const getRequestCache = Symbol("getRequestCache");
|
|
756
|
+
const requestCache = Symbol("requestCache");
|
|
757
|
+
const incomingKey = Symbol("incomingKey");
|
|
758
|
+
const urlKey = Symbol("urlKey");
|
|
759
|
+
const methodKey = Symbol("methodKey");
|
|
760
|
+
const headersKey = Symbol("headersKey");
|
|
761
|
+
const abortControllerKey = Symbol("abortControllerKey");
|
|
762
|
+
const getAbortController = Symbol("getAbortController");
|
|
763
|
+
const abortRequest = Symbol("abortRequest");
|
|
764
|
+
const bodyBufferKey = Symbol("bodyBuffer");
|
|
765
|
+
const bodyReadPromiseKey = Symbol("bodyReadPromise");
|
|
766
|
+
const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
|
|
767
|
+
const bodyLockReaderKey = Symbol("bodyLockReader");
|
|
768
|
+
const abortReasonKey = Symbol("abortReason");
|
|
769
|
+
const newBodyUnusableError = () => {
|
|
770
|
+
return /* @__PURE__ */ new TypeError("Body is unusable");
|
|
771
|
+
};
|
|
772
|
+
const rejectBodyUnusable = () => {
|
|
773
|
+
return Promise.reject(newBodyUnusableError());
|
|
774
|
+
};
|
|
775
|
+
const textDecoder = new TextDecoder();
|
|
776
|
+
const consumeBodyDirectOnce = (request) => {
|
|
777
|
+
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
|
778
|
+
request[bodyConsumedDirectlyKey] = true;
|
|
779
|
+
};
|
|
780
|
+
const toArrayBuffer = (buf) => {
|
|
781
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
782
|
+
};
|
|
783
|
+
const contentType = (request) => {
|
|
784
|
+
return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
|
|
785
|
+
};
|
|
786
|
+
const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
787
|
+
const normalizeIncomingMethod = (method) => {
|
|
788
|
+
if (typeof method !== "string" || method.length === 0) return "GET";
|
|
789
|
+
switch (method) {
|
|
790
|
+
case "DELETE":
|
|
791
|
+
case "GET":
|
|
792
|
+
case "HEAD":
|
|
793
|
+
case "OPTIONS":
|
|
794
|
+
case "POST":
|
|
795
|
+
case "PUT": return method;
|
|
796
|
+
}
|
|
797
|
+
const upper = method.toUpperCase();
|
|
798
|
+
switch (upper) {
|
|
799
|
+
case "DELETE":
|
|
800
|
+
case "GET":
|
|
801
|
+
case "HEAD":
|
|
802
|
+
case "OPTIONS":
|
|
803
|
+
case "POST":
|
|
804
|
+
case "PUT": return upper;
|
|
805
|
+
default: return method;
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
const validateDirectReadMethod = (method) => {
|
|
809
|
+
if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
|
|
810
|
+
const normalized = method.toUpperCase();
|
|
811
|
+
if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
|
|
812
|
+
};
|
|
813
|
+
const readBodyWithFastPath = (request, method, fromBuffer) => {
|
|
814
|
+
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
|
815
|
+
const methodName = request.method;
|
|
816
|
+
if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
|
|
817
|
+
const methodValidationError = validateDirectReadMethod(methodName);
|
|
818
|
+
if (methodValidationError) return Promise.reject(methodValidationError);
|
|
819
|
+
if (request[requestCache]) {
|
|
820
|
+
if (methodName !== "TRACE") return request[requestCache][method]();
|
|
821
|
+
}
|
|
822
|
+
const alreadyUsedError = consumeBodyDirectOnce(request);
|
|
823
|
+
if (alreadyUsedError) return alreadyUsedError;
|
|
824
|
+
const raw = readRawBodyIfAvailable(request);
|
|
825
|
+
if (raw) {
|
|
826
|
+
const result = Promise.resolve(fromBuffer(raw, request));
|
|
827
|
+
request[bodyBufferKey] = void 0;
|
|
828
|
+
return result;
|
|
829
|
+
}
|
|
830
|
+
return readBodyDirect(request).then((buf) => {
|
|
831
|
+
const result = fromBuffer(buf, request);
|
|
832
|
+
request[bodyBufferKey] = void 0;
|
|
833
|
+
return result;
|
|
834
|
+
});
|
|
835
|
+
};
|
|
836
|
+
const readRawBodyIfAvailable = (request) => {
|
|
837
|
+
const incoming = request[incomingKey];
|
|
838
|
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
|
|
839
|
+
};
|
|
840
|
+
const readBodyDirect = (request) => {
|
|
841
|
+
if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
|
|
842
|
+
if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
|
|
843
|
+
const incoming = request[incomingKey];
|
|
844
|
+
if (Readable.isDisturbed(incoming)) return rejectBodyUnusable();
|
|
845
|
+
const promise = new Promise((resolve, reject) => {
|
|
846
|
+
const chunks = [];
|
|
847
|
+
let settled = false;
|
|
848
|
+
const finish = (callback) => {
|
|
849
|
+
if (settled) return;
|
|
850
|
+
settled = true;
|
|
851
|
+
cleanup();
|
|
852
|
+
callback();
|
|
853
|
+
};
|
|
854
|
+
const onData = (chunk) => {
|
|
855
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
856
|
+
};
|
|
857
|
+
const onEnd = () => {
|
|
858
|
+
finish(() => {
|
|
859
|
+
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
|
|
860
|
+
request[bodyBufferKey] = buffer;
|
|
861
|
+
resolve(buffer);
|
|
862
|
+
});
|
|
863
|
+
};
|
|
864
|
+
const onError = (error) => {
|
|
865
|
+
finish(() => {
|
|
866
|
+
reject(error);
|
|
867
|
+
});
|
|
868
|
+
};
|
|
869
|
+
const onClose = () => {
|
|
870
|
+
if (incoming.readableEnded) {
|
|
871
|
+
onEnd();
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
finish(() => {
|
|
875
|
+
if (incoming.errored) {
|
|
876
|
+
reject(incoming.errored);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
const reason = request[abortReasonKey];
|
|
880
|
+
if (reason !== void 0) {
|
|
881
|
+
reject(reason instanceof Error ? reason : new Error(String(reason)));
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
|
|
885
|
+
});
|
|
886
|
+
};
|
|
887
|
+
const cleanup = () => {
|
|
888
|
+
incoming.off("data", onData);
|
|
889
|
+
incoming.off("end", onEnd);
|
|
890
|
+
incoming.off("error", onError);
|
|
891
|
+
incoming.off("close", onClose);
|
|
892
|
+
request[bodyReadPromiseKey] = void 0;
|
|
893
|
+
};
|
|
894
|
+
incoming.on("data", onData);
|
|
895
|
+
incoming.on("end", onEnd);
|
|
896
|
+
incoming.on("error", onError);
|
|
897
|
+
incoming.on("close", onClose);
|
|
898
|
+
queueMicrotask(() => {
|
|
899
|
+
if (settled) return;
|
|
900
|
+
if (incoming.readableEnded) onEnd();
|
|
901
|
+
else if (incoming.errored) onError(incoming.errored);
|
|
902
|
+
else if (incoming.destroyed) onClose();
|
|
903
|
+
});
|
|
904
|
+
});
|
|
905
|
+
request[bodyReadPromiseKey] = promise;
|
|
906
|
+
return promise;
|
|
907
|
+
};
|
|
908
|
+
const requestPrototype = {
|
|
909
|
+
get method() {
|
|
910
|
+
return this[methodKey];
|
|
911
|
+
},
|
|
912
|
+
get url() {
|
|
913
|
+
return this[urlKey];
|
|
914
|
+
},
|
|
915
|
+
get headers() {
|
|
916
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
917
|
+
},
|
|
918
|
+
[abortRequest](reason) {
|
|
919
|
+
if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
|
|
920
|
+
const abortController = this[abortControllerKey];
|
|
921
|
+
if (abortController && !abortController.signal.aborted) abortController.abort(reason);
|
|
922
|
+
},
|
|
923
|
+
[getAbortController]() {
|
|
924
|
+
this[abortControllerKey] ||= new AbortController();
|
|
925
|
+
if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
|
|
926
|
+
return this[abortControllerKey];
|
|
927
|
+
},
|
|
928
|
+
[getRequestCache]() {
|
|
929
|
+
const abortController = this[getAbortController]();
|
|
930
|
+
if (this[requestCache]) return this[requestCache];
|
|
931
|
+
const method = this.method;
|
|
932
|
+
if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
|
|
933
|
+
this[bodyBufferKey] = void 0;
|
|
934
|
+
const init = {
|
|
935
|
+
method: method === "TRACE" ? "GET" : method,
|
|
936
|
+
headers: this.headers,
|
|
937
|
+
signal: abortController.signal
|
|
938
|
+
};
|
|
939
|
+
if (method !== "TRACE") {
|
|
940
|
+
init.body = new ReadableStream({ start(c) {
|
|
941
|
+
c.close();
|
|
942
|
+
} });
|
|
943
|
+
init.duplex = "half";
|
|
944
|
+
}
|
|
945
|
+
const req = new Request$1(this[urlKey], init);
|
|
946
|
+
if (method === "TRACE") Object.defineProperty(req, "method", { get() {
|
|
947
|
+
return "TRACE";
|
|
948
|
+
} });
|
|
949
|
+
return this[requestCache] = req;
|
|
950
|
+
}
|
|
951
|
+
return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
|
|
952
|
+
},
|
|
953
|
+
get body() {
|
|
954
|
+
if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
|
|
955
|
+
const request = this[getRequestCache]();
|
|
956
|
+
if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
|
|
957
|
+
return request.body;
|
|
958
|
+
},
|
|
959
|
+
get bodyUsed() {
|
|
960
|
+
if (this[bodyConsumedDirectlyKey]) return true;
|
|
961
|
+
if (this[requestCache]) return this[requestCache].bodyUsed;
|
|
962
|
+
return false;
|
|
963
|
+
}
|
|
964
|
+
};
|
|
965
|
+
Object.defineProperty(requestPrototype, "signal", { get() {
|
|
966
|
+
return this[getAbortController]().signal;
|
|
967
|
+
} });
|
|
968
|
+
[
|
|
969
|
+
"cache",
|
|
970
|
+
"credentials",
|
|
971
|
+
"destination",
|
|
972
|
+
"integrity",
|
|
973
|
+
"mode",
|
|
974
|
+
"redirect",
|
|
975
|
+
"referrer",
|
|
976
|
+
"referrerPolicy",
|
|
977
|
+
"keepalive"
|
|
978
|
+
].forEach((k) => {
|
|
979
|
+
Object.defineProperty(requestPrototype, k, { get() {
|
|
980
|
+
return this[getRequestCache]()[k];
|
|
981
|
+
} });
|
|
982
|
+
});
|
|
983
|
+
["clone", "formData"].forEach((k) => {
|
|
984
|
+
Object.defineProperty(requestPrototype, k, { value: function() {
|
|
985
|
+
if (this[bodyConsumedDirectlyKey]) {
|
|
986
|
+
if (k === "clone") throw newBodyUnusableError();
|
|
987
|
+
return rejectBodyUnusable();
|
|
988
|
+
}
|
|
989
|
+
return this[getRequestCache]()[k]();
|
|
990
|
+
} });
|
|
991
|
+
});
|
|
992
|
+
Object.defineProperty(requestPrototype, "text", { value: function() {
|
|
993
|
+
return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
|
|
994
|
+
} });
|
|
995
|
+
Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
|
|
996
|
+
return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
|
|
997
|
+
} });
|
|
998
|
+
Object.defineProperty(requestPrototype, "blob", { value: function() {
|
|
999
|
+
return readBodyWithFastPath(this, "blob", (buf, request) => {
|
|
1000
|
+
const type = contentType(request);
|
|
1001
|
+
return new Response(buf, type ? { headers: { "content-type": type } } : void 0).blob();
|
|
1002
|
+
});
|
|
1003
|
+
} });
|
|
1004
|
+
Object.defineProperty(requestPrototype, "json", { value: function() {
|
|
1005
|
+
if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
|
1006
|
+
return this.text().then(JSON.parse);
|
|
1007
|
+
} });
|
|
1008
|
+
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
1009
|
+
return `Request (lightweight) ${inspectFn({
|
|
1010
|
+
method: this.method,
|
|
1011
|
+
url: this.url,
|
|
1012
|
+
headers: this.headers,
|
|
1013
|
+
nativeRequest: this[requestCache]
|
|
1014
|
+
}, {
|
|
1015
|
+
...options,
|
|
1016
|
+
depth: depth == null ? null : depth - 1
|
|
1017
|
+
})}`;
|
|
1018
|
+
} });
|
|
1019
|
+
Object.setPrototypeOf(requestPrototype, Request$1.prototype);
|
|
1020
|
+
const newRequest = (incoming, defaultHostname) => {
|
|
1021
|
+
const req = Object.create(requestPrototype);
|
|
1022
|
+
req[incomingKey] = incoming;
|
|
1023
|
+
req[methodKey] = normalizeIncomingMethod(incoming.method);
|
|
1024
|
+
const incomingUrl = incoming.url || "";
|
|
1025
|
+
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
1026
|
+
if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
1027
|
+
try {
|
|
1028
|
+
req[urlKey] = new URL(incomingUrl).href;
|
|
1029
|
+
} catch (e) {
|
|
1030
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
1031
|
+
}
|
|
1032
|
+
return req;
|
|
1033
|
+
}
|
|
1034
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
1035
|
+
if (!host) throw new RequestError("Missing host header");
|
|
1036
|
+
let scheme;
|
|
1037
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
1038
|
+
scheme = incoming.scheme;
|
|
1039
|
+
if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
|
|
1040
|
+
} else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
1041
|
+
try {
|
|
1042
|
+
req[urlKey] = buildUrl(scheme, host, incomingUrl);
|
|
1043
|
+
} catch (e) {
|
|
1044
|
+
if (e instanceof RequestError) throw e;
|
|
1045
|
+
else throw new RequestError("Invalid URL", { cause: e });
|
|
1046
|
+
}
|
|
1047
|
+
return req;
|
|
1048
|
+
};
|
|
1049
|
+
const defaultContentType = "text/plain; charset=UTF-8";
|
|
1050
|
+
const responseCache = Symbol("responseCache");
|
|
1051
|
+
const getResponseCache = Symbol("getResponseCache");
|
|
1052
|
+
const cacheKey = Symbol("cache");
|
|
1053
|
+
const GlobalResponse = global.Response;
|
|
1054
|
+
var Response$1 = class Response$1 {
|
|
1055
|
+
#body;
|
|
1056
|
+
#init;
|
|
1057
|
+
[getResponseCache]() {
|
|
1058
|
+
const cache = this[cacheKey];
|
|
1059
|
+
const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
|
|
1060
|
+
delete this[cacheKey];
|
|
1061
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
|
|
1062
|
+
status: this.#init?.status,
|
|
1063
|
+
statusText: this.#init?.statusText,
|
|
1064
|
+
headers: liveHeaders
|
|
1065
|
+
} : this.#init);
|
|
1066
|
+
}
|
|
1067
|
+
constructor(body, init) {
|
|
1068
|
+
let headers;
|
|
1069
|
+
this.#body = body;
|
|
1070
|
+
if (init instanceof Response$1) {
|
|
1071
|
+
const cachedGlobalResponse = init[responseCache];
|
|
1072
|
+
if (cachedGlobalResponse) {
|
|
1073
|
+
this.#init = cachedGlobalResponse;
|
|
1074
|
+
this[getResponseCache]();
|
|
1075
|
+
return;
|
|
1076
|
+
} else {
|
|
1077
|
+
this.#init = init.#init;
|
|
1078
|
+
headers = new Headers(init.headers);
|
|
1079
|
+
}
|
|
1080
|
+
} else this.#init = init;
|
|
1081
|
+
if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
|
|
1082
|
+
init?.status || 200,
|
|
1083
|
+
body ?? null,
|
|
1084
|
+
headers || init?.headers
|
|
1085
|
+
];
|
|
1086
|
+
}
|
|
1087
|
+
get headers() {
|
|
1088
|
+
const cache = this[cacheKey];
|
|
1089
|
+
if (cache) {
|
|
1090
|
+
if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
|
|
1091
|
+
return cache[2];
|
|
1092
|
+
}
|
|
1093
|
+
return this[getResponseCache]().headers;
|
|
1094
|
+
}
|
|
1095
|
+
get status() {
|
|
1096
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
1097
|
+
}
|
|
1098
|
+
get ok() {
|
|
1099
|
+
const status = this.status;
|
|
1100
|
+
return status >= 200 && status < 300;
|
|
1101
|
+
}
|
|
1102
|
+
};
|
|
1103
|
+
[
|
|
1104
|
+
"body",
|
|
1105
|
+
"bodyUsed",
|
|
1106
|
+
"redirected",
|
|
1107
|
+
"statusText",
|
|
1108
|
+
"trailers",
|
|
1109
|
+
"type",
|
|
1110
|
+
"url"
|
|
1111
|
+
].forEach((k) => {
|
|
1112
|
+
Object.defineProperty(Response$1.prototype, k, { get() {
|
|
1113
|
+
return this[getResponseCache]()[k];
|
|
1114
|
+
} });
|
|
1115
|
+
});
|
|
1116
|
+
[
|
|
1117
|
+
"arrayBuffer",
|
|
1118
|
+
"blob",
|
|
1119
|
+
"clone",
|
|
1120
|
+
"formData",
|
|
1121
|
+
"json",
|
|
1122
|
+
"text"
|
|
1123
|
+
].forEach((k) => {
|
|
1124
|
+
Object.defineProperty(Response$1.prototype, k, { value: function() {
|
|
1125
|
+
return this[getResponseCache]()[k]();
|
|
1126
|
+
} });
|
|
1127
|
+
});
|
|
1128
|
+
Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
|
1129
|
+
return `Response (lightweight) ${inspectFn({
|
|
1130
|
+
status: this.status,
|
|
1131
|
+
headers: this.headers,
|
|
1132
|
+
ok: this.ok,
|
|
1133
|
+
nativeResponse: this[responseCache]
|
|
1134
|
+
}, {
|
|
1135
|
+
...options,
|
|
1136
|
+
depth: depth == null ? null : depth - 1
|
|
1137
|
+
})}`;
|
|
1138
|
+
} });
|
|
1139
|
+
Object.setPrototypeOf(Response$1, GlobalResponse);
|
|
1140
|
+
Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
|
|
1141
|
+
const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
|
|
1142
|
+
const parseRedirectUrl = (url) => {
|
|
1143
|
+
if (url instanceof URL) return url.href;
|
|
1144
|
+
if (validRedirectUrl.test(url)) return url;
|
|
1145
|
+
return new URL(url).href;
|
|
1146
|
+
};
|
|
1147
|
+
const validRedirectStatuses = /* @__PURE__ */ new Set([
|
|
1148
|
+
301,
|
|
1149
|
+
302,
|
|
1150
|
+
303,
|
|
1151
|
+
307,
|
|
1152
|
+
308
|
|
1153
|
+
]);
|
|
1154
|
+
Object.defineProperty(Response$1, "redirect", {
|
|
1155
|
+
value: function redirect(url, status = 302) {
|
|
1156
|
+
if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
|
|
1157
|
+
return new Response$1(null, {
|
|
1158
|
+
status,
|
|
1159
|
+
headers: { location: parseRedirectUrl(url) }
|
|
1160
|
+
});
|
|
1161
|
+
},
|
|
1162
|
+
writable: true,
|
|
1163
|
+
configurable: true
|
|
1164
|
+
});
|
|
1165
|
+
Object.defineProperty(Response$1, "json", {
|
|
1166
|
+
value: function json(data, init) {
|
|
1167
|
+
const body = JSON.stringify(data);
|
|
1168
|
+
if (body === void 0) throw new TypeError("The data is not JSON serializable");
|
|
1169
|
+
const initHeaders = init?.headers;
|
|
1170
|
+
let headers;
|
|
1171
|
+
if (initHeaders) {
|
|
1172
|
+
headers = new Headers(initHeaders);
|
|
1173
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
1174
|
+
} else headers = { "content-type": "application/json" };
|
|
1175
|
+
return new Response$1(body, {
|
|
1176
|
+
status: init?.status ?? 200,
|
|
1177
|
+
statusText: init?.statusText,
|
|
1178
|
+
headers
|
|
1179
|
+
});
|
|
1180
|
+
},
|
|
1181
|
+
writable: true,
|
|
1182
|
+
configurable: true
|
|
1183
|
+
});
|
|
1184
|
+
async function readWithoutBlocking(readPromise) {
|
|
1185
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
1186
|
+
}
|
|
1187
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
1188
|
+
const cancel = (error) => {
|
|
1189
|
+
reader.cancel(error).catch(() => {});
|
|
1190
|
+
};
|
|
1191
|
+
writable.on("close", cancel);
|
|
1192
|
+
writable.on("error", cancel);
|
|
1193
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
1194
|
+
return reader.closed.finally(() => {
|
|
1195
|
+
writable.off("close", cancel);
|
|
1196
|
+
writable.off("error", cancel);
|
|
1197
|
+
});
|
|
1198
|
+
function handleStreamError(error) {
|
|
1199
|
+
if (error) writable.destroy(error);
|
|
1200
|
+
}
|
|
1201
|
+
function onDrain() {
|
|
1202
|
+
reader.read().then(flow, handleStreamError);
|
|
1203
|
+
}
|
|
1204
|
+
function flow({ done, value }) {
|
|
1205
|
+
try {
|
|
1206
|
+
if (done) writable.end();
|
|
1207
|
+
else if (!writable.write(value)) writable.once("drain", onDrain);
|
|
1208
|
+
else return reader.read().then(flow, handleStreamError);
|
|
1209
|
+
} catch (e) {
|
|
1210
|
+
handleStreamError(e);
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
function writeFromReadableStream(stream, writable) {
|
|
1215
|
+
if (stream.locked) throw new TypeError("ReadableStream is locked.");
|
|
1216
|
+
else if (writable.destroyed) return;
|
|
1217
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
1218
|
+
}
|
|
1219
|
+
const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
|
|
1220
|
+
const res = {};
|
|
1221
|
+
if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
|
|
1222
|
+
if (headers.has("set-cookie")) {
|
|
1223
|
+
const cookies = [];
|
|
1224
|
+
for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
|
|
1225
|
+
else res[k] = v;
|
|
1226
|
+
if (cookies.length > 0) res["set-cookie"] = cookies;
|
|
1227
|
+
} else for (const [k, v] of headers) res[k] = v;
|
|
1228
|
+
if (defaultContentType) res["content-type"] ??= defaultContentType;
|
|
1229
|
+
return res;
|
|
1230
|
+
};
|
|
1231
|
+
const outgoingEnded = Symbol("outgoingEnded");
|
|
1232
|
+
const incomingDraining = Symbol("incomingDraining");
|
|
1233
|
+
const DRAIN_TIMEOUT_MS = 500;
|
|
1234
|
+
const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
|
1235
|
+
const drainIncoming = (incoming) => {
|
|
1236
|
+
const incomingWithDrainState = incoming;
|
|
1237
|
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
|
|
1238
|
+
incomingWithDrainState[incomingDraining] = true;
|
|
1239
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
1240
|
+
try {
|
|
1241
|
+
incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
|
|
1242
|
+
} catch {}
|
|
1243
|
+
return;
|
|
1244
|
+
}
|
|
1245
|
+
let bytesRead = 0;
|
|
1246
|
+
const cleanup = () => {
|
|
1247
|
+
clearTimeout(timer);
|
|
1248
|
+
incoming.off("data", onData);
|
|
1249
|
+
incoming.off("end", cleanup);
|
|
1250
|
+
incoming.off("error", cleanup);
|
|
1251
|
+
};
|
|
1252
|
+
const forceClose = () => {
|
|
1253
|
+
cleanup();
|
|
1254
|
+
const socket = incoming.socket;
|
|
1255
|
+
if (socket && !socket.destroyed) socket.destroySoon();
|
|
1256
|
+
};
|
|
1257
|
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
|
1258
|
+
timer.unref?.();
|
|
1259
|
+
const onData = (chunk) => {
|
|
1260
|
+
bytesRead += chunk.length;
|
|
1261
|
+
if (bytesRead > MAX_DRAIN_BYTES) forceClose();
|
|
1262
|
+
};
|
|
1263
|
+
incoming.on("data", onData);
|
|
1264
|
+
incoming.on("end", cleanup);
|
|
1265
|
+
incoming.on("error", cleanup);
|
|
1266
|
+
incoming.resume();
|
|
1267
|
+
};
|
|
1268
|
+
const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
|
|
1269
|
+
if (incoming.errored) req[abortRequest](incoming.errored.toString());
|
|
1270
|
+
else if (!outgoing.writableFinished) req[abortRequest]("Client connection prematurely closed.");
|
|
1271
|
+
if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
|
|
1272
|
+
if (!incoming.readableEnded) setTimeout(() => {
|
|
1273
|
+
drainIncoming(incoming);
|
|
1274
|
+
});
|
|
1275
|
+
});
|
|
1276
|
+
};
|
|
1277
|
+
const isImmediateCacheableResponse = (res) => {
|
|
1278
|
+
if (!(cacheKey in res)) return false;
|
|
1279
|
+
const body = res[cacheKey][1];
|
|
1280
|
+
return body === null || typeof body === "string" || body instanceof Uint8Array;
|
|
1281
|
+
};
|
|
1282
|
+
const handleRequestError = () => new Response(null, { status: 400 });
|
|
1283
|
+
const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
|
|
1284
|
+
const handleResponseError = (e, outgoing) => {
|
|
1285
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
1286
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
|
|
1287
|
+
else {
|
|
1288
|
+
console.error(e);
|
|
1289
|
+
if (!outgoing.headersSent) outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
1290
|
+
outgoing.end(`Error: ${err.message}`);
|
|
1291
|
+
outgoing.destroy(err);
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
const flushHeaders = (outgoing) => {
|
|
1295
|
+
if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
|
|
1296
|
+
};
|
|
1297
|
+
const responseViaCache = async (res, outgoing) => {
|
|
1298
|
+
let [status, body, header] = res[cacheKey];
|
|
1299
|
+
if (!header) {
|
|
1300
|
+
if (body === null) {
|
|
1301
|
+
outgoing.writeHead(status);
|
|
1302
|
+
outgoing.end();
|
|
1303
|
+
} else if (typeof body === "string") {
|
|
1304
|
+
outgoing.writeHead(status, {
|
|
1305
|
+
"Content-Type": defaultContentType,
|
|
1306
|
+
"Content-Length": Buffer.byteLength(body)
|
|
1307
|
+
});
|
|
1308
|
+
outgoing.end(body);
|
|
1309
|
+
} else if (body instanceof Uint8Array) {
|
|
1310
|
+
outgoing.writeHead(status, {
|
|
1311
|
+
"Content-Type": defaultContentType,
|
|
1312
|
+
"Content-Length": body.byteLength
|
|
1313
|
+
});
|
|
1314
|
+
outgoing.end(body);
|
|
1315
|
+
} else if (body instanceof Blob) {
|
|
1316
|
+
outgoing.writeHead(status, {
|
|
1317
|
+
"Content-Type": defaultContentType,
|
|
1318
|
+
"Content-Length": body.size
|
|
1319
|
+
});
|
|
1320
|
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
1321
|
+
} else {
|
|
1322
|
+
outgoing.writeHead(status, { "Content-Type": defaultContentType });
|
|
1323
|
+
flushHeaders(outgoing);
|
|
1324
|
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
|
1325
|
+
}
|
|
1326
|
+
outgoing[outgoingEnded]?.();
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
let hasContentLength = false;
|
|
1330
|
+
if (header instanceof Headers) {
|
|
1331
|
+
hasContentLength = header.has("content-length");
|
|
1332
|
+
header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
|
|
1333
|
+
} else if (Array.isArray(header)) {
|
|
1334
|
+
const headerObj = new Headers(header);
|
|
1335
|
+
hasContentLength = headerObj.has("content-length");
|
|
1336
|
+
header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
|
|
1337
|
+
} else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
|
|
1338
|
+
hasContentLength = true;
|
|
1339
|
+
break;
|
|
1340
|
+
}
|
|
1341
|
+
if (!hasContentLength) {
|
|
1342
|
+
if (typeof body === "string") header["Content-Length"] = Buffer.byteLength(body);
|
|
1343
|
+
else if (body instanceof Uint8Array) header["Content-Length"] = body.byteLength;
|
|
1344
|
+
else if (body instanceof Blob) header["Content-Length"] = body.size;
|
|
1345
|
+
}
|
|
1346
|
+
outgoing.writeHead(status, header);
|
|
1347
|
+
if (body == null) outgoing.end();
|
|
1348
|
+
else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
|
|
1349
|
+
else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
1350
|
+
else {
|
|
1351
|
+
flushHeaders(outgoing);
|
|
1352
|
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
|
1353
|
+
}
|
|
1354
|
+
outgoing[outgoingEnded]?.();
|
|
1355
|
+
};
|
|
1356
|
+
const isPromise = (res) => typeof res.then === "function";
|
|
1357
|
+
const responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
1358
|
+
if (isPromise(res)) if (options.errorHandler) try {
|
|
1359
|
+
res = await res;
|
|
1360
|
+
} catch (err) {
|
|
1361
|
+
const errRes = await options.errorHandler(err);
|
|
1362
|
+
if (!errRes) return;
|
|
1363
|
+
res = errRes;
|
|
1364
|
+
}
|
|
1365
|
+
else res = await res.catch(handleFetchError);
|
|
1366
|
+
if (cacheKey in res) return responseViaCache(res, outgoing);
|
|
1367
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
|
|
1368
|
+
if (res.body) {
|
|
1369
|
+
const reader = res.body.getReader();
|
|
1370
|
+
const values = [];
|
|
1371
|
+
let done = false;
|
|
1372
|
+
let currentReadPromise = void 0;
|
|
1373
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
1374
|
+
let maxReadCount = 2;
|
|
1375
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
1376
|
+
currentReadPromise ||= reader.read();
|
|
1377
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
1378
|
+
console.error(e);
|
|
1379
|
+
done = true;
|
|
1380
|
+
});
|
|
1381
|
+
if (!chunk) {
|
|
1382
|
+
if (i === 1) {
|
|
1383
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
1384
|
+
maxReadCount = 3;
|
|
1385
|
+
continue;
|
|
1386
|
+
}
|
|
1387
|
+
break;
|
|
1388
|
+
}
|
|
1389
|
+
currentReadPromise = void 0;
|
|
1390
|
+
if (chunk.value) values.push(chunk.value);
|
|
1391
|
+
if (chunk.done) {
|
|
1392
|
+
done = true;
|
|
1393
|
+
break;
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
1397
|
+
}
|
|
1398
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
1399
|
+
values.forEach((value) => {
|
|
1400
|
+
outgoing.write(value);
|
|
1401
|
+
});
|
|
1402
|
+
if (done) outgoing.end();
|
|
1403
|
+
else {
|
|
1404
|
+
if (values.length === 0) flushHeaders(outgoing);
|
|
1405
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
1406
|
+
}
|
|
1407
|
+
} else if (resHeaderRecord["x-hono-already-sent"]) {} else {
|
|
1408
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
1409
|
+
outgoing.end();
|
|
1410
|
+
}
|
|
1411
|
+
outgoing[outgoingEnded]?.();
|
|
1412
|
+
};
|
|
1413
|
+
const getRequestListener = (fetchCallback, options = {}) => {
|
|
1414
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
1415
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
|
|
1416
|
+
Object.defineProperty(global, "Request", { value: Request$1 });
|
|
1417
|
+
Object.defineProperty(global, "Response", { value: Response$1 });
|
|
1418
|
+
}
|
|
1419
|
+
return async (incoming, outgoing) => {
|
|
1420
|
+
let res, req;
|
|
1421
|
+
let needsBodyCleanup = false;
|
|
1422
|
+
let closeHandlerAttached = false;
|
|
1423
|
+
const ensureCloseHandler = () => {
|
|
1424
|
+
if (!req || closeHandlerAttached) return;
|
|
1425
|
+
closeHandlerAttached = true;
|
|
1426
|
+
outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
|
|
1427
|
+
};
|
|
1428
|
+
try {
|
|
1429
|
+
req = newRequest(incoming, options.hostname);
|
|
1430
|
+
needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
|
|
1431
|
+
if (needsBodyCleanup) {
|
|
1432
|
+
incoming[wrapBodyStream] = true;
|
|
1433
|
+
if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
|
|
1434
|
+
if (!incoming.readableEnded) setTimeout(() => {
|
|
1435
|
+
if (!incoming.readableEnded) setTimeout(() => {
|
|
1436
|
+
incoming.destroy();
|
|
1437
|
+
outgoing.destroy();
|
|
1438
|
+
});
|
|
1439
|
+
});
|
|
1440
|
+
};
|
|
1441
|
+
}
|
|
1442
|
+
res = fetchCallback(req, {
|
|
1443
|
+
incoming,
|
|
1444
|
+
outgoing
|
|
1445
|
+
});
|
|
1446
|
+
if (!isPromise(res) && isImmediateCacheableResponse(res)) {
|
|
1447
|
+
if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
|
|
1448
|
+
if (!incoming.readableEnded) drainIncoming(incoming);
|
|
1449
|
+
});
|
|
1450
|
+
return responseViaCache(res, outgoing);
|
|
1451
|
+
}
|
|
1452
|
+
ensureCloseHandler();
|
|
1453
|
+
} catch (e) {
|
|
1454
|
+
if (!res) if (options.errorHandler) {
|
|
1455
|
+
ensureCloseHandler();
|
|
1456
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
1457
|
+
if (!res) return;
|
|
1458
|
+
} else if (!req) res = handleRequestError();
|
|
1459
|
+
else res = handleFetchError(e);
|
|
1460
|
+
else return handleResponseError(e, outgoing);
|
|
1461
|
+
}
|
|
1462
|
+
try {
|
|
1463
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
1464
|
+
} catch (e) {
|
|
1465
|
+
return handleResponseError(e, outgoing);
|
|
1466
|
+
}
|
|
1467
|
+
};
|
|
1468
|
+
};
|
|
1469
|
+
globalThis.CloseEvent;
|
|
1470
|
+
const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
|
|
1471
|
+
const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
|
|
1472
|
+
const responseHeadersToSkip = /* @__PURE__ */ new Set([
|
|
1473
|
+
"connection",
|
|
1474
|
+
"content-length",
|
|
1475
|
+
"keep-alive",
|
|
1476
|
+
"proxy-authenticate",
|
|
1477
|
+
"proxy-authorization",
|
|
1478
|
+
"te",
|
|
1479
|
+
"trailer",
|
|
1480
|
+
"transfer-encoding",
|
|
1481
|
+
"upgrade",
|
|
1482
|
+
"sec-websocket-accept",
|
|
1483
|
+
"sec-websocket-extensions",
|
|
1484
|
+
"sec-websocket-protocol"
|
|
1485
|
+
]);
|
|
1486
|
+
const appendResponseHeaders = (headers, responseHeaders) => {
|
|
1487
|
+
if (!responseHeaders) return;
|
|
1488
|
+
responseHeaders.forEach((value, key) => {
|
|
1489
|
+
if (responseHeadersToSkip.has(key.toLowerCase())) return;
|
|
1490
|
+
headers.push(`${key}: ${value}`);
|
|
1491
|
+
});
|
|
1492
|
+
};
|
|
1493
|
+
const rejectUpgradeRequest = (socket, status, responseHeaders) => {
|
|
1494
|
+
const responseLines = ["Connection: close", "Content-Length: 0"];
|
|
1495
|
+
appendResponseHeaders(responseLines, responseHeaders);
|
|
1496
|
+
socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
|
|
1497
|
+
`);
|
|
1498
|
+
};
|
|
1499
|
+
const createUpgradeRequest = (request) => {
|
|
1500
|
+
const protocol = request.socket.encrypted ? "https" : "http";
|
|
1501
|
+
const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
|
|
1502
|
+
const headers = new Headers();
|
|
1503
|
+
for (const key in request.headers) {
|
|
1504
|
+
const value = request.headers[key];
|
|
1505
|
+
if (!value) continue;
|
|
1506
|
+
headers.append(key, Array.isArray(value) ? value[0] : value);
|
|
1507
|
+
}
|
|
1508
|
+
return new Request(url, { headers });
|
|
1509
|
+
};
|
|
1510
|
+
const setupWebSocket = (options) => {
|
|
1511
|
+
const { server, fetchCallback, wss } = options;
|
|
1512
|
+
const waiterMap = /* @__PURE__ */ new Map();
|
|
1513
|
+
wss.on("connection", (ws, request) => {
|
|
1514
|
+
const waiter = waiterMap.get(request);
|
|
1515
|
+
if (waiter) {
|
|
1516
|
+
waiter.resolve(ws);
|
|
1517
|
+
waiterMap.delete(request);
|
|
1518
|
+
}
|
|
1519
|
+
});
|
|
1520
|
+
const waitForWebSocket = (request, connectionSymbol) => {
|
|
1521
|
+
return new Promise((resolve) => {
|
|
1522
|
+
waiterMap.set(request, {
|
|
1523
|
+
resolve,
|
|
1524
|
+
connectionSymbol
|
|
1525
|
+
});
|
|
1526
|
+
});
|
|
1527
|
+
};
|
|
1528
|
+
server.on("upgrade", async (request, socket, head) => {
|
|
1529
|
+
if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
|
|
1530
|
+
const env = {
|
|
1531
|
+
incoming: request,
|
|
1532
|
+
outgoing: void 0,
|
|
1533
|
+
wss,
|
|
1534
|
+
[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
|
|
1535
|
+
};
|
|
1536
|
+
let status = 400;
|
|
1537
|
+
let responseHeaders;
|
|
1538
|
+
try {
|
|
1539
|
+
const response = await fetchCallback(createUpgradeRequest(request), env);
|
|
1540
|
+
if (response instanceof Response) {
|
|
1541
|
+
status = response.status;
|
|
1542
|
+
responseHeaders = response.headers;
|
|
1543
|
+
}
|
|
1544
|
+
} catch {
|
|
1545
|
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
const waiter = waiterMap.get(request);
|
|
1549
|
+
if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
|
|
1550
|
+
waiterMap.delete(request);
|
|
1551
|
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
|
|
1552
|
+
return;
|
|
1553
|
+
}
|
|
1554
|
+
const addResponseHeaders = (headers) => {
|
|
1555
|
+
appendResponseHeaders(headers, responseHeaders);
|
|
1556
|
+
};
|
|
1557
|
+
wss.on("headers", addResponseHeaders);
|
|
1558
|
+
try {
|
|
1559
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
1560
|
+
wss.emit("connection", ws, request);
|
|
1561
|
+
});
|
|
1562
|
+
} finally {
|
|
1563
|
+
wss.off("headers", addResponseHeaders);
|
|
1564
|
+
}
|
|
1565
|
+
});
|
|
1566
|
+
server.on("close", () => {
|
|
1567
|
+
wss.close();
|
|
1568
|
+
});
|
|
1569
|
+
};
|
|
1570
|
+
const createAdaptorServer = (options) => {
|
|
1571
|
+
const fetchCallback = options.fetch;
|
|
1572
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
1573
|
+
hostname: options.hostname,
|
|
1574
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
1575
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
1576
|
+
});
|
|
1577
|
+
const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
|
|
1578
|
+
if (options.websocket && options.websocket.server) {
|
|
1579
|
+
if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
|
|
1580
|
+
setupWebSocket({
|
|
1581
|
+
server,
|
|
1582
|
+
fetchCallback,
|
|
1583
|
+
wss: options.websocket.server
|
|
1584
|
+
});
|
|
1585
|
+
}
|
|
1586
|
+
return server;
|
|
1587
|
+
};
|
|
1588
|
+
const serve = (options, listeningListener) => {
|
|
1589
|
+
const server = createAdaptorServer(options);
|
|
1590
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
1591
|
+
const serverInfo = server.address();
|
|
1592
|
+
listeningListener && listeningListener(serverInfo);
|
|
1593
|
+
});
|
|
1594
|
+
return server;
|
|
1595
|
+
};
|
|
1596
|
+
//#endregion
|
|
1597
|
+
//#region packages/adapter-node/src/middleware/body-cap.ts
|
|
1598
|
+
/**
|
|
1599
|
+
* Body-cap enforcement for Node-hosted requests. Replaces the
|
|
1600
|
+
* pre-pivot `bodyCapMiddleware` that attached `incoming.on("data",
|
|
1601
|
+
* ...)` — that listener raced with `@hono/node-server`'s own body
|
|
1602
|
+
* reader and dropped the first chunks of every POST. Wrapping
|
|
1603
|
+
* `req.body` with a counting `TransformStream` puts the cap in the
|
|
1604
|
+
* same reader chain as the kernel router's `c.req.arrayBuffer()`
|
|
1605
|
+
* consumer, so there is no race.
|
|
1606
|
+
*
|
|
1607
|
+
* Two cap-trip paths, both drain the upstream `IncomingMessage`
|
|
1608
|
+
* (`resume()`) so the client's body write completes and the 413
|
|
1609
|
+
* envelope reaches it cleanly (without drain, closing the response
|
|
1610
|
+
* mid-upload surfaces client-side as "socket hang up"):
|
|
1611
|
+
*
|
|
1612
|
+
* - Content-Length fast path → returns a 413 `Response` directly.
|
|
1613
|
+
* - Chunked slow path → wraps `req.body` with a counting
|
|
1614
|
+
* `TransformStream` that errors with `BaerlyError{code:
|
|
1615
|
+
* "PayloadTooLarge"}` when the running count exceeds `max`.
|
|
1616
|
+
* The kernel router's `readJsonBody` recognises the
|
|
1617
|
+
* `BaerlyError` and re-throws it verbatim; `mapToResponse`
|
|
1618
|
+
* surfaces the same 413 envelope as the fast path.
|
|
1619
|
+
*
|
|
1620
|
+
* Returns the original `Request` unchanged for `GET`/`HEAD`/
|
|
1621
|
+
* `OPTIONS` (no body to cap) and for hosts that don't expose an
|
|
1622
|
+
* `IncomingMessage` on the Hono context's env binding — defence-in-
|
|
1623
|
+
* depth lives in the kernel router's `readJsonBody`.
|
|
1624
|
+
*/
|
|
1625
|
+
function applyBodyCap(req, env, max) {
|
|
1626
|
+
if (req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return req;
|
|
1627
|
+
const incoming = env?.incoming;
|
|
1628
|
+
if (incoming === void 0) return req;
|
|
1629
|
+
const lenHeader = req.headers.get("content-length");
|
|
1630
|
+
if (lenHeader !== null) {
|
|
1631
|
+
const parsed = Number.parseInt(lenHeader, 10);
|
|
1632
|
+
if (Number.isFinite(parsed) && parsed > max) {
|
|
1633
|
+
incoming.resume();
|
|
1634
|
+
return cap413(max);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
const body = req.body;
|
|
1638
|
+
if (body === null) return req;
|
|
1639
|
+
let count = 0;
|
|
1640
|
+
let tripped = false;
|
|
1641
|
+
const counter = new TransformStream({ transform(chunk, controller) {
|
|
1642
|
+
if (tripped) return;
|
|
1643
|
+
count += chunk.byteLength;
|
|
1644
|
+
if (count > max) {
|
|
1645
|
+
tripped = true;
|
|
1646
|
+
incoming.resume();
|
|
1647
|
+
controller.error(new BaerlyError("PayloadTooLarge", `Body exceeds ${max} bytes`));
|
|
1648
|
+
return;
|
|
1649
|
+
}
|
|
1650
|
+
controller.enqueue(chunk);
|
|
1651
|
+
} });
|
|
1652
|
+
return new Request(req.url, {
|
|
1653
|
+
method: req.method,
|
|
1654
|
+
headers: req.headers,
|
|
1655
|
+
body: body.pipeThrough(counter),
|
|
1656
|
+
duplex: "half"
|
|
1657
|
+
});
|
|
1658
|
+
}
|
|
1659
|
+
function cap413(max) {
|
|
1660
|
+
return new Response(JSON.stringify(errorEnvelope("PayloadTooLarge", `Body exceeds ${max} bytes`)), {
|
|
1661
|
+
status: 413,
|
|
1662
|
+
headers: { "content-type": "application/json" }
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
//#endregion
|
|
1666
|
+
//#region packages/adapter-node/src/middleware/dev-landing.ts
|
|
1667
|
+
/**
|
|
1668
|
+
* Opt-in dev landing-page short-circuit. Serves `GET /` with a
|
|
1669
|
+
* human-readable HTML page that links to the configured UI URL, and
|
|
1670
|
+
* `GET /favicon.ico` with 204 No Content. Bypasses verifier and
|
|
1671
|
+
* observability so it doesn't flood logs in dev.
|
|
1672
|
+
*
|
|
1673
|
+
* Other methods and other paths fall through to the cascade. Mounted
|
|
1674
|
+
* by {@link createApp} (in `app.ts`) ahead of `staticAssetsMiddleware`
|
|
1675
|
+
* so the dev short-circuit wins over any on-disk `index.html` /
|
|
1676
|
+
* `favicon.ico` that might live in `webRoot`.
|
|
1677
|
+
*
|
|
1678
|
+
* Mirrors the imperative dev-landing block in
|
|
1679
|
+
* `packages/adapter-node/src/server.ts` (which the hand-rolled
|
|
1680
|
+
* `handle()` bridge still uses until the bridge cutover).
|
|
1681
|
+
*/
|
|
1682
|
+
function devLandingMiddleware(opts) {
|
|
1683
|
+
return async (c, next) => {
|
|
1684
|
+
if (c.req.method !== "GET") return next();
|
|
1685
|
+
const path = new URL(c.req.url).pathname;
|
|
1686
|
+
if (path === "/") {
|
|
1687
|
+
const body = renderDevLanding(opts.dev);
|
|
1688
|
+
return new Response(body, {
|
|
1689
|
+
status: 200,
|
|
1690
|
+
headers: {
|
|
1691
|
+
"content-type": "text/html; charset=utf-8",
|
|
1692
|
+
"content-length": String(Buffer.byteLength(body))
|
|
1693
|
+
}
|
|
1694
|
+
});
|
|
1695
|
+
}
|
|
1696
|
+
if (path === "/favicon.ico") return new Response(null, { status: 204 });
|
|
1697
|
+
return next();
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
//#endregion
|
|
1701
|
+
//#region packages/adapter-node/src/middleware/static-assets.ts
|
|
1702
|
+
/**
|
|
1703
|
+
* Map a file extension to its `Content-Type`. The set is deliberately
|
|
1704
|
+
* small — every entry corresponds to something Vite or a typical SPA
|
|
1705
|
+
* pipeline actually emits. Unknown extensions fall back to
|
|
1706
|
+
* `application/octet-stream`, which keeps the browser from sniffing
|
|
1707
|
+
* untrusted bytes as HTML.
|
|
1708
|
+
*/
|
|
1709
|
+
const MIME_TYPES = {
|
|
1710
|
+
".html": "text/html; charset=utf-8",
|
|
1711
|
+
".js": "text/javascript; charset=utf-8",
|
|
1712
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
1713
|
+
".css": "text/css; charset=utf-8",
|
|
1714
|
+
".json": "application/json; charset=utf-8",
|
|
1715
|
+
".svg": "image/svg+xml",
|
|
1716
|
+
".png": "image/png",
|
|
1717
|
+
".jpg": "image/jpeg",
|
|
1718
|
+
".jpeg": "image/jpeg",
|
|
1719
|
+
".gif": "image/gif",
|
|
1720
|
+
".webp": "image/webp",
|
|
1721
|
+
".ico": "image/x-icon",
|
|
1722
|
+
".woff": "font/woff",
|
|
1723
|
+
".woff2": "font/woff2",
|
|
1724
|
+
".ttf": "font/ttf",
|
|
1725
|
+
".txt": "text/plain; charset=utf-8",
|
|
1726
|
+
".map": "application/json; charset=utf-8"
|
|
1727
|
+
};
|
|
1728
|
+
/**
|
|
1729
|
+
* Serve files from `webRoot` for GET/HEAD requests that miss `/v1/*`.
|
|
1730
|
+
*
|
|
1731
|
+
* HTML navigation (`Accept: text/html`) that misses an on-disk file
|
|
1732
|
+
* falls back to `<webRoot>/index.html` (SPA shell). Non-HTML misses
|
|
1733
|
+
* pass through `next()` so the cascade emits its 404 envelope.
|
|
1734
|
+
*
|
|
1735
|
+
* Path resolution rejects `..` segments and absolute paths so the
|
|
1736
|
+
* middleware can't escape `webRoot`. Pure `node:fs` + `node:path` —
|
|
1737
|
+
* no new dependency.
|
|
1738
|
+
*
|
|
1739
|
+
* The response body is built as
|
|
1740
|
+
* `new Response(Readable.toWeb(createReadStream(...)))`, keeping the
|
|
1741
|
+
* middleware Fetch-shaped so it composes cleanly with other Hono
|
|
1742
|
+
* middleware. The actual byte pump runs through
|
|
1743
|
+
* `@hono/node-server`'s response writer, which handles backpressure +
|
|
1744
|
+
* client-disconnect cleanly.
|
|
1745
|
+
*
|
|
1746
|
+
* Mirrors the imperative `serveStaticAsset` in
|
|
1747
|
+
* `packages/adapter-node/src/server.ts` (which the hand-rolled
|
|
1748
|
+
* `handle()` bridge still uses until T04 cuts over).
|
|
1749
|
+
*/
|
|
1750
|
+
function staticAssetsMiddleware(opts) {
|
|
1751
|
+
return async (c, next) => {
|
|
1752
|
+
const method = c.req.method;
|
|
1753
|
+
if (method !== "GET" && method !== "HEAD") return next();
|
|
1754
|
+
const path = new URL(c.req.url).pathname;
|
|
1755
|
+
if (path.startsWith("/v1/")) return next();
|
|
1756
|
+
const resolved = resolveUnderWebRoot(path, opts.webRoot);
|
|
1757
|
+
if (resolved === null) return next();
|
|
1758
|
+
const resolution = await resolveStaticTarget(resolved, opts.webRoot, c.req.header("accept"));
|
|
1759
|
+
if (resolution === null) return next();
|
|
1760
|
+
const { target, stats } = resolution;
|
|
1761
|
+
const contentType = MIME_TYPES[extname(target).toLowerCase()] ?? "application/octet-stream";
|
|
1762
|
+
const cacheControl = relative(opts.webRoot, target).split(sep).join("/").startsWith("assets/") && target !== resolve(opts.webRoot, "index.html") ? "public, max-age=3600" : "no-cache";
|
|
1763
|
+
const headers = {
|
|
1764
|
+
"content-type": contentType,
|
|
1765
|
+
"content-length": String(stats.size),
|
|
1766
|
+
"cache-control": cacheControl
|
|
1767
|
+
};
|
|
1768
|
+
if (method === "HEAD") return new Response(null, {
|
|
1769
|
+
status: 200,
|
|
1770
|
+
headers
|
|
1771
|
+
});
|
|
1772
|
+
const nodeWeb = Readable.toWeb(createReadStream(target));
|
|
1773
|
+
return new Response(nodeWeb, {
|
|
1774
|
+
status: 200,
|
|
1775
|
+
headers
|
|
1776
|
+
});
|
|
1777
|
+
};
|
|
1778
|
+
}
|
|
1779
|
+
/**
|
|
1780
|
+
* Resolve a request path under `webRoot` without allowing `..` escape
|
|
1781
|
+
* or absolute-segment hijacking. Returns the resolved absolute path on
|
|
1782
|
+
* success, or `null` when the request should fall through (traversal
|
|
1783
|
+
* attempt, NUL byte, malformed URL encoding).
|
|
1784
|
+
*/
|
|
1785
|
+
function resolveUnderWebRoot(reqPath, webRoot) {
|
|
1786
|
+
let relative$1 = reqPath;
|
|
1787
|
+
if (relative$1 === "" || relative$1 === "/") relative$1 = "/index.html";
|
|
1788
|
+
else if (relative$1.endsWith("/")) relative$1 = `${relative$1}index.html`;
|
|
1789
|
+
if (relative$1.includes("\0")) return null;
|
|
1790
|
+
const segments = [];
|
|
1791
|
+
for (const raw of relative$1.split("/")) {
|
|
1792
|
+
if (raw === "") continue;
|
|
1793
|
+
let decoded;
|
|
1794
|
+
try {
|
|
1795
|
+
decoded = decodeURIComponent(raw);
|
|
1796
|
+
} catch {
|
|
1797
|
+
return null;
|
|
1798
|
+
}
|
|
1799
|
+
if (decoded === "" || decoded === ".") continue;
|
|
1800
|
+
if (decoded === "..") return null;
|
|
1801
|
+
if (decoded.includes("\0")) return null;
|
|
1802
|
+
if (decoded.includes("/") || decoded.includes("\\")) return null;
|
|
1803
|
+
segments.push(decoded);
|
|
1804
|
+
}
|
|
1805
|
+
const resolved = resolve(webRoot, ...segments);
|
|
1806
|
+
const rel = relative(webRoot, resolved);
|
|
1807
|
+
if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) return null;
|
|
1808
|
+
return resolved;
|
|
1809
|
+
}
|
|
1810
|
+
/**
|
|
1811
|
+
* Determine whether the request should fall back to `index.html` on a
|
|
1812
|
+
* filesystem miss. Browsers send `Accept: text/html,...` for SPA
|
|
1813
|
+
* navigations; programmatic `fetch()` calls for missing JSON / image
|
|
1814
|
+
* assets do not, and they get the kernel's 404 envelope instead.
|
|
1815
|
+
*/
|
|
1816
|
+
function wantsHtmlFallback(accept) {
|
|
1817
|
+
if (typeof accept !== "string") return false;
|
|
1818
|
+
return accept.includes("text/html");
|
|
1819
|
+
}
|
|
1820
|
+
async function resolveStaticTarget(resolved, webRoot, accept) {
|
|
1821
|
+
const primary = await statFile(resolved);
|
|
1822
|
+
if (primary !== null) return {
|
|
1823
|
+
target: resolved,
|
|
1824
|
+
stats: primary
|
|
1825
|
+
};
|
|
1826
|
+
if (!wantsHtmlFallback(accept)) return null;
|
|
1827
|
+
const indexPath = resolve(webRoot, "index.html");
|
|
1828
|
+
const fallback = await statFile(indexPath);
|
|
1829
|
+
if (fallback === null) return null;
|
|
1830
|
+
return {
|
|
1831
|
+
target: indexPath,
|
|
1832
|
+
stats: fallback
|
|
1833
|
+
};
|
|
1834
|
+
}
|
|
1835
|
+
/**
|
|
1836
|
+
* `fs.stat` that returns `null` for the missing-file cases that this
|
|
1837
|
+
* handler treats as a fall-through (ENOENT / ENOTDIR / non-file).
|
|
1838
|
+
* Other errors (EACCES, EIO, ...) propagate.
|
|
1839
|
+
*/
|
|
1840
|
+
async function statFile(target) {
|
|
1841
|
+
try {
|
|
1842
|
+
const stats = await stat(target);
|
|
1843
|
+
return stats.isFile() ? stats : null;
|
|
1844
|
+
} catch (error) {
|
|
1845
|
+
const code = error.code;
|
|
1846
|
+
if (code === "ENOENT" || code === "ENOTDIR") return null;
|
|
1847
|
+
throw error;
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
//#endregion
|
|
1851
|
+
//#region packages/adapter-node/src/logger-pretty.ts
|
|
1852
|
+
var import_picocolors_browser = require_picocolors_browser();
|
|
1853
|
+
/**
|
|
1854
|
+
* Metric keys the pretty sink reads off the canonical-line record.
|
|
1855
|
+
* These names match `RequestScopedMetricsRecorder.summarize()` output
|
|
1856
|
+
* in `packages/server/src/observability/recorder.ts`. If the recorder
|
|
1857
|
+
* renames a key, update both sides here.
|
|
1858
|
+
*/
|
|
1859
|
+
const CANONICAL_KEYS = {
|
|
1860
|
+
classA: "db.storage.class_a_ops_total",
|
|
1861
|
+
classB: "db.storage.class_b_ops_total",
|
|
1862
|
+
wamp: "db.write.class_a_ops_per_logical_write_sum",
|
|
1863
|
+
put412: "db.r2.put.412_total",
|
|
1864
|
+
put429: "db.r2.put.429_total",
|
|
1865
|
+
cacheStatus: "cache_status"
|
|
1866
|
+
};
|
|
1867
|
+
/**
|
|
1868
|
+
* Fixed-width column sizes for the pretty sink's HTTP line.
|
|
1869
|
+
* Local to the renderer — these are presentation defaults, not
|
|
1870
|
+
* protocol invariants, so they don't belong in `@baerly/protocol`.
|
|
1871
|
+
*/
|
|
1872
|
+
const METHOD_W = 6;
|
|
1873
|
+
const PATH_W = 28;
|
|
1874
|
+
const pickProp = (props, key) => Object.prototype.hasOwnProperty.call(props, key) ? props[key] : void 0;
|
|
1875
|
+
const numProp = (props, key) => {
|
|
1876
|
+
const v = pickProp(props, key);
|
|
1877
|
+
return typeof v === "number" ? v : void 0;
|
|
1878
|
+
};
|
|
1879
|
+
const colorStatus = (statusStr, status, plain, pc) => {
|
|
1880
|
+
if (plain || status === void 0) return statusStr;
|
|
1881
|
+
if (status >= 500) return pc.red(statusStr);
|
|
1882
|
+
if (status >= 400) return pc.yellow(statusStr);
|
|
1883
|
+
if (status >= 300) return pc.cyan(statusStr);
|
|
1884
|
+
return pc.dim(statusStr);
|
|
1885
|
+
};
|
|
1886
|
+
const renderCanonical = (record, pc, plain) => {
|
|
1887
|
+
const props = record.properties;
|
|
1888
|
+
const ts = new Date(record.timestamp).toISOString().slice(11, 19);
|
|
1889
|
+
const reqId = String(pickProp(props, "request_id") ?? "").slice(0, 8);
|
|
1890
|
+
const duration = numProp(props, "duration_ms") ?? 0;
|
|
1891
|
+
const durationStr = `${Math.round(duration)}ms`.padStart(5);
|
|
1892
|
+
const status = numProp(props, "status");
|
|
1893
|
+
const method = typeof pickProp(props, "method") === "string" ? String(pickProp(props, "method")) : "";
|
|
1894
|
+
const path = typeof pickProp(props, "path") === "string" ? String(pickProp(props, "path")) : "";
|
|
1895
|
+
const prefix = `${method.padEnd(METHOD_W)}${path.length > PATH_W ? `${path.slice(0, PATH_W - 1)}…` : path.padEnd(PATH_W)} ${colorStatus(status === void 0 ? " " : String(status), status, plain, pc)} ${durationStr}`;
|
|
1896
|
+
const tail = [];
|
|
1897
|
+
if (reqId) tail.push(`req=${reqId}`);
|
|
1898
|
+
const classA = numProp(props, CANONICAL_KEYS.classA);
|
|
1899
|
+
const classB = numProp(props, CANONICAL_KEYS.classB);
|
|
1900
|
+
if (classA !== void 0) tail.push(`class_a=${classA}`);
|
|
1901
|
+
if (classB !== void 0) tail.push(`class_b=${classB}`);
|
|
1902
|
+
const wamp = numProp(props, CANONICAL_KEYS.wamp);
|
|
1903
|
+
if (wamp !== void 0) tail.push(`wamp=${wamp}`);
|
|
1904
|
+
const c412 = numProp(props, CANONICAL_KEYS.put412);
|
|
1905
|
+
if (c412 !== void 0 && c412 > 0) tail.push(`412=${c412}`);
|
|
1906
|
+
const c429 = numProp(props, CANONICAL_KEYS.put429);
|
|
1907
|
+
if (c429 !== void 0 && c429 > 0) tail.push(`429=${c429}`);
|
|
1908
|
+
const cacheStatus = pickProp(props, CANONICAL_KEYS.cacheStatus);
|
|
1909
|
+
if (typeof cacheStatus === "string") tail.push(`cache=${cacheStatus}`);
|
|
1910
|
+
if (status !== void 0 && status >= 400) {
|
|
1911
|
+
const outcome = pickProp(props, "outcome");
|
|
1912
|
+
if (typeof outcome === "string") tail.push(`outcome=${outcome}`);
|
|
1913
|
+
}
|
|
1914
|
+
const tailStr = tail.length ? ` ${tail.join(" ")}` : "";
|
|
1915
|
+
return `${plain ? `${ts} ` : `${pc.dim(ts)} `}${prefix}${tailStr}`;
|
|
1916
|
+
};
|
|
1917
|
+
const isCanonicalRecord = (record) => record.message.length === 1 && record.message[0] === "canonical";
|
|
1918
|
+
const isPlainEnv = () => {
|
|
1919
|
+
const proc = globalThis.process;
|
|
1920
|
+
return proc?.stdout?.isTTY !== true || proc?.env?.["CI"] !== void 0;
|
|
1921
|
+
};
|
|
1922
|
+
/**
|
|
1923
|
+
* Built-in pretty sink. Renders canonical-line records (the
|
|
1924
|
+
* single-emit/unit-of-work records produced by `flushCanonicalLine`
|
|
1925
|
+
* in `@baerly/server/observability`) in a column-aligned cost-aware
|
|
1926
|
+
* format intended for local dev; falls back to a generic
|
|
1927
|
+
* `<ts> <LEVEL> <category> <msg> <jsonProps>` layout for every
|
|
1928
|
+
* other record (warn-line `verifier_rejected`, debug storage
|
|
1929
|
+
* emits, etc.).
|
|
1930
|
+
*
|
|
1931
|
+
* Color is enabled when stderr is a TTY and `CI` is unset. Under
|
|
1932
|
+
* vitest, stderr is non-TTY so color is off — tests can assert
|
|
1933
|
+
* substring matches without stripping ANSI escapes.
|
|
1934
|
+
*/
|
|
1935
|
+
const prettyConsoleSink = () => {
|
|
1936
|
+
const plain = isPlainEnv();
|
|
1937
|
+
const pc = (0, import_picocolors_browser.createColors)(!plain);
|
|
1938
|
+
return (record) => {
|
|
1939
|
+
if (isCanonicalRecord(record)) {
|
|
1940
|
+
console.log(renderCanonical(record, pc, plain));
|
|
1941
|
+
return;
|
|
1942
|
+
}
|
|
1943
|
+
const ts = new Date(record.timestamp).toISOString();
|
|
1944
|
+
const cat = record.category.join(".");
|
|
1945
|
+
const msg = record.message.map((m) => typeof m === "string" ? m : JSON.stringify(m)).join("");
|
|
1946
|
+
const props = Object.keys(record.properties).length ? ` ${JSON.stringify(record.properties)}` : "";
|
|
1947
|
+
console.log(`${ts} ${record.level.toUpperCase()} ${cat} ${msg}${props}`);
|
|
1948
|
+
};
|
|
1949
|
+
};
|
|
1950
|
+
//#endregion
|
|
1951
|
+
//#region packages/adapter-node/src/server.ts
|
|
1952
|
+
/**
|
|
1953
|
+
* Assemble the per-request {@link MaintenanceDispatch} for a Node host.
|
|
1954
|
+
*
|
|
1955
|
+
* baerly maintains IN-BAND: the writer reads
|
|
1956
|
+
* `getCurrentContext()?.maintenance` at its post-commit dispatch point and
|
|
1957
|
+
* runs one bounded compact + GC slice on the (rare) write that crosses a
|
|
1958
|
+
* maintenance trigger. Reads stay pure — they never tick. There is no
|
|
1959
|
+
* `setInterval`, no cron, no operator-installed scheduler: the kernel
|
|
1960
|
+
* maintains itself on a bare bucket with zero operator infrastructure.
|
|
1961
|
+
*
|
|
1962
|
+
* On Node v1 maintenance runs INLINE on the commit path (no
|
|
1963
|
+
* `dispatch` override — serverful Node has no `waitUntil`, and inline is
|
|
1964
|
+
* deterministic + correct here), so this returns no `dispatch` field;
|
|
1965
|
+
* the writer falls back to its inline-awaited default dispatch.
|
|
1966
|
+
*
|
|
1967
|
+
* The caps (`options`) are a MODERATE multiple of the CF-free defaults —
|
|
1968
|
+
* Node has no Cloudflare subrequest wall, but because v1 runs inline the
|
|
1969
|
+
* per-pass work is still BOUNDED by worst-case single-write added
|
|
1970
|
+
* latency, not unbounded. We thread `phasesPerTick: "both"` (a capable
|
|
1971
|
+
* host can fold AND GC in one tick) plus the Node-tier `WRITE_TICK_*`
|
|
1972
|
+
* overrides from `@baerly/protocol`'s `NODE_MAINTENANCE_*` constants
|
|
1973
|
+
* (10× CF-free, with a shorter GC interval so the sweep budget keeps up).
|
|
1974
|
+
*
|
|
1975
|
+
* The two ops-plane env vars are read here (per call) so a `vi.stubEnv`
|
|
1976
|
+
* in tests — and a real process env in production — is observed:
|
|
1977
|
+
*
|
|
1978
|
+
* - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (the snapshot
|
|
1979
|
+
* ceiling `C`). Parsed as a number; ignored when unset / NaN.
|
|
1980
|
+
* - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Truthy
|
|
1981
|
+
* when set to a non-empty value other than `"0"` / `"false"`.
|
|
1982
|
+
*
|
|
1983
|
+
* `readEnv` defaults to `process.env`; the parameter exists for direct
|
|
1984
|
+
* unit coverage.
|
|
1985
|
+
*/
|
|
1986
|
+
const nodeMaintenanceDispatch = (readEnv = (k) => process.env[k]) => {
|
|
1987
|
+
const { maxFoldBytes, disabled } = parseMaintenanceEnv(readEnv);
|
|
1988
|
+
return {
|
|
1989
|
+
...disabled && { disabled: true },
|
|
1990
|
+
...maxFoldBytes !== void 0 && { maxFoldBytes },
|
|
1991
|
+
options: {
|
|
1992
|
+
phasesPerTick: "both",
|
|
1993
|
+
profile: MAINTENANCE_PROFILE_NODE
|
|
1994
|
+
}
|
|
1995
|
+
};
|
|
1996
|
+
};
|
|
1997
|
+
/**
|
|
1998
|
+
* Build a `(req: Request) => Promise<Response>` handler that runs the
|
|
1999
|
+
* baerly `/v1/*` cascade: healthz short-circuit → observability context
|
|
2000
|
+
* → verifier → `Db.create` → `createRouter({db}).fetch(req)` →
|
|
2001
|
+
* canonical-line flush. The handler is host-agnostic; mount it under
|
|
2002
|
+
* `/v1/*` in your Fetch framework.
|
|
2003
|
+
*
|
|
2004
|
+
* Non-`/v1/*` paths fall through to the Hono router, which renders the
|
|
2005
|
+
* kernel's 404 envelope. To compose static-asset or dev-landing
|
|
2006
|
+
* handlers, dispatch those upstream of this factory — see the
|
|
2007
|
+
* internal Hono-app factory in `./app.ts` for the production composition.
|
|
2008
|
+
*
|
|
2009
|
+
* @internal — public consumers reach this via `baerlyNode` from
|
|
2010
|
+
* `./baerly-node.ts`. Exported for intra-package re-use and direct unit
|
|
2011
|
+
* coverage in `server.test.ts`.
|
|
2012
|
+
*/
|
|
2013
|
+
function createFetchHandler(opts) {
|
|
2014
|
+
configureObservability(resolveDefaultSink(opts.observability ?? {}));
|
|
2015
|
+
const wrappedStorage = observableStorage(opts.storage);
|
|
2016
|
+
return async (request) => {
|
|
2017
|
+
const path = new URL(request.url).pathname;
|
|
2018
|
+
if (request.method === "GET" && path === "/v1/healthz") return new Response(JSON.stringify({ ok: true }), {
|
|
2019
|
+
status: 200,
|
|
2020
|
+
headers: { "content-type": "application/json" }
|
|
2021
|
+
});
|
|
2022
|
+
if (request.method === "GET" && path === "/v1/spec") return handleSpecRequest(request, async () => ({
|
|
2023
|
+
verifier: opts.verifier,
|
|
2024
|
+
config: opts.config
|
|
2025
|
+
}));
|
|
2026
|
+
const obsCtx = createObservabilityContext({
|
|
2027
|
+
request_id: request.headers.get("x-request-id") ?? crypto.randomUUID(),
|
|
2028
|
+
maintenance: nodeMaintenanceDispatch()
|
|
2029
|
+
});
|
|
2030
|
+
const result = await opts.verifier(request);
|
|
2031
|
+
if (result === null) return await runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, request));
|
|
2032
|
+
return await runWithContext(obsCtx, async () => {
|
|
2033
|
+
let outboundStatus = 500;
|
|
2034
|
+
let caughtError;
|
|
2035
|
+
let response;
|
|
2036
|
+
try {
|
|
2037
|
+
response = await createRouter({
|
|
2038
|
+
db: Db.create({
|
|
2039
|
+
storage: wrappedStorage,
|
|
2040
|
+
app: opts.app,
|
|
2041
|
+
tenant: result.tenantPrefix,
|
|
2042
|
+
config: opts.config
|
|
2043
|
+
}),
|
|
2044
|
+
...opts.sinceTimeoutMs !== void 0 && { sinceTimeoutMs: opts.sinceTimeoutMs },
|
|
2045
|
+
...opts.sincePollIntervalMs !== void 0 && { sincePollIntervalMs: opts.sincePollIntervalMs }
|
|
2046
|
+
}).fetch(request);
|
|
2047
|
+
outboundStatus = response.status;
|
|
2048
|
+
} catch (error) {
|
|
2049
|
+
caughtError = error;
|
|
2050
|
+
const { status, envelope } = mapError(error);
|
|
2051
|
+
outboundStatus = status;
|
|
2052
|
+
response = new Response(JSON.stringify(envelope), {
|
|
2053
|
+
status,
|
|
2054
|
+
headers: { "content-type": "application/json" }
|
|
2055
|
+
});
|
|
2056
|
+
} finally {
|
|
2057
|
+
flushCanonicalLine(obsCtx, obsCtx.recorder, {
|
|
2058
|
+
unit: "http",
|
|
2059
|
+
status: outboundStatus,
|
|
2060
|
+
outcome: deriveOutcome(request.method, outboundStatus, caughtError),
|
|
2061
|
+
...caughtError !== void 0 && { error: caughtError },
|
|
2062
|
+
extra: {
|
|
2063
|
+
method: request.method,
|
|
2064
|
+
path
|
|
2065
|
+
}
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
return response;
|
|
2069
|
+
});
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
/**
|
|
2073
|
+
* Auto-pick the default sink when the caller passed an
|
|
2074
|
+
* {@link ObservabilityConfig} without a `sink` field. On a TTY
|
|
2075
|
+
* (developer terminals) we prefer pretty output; otherwise JSON
|
|
2076
|
+
* (production hosts pipe stdout to a log aggregator).
|
|
2077
|
+
*
|
|
2078
|
+
* Returns a new config with `sink` defaulted; if the caller already
|
|
2079
|
+
* supplied a `sink` (function or shorthand string) we pass the
|
|
2080
|
+
* config through verbatim. Either way the caller's `level` (when
|
|
2081
|
+
* set) reaches LogTape unchanged.
|
|
2082
|
+
*
|
|
2083
|
+
* Exported for the test suite — the TTY check is otherwise a pure
|
|
2084
|
+
* read of `process.stdout.isTTY` and a default lookup, neither
|
|
2085
|
+
* worth a black-box round-trip.
|
|
2086
|
+
*/
|
|
2087
|
+
const resolveDefaultSink = (config) => {
|
|
2088
|
+
if (config.sink !== void 0) return config;
|
|
2089
|
+
const isTty = Boolean(process.stdout.isTTY);
|
|
2090
|
+
return {
|
|
2091
|
+
...config,
|
|
2092
|
+
sink: isTty ? prettyConsoleSink() : "console-json"
|
|
2093
|
+
};
|
|
2094
|
+
};
|
|
2095
|
+
//#endregion
|
|
2096
|
+
//#region packages/adapter-node/src/app.ts
|
|
2097
|
+
/**
|
|
2098
|
+
* Build a Hono app that serves the baerly cascade plus Node-host
|
|
2099
|
+
* middleware (dev-landing when `dev` is set, then static-assets when
|
|
2100
|
+
* `webRoot` is set, then the cascade).
|
|
2101
|
+
*
|
|
2102
|
+
* The returned app's `.fetch` is `(req: Request) => Promise<Response>`
|
|
2103
|
+
* — feed it to `@hono/node-server`'s `serve({ fetch })`, mount under
|
|
2104
|
+
* another Hono app via `app.route(prefix, baerlyApp)`, or convert
|
|
2105
|
+
* to a Node listener via `getRequestListener(baerlyApp.fetch)`.
|
|
2106
|
+
*
|
|
2107
|
+
* Body size enforcement: every non-`GET`/`HEAD`/`OPTIONS` request
|
|
2108
|
+
* passes through {@link applyBodyCap} before reaching the cascade.
|
|
2109
|
+
* The helper short-circuits with a 413 envelope when `Content-
|
|
2110
|
+
* Length` advertises an over-cap body, and otherwise wraps
|
|
2111
|
+
* `req.body` with a counting `TransformStream` that errors with
|
|
2112
|
+
* `BaerlyError{code:"PayloadTooLarge"}` once the running byte
|
|
2113
|
+
* count exceeds {@link MAX_BODY_BYTES}. On cap-trip in either
|
|
2114
|
+
* path the upstream `IncomingMessage` is drained (`resume()`) so
|
|
2115
|
+
* the client's body write completes and the 413 reaches it
|
|
2116
|
+
* cleanly. The kernel router's defence-in-depth
|
|
2117
|
+
* (`packages/server/src/http/router.ts:464-501`) remains the
|
|
2118
|
+
* backstop for hosts without an `incoming` binding.
|
|
2119
|
+
*/
|
|
2120
|
+
function createApp(opts) {
|
|
2121
|
+
const fetchHandler = createFetchHandler(opts);
|
|
2122
|
+
const app = new Hono();
|
|
2123
|
+
if (opts.dev !== void 0) app.use("*", devLandingMiddleware({ dev: opts.dev }));
|
|
2124
|
+
if (opts.webRoot !== void 0) app.use("*", staticAssetsMiddleware({ webRoot: opts.webRoot }));
|
|
2125
|
+
app.all("*", async (c) => {
|
|
2126
|
+
const capped = applyBodyCap(c.req.raw, c.env, MAX_BODY_BYTES);
|
|
2127
|
+
if (capped instanceof Response) return capped;
|
|
2128
|
+
return fetchHandler(capped);
|
|
2129
|
+
});
|
|
2130
|
+
return app;
|
|
2131
|
+
}
|
|
2132
|
+
//#endregion
|
|
2133
|
+
//#region packages/adapter-node/src/baerly-node.ts
|
|
2134
|
+
/**
|
|
2135
|
+
* Mount baerly on `node:http` with one call. Mirrors `baerlyWorker`
|
|
2136
|
+
* from `@baerly/adapter-cloudflare`.
|
|
2137
|
+
*
|
|
2138
|
+
* Composes:
|
|
2139
|
+
* - {@link createApp} → exposed as `handle.fetch` for in-process
|
|
2140
|
+
* embedding; wrapped in `@hono/node-server.serve({ fetch, createServer })`
|
|
2141
|
+
* lazily when `listen()` is called.
|
|
2142
|
+
* - SIGTERM + SIGINT handlers installed on `listen()` that call
|
|
2143
|
+
* `close()` and `process.exit(0)`. On any error during close,
|
|
2144
|
+
* `process.exit(1)`.
|
|
2145
|
+
*
|
|
2146
|
+
* **Maintenance is in-band, not scheduled.** There is no `setInterval`,
|
|
2147
|
+
* no cron, and no `maintenance:` option: the kernel maintains itself on
|
|
2148
|
+
* a bare bucket with zero operator infrastructure. Compaction + GC run
|
|
2149
|
+
* INLINE on the (rare) write that crosses a maintenance trigger —
|
|
2150
|
+
* `createFetchHandler` threads a Node-tier `MaintenanceDispatch`
|
|
2151
|
+
* onto the per-request observability context, which the writer reads at
|
|
2152
|
+
* its post-commit dispatch point. Reads never tick. Tune via the
|
|
2153
|
+
* `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` / `BAERLY_MAINTENANCE_DISABLE`
|
|
2154
|
+
* env vars; for an explicit out-of-band sweep, call
|
|
2155
|
+
* `runScheduledMaintenance` from `@gusto/baerly-storage` directly.
|
|
2156
|
+
*
|
|
2157
|
+
* @example
|
|
2158
|
+
* ```ts
|
|
2159
|
+
* import { baerlyNode, s3Storage } from "@gusto/baerly-storage/node";
|
|
2160
|
+
* import config from "./baerly.config.ts";
|
|
2161
|
+
*
|
|
2162
|
+
* const handle = baerlyNode({
|
|
2163
|
+
* config,
|
|
2164
|
+
* storage: s3Storage({
|
|
2165
|
+
* region: "us-east-1",
|
|
2166
|
+
* bucket: process.env["BUCKET"]!,
|
|
2167
|
+
* credentials: {
|
|
2168
|
+
* accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
|
|
2169
|
+
* secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
|
|
2170
|
+
* },
|
|
2171
|
+
* }),
|
|
2172
|
+
* // No verifier needed when config.auth is "none" or "shared-secret".
|
|
2173
|
+
* webRoot: "./dist/client",
|
|
2174
|
+
* });
|
|
2175
|
+
* await handle.listen(Number(process.env["PORT"] ?? 8080));
|
|
2176
|
+
* ```
|
|
2177
|
+
*/
|
|
2178
|
+
function baerlyNode(opts) {
|
|
2179
|
+
const verifier = resolveVerifier({
|
|
2180
|
+
factoryVerifier: opts.verifier,
|
|
2181
|
+
config: opts.config,
|
|
2182
|
+
readEnv: (k) => process.env[k]
|
|
2183
|
+
});
|
|
2184
|
+
if (opts.verifier === void 0 && opts.config.auth === "none") console.log(`[baerly] auth=none — all requests resolve to tenant=${JSON.stringify(opts.config.tenant)}`);
|
|
2185
|
+
const app = createApp({
|
|
2186
|
+
app: opts.config.app,
|
|
2187
|
+
storage: opts.storage,
|
|
2188
|
+
verifier,
|
|
2189
|
+
config: opts.config,
|
|
2190
|
+
...opts.observability !== void 0 && { observability: opts.observability },
|
|
2191
|
+
...opts.dev !== void 0 && { dev: opts.dev },
|
|
2192
|
+
...opts.webRoot !== void 0 && { webRoot: opts.webRoot },
|
|
2193
|
+
...opts.sinceTimeoutMs !== void 0 && { sinceTimeoutMs: opts.sinceTimeoutMs },
|
|
2194
|
+
...opts.sincePollIntervalMs !== void 0 && { sincePollIntervalMs: opts.sincePollIntervalMs }
|
|
2195
|
+
});
|
|
2196
|
+
let server;
|
|
2197
|
+
let signalHandler;
|
|
2198
|
+
let closed = false;
|
|
2199
|
+
const close = async () => {
|
|
2200
|
+
if (closed) return;
|
|
2201
|
+
closed = true;
|
|
2202
|
+
if (signalHandler !== void 0) {
|
|
2203
|
+
process.off("SIGTERM", signalHandler);
|
|
2204
|
+
process.off("SIGINT", signalHandler);
|
|
2205
|
+
signalHandler = void 0;
|
|
2206
|
+
}
|
|
2207
|
+
await new Promise((resolve, reject) => {
|
|
2208
|
+
if (server === void 0) {
|
|
2209
|
+
resolve();
|
|
2210
|
+
return;
|
|
2211
|
+
}
|
|
2212
|
+
if (!server.listening) {
|
|
2213
|
+
resolve();
|
|
2214
|
+
return;
|
|
2215
|
+
}
|
|
2216
|
+
server.close((err) => {
|
|
2217
|
+
if (err) reject(err);
|
|
2218
|
+
else resolve();
|
|
2219
|
+
});
|
|
2220
|
+
});
|
|
2221
|
+
};
|
|
2222
|
+
const listen = async (port) => {
|
|
2223
|
+
server = serve({
|
|
2224
|
+
fetch: app.fetch,
|
|
2225
|
+
port: 0,
|
|
2226
|
+
hostname: "0.0.0.0",
|
|
2227
|
+
createServer
|
|
2228
|
+
});
|
|
2229
|
+
const httpServer = server;
|
|
2230
|
+
await new Promise((resolve, reject) => {
|
|
2231
|
+
const onError = (err) => {
|
|
2232
|
+
httpServer.off("listening", onListening);
|
|
2233
|
+
httpServer.off("close", onClose);
|
|
2234
|
+
reject(err);
|
|
2235
|
+
};
|
|
2236
|
+
const onListening = () => {
|
|
2237
|
+
httpServer.off("error", onError);
|
|
2238
|
+
httpServer.off("close", onClose);
|
|
2239
|
+
resolve();
|
|
2240
|
+
};
|
|
2241
|
+
const onClose = () => {
|
|
2242
|
+
httpServer.off("error", onError);
|
|
2243
|
+
httpServer.off("listening", onListening);
|
|
2244
|
+
resolve();
|
|
2245
|
+
};
|
|
2246
|
+
httpServer.once("error", onError);
|
|
2247
|
+
httpServer.once("listening", onListening);
|
|
2248
|
+
httpServer.once("close", onClose);
|
|
2249
|
+
httpServer.listen(port);
|
|
2250
|
+
});
|
|
2251
|
+
if (closed) return;
|
|
2252
|
+
signalHandler = (sig) => {
|
|
2253
|
+
console.log(`Received ${sig}; closing baerlyNode server`);
|
|
2254
|
+
close().then(() => process.exit(0)).catch((error) => {
|
|
2255
|
+
console.error("baerlyNode close failed", error);
|
|
2256
|
+
process.exit(1);
|
|
2257
|
+
});
|
|
2258
|
+
};
|
|
2259
|
+
process.on("SIGTERM", signalHandler);
|
|
2260
|
+
process.on("SIGINT", signalHandler);
|
|
2261
|
+
};
|
|
2262
|
+
return {
|
|
2263
|
+
fetch: app.fetch,
|
|
2264
|
+
listen,
|
|
2265
|
+
close
|
|
2266
|
+
};
|
|
2267
|
+
}
|
|
2268
|
+
//#endregion
|
|
2269
|
+
export { fromEksPodIdentity as a, localFsStorage as c, r2Storage as d, s3Storage as f, fromWebIdentity as i, gcsStorage as l, getRequestListener as n, assertStorageReachable as o, fromEks as r, resolveStorageFromEnv as s, baerlyNode as t, minioStorage as u };
|
|
2270
|
+
|
|
2271
|
+
//# sourceMappingURL=src-BG20LZs7.js.map
|