@tungoai/sdk 0.0.0-stage → 0.2.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/CHANGELOG.md +40 -0
- package/LICENSE +21 -0
- package/README.kk.md +327 -0
- package/README.md +346 -2
- package/README.ru.md +327 -0
- package/dist/cjs/chat.d.ts +85 -0
- package/dist/cjs/chat.js +151 -0
- package/dist/cjs/client.d.ts +116 -0
- package/dist/cjs/client.js +223 -0
- package/dist/cjs/core.d.ts +210 -0
- package/dist/cjs/core.js +605 -0
- package/dist/cjs/errors.d.ts +212 -0
- package/dist/cjs/errors.js +410 -0
- package/dist/cjs/generated/resources.d.ts +1059 -0
- package/dist/cjs/generated/resources.js +1064 -0
- package/dist/cjs/generated/types.d.ts +4927 -0
- package/dist/cjs/generated/types.js +11 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +80 -0
- package/dist/cjs/json.d.ts +10 -0
- package/dist/cjs/json.js +120 -0
- package/dist/cjs/money.d.ts +32 -0
- package/dist/cjs/money.js +141 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +47 -0
- package/dist/cjs/pagination.js +113 -0
- package/dist/cjs/streaming.d.ts +74 -0
- package/dist/cjs/streaming.js +253 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cjs/webhooks.d.ts +74 -0
- package/dist/cjs/webhooks.js +248 -0
- package/dist/esm/chat.d.ts +85 -0
- package/dist/esm/chat.js +143 -0
- package/dist/esm/client.d.ts +116 -0
- package/dist/esm/client.js +219 -0
- package/dist/esm/core.d.ts +210 -0
- package/dist/esm/core.js +589 -0
- package/dist/esm/errors.d.ts +212 -0
- package/dist/esm/errors.js +381 -0
- package/dist/esm/generated/resources.d.ts +1059 -0
- package/dist/esm/generated/resources.js +1048 -0
- package/dist/esm/generated/types.d.ts +4927 -0
- package/dist/esm/generated/types.js +10 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/json.d.ts +10 -0
- package/dist/esm/json.js +116 -0
- package/dist/esm/money.d.ts +32 -0
- package/dist/esm/money.js +137 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pagination.d.ts +47 -0
- package/dist/esm/pagination.js +107 -0
- package/dist/esm/streaming.d.ts +74 -0
- package/dist/esm/streaming.js +247 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/webhooks.d.ts +74 -0
- package/dist/esm/webhooks.js +239 -0
- package/package.json +67 -4
package/dist/esm/core.js
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
2
|
+
import { AbortError, APIError, ConfigError, ConnectionError, DecodeError, TimeoutError, TungoError, ValidationError, apiErrorFromResponse, parseRateLimit, } from './errors.js';
|
|
3
|
+
import { parseJSON, stringifyJSON } from './json.js';
|
|
4
|
+
import { VERSION } from './version.js';
|
|
5
|
+
/** The production API host. */
|
|
6
|
+
export const DEFAULT_BASE_URL = 'https://api.tungo.kz';
|
|
7
|
+
/** Default timeout of an ordinary request, in milliseconds. */
|
|
8
|
+
export const DEFAULT_TIMEOUT = 60_000;
|
|
9
|
+
/** Default timeout of a non-streaming chat turn, in milliseconds. */
|
|
10
|
+
export const DEFAULT_LONG_RUNNING_TIMEOUT = 600_000;
|
|
11
|
+
/** Default number of retries (so 3 attempts in total). */
|
|
12
|
+
export const DEFAULT_MAX_RETRIES = 2;
|
|
13
|
+
/** Default idle timeout of a stream, in milliseconds. */
|
|
14
|
+
export const DEFAULT_STREAM_IDLE_TIMEOUT = 120_000;
|
|
15
|
+
/** A server-requested delay above this many seconds is not slept: the error is raised instead. */
|
|
16
|
+
export const MAX_RETRY_AFTER_SECONDS = 60;
|
|
17
|
+
/**
|
|
18
|
+
* The longest delay a platform timer supports, in milliseconds (2^31 - 1, about 24.8 days).
|
|
19
|
+
* A timeout above it, `Infinity` included, means "no time limit": no timer is started.
|
|
20
|
+
*/
|
|
21
|
+
export const MAX_TIMER_MS = 2_147_483_647;
|
|
22
|
+
const USER_AGENT = 'tungo-sdk-typescript/' + VERSION;
|
|
23
|
+
/** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
|
|
24
|
+
export function readEnv(name) {
|
|
25
|
+
try {
|
|
26
|
+
const scope = globalThis;
|
|
27
|
+
const fromProcess = scope.process?.env?.[name];
|
|
28
|
+
if (typeof fromProcess === 'string' && fromProcess !== '')
|
|
29
|
+
return fromProcess;
|
|
30
|
+
const fromDeno = scope.Deno?.env?.get?.(name);
|
|
31
|
+
if (typeof fromDeno === 'string' && fromDeno !== '')
|
|
32
|
+
return fromDeno;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// No permission to read the environment.
|
|
36
|
+
}
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
/** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
|
|
40
|
+
export function uuid4() {
|
|
41
|
+
const bytes = new Uint8Array(16);
|
|
42
|
+
crypto.getRandomValues(bytes);
|
|
43
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
|
|
44
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
|
45
|
+
let hex = '';
|
|
46
|
+
for (const b of bytes)
|
|
47
|
+
hex += b.toString(16).padStart(2, '0');
|
|
48
|
+
return hex.slice(0, 8) + '-' + hex.slice(8, 12) + '-' + hex.slice(12, 16) + '-' + hex.slice(16, 20) + '-' + hex.slice(20);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Percent-encodes a value as ONE path segment (`/`, `?`, `#`, spaces, CR/LF and non-ASCII are all
|
|
52
|
+
* encoded). An empty value, `.` and `..` are rejected because they would change the path.
|
|
53
|
+
*/
|
|
54
|
+
export function encodePathSegment(value, name = 'value') {
|
|
55
|
+
if (typeof value !== 'string') {
|
|
56
|
+
throw new ValidationError('The path parameter "' + name + '" must be a string');
|
|
57
|
+
}
|
|
58
|
+
if (value === '' || value === '.' || value === '..') {
|
|
59
|
+
throw new ValidationError('The path parameter "' + name + '" must not be empty, "." or ".."');
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
|
|
63
|
+
}
|
|
64
|
+
catch (cause) {
|
|
65
|
+
throw new ValidationError('The path parameter "' + name + '" is not valid Unicode text', { cause });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Fills a path template (`/v1/companies/{co}`) with encoded parameter values. */
|
|
69
|
+
export function buildPath(template, params) {
|
|
70
|
+
return template.replace(/\{([^{}]+)\}/g, (_match, name) => {
|
|
71
|
+
const value = params === undefined ? undefined : params[name];
|
|
72
|
+
return encodePathSegment(value, name);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
function queryText(name, value) {
|
|
76
|
+
switch (typeof value) {
|
|
77
|
+
case 'string':
|
|
78
|
+
return value;
|
|
79
|
+
case 'boolean':
|
|
80
|
+
return value ? 'true' : 'false';
|
|
81
|
+
case 'bigint':
|
|
82
|
+
return value.toString();
|
|
83
|
+
case 'number':
|
|
84
|
+
if (!Number.isFinite(value))
|
|
85
|
+
break;
|
|
86
|
+
return String(value);
|
|
87
|
+
case 'object':
|
|
88
|
+
if (value instanceof Date && !Number.isNaN(value.getTime()))
|
|
89
|
+
return value.toISOString();
|
|
90
|
+
break;
|
|
91
|
+
default:
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
throw new ValidationError('The query parameter "' + name + '" has a value that cannot be sent');
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Builds a query string (without the leading `?`): booleans as `true`/`false`, dates as RFC 3339,
|
|
98
|
+
* arrays as repeated keys, null and undefined omitted, `+` encoded as `%2B`.
|
|
99
|
+
*/
|
|
100
|
+
export function buildQuery(query) {
|
|
101
|
+
if (query === undefined)
|
|
102
|
+
return '';
|
|
103
|
+
const parts = [];
|
|
104
|
+
const add = (name, value) => {
|
|
105
|
+
try {
|
|
106
|
+
parts.push(encodeURIComponent(name) + '=' + encodeURIComponent(queryText(name, value)));
|
|
107
|
+
}
|
|
108
|
+
catch (cause) {
|
|
109
|
+
if (cause instanceof TungoError)
|
|
110
|
+
throw cause;
|
|
111
|
+
throw new ValidationError('The query parameter "' + name + '" is not valid Unicode text', { cause });
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
for (const [name, value] of Object.entries(query)) {
|
|
115
|
+
if (value === undefined || value === null)
|
|
116
|
+
continue;
|
|
117
|
+
if (Array.isArray(value)) {
|
|
118
|
+
for (const item of value) {
|
|
119
|
+
if (item !== undefined && item !== null)
|
|
120
|
+
add(name, item);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
add(name, value);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return parts.join('&');
|
|
128
|
+
}
|
|
129
|
+
/** Delay before retry number `attempt` (0-based), in milliseconds: min(0.5 s * 2^attempt, 8 s) * [0.75, 1]. */
|
|
130
|
+
export function backoffDelay(attempt, random = Math.random) {
|
|
131
|
+
const base = Math.min(500 * 2 ** attempt, 8000);
|
|
132
|
+
return base * (0.75 + 0.25 * random());
|
|
133
|
+
}
|
|
134
|
+
/** Statuses after which a request may be repeated. */
|
|
135
|
+
export function isRetryableStatus(status) {
|
|
136
|
+
return status === 408 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The retry rule: the failure must be transient (a retryable status, a connection error or a
|
|
140
|
+
* timeout) AND repeating the request must be safe (GET, HEAD, PUT, DELETE, or any request that
|
|
141
|
+
* carries an idempotency key).
|
|
142
|
+
*/
|
|
143
|
+
export function shouldRetry(method, hasIdempotencyKey, cause) {
|
|
144
|
+
const transient = typeof cause === 'number' ? isRetryableStatus(cause) : true;
|
|
145
|
+
const m = method.toUpperCase();
|
|
146
|
+
const repeatable = m === 'GET' || m === 'HEAD' || m === 'PUT' || m === 'DELETE' || hasIdempotencyKey;
|
|
147
|
+
return transient && repeatable;
|
|
148
|
+
}
|
|
149
|
+
function abortError(signal, what) {
|
|
150
|
+
return new AbortError(what + ' was aborted', { cause: signal.reason });
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Starts a timer, or none (undefined) when the delay is infinite or longer than the platform can
|
|
154
|
+
* count: `setTimeout` would fire such a timer at once instead of never.
|
|
155
|
+
*/
|
|
156
|
+
export function startTimer(callback, ms) {
|
|
157
|
+
return ms > MAX_TIMER_MS ? undefined : setTimeout(callback, ms);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Waits `ms` milliseconds; rejects with an AbortError as soon as the signal aborts. A delay above
|
|
161
|
+
* {@link MAX_TIMER_MS} waits until the signal aborts.
|
|
162
|
+
*/
|
|
163
|
+
export function sleep(ms, signal) {
|
|
164
|
+
return new Promise((resolve, reject) => {
|
|
165
|
+
if (signal !== undefined && signal.aborted) {
|
|
166
|
+
reject(abortError(signal, 'The wait'));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const onAbort = () => {
|
|
170
|
+
clearTimeout(timer);
|
|
171
|
+
reject(abortError(signal, 'The wait'));
|
|
172
|
+
};
|
|
173
|
+
const timer = startTimer(() => {
|
|
174
|
+
if (signal !== undefined)
|
|
175
|
+
signal.removeEventListener('abort', onAbort);
|
|
176
|
+
resolve();
|
|
177
|
+
}, ms);
|
|
178
|
+
if (signal !== undefined)
|
|
179
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
function causeText(cause) {
|
|
183
|
+
if (!(cause instanceof Error))
|
|
184
|
+
return String(cause);
|
|
185
|
+
const inner = cause.cause;
|
|
186
|
+
if (inner instanceof Error && inner.message !== '' && inner.message !== cause.message) {
|
|
187
|
+
return cause.message + ': ' + inner.message;
|
|
188
|
+
}
|
|
189
|
+
return cause.message;
|
|
190
|
+
}
|
|
191
|
+
function positive(value, fallback, name, zeroAllowed) {
|
|
192
|
+
if (value === undefined)
|
|
193
|
+
return fallback;
|
|
194
|
+
if (typeof value !== 'number' || Number.isNaN(value) || value < 0 || (value === 0 && !zeroAllowed)) {
|
|
195
|
+
throw new ConfigError('The option "' + name + '" must be a ' + (zeroAllowed ? 'non-negative' : 'positive') + ' number');
|
|
196
|
+
}
|
|
197
|
+
return value;
|
|
198
|
+
}
|
|
199
|
+
function retries(value, fallback) {
|
|
200
|
+
if (value === undefined)
|
|
201
|
+
return fallback;
|
|
202
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
203
|
+
throw new ConfigError('The option "maxRetries" must be a non-negative integer');
|
|
204
|
+
}
|
|
205
|
+
return value;
|
|
206
|
+
}
|
|
207
|
+
class HeaderBag {
|
|
208
|
+
#map = new Map();
|
|
209
|
+
set(name, value) {
|
|
210
|
+
if (value.includes('\r') || value.includes('\n') || value.includes('\0') || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
|
|
211
|
+
throw new ValidationError('The header "' + name.replace(/[^ -~]/g, '?') + '" has an invalid name or value');
|
|
212
|
+
}
|
|
213
|
+
this.#map.set(name.toLowerCase(), [name, value]);
|
|
214
|
+
}
|
|
215
|
+
delete(name) {
|
|
216
|
+
this.#map.delete(name.toLowerCase());
|
|
217
|
+
}
|
|
218
|
+
has(name) {
|
|
219
|
+
return this.#map.has(name.toLowerCase());
|
|
220
|
+
}
|
|
221
|
+
toRecord() {
|
|
222
|
+
const out = {};
|
|
223
|
+
for (const [name, value] of this.#map.values())
|
|
224
|
+
out[name] = value;
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* A promise of a decoded response that also gives access to the raw response:
|
|
230
|
+
* `await client.companies.get(id)` yields the data, `.withResponse()` adds status, headers,
|
|
231
|
+
* request id and rate-limit information of that very response.
|
|
232
|
+
*/
|
|
233
|
+
export class APIPromise extends Promise {
|
|
234
|
+
#result;
|
|
235
|
+
constructor(result) {
|
|
236
|
+
super((resolve) => {
|
|
237
|
+
resolve(undefined);
|
|
238
|
+
});
|
|
239
|
+
this.#result = result;
|
|
240
|
+
}
|
|
241
|
+
/** The decoded data together with the status, headers, request id and rate limit of the response. */
|
|
242
|
+
withResponse() {
|
|
243
|
+
return this.#result;
|
|
244
|
+
}
|
|
245
|
+
/** Only the status, headers, request id and rate limit of the response. */
|
|
246
|
+
asResponse() {
|
|
247
|
+
return this.#result.then((r) => r.response);
|
|
248
|
+
}
|
|
249
|
+
then(onfulfilled, onrejected) {
|
|
250
|
+
return this.#result.then((r) => r.data).then(onfulfilled, onrejected);
|
|
251
|
+
}
|
|
252
|
+
catch(onrejected) {
|
|
253
|
+
return this.#result.then((r) => r.data).catch(onrejected);
|
|
254
|
+
}
|
|
255
|
+
finally(onfinally) {
|
|
256
|
+
return this.#result.then((r) => r.data).finally(onfinally);
|
|
257
|
+
}
|
|
258
|
+
static get [Symbol.species]() {
|
|
259
|
+
return Promise;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* A promise of an open stream that can also be iterated directly:
|
|
264
|
+
* `for await (const event of client.feed.listEvents(co))`. Awaiting it gives the stream object
|
|
265
|
+
* (with `response`, `close()` and, for chat streams, `dialogId` and `turnNo`).
|
|
266
|
+
*/
|
|
267
|
+
export class StreamPromise extends Promise {
|
|
268
|
+
#stream;
|
|
269
|
+
constructor(stream) {
|
|
270
|
+
super((resolve) => {
|
|
271
|
+
resolve(undefined);
|
|
272
|
+
});
|
|
273
|
+
this.#stream = stream;
|
|
274
|
+
}
|
|
275
|
+
then(onfulfilled, onrejected) {
|
|
276
|
+
return this.#stream.then(onfulfilled, onrejected);
|
|
277
|
+
}
|
|
278
|
+
catch(onrejected) {
|
|
279
|
+
return this.#stream.catch(onrejected);
|
|
280
|
+
}
|
|
281
|
+
finally(onfinally) {
|
|
282
|
+
return this.#stream.finally(onfinally);
|
|
283
|
+
}
|
|
284
|
+
async *[Symbol.asyncIterator]() {
|
|
285
|
+
const stream = await this.#stream;
|
|
286
|
+
yield* stream;
|
|
287
|
+
}
|
|
288
|
+
static get [Symbol.species]() {
|
|
289
|
+
return Promise;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* The HTTP engine shared by all resources: configuration, authentication, retries, timeouts,
|
|
294
|
+
* cancellation and decoding. It is immutable after construction and safe to share.
|
|
295
|
+
*/
|
|
296
|
+
export class APIClient {
|
|
297
|
+
/** Base URL without a trailing slash. */
|
|
298
|
+
baseUrl;
|
|
299
|
+
/** Default request timeout in milliseconds. */
|
|
300
|
+
timeout;
|
|
301
|
+
/** Default timeout of non-streaming chat turns in milliseconds. */
|
|
302
|
+
longRunningTimeout;
|
|
303
|
+
/** Default number of retries. */
|
|
304
|
+
maxRetries;
|
|
305
|
+
/** Default idle timeout of streams in milliseconds. */
|
|
306
|
+
streamIdleTimeout;
|
|
307
|
+
#apiKey;
|
|
308
|
+
#webhookSecret;
|
|
309
|
+
#fetch;
|
|
310
|
+
#defaultHeaders;
|
|
311
|
+
#bearer;
|
|
312
|
+
#logger;
|
|
313
|
+
constructor(options = {}) {
|
|
314
|
+
const baseUrl = (options.baseUrl ?? readEnv('TUNGO_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
315
|
+
let parsed;
|
|
316
|
+
try {
|
|
317
|
+
parsed = new URL(baseUrl);
|
|
318
|
+
}
|
|
319
|
+
catch (cause) {
|
|
320
|
+
throw new ConfigError('The base URL is not a valid absolute URL', { cause });
|
|
321
|
+
}
|
|
322
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
323
|
+
throw new ConfigError('The base URL must start with https:// or http://');
|
|
324
|
+
}
|
|
325
|
+
if (parsed.search !== '' || parsed.hash !== '' || parsed.username !== '' || parsed.password !== '') {
|
|
326
|
+
throw new ConfigError('The base URL must not contain credentials, a query string or a fragment');
|
|
327
|
+
}
|
|
328
|
+
this.baseUrl = baseUrl;
|
|
329
|
+
this.timeout = positive(options.timeout, DEFAULT_TIMEOUT, 'timeout', false);
|
|
330
|
+
this.longRunningTimeout = positive(options.longRunningTimeout, DEFAULT_LONG_RUNNING_TIMEOUT, 'longRunningTimeout', false);
|
|
331
|
+
this.streamIdleTimeout = positive(options.streamIdleTimeout, DEFAULT_STREAM_IDLE_TIMEOUT, 'streamIdleTimeout', true);
|
|
332
|
+
this.maxRetries = retries(options.maxRetries, DEFAULT_MAX_RETRIES);
|
|
333
|
+
const apiKey = options.apiKey ?? readEnv('TUNGO_API_KEY');
|
|
334
|
+
this.#apiKey = apiKey === '' ? undefined : apiKey;
|
|
335
|
+
const webhookSecret = options.webhookSecret ?? readEnv('TUNGO_WEBHOOK_SECRET');
|
|
336
|
+
this.#webhookSecret = webhookSecret === '' ? undefined : webhookSecret;
|
|
337
|
+
this.#bearer = options.authScheme === 'bearer';
|
|
338
|
+
this.#defaultHeaders = { ...(options.defaultHeaders ?? {}) };
|
|
339
|
+
this.#logger = options.logger;
|
|
340
|
+
if (options.fetch !== undefined) {
|
|
341
|
+
this.#fetch = options.fetch;
|
|
342
|
+
}
|
|
343
|
+
else if (typeof globalThis.fetch === 'function') {
|
|
344
|
+
this.#fetch = (input, init) => globalThis.fetch(input, init);
|
|
345
|
+
}
|
|
346
|
+
else {
|
|
347
|
+
throw new ConfigError('This runtime has no global fetch: pass a fetch implementation in the "fetch" option');
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/** The webhook secret to use: the explicit one, else the client's; a ConfigError when there is none. */
|
|
351
|
+
webhookSecret(explicit) {
|
|
352
|
+
const secret = explicit ?? this.#webhookSecret;
|
|
353
|
+
if (secret === undefined || secret === '') {
|
|
354
|
+
throw new ConfigError('No webhook secret: pass one or set the TUNGO_WEBHOOK_SECRET environment variable');
|
|
355
|
+
}
|
|
356
|
+
return secret;
|
|
357
|
+
}
|
|
358
|
+
/** Performs a request and decodes the JSON response. */
|
|
359
|
+
request(spec) {
|
|
360
|
+
return new APIPromise(this.#requestJSON(spec));
|
|
361
|
+
}
|
|
362
|
+
/** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
|
|
363
|
+
openStream(spec, make) {
|
|
364
|
+
return this.#exchange(spec, true).then((x) => make({
|
|
365
|
+
response: x.info,
|
|
366
|
+
body: x.response.body,
|
|
367
|
+
controller: x.controller,
|
|
368
|
+
signal: spec.options?.signal ?? undefined,
|
|
369
|
+
detach: x.detach,
|
|
370
|
+
idleTimeout: positive(spec.options?.streamIdleTimeout, this.streamIdleTimeout, 'streamIdleTimeout', true),
|
|
371
|
+
route: spec.method.toUpperCase() + ' ' + spec.path,
|
|
372
|
+
}));
|
|
373
|
+
}
|
|
374
|
+
async #requestJSON(spec) {
|
|
375
|
+
const x = await this.#exchange(spec, false);
|
|
376
|
+
const status = x.info.status;
|
|
377
|
+
if (spec.emptyResult === true || status === 204 || status === 205) {
|
|
378
|
+
return { data: undefined, response: x.info };
|
|
379
|
+
}
|
|
380
|
+
const route = spec.method.toUpperCase() + ' ' + spec.path;
|
|
381
|
+
if (x.text.trim() === '') {
|
|
382
|
+
throw new DecodeError('The response of ' + route + ' (status ' + status + ') has an empty body where JSON was expected', {
|
|
383
|
+
status,
|
|
384
|
+
requestId: x.info.requestId,
|
|
385
|
+
body: x.text,
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
try {
|
|
389
|
+
return { data: parseJSON(x.text), response: x.info };
|
|
390
|
+
}
|
|
391
|
+
catch (cause) {
|
|
392
|
+
throw new DecodeError('The response of ' + route + ' (status ' + status + ') is not valid JSON', {
|
|
393
|
+
status,
|
|
394
|
+
requestId: x.info.requestId,
|
|
395
|
+
body: x.text,
|
|
396
|
+
cause,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
#headers(spec, stream) {
|
|
401
|
+
const options = spec.options ?? {};
|
|
402
|
+
const bag = new HeaderBag();
|
|
403
|
+
bag.set('Accept', stream ? 'text/event-stream' : 'application/json');
|
|
404
|
+
bag.set('User-Agent', USER_AGENT);
|
|
405
|
+
if (spec.rawBody !== undefined) {
|
|
406
|
+
bag.set('Content-Type', spec.contentType ?? 'application/octet-stream');
|
|
407
|
+
}
|
|
408
|
+
else if (spec.body !== undefined) {
|
|
409
|
+
bag.set('Content-Type', 'application/json');
|
|
410
|
+
}
|
|
411
|
+
for (const [name, value] of Object.entries(this.#defaultHeaders))
|
|
412
|
+
bag.set(name, value);
|
|
413
|
+
for (const [name, value] of Object.entries(spec.headers ?? {})) {
|
|
414
|
+
if (value !== undefined)
|
|
415
|
+
bag.set(name, value);
|
|
416
|
+
}
|
|
417
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) {
|
|
418
|
+
if (value === null)
|
|
419
|
+
bag.delete(name);
|
|
420
|
+
else if (value !== undefined)
|
|
421
|
+
bag.set(name, value);
|
|
422
|
+
}
|
|
423
|
+
// Credentials go only to operations that require the API key.
|
|
424
|
+
bag.delete('x-api-key');
|
|
425
|
+
bag.delete('authorization');
|
|
426
|
+
if ((spec.auth ?? 'key') === 'key') {
|
|
427
|
+
const key = this.#apiKey;
|
|
428
|
+
if (key === undefined) {
|
|
429
|
+
throw new ConfigError('No API key: pass "apiKey" to the client or set the TUNGO_API_KEY environment variable');
|
|
430
|
+
}
|
|
431
|
+
if (this.#bearer)
|
|
432
|
+
bag.set('Authorization', 'Bearer ' + key);
|
|
433
|
+
else
|
|
434
|
+
bag.set('x-api-key', key);
|
|
435
|
+
}
|
|
436
|
+
const headerName = spec.idempotencyHeader ?? 'Idempotency-Key';
|
|
437
|
+
if (options.idempotencyKey !== undefined) {
|
|
438
|
+
if (options.idempotencyKey === '')
|
|
439
|
+
throw new ValidationError('The idempotency key must not be empty');
|
|
440
|
+
bag.set(headerName, options.idempotencyKey);
|
|
441
|
+
}
|
|
442
|
+
else if (spec.idempotencyHeader !== undefined && !bag.has(headerName)) {
|
|
443
|
+
bag.set(headerName, uuid4());
|
|
444
|
+
}
|
|
445
|
+
return { headers: bag.toRecord(), hasIdempotencyKey: bag.has(headerName) };
|
|
446
|
+
}
|
|
447
|
+
#log(event) {
|
|
448
|
+
const logger = this.#logger;
|
|
449
|
+
if (logger === undefined)
|
|
450
|
+
return;
|
|
451
|
+
try {
|
|
452
|
+
logger(event);
|
|
453
|
+
}
|
|
454
|
+
catch {
|
|
455
|
+
// A failing logger must not break the request.
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Fetches without ever following a redirect: the request carries the API key in a custom
|
|
460
|
+
* header, which no HTTP client strips when a redirect leads to another host. A 3xx answer is
|
|
461
|
+
* returned as it is and becomes an APIError with that status.
|
|
462
|
+
*/
|
|
463
|
+
async #fetchNoRedirect(url, init) {
|
|
464
|
+
const res = await this.#fetch(url, init);
|
|
465
|
+
if (res.type === 'opaqueredirect') {
|
|
466
|
+
// Browsers hide the status and the headers of a redirect fetched with redirect: 'manual'.
|
|
467
|
+
throw new ConnectionError('The API answered with a redirect, which is never followed');
|
|
468
|
+
}
|
|
469
|
+
return res;
|
|
470
|
+
}
|
|
471
|
+
async #exchange(spec, stream) {
|
|
472
|
+
const options = spec.options ?? {};
|
|
473
|
+
const signal = options.signal ?? undefined;
|
|
474
|
+
const method = spec.method.toUpperCase();
|
|
475
|
+
const route = method + ' ' + spec.path;
|
|
476
|
+
if (signal !== undefined && signal.aborted)
|
|
477
|
+
throw abortError(signal, 'The request ' + route);
|
|
478
|
+
const query = buildQuery(spec.query);
|
|
479
|
+
const url = this.baseUrl + buildPath(spec.path, spec.pathParams) + (query === '' ? '' : '?' + query);
|
|
480
|
+
const { headers, hasIdempotencyKey } = this.#headers(spec, stream);
|
|
481
|
+
let body;
|
|
482
|
+
if (spec.rawBody !== undefined)
|
|
483
|
+
body = spec.rawBody;
|
|
484
|
+
else if (spec.body !== undefined)
|
|
485
|
+
body = stringifyJSON(spec.body);
|
|
486
|
+
const maxRetries = retries(options.maxRetries, this.maxRetries);
|
|
487
|
+
const timeout = positive(options.timeout, spec.longRunning === true ? this.longRunningTimeout : this.timeout, 'timeout', false);
|
|
488
|
+
for (let attempt = 0;; attempt++) {
|
|
489
|
+
const controller = new AbortController();
|
|
490
|
+
let timedOut = false;
|
|
491
|
+
// No timer at all for an unlimited timeout (see MAX_TIMER_MS).
|
|
492
|
+
const timer = startTimer(() => {
|
|
493
|
+
timedOut = true;
|
|
494
|
+
controller.abort();
|
|
495
|
+
}, timeout);
|
|
496
|
+
const onAbort = () => {
|
|
497
|
+
controller.abort();
|
|
498
|
+
};
|
|
499
|
+
const detach = () => {
|
|
500
|
+
if (signal !== undefined)
|
|
501
|
+
signal.removeEventListener('abort', onAbort);
|
|
502
|
+
};
|
|
503
|
+
if (signal !== undefined)
|
|
504
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
505
|
+
const started = Date.now();
|
|
506
|
+
let keepOpen = false;
|
|
507
|
+
let failure;
|
|
508
|
+
let cause;
|
|
509
|
+
let retryAfter = null;
|
|
510
|
+
this.#log({ kind: 'request', method, route: spec.path, attempt: attempt + 1 });
|
|
511
|
+
try {
|
|
512
|
+
const init = { method, headers, signal: controller.signal, redirect: 'manual' };
|
|
513
|
+
if (body !== undefined)
|
|
514
|
+
init.body = body;
|
|
515
|
+
const response = await this.#fetchNoRedirect(url, init);
|
|
516
|
+
const requestId = response.headers.get('x-request-id');
|
|
517
|
+
const info = {
|
|
518
|
+
status: response.status,
|
|
519
|
+
headers: response.headers,
|
|
520
|
+
requestId: requestId === '' ? null : requestId,
|
|
521
|
+
rateLimit: parseRateLimit(response.headers),
|
|
522
|
+
attempts: attempt + 1,
|
|
523
|
+
};
|
|
524
|
+
if (response.status >= 200 && response.status < 300) {
|
|
525
|
+
if (stream) {
|
|
526
|
+
const contentType = (response.headers.get('content-type') ?? '').trim().toLowerCase();
|
|
527
|
+
if (!contentType.startsWith('text/event-stream')) {
|
|
528
|
+
// Not an event stream (a proxy page, a JSON body): reading it as one would yield
|
|
529
|
+
// zero events and look like a turn that produced nothing.
|
|
530
|
+
const unexpected = await response.text();
|
|
531
|
+
const shown = contentType === '' ? 'missing' : '"' + contentType.replace(/[^ -~]/g, '?').slice(0, 100) + '"';
|
|
532
|
+
throw new DecodeError('The response of ' + route + ' (status ' + response.status + ') is not an event stream: its content type is ' + shown, {
|
|
533
|
+
status: response.status,
|
|
534
|
+
requestId: info.requestId,
|
|
535
|
+
body: unexpected,
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
keepOpen = true;
|
|
539
|
+
clearTimeout(timer);
|
|
540
|
+
this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
|
|
541
|
+
return { info, text: '', response, controller, detach };
|
|
542
|
+
}
|
|
543
|
+
const text = await response.text();
|
|
544
|
+
this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
|
|
545
|
+
return { info, text, response, controller, detach };
|
|
546
|
+
}
|
|
547
|
+
const text = await response.text();
|
|
548
|
+
this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
|
|
549
|
+
const apiError = apiErrorFromResponse(response.status, response.headers, text);
|
|
550
|
+
failure = apiError;
|
|
551
|
+
cause = response.status;
|
|
552
|
+
retryAfter = apiError.retryAfter;
|
|
553
|
+
}
|
|
554
|
+
catch (reason) {
|
|
555
|
+
if (signal !== undefined && signal.aborted)
|
|
556
|
+
throw abortError(signal, 'The request ' + route);
|
|
557
|
+
if (reason instanceof TungoError)
|
|
558
|
+
throw reason;
|
|
559
|
+
if (timedOut) {
|
|
560
|
+
failure = new TimeoutError('The request ' + route + ' timed out after ' + timeout + ' ms', timeout, { cause: reason });
|
|
561
|
+
cause = 'timeout';
|
|
562
|
+
}
|
|
563
|
+
else {
|
|
564
|
+
failure = new ConnectionError('Could not reach the API for ' + route + ': ' + causeText(reason), { cause: reason });
|
|
565
|
+
cause = 'connection_error';
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
finally {
|
|
569
|
+
if (!keepOpen) {
|
|
570
|
+
clearTimeout(timer);
|
|
571
|
+
detach();
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
const retry = attempt < maxRetries && shouldRetry(method, hasIdempotencyKey, cause) && (retryAfter === null || retryAfter <= MAX_RETRY_AFTER_SECONDS);
|
|
575
|
+
if (!retry) {
|
|
576
|
+
this.#log({ kind: 'error', method, route: spec.path, attempt: attempt + 1, error: failure });
|
|
577
|
+
throw failure;
|
|
578
|
+
}
|
|
579
|
+
// A delay of zero (also an HTTP-date that has already passed) is not an order to hammer the
|
|
580
|
+
// server at once: the computed backoff applies.
|
|
581
|
+
const delayMs = retryAfter !== null && retryAfter > 0 ? Math.ceil(retryAfter * 1000) : Math.round(backoffDelay(attempt));
|
|
582
|
+
const event = { kind: 'retry', method, route: spec.path, attempt: attempt + 1, delayMs, error: failure };
|
|
583
|
+
if (failure instanceof APIError && failure.status !== undefined)
|
|
584
|
+
event.status = failure.status;
|
|
585
|
+
this.#log(event);
|
|
586
|
+
await sleep(delayMs, signal);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|