@runinfra/sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +364 -0
- package/dist/index.d.ts +292 -0
- package/dist/index.js +1129 -0
- package/package.json +52 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1129 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
export const RUNINFRA_SDK_VERSION = "0.1.0";
|
|
3
|
+
const MAX_AUTOMATIC_RETRY_AFTER_MS = 60_000;
|
|
4
|
+
export class RunInfraError extends Error {
|
|
5
|
+
status;
|
|
6
|
+
type;
|
|
7
|
+
requestId;
|
|
8
|
+
retryAfterMs;
|
|
9
|
+
constructor(message, input) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "RunInfraError";
|
|
12
|
+
this.status = input.status;
|
|
13
|
+
this.type = input.type;
|
|
14
|
+
this.requestId = input.requestId;
|
|
15
|
+
this.retryAfterMs = input.retryAfterMs;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export class AuthenticationError extends RunInfraError {
|
|
19
|
+
constructor(message, status, requestId) {
|
|
20
|
+
super(message, { status, type: "auth_error", requestId });
|
|
21
|
+
this.name = "AuthenticationError";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export class PermissionDeniedError extends RunInfraError {
|
|
25
|
+
constructor(message, status, requestId) {
|
|
26
|
+
super(message, { status, type: "permission_denied", requestId });
|
|
27
|
+
this.name = "PermissionDeniedError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export class RateLimitError extends RunInfraError {
|
|
31
|
+
constructor(message, status, requestId, retryAfterMs) {
|
|
32
|
+
super(message, { status, type: "rate_limit_error", requestId, retryAfterMs });
|
|
33
|
+
this.name = "RateLimitError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export class InsufficientCreditsError extends RunInfraError {
|
|
37
|
+
constructor(message, status, requestId) {
|
|
38
|
+
super(message, { status, type: "insufficient_credits", requestId });
|
|
39
|
+
this.name = "InsufficientCreditsError";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export class DeploymentError extends RunInfraError {
|
|
43
|
+
constructor(message, status, requestId) {
|
|
44
|
+
super(message, { status, type: "deployment_error", requestId });
|
|
45
|
+
this.name = "DeploymentError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export class ModelNotFoundError extends RunInfraError {
|
|
49
|
+
constructor(message, status, requestId) {
|
|
50
|
+
super(message, { status, type: "model_not_found", requestId });
|
|
51
|
+
this.name = "ModelNotFoundError";
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export class RunInfraTimeoutError extends RunInfraError {
|
|
55
|
+
constructor(message = "RunInfra request timed out", requestId) {
|
|
56
|
+
super(message, { status: 0, type: "timeout_error", requestId });
|
|
57
|
+
this.name = "RunInfraTimeoutError";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export class RunInfraConnectionError extends RunInfraError {
|
|
61
|
+
constructor(message = "RunInfra request failed before a response was received", requestId) {
|
|
62
|
+
super(message, { status: 0, type: "connection_error", requestId });
|
|
63
|
+
this.name = "RunInfraConnectionError";
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
export class RunInfraStreamParseError extends RunInfraError {
|
|
67
|
+
constructor(message = "RunInfra stream event payload was not valid JSON", requestId) {
|
|
68
|
+
super(message, { status: 0, type: "stream_parse_error", requestId });
|
|
69
|
+
this.name = "RunInfraStreamParseError";
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export class UnsupportedOperationError extends RunInfraError {
|
|
73
|
+
constructor(message) {
|
|
74
|
+
super(message, { status: 400, type: "unsupported_operation" });
|
|
75
|
+
this.name = "UnsupportedOperationError";
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
export class WebhookVerificationError extends RunInfraError {
|
|
79
|
+
constructor(message) {
|
|
80
|
+
super(message, { status: 400, type: "webhook_verification_error" });
|
|
81
|
+
this.name = "WebhookVerificationError";
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const WEBHOOK_SIGNATURE_HEADER_MAX_LENGTH = 8_192;
|
|
85
|
+
function webhookPayloadBytes(payload) {
|
|
86
|
+
if (typeof payload === "string")
|
|
87
|
+
return new TextEncoder().encode(payload);
|
|
88
|
+
if (payload instanceof ArrayBuffer)
|
|
89
|
+
return new Uint8Array(payload);
|
|
90
|
+
if (payload instanceof Uint8Array)
|
|
91
|
+
return payload;
|
|
92
|
+
throw new WebhookVerificationError("Webhook payload must be a string, Uint8Array, or ArrayBuffer.");
|
|
93
|
+
}
|
|
94
|
+
function parseWebhookSignatureHeader(header) {
|
|
95
|
+
if (typeof header !== "string") {
|
|
96
|
+
throw new WebhookVerificationError("Webhook signature header must be a string.");
|
|
97
|
+
}
|
|
98
|
+
if (header.length > WEBHOOK_SIGNATURE_HEADER_MAX_LENGTH) {
|
|
99
|
+
throw new WebhookVerificationError("Webhook signature header is too large.");
|
|
100
|
+
}
|
|
101
|
+
const parts = header.split(",").map((part) => part.trim());
|
|
102
|
+
let timestamp = null;
|
|
103
|
+
const signatures = [];
|
|
104
|
+
for (const part of parts) {
|
|
105
|
+
const [key, value] = part.split("=", 2);
|
|
106
|
+
if (key === "t" && value) {
|
|
107
|
+
if (!/^[0-9]+$/u.test(value)) {
|
|
108
|
+
throw new WebhookVerificationError("Webhook signature timestamp must be a non-negative integer.");
|
|
109
|
+
}
|
|
110
|
+
const parsed = Number(value);
|
|
111
|
+
if (!Number.isSafeInteger(parsed)) {
|
|
112
|
+
throw new WebhookVerificationError("Webhook signature timestamp must be a non-negative integer.");
|
|
113
|
+
}
|
|
114
|
+
timestamp = parsed;
|
|
115
|
+
}
|
|
116
|
+
if (key === "v1" && value)
|
|
117
|
+
signatures.push(value);
|
|
118
|
+
}
|
|
119
|
+
if (timestamp === null || signatures.length === 0) {
|
|
120
|
+
throw new WebhookVerificationError("RunInfra webhook signature must include t=<unix_seconds> and v1=<hex_signature>.");
|
|
121
|
+
}
|
|
122
|
+
return { timestamp, signatures };
|
|
123
|
+
}
|
|
124
|
+
function webhookExpectedSignature(params) {
|
|
125
|
+
const hmac = createHmac("sha256", params.secret);
|
|
126
|
+
hmac.update(`${params.timestamp}.`);
|
|
127
|
+
hmac.update(params.payload);
|
|
128
|
+
return hmac.digest("hex");
|
|
129
|
+
}
|
|
130
|
+
function timingSafeHexEqual(a, b) {
|
|
131
|
+
if (a.length !== b.length || a.length % 2 !== 0)
|
|
132
|
+
return false;
|
|
133
|
+
if (!/^[a-f0-9]+$/iu.test(a) || !/^[a-f0-9]+$/iu.test(b))
|
|
134
|
+
return false;
|
|
135
|
+
const left = Buffer.from(a, "hex");
|
|
136
|
+
const right = Buffer.from(b, "hex");
|
|
137
|
+
return timingSafeEqual(left, right);
|
|
138
|
+
}
|
|
139
|
+
export function verifyWebhookSignature(options) {
|
|
140
|
+
if (typeof options.secret !== "string" || !options.secret.trim()) {
|
|
141
|
+
throw new WebhookVerificationError("Webhook secret is required.");
|
|
142
|
+
}
|
|
143
|
+
const toleranceSeconds = options.toleranceSeconds ?? 300;
|
|
144
|
+
if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0) {
|
|
145
|
+
throw new WebhookVerificationError("Webhook tolerance must be a non-negative number.");
|
|
146
|
+
}
|
|
147
|
+
const { timestamp, signatures } = parseWebhookSignatureHeader(options.signatureHeader);
|
|
148
|
+
const now = options.now ?? Math.floor(Date.now() / 1000);
|
|
149
|
+
if (!Number.isFinite(now) || now < 0) {
|
|
150
|
+
throw new WebhookVerificationError("Webhook verification clock must be a non-negative finite number.");
|
|
151
|
+
}
|
|
152
|
+
if (Math.abs(now - timestamp) > toleranceSeconds) {
|
|
153
|
+
throw new WebhookVerificationError("Webhook signature timestamp is outside the allowed tolerance.");
|
|
154
|
+
}
|
|
155
|
+
const payload = webhookPayloadBytes(options.payload);
|
|
156
|
+
const expected = webhookExpectedSignature({ payload, secret: options.secret, timestamp });
|
|
157
|
+
if (!signatures.some((signature) => timingSafeHexEqual(signature, expected))) {
|
|
158
|
+
throw new WebhookVerificationError("Webhook signature verification failed.");
|
|
159
|
+
}
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
export function constructWebhookEvent(options) {
|
|
163
|
+
verifyWebhookSignature(options);
|
|
164
|
+
const payloadText = typeof options.payload === "string"
|
|
165
|
+
? options.payload
|
|
166
|
+
: new TextDecoder().decode(webhookPayloadBytes(options.payload));
|
|
167
|
+
try {
|
|
168
|
+
return JSON.parse(payloadText);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
throw new WebhookVerificationError("Webhook payload must be valid JSON.");
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
export class RunInfraAudioResponse {
|
|
175
|
+
contentType;
|
|
176
|
+
requestId;
|
|
177
|
+
response;
|
|
178
|
+
readTimeoutMs;
|
|
179
|
+
constructor(response, readTimeoutMs) {
|
|
180
|
+
this.response = response;
|
|
181
|
+
this.contentType = response.headers.get("content-type") ?? "application/octet-stream";
|
|
182
|
+
this.requestId = response.headers.get("x-request-id") ?? undefined;
|
|
183
|
+
this.readTimeoutMs = readTimeoutMs;
|
|
184
|
+
}
|
|
185
|
+
arrayBuffer() {
|
|
186
|
+
return this.readBody(() => this.response.arrayBuffer(), "RunInfra audio response timed out while reading body");
|
|
187
|
+
}
|
|
188
|
+
blob() {
|
|
189
|
+
return this.readBody(() => this.response.blob(), "RunInfra audio response timed out while reading body");
|
|
190
|
+
}
|
|
191
|
+
stream() {
|
|
192
|
+
return this.response.body;
|
|
193
|
+
}
|
|
194
|
+
async readBody(operation, timeoutMessage) {
|
|
195
|
+
const bodyRead = operation();
|
|
196
|
+
bodyRead.catch(() => undefined);
|
|
197
|
+
if (this.readTimeoutMs === undefined) {
|
|
198
|
+
try {
|
|
199
|
+
return await bodyRead;
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
throw normalizeTransportError(error, this.requestId);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
let timeout;
|
|
206
|
+
try {
|
|
207
|
+
return await Promise.race([
|
|
208
|
+
bodyRead,
|
|
209
|
+
new Promise((_, reject) => {
|
|
210
|
+
timeout = setTimeout(() => {
|
|
211
|
+
void this.response.body?.cancel().catch(() => undefined);
|
|
212
|
+
reject(new RunInfraTimeoutError(timeoutMessage, this.requestId));
|
|
213
|
+
}, this.readTimeoutMs);
|
|
214
|
+
}),
|
|
215
|
+
]);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
throw normalizeTransportError(error, this.requestId);
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
if (timeout !== undefined)
|
|
222
|
+
clearTimeout(timeout);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
export class RunInfraStream {
|
|
227
|
+
response;
|
|
228
|
+
requestId;
|
|
229
|
+
readTimeoutMs;
|
|
230
|
+
constructor(response, readTimeoutMs) {
|
|
231
|
+
this.response = response;
|
|
232
|
+
this.requestId = response.headers.get("x-request-id") ?? undefined;
|
|
233
|
+
this.readTimeoutMs = readTimeoutMs;
|
|
234
|
+
}
|
|
235
|
+
async *[Symbol.asyncIterator]() {
|
|
236
|
+
if (!this.response.body)
|
|
237
|
+
return;
|
|
238
|
+
const reader = this.response.body.getReader();
|
|
239
|
+
const decoder = new TextDecoder();
|
|
240
|
+
let buffer = "";
|
|
241
|
+
let dataLines = [];
|
|
242
|
+
let readerDone = false;
|
|
243
|
+
const dispatchEvent = () => {
|
|
244
|
+
const payload = dataLines.join("\n").trim();
|
|
245
|
+
dataLines = [];
|
|
246
|
+
if (!payload || payload === "[DONE]")
|
|
247
|
+
return null;
|
|
248
|
+
try {
|
|
249
|
+
return JSON.parse(payload);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
throw new RunInfraStreamParseError(undefined, this.requestId);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
const processLine = (line) => {
|
|
256
|
+
const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
257
|
+
if (trimmed === "")
|
|
258
|
+
return dispatchEvent();
|
|
259
|
+
if (trimmed.startsWith(":"))
|
|
260
|
+
return null;
|
|
261
|
+
const separatorIndex = trimmed.indexOf(":");
|
|
262
|
+
const field = separatorIndex === -1 ? trimmed : trimmed.slice(0, separatorIndex);
|
|
263
|
+
let value = separatorIndex === -1 ? "" : trimmed.slice(separatorIndex + 1);
|
|
264
|
+
if (value.startsWith(" "))
|
|
265
|
+
value = value.slice(1);
|
|
266
|
+
if (field === "data")
|
|
267
|
+
dataLines.push(value);
|
|
268
|
+
return null;
|
|
269
|
+
};
|
|
270
|
+
const readChunk = async () => {
|
|
271
|
+
if (this.readTimeoutMs === undefined)
|
|
272
|
+
return reader.read();
|
|
273
|
+
let timeout;
|
|
274
|
+
try {
|
|
275
|
+
return await Promise.race([
|
|
276
|
+
reader.read(),
|
|
277
|
+
new Promise((_, reject) => {
|
|
278
|
+
timeout = setTimeout(() => {
|
|
279
|
+
reject(new RunInfraTimeoutError("RunInfra stream timed out while waiting for data", this.requestId));
|
|
280
|
+
}, this.readTimeoutMs);
|
|
281
|
+
}),
|
|
282
|
+
]);
|
|
283
|
+
}
|
|
284
|
+
finally {
|
|
285
|
+
if (timeout !== undefined)
|
|
286
|
+
clearTimeout(timeout);
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
try {
|
|
290
|
+
while (true) {
|
|
291
|
+
const { done, value } = await readChunk();
|
|
292
|
+
if (done) {
|
|
293
|
+
readerDone = true;
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
buffer += decoder.decode(value, { stream: true });
|
|
297
|
+
const lines = buffer.split("\n");
|
|
298
|
+
buffer = lines.pop() ?? "";
|
|
299
|
+
for (const line of lines) {
|
|
300
|
+
const parsed = processLine(line);
|
|
301
|
+
if (parsed)
|
|
302
|
+
yield parsed;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
buffer += decoder.decode();
|
|
306
|
+
if (buffer) {
|
|
307
|
+
const parsed = processLine(buffer);
|
|
308
|
+
if (parsed)
|
|
309
|
+
yield parsed;
|
|
310
|
+
}
|
|
311
|
+
if (dataLines.length > 0) {
|
|
312
|
+
const parsed = dispatchEvent();
|
|
313
|
+
if (parsed)
|
|
314
|
+
yield parsed;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
if (error instanceof RunInfraError)
|
|
319
|
+
throw error;
|
|
320
|
+
throw normalizeTransportError(error, this.requestId);
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
if (!readerDone) {
|
|
324
|
+
try {
|
|
325
|
+
await reader.cancel();
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
// The stream may already be errored or closed by the runtime.
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
reader.releaseLock();
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
// Some runtimes release the lock while propagating stream errors.
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
function unsupportedOperation(message) {
|
|
341
|
+
return Promise.reject(new UnsupportedOperationError(message));
|
|
342
|
+
}
|
|
343
|
+
function baseUrlAlreadyHasPipelineId(baseURL, pipelineId) {
|
|
344
|
+
const encodedPipelineId = encodeURIComponent(pipelineId);
|
|
345
|
+
try {
|
|
346
|
+
const parsed = new URL(baseURL);
|
|
347
|
+
const lastSegment = parsed.pathname.replace(/\/+$/u, "").split("/").pop();
|
|
348
|
+
return lastSegment === encodedPipelineId || decodeURIComponent(lastSegment ?? "") === pipelineId;
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
const trimmed = baseURL.replace(/\/+$/u, "");
|
|
352
|
+
return (trimmed.endsWith(`/${encodedPipelineId}`) ||
|
|
353
|
+
trimmed.endsWith(`/${pipelineId}`));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function validateBaseURL(baseURL) {
|
|
357
|
+
if (typeof baseURL !== "string") {
|
|
358
|
+
throw invalidRequestOption("baseURL must be a string");
|
|
359
|
+
}
|
|
360
|
+
const trimmed = baseURL.trim().replace(/\/+$/, "");
|
|
361
|
+
try {
|
|
362
|
+
const parsed = new URL(trimmed);
|
|
363
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
364
|
+
throw new Error("unsupported protocol");
|
|
365
|
+
}
|
|
366
|
+
if (!parsed.host) {
|
|
367
|
+
throw new Error("missing host");
|
|
368
|
+
}
|
|
369
|
+
if (parsed.username || parsed.password) {
|
|
370
|
+
throw new RunInfraError("baseURL must not include credentials", {
|
|
371
|
+
status: 0,
|
|
372
|
+
type: "invalid_request_options",
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
if (parsed.search || parsed.hash) {
|
|
376
|
+
throw new RunInfraError("baseURL must not include query strings or fragments", {
|
|
377
|
+
status: 0,
|
|
378
|
+
type: "invalid_request_options",
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
if (parsed.protocol === "http:" && !isLocalBaseURLHost(parsed.hostname)) {
|
|
382
|
+
throw new RunInfraError("Remote baseURL must use https", {
|
|
383
|
+
status: 0,
|
|
384
|
+
type: "invalid_request_options",
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
return trimmed;
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
if (error instanceof RunInfraError)
|
|
391
|
+
throw error;
|
|
392
|
+
throw new RunInfraError("baseURL must be an http or https URL", {
|
|
393
|
+
status: 0,
|
|
394
|
+
type: "invalid_request_options",
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
function isLocalBaseURLHost(hostname) {
|
|
399
|
+
const normalized = hostname.trim().toLowerCase().replace(/^\[|\]$/gu, "");
|
|
400
|
+
return (normalized === "localhost" ||
|
|
401
|
+
normalized === "127.0.0.1" ||
|
|
402
|
+
normalized === "0.0.0.0" ||
|
|
403
|
+
normalized === "::1");
|
|
404
|
+
}
|
|
405
|
+
function normalizeBaseURL(baseURL, pipelineId) {
|
|
406
|
+
const trimmed = validateBaseURL(baseURL);
|
|
407
|
+
if (pipelineId === undefined || pipelineId === null)
|
|
408
|
+
return trimmed;
|
|
409
|
+
const validatedPipelineId = validateSdkIdentifierHeader(pipelineId, "pipelineId");
|
|
410
|
+
if (baseUrlAlreadyHasPipelineId(trimmed, validatedPipelineId))
|
|
411
|
+
return trimmed;
|
|
412
|
+
return `${trimmed}/${encodeURIComponent(validatedPipelineId)}`;
|
|
413
|
+
}
|
|
414
|
+
function sleep(ms) {
|
|
415
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
416
|
+
}
|
|
417
|
+
function isRetryableStatus(status) {
|
|
418
|
+
return status === 408 || status === 409 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
|
|
419
|
+
}
|
|
420
|
+
function validateSdkHeader(value, name, maxLength = 512) {
|
|
421
|
+
if (value.length > maxLength || /[^\x20-\x7E]/u.test(value)) {
|
|
422
|
+
throw new RunInfraError(`${name} must be ASCII and ${maxLength} characters or less`, {
|
|
423
|
+
status: 0,
|
|
424
|
+
type: "invalid_request_options",
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
return value;
|
|
428
|
+
}
|
|
429
|
+
function validateSdkIdentifierHeader(value, name, maxLength = 512) {
|
|
430
|
+
if (typeof value !== "string") {
|
|
431
|
+
throw invalidRequestOption(`${name} must be a string`);
|
|
432
|
+
}
|
|
433
|
+
const trimmed = value.trim();
|
|
434
|
+
if (!trimmed) {
|
|
435
|
+
throw new RunInfraError(`${name} must not be blank`, {
|
|
436
|
+
status: 0,
|
|
437
|
+
type: "invalid_request_options",
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
return validateSdkHeader(trimmed, name, maxLength);
|
|
441
|
+
}
|
|
442
|
+
function validateSdkModel(value) {
|
|
443
|
+
if (typeof value !== "string") {
|
|
444
|
+
throw invalidRequestOption("model must be a string");
|
|
445
|
+
}
|
|
446
|
+
return validateSdkIdentifierHeader(value, "model");
|
|
447
|
+
}
|
|
448
|
+
function withValidatedModel(request) {
|
|
449
|
+
return {
|
|
450
|
+
...request,
|
|
451
|
+
model: validateSdkModel(request.model),
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function validateNonEmptyStringField(value, name) {
|
|
455
|
+
if (typeof value !== "string") {
|
|
456
|
+
throw invalidRequestOption(`${name} must be a string`);
|
|
457
|
+
}
|
|
458
|
+
if (!value.trim()) {
|
|
459
|
+
throw invalidRequestOption(`${name} must be a non-empty string`);
|
|
460
|
+
}
|
|
461
|
+
return value;
|
|
462
|
+
}
|
|
463
|
+
function validateSpeechReference(body) {
|
|
464
|
+
const voice = body.voice;
|
|
465
|
+
if (voice !== undefined) {
|
|
466
|
+
validateNonEmptyStringField(voice, "voice");
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
const refAudio = body.ref_audio;
|
|
470
|
+
const refText = body.ref_text;
|
|
471
|
+
if (refAudio !== undefined || refText !== undefined) {
|
|
472
|
+
validateNonEmptyStringField(refAudio, "ref_audio");
|
|
473
|
+
validateNonEmptyStringField(refText, "ref_text");
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
throw invalidRequestOption("speech requests require either voice, or both ref_audio and ref_text");
|
|
477
|
+
}
|
|
478
|
+
function validateChatMessages(value) {
|
|
479
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
480
|
+
throw invalidRequestOption("messages must be a non-empty array");
|
|
481
|
+
}
|
|
482
|
+
for (const [index, message] of value.entries()) {
|
|
483
|
+
if (!isPlainRecord(message) ||
|
|
484
|
+
typeof message.role !== "string" ||
|
|
485
|
+
!message.role.trim()) {
|
|
486
|
+
throw invalidRequestOption(`messages[${index}] must be an object with a non-empty role`);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function validateResponsesInput(value) {
|
|
491
|
+
if (typeof value === "string" && value.trim())
|
|
492
|
+
return;
|
|
493
|
+
if (Array.isArray(value) && value.length > 0) {
|
|
494
|
+
for (const [index, item] of value.entries()) {
|
|
495
|
+
if (!isPlainRecord(item)) {
|
|
496
|
+
throw invalidRequestOption(`input[${index}] must be an object`);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
throw invalidRequestOption("input must be a non-empty string or array");
|
|
502
|
+
}
|
|
503
|
+
function validateEmbeddingInput(value) {
|
|
504
|
+
if (typeof value === "string" && value.trim())
|
|
505
|
+
return;
|
|
506
|
+
if (Array.isArray(value) &&
|
|
507
|
+
value.length > 0 &&
|
|
508
|
+
value.every((item) => typeof item === "string" && item.trim().length > 0)) {
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
throw invalidRequestOption("input must be a non-empty string or array of strings");
|
|
512
|
+
}
|
|
513
|
+
function validateBlobFile(value) {
|
|
514
|
+
if (!(value instanceof Blob)) {
|
|
515
|
+
throw invalidRequestOption("file must be a Blob");
|
|
516
|
+
}
|
|
517
|
+
return value;
|
|
518
|
+
}
|
|
519
|
+
function validateVoicePipelineAudio(value) {
|
|
520
|
+
if (value instanceof Blob) {
|
|
521
|
+
if (value.size === 0)
|
|
522
|
+
throw invalidRequestOption("audio must not be empty");
|
|
523
|
+
return value;
|
|
524
|
+
}
|
|
525
|
+
if (value instanceof ArrayBuffer) {
|
|
526
|
+
if (value.byteLength === 0)
|
|
527
|
+
throw invalidRequestOption("audio must not be empty");
|
|
528
|
+
return value;
|
|
529
|
+
}
|
|
530
|
+
if (value instanceof Uint8Array) {
|
|
531
|
+
if (value.byteLength === 0)
|
|
532
|
+
throw invalidRequestOption("audio must not be empty");
|
|
533
|
+
const copy = new ArrayBuffer(value.byteLength);
|
|
534
|
+
new Uint8Array(copy).set(value);
|
|
535
|
+
return copy;
|
|
536
|
+
}
|
|
537
|
+
throw invalidRequestOption("audio must be a Blob, ArrayBuffer, or Uint8Array");
|
|
538
|
+
}
|
|
539
|
+
function validateMimeType(value, fallback = "audio/wav") {
|
|
540
|
+
if (value === undefined)
|
|
541
|
+
return fallback;
|
|
542
|
+
if (typeof value !== "string") {
|
|
543
|
+
throw invalidRequestOption("mimeType must be a string");
|
|
544
|
+
}
|
|
545
|
+
const trimmed = value.trim();
|
|
546
|
+
if (!trimmed) {
|
|
547
|
+
throw invalidRequestOption("mimeType must not be blank");
|
|
548
|
+
}
|
|
549
|
+
return validateSdkHeader(trimmed, "mimeType", 255);
|
|
550
|
+
}
|
|
551
|
+
function validateMultipartFieldName(value) {
|
|
552
|
+
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(value)) {
|
|
553
|
+
throw invalidRequestOption("multipart field names must be ASCII tokens");
|
|
554
|
+
}
|
|
555
|
+
return value;
|
|
556
|
+
}
|
|
557
|
+
function validateMultipartFilename(value) {
|
|
558
|
+
if (typeof value !== "string") {
|
|
559
|
+
throw invalidRequestOption("filename must be a string");
|
|
560
|
+
}
|
|
561
|
+
if (!value.trim()) {
|
|
562
|
+
throw invalidRequestOption("filename must not be blank");
|
|
563
|
+
}
|
|
564
|
+
validateSdkHeader(value, "filename", 255);
|
|
565
|
+
if (/["\\]/u.test(value)) {
|
|
566
|
+
throw invalidRequestOption("filename must not contain quotes or backslashes");
|
|
567
|
+
}
|
|
568
|
+
return value;
|
|
569
|
+
}
|
|
570
|
+
function validateMultipartFieldValue(value) {
|
|
571
|
+
if (typeof value !== "string" &&
|
|
572
|
+
typeof value !== "number" &&
|
|
573
|
+
typeof value !== "boolean") {
|
|
574
|
+
throw invalidRequestOption("multipart field values must be strings, numbers, or booleans");
|
|
575
|
+
}
|
|
576
|
+
if (typeof value === "number" && !Number.isFinite(value)) {
|
|
577
|
+
throw invalidRequestOption("multipart field values must contain only finite numbers");
|
|
578
|
+
}
|
|
579
|
+
return String(value);
|
|
580
|
+
}
|
|
581
|
+
const JSON_BODY_ERROR = "JSON request body must be JSON-serializable and contain only finite numbers";
|
|
582
|
+
function sanitizeJsonValue(value, seen = new WeakSet()) {
|
|
583
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
584
|
+
return value;
|
|
585
|
+
if (typeof value === "number") {
|
|
586
|
+
if (!Number.isFinite(value))
|
|
587
|
+
throw invalidRequestOption(JSON_BODY_ERROR);
|
|
588
|
+
return value;
|
|
589
|
+
}
|
|
590
|
+
if (value === undefined)
|
|
591
|
+
return undefined;
|
|
592
|
+
if (typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") {
|
|
593
|
+
throw invalidRequestOption(JSON_BODY_ERROR);
|
|
594
|
+
}
|
|
595
|
+
if (Array.isArray(value)) {
|
|
596
|
+
if (seen.has(value))
|
|
597
|
+
throw invalidRequestOption(JSON_BODY_ERROR);
|
|
598
|
+
seen.add(value);
|
|
599
|
+
const sanitized = value.map((item) => {
|
|
600
|
+
const sanitized = sanitizeJsonValue(item, seen);
|
|
601
|
+
if (sanitized === undefined)
|
|
602
|
+
throw invalidRequestOption(JSON_BODY_ERROR);
|
|
603
|
+
return sanitized;
|
|
604
|
+
});
|
|
605
|
+
seen.delete(value);
|
|
606
|
+
return sanitized;
|
|
607
|
+
}
|
|
608
|
+
if (!isPlainRecord(value))
|
|
609
|
+
throw invalidRequestOption(JSON_BODY_ERROR);
|
|
610
|
+
if (seen.has(value))
|
|
611
|
+
throw invalidRequestOption(JSON_BODY_ERROR);
|
|
612
|
+
seen.add(value);
|
|
613
|
+
const sanitized = {};
|
|
614
|
+
for (const [key, item] of Object.entries(value)) {
|
|
615
|
+
const sanitizedItem = sanitizeJsonValue(item, seen);
|
|
616
|
+
if (sanitizedItem !== undefined)
|
|
617
|
+
sanitized[key] = sanitizedItem;
|
|
618
|
+
}
|
|
619
|
+
seen.delete(value);
|
|
620
|
+
return sanitized;
|
|
621
|
+
}
|
|
622
|
+
function encodeJsonBody(payload) {
|
|
623
|
+
return JSON.stringify(sanitizeJsonValue(payload));
|
|
624
|
+
}
|
|
625
|
+
function invalidRequestOption(message) {
|
|
626
|
+
return new RunInfraError(message, {
|
|
627
|
+
status: 0,
|
|
628
|
+
type: "invalid_request_options",
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
function validatePositiveNumber(value, name) {
|
|
632
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
633
|
+
throw invalidRequestOption(`${name} must be a positive number`);
|
|
634
|
+
}
|
|
635
|
+
return value;
|
|
636
|
+
}
|
|
637
|
+
function validateNonNegativeNumber(value, name) {
|
|
638
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
639
|
+
throw invalidRequestOption(`${name} must be a non-negative number`);
|
|
640
|
+
}
|
|
641
|
+
return value;
|
|
642
|
+
}
|
|
643
|
+
function validateNonNegativeInteger(value, name) {
|
|
644
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
645
|
+
throw invalidRequestOption(`${name} must be a non-negative integer`);
|
|
646
|
+
}
|
|
647
|
+
return value;
|
|
648
|
+
}
|
|
649
|
+
const SDK_CONTROLLED_HEADERS = new Set([
|
|
650
|
+
"authorization",
|
|
651
|
+
"api-key",
|
|
652
|
+
"connection",
|
|
653
|
+
"content-type",
|
|
654
|
+
"content-length",
|
|
655
|
+
"cookie",
|
|
656
|
+
"forwarded",
|
|
657
|
+
"host",
|
|
658
|
+
"idempotency-key",
|
|
659
|
+
"keep-alive",
|
|
660
|
+
"proxy-authenticate",
|
|
661
|
+
"proxy-authorization",
|
|
662
|
+
"te",
|
|
663
|
+
"trailer",
|
|
664
|
+
"transfer-encoding",
|
|
665
|
+
"upgrade",
|
|
666
|
+
"via",
|
|
667
|
+
"x-access-token",
|
|
668
|
+
"x-api-key",
|
|
669
|
+
"x-auth-token",
|
|
670
|
+
"x-client-request-id",
|
|
671
|
+
"x-forwarded-for",
|
|
672
|
+
"x-forwarded-host",
|
|
673
|
+
"x-forwarded-proto",
|
|
674
|
+
"x-runinfra-sdk",
|
|
675
|
+
"x-runinfra-sdk-version",
|
|
676
|
+
]);
|
|
677
|
+
function isPlainRecord(value) {
|
|
678
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
679
|
+
return false;
|
|
680
|
+
const prototype = Object.getPrototypeOf(value);
|
|
681
|
+
return prototype === Object.prototype || prototype === null;
|
|
682
|
+
}
|
|
683
|
+
function validateCustomHeaders(headers) {
|
|
684
|
+
if (headers === undefined)
|
|
685
|
+
return {};
|
|
686
|
+
if (!isPlainRecord(headers)) {
|
|
687
|
+
throw invalidRequestOption("headers must be an object with string names and values");
|
|
688
|
+
}
|
|
689
|
+
const validated = {};
|
|
690
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
691
|
+
const normalizedName = name.trim().toLowerCase();
|
|
692
|
+
if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(name)) {
|
|
693
|
+
throw new RunInfraError(`Invalid custom header name: ${name}`, {
|
|
694
|
+
status: 0,
|
|
695
|
+
type: "invalid_request_options",
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
if (SDK_CONTROLLED_HEADERS.has(normalizedName)) {
|
|
699
|
+
throw new RunInfraError(`${name} is controlled by the RunInfra SDK`, {
|
|
700
|
+
status: 0,
|
|
701
|
+
type: "invalid_request_options",
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
if (typeof value !== "string") {
|
|
705
|
+
throw new RunInfraError(`${name} header value must be a string`, {
|
|
706
|
+
status: 0,
|
|
707
|
+
type: "invalid_request_options",
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
validated[name] = validateSdkHeader(value, name);
|
|
711
|
+
}
|
|
712
|
+
return validated;
|
|
713
|
+
}
|
|
714
|
+
const REQUEST_OPTION_KEYS = new Set([
|
|
715
|
+
"clientRequestId",
|
|
716
|
+
"idempotencyKey",
|
|
717
|
+
"timeoutMs",
|
|
718
|
+
"maxRetries",
|
|
719
|
+
"retryBaseMs",
|
|
720
|
+
"headers",
|
|
721
|
+
]);
|
|
722
|
+
function validateRequestOptions(requestOptions) {
|
|
723
|
+
if (requestOptions === undefined)
|
|
724
|
+
return {};
|
|
725
|
+
if (!isPlainRecord(requestOptions)) {
|
|
726
|
+
throw invalidRequestOption("requestOptions must be an object");
|
|
727
|
+
}
|
|
728
|
+
for (const key of Object.keys(requestOptions)) {
|
|
729
|
+
if (!REQUEST_OPTION_KEYS.has(key)) {
|
|
730
|
+
throw invalidRequestOption(`Unknown request option: ${key}`);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
return requestOptions;
|
|
734
|
+
}
|
|
735
|
+
const RUNINFRA_OPTION_KEYS = new Set([
|
|
736
|
+
"apiKey",
|
|
737
|
+
"pipelineId",
|
|
738
|
+
"baseURL",
|
|
739
|
+
"timeoutMs",
|
|
740
|
+
"maxRetries",
|
|
741
|
+
"retryBaseMs",
|
|
742
|
+
"fetch",
|
|
743
|
+
"dangerouslyAllowBrowser",
|
|
744
|
+
]);
|
|
745
|
+
function validateRunInfraOptions(options) {
|
|
746
|
+
for (const key of Object.keys(options)) {
|
|
747
|
+
if (!RUNINFRA_OPTION_KEYS.has(key)) {
|
|
748
|
+
throw invalidRequestOption(`Unknown RunInfra option: ${key}`);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
function generatedClientRequestId() {
|
|
753
|
+
const randomUUID = globalThis.crypto?.randomUUID;
|
|
754
|
+
if (randomUUID)
|
|
755
|
+
return randomUUID.call(globalThis.crypto);
|
|
756
|
+
return `runinfra-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
757
|
+
}
|
|
758
|
+
function isBrowserRuntime() {
|
|
759
|
+
return typeof globalThis.window === "object" && typeof globalThis.document === "object";
|
|
760
|
+
}
|
|
761
|
+
function retryAfterMs(response) {
|
|
762
|
+
const value = response.headers.get("retry-after");
|
|
763
|
+
if (!value)
|
|
764
|
+
return null;
|
|
765
|
+
const trimmed = value.trim();
|
|
766
|
+
if (/^[0-9]+$/.test(trimmed)) {
|
|
767
|
+
const seconds = Number(trimmed);
|
|
768
|
+
if (Number.isSafeInteger(seconds))
|
|
769
|
+
return seconds * 1000;
|
|
770
|
+
return null;
|
|
771
|
+
}
|
|
772
|
+
if (/^(?:[+-]|\d)/.test(trimmed))
|
|
773
|
+
return null;
|
|
774
|
+
const dateMs = Date.parse(trimmed);
|
|
775
|
+
if (Number.isFinite(dateMs))
|
|
776
|
+
return Math.max(0, dateMs - Date.now());
|
|
777
|
+
return null;
|
|
778
|
+
}
|
|
779
|
+
function automaticRetryAfterMs(response) {
|
|
780
|
+
const delay = retryAfterMs(response);
|
|
781
|
+
if (delay === null || delay > MAX_AUTOMATIC_RETRY_AFTER_MS)
|
|
782
|
+
return null;
|
|
783
|
+
return delay;
|
|
784
|
+
}
|
|
785
|
+
function retryDelayMs(attempt, baseMs, response) {
|
|
786
|
+
if (response) {
|
|
787
|
+
const retryAfter = automaticRetryAfterMs(response);
|
|
788
|
+
if (retryAfter !== null)
|
|
789
|
+
return retryAfter;
|
|
790
|
+
}
|
|
791
|
+
if (baseMs <= 0)
|
|
792
|
+
return 0;
|
|
793
|
+
const exponential = baseMs * 2 ** Math.max(0, attempt - 1);
|
|
794
|
+
const jitter = Math.random() * baseMs;
|
|
795
|
+
return Math.min(30_000, exponential + jitter);
|
|
796
|
+
}
|
|
797
|
+
async function parseError(response) {
|
|
798
|
+
try {
|
|
799
|
+
const body = (await response.json());
|
|
800
|
+
return {
|
|
801
|
+
message: typeof body.error?.message === "string"
|
|
802
|
+
? body.error.message
|
|
803
|
+
: `RunInfra request failed with status ${response.status}`,
|
|
804
|
+
type: typeof body.error?.type === "string" ? body.error.type : "api_error",
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
catch {
|
|
808
|
+
return {
|
|
809
|
+
message: `RunInfra request failed with status ${response.status}`,
|
|
810
|
+
type: "api_error",
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
async function discardResponseBody(response) {
|
|
815
|
+
try {
|
|
816
|
+
await response.body?.cancel();
|
|
817
|
+
}
|
|
818
|
+
catch {
|
|
819
|
+
// Best-effort cleanup before retrying a failed response.
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
async function raiseForStatus(response) {
|
|
823
|
+
if (response.ok)
|
|
824
|
+
return;
|
|
825
|
+
const { message, type } = await parseError(response);
|
|
826
|
+
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
827
|
+
if (response.status === 401)
|
|
828
|
+
throw new AuthenticationError(message, response.status, requestId);
|
|
829
|
+
if (response.status === 403)
|
|
830
|
+
throw new PermissionDeniedError(message, response.status, requestId);
|
|
831
|
+
if (response.status === 402)
|
|
832
|
+
throw new InsufficientCreditsError(message, response.status, requestId);
|
|
833
|
+
if (response.status === 404 || type === "model_not_found") {
|
|
834
|
+
throw new ModelNotFoundError(message, response.status, requestId);
|
|
835
|
+
}
|
|
836
|
+
if (response.status === 429) {
|
|
837
|
+
throw new RateLimitError(message, response.status, requestId, retryAfterMs(response) ?? undefined);
|
|
838
|
+
}
|
|
839
|
+
if (type === "deployment_error")
|
|
840
|
+
throw new DeploymentError(message, response.status, requestId);
|
|
841
|
+
throw new RunInfraError(message, { status: response.status, type, requestId });
|
|
842
|
+
}
|
|
843
|
+
async function parseJsonResponse(response) {
|
|
844
|
+
const requestId = response.headers.get("x-request-id") ?? undefined;
|
|
845
|
+
let payload;
|
|
846
|
+
try {
|
|
847
|
+
payload = await response.json();
|
|
848
|
+
}
|
|
849
|
+
catch (error) {
|
|
850
|
+
throw new ResponseBodyReadError(normalizeTransportError(error, requestId));
|
|
851
|
+
}
|
|
852
|
+
if (requestId &&
|
|
853
|
+
payload &&
|
|
854
|
+
typeof payload === "object" &&
|
|
855
|
+
!Array.isArray(payload)) {
|
|
856
|
+
return { ...payload, _request_id: requestId };
|
|
857
|
+
}
|
|
858
|
+
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
|
859
|
+
return payload;
|
|
860
|
+
}
|
|
861
|
+
throw new RunInfraError(`RunInfra JSON response shape error: expected object, got ${jsonPayloadKind(payload)}.`, {
|
|
862
|
+
status: response.status,
|
|
863
|
+
type: "response_shape_error",
|
|
864
|
+
requestId,
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
function jsonPayloadKind(payload) {
|
|
868
|
+
if (payload === null)
|
|
869
|
+
return "null";
|
|
870
|
+
if (Array.isArray(payload))
|
|
871
|
+
return "array";
|
|
872
|
+
return typeof payload;
|
|
873
|
+
}
|
|
874
|
+
class ResponseBodyReadError extends Error {
|
|
875
|
+
error;
|
|
876
|
+
constructor(error) {
|
|
877
|
+
super(error.message);
|
|
878
|
+
this.name = "ResponseBodyReadError";
|
|
879
|
+
this.error = error;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
function normalizeTransportError(error, requestId) {
|
|
883
|
+
if (error instanceof RunInfraError)
|
|
884
|
+
return error;
|
|
885
|
+
if (error instanceof DOMException &&
|
|
886
|
+
error.name === "AbortError") {
|
|
887
|
+
return new RunInfraTimeoutError(error.message, requestId);
|
|
888
|
+
}
|
|
889
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
890
|
+
return new RunInfraTimeoutError(error.message, requestId);
|
|
891
|
+
}
|
|
892
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
893
|
+
return new RunInfraConnectionError(message, requestId);
|
|
894
|
+
}
|
|
895
|
+
export class RunInfra {
|
|
896
|
+
chat;
|
|
897
|
+
embeddings;
|
|
898
|
+
responses;
|
|
899
|
+
audio;
|
|
900
|
+
models;
|
|
901
|
+
images;
|
|
902
|
+
webhooks;
|
|
903
|
+
voice;
|
|
904
|
+
apiKey;
|
|
905
|
+
baseURL;
|
|
906
|
+
timeoutMs;
|
|
907
|
+
maxRetries;
|
|
908
|
+
retryBaseMs;
|
|
909
|
+
fetcher;
|
|
910
|
+
constructor(options) {
|
|
911
|
+
if (!options || typeof options !== "object") {
|
|
912
|
+
throw invalidRequestOption("RunInfra options are required");
|
|
913
|
+
}
|
|
914
|
+
validateRunInfraOptions(options);
|
|
915
|
+
if (typeof options.apiKey !== "string") {
|
|
916
|
+
throw invalidRequestOption("apiKey must be a string");
|
|
917
|
+
}
|
|
918
|
+
const apiKey = options.apiKey.trim();
|
|
919
|
+
if (!apiKey) {
|
|
920
|
+
throw new AuthenticationError("apiKey is required", 401);
|
|
921
|
+
}
|
|
922
|
+
const validatedApiKey = validateSdkHeader(apiKey, "apiKey");
|
|
923
|
+
if (isBrowserRuntime() && !options.dangerouslyAllowBrowser) {
|
|
924
|
+
throw new RunInfraError("RunInfra SDK is intended for server-side environments because API keys are bearer secrets. Pass dangerouslyAllowBrowser: true only if you understand the risk.", { status: 0, type: "invalid_runtime" });
|
|
925
|
+
}
|
|
926
|
+
this.apiKey = validatedApiKey;
|
|
927
|
+
this.baseURL = normalizeBaseURL(options.baseURL ?? "https://api.runinfra.ai/v1", options.pipelineId);
|
|
928
|
+
this.timeoutMs = validatePositiveNumber(options.timeoutMs ?? 120_000, "timeoutMs");
|
|
929
|
+
this.maxRetries = validateNonNegativeInteger(options.maxRetries ?? 2, "maxRetries");
|
|
930
|
+
this.retryBaseMs = validateNonNegativeNumber(options.retryBaseMs ?? 250, "retryBaseMs");
|
|
931
|
+
if (options.fetch !== undefined && typeof options.fetch !== "function") {
|
|
932
|
+
throw invalidRequestOption("fetch must be a function");
|
|
933
|
+
}
|
|
934
|
+
this.fetcher = options.fetch ?? fetch;
|
|
935
|
+
const createChatCompletion = ((request, requestOptions) => {
|
|
936
|
+
const body = withValidatedModel(request);
|
|
937
|
+
validateChatMessages(body.messages);
|
|
938
|
+
return this.request("/chat/completions", {
|
|
939
|
+
method: "POST",
|
|
940
|
+
body,
|
|
941
|
+
stream: body.stream === true,
|
|
942
|
+
}, requestOptions);
|
|
943
|
+
});
|
|
944
|
+
this.chat = {
|
|
945
|
+
completions: {
|
|
946
|
+
create: createChatCompletion,
|
|
947
|
+
},
|
|
948
|
+
};
|
|
949
|
+
this.embeddings = {
|
|
950
|
+
create: (request, requestOptions) => {
|
|
951
|
+
const body = withValidatedModel(request);
|
|
952
|
+
validateEmbeddingInput(body.input);
|
|
953
|
+
return this.request("/embeddings", {
|
|
954
|
+
method: "POST",
|
|
955
|
+
body,
|
|
956
|
+
}, requestOptions);
|
|
957
|
+
},
|
|
958
|
+
};
|
|
959
|
+
this.responses = {
|
|
960
|
+
create: ((request, requestOptions) => {
|
|
961
|
+
const body = withValidatedModel(request);
|
|
962
|
+
validateResponsesInput(body.input);
|
|
963
|
+
return this.request("/responses", {
|
|
964
|
+
method: "POST",
|
|
965
|
+
body,
|
|
966
|
+
stream: body.stream === true,
|
|
967
|
+
}, requestOptions);
|
|
968
|
+
}),
|
|
969
|
+
};
|
|
970
|
+
this.audio = {
|
|
971
|
+
speech: {
|
|
972
|
+
create: async (request, requestOptions) => {
|
|
973
|
+
const body = withValidatedModel(request);
|
|
974
|
+
validateNonEmptyStringField(body.input, "input");
|
|
975
|
+
validateSpeechReference(body);
|
|
976
|
+
const response = await this.rawRequest("/audio/speech", {
|
|
977
|
+
method: "POST",
|
|
978
|
+
body,
|
|
979
|
+
binary: true,
|
|
980
|
+
}, requestOptions);
|
|
981
|
+
return new RunInfraAudioResponse(response, this.requestTimeoutMs(requestOptions));
|
|
982
|
+
},
|
|
983
|
+
},
|
|
984
|
+
transcriptions: {
|
|
985
|
+
create: (request, requestOptions) => {
|
|
986
|
+
const formData = new FormData();
|
|
987
|
+
formData.append("model", validateSdkModel(request.model));
|
|
988
|
+
formData.append("file", validateBlobFile(request.file), validateMultipartFilename(request.filename ?? "audio.wav"));
|
|
989
|
+
for (const [key, value] of Object.entries(request)) {
|
|
990
|
+
if (key === "model" || key === "file" || key === "filename")
|
|
991
|
+
continue;
|
|
992
|
+
if (value !== undefined && value !== null) {
|
|
993
|
+
formData.append(validateMultipartFieldName(key), validateMultipartFieldValue(value));
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
return this.request("/audio/transcriptions", {
|
|
997
|
+
method: "POST",
|
|
998
|
+
formData,
|
|
999
|
+
}, requestOptions);
|
|
1000
|
+
},
|
|
1001
|
+
},
|
|
1002
|
+
};
|
|
1003
|
+
this.models = {
|
|
1004
|
+
list: (requestOptions) => this.request("/models", { method: "GET" }, requestOptions),
|
|
1005
|
+
retrieve: async (model, requestOptions) => this.request(`/models/${encodeURIComponent(validateSdkIdentifierHeader(model, "model"))}`, { method: "GET" }, requestOptions),
|
|
1006
|
+
};
|
|
1007
|
+
this.images = {
|
|
1008
|
+
generate: (request, requestOptions) => {
|
|
1009
|
+
const body = withValidatedModel(request);
|
|
1010
|
+
validateNonEmptyStringField(body.prompt, "prompt");
|
|
1011
|
+
return this.request("/images/generations", {
|
|
1012
|
+
method: "POST",
|
|
1013
|
+
body,
|
|
1014
|
+
}, requestOptions);
|
|
1015
|
+
},
|
|
1016
|
+
};
|
|
1017
|
+
this.webhooks = {
|
|
1018
|
+
verifySignature: verifyWebhookSignature,
|
|
1019
|
+
constructEvent: constructWebhookEvent,
|
|
1020
|
+
create: () => unsupportedOperation("RunInfra public webhooks are not available yet; delivery and signature verification endpoints are not shipped."),
|
|
1021
|
+
list: () => unsupportedOperation("RunInfra public webhooks are not available yet; delivery and signature verification endpoints are not shipped."),
|
|
1022
|
+
};
|
|
1023
|
+
this.voice = {
|
|
1024
|
+
pipeline: {
|
|
1025
|
+
create: (request, requestOptions) => {
|
|
1026
|
+
const audio = validateVoicePipelineAudio(request?.audio);
|
|
1027
|
+
return this.request("/pipeline", {
|
|
1028
|
+
method: "POST",
|
|
1029
|
+
rawBody: audio,
|
|
1030
|
+
rawContentType: validateMimeType(request.mimeType),
|
|
1031
|
+
accept: "application/json",
|
|
1032
|
+
}, requestOptions);
|
|
1033
|
+
},
|
|
1034
|
+
},
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
async request(path, options, requestOptions) {
|
|
1038
|
+
if (options.stream) {
|
|
1039
|
+
const response = await this.rawRequest(path, options, requestOptions);
|
|
1040
|
+
return new RunInfraStream(response, this.requestTimeoutMs(requestOptions));
|
|
1041
|
+
}
|
|
1042
|
+
return this.sendWithRetry(path, options, requestOptions, (parseJsonResponse));
|
|
1043
|
+
}
|
|
1044
|
+
requestTimeoutMs(requestOptions = {}) {
|
|
1045
|
+
const validatedRequestOptions = validateRequestOptions(requestOptions);
|
|
1046
|
+
return validatePositiveNumber(validatedRequestOptions.timeoutMs ?? this.timeoutMs, "timeoutMs");
|
|
1047
|
+
}
|
|
1048
|
+
async rawRequest(path, options, requestOptions = {}) {
|
|
1049
|
+
return this.sendWithRetry(path, options, requestOptions, async (response) => response);
|
|
1050
|
+
}
|
|
1051
|
+
async sendWithRetry(path, options, requestOptions = {}, consumeResponse) {
|
|
1052
|
+
const validatedRequestOptions = validateRequestOptions(requestOptions);
|
|
1053
|
+
const clientRequestId = validateSdkIdentifierHeader(validatedRequestOptions.clientRequestId ?? generatedClientRequestId(), "clientRequestId");
|
|
1054
|
+
const headers = {
|
|
1055
|
+
...validateCustomHeaders(validatedRequestOptions.headers),
|
|
1056
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
1057
|
+
"X-RunInfra-SDK": "typescript",
|
|
1058
|
+
"X-RunInfra-SDK-Version": RUNINFRA_SDK_VERSION,
|
|
1059
|
+
"X-Client-Request-Id": clientRequestId,
|
|
1060
|
+
};
|
|
1061
|
+
if (validatedRequestOptions.idempotencyKey !== undefined) {
|
|
1062
|
+
headers["Idempotency-Key"] = validateSdkIdentifierHeader(validatedRequestOptions.idempotencyKey, "idempotencyKey", 255);
|
|
1063
|
+
}
|
|
1064
|
+
let body;
|
|
1065
|
+
if (options.formData) {
|
|
1066
|
+
body = options.formData;
|
|
1067
|
+
}
|
|
1068
|
+
else if (options.rawBody !== undefined) {
|
|
1069
|
+
body = options.rawBody;
|
|
1070
|
+
headers["Content-Type"] = options.rawContentType ?? "application/octet-stream";
|
|
1071
|
+
if (options.accept)
|
|
1072
|
+
headers.Accept = options.accept;
|
|
1073
|
+
}
|
|
1074
|
+
else if (options.body !== undefined) {
|
|
1075
|
+
headers["Content-Type"] = "application/json";
|
|
1076
|
+
body = encodeJsonBody(options.body);
|
|
1077
|
+
}
|
|
1078
|
+
let attempt = 0;
|
|
1079
|
+
const method = options.method ?? "POST";
|
|
1080
|
+
const hasReplayableJsonBody = options.body !== undefined && !options.stream && !options.binary && !options.formData;
|
|
1081
|
+
const canRetry = method === "GET" ||
|
|
1082
|
+
(Boolean(validatedRequestOptions.idempotencyKey) && hasReplayableJsonBody);
|
|
1083
|
+
const maxRetries = validateNonNegativeInteger(validatedRequestOptions.maxRetries ?? this.maxRetries, "maxRetries");
|
|
1084
|
+
const retryBaseMs = validateNonNegativeNumber(validatedRequestOptions.retryBaseMs ?? this.retryBaseMs, "retryBaseMs");
|
|
1085
|
+
const timeoutMs = validatePositiveNumber(validatedRequestOptions.timeoutMs ?? this.timeoutMs, "timeoutMs");
|
|
1086
|
+
while (true) {
|
|
1087
|
+
const controller = new AbortController();
|
|
1088
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
1089
|
+
try {
|
|
1090
|
+
const response = await this.fetcher(`${this.baseURL}${path}`, {
|
|
1091
|
+
method,
|
|
1092
|
+
headers,
|
|
1093
|
+
body,
|
|
1094
|
+
signal: controller.signal,
|
|
1095
|
+
});
|
|
1096
|
+
if (canRetry &&
|
|
1097
|
+
!response.ok &&
|
|
1098
|
+
isRetryableStatus(response.status) &&
|
|
1099
|
+
attempt < maxRetries) {
|
|
1100
|
+
attempt += 1;
|
|
1101
|
+
await discardResponseBody(response);
|
|
1102
|
+
await sleep(retryDelayMs(attempt, retryBaseMs, response));
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
await raiseForStatus(response);
|
|
1106
|
+
return await consumeResponse(response);
|
|
1107
|
+
}
|
|
1108
|
+
catch (error) {
|
|
1109
|
+
if (error instanceof ResponseBodyReadError) {
|
|
1110
|
+
if (canRetry && attempt < maxRetries) {
|
|
1111
|
+
attempt += 1;
|
|
1112
|
+
await sleep(retryDelayMs(attempt, retryBaseMs));
|
|
1113
|
+
continue;
|
|
1114
|
+
}
|
|
1115
|
+
throw error.error;
|
|
1116
|
+
}
|
|
1117
|
+
if (error instanceof RunInfraError)
|
|
1118
|
+
throw error;
|
|
1119
|
+
if (!canRetry || attempt >= maxRetries)
|
|
1120
|
+
throw normalizeTransportError(error);
|
|
1121
|
+
attempt += 1;
|
|
1122
|
+
await sleep(retryDelayMs(attempt, retryBaseMs));
|
|
1123
|
+
}
|
|
1124
|
+
finally {
|
|
1125
|
+
clearTimeout(timeout);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
}
|