sarvam-agents-client 0.5.0 → 0.5.2
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/dist/compat/core/agents.d.ts +53 -0
- package/dist/compat/core/agents.js +338 -0
- package/dist/compat/core/data.d.ts +10 -0
- package/dist/compat/core/data.js +275 -0
- package/dist/compat/core/errors.d.ts +37 -0
- package/dist/compat/core/errors.js +155 -0
- package/dist/compat/core/events.d.ts +107 -0
- package/dist/compat/core/events.js +160 -0
- package/dist/compat/core/files.d.ts +65 -0
- package/dist/compat/core/files.js +851 -0
- package/dist/compat/core/history.d.ts +9 -0
- package/dist/compat/core/history.js +112 -0
- package/dist/compat/core/http.d.ts +112 -0
- package/dist/compat/core/http.js +753 -0
- package/dist/compat/core/ids.d.ts +4 -0
- package/dist/compat/core/ids.js +36 -0
- package/dist/compat/core/index.d.ts +14 -0
- package/dist/compat/core/index.js +30 -0
- package/dist/compat/core/models.d.ts +20 -0
- package/dist/compat/core/models.js +75 -0
- package/dist/compat/core/paging.d.ts +14 -0
- package/dist/compat/core/paging.js +124 -0
- package/dist/compat/core/refusals.d.ts +9 -0
- package/dist/compat/core/refusals.js +25 -0
- package/dist/compat/core/sessions.d.ts +65 -0
- package/dist/compat/core/sessions.js +317 -0
- package/dist/compat/core/toolResults.d.ts +43 -0
- package/dist/compat/core/toolResults.js +208 -0
- package/dist/compat/core/turns.d.ts +104 -0
- package/dist/compat/core/turns.js +504 -0
- package/dist/compat/core/warnings.d.ts +6 -0
- package/dist/compat/core/warnings.js +26 -0
- package/dist/compat/index.d.ts +3 -0
- package/dist/compat/index.js +9 -0
- package/dist/compat/openai/client.d.ts +62 -0
- package/dist/compat/openai/client.js +108 -0
- package/dist/compat/openai/errors.d.ts +72 -0
- package/dist/compat/openai/errors.js +150 -0
- package/dist/compat/openai/index.d.ts +14 -0
- package/dist/compat/openai/index.js +42 -0
- package/dist/compat/openai/pages.d.ts +19 -0
- package/dist/compat/openai/pages.js +39 -0
- package/dist/compat/openai/resources/agents.d.ts +36 -0
- package/dist/compat/openai/resources/agents.js +549 -0
- package/dist/compat/openai/resources/events.d.ts +23 -0
- package/dist/compat/openai/resources/events.js +485 -0
- package/dist/compat/openai/resources/sessions.d.ts +33 -0
- package/dist/compat/openai/resources/sessions.js +283 -0
- package/dist/compat/openai/stream.d.ts +40 -0
- package/dist/compat/openai/stream.js +585 -0
- package/dist/compat/openai/types.d.ts +125 -0
- package/dist/compat/openai/types.js +98 -0
- package/dist/compose/agent.d.ts +2 -0
- package/dist/compose/agent.js +27 -0
- package/dist/compose/functionTool.d.ts +2 -0
- package/dist/compose/functionTool.js +46 -0
- package/dist/compose/output.d.ts +2 -0
- package/dist/compose/output.js +15 -7
- package/dist/esm/compat/core/agents.d.ts +53 -0
- package/dist/esm/compat/core/agents.js +334 -0
- package/dist/esm/compat/core/data.d.ts +10 -0
- package/dist/esm/compat/core/data.js +272 -0
- package/dist/esm/compat/core/errors.d.ts +37 -0
- package/dist/esm/compat/core/errors.js +146 -0
- package/dist/esm/compat/core/events.d.ts +107 -0
- package/dist/esm/compat/core/events.js +156 -0
- package/dist/esm/compat/core/files.d.ts +65 -0
- package/dist/esm/compat/core/files.js +829 -0
- package/dist/esm/compat/core/history.d.ts +9 -0
- package/dist/esm/compat/core/history.js +109 -0
- package/dist/esm/compat/core/http.d.ts +112 -0
- package/dist/esm/compat/core/http.js +746 -0
- package/dist/esm/compat/core/ids.d.ts +4 -0
- package/dist/esm/compat/core/ids.js +30 -0
- package/dist/esm/compat/core/index.d.ts +14 -0
- package/dist/esm/compat/core/index.js +14 -0
- package/dist/esm/compat/core/models.d.ts +20 -0
- package/dist/esm/compat/core/models.js +71 -0
- package/dist/esm/compat/core/paging.d.ts +14 -0
- package/dist/esm/compat/core/paging.js +118 -0
- package/dist/esm/compat/core/refusals.d.ts +9 -0
- package/dist/esm/compat/core/refusals.js +21 -0
- package/dist/esm/compat/core/sessions.d.ts +65 -0
- package/dist/esm/compat/core/sessions.js +312 -0
- package/dist/esm/compat/core/toolResults.d.ts +43 -0
- package/dist/esm/compat/core/toolResults.js +203 -0
- package/dist/esm/compat/core/turns.d.ts +104 -0
- package/dist/esm/compat/core/turns.js +497 -0
- package/dist/esm/compat/core/warnings.d.ts +6 -0
- package/dist/esm/compat/core/warnings.js +20 -0
- package/dist/esm/compat/index.d.ts +3 -0
- package/dist/esm/compat/index.js +3 -0
- package/dist/esm/compat/openai/client.d.ts +62 -0
- package/dist/esm/compat/openai/client.js +104 -0
- package/dist/esm/compat/openai/errors.d.ts +72 -0
- package/dist/esm/compat/openai/errors.js +130 -0
- package/dist/esm/compat/openai/index.d.ts +14 -0
- package/dist/esm/compat/openai/index.js +17 -0
- package/dist/esm/compat/openai/pages.d.ts +19 -0
- package/dist/esm/compat/openai/pages.js +35 -0
- package/dist/esm/compat/openai/resources/agents.d.ts +36 -0
- package/dist/esm/compat/openai/resources/agents.js +540 -0
- package/dist/esm/compat/openai/resources/events.d.ts +23 -0
- package/dist/esm/compat/openai/resources/events.js +479 -0
- package/dist/esm/compat/openai/resources/sessions.d.ts +33 -0
- package/dist/esm/compat/openai/resources/sessions.js +278 -0
- package/dist/esm/compat/openai/stream.d.ts +40 -0
- package/dist/esm/compat/openai/stream.js +579 -0
- package/dist/esm/compat/openai/types.d.ts +125 -0
- package/dist/esm/compat/openai/types.js +91 -0
- package/dist/esm/compose/agent.d.ts +2 -0
- package/dist/esm/compose/agent.js +28 -2
- package/dist/esm/compose/functionTool.d.ts +2 -0
- package/dist/esm/compose/functionTool.js +45 -0
- package/dist/esm/compose/output.d.ts +2 -0
- package/dist/esm/compose/output.js +14 -7
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -1
- package/package.json +53 -11
- package/src/compat/core/agents.ts +437 -0
- package/src/compat/core/data.ts +283 -0
- package/src/compat/core/errors.ts +162 -0
- package/src/compat/core/events.ts +198 -0
- package/src/compat/core/files.ts +913 -0
- package/src/compat/core/history.ts +116 -0
- package/src/compat/core/http.ts +827 -0
- package/src/compat/core/ids.ts +35 -0
- package/src/compat/core/index.ts +14 -0
- package/src/compat/core/models.ts +85 -0
- package/src/compat/core/paging.ts +119 -0
- package/src/compat/core/refusals.ts +31 -0
- package/src/compat/core/sessions.ts +358 -0
- package/src/compat/core/toolResults.ts +235 -0
- package/src/compat/core/turns.ts +622 -0
- package/src/compat/core/warnings.ts +23 -0
- package/src/compat/index.ts +3 -0
- package/src/compat/openai/client.ts +177 -0
- package/src/compat/openai/errors.ts +165 -0
- package/src/compat/openai/index.ts +65 -0
- package/src/compat/openai/pages.ts +55 -0
- package/src/compat/openai/resources/agents.ts +603 -0
- package/src/compat/openai/resources/events.ts +523 -0
- package/src/compat/openai/resources/sessions.ts +369 -0
- package/src/compat/openai/stream.ts +599 -0
- package/src/compat/openai/types.ts +217 -0
- package/src/compose/agent.ts +30 -3
- package/src/compose/functionTool.ts +44 -0
- package/src/compose/output.ts +14 -8
- package/src/index.ts +3 -0
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
/** HTTP config, key/URL resolution, retry loop, timeouts, default/per-call options, and Configuration wrapper. */
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
5
|
+
import * as httpMod from "node:http";
|
|
6
|
+
import * as httpsMod from "node:https";
|
|
7
|
+
import { isIP } from "node:net";
|
|
8
|
+
import { Readable } from "node:stream";
|
|
9
|
+
import { Configuration, ResponseError, FetchError, type FetchAPI } from "../../runtime.js";
|
|
10
|
+
import { NotSupportedByServerError, UserError } from "../../compose/errors.js";
|
|
11
|
+
import {
|
|
12
|
+
CoreAPIError,
|
|
13
|
+
CoreConnectionError,
|
|
14
|
+
CoreTimeoutError,
|
|
15
|
+
CoreUserAbortError,
|
|
16
|
+
mapPanjaError,
|
|
17
|
+
} from "./errors.js";
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_BASE_URL = "https://chat.sarvamclaw.sarvam.ai";
|
|
20
|
+
export const DEFAULT_TIMEOUT_MS = 600_000;
|
|
21
|
+
export const DEFAULT_MAX_RETRIES = 2;
|
|
22
|
+
const MAX_BACKOFF_MS = 8_000;
|
|
23
|
+
const PROVIDER_KEY_PREFIXES = ["sk-ant-", "sk-proj-", "sk-"];
|
|
24
|
+
const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
|
|
25
|
+
const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
|
|
26
|
+
const STRIPPED_HEADERS = new Set(["openai-beta", "anthropic-beta", "anthropic-version"]);
|
|
27
|
+
|
|
28
|
+
function looksLikeProviderKey(key: string): boolean {
|
|
29
|
+
return PROVIDER_KEY_PREFIXES.some((p) => key.startsWith(p));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ClientConfigInput {
|
|
33
|
+
apiKey?: string | null;
|
|
34
|
+
baseURL?: string | null;
|
|
35
|
+
timeout?: number | null;
|
|
36
|
+
maxRetries?: number;
|
|
37
|
+
defaultHeaders?: Record<string, string>;
|
|
38
|
+
defaultQuery?: Record<string, string>;
|
|
39
|
+
fetch?: FetchAPI;
|
|
40
|
+
provider?: string;
|
|
41
|
+
allowPrivateRemoteUrls?: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ResolvedClientConfig {
|
|
45
|
+
apiKey: string;
|
|
46
|
+
baseURL: string;
|
|
47
|
+
timeout: number;
|
|
48
|
+
maxRetries: number;
|
|
49
|
+
defaultHeaders: Record<string, string>;
|
|
50
|
+
defaultQuery: Record<string, string>;
|
|
51
|
+
fetch?: FetchAPI;
|
|
52
|
+
provider: string;
|
|
53
|
+
allowPrivateRemoteUrls: boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface PerCallRequestOptions {
|
|
57
|
+
timeout?: number;
|
|
58
|
+
maxRetries?: number;
|
|
59
|
+
headers?: Record<string, string>;
|
|
60
|
+
query?: Record<string, string>;
|
|
61
|
+
signal?: AbortSignal;
|
|
62
|
+
idempotencyKey?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface RawResponseSnapshot {
|
|
66
|
+
status: number;
|
|
67
|
+
headers: Record<string, string>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface InternalRequestContext extends PerCallRequestOptions {
|
|
71
|
+
/** Scoped exclusively to one http.call(..., { idempotencyKey }) write so keys never leak onto GETs. */
|
|
72
|
+
_callIdempotencyKey?: string;
|
|
73
|
+
/** Per-call raw response capture box so concurrent calls never overwrite each other. */
|
|
74
|
+
_rawBox?: { snap: RawResponseSnapshot | null };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function resolveClientConfig(input: ClientConfigInput = {}): ResolvedClientConfig {
|
|
78
|
+
const env = typeof process !== "undefined" ? process.env : {};
|
|
79
|
+
const key = input.apiKey || env["SARVAM_API_KEY"] || env["SARVAM_AGENTS_TOKEN"] || "";
|
|
80
|
+
if (!key) {
|
|
81
|
+
throw new CoreAPIError(
|
|
82
|
+
"Missing Sarvam API key: pass apiKey or set SARVAM_API_KEY (OPENAI_API_KEY and ANTHROPIC_API_KEY are never read).",
|
|
83
|
+
{ status: 401, code: "authentication_error" },
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
if (looksLikeProviderKey(key)) {
|
|
87
|
+
throw new CoreAPIError(
|
|
88
|
+
"Provider-shaped API key rejected locally: pass a Sarvam API key via apiKey or SARVAM_API_KEY.",
|
|
89
|
+
{ status: 401, code: "authentication_error" },
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
const rawUrl = input.baseURL || env["SARVAM_BASE_URL"] || DEFAULT_BASE_URL;
|
|
93
|
+
const baseURL = rawUrl.replace(/\/+$/, "");
|
|
94
|
+
const timeout = input.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
95
|
+
const maxRetries = Math.max(0, Math.floor(input.maxRetries ?? DEFAULT_MAX_RETRIES));
|
|
96
|
+
return {
|
|
97
|
+
apiKey: key,
|
|
98
|
+
baseURL,
|
|
99
|
+
timeout,
|
|
100
|
+
maxRetries,
|
|
101
|
+
defaultHeaders: { ...(input.defaultHeaders ?? {}) },
|
|
102
|
+
defaultQuery: { ...(input.defaultQuery ?? {}) },
|
|
103
|
+
fetch: input.fetch,
|
|
104
|
+
provider: input.provider ?? "openai",
|
|
105
|
+
allowPrivateRemoteUrls: Boolean(input.allowPrivateRemoteUrls),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function getHeader(headers: Record<string, string>, name: string): string | null {
|
|
110
|
+
const low = name.toLowerCase();
|
|
111
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
112
|
+
if (k.toLowerCase() === low) return v;
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function parseRetryAfterMs(headers: Record<string, string>): number | null {
|
|
118
|
+
const msRaw = getHeader(headers, "retry-after-ms");
|
|
119
|
+
if (msRaw !== null) {
|
|
120
|
+
const ms = Number(msRaw.trim());
|
|
121
|
+
if (Number.isFinite(ms)) return Math.max(0, Math.min(ms, 60_000));
|
|
122
|
+
}
|
|
123
|
+
const raw = getHeader(headers, "retry-after");
|
|
124
|
+
if (raw === null) return null;
|
|
125
|
+
const trimmed = raw.trim();
|
|
126
|
+
const secs = Number(trimmed);
|
|
127
|
+
if (Number.isFinite(secs)) return Math.max(0, Math.min(secs * 1000, 60_000));
|
|
128
|
+
const dateMs = Date.parse(trimmed);
|
|
129
|
+
if (!Number.isNaN(dateMs)) {
|
|
130
|
+
return Math.max(0, Math.min(dateMs - Date.now(), 60_000));
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function shouldRetry(err: CoreAPIError): boolean {
|
|
136
|
+
if (err instanceof CoreUserAbortError) return false;
|
|
137
|
+
if (err instanceof CoreConnectionError) return true;
|
|
138
|
+
const xRetry = getHeader(err.headers, "x-should-retry");
|
|
139
|
+
if (xRetry !== null) {
|
|
140
|
+
const low = xRetry.trim().toLowerCase();
|
|
141
|
+
if (low === "false") return false;
|
|
142
|
+
if (low === "true") return true;
|
|
143
|
+
}
|
|
144
|
+
if (err.status !== null && RETRYABLE_STATUSES.has(err.status)) return true;
|
|
145
|
+
if (err.status === 409 && err.code === "lock_timeout") return true;
|
|
146
|
+
if (err.status !== null && err.status >= 500) return true;
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function headersToRecord(h: Headers): Record<string, string> {
|
|
151
|
+
const out: Record<string, string> = {};
|
|
152
|
+
h.forEach((v, k) => { out[k.toLowerCase()] = v; });
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function mergeUrlQuery(urlStr: string, extra: Record<string, string>): string {
|
|
157
|
+
const entries = Object.entries(extra);
|
|
158
|
+
if (entries.length === 0) return urlStr;
|
|
159
|
+
const u = new URL(urlStr);
|
|
160
|
+
for (const [k, v] of entries) {
|
|
161
|
+
if (v !== undefined && v !== null && !u.searchParams.has(k)) {
|
|
162
|
+
u.searchParams.set(k, String(v));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return u.toString();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface PinnedNodeTransport {
|
|
169
|
+
httpRequest?: typeof httpMod.request;
|
|
170
|
+
httpsRequest?: typeof httpsMod.request;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Create a Node `net.LookupFunction` that always resolves directly to ``pinnedIp`` without
|
|
175
|
+
* issuing a second DNS lookup, supporting both `{ all: true }` (Node 20+ autoSelectFamily)
|
|
176
|
+
* and single-address callback forms.
|
|
177
|
+
*/
|
|
178
|
+
export function createPinnedLookup(pinnedIp: string) {
|
|
179
|
+
const family = isIP(pinnedIp);
|
|
180
|
+
if (family !== 4 && family !== 6) {
|
|
181
|
+
throw new Error(`Invalid pinned IP address: ${pinnedIp}`);
|
|
182
|
+
}
|
|
183
|
+
return (
|
|
184
|
+
_hostname: string,
|
|
185
|
+
options:
|
|
186
|
+
| number
|
|
187
|
+
| { all?: boolean }
|
|
188
|
+
| ((err: NodeJS.ErrnoException | null, address: string | Array<{ address: string; family: number }>, family?: number) => void),
|
|
189
|
+
callback?: (err: NodeJS.ErrnoException | null, address: string | Array<{ address: string; family: number }>, family?: number) => void,
|
|
190
|
+
): void => {
|
|
191
|
+
const cb = typeof options === "function" ? options : callback;
|
|
192
|
+
if (!cb) return;
|
|
193
|
+
const wantAll = typeof options === "object" && options !== null && Boolean(options.all);
|
|
194
|
+
if (wantAll) {
|
|
195
|
+
cb(null, [{ address: pinnedIp, family }]);
|
|
196
|
+
} else {
|
|
197
|
+
cb(null, pinnedIp, family);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function normalizeInitHeaders(raw?: HeadersInit): Record<string, string> {
|
|
203
|
+
const out: Record<string, string> = {};
|
|
204
|
+
if (!raw) return out;
|
|
205
|
+
if (raw instanceof Headers) {
|
|
206
|
+
raw.forEach((v, k) => {
|
|
207
|
+
out[k] = v;
|
|
208
|
+
});
|
|
209
|
+
} else if (Array.isArray(raw)) {
|
|
210
|
+
for (const [k, v] of raw) {
|
|
211
|
+
out[k] = v;
|
|
212
|
+
}
|
|
213
|
+
} else {
|
|
214
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
215
|
+
if (v !== undefined) out[k] = String(v);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function incomingHeadersToWeb(res: httpMod.IncomingMessage): Headers {
|
|
222
|
+
const headers = new Headers();
|
|
223
|
+
if (Array.isArray(res.rawHeaders) && res.rawHeaders.length >= 2) {
|
|
224
|
+
for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
|
|
225
|
+
const k = res.rawHeaders[i];
|
|
226
|
+
const v = res.rawHeaders[i + 1];
|
|
227
|
+
if (k) headers.append(k, v);
|
|
228
|
+
}
|
|
229
|
+
return headers;
|
|
230
|
+
}
|
|
231
|
+
for (const [k, v] of Object.entries(res.headers ?? {})) {
|
|
232
|
+
if (v === undefined) continue;
|
|
233
|
+
if (Array.isArray(v)) {
|
|
234
|
+
for (const item of v) headers.append(k, item);
|
|
235
|
+
} else {
|
|
236
|
+
headers.append(k, v);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return headers;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Issue an HTTP/HTTPS request pinned to ``pinnedIp`` via Node's stdlib ``node:http`` / ``node:https``
|
|
244
|
+
* while preserving the original ``Host`` header, TLS SNI (``servername``), and certificate hostname
|
|
245
|
+
* verification (closing the DNS rebinding TOCTOU gap).
|
|
246
|
+
*/
|
|
247
|
+
export function pinnedNodeFetch(
|
|
248
|
+
url: string,
|
|
249
|
+
init: RequestInit,
|
|
250
|
+
pinnedIp: string,
|
|
251
|
+
signal?: AbortSignal,
|
|
252
|
+
transport?: PinnedNodeTransport,
|
|
253
|
+
): Promise<Response> {
|
|
254
|
+
const parsed = new URL(url);
|
|
255
|
+
const isHttps = parsed.protocol === "https:";
|
|
256
|
+
const unbracketedHost =
|
|
257
|
+
parsed.hostname.startsWith("[") && parsed.hostname.endsWith("]")
|
|
258
|
+
? parsed.hostname.slice(1, -1)
|
|
259
|
+
: parsed.hostname;
|
|
260
|
+
const hostIsIp = isIP(unbracketedHost) !== 0;
|
|
261
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
262
|
+
const reqHeaders = normalizeInitHeaders(init.headers);
|
|
263
|
+
const hasHost = Object.keys(reqHeaders).some((k) => k.toLowerCase() === "host");
|
|
264
|
+
if (!hasHost) {
|
|
265
|
+
reqHeaders["Host"] = parsed.host;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const reqOpts: httpsMod.RequestOptions = {
|
|
269
|
+
protocol: parsed.protocol,
|
|
270
|
+
hostname: unbracketedHost,
|
|
271
|
+
port: parsed.port || undefined,
|
|
272
|
+
path: `${parsed.pathname || "/"}${parsed.search}`,
|
|
273
|
+
method,
|
|
274
|
+
headers: reqHeaders,
|
|
275
|
+
lookup: createPinnedLookup(pinnedIp) as unknown as httpsMod.RequestOptions["lookup"],
|
|
276
|
+
signal,
|
|
277
|
+
...(isHttps && !hostIsIp ? { servername: unbracketedHost } : {}),
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
const requestFn = isHttps
|
|
281
|
+
? (transport?.httpsRequest ?? httpsMod.request)
|
|
282
|
+
: (transport?.httpRequest ?? httpMod.request);
|
|
283
|
+
|
|
284
|
+
return new Promise<Response>((resolve, reject) => {
|
|
285
|
+
let settled = false;
|
|
286
|
+
const finishResolve = (r: Response): void => {
|
|
287
|
+
if (settled) return;
|
|
288
|
+
settled = true;
|
|
289
|
+
resolve(r);
|
|
290
|
+
};
|
|
291
|
+
const finishReject = (err: unknown): void => {
|
|
292
|
+
if (settled) return;
|
|
293
|
+
settled = true;
|
|
294
|
+
reject(err);
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
const req = requestFn(reqOpts, (res: httpMod.IncomingMessage) => {
|
|
298
|
+
const status = res.statusCode ?? 500;
|
|
299
|
+
const respHeaders = incomingHeadersToWeb(res);
|
|
300
|
+
const statusText = res.statusMessage ?? "";
|
|
301
|
+
|
|
302
|
+
if (NULL_BODY_STATUSES.has(status) || method === "HEAD") {
|
|
303
|
+
res.resume();
|
|
304
|
+
finishResolve(new Response(null, { status, statusText, headers: respHeaders }));
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (signal) {
|
|
309
|
+
const onAbort = (): void => {
|
|
310
|
+
const reason = signal.reason instanceof Error
|
|
311
|
+
? signal.reason
|
|
312
|
+
: Object.assign(new Error("Request was aborted."), { name: "AbortError" });
|
|
313
|
+
res.destroy(reason);
|
|
314
|
+
req.destroy(reason);
|
|
315
|
+
};
|
|
316
|
+
if (signal.aborted) {
|
|
317
|
+
onAbort();
|
|
318
|
+
} else {
|
|
319
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
320
|
+
const detach = (): void => {
|
|
321
|
+
signal.removeEventListener("abort", onAbort);
|
|
322
|
+
};
|
|
323
|
+
res.once("end", detach);
|
|
324
|
+
res.once("close", detach);
|
|
325
|
+
res.once("error", detach);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const webStream = Readable.toWeb(res) as unknown as ReadableStream<Uint8Array>;
|
|
330
|
+
finishResolve(new Response(webStream, { status, statusText, headers: respHeaders }));
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
req.on("error", (err) => {
|
|
334
|
+
finishReject(err);
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
const body = init.body;
|
|
338
|
+
if (body === undefined || body === null) {
|
|
339
|
+
req.end();
|
|
340
|
+
} else if (typeof body === "string") {
|
|
341
|
+
req.end(body);
|
|
342
|
+
} else if (body instanceof Uint8Array) {
|
|
343
|
+
req.end(Buffer.from(body.buffer, body.byteOffset, body.byteLength));
|
|
344
|
+
} else if (body instanceof ArrayBuffer) {
|
|
345
|
+
req.end(Buffer.from(body));
|
|
346
|
+
} else {
|
|
347
|
+
req.end(String(body));
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export class Http {
|
|
353
|
+
readonly config: ResolvedClientConfig;
|
|
354
|
+
readonly sdkConfig: Configuration;
|
|
355
|
+
private readonly baseFetch: FetchAPI;
|
|
356
|
+
private readonly sleepFn: (ms: number) => Promise<void>;
|
|
357
|
+
private readonly jitterFn: (ms: number) => number;
|
|
358
|
+
private readonly resolveHostFn?: (host: string) => Promise<string[]>;
|
|
359
|
+
private readonly reqStore = new AsyncLocalStorage<InternalRequestContext>();
|
|
360
|
+
|
|
361
|
+
constructor(
|
|
362
|
+
input: ClientConfigInput,
|
|
363
|
+
opts: {
|
|
364
|
+
sleep?: (ms: number) => Promise<void>;
|
|
365
|
+
jitter?: (ms: number) => number;
|
|
366
|
+
resolveHost?: (host: string) => Promise<string[]>;
|
|
367
|
+
} = {},
|
|
368
|
+
) {
|
|
369
|
+
this.config = resolveClientConfig(input);
|
|
370
|
+
this.sleepFn = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
371
|
+
this.resolveHostFn = opts.resolveHost;
|
|
372
|
+
if (opts.jitter) {
|
|
373
|
+
this.jitterFn = opts.jitter;
|
|
374
|
+
} else if (opts.sleep) {
|
|
375
|
+
this.jitterFn = (ms) => ms;
|
|
376
|
+
} else {
|
|
377
|
+
this.jitterFn = (ms) => Math.floor(ms * (0.75 + Math.random() * 0.5));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const headers: Record<string, string> = {
|
|
381
|
+
"X-Panja-Origin": "managed_agents",
|
|
382
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
383
|
+
};
|
|
384
|
+
for (const [k, v] of Object.entries(this.config.defaultHeaders)) {
|
|
385
|
+
if (STRIPPED_HEADERS.has(k.toLowerCase())) continue;
|
|
386
|
+
headers[k] = v;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const baseFetch: FetchAPI = this.config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
390
|
+
this.baseFetch = baseFetch;
|
|
391
|
+
const httpSelf = this;
|
|
392
|
+
|
|
393
|
+
const wrappedFetch: FetchAPI = async (reqInput: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
|
394
|
+
const ov = httpSelf.reqStore.getStore();
|
|
395
|
+
const mergedQuery: Record<string, string> = {
|
|
396
|
+
...httpSelf.config.defaultQuery,
|
|
397
|
+
...(ov?.query ?? {}),
|
|
398
|
+
};
|
|
399
|
+
const rawUrl = typeof reqInput === "string"
|
|
400
|
+
? reqInput
|
|
401
|
+
: reqInput instanceof URL
|
|
402
|
+
? reqInput.toString()
|
|
403
|
+
: reqInput.url;
|
|
404
|
+
const finalUrl = mergeUrlQuery(rawUrl, mergedQuery);
|
|
405
|
+
|
|
406
|
+
const finalHeaders = new Headers(init?.headers);
|
|
407
|
+
if (ov?.headers) {
|
|
408
|
+
for (const [hk, hv] of Object.entries(ov.headers)) {
|
|
409
|
+
if (STRIPPED_HEADERS.has(hk.toLowerCase())) continue;
|
|
410
|
+
finalHeaders.set(hk, hv);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
// Attach Idempotency-Key ONLY when explicitly scoped to this single write via http.call({ idempotencyKey }).
|
|
414
|
+
if (ov?._callIdempotencyKey && !finalHeaders.has("idempotency-key")) {
|
|
415
|
+
finalHeaders.set("Idempotency-Key", ov._callIdempotencyKey);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const timeoutMs = ov?.timeout ?? httpSelf.config.timeout;
|
|
419
|
+
const ovSignal = ov?.signal;
|
|
420
|
+
const initSignal = init?.signal ?? undefined;
|
|
421
|
+
const hasTimeout = timeoutMs > 0 && Number.isFinite(timeoutMs);
|
|
422
|
+
|
|
423
|
+
if (ovSignal?.aborted) {
|
|
424
|
+
throw new CoreUserAbortError("Request was aborted.");
|
|
425
|
+
}
|
|
426
|
+
if (initSignal?.aborted) {
|
|
427
|
+
const reason = initSignal.reason;
|
|
428
|
+
if (reason instanceof Error) throw reason;
|
|
429
|
+
const abortErr = new Error("Request was aborted.");
|
|
430
|
+
abortErr.name = "AbortError";
|
|
431
|
+
throw abortErr;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
let controller: AbortController | null = null;
|
|
435
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
436
|
+
let onOvAbort: (() => void) | null = null;
|
|
437
|
+
let onInitAbort: (() => void) | null = null;
|
|
438
|
+
let effectiveSignal: AbortSignal | undefined;
|
|
439
|
+
let timedOut = false;
|
|
440
|
+
let userAborted = false;
|
|
441
|
+
let initAborted = false;
|
|
442
|
+
let settled = false;
|
|
443
|
+
let rejectRace: ((err: Error) => void) | null = null;
|
|
444
|
+
let racePromise: Promise<never> | null = null;
|
|
445
|
+
|
|
446
|
+
if (hasTimeout || ovSignal || initSignal) {
|
|
447
|
+
controller = new AbortController();
|
|
448
|
+
effectiveSignal = controller.signal;
|
|
449
|
+
racePromise = new Promise<never>((_resolve, reject) => {
|
|
450
|
+
rejectRace = reject;
|
|
451
|
+
});
|
|
452
|
+
// Prevent unhandled rejection if fetch/body completes before any race consumer attaches.
|
|
453
|
+
racePromise.catch(() => {});
|
|
454
|
+
|
|
455
|
+
if (ovSignal) {
|
|
456
|
+
onOvAbort = () => {
|
|
457
|
+
userAborted = true;
|
|
458
|
+
if (initSignal && onInitAbort) initSignal.removeEventListener("abort", onInitAbort);
|
|
459
|
+
const abortErr = new CoreUserAbortError("Request was aborted.");
|
|
460
|
+
controller?.abort(abortErr);
|
|
461
|
+
if (!settled && rejectRace) rejectRace(abortErr);
|
|
462
|
+
};
|
|
463
|
+
ovSignal.addEventListener("abort", onOvAbort, { once: true });
|
|
464
|
+
}
|
|
465
|
+
if (initSignal) {
|
|
466
|
+
onInitAbort = () => {
|
|
467
|
+
initAborted = true;
|
|
468
|
+
if (ovSignal && onOvAbort) ovSignal.removeEventListener("abort", onOvAbort);
|
|
469
|
+
const reason = initSignal.reason instanceof Error
|
|
470
|
+
? initSignal.reason
|
|
471
|
+
: Object.assign(new Error("Request was aborted."), { name: "AbortError" });
|
|
472
|
+
controller?.abort(reason);
|
|
473
|
+
if (!settled && rejectRace) rejectRace(reason);
|
|
474
|
+
};
|
|
475
|
+
initSignal.addEventListener("abort", onInitAbort, { once: true });
|
|
476
|
+
}
|
|
477
|
+
if (hasTimeout) {
|
|
478
|
+
timer = setTimeout(() => {
|
|
479
|
+
timedOut = true;
|
|
480
|
+
const err = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
481
|
+
err.name = "TimeoutError";
|
|
482
|
+
controller?.abort(err);
|
|
483
|
+
if (!settled && rejectRace) {
|
|
484
|
+
rejectRace(new CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`));
|
|
485
|
+
}
|
|
486
|
+
}, timeoutMs);
|
|
487
|
+
if (typeof (timer as unknown as { unref?: () => void }).unref === "function") {
|
|
488
|
+
(timer as unknown as { unref: () => void }).unref();
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const cleanupTimerAndListeners = (removeSignalListeners: boolean): void => {
|
|
494
|
+
settled = true;
|
|
495
|
+
if (timer !== null) {
|
|
496
|
+
clearTimeout(timer);
|
|
497
|
+
timer = null;
|
|
498
|
+
}
|
|
499
|
+
if (removeSignalListeners) {
|
|
500
|
+
if (ovSignal && onOvAbort) ovSignal.removeEventListener("abort", onOvAbort);
|
|
501
|
+
if (initSignal && onInitAbort) initSignal.removeEventListener("abort", onInitAbort);
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
try {
|
|
506
|
+
const fetchPromise = baseFetch(finalUrl, {
|
|
507
|
+
...init,
|
|
508
|
+
headers: finalHeaders,
|
|
509
|
+
signal: effectiveSignal,
|
|
510
|
+
});
|
|
511
|
+
// If a custom fetch ignores AbortSignal and resolves after timeout/abort, cancel its body.
|
|
512
|
+
fetchPromise.then(
|
|
513
|
+
(lateResp) => {
|
|
514
|
+
if (timedOut || userAborted || initAborted) {
|
|
515
|
+
try {
|
|
516
|
+
void lateResp.body?.cancel().catch(() => {});
|
|
517
|
+
} catch {
|
|
518
|
+
// Ignore cancel errors on already-locked/closed streams.
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
},
|
|
522
|
+
() => {},
|
|
523
|
+
);
|
|
524
|
+
const resp = await (racePromise ? Promise.race([fetchPromise, racePromise]) : fetchPromise);
|
|
525
|
+
if (ov?._rawBox) {
|
|
526
|
+
ov._rawBox.snap = { status: resp.status, headers: headersToRecord(resp.headers) };
|
|
527
|
+
}
|
|
528
|
+
const contentType = (resp.headers.get("content-type") ?? "").toLowerCase();
|
|
529
|
+
const isEventStream = contentType.includes("text/event-stream");
|
|
530
|
+
if (isEventStream) {
|
|
531
|
+
// SSE streams have their own idle timeout and can legitimately stay open longer than
|
|
532
|
+
// a single-request timeout; clear the request timer once headers arrive while keeping
|
|
533
|
+
// BOTH caller and stream-close signals wired so either aborts the underlying socket.
|
|
534
|
+
cleanupTimerAndListeners(!resp.body);
|
|
535
|
+
return resp;
|
|
536
|
+
}
|
|
537
|
+
if (resp.body && !NULL_BODY_STATUSES.has(resp.status)) {
|
|
538
|
+
// Keep the request timeout active until the full non-streaming body finishes arriving.
|
|
539
|
+
try {
|
|
540
|
+
const buf = await (racePromise
|
|
541
|
+
? Promise.race([resp.arrayBuffer(), racePromise])
|
|
542
|
+
: resp.arrayBuffer());
|
|
543
|
+
cleanupTimerAndListeners(true);
|
|
544
|
+
const buffered = new Response(buf, {
|
|
545
|
+
status: resp.status,
|
|
546
|
+
statusText: resp.statusText,
|
|
547
|
+
headers: resp.headers,
|
|
548
|
+
});
|
|
549
|
+
if (resp.url) {
|
|
550
|
+
try {
|
|
551
|
+
Object.defineProperty(buffered, "url", { value: resp.url });
|
|
552
|
+
} catch {
|
|
553
|
+
// Ignore if runtime makes Response.url non-configurable.
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
return buffered;
|
|
557
|
+
} catch (bodyErr) {
|
|
558
|
+
try {
|
|
559
|
+
void resp.body.cancel().catch(() => {});
|
|
560
|
+
} catch {
|
|
561
|
+
// Ignore cancel errors on already-locked/closed streams.
|
|
562
|
+
}
|
|
563
|
+
throw bodyErr;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
cleanupTimerAndListeners(true);
|
|
567
|
+
return resp;
|
|
568
|
+
} catch (err) {
|
|
569
|
+
cleanupTimerAndListeners(true);
|
|
570
|
+
if (userAborted || ovSignal?.aborted) {
|
|
571
|
+
throw new CoreUserAbortError("Request was aborted.");
|
|
572
|
+
}
|
|
573
|
+
if (timedOut) {
|
|
574
|
+
throw new CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`);
|
|
575
|
+
}
|
|
576
|
+
throw err;
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
this.sdkConfig = new Configuration({
|
|
581
|
+
basePath: this.config.baseURL,
|
|
582
|
+
accessToken: this.config.apiKey,
|
|
583
|
+
headers,
|
|
584
|
+
fetchApi: wrappedFetch,
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
newIdempotencyKey(): string {
|
|
589
|
+
return randomUUID();
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
async resolveHost(host: string): Promise<string[]> {
|
|
593
|
+
if (this.resolveHostFn) {
|
|
594
|
+
return [...(await this.resolveHostFn(host))];
|
|
595
|
+
}
|
|
596
|
+
const entries = await dnsLookup(host, { all: true });
|
|
597
|
+
const ips: string[] = [];
|
|
598
|
+
for (const entry of entries) {
|
|
599
|
+
if (entry.address && !ips.includes(entry.address)) {
|
|
600
|
+
ips.push(entry.address);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return ips;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
effectiveRemoteTimeoutMs(maxMs: number): number {
|
|
607
|
+
const ov = this.reqStore.getStore();
|
|
608
|
+
const configured = ov?.timeout ?? this.config.timeout;
|
|
609
|
+
if (configured > 0 && Number.isFinite(configured)) {
|
|
610
|
+
return Math.min(configured, maxMs);
|
|
611
|
+
}
|
|
612
|
+
return maxMs;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* Issue a raw HTTP request WITHOUT Sarvam Authorization, X-Panja-Origin, defaultHeaders, defaultQuery,
|
|
617
|
+
* or Idempotency-Key. Honors per-call AbortSignal and timeout (optionally capped by maxTimeoutMs or
|
|
618
|
+
* pinned by timeoutOverrideMs), and returns the raw unbuffered Response plus a cleanup handle and
|
|
619
|
+
* deadline race promise so callers can stream and cap response bodies safely.
|
|
620
|
+
*
|
|
621
|
+
* When ``opts.pinnedIp`` is supplied and no custom ``fetch`` override was provided, connects
|
|
622
|
+
* directly to ``opts.pinnedIp`` via ``node:http``/``node:https`` with original ``Host`` and TLS
|
|
623
|
+
* ``servername`` to eliminate the DNS rebinding TOCTOU window.
|
|
624
|
+
*/
|
|
625
|
+
async externalFetch(
|
|
626
|
+
url: string,
|
|
627
|
+
init: RequestInit = {},
|
|
628
|
+
opts: { maxTimeoutMs?: number; timeoutOverrideMs?: number; pinnedIp?: string | null } = {},
|
|
629
|
+
): Promise<{ response: Response; racePromise: Promise<never> | null; cleanup: () => void }> {
|
|
630
|
+
const ov = this.reqStore.getStore();
|
|
631
|
+
const ovSignal = ov?.signal;
|
|
632
|
+
if (ovSignal?.aborted) {
|
|
633
|
+
throw new CoreUserAbortError("Request was aborted.");
|
|
634
|
+
}
|
|
635
|
+
const configuredTimeout = ov?.timeout ?? this.config.timeout;
|
|
636
|
+
let timeoutMs = opts.timeoutOverrideMs ?? configuredTimeout;
|
|
637
|
+
if (opts.timeoutOverrideMs === undefined && opts.maxTimeoutMs !== undefined) {
|
|
638
|
+
timeoutMs = timeoutMs > 0 && Number.isFinite(timeoutMs)
|
|
639
|
+
? Math.min(timeoutMs, opts.maxTimeoutMs)
|
|
640
|
+
: opts.maxTimeoutMs;
|
|
641
|
+
}
|
|
642
|
+
const hasTimeout = timeoutMs > 0 && Number.isFinite(timeoutMs);
|
|
643
|
+
|
|
644
|
+
let controller: AbortController | null = null;
|
|
645
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
646
|
+
let onOvAbort: (() => void) | null = null;
|
|
647
|
+
let timedOut = false;
|
|
648
|
+
let userAborted = false;
|
|
649
|
+
let settled = false;
|
|
650
|
+
let rejectRace: ((err: Error) => void) | null = null;
|
|
651
|
+
let racePromise: Promise<never> | null = null;
|
|
652
|
+
|
|
653
|
+
if (hasTimeout || ovSignal) {
|
|
654
|
+
controller = new AbortController();
|
|
655
|
+
racePromise = new Promise<never>((_resolve, reject) => {
|
|
656
|
+
rejectRace = reject;
|
|
657
|
+
});
|
|
658
|
+
racePromise.catch(() => {});
|
|
659
|
+
|
|
660
|
+
if (ovSignal) {
|
|
661
|
+
onOvAbort = () => {
|
|
662
|
+
userAborted = true;
|
|
663
|
+
const abortErr = new CoreUserAbortError("Request was aborted.");
|
|
664
|
+
controller?.abort(abortErr);
|
|
665
|
+
if (!settled && rejectRace) rejectRace(abortErr);
|
|
666
|
+
};
|
|
667
|
+
ovSignal.addEventListener("abort", onOvAbort, { once: true });
|
|
668
|
+
}
|
|
669
|
+
if (hasTimeout) {
|
|
670
|
+
timer = setTimeout(() => {
|
|
671
|
+
timedOut = true;
|
|
672
|
+
const err = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
673
|
+
err.name = "TimeoutError";
|
|
674
|
+
controller?.abort(err);
|
|
675
|
+
if (!settled && rejectRace) {
|
|
676
|
+
rejectRace(new CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`));
|
|
677
|
+
}
|
|
678
|
+
}, timeoutMs);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const cleanup = (): void => {
|
|
683
|
+
settled = true;
|
|
684
|
+
if (timer !== null) {
|
|
685
|
+
clearTimeout(timer);
|
|
686
|
+
timer = null;
|
|
687
|
+
}
|
|
688
|
+
if (ovSignal && onOvAbort) {
|
|
689
|
+
ovSignal.removeEventListener("abort", onOvAbort);
|
|
690
|
+
onOvAbort = null;
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
try {
|
|
695
|
+
const fetchPromise =
|
|
696
|
+
opts.pinnedIp && !this.config.fetch
|
|
697
|
+
? pinnedNodeFetch(url, init, opts.pinnedIp, controller?.signal)
|
|
698
|
+
: this.baseFetch(url, {
|
|
699
|
+
...init,
|
|
700
|
+
redirect: "manual",
|
|
701
|
+
signal: controller?.signal,
|
|
702
|
+
});
|
|
703
|
+
fetchPromise.then(
|
|
704
|
+
(lateResp) => {
|
|
705
|
+
if (timedOut || userAborted) {
|
|
706
|
+
try {
|
|
707
|
+
void lateResp.body?.cancel().catch(() => {});
|
|
708
|
+
} catch {
|
|
709
|
+
// ignore
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
},
|
|
713
|
+
() => {},
|
|
714
|
+
);
|
|
715
|
+
const response = await (racePromise ? Promise.race([fetchPromise, racePromise]) : fetchPromise);
|
|
716
|
+
return { response, racePromise, cleanup };
|
|
717
|
+
} catch (err) {
|
|
718
|
+
cleanup();
|
|
719
|
+
if (userAborted || ovSignal?.aborted) {
|
|
720
|
+
throw new CoreUserAbortError("Request was aborted.");
|
|
721
|
+
}
|
|
722
|
+
if (timedOut) {
|
|
723
|
+
throw new CoreTimeoutError(`Request timed out after ${timeoutMs}ms.`);
|
|
724
|
+
}
|
|
725
|
+
throw err;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
withRequestOptions<T>(opts: PerCallRequestOptions | undefined, fn: () => Promise<T>): Promise<T> {
|
|
730
|
+
if (!opts) return fn();
|
|
731
|
+
const parent = this.reqStore.getStore();
|
|
732
|
+
const merged: InternalRequestContext = {
|
|
733
|
+
timeout: opts.timeout ?? parent?.timeout,
|
|
734
|
+
maxRetries: opts.maxRetries ?? parent?.maxRetries,
|
|
735
|
+
headers: { ...(parent?.headers ?? {}), ...(opts.headers ?? {}) },
|
|
736
|
+
query: { ...(parent?.query ?? {}), ...(opts.query ?? {}) },
|
|
737
|
+
signal: opts.signal ?? parent?.signal,
|
|
738
|
+
idempotencyKey: opts.idempotencyKey ?? parent?.idempotencyKey,
|
|
739
|
+
_callIdempotencyKey: parent?._callIdempotencyKey,
|
|
740
|
+
_rawBox: parent?._rawBox,
|
|
741
|
+
};
|
|
742
|
+
return this.reqStore.run(merged, fn);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
async captureRawResponse<T>(fn: () => Promise<T>): Promise<{ data: T; raw: RawResponseSnapshot | null }> {
|
|
746
|
+
const parent = this.reqStore.getStore();
|
|
747
|
+
const box: { snap: RawResponseSnapshot | null } = { snap: null };
|
|
748
|
+
const ctx: InternalRequestContext = {
|
|
749
|
+
...(parent ?? {}),
|
|
750
|
+
_rawBox: box,
|
|
751
|
+
};
|
|
752
|
+
const data = await this.reqStore.run(ctx, fn);
|
|
753
|
+
return { data, raw: box.snap };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async call<T>(
|
|
757
|
+
fn: () => Promise<T>,
|
|
758
|
+
opts: { idempotent?: boolean; maxRetries?: number; idempotencyKey?: string } = {},
|
|
759
|
+
): Promise<T> {
|
|
760
|
+
const ov = this.reqStore.getStore();
|
|
761
|
+
const idempotent = opts.idempotent ?? true;
|
|
762
|
+
const configuredMax = opts.maxRetries ?? ov?.maxRetries ?? this.config.maxRetries;
|
|
763
|
+
const limit = idempotent ? Math.max(0, configuredMax) : 0;
|
|
764
|
+
let attempt = 0;
|
|
765
|
+
for (;;) {
|
|
766
|
+
try {
|
|
767
|
+
if (opts.idempotencyKey !== undefined) {
|
|
768
|
+
const ctx: InternalRequestContext = {
|
|
769
|
+
...(ov ?? {}),
|
|
770
|
+
_callIdempotencyKey: opts.idempotencyKey,
|
|
771
|
+
};
|
|
772
|
+
return await this.reqStore.run(ctx, fn);
|
|
773
|
+
}
|
|
774
|
+
return await fn();
|
|
775
|
+
} catch (raw) {
|
|
776
|
+
if (raw instanceof UserError || raw instanceof NotSupportedByServerError) throw raw;
|
|
777
|
+
const err = await this.toCoreError(raw);
|
|
778
|
+
if (attempt >= limit || !shouldRetry(err)) throw err;
|
|
779
|
+
const retryAfter = parseRetryAfterMs(err.headers);
|
|
780
|
+
const delay = retryAfter ?? this.jitterFn(Math.min(500 * 2 ** attempt, MAX_BACKOFF_MS));
|
|
781
|
+
await this.sleepFn(delay);
|
|
782
|
+
attempt += 1;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
private async toCoreError(raw: unknown): Promise<CoreAPIError> {
|
|
788
|
+
if (raw instanceof CoreAPIError) return raw;
|
|
789
|
+
if (raw instanceof ResponseError) {
|
|
790
|
+
const hdrs = headersToRecord(raw.response.headers);
|
|
791
|
+
let text = "";
|
|
792
|
+
try {
|
|
793
|
+
text = await raw.response.clone().text();
|
|
794
|
+
} catch {
|
|
795
|
+
text = "";
|
|
796
|
+
}
|
|
797
|
+
return mapPanjaError(raw.response.status, text, hdrs);
|
|
798
|
+
}
|
|
799
|
+
if (raw instanceof FetchError) {
|
|
800
|
+
const cause = (raw as unknown as { cause?: unknown }).cause;
|
|
801
|
+
if (cause instanceof CoreAPIError) return cause;
|
|
802
|
+
if (cause instanceof Error) {
|
|
803
|
+
if (cause.name === "TimeoutError") {
|
|
804
|
+
return new CoreTimeoutError(`Request timed out: ${cause.message}`);
|
|
805
|
+
}
|
|
806
|
+
if (cause.name === "AbortError") {
|
|
807
|
+
const ov = this.reqStore.getStore();
|
|
808
|
+
if (ov?.signal?.aborted) return new CoreUserAbortError("Request was aborted.");
|
|
809
|
+
return new CoreTimeoutError(`Request timed out: ${cause.message}`);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return new CoreConnectionError(`Connection error: ${raw.message}`);
|
|
813
|
+
}
|
|
814
|
+
if (raw instanceof Error) {
|
|
815
|
+
if (raw.name === "TimeoutError") {
|
|
816
|
+
return new CoreTimeoutError(`Request timed out: ${raw.message}`);
|
|
817
|
+
}
|
|
818
|
+
if (raw.name === "AbortError") {
|
|
819
|
+
const ov = this.reqStore.getStore();
|
|
820
|
+
if (ov?.signal?.aborted) return new CoreUserAbortError("Request was aborted.");
|
|
821
|
+
return new CoreTimeoutError(`Request timed out: ${raw.message}`);
|
|
822
|
+
}
|
|
823
|
+
return new CoreConnectionError(`Connection error: ${raw.message}`);
|
|
824
|
+
}
|
|
825
|
+
return new CoreConnectionError(`Connection error: ${String(raw)}`);
|
|
826
|
+
}
|
|
827
|
+
}
|