@gradiated/grad 0.0.0-stage → 0.2.0-alpha.1
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/LICENSE +21 -0
- package/README.md +83 -2
- package/dist/client.d.ts +71 -0
- package/dist/client.js +188 -0
- package/dist/config.d.ts +21 -0
- package/dist/config.js +90 -0
- package/dist/core.d.ts +13 -0
- package/dist/core.js +1 -0
- package/dist/errors.d.ts +37 -0
- package/dist/errors.js +70 -0
- package/dist/generated/client.d.ts +532 -0
- package/dist/generated/client.js +596 -0
- package/dist/generated/index.d.ts +2 -0
- package/dist/generated/index.js +3 -0
- package/dist/generated/models.d.ts +998 -0
- package/dist/generated/models.js +9 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +16 -0
- package/dist/node/files.d.ts +26 -0
- package/dist/node/files.js +130 -0
- package/dist/pagination.d.ts +39 -0
- package/dist/pagination.js +73 -0
- package/dist/pending.d.ts +14 -0
- package/dist/pending.js +20 -0
- package/dist/polling.d.ts +25 -0
- package/dist/polling.js +63 -0
- package/dist/recipes.d.ts +220 -0
- package/dist/recipes.js +255 -0
- package/dist/resources/artifacts.d.ts +82 -0
- package/dist/resources/artifacts.js +122 -0
- package/dist/resources/datasets.d.ts +178 -0
- package/dist/resources/datasets.js +318 -0
- package/dist/resources/evals.d.ts +110 -0
- package/dist/resources/evals.js +258 -0
- package/dist/resources/misc.d.ts +31 -0
- package/dist/resources/misc.js +45 -0
- package/dist/resources/runs.d.ts +119 -0
- package/dist/resources/runs.js +245 -0
- package/dist/resources/sources.d.ts +118 -0
- package/dist/resources/sources.js +156 -0
- package/dist/rubrics.d.ts +87 -0
- package/dist/rubrics.js +167 -0
- package/dist/trajectory.d.ts +16 -0
- package/dist/trajectory.js +13 -0
- package/dist/transport.d.ts +229 -0
- package/dist/transport.js +678 -0
- package/package.json +53 -4
|
@@ -0,0 +1,678 @@
|
|
|
1
|
+
/* HTTP runtime (hand-written) shared by every generated operation: typed errors, retries with
|
|
2
|
+
* backoff and Retry-After (POSTs carry one Idempotency-Key across retries, so
|
|
3
|
+
* they retry like GETs), same-origin-only redirects, per-attempt timeouts
|
|
4
|
+
* that stop at the response headers for streams, SSE parsing, request ids,
|
|
5
|
+
* and the camelCase <-> wire key codec. Browser-safe: no Node imports. */
|
|
6
|
+
export const SDK_VERSION = "0.2.0-alpha.1";
|
|
7
|
+
const nodeProcess = () => globalThis.process;
|
|
8
|
+
export const readEnv = (name) => {
|
|
9
|
+
const value = nodeProcess()?.env?.[name];
|
|
10
|
+
return value === undefined || value === "" ? undefined : value;
|
|
11
|
+
};
|
|
12
|
+
/** Base class of every error the SDK throws. */
|
|
13
|
+
export class GradError extends Error {
|
|
14
|
+
status;
|
|
15
|
+
code;
|
|
16
|
+
requestId;
|
|
17
|
+
constructor(message, init) {
|
|
18
|
+
super(message, init.cause === undefined ? undefined : { cause: init.cause });
|
|
19
|
+
this.name = new.target.name;
|
|
20
|
+
this.status = init.status;
|
|
21
|
+
this.code = init.code;
|
|
22
|
+
this.requestId = init.requestId;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** The server answered with a non-2xx status (RFC 7807 problem+json when it can). */
|
|
26
|
+
export class APIError extends GradError {
|
|
27
|
+
title;
|
|
28
|
+
detail;
|
|
29
|
+
type;
|
|
30
|
+
method;
|
|
31
|
+
url;
|
|
32
|
+
headers;
|
|
33
|
+
body;
|
|
34
|
+
fieldErrors;
|
|
35
|
+
retryAfterMs;
|
|
36
|
+
constructor(message, init) {
|
|
37
|
+
super(message, {
|
|
38
|
+
status: init.status,
|
|
39
|
+
code: init.code,
|
|
40
|
+
requestId: init.requestId,
|
|
41
|
+
});
|
|
42
|
+
this.title = init.title;
|
|
43
|
+
this.detail = init.detail;
|
|
44
|
+
this.type = init.type;
|
|
45
|
+
this.method = init.method;
|
|
46
|
+
this.url = init.url;
|
|
47
|
+
this.headers = init.headers;
|
|
48
|
+
this.body = init.body;
|
|
49
|
+
this.fieldErrors = init.fieldErrors;
|
|
50
|
+
this.retryAfterMs = init.retryAfterMs;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export class BadRequestError extends APIError {
|
|
54
|
+
}
|
|
55
|
+
export class AuthenticationError extends APIError {
|
|
56
|
+
}
|
|
57
|
+
export class PermissionDeniedError extends APIError {
|
|
58
|
+
}
|
|
59
|
+
export class NotFoundError extends APIError {
|
|
60
|
+
}
|
|
61
|
+
export class ConflictError extends APIError {
|
|
62
|
+
}
|
|
63
|
+
export class ValidationError extends APIError {
|
|
64
|
+
}
|
|
65
|
+
export class RateLimitError extends APIError {
|
|
66
|
+
}
|
|
67
|
+
export class ServerError extends APIError {
|
|
68
|
+
}
|
|
69
|
+
/** 501 `deploy_unavailable`: this server has no Cloud serving (self-hosted); download the artifact and serve it yourself. */
|
|
70
|
+
export class DeployUnavailableError extends APIError {
|
|
71
|
+
}
|
|
72
|
+
/** 501 `inference_unavailable`: no inference endpoint is configured, so evals cannot generate outputs. */
|
|
73
|
+
export class InferenceUnavailableError extends APIError {
|
|
74
|
+
}
|
|
75
|
+
/** The request never produced an HTTP response (DNS, refused, reset, TLS). */
|
|
76
|
+
export class APIConnectionError extends GradError {
|
|
77
|
+
}
|
|
78
|
+
/** The per-request timeout elapsed before a response (or a stream went idle). */
|
|
79
|
+
export class APITimeoutError extends APIConnectionError {
|
|
80
|
+
}
|
|
81
|
+
/** The caller's AbortSignal fired. */
|
|
82
|
+
export class APIUserAbortError extends GradError {
|
|
83
|
+
}
|
|
84
|
+
/** A redirect would leave the API origin (or change the method); refused so credentials never leak. */
|
|
85
|
+
export class RedirectError extends GradError {
|
|
86
|
+
}
|
|
87
|
+
/** A 2xx response body was not valid JSON. */
|
|
88
|
+
export class ResponseDecodeError extends GradError {
|
|
89
|
+
}
|
|
90
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
91
|
+
const str = (value) => typeof value === "string" && value !== "" ? value : undefined;
|
|
92
|
+
/** Parses `a.b: message; c: other` (the server's validation detail) or a problem `errors` array. */
|
|
93
|
+
export const parseFieldErrors = (body, detail) => {
|
|
94
|
+
if (isObject(body) && Array.isArray(body.errors)) {
|
|
95
|
+
return body.errors.flatMap((item) => {
|
|
96
|
+
if (!isObject(item))
|
|
97
|
+
return [];
|
|
98
|
+
const field = str(item.field) ??
|
|
99
|
+
(Array.isArray(item.path) ? item.path.join(".") : undefined) ??
|
|
100
|
+
str(item.pointer) ??
|
|
101
|
+
"";
|
|
102
|
+
return [{ field, message: str(item.message) ?? str(item.detail) ?? "" }];
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return detail
|
|
106
|
+
.split("; ")
|
|
107
|
+
.map((part) => /^([A-Za-z0-9_.[\]-]+): (.+)$/s.exec(part))
|
|
108
|
+
.filter((m) => m !== null)
|
|
109
|
+
.map((m) => ({ field: m[1] ?? "", message: m[2] ?? "" }));
|
|
110
|
+
};
|
|
111
|
+
export const parseRetryAfterMs = (headers, now = Date.now()) => {
|
|
112
|
+
const ms = headers.get("retry-after-ms");
|
|
113
|
+
if (ms !== null && /^\d+(\.\d+)?$/.test(ms.trim()))
|
|
114
|
+
return Number(ms);
|
|
115
|
+
const raw = headers.get("retry-after");
|
|
116
|
+
if (raw === null)
|
|
117
|
+
return undefined;
|
|
118
|
+
const value = raw.trim();
|
|
119
|
+
if (/^\d+(\.\d+)?$/.test(value))
|
|
120
|
+
return Number(value) * 1000;
|
|
121
|
+
const date = Date.parse(value);
|
|
122
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - now);
|
|
123
|
+
};
|
|
124
|
+
const errorClassFor = (status, code) => {
|
|
125
|
+
if (code === "deploy_unavailable")
|
|
126
|
+
return DeployUnavailableError;
|
|
127
|
+
if (code === "inference_unavailable")
|
|
128
|
+
return InferenceUnavailableError;
|
|
129
|
+
if (status === 400)
|
|
130
|
+
return BadRequestError;
|
|
131
|
+
if (status === 401)
|
|
132
|
+
return AuthenticationError;
|
|
133
|
+
if (status === 403)
|
|
134
|
+
return PermissionDeniedError;
|
|
135
|
+
if (status === 404)
|
|
136
|
+
return NotFoundError;
|
|
137
|
+
if (status === 409)
|
|
138
|
+
return ConflictError;
|
|
139
|
+
if (status === 422)
|
|
140
|
+
return ValidationError;
|
|
141
|
+
if (status === 429)
|
|
142
|
+
return RateLimitError;
|
|
143
|
+
if (status >= 500)
|
|
144
|
+
return ServerError;
|
|
145
|
+
return APIError;
|
|
146
|
+
};
|
|
147
|
+
/** Builds the typed error for a non-2xx response; tolerant of any body shape. */
|
|
148
|
+
export const makeAPIError = (status, headers, text, ctx) => {
|
|
149
|
+
let body = text;
|
|
150
|
+
try {
|
|
151
|
+
body = text.trim() === "" ? undefined : JSON.parse(text);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
// Non-JSON body (proxy HTML, plain text): keep the raw text.
|
|
155
|
+
}
|
|
156
|
+
const problem = isObject(body) ? body : {};
|
|
157
|
+
const code = str(problem.code) ?? `http_${status}`;
|
|
158
|
+
const title = str(problem.title) ?? `HTTP ${status}`;
|
|
159
|
+
const detail = str(problem.detail) ??
|
|
160
|
+
str(problem.message) ??
|
|
161
|
+
(typeof body === "string" ? body.slice(0, 500).trim() : "");
|
|
162
|
+
const requestId = headers.get("x-request-id") ?? str(problem.request_id);
|
|
163
|
+
let hint = "";
|
|
164
|
+
if (status === 401 && !ctx.apiKeyConfigured) {
|
|
165
|
+
hint =
|
|
166
|
+
" No API key is configured: set GRADIATED_API_KEY, pass `apiKey`, or run `grad login`.";
|
|
167
|
+
}
|
|
168
|
+
const message = `${ctx.method} ${ctx.url} returned ${status} ${code}${detail ? `: ${detail}` : ""}${hint}${requestId ? ` (request_id ${requestId})` : ""}`;
|
|
169
|
+
const ErrorClass = errorClassFor(status, code);
|
|
170
|
+
return new ErrorClass(message, {
|
|
171
|
+
status,
|
|
172
|
+
code,
|
|
173
|
+
title,
|
|
174
|
+
detail,
|
|
175
|
+
type: str(problem.type) ?? "about:blank",
|
|
176
|
+
requestId,
|
|
177
|
+
method: ctx.method,
|
|
178
|
+
url: ctx.url,
|
|
179
|
+
headers,
|
|
180
|
+
body,
|
|
181
|
+
fieldErrors: status === 422 ? parseFieldErrors(body, detail) : [],
|
|
182
|
+
retryAfterMs: parseRetryAfterMs(headers),
|
|
183
|
+
});
|
|
184
|
+
};
|
|
185
|
+
const indexCache = new WeakMap();
|
|
186
|
+
const fieldIndex = (node) => {
|
|
187
|
+
let index = indexCache.get(node);
|
|
188
|
+
if (!index) {
|
|
189
|
+
index = { byWire: new Map(), byCamel: new Map() };
|
|
190
|
+
for (const [camel, wire, child] of node.o) {
|
|
191
|
+
index.byWire.set(wire, [camel, child]);
|
|
192
|
+
index.byCamel.set(camel, [wire, child]);
|
|
193
|
+
}
|
|
194
|
+
indexCache.set(node, index);
|
|
195
|
+
}
|
|
196
|
+
return index;
|
|
197
|
+
};
|
|
198
|
+
/** Renames declared keys between camelCase and wire names; user-keyed maps stay verbatim. */
|
|
199
|
+
export const convertKeys = (table, node, value, direction) => {
|
|
200
|
+
if (node === 0 || value === null || value === undefined)
|
|
201
|
+
return value;
|
|
202
|
+
if (typeof node === "string") {
|
|
203
|
+
const target = table[node];
|
|
204
|
+
return target === undefined ? value : convertKeys(table, target, value, direction);
|
|
205
|
+
}
|
|
206
|
+
if ("a" in node) {
|
|
207
|
+
return Array.isArray(value)
|
|
208
|
+
? value.map((item) => convertKeys(table, node.a, item, direction))
|
|
209
|
+
: value;
|
|
210
|
+
}
|
|
211
|
+
if ("m" in node) {
|
|
212
|
+
if (!isObject(value))
|
|
213
|
+
return value;
|
|
214
|
+
const out = {};
|
|
215
|
+
for (const [key, item] of Object.entries(value)) {
|
|
216
|
+
out[key] = convertKeys(table, node.m, item, direction);
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
if ("u" in node) {
|
|
221
|
+
if (Array.isArray(value) && node.u.a !== undefined) {
|
|
222
|
+
return convertKeys(table, node.u.a, value, direction);
|
|
223
|
+
}
|
|
224
|
+
if (isObject(value) && node.u.o !== undefined) {
|
|
225
|
+
return convertKeys(table, node.u.o, value, direction);
|
|
226
|
+
}
|
|
227
|
+
return value;
|
|
228
|
+
}
|
|
229
|
+
if (!isObject(value))
|
|
230
|
+
return value;
|
|
231
|
+
const index = fieldIndex(node);
|
|
232
|
+
const lookup = direction === "decode" ? index.byWire : index.byCamel;
|
|
233
|
+
const out = {};
|
|
234
|
+
for (const [key, item] of Object.entries(value)) {
|
|
235
|
+
if (item === undefined)
|
|
236
|
+
continue;
|
|
237
|
+
const field = lookup.get(key);
|
|
238
|
+
if (field) {
|
|
239
|
+
out[field[0]] = convertKeys(table, field[1], item, direction);
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
out[key] = node.x === undefined ? item : convertKeys(table, node.x, item, direction);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return out;
|
|
246
|
+
};
|
|
247
|
+
export const DEFAULT_TIMEOUT_MS = 60_000;
|
|
248
|
+
export const DEFAULT_MAX_RETRIES = 2;
|
|
249
|
+
export const DEFAULT_IDLE_TIMEOUT_MS = 120_000;
|
|
250
|
+
export const MAX_RETRY_AFTER_MS = 60_000;
|
|
251
|
+
const MAX_REDIRECTS = 5;
|
|
252
|
+
const IDEMPOTENT = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
|
|
253
|
+
const RETRY_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
|
|
254
|
+
const NEVER_SENT_CODES = new Set([
|
|
255
|
+
"ECONNREFUSED",
|
|
256
|
+
"ENOTFOUND",
|
|
257
|
+
"EAI_AGAIN",
|
|
258
|
+
"EHOSTUNREACH",
|
|
259
|
+
"ENETUNREACH",
|
|
260
|
+
"EADDRNOTAVAIL",
|
|
261
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
262
|
+
]);
|
|
263
|
+
const TIMEOUT = Symbol("timeout");
|
|
264
|
+
export const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
265
|
+
if (signal?.aborted) {
|
|
266
|
+
reject(signal.reason);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
const onAbort = () => {
|
|
270
|
+
clearTimeout(timer);
|
|
271
|
+
reject(signal?.reason);
|
|
272
|
+
};
|
|
273
|
+
const timer = setTimeout(() => {
|
|
274
|
+
signal?.removeEventListener("abort", onAbort);
|
|
275
|
+
resolve();
|
|
276
|
+
}, ms);
|
|
277
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
278
|
+
});
|
|
279
|
+
const errorCodes = (error, depth = 0) => {
|
|
280
|
+
if (!isObject(error) && !(error instanceof Error))
|
|
281
|
+
return [];
|
|
282
|
+
if (depth > 4)
|
|
283
|
+
return [];
|
|
284
|
+
const e = error;
|
|
285
|
+
const codes = typeof e.code === "string" ? [e.code] : [];
|
|
286
|
+
if (e.cause !== undefined)
|
|
287
|
+
codes.push(...errorCodes(e.cause, depth + 1));
|
|
288
|
+
if (Array.isArray(e.errors)) {
|
|
289
|
+
for (const inner of e.errors)
|
|
290
|
+
codes.push(...errorCodes(inner, depth + 1));
|
|
291
|
+
}
|
|
292
|
+
return codes;
|
|
293
|
+
};
|
|
294
|
+
const describeCause = (error) => {
|
|
295
|
+
const codes = errorCodes(error);
|
|
296
|
+
const cause = error?.cause;
|
|
297
|
+
const text = cause instanceof Error ? cause.message : error instanceof Error ? error.message : String(error);
|
|
298
|
+
return codes.length > 0 && !text.includes(codes[0] ?? "") ? `${codes[0]}: ${text}` : text;
|
|
299
|
+
};
|
|
300
|
+
/** A UUIDv4 for the Idempotency-Key header. */
|
|
301
|
+
export const newIdempotencyKey = () => globalThis.crypto.randomUUID();
|
|
302
|
+
export const encodePathParam = (value, name) => {
|
|
303
|
+
const text = typeof value === "string" ? value : String(value ?? "");
|
|
304
|
+
if (text === "" || text === "." || text === "..") {
|
|
305
|
+
throw new GradError(`Path parameter '${name}' must be a non-empty value other than '.' or '..'.`, {
|
|
306
|
+
code: "invalid_path_parameter",
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
return encodeURIComponent(text);
|
|
310
|
+
};
|
|
311
|
+
const scalar = (value) => typeof value === "string" ? value : typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
312
|
+
export const defaultUserAgent = () => {
|
|
313
|
+
const version = nodeProcess()?.version;
|
|
314
|
+
return version ? `grad-typescript/${SDK_VERSION} node/${version}` : undefined;
|
|
315
|
+
};
|
|
316
|
+
export class Transport {
|
|
317
|
+
baseURL;
|
|
318
|
+
origin;
|
|
319
|
+
apiKey;
|
|
320
|
+
timeoutMs;
|
|
321
|
+
maxRetries;
|
|
322
|
+
fetchImpl;
|
|
323
|
+
defaultHeaders;
|
|
324
|
+
userAgent;
|
|
325
|
+
sleep;
|
|
326
|
+
random;
|
|
327
|
+
constructor(options) {
|
|
328
|
+
let parsed;
|
|
329
|
+
try {
|
|
330
|
+
parsed = new URL(options.baseURL);
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
throw new GradError(`Invalid base URL '${options.baseURL}': it must be an absolute http(s) URL.`, {
|
|
334
|
+
code: "invalid_base_url",
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
338
|
+
throw new GradError(`Invalid base URL '${options.baseURL}': only http and https are supported (include the scheme, e.g. http://localhost:8787).`, {
|
|
339
|
+
code: "invalid_base_url",
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
this.baseURL = options.baseURL.replace(/\/+$/, "");
|
|
343
|
+
this.origin = parsed.origin;
|
|
344
|
+
this.apiKey = options.apiKey;
|
|
345
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
346
|
+
this.maxRetries = Math.max(0, options.maxRetries ?? DEFAULT_MAX_RETRIES);
|
|
347
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
348
|
+
if (typeof fetchImpl !== "function") {
|
|
349
|
+
throw new GradError("No fetch implementation available; pass `fetch` (Node 20+ has one built in).", {
|
|
350
|
+
code: "no_fetch",
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
this.fetchImpl = fetchImpl;
|
|
354
|
+
this.defaultHeaders = options.defaultHeaders ?? {};
|
|
355
|
+
this.userAgent = options.userAgent ?? defaultUserAgent();
|
|
356
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
357
|
+
this.random = options.random ?? Math.random;
|
|
358
|
+
}
|
|
359
|
+
buildURL(spec) {
|
|
360
|
+
const url = new URL(`${this.baseURL}${spec.path}`);
|
|
361
|
+
for (const [name, value] of spec.query ?? []) {
|
|
362
|
+
if (value === undefined || value === null)
|
|
363
|
+
continue;
|
|
364
|
+
if (Array.isArray(value)) {
|
|
365
|
+
for (const item of value) {
|
|
366
|
+
if (item !== undefined && item !== null)
|
|
367
|
+
url.searchParams.append(name, scalar(item));
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
else {
|
|
371
|
+
url.searchParams.append(name, scalar(value));
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return url.toString();
|
|
375
|
+
}
|
|
376
|
+
async resolveKey() {
|
|
377
|
+
const key = typeof this.apiKey === "function" ? await this.apiKey() : this.apiKey;
|
|
378
|
+
return key === "" ? undefined : key;
|
|
379
|
+
}
|
|
380
|
+
/** Exponential backoff with jitter: 0.5 s, 1 s, 2 s ... capped at 8 s, scaled into [50%, 100%]. */
|
|
381
|
+
backoffMs(attempt) {
|
|
382
|
+
const base = Math.min(8_000, 500 * 2 ** attempt);
|
|
383
|
+
return Math.round(base * (0.5 + this.random() * 0.5));
|
|
384
|
+
}
|
|
385
|
+
async headersFor(spec, options) {
|
|
386
|
+
const headers = new Headers(this.defaultHeaders);
|
|
387
|
+
if (this.userAgent)
|
|
388
|
+
headers.set("User-Agent", this.userAgent);
|
|
389
|
+
headers.set("Accept", spec.accept ?? "application/json");
|
|
390
|
+
const key = await this.resolveKey();
|
|
391
|
+
if (key)
|
|
392
|
+
headers.set("Authorization", `Bearer ${key}`);
|
|
393
|
+
if (spec.json !== undefined)
|
|
394
|
+
headers.set("Content-Type", "application/json");
|
|
395
|
+
for (const [name, value] of spec.headers ?? []) {
|
|
396
|
+
if (value !== undefined && value !== null)
|
|
397
|
+
headers.set(name, scalar(value));
|
|
398
|
+
}
|
|
399
|
+
for (const [name, value] of Object.entries(options?.headers ?? {}))
|
|
400
|
+
headers.set(name, value);
|
|
401
|
+
if (options?.idempotencyKey !== undefined)
|
|
402
|
+
headers.set("Idempotency-Key", options.idempotencyKey);
|
|
403
|
+
else if (spec.idempotent && !headers.has("Idempotency-Key"))
|
|
404
|
+
headers.set("Idempotency-Key", newIdempotencyKey());
|
|
405
|
+
return { headers, authed: Boolean(key) };
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Sends with retries and same-origin redirects. Returns the successful
|
|
409
|
+
* response plus a `done` callback that releases the attempt's timer/signal.
|
|
410
|
+
* When `streaming`, the timeout stops once headers arrive.
|
|
411
|
+
*/
|
|
412
|
+
async send(spec, options, streaming) {
|
|
413
|
+
const method = spec.method.toUpperCase();
|
|
414
|
+
const maxRetries = Math.max(0, options?.maxRetries ?? this.maxRetries);
|
|
415
|
+
const timeoutMs = options?.timeoutMs ?? this.timeoutMs;
|
|
416
|
+
const userSignal = options?.signal;
|
|
417
|
+
const { headers, authed } = await this.headersFor(spec, options);
|
|
418
|
+
const keyed = headers.has("Idempotency-Key");
|
|
419
|
+
const idempotent = IDEMPOTENT.has(method) || keyed;
|
|
420
|
+
const body = spec.json === undefined ? spec.body : JSON.stringify(spec.json);
|
|
421
|
+
let url = this.buildURL(spec);
|
|
422
|
+
let redirects = 0;
|
|
423
|
+
for (let attempt = 0;; attempt += 1) {
|
|
424
|
+
if (userSignal?.aborted)
|
|
425
|
+
throw this.abortError(method, url, userSignal.reason);
|
|
426
|
+
const controller = new AbortController();
|
|
427
|
+
const onUserAbort = () => controller.abort(userSignal?.reason);
|
|
428
|
+
userSignal?.addEventListener("abort", onUserAbort, { once: true });
|
|
429
|
+
let timer = setTimeout(() => controller.abort(TIMEOUT), timeoutMs);
|
|
430
|
+
const done = () => {
|
|
431
|
+
if (timer !== undefined)
|
|
432
|
+
clearTimeout(timer);
|
|
433
|
+
timer = undefined;
|
|
434
|
+
userSignal?.removeEventListener("abort", onUserAbort);
|
|
435
|
+
};
|
|
436
|
+
let response;
|
|
437
|
+
try {
|
|
438
|
+
response = await this.fetchImpl(url, {
|
|
439
|
+
method,
|
|
440
|
+
headers,
|
|
441
|
+
redirect: "manual",
|
|
442
|
+
signal: controller.signal,
|
|
443
|
+
...(body !== undefined ? { body } : {}),
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
done();
|
|
448
|
+
if (userSignal?.aborted)
|
|
449
|
+
throw this.abortError(method, url, userSignal.reason);
|
|
450
|
+
const timedOut = controller.signal.reason === TIMEOUT;
|
|
451
|
+
const neverSent = errorCodes(error).some((code) => NEVER_SENT_CODES.has(code));
|
|
452
|
+
const wrapped = timedOut
|
|
453
|
+
? new APITimeoutError(`${method} ${url} timed out after ${timeoutMs} ms.`, { code: "timeout", cause: error })
|
|
454
|
+
: new APIConnectionError(`${method} ${url} failed: could not reach ${this.origin} (${describeCause(error)}). Is the server running? Check GRADIATED_BASE_URL or \`baseURL\`.`, { code: "connection_error", cause: error });
|
|
455
|
+
if (attempt < maxRetries && (idempotent || (neverSent && !timedOut))) {
|
|
456
|
+
await this.wait(this.backoffMs(attempt), userSignal, method, url);
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
throw wrapped;
|
|
460
|
+
}
|
|
461
|
+
if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400 && response.status !== 304)) {
|
|
462
|
+
done();
|
|
463
|
+
await response.body?.cancel().catch(() => undefined);
|
|
464
|
+
const location = response.headers.get("location");
|
|
465
|
+
const target = location ? new URL(location, url) : undefined;
|
|
466
|
+
if (target && target.origin === this.origin && (method === "GET" || method === "HEAD") && redirects < MAX_REDIRECTS) {
|
|
467
|
+
redirects += 1;
|
|
468
|
+
url = target.toString();
|
|
469
|
+
attempt -= 1;
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
throw new RedirectError(`${method} ${url} was redirected (${response.status || "opaque"}) to ${target?.toString() ?? "an unknown location"}; refusing to follow a redirect that leaves ${this.origin} or changes a ${method} request, so credentials are never sent elsewhere. Point GRADIATED_BASE_URL at the final URL.`, { status: response.status || undefined, code: "redirect_refused", requestId: response.headers.get("x-request-id") ?? undefined });
|
|
473
|
+
}
|
|
474
|
+
if (!response.ok) {
|
|
475
|
+
let text = "";
|
|
476
|
+
try {
|
|
477
|
+
text = await response.text();
|
|
478
|
+
}
|
|
479
|
+
catch {
|
|
480
|
+
// Body unreadable; the status alone still classifies the error.
|
|
481
|
+
}
|
|
482
|
+
done();
|
|
483
|
+
const error = makeAPIError(response.status, response.headers, text, { method, url, apiKeyConfigured: authed });
|
|
484
|
+
// 409 + Retry-After on a keyed request: the first attempt is still running server-side.
|
|
485
|
+
const inProgress = response.status === 409 && keyed && error.retryAfterMs !== undefined;
|
|
486
|
+
const retryable = (RETRY_STATUSES.has(response.status) && (idempotent || response.status === 429)) || inProgress;
|
|
487
|
+
if (retryable && attempt < maxRetries) {
|
|
488
|
+
const retryAfter = error.retryAfterMs;
|
|
489
|
+
if (retryAfter === undefined || retryAfter <= MAX_RETRY_AFTER_MS) {
|
|
490
|
+
await this.wait(retryAfter ?? this.backoffMs(attempt), userSignal, method, url);
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
options?.onResponse?.({ status: response.status, headers: response.headers, requestId: error.requestId, url });
|
|
495
|
+
throw error;
|
|
496
|
+
}
|
|
497
|
+
if (streaming) {
|
|
498
|
+
if (timer !== undefined)
|
|
499
|
+
clearTimeout(timer);
|
|
500
|
+
timer = undefined;
|
|
501
|
+
}
|
|
502
|
+
options?.onResponse?.({
|
|
503
|
+
status: response.status,
|
|
504
|
+
headers: response.headers,
|
|
505
|
+
requestId: response.headers.get("x-request-id") ?? undefined,
|
|
506
|
+
url,
|
|
507
|
+
});
|
|
508
|
+
return { response, url, done, signal: controller.signal, abort: (reason) => controller.abort(reason) };
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
async wait(ms, signal, method, url) {
|
|
512
|
+
try {
|
|
513
|
+
await this.sleep(ms, signal);
|
|
514
|
+
}
|
|
515
|
+
catch (error) {
|
|
516
|
+
throw this.abortError(method, url, signal?.reason ?? error);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
abortError(method, url, reason) {
|
|
520
|
+
return new APIUserAbortError(`${method} ${url} was aborted.`, { code: "aborted", cause: reason });
|
|
521
|
+
}
|
|
522
|
+
/** JSON request; resolves to the parsed body (undefined for empty bodies). */
|
|
523
|
+
async json(spec, options) {
|
|
524
|
+
const method = spec.method.toUpperCase();
|
|
525
|
+
const { response, url, done, signal } = await this.send(spec, options, false);
|
|
526
|
+
let text;
|
|
527
|
+
try {
|
|
528
|
+
text = await response.text();
|
|
529
|
+
}
|
|
530
|
+
catch (error) {
|
|
531
|
+
if (options?.signal?.aborted)
|
|
532
|
+
throw this.abortError(method, url, options.signal.reason);
|
|
533
|
+
if (signal.reason === TIMEOUT) {
|
|
534
|
+
throw new APITimeoutError(`${method} ${url} timed out reading the response body.`, { code: "timeout", cause: error });
|
|
535
|
+
}
|
|
536
|
+
throw new APIConnectionError(`${method} ${url} failed while reading the response: ${describeCause(error)}`, {
|
|
537
|
+
code: "connection_error",
|
|
538
|
+
cause: error,
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
finally {
|
|
542
|
+
done();
|
|
543
|
+
}
|
|
544
|
+
if (response.status === 204 || response.status === 205 || text.trim() === "")
|
|
545
|
+
return undefined;
|
|
546
|
+
try {
|
|
547
|
+
return JSON.parse(text);
|
|
548
|
+
}
|
|
549
|
+
catch (error) {
|
|
550
|
+
throw new ResponseDecodeError(`${method} ${url} returned ${response.status} with a body that is not JSON: ${text.slice(0, 200)}`, { status: response.status, code: "invalid_json", requestId: response.headers.get("x-request-id") ?? undefined, cause: error });
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
/** Streaming request; the timeout covers only the headers, then an idle timeout guards the body. */
|
|
554
|
+
async raw(spec, options) {
|
|
555
|
+
const method = spec.method.toUpperCase();
|
|
556
|
+
const { response, url, done, signal, abort } = await this.send(spec, options, true);
|
|
557
|
+
const idleMs = options?.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
|
|
558
|
+
const source = response.body;
|
|
559
|
+
const userSignal = options?.signal;
|
|
560
|
+
let idle;
|
|
561
|
+
const arm = () => {
|
|
562
|
+
if (idle !== undefined)
|
|
563
|
+
clearTimeout(idle);
|
|
564
|
+
idle = setTimeout(() => abort(TIMEOUT), idleMs);
|
|
565
|
+
};
|
|
566
|
+
const finish = () => {
|
|
567
|
+
if (idle !== undefined)
|
|
568
|
+
clearTimeout(idle);
|
|
569
|
+
idle = undefined;
|
|
570
|
+
done();
|
|
571
|
+
};
|
|
572
|
+
const reader = source?.getReader();
|
|
573
|
+
const body = new ReadableStream({
|
|
574
|
+
start: () => arm(),
|
|
575
|
+
pull: async (controller) => {
|
|
576
|
+
if (!reader) {
|
|
577
|
+
finish();
|
|
578
|
+
controller.close();
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
try {
|
|
582
|
+
const chunk = await reader.read();
|
|
583
|
+
if (chunk.done) {
|
|
584
|
+
finish();
|
|
585
|
+
controller.close();
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
arm();
|
|
589
|
+
controller.enqueue(chunk.value);
|
|
590
|
+
}
|
|
591
|
+
catch (error) {
|
|
592
|
+
finish();
|
|
593
|
+
if (userSignal?.aborted)
|
|
594
|
+
controller.error(this.abortError(method, url, userSignal.reason));
|
|
595
|
+
else if (signal.reason === TIMEOUT) {
|
|
596
|
+
controller.error(new APITimeoutError(`${method} ${url}: the stream sent nothing for ${idleMs} ms.`, { code: "timeout", cause: error }));
|
|
597
|
+
}
|
|
598
|
+
else {
|
|
599
|
+
controller.error(new APIConnectionError(`${method} ${url}: the stream broke: ${describeCause(error)}`, { code: "connection_error", cause: error }));
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
},
|
|
603
|
+
cancel: (reason) => {
|
|
604
|
+
finish();
|
|
605
|
+
// Not awaited: cancelling a tee'd body resolves only once every branch is cancelled.
|
|
606
|
+
void reader?.cancel(reason).catch(() => undefined);
|
|
607
|
+
},
|
|
608
|
+
});
|
|
609
|
+
return {
|
|
610
|
+
status: response.status,
|
|
611
|
+
headers: response.headers,
|
|
612
|
+
requestId: response.headers.get("x-request-id") ?? undefined,
|
|
613
|
+
url,
|
|
614
|
+
body,
|
|
615
|
+
cancel: async () => {
|
|
616
|
+
finish();
|
|
617
|
+
abort(new Error("cancelled"));
|
|
618
|
+
await body.cancel().catch(() => undefined);
|
|
619
|
+
},
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
/** Single SSE connection; yields events until the server closes the stream. */
|
|
623
|
+
async *sse(spec, options) {
|
|
624
|
+
const extra = { ...(options?.headers ?? {}) };
|
|
625
|
+
if (options?.lastEventId !== undefined)
|
|
626
|
+
extra["Last-Event-ID"] = options.lastEventId;
|
|
627
|
+
const raw = await this.raw({ ...spec, accept: "text/event-stream" }, { ...options, headers: extra });
|
|
628
|
+
const reader = raw.body.getReader();
|
|
629
|
+
const decoder = new TextDecoder();
|
|
630
|
+
let buffer = "";
|
|
631
|
+
let event = "";
|
|
632
|
+
let data = [];
|
|
633
|
+
let id;
|
|
634
|
+
let retry;
|
|
635
|
+
try {
|
|
636
|
+
while (true) {
|
|
637
|
+
const { done, value } = await reader.read();
|
|
638
|
+
buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
|
|
639
|
+
let newline;
|
|
640
|
+
while ((newline = buffer.search(/\r\n|\r|\n/)) >= 0) {
|
|
641
|
+
const line = buffer.slice(0, newline);
|
|
642
|
+
const sep = buffer.startsWith("\r\n", newline) ? 2 : 1;
|
|
643
|
+
buffer = buffer.slice(newline + sep);
|
|
644
|
+
if (line === "") {
|
|
645
|
+
if (data.length > 0 || event !== "") {
|
|
646
|
+
yield { event: event || "message", data: data.join("\n"), id, retry };
|
|
647
|
+
}
|
|
648
|
+
event = "";
|
|
649
|
+
data = [];
|
|
650
|
+
retry = undefined;
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
if (line.startsWith(":"))
|
|
654
|
+
continue;
|
|
655
|
+
const colon = line.indexOf(":");
|
|
656
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
657
|
+
let fieldValue = colon < 0 ? "" : line.slice(colon + 1);
|
|
658
|
+
if (fieldValue.startsWith(" "))
|
|
659
|
+
fieldValue = fieldValue.slice(1);
|
|
660
|
+
if (field === "event")
|
|
661
|
+
event = fieldValue;
|
|
662
|
+
else if (field === "data")
|
|
663
|
+
data.push(fieldValue);
|
|
664
|
+
else if (field === "id" && !fieldValue.includes("\0"))
|
|
665
|
+
id = fieldValue;
|
|
666
|
+
else if (field === "retry" && /^\d+$/.test(fieldValue))
|
|
667
|
+
retry = Number(fieldValue);
|
|
668
|
+
}
|
|
669
|
+
if (done)
|
|
670
|
+
break;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
finally {
|
|
674
|
+
reader.releaseLock();
|
|
675
|
+
await raw.cancel();
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
}
|