@agentbadge/circle-payments 0.1.19 → 0.1.25

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.
@@ -0,0 +1,134 @@
1
+ import { getAddress, isAddress } from "viem";
2
+ export class TermsUncomparableError extends Error {
3
+ detail;
4
+ constructor(detail) {
5
+ super(`terms_uncomparable: ${detail}`);
6
+ this.name = "TermsUncomparableError";
7
+ this.detail = detail;
8
+ }
9
+ }
10
+ const CAIP2_NAMESPACE_RE = /^[-a-z0-9]{3,8}$/i;
11
+ const CAIP2_REFERENCE_RE = /^[-_a-zA-Z0-9]{1,64}$/;
12
+ export function parseCaip2(network) {
13
+ const idx = network.indexOf(":");
14
+ if (idx <= 0) {
15
+ throw new TermsUncomparableError(`network ${JSON.stringify(network)} is not CAIP-2`);
16
+ }
17
+ const namespace = network.slice(0, idx).toLowerCase();
18
+ const reference = network.slice(idx + 1);
19
+ if (!CAIP2_NAMESPACE_RE.test(namespace) || !CAIP2_REFERENCE_RE.test(reference)) {
20
+ throw new TermsUncomparableError(`network ${JSON.stringify(network)} is not a valid CAIP-2 id`);
21
+ }
22
+ return { namespace, reference };
23
+ }
24
+ export function normalizeNetwork(network) {
25
+ const { namespace, reference } = parseCaip2(network);
26
+ if (namespace === "eip155") {
27
+ if (!/^\d+$/.test(reference)) {
28
+ throw new TermsUncomparableError(`eip155 reference ${JSON.stringify(reference)} is not numeric`);
29
+ }
30
+ return `eip155:${BigInt(reference).toString()}`;
31
+ }
32
+ return `${namespace}:${reference}`;
33
+ }
34
+ const EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
35
+ const BASE58_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
36
+ export function normalizeAddress(addr, network) {
37
+ const { namespace } = parseCaip2(network);
38
+ const trimmed = addr.trim();
39
+ if (namespace === "eip155") {
40
+ if (!EVM_ADDRESS_RE.test(trimmed)) {
41
+ throw new TermsUncomparableError(`payTo/asset ${JSON.stringify(addr)} is not an EVM address`);
42
+ }
43
+ const body = trimmed.slice(2);
44
+ const mixedCase = /[a-f]/.test(body) && /[A-F]/.test(body);
45
+ if (mixedCase && !isAddress(trimmed)) {
46
+ throw new TermsUncomparableError(`EVM address ${JSON.stringify(addr)} fails EIP-55 checksum`);
47
+ }
48
+ try {
49
+ return getAddress(trimmed).toLowerCase();
50
+ }
51
+ catch {
52
+ throw new TermsUncomparableError(`EVM address ${JSON.stringify(addr)} fails EIP-55 checksum`);
53
+ }
54
+ }
55
+ if (namespace === "solana") {
56
+ if (!BASE58_ADDRESS_RE.test(trimmed)) {
57
+ throw new TermsUncomparableError(`payTo/asset ${JSON.stringify(addr)} is not a Base58 address`);
58
+ }
59
+ return trimmed;
60
+ }
61
+ throw new TermsUncomparableError(`no address rule for network namespace ${JSON.stringify(namespace)}`);
62
+ }
63
+ export function normalizeAmount(amount) {
64
+ const t = amount.trim();
65
+ if (!/^\d+$/.test(t)) {
66
+ throw new TermsUncomparableError(`amount ${JSON.stringify(amount)} is not an atomic integer string`);
67
+ }
68
+ return BigInt(t).toString();
69
+ }
70
+ export function normalizeScheme(scheme) {
71
+ const t = scheme.trim().toLowerCase();
72
+ if (t === "") {
73
+ throw new TermsUncomparableError("scheme is empty");
74
+ }
75
+ return t;
76
+ }
77
+ export function normalizeTerms(terms) {
78
+ const network = normalizeNetwork(terms.network);
79
+ return {
80
+ payTo: normalizeAddress(terms.payTo, network),
81
+ asset: normalizeAddress(terms.asset, network),
82
+ amount: normalizeAmount(terms.amount),
83
+ network,
84
+ scheme: normalizeScheme(terms.scheme),
85
+ };
86
+ }
87
+ const TERMS_FIELDS = ["payTo", "asset", "amount", "network", "scheme"];
88
+ export function matchTerms(verified, offered) {
89
+ if (verified == null) {
90
+ return { result: "unmeasured" };
91
+ }
92
+ let v;
93
+ let o;
94
+ try {
95
+ v = normalizeTerms(verified);
96
+ }
97
+ catch (e) {
98
+ return {
99
+ result: "uncomparable",
100
+ reason: `verified terms: ${e instanceof Error ? e.message : String(e)}`,
101
+ };
102
+ }
103
+ try {
104
+ o = normalizeTerms(offered);
105
+ }
106
+ catch (e) {
107
+ return {
108
+ result: "uncomparable",
109
+ reason: `offered terms: ${e instanceof Error ? e.message : String(e)}`,
110
+ };
111
+ }
112
+ const diff = {};
113
+ for (const f of TERMS_FIELDS) {
114
+ if (v[f] !== o[f]) {
115
+ diff[f] = { verified: v[f], offered: o[f] };
116
+ }
117
+ }
118
+ return Object.keys(diff).length === 0
119
+ ? { result: "match" }
120
+ : { result: "mismatch", diff };
121
+ }
122
+ export function offeredTermsFromRequirements(req) {
123
+ const amount = req.amount ?? req.maxAmountRequired;
124
+ if (amount === undefined) {
125
+ throw new TermsUncomparableError("offer has neither amount nor maxAmountRequired");
126
+ }
127
+ return {
128
+ payTo: req.payTo,
129
+ asset: req.asset,
130
+ amount,
131
+ network: req.network,
132
+ scheme: req.scheme,
133
+ };
134
+ }
@@ -0,0 +1,89 @@
1
+ export type Vet402Verdict = "ALLOW" | "WARN" | "BLOCK";
2
+ export type CounterpartyVerdict = "allow" | "hold" | "deny" | "unavailable";
3
+ export type CounterpartyReasonCode = "allowed" | "terms_mismatch" | "terms_uncomparable" | "counterparty_blocked" | "counterparty_warn" | "counterparty_unmeasured" | "counterparty_unavailable";
4
+ export type ApprovalReason = "amount_threshold" | "counterparty_warn" | "counterparty_unmeasured";
5
+ export type CounterpartyCheckMode = "off" | "shadow" | "enforce";
6
+ export interface DealTerms {
7
+ payTo: string;
8
+ asset: string;
9
+ amount: string;
10
+ network: string;
11
+ scheme: string;
12
+ }
13
+ export type OfferedTerms = DealTerms;
14
+ export type VerifiedTerms = DealTerms;
15
+ export interface NormalizedTerms {
16
+ payTo: string;
17
+ asset: string;
18
+ amount: string;
19
+ network: string;
20
+ scheme: string;
21
+ }
22
+ interface AssessmentBase {
23
+ checkedAt: string;
24
+ cacheHit?: boolean;
25
+ }
26
+ export interface Vet402VerdictAssessment extends AssessmentBase {
27
+ kind: "verdict";
28
+ verdict: Vet402Verdict;
29
+ reasonCodes: readonly string[];
30
+ verifiedTerms: VerifiedTerms | null;
31
+ evidenceAgeSeconds?: number;
32
+ degraded?: boolean;
33
+ }
34
+ export interface Vet402NotInCatalogAssessment extends AssessmentBase {
35
+ kind: "not_in_catalog";
36
+ }
37
+ export interface Vet402PrivacyUnmeasurableAssessment extends AssessmentBase {
38
+ kind: "privacy_unmeasurable";
39
+ sanitizeBlock?: SanitizeUrlBlock;
40
+ }
41
+ export type Vet402UnavailableFailure = "timeout" | "rate_limited" | "upstream_5xx" | "network_error" | "invalid_response" | "degraded";
42
+ export interface Vet402UnavailableAssessment extends AssessmentBase {
43
+ kind: "unavailable";
44
+ failure: Vet402UnavailableFailure;
45
+ }
46
+ export type Vet402Assessment = Vet402VerdictAssessment | Vet402NotInCatalogAssessment | Vet402PrivacyUnmeasurableAssessment | Vet402UnavailableAssessment;
47
+ export type TermsMatchResult = "match" | "mismatch" | "uncomparable" | "unmeasured";
48
+ export interface TermsFieldDiff {
49
+ verified: string;
50
+ offered: string;
51
+ }
52
+ export interface TermsMatch {
53
+ result: TermsMatchResult;
54
+ reason?: string;
55
+ diff?: Partial<Record<keyof NormalizedTerms, TermsFieldDiff>>;
56
+ }
57
+ export interface PaymentDecision {
58
+ action: CounterpartyVerdict;
59
+ reasonCode: CounterpartyReasonCode;
60
+ holdHint?: Extract<ApprovalReason, "counterparty_warn" | "counterparty_unmeasured">;
61
+ }
62
+ export interface CounterpartyCheckInput {
63
+ resourceUrl: string;
64
+ signal?: AbortSignal;
65
+ }
66
+ export interface CounterpartyChecker {
67
+ check(input: CounterpartyCheckInput): Promise<Vet402Assessment>;
68
+ }
69
+ export interface CounterpartyPolicy {
70
+ evaluate(input: {
71
+ assessment: Vet402Assessment;
72
+ termsMatch: TermsMatch;
73
+ }): PaymentDecision;
74
+ }
75
+ export type SanitizeUrlBlock = "unparseable" | "non_https_scheme" | "credentials" | "query" | "fragment" | "secret_path_segment";
76
+ export type SanitizeUrlResult = {
77
+ ok: true;
78
+ url: string;
79
+ } | {
80
+ ok: false;
81
+ block: SanitizeUrlBlock;
82
+ segmentLength?: number;
83
+ };
84
+ export interface DealFingerprintInput {
85
+ wallet: string;
86
+ url: string;
87
+ offer: OfferedTerms;
88
+ }
89
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,48 @@
1
+ import type { CounterpartyCheckInput, CounterpartyChecker, Vet402Assessment } from "./types.js";
2
+ type FetchImpl = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
3
+ export interface Vet402ClientOptions {
4
+ baseUrl?: string;
5
+ fetchImpl?: FetchImpl;
6
+ now?: () => number;
7
+ sleepImpl?: (ms: number) => Promise<void>;
8
+ decisionTtlMs?: number;
9
+ blockTtlMs?: number;
10
+ maxRpm?: number;
11
+ connectTimeoutMs?: number;
12
+ totalTimeoutMs?: number;
13
+ resolveCacheSize?: number;
14
+ decisionCacheSize?: number;
15
+ metrics?: CounterpartyMetricsHooks;
16
+ }
17
+ export interface CounterpartyMetricsHooks {
18
+ onCheck?(outcome: "allow" | "hold" | "deny" | "unavailable", ms: number): void;
19
+ onCache?(result: "hit" | "miss"): void;
20
+ onRateLimited?(endpoint: "resolve" | "decision"): void;
21
+ }
22
+ export declare function vet402ClientOptionsFromEnv(env: Record<string, string | undefined>): Pick<Vet402ClientOptions, "decisionTtlMs" | "blockTtlMs" | "maxRpm" | "connectTimeoutMs" | "totalTimeoutMs">;
23
+ export declare class Vet402Client implements CounterpartyChecker {
24
+ private baseUrl;
25
+ private fetch;
26
+ private now;
27
+ private sleep;
28
+ private decisionTtlMs;
29
+ private blockTtlMs;
30
+ private connectTimeoutMs;
31
+ private totalTimeoutMs;
32
+ private metrics?;
33
+ private resolveCache;
34
+ private decisionCache;
35
+ private inflight;
36
+ private bucket;
37
+ constructor(opts?: Vet402ClientOptions);
38
+ check(input: CounterpartyCheckInput): Promise<Vet402Assessment>;
39
+ private runCheck;
40
+ private emitCheck;
41
+ private resolveResourceId;
42
+ private fetchDecision;
43
+ private parseVerifiedTerms;
44
+ private unavailable;
45
+ private iso;
46
+ private outbound;
47
+ }
48
+ export {};
@@ -0,0 +1,337 @@
1
+ import { sanitizeUrlForCheck } from "./sanitize-url.js";
2
+ export function vet402ClientOptionsFromEnv(env) {
3
+ const int = (k) => {
4
+ const v = env[k];
5
+ if (v === undefined || v === "")
6
+ return undefined;
7
+ const n = Number(v);
8
+ return Number.isFinite(n) && n > 0 ? n : undefined;
9
+ };
10
+ return {
11
+ decisionTtlMs: int("COUNTERPARTY_DECISION_TTL_MS"),
12
+ blockTtlMs: int("COUNTERPARTY_BLOCK_TTL_MS"),
13
+ maxRpm: int("COUNTERPARTY_MAX_RPM"),
14
+ connectTimeoutMs: int("COUNTERPARTY_CONNECT_TIMEOUT_MS"),
15
+ totalTimeoutMs: int("COUNTERPARTY_TOTAL_TIMEOUT_MS"),
16
+ };
17
+ }
18
+ class LruCache {
19
+ maxSize;
20
+ map = new Map();
21
+ constructor(maxSize) {
22
+ this.maxSize = maxSize;
23
+ }
24
+ get(k) {
25
+ const v = this.map.get(k);
26
+ if (v !== undefined) {
27
+ this.map.delete(k);
28
+ this.map.set(k, v);
29
+ }
30
+ return v;
31
+ }
32
+ set(k, v) {
33
+ this.map.delete(k);
34
+ this.map.set(k, v);
35
+ if (this.map.size > this.maxSize) {
36
+ this.map.delete(this.map.keys().next().value);
37
+ }
38
+ }
39
+ delete(k) {
40
+ this.map.delete(k);
41
+ }
42
+ }
43
+ class TokenBucket {
44
+ capacity;
45
+ now;
46
+ tokens;
47
+ lastRefill;
48
+ constructor(capacity, now) {
49
+ this.capacity = capacity;
50
+ this.now = now;
51
+ this.tokens = capacity;
52
+ this.lastRefill = now();
53
+ }
54
+ refill() {
55
+ const t = this.now();
56
+ const rate = this.capacity / 60_000;
57
+ this.tokens = Math.min(this.capacity, this.tokens + (t - this.lastRefill) * rate);
58
+ this.lastRefill = t;
59
+ }
60
+ tryAcquire() {
61
+ this.refill();
62
+ if (this.tokens >= 1) {
63
+ this.tokens -= 1;
64
+ return { ok: true };
65
+ }
66
+ const rate = this.capacity / 60_000;
67
+ return { ok: false, waitMs: Math.ceil((1 - this.tokens) / rate) };
68
+ }
69
+ }
70
+ const LEDGER_UNIT_FACTOR = {
71
+ "eip155:56": 10n ** 12n,
72
+ "stellar:pubnet": 10n,
73
+ "stellar:testnet": 10n,
74
+ };
75
+ const RESOURCE_ID_RE = /^[0-9a-f]{64}$/;
76
+ export class Vet402Client {
77
+ baseUrl;
78
+ fetch;
79
+ now;
80
+ sleep;
81
+ decisionTtlMs;
82
+ blockTtlMs;
83
+ connectTimeoutMs;
84
+ totalTimeoutMs;
85
+ metrics;
86
+ resolveCache;
87
+ decisionCache;
88
+ inflight = new Map();
89
+ bucket;
90
+ constructor(opts = {}) {
91
+ this.baseUrl = (opts.baseUrl ?? "https://vet402.com").replace(/\/+$/, "");
92
+ this.fetch = opts.fetchImpl ?? fetch;
93
+ this.now = opts.now ?? Date.now;
94
+ this.sleep =
95
+ opts.sleepImpl ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
96
+ this.decisionTtlMs = opts.decisionTtlMs ?? 5 * 60_000;
97
+ this.blockTtlMs = opts.blockTtlMs ?? 60_000;
98
+ this.connectTimeoutMs = opts.connectTimeoutMs ?? 2_000;
99
+ this.totalTimeoutMs = opts.totalTimeoutMs ?? 8_000;
100
+ this.metrics = opts.metrics;
101
+ this.resolveCache = new LruCache(opts.resolveCacheSize ?? 1024);
102
+ this.decisionCache = new LruCache(opts.decisionCacheSize ?? 1024);
103
+ this.bucket = new TokenBucket(Math.max(1, opts.maxRpm ?? 11), this.now);
104
+ }
105
+ async check(input) {
106
+ const t0 = this.now();
107
+ const s = sanitizeUrlForCheck(input.resourceUrl);
108
+ if (!s.ok) {
109
+ const a = {
110
+ kind: "privacy_unmeasurable",
111
+ sanitizeBlock: s.block,
112
+ checkedAt: new Date(t0).toISOString(),
113
+ };
114
+ this.metrics?.onCheck?.("hold", this.now() - t0);
115
+ return a;
116
+ }
117
+ const key = s.url;
118
+ const existing = this.inflight.get(key);
119
+ if (existing) {
120
+ const a = await existing;
121
+ this.emitCheck(a, t0, true);
122
+ return a;
123
+ }
124
+ const p = this.runCheck(s.url, t0, input.signal)
125
+ .finally(() => this.inflight.delete(key));
126
+ this.inflight.set(key, p);
127
+ return p;
128
+ }
129
+ async runCheck(url, t0, callerSignal) {
130
+ const deadline = t0 + this.totalTimeoutMs;
131
+ let rereolved = false;
132
+ for (;;) {
133
+ const resolved = await this.resolveResourceId(url, deadline, callerSignal);
134
+ if (resolved.assessment) {
135
+ this.emitCheck(resolved.assessment, t0, resolved.cacheHit === true);
136
+ return resolved.assessment;
137
+ }
138
+ const resourceId = resolved.resourceId;
139
+ const cached = this.decisionCache.get(resourceId);
140
+ if (cached && cached.expiresAt > this.now()) {
141
+ const a = { ...cached.assessment, cacheHit: true };
142
+ this.emitCheck(a, t0, true);
143
+ return a;
144
+ }
145
+ const out = await this.fetchDecision(resourceId, url, deadline, callerSignal);
146
+ if (out.assessment) {
147
+ if (out.assessment.kind === "unavailable" &&
148
+ out.assessment.failure === "invalid_response" &&
149
+ out.unknownResource &&
150
+ !rereolved) {
151
+ rereolved = true;
152
+ this.resolveCache.delete(url);
153
+ continue;
154
+ }
155
+ this.emitCheck(out.assessment, t0, false);
156
+ return out.assessment;
157
+ }
158
+ const a = out.verdict;
159
+ const ttl = a.verdict === "BLOCK" ? this.blockTtlMs : this.decisionTtlMs;
160
+ this.decisionCache.set(resourceId, {
161
+ assessment: a,
162
+ expiresAt: this.now() + ttl,
163
+ });
164
+ this.emitCheck(a, t0, false);
165
+ return a;
166
+ }
167
+ }
168
+ emitCheck(a, t0, cacheHit) {
169
+ const outcome = a.kind === "unavailable"
170
+ ? "unavailable"
171
+ : a.kind === "verdict"
172
+ ? a.verdict === "ALLOW"
173
+ ? "allow"
174
+ : a.verdict === "BLOCK"
175
+ ? "deny"
176
+ : "hold"
177
+ : "hold";
178
+ this.metrics?.onCheck?.(outcome, this.now() - t0);
179
+ this.metrics?.onCache?.(cacheHit ? "hit" : "miss");
180
+ }
181
+ async resolveResourceId(url, deadline, callerSignal) {
182
+ const cached = this.resolveCache.get(url);
183
+ if (cached && cached.expiresAt > this.now()) {
184
+ if (cached.notInCatalog) {
185
+ return {
186
+ assessment: { kind: "not_in_catalog", checkedAt: this.iso(), cacheHit: true },
187
+ cacheHit: true,
188
+ };
189
+ }
190
+ return { resourceId: cached.resourceId, cacheHit: true };
191
+ }
192
+ const r = await this.outbound(`${this.baseUrl}/api/v1/resolve?q=${encodeURIComponent(url)}`, "resolve", deadline, callerSignal);
193
+ if (r.failure)
194
+ return { assessment: this.unavailable(r.failure) };
195
+ if (r.status !== 200)
196
+ return { assessment: this.unavailable("invalid_response") };
197
+ const body = r.body;
198
+ if (body?.not_found?.reason === "not_in_catalog") {
199
+ this.resolveCache.set(url, {
200
+ notInCatalog: true,
201
+ expiresAt: this.now() + this.decisionTtlMs,
202
+ });
203
+ return { assessment: { kind: "not_in_catalog", checkedAt: this.iso() } };
204
+ }
205
+ const id = body?.resource?.resource_id;
206
+ if (typeof id === "string" && RESOURCE_ID_RE.test(id)) {
207
+ this.resolveCache.set(url, { resourceId: id, expiresAt: Infinity });
208
+ return { resourceId: id };
209
+ }
210
+ return { assessment: this.unavailable("invalid_response") };
211
+ }
212
+ async fetchDecision(resourceId, url, deadline, callerSignal) {
213
+ const qs = new URLSearchParams({ role: "payer", url });
214
+ const r = await this.outbound(`${this.baseUrl}/api/v1/resources/${resourceId}/decision?${qs}`, "decision", deadline, callerSignal);
215
+ if (r.failure)
216
+ return { assessment: this.unavailable(r.failure) };
217
+ if (r.status === 404) {
218
+ const b = r.body;
219
+ if (b?.error === "not_found") {
220
+ return {
221
+ assessment: this.unavailable("invalid_response"),
222
+ unknownResource: true,
223
+ };
224
+ }
225
+ return { assessment: this.unavailable("invalid_response") };
226
+ }
227
+ if (r.status !== 200)
228
+ return { assessment: this.unavailable("invalid_response") };
229
+ const b = r.body;
230
+ if (b?.recommendation !== "ALLOW" && b?.recommendation !== "WARN" && b?.recommendation !== "BLOCK") {
231
+ return { assessment: this.unavailable("invalid_response") };
232
+ }
233
+ const vt = this.parseVerifiedTerms(b.verified_terms);
234
+ if (vt === "invalid")
235
+ return { assessment: this.unavailable("invalid_response") };
236
+ return {
237
+ verdict: {
238
+ kind: "verdict",
239
+ verdict: b.recommendation,
240
+ reasonCodes: Array.isArray(b.reason_codes)
241
+ ? b.reason_codes.filter((c) => typeof c === "string")
242
+ : [],
243
+ verifiedTerms: vt,
244
+ evidenceAgeSeconds: typeof b.evidence_age?.days_since_last_delivery === "number"
245
+ ? b.evidence_age.days_since_last_delivery * 86_400
246
+ : undefined,
247
+ degraded: b.degraded === true,
248
+ checkedAt: this.iso(),
249
+ },
250
+ };
251
+ }
252
+ parseVerifiedTerms(v) {
253
+ if (v === null || v === undefined)
254
+ return null;
255
+ if (typeof v !== "object")
256
+ return "invalid";
257
+ const t = v;
258
+ const { pay_to, asset, amount, network, scheme } = t;
259
+ if (typeof pay_to !== "string" ||
260
+ typeof asset !== "string" ||
261
+ typeof amount !== "string" ||
262
+ !/^\d+$/.test(amount) ||
263
+ typeof network !== "string" ||
264
+ typeof scheme !== "string") {
265
+ return "invalid";
266
+ }
267
+ const factor = LEDGER_UNIT_FACTOR[network] ?? 1n;
268
+ return {
269
+ payTo: pay_to,
270
+ asset,
271
+ amount: (BigInt(amount) * factor).toString(),
272
+ network,
273
+ scheme,
274
+ };
275
+ }
276
+ unavailable(failure) {
277
+ return { kind: "unavailable", failure, checkedAt: this.iso() };
278
+ }
279
+ iso() {
280
+ return new Date(this.now()).toISOString();
281
+ }
282
+ async outbound(url, endpoint, deadline, callerSignal) {
283
+ for (;;) {
284
+ const remaining = deadline - this.now();
285
+ if (remaining <= 0)
286
+ return { failure: "timeout" };
287
+ const t = this.bucket.tryAcquire();
288
+ if (t.ok)
289
+ break;
290
+ if (this.now() + t.waitMs > deadline)
291
+ return { failure: "rate_limited" };
292
+ await this.sleep(t.waitMs);
293
+ }
294
+ const remaining = deadline - this.now();
295
+ if (remaining <= 0)
296
+ return { failure: "timeout" };
297
+ const perRequest = Math.min(this.connectTimeoutMs, remaining);
298
+ const signals = [AbortSignal.timeout(perRequest)];
299
+ if (callerSignal)
300
+ signals.push(callerSignal);
301
+ const signal = typeof AbortSignal.any === "function"
302
+ ? AbortSignal.any(signals)
303
+ : signals[0];
304
+ let res;
305
+ try {
306
+ res = await this.fetch(url, {
307
+ method: "GET",
308
+ headers: { accept: "application/json" },
309
+ signal,
310
+ });
311
+ }
312
+ catch (e) {
313
+ const name = e?.name;
314
+ return {
315
+ failure: name === "AbortError" || name === "TimeoutError"
316
+ ? "timeout"
317
+ : "network_error",
318
+ };
319
+ }
320
+ if (res.status === 429) {
321
+ this.metrics?.onRateLimited?.(endpoint);
322
+ return { failure: "rate_limited" };
323
+ }
324
+ if (res.status === 503)
325
+ return { failure: "degraded" };
326
+ if (res.status >= 500)
327
+ return { failure: "upstream_5xx" };
328
+ let body;
329
+ try {
330
+ body = await res.json();
331
+ }
332
+ catch {
333
+ return { failure: "invalid_response" };
334
+ }
335
+ return { status: res.status, body };
336
+ }
337
+ }