@tungoai/sdk 0.0.0-stage → 0.3.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/LICENSE +21 -0
  3. package/README.kk.md +327 -0
  4. package/README.md +346 -2
  5. package/README.ru.md +327 -0
  6. package/dist/cjs/chat.d.ts +85 -0
  7. package/dist/cjs/chat.js +152 -0
  8. package/dist/cjs/client.d.ts +117 -0
  9. package/dist/cjs/client.js +225 -0
  10. package/dist/cjs/core.d.ts +217 -0
  11. package/dist/cjs/core.js +779 -0
  12. package/dist/cjs/errors.d.ts +237 -0
  13. package/dist/cjs/errors.js +446 -0
  14. package/dist/cjs/generated/resources.d.ts +1149 -0
  15. package/dist/cjs/generated/resources.js +1145 -0
  16. package/dist/cjs/generated/types.d.ts +5435 -0
  17. package/dist/cjs/generated/types.js +11 -0
  18. package/dist/cjs/index.d.ts +12 -0
  19. package/dist/cjs/index.js +81 -0
  20. package/dist/cjs/json.d.ts +16 -0
  21. package/dist/cjs/json.js +137 -0
  22. package/dist/cjs/money.d.ts +32 -0
  23. package/dist/cjs/money.js +141 -0
  24. package/dist/cjs/package.json +1 -0
  25. package/dist/cjs/pagination.d.ts +47 -0
  26. package/dist/cjs/pagination.js +114 -0
  27. package/dist/cjs/streaming.d.ts +76 -0
  28. package/dist/cjs/streaming.js +291 -0
  29. package/dist/cjs/version.d.ts +2 -0
  30. package/dist/cjs/version.js +6 -0
  31. package/dist/cjs/webhooks.d.ts +79 -0
  32. package/dist/cjs/webhooks.js +262 -0
  33. package/dist/esm/chat.d.ts +85 -0
  34. package/dist/esm/chat.js +144 -0
  35. package/dist/esm/client.d.ts +117 -0
  36. package/dist/esm/client.js +221 -0
  37. package/dist/esm/core.d.ts +217 -0
  38. package/dist/esm/core.js +763 -0
  39. package/dist/esm/errors.d.ts +237 -0
  40. package/dist/esm/errors.js +416 -0
  41. package/dist/esm/generated/resources.d.ts +1149 -0
  42. package/dist/esm/generated/resources.js +1129 -0
  43. package/dist/esm/generated/types.d.ts +5435 -0
  44. package/dist/esm/generated/types.js +10 -0
  45. package/dist/esm/index.d.ts +12 -0
  46. package/dist/esm/index.js +11 -0
  47. package/dist/esm/json.d.ts +16 -0
  48. package/dist/esm/json.js +132 -0
  49. package/dist/esm/money.d.ts +32 -0
  50. package/dist/esm/money.js +137 -0
  51. package/dist/esm/package.json +1 -0
  52. package/dist/esm/pagination.d.ts +47 -0
  53. package/dist/esm/pagination.js +108 -0
  54. package/dist/esm/streaming.d.ts +76 -0
  55. package/dist/esm/streaming.js +285 -0
  56. package/dist/esm/version.d.ts +2 -0
  57. package/dist/esm/version.js +3 -0
  58. package/dist/esm/webhooks.d.ts +79 -0
  59. package/dist/esm/webhooks.js +253 -0
  60. package/package.json +67 -4
@@ -0,0 +1,779 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.APIClient = exports.StreamPromise = exports.APIPromise = exports.MAX_TIMER_MS = exports.MAX_RETRY_AFTER_SECONDS = exports.DEFAULT_STREAM_IDLE_TIMEOUT = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_LONG_RUNNING_TIMEOUT = exports.DEFAULT_TIMEOUT = exports.DEFAULT_BASE_URL = void 0;
4
+ exports.readEnv = readEnv;
5
+ exports.uuid4 = uuid4;
6
+ exports.encodePathSegment = encodePathSegment;
7
+ exports.buildPath = buildPath;
8
+ exports.buildQuery = buildQuery;
9
+ exports.backoffDelay = backoffDelay;
10
+ exports.isRetryableStatus = isRetryableStatus;
11
+ exports.shouldRetry = shouldRetry;
12
+ exports.startTimer = startTimer;
13
+ exports.sleep = sleep;
14
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
15
+ const errors_js_1 = require("./errors.js");
16
+ const json_js_1 = require("./json.js");
17
+ const version_js_1 = require("./version.js");
18
+ /** The production API host. */
19
+ exports.DEFAULT_BASE_URL = 'https://api.tungo.kz';
20
+ /** Default timeout of an ordinary request, in milliseconds. */
21
+ exports.DEFAULT_TIMEOUT = 60_000;
22
+ /** Default timeout of a non-streaming chat turn, in milliseconds. */
23
+ exports.DEFAULT_LONG_RUNNING_TIMEOUT = 600_000;
24
+ /** Default number of retries (so 3 attempts in total). */
25
+ exports.DEFAULT_MAX_RETRIES = 2;
26
+ /** Default idle timeout of a stream, in milliseconds. */
27
+ exports.DEFAULT_STREAM_IDLE_TIMEOUT = 120_000;
28
+ /** A server-requested delay above this many seconds is not slept: the error is raised instead. */
29
+ exports.MAX_RETRY_AFTER_SECONDS = 60;
30
+ /**
31
+ * The longest delay a platform timer supports, in milliseconds (2^31 - 1, about 24.8 days).
32
+ * A timeout above it, `Infinity` included, means "no time limit": no timer is started.
33
+ */
34
+ exports.MAX_TIMER_MS = 2_147_483_647;
35
+ const USER_AGENT = 'tungo-sdk-typescript/' + version_js_1.VERSION;
36
+ /** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
37
+ /** Whether a stream call was answered with a stored result replayed by Idempotency-Key. */
38
+ function isReplayedJSON(headers) {
39
+ const mediaType = (headers.get('content-type') ?? '').split(';')[0] ?? '';
40
+ return mediaType.trim().toLowerCase() === 'application/json' && (headers.get('idempotent-replayed') ?? '').trim().toLowerCase() === 'true';
41
+ }
42
+ function isObject(value) {
43
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
44
+ }
45
+ /**
46
+ * Turns a replayed ChatTurnResult into the event stream of the turn it stands for: text (the
47
+ * answer), proposal, question, citation, error, choice and next events, then done. The dialog id and
48
+ * the turn number, which a replay carries only in the body, become the X-Dialog-Id and X-Turn-No
49
+ * headers when they are missing: `headers` are those of the response with them, the other headers
50
+ * (Idempotent-Replayed among them) unchanged. Returns null when the body is not a chat turn result.
51
+ */
52
+ function replayAsEventStream(response, text, requestId) {
53
+ let result;
54
+ try {
55
+ result = (0, json_js_1.parseJSON)(text);
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ if (!isObject(result))
61
+ return null;
62
+ const dialogId = result['dialog_id'];
63
+ if (typeof dialogId !== 'string')
64
+ return null;
65
+ const headers = new Headers(response.headers);
66
+ if ((headers.get('x-dialog-id') ?? '') === '')
67
+ headers.set('x-dialog-id', dialogId);
68
+ const turnNo = result['turn_no'];
69
+ if ((headers.get('x-turn-no') ?? '') === '' && (typeof turnNo === 'number' || typeof turnNo === 'bigint'))
70
+ headers.set('x-turn-no', String(turnNo));
71
+ const entries = (key) => {
72
+ const list = result[key];
73
+ return Array.isArray(list) ? list.filter(isObject) : [];
74
+ };
75
+ let body = '';
76
+ const emit = (type, event) => {
77
+ body += 'event: ' + type + '\ndata: ' + (0, json_js_1.stringifyJSON)({ ...event, type }) + '\n\n';
78
+ };
79
+ const answerValue = result['answer'];
80
+ const answer = typeof answerValue === 'string' ? answerValue : '';
81
+ if (answer !== '')
82
+ emit('text', { delta: answer });
83
+ for (const { id, ...rest } of entries('proposals'))
84
+ emit('proposal', { ...rest, proposal_id: id });
85
+ for (const question of entries('questions'))
86
+ emit('question', question);
87
+ for (const citation of entries('citations'))
88
+ emit('citation', citation);
89
+ for (const error of entries('errors'))
90
+ emit('error', { error, request_id: requestId });
91
+ const done = { answer };
92
+ const stopReason = result['stop_reason'];
93
+ if (typeof stopReason === 'string')
94
+ done['stop_reason'] = stopReason;
95
+ const usageValue = result['usage'];
96
+ if (isObject(usageValue)) {
97
+ const { cost_tiyn: cost, ...usage } = usageValue;
98
+ done['usage'] = usage;
99
+ if (cost !== undefined)
100
+ done['cost_tiyn'] = cost;
101
+ }
102
+ const pending = result['pending_question'];
103
+ if (isObject(pending)) {
104
+ emit('choice', pending);
105
+ done['choice_id'] = pending['choice_id'];
106
+ }
107
+ // A live turn ends its finished answer with next right before done; the stored result keeps it
108
+ // as followups and next_action.
109
+ const followups = Array.isArray(result['followups']) ? result['followups'] : [];
110
+ const action = result['next_action'];
111
+ if (followups.length > 0 || isObject(action))
112
+ emit('next', { followups, action: isObject(action) ? action : null });
113
+ emit('done', done);
114
+ const streamHeaders = new Headers(headers);
115
+ streamHeaders.set('content-type', 'text/event-stream');
116
+ return { response: new Response(body, { status: response.status, headers: streamHeaders }), headers };
117
+ }
118
+ function readEnv(name) {
119
+ try {
120
+ const scope = globalThis;
121
+ const fromProcess = scope.process?.env?.[name];
122
+ if (typeof fromProcess === 'string' && fromProcess !== '')
123
+ return fromProcess;
124
+ const fromDeno = scope.Deno?.env?.get?.(name);
125
+ if (typeof fromDeno === 'string' && fromDeno !== '')
126
+ return fromDeno;
127
+ }
128
+ catch {
129
+ // No permission to read the environment.
130
+ }
131
+ return undefined;
132
+ }
133
+ /**
134
+ * The `idempotency_key` field of a JSON object body (approving a proposal documents it as the same
135
+ * as the header), trimmed like the API trims it. The API prefers the header over the field, so a
136
+ * generated header would make the caller's own key useless. A key that cannot travel in a header
137
+ * (outside printable ASCII) is ignored here.
138
+ */
139
+ function bodyIdempotencyKey(body) {
140
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
141
+ return undefined;
142
+ const value = body['idempotency_key'];
143
+ if (typeof value !== 'string')
144
+ return undefined;
145
+ const key = value.trim();
146
+ return key !== '' && /^[\x20-\x7e]+$/.test(key) ? key : undefined;
147
+ }
148
+ /** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
149
+ function uuid4() {
150
+ const bytes = new Uint8Array(16);
151
+ crypto.getRandomValues(bytes);
152
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
153
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
154
+ let hex = '';
155
+ for (const b of bytes)
156
+ hex += b.toString(16).padStart(2, '0');
157
+ return hex.slice(0, 8) + '-' + hex.slice(8, 12) + '-' + hex.slice(12, 16) + '-' + hex.slice(16, 20) + '-' + hex.slice(20);
158
+ }
159
+ /**
160
+ * Percent-encodes a value as ONE path segment (`/`, `?`, `#`, spaces, CR/LF and non-ASCII are all
161
+ * encoded). An empty value, `.` and `..` are rejected because they would change the path.
162
+ */
163
+ function encodePathSegment(value, name = 'value') {
164
+ if (typeof value !== 'string') {
165
+ throw new errors_js_1.ValidationError('The path parameter "' + name + '" must be a string');
166
+ }
167
+ if (value === '' || value === '.' || value === '..') {
168
+ throw new errors_js_1.ValidationError('The path parameter "' + name + '" must not be empty, "." or ".."');
169
+ }
170
+ try {
171
+ return encodeURIComponent(value).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
172
+ }
173
+ catch (cause) {
174
+ throw new errors_js_1.ValidationError('The path parameter "' + name + '" is not valid Unicode text', { cause });
175
+ }
176
+ }
177
+ /** Fills a path template (`/v1/companies/{co}`) with encoded parameter values. */
178
+ function buildPath(template, params) {
179
+ return template.replace(/\{([^{}]+)\}/g, (_match, name) => {
180
+ const value = params === undefined ? undefined : params[name];
181
+ return encodePathSegment(value, name);
182
+ });
183
+ }
184
+ function queryText(name, value) {
185
+ switch (typeof value) {
186
+ case 'string':
187
+ return value;
188
+ case 'boolean':
189
+ return value ? 'true' : 'false';
190
+ case 'bigint':
191
+ return value.toString();
192
+ case 'number':
193
+ if (!Number.isFinite(value))
194
+ break;
195
+ return String(value);
196
+ case 'object':
197
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
198
+ return value.toISOString();
199
+ break;
200
+ default:
201
+ break;
202
+ }
203
+ throw new errors_js_1.ValidationError('The query parameter "' + name + '" has a value that cannot be sent');
204
+ }
205
+ /**
206
+ * Builds a query string (without the leading `?`): booleans as `true`/`false`, dates as RFC 3339,
207
+ * arrays as repeated keys, null and undefined omitted, `+` encoded as `%2B`.
208
+ */
209
+ function buildQuery(query) {
210
+ if (query === undefined)
211
+ return '';
212
+ const parts = [];
213
+ const add = (name, value) => {
214
+ try {
215
+ parts.push(encodeURIComponent(name) + '=' + encodeURIComponent(queryText(name, value)));
216
+ }
217
+ catch (cause) {
218
+ if (cause instanceof errors_js_1.TungoError)
219
+ throw cause;
220
+ throw new errors_js_1.ValidationError('The query parameter "' + name + '" is not valid Unicode text', { cause });
221
+ }
222
+ };
223
+ for (const [name, value] of Object.entries(query)) {
224
+ if (value === undefined || value === null)
225
+ continue;
226
+ if (Array.isArray(value)) {
227
+ for (const item of value) {
228
+ if (item !== undefined && item !== null)
229
+ add(name, item);
230
+ }
231
+ }
232
+ else {
233
+ add(name, value);
234
+ }
235
+ }
236
+ return parts.join('&');
237
+ }
238
+ /** Delay before retry number `attempt` (0-based), in milliseconds: min(0.5 s * 2^attempt, 8 s) * [0.75, 1]. */
239
+ function backoffDelay(attempt, random = Math.random) {
240
+ const base = Math.min(500 * 2 ** attempt, 8000);
241
+ return base * (0.75 + 0.25 * random());
242
+ }
243
+ /** Statuses after which a request may be repeated. */
244
+ function isRetryableStatus(status) {
245
+ return status === 408 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
246
+ }
247
+ /**
248
+ * The retry rule: the failure must be transient (a retryable status, a connection error or a
249
+ * timeout) AND repeating the request must be safe (GET, HEAD, PUT, DELETE, or any request that
250
+ * carries an idempotency key).
251
+ */
252
+ function shouldRetry(method, hasIdempotencyKey, cause) {
253
+ const transient = typeof cause === 'number' ? isRetryableStatus(cause) : true;
254
+ const m = method.toUpperCase();
255
+ const repeatable = m === 'GET' || m === 'HEAD' || m === 'PUT' || m === 'DELETE' || hasIdempotencyKey;
256
+ return transient && repeatable;
257
+ }
258
+ function abortError(signal, what) {
259
+ return new errors_js_1.AbortError(what + ' was aborted', { cause: signal.reason });
260
+ }
261
+ /**
262
+ * Starts a timer, or none (undefined) when the delay is infinite or longer than the platform can
263
+ * count: `setTimeout` would fire such a timer at once instead of never.
264
+ */
265
+ function startTimer(callback, ms) {
266
+ return ms > exports.MAX_TIMER_MS ? undefined : setTimeout(callback, ms);
267
+ }
268
+ /**
269
+ * Waits `ms` milliseconds; rejects with an AbortError as soon as the signal aborts. A delay above
270
+ * {@link MAX_TIMER_MS} waits until the signal aborts.
271
+ */
272
+ function sleep(ms, signal) {
273
+ return new Promise((resolve, reject) => {
274
+ if (signal !== undefined && signal.aborted) {
275
+ reject(abortError(signal, 'The wait'));
276
+ return;
277
+ }
278
+ const onAbort = () => {
279
+ clearTimeout(timer);
280
+ reject(abortError(signal, 'The wait'));
281
+ };
282
+ const timer = startTimer(() => {
283
+ if (signal !== undefined)
284
+ signal.removeEventListener('abort', onAbort);
285
+ resolve();
286
+ }, ms);
287
+ if (signal !== undefined)
288
+ signal.addEventListener('abort', onAbort, { once: true });
289
+ });
290
+ }
291
+ function causeText(cause) {
292
+ if (!(cause instanceof Error))
293
+ return String(cause);
294
+ const inner = cause.cause;
295
+ if (inner instanceof Error && inner.message !== '' && inner.message !== cause.message) {
296
+ return cause.message + ': ' + inner.message;
297
+ }
298
+ return cause.message;
299
+ }
300
+ /**
301
+ * The text of a transport failure without the request URL: a custom fetch (node-fetch, a proxy
302
+ * or tracing wrapper) may put the full URL into its message, and the path can carry a hook token
303
+ * and the query search text. The URL and the concrete path become the route template, and any
304
+ * other absolute URL and every path parameter value are cut out.
305
+ */
306
+ function redactedCauseText(cause, baseUrl, url, spec) {
307
+ let text = causeText(cause);
308
+ const path = buildPath(spec.path, spec.pathParams);
309
+ const pathAndQuery = url.slice(baseUrl.length);
310
+ for (const concrete of [url, url.split('?')[0] ?? url, pathAndQuery, path]) {
311
+ if (concrete !== '' && concrete !== '/')
312
+ text = text.split(concrete).join(spec.path);
313
+ }
314
+ text = text.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*/gi, '[url]');
315
+ for (const value of Object.values(spec.pathParams ?? {})) {
316
+ if (typeof value !== 'string' || value === '')
317
+ continue;
318
+ for (const form of new Set([value, encodeURIComponent(value)]))
319
+ text = text.split(form).join('[redacted]');
320
+ }
321
+ return text;
322
+ }
323
+ function positive(value, fallback, name, zeroAllowed) {
324
+ if (value === undefined)
325
+ return fallback;
326
+ if (typeof value !== 'number' || Number.isNaN(value) || value < 0 || (value === 0 && !zeroAllowed)) {
327
+ throw new errors_js_1.ConfigError('The option "' + name + '" must be a ' + (zeroAllowed ? 'non-negative' : 'positive') + ' number');
328
+ }
329
+ return value;
330
+ }
331
+ function retries(value, fallback) {
332
+ if (value === undefined)
333
+ return fallback;
334
+ if (!Number.isInteger(value) || value < 0) {
335
+ throw new errors_js_1.ConfigError('The option "maxRetries" must be a non-negative integer');
336
+ }
337
+ return value;
338
+ }
339
+ /**
340
+ * Whether a header value can be sent at all: fetch refuses CR, LF and NUL, and a character above
341
+ * U+00FF (a Cyrillic look-alike pasted into a key) is not a byte, so fetch would throw a
342
+ * TypeError that looks like a network failure.
343
+ */
344
+ function sendableHeaderValue(value) {
345
+ for (let i = 0; i < value.length; i++) {
346
+ const code = value.charCodeAt(i);
347
+ if (code === 0 || code === 10 || code === 13 || code > 0xff)
348
+ return false;
349
+ }
350
+ return true;
351
+ }
352
+ class HeaderBag {
353
+ #map = new Map();
354
+ set(name, value) {
355
+ if (!sendableHeaderValue(value) || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
356
+ throw new errors_js_1.ValidationError('The header "' + name.replace(/[^ -~]/g, '?') + '" has an invalid name or value');
357
+ }
358
+ this.#map.set(name.toLowerCase(), [name, value]);
359
+ }
360
+ delete(name) {
361
+ this.#map.delete(name.toLowerCase());
362
+ }
363
+ has(name) {
364
+ return this.#map.has(name.toLowerCase());
365
+ }
366
+ toRecord() {
367
+ const out = {};
368
+ for (const [name, value] of this.#map.values())
369
+ out[name] = value;
370
+ return out;
371
+ }
372
+ }
373
+ /**
374
+ * A promise of a decoded response that also gives access to the raw response:
375
+ * `await client.companies.get(id)` yields the data, `.withResponse()` adds status, headers,
376
+ * request id and rate-limit information of that very response.
377
+ */
378
+ class APIPromise extends Promise {
379
+ #result;
380
+ constructor(result) {
381
+ super((resolve) => {
382
+ resolve(undefined);
383
+ });
384
+ this.#result = result;
385
+ }
386
+ /** The decoded data together with the status, headers, request id and rate limit of the response. */
387
+ withResponse() {
388
+ return this.#result;
389
+ }
390
+ /** Only the status, headers, request id and rate limit of the response. */
391
+ asResponse() {
392
+ return this.#result.then((r) => r.response);
393
+ }
394
+ then(onfulfilled, onrejected) {
395
+ return this.#result.then((r) => r.data).then(onfulfilled, onrejected);
396
+ }
397
+ catch(onrejected) {
398
+ return this.#result.then((r) => r.data).catch(onrejected);
399
+ }
400
+ finally(onfinally) {
401
+ return this.#result.then((r) => r.data).finally(onfinally);
402
+ }
403
+ static get [Symbol.species]() {
404
+ return Promise;
405
+ }
406
+ }
407
+ exports.APIPromise = APIPromise;
408
+ /**
409
+ * A promise of an open stream that can also be iterated directly:
410
+ * `for await (const event of client.feed.listEvents(co))`. Awaiting it gives the stream object
411
+ * (with `response`, `close()` and, for chat streams, `dialogId` and `turnNo`).
412
+ */
413
+ class StreamPromise extends Promise {
414
+ #stream;
415
+ constructor(stream) {
416
+ super((resolve) => {
417
+ resolve(undefined);
418
+ });
419
+ this.#stream = stream;
420
+ }
421
+ then(onfulfilled, onrejected) {
422
+ return this.#stream.then(onfulfilled, onrejected);
423
+ }
424
+ catch(onrejected) {
425
+ return this.#stream.catch(onrejected);
426
+ }
427
+ finally(onfinally) {
428
+ return this.#stream.finally(onfinally);
429
+ }
430
+ async *[Symbol.asyncIterator]() {
431
+ const stream = await this.#stream;
432
+ yield* stream;
433
+ }
434
+ static get [Symbol.species]() {
435
+ return Promise;
436
+ }
437
+ }
438
+ exports.StreamPromise = StreamPromise;
439
+ /**
440
+ * The HTTP engine shared by all resources: configuration, authentication, retries, timeouts,
441
+ * cancellation and decoding. It is immutable after construction and safe to share.
442
+ */
443
+ class APIClient {
444
+ /** Base URL without a trailing slash. */
445
+ baseUrl;
446
+ /** Default request timeout in milliseconds. */
447
+ timeout;
448
+ /** Default timeout of non-streaming chat turns in milliseconds. */
449
+ longRunningTimeout;
450
+ /** Default number of retries. */
451
+ maxRetries;
452
+ /** Default idle timeout of streams in milliseconds. */
453
+ streamIdleTimeout;
454
+ #apiKey;
455
+ #webhookSecret;
456
+ #fetch;
457
+ #defaultHeaders;
458
+ #bearer;
459
+ #logger;
460
+ constructor(options = {}) {
461
+ const baseUrl = (options.baseUrl ?? readEnv('TUNGO_BASE_URL') ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
462
+ let parsed;
463
+ try {
464
+ parsed = new URL(baseUrl);
465
+ }
466
+ catch (cause) {
467
+ throw new errors_js_1.ConfigError('The base URL is not a valid absolute URL', { cause });
468
+ }
469
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
470
+ throw new errors_js_1.ConfigError('The base URL must start with https:// or http://');
471
+ }
472
+ if (parsed.search !== '' || parsed.hash !== '' || parsed.username !== '' || parsed.password !== '') {
473
+ throw new errors_js_1.ConfigError('The base URL must not contain credentials, a query string or a fragment');
474
+ }
475
+ this.baseUrl = baseUrl;
476
+ this.timeout = positive(options.timeout, exports.DEFAULT_TIMEOUT, 'timeout', false);
477
+ this.longRunningTimeout = positive(options.longRunningTimeout, exports.DEFAULT_LONG_RUNNING_TIMEOUT, 'longRunningTimeout', false);
478
+ this.streamIdleTimeout = positive(options.streamIdleTimeout, exports.DEFAULT_STREAM_IDLE_TIMEOUT, 'streamIdleTimeout', true);
479
+ this.maxRetries = retries(options.maxRetries, exports.DEFAULT_MAX_RETRIES);
480
+ const apiKey = options.apiKey ?? readEnv('TUNGO_API_KEY');
481
+ this.#apiKey = apiKey === '' ? undefined : apiKey;
482
+ const webhookSecret = options.webhookSecret ?? readEnv('TUNGO_WEBHOOK_SECRET');
483
+ this.#webhookSecret = webhookSecret === '' ? undefined : webhookSecret;
484
+ this.#bearer = options.authScheme === 'bearer';
485
+ this.#defaultHeaders = { ...(options.defaultHeaders ?? {}) };
486
+ this.#logger = options.logger;
487
+ if (options.fetch !== undefined) {
488
+ this.#fetch = options.fetch;
489
+ }
490
+ else if (typeof globalThis.fetch === 'function') {
491
+ this.#fetch = (input, init) => globalThis.fetch(input, init);
492
+ }
493
+ else {
494
+ throw new errors_js_1.ConfigError('This runtime has no global fetch: pass a fetch implementation in the "fetch" option');
495
+ }
496
+ }
497
+ /** The webhook secret to use: the explicit one, else the client's; a ConfigError when there is none. */
498
+ webhookSecret(explicit) {
499
+ const secret = explicit ?? this.#webhookSecret;
500
+ if (secret === undefined || secret === '') {
501
+ throw new errors_js_1.ConfigError('No webhook secret: pass one or set the TUNGO_WEBHOOK_SECRET environment variable');
502
+ }
503
+ return secret;
504
+ }
505
+ /** Performs a request and decodes the JSON response. */
506
+ request(spec) {
507
+ return new APIPromise(this.#requestJSON(spec));
508
+ }
509
+ /** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
510
+ async openStream(spec, make) {
511
+ // Checked before anything is sent: once the turn is posted it runs (and is billed) on the
512
+ // server, so a bad option found afterwards would cost a turn and leave the connection open.
513
+ const idleTimeout = positive(spec.options?.streamIdleTimeout, this.streamIdleTimeout, 'streamIdleTimeout', true);
514
+ const x = await this.#exchange(spec, true);
515
+ try {
516
+ return make({
517
+ response: x.info,
518
+ body: x.response.body,
519
+ controller: x.controller,
520
+ signal: spec.options?.signal ?? undefined,
521
+ detach: x.detach,
522
+ idleTimeout,
523
+ route: spec.method.toUpperCase() + ' ' + spec.path,
524
+ });
525
+ }
526
+ catch (error) {
527
+ // The stream object never came to be: nobody else can close the connection.
528
+ x.detach();
529
+ x.controller.abort();
530
+ x.response.body?.cancel().catch(() => undefined);
531
+ throw error;
532
+ }
533
+ }
534
+ async #requestJSON(spec) {
535
+ const x = await this.#exchange(spec, false);
536
+ const status = x.info.status;
537
+ if (spec.emptyResult === true || status === 204 || status === 205) {
538
+ return { data: undefined, response: x.info };
539
+ }
540
+ const route = spec.method.toUpperCase() + ' ' + spec.path;
541
+ if (x.text.trim() === '') {
542
+ throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + status + ') has an empty body where JSON was expected', {
543
+ status,
544
+ requestId: x.info.requestId,
545
+ body: x.text,
546
+ });
547
+ }
548
+ try {
549
+ return { data: (0, json_js_1.parseJSON)(x.text), response: x.info };
550
+ }
551
+ catch (cause) {
552
+ throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + status + ') is not valid JSON', {
553
+ status,
554
+ requestId: x.info.requestId,
555
+ body: x.text,
556
+ cause,
557
+ });
558
+ }
559
+ }
560
+ #headers(spec, stream) {
561
+ const options = spec.options ?? {};
562
+ const bag = new HeaderBag();
563
+ bag.set('Accept', stream ? 'text/event-stream' : 'application/json');
564
+ bag.set('User-Agent', USER_AGENT);
565
+ if (spec.rawBody !== undefined) {
566
+ bag.set('Content-Type', spec.contentType ?? 'application/octet-stream');
567
+ }
568
+ else if (spec.body !== undefined) {
569
+ bag.set('Content-Type', 'application/json');
570
+ }
571
+ for (const [name, value] of Object.entries(this.#defaultHeaders))
572
+ bag.set(name, value);
573
+ for (const [name, value] of Object.entries(spec.headers ?? {})) {
574
+ if (value !== undefined)
575
+ bag.set(name, value);
576
+ }
577
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
578
+ if (value === null)
579
+ bag.delete(name);
580
+ else if (value !== undefined)
581
+ bag.set(name, value);
582
+ }
583
+ // Credentials go only to operations that require the API key.
584
+ bag.delete('x-api-key');
585
+ bag.delete('authorization');
586
+ if ((spec.auth ?? 'key') === 'key') {
587
+ const key = this.#apiKey;
588
+ if (key === undefined) {
589
+ throw new errors_js_1.ConfigError('No API key: pass "apiKey" to the client or set the TUNGO_API_KEY environment variable');
590
+ }
591
+ if (!sendableHeaderValue(key)) {
592
+ // Never the key itself: only what is wrong with it.
593
+ throw new errors_js_1.ConfigError('The API key contains a character that cannot be sent in a header (a line break, or a letter outside Latin-1 such as a Cyrillic look-alike): check "apiKey" or TUNGO_API_KEY');
594
+ }
595
+ if (this.#bearer)
596
+ bag.set('Authorization', 'Bearer ' + key);
597
+ else
598
+ bag.set('x-api-key', key);
599
+ }
600
+ if (options.idempotencyKey === '')
601
+ throw new errors_js_1.ValidationError('The idempotency key must not be empty');
602
+ const headerName = spec.idempotencyHeader;
603
+ if (headerName === undefined) {
604
+ // The API ignores a key on an operation that declares none: sending one would make a retry
605
+ // look safe when it repeats the action.
606
+ bag.delete('Idempotency-Key');
607
+ return { headers: bag.toRecord(), hasIdempotencyKey: false };
608
+ }
609
+ if (options.idempotencyKey !== undefined) {
610
+ bag.set(headerName, options.idempotencyKey);
611
+ }
612
+ else if (!bag.has(headerName)) {
613
+ const fallback = spec.defaultIdempotencyKey !== undefined && spec.defaultIdempotencyKey !== '' ? spec.defaultIdempotencyKey : bodyIdempotencyKey(spec.body);
614
+ bag.set(headerName, fallback ?? uuid4());
615
+ }
616
+ return { headers: bag.toRecord(), hasIdempotencyKey: bag.has(headerName) };
617
+ }
618
+ #log(event) {
619
+ const logger = this.#logger;
620
+ if (logger === undefined)
621
+ return;
622
+ try {
623
+ logger(event);
624
+ }
625
+ catch {
626
+ // A failing logger must not break the request.
627
+ }
628
+ }
629
+ /**
630
+ * Fetches without ever following a redirect: the request carries the API key in a custom
631
+ * header, which no HTTP client strips when a redirect leads to another host. A 3xx answer is
632
+ * returned as it is and becomes an APIError with that status.
633
+ */
634
+ async #fetchNoRedirect(url, init) {
635
+ const res = await this.#fetch(url, init);
636
+ if (res.type === 'opaqueredirect') {
637
+ // Browsers hide the status and the headers of a redirect fetched with redirect: 'manual'.
638
+ throw new errors_js_1.ConnectionError('The API answered with a redirect, which is never followed');
639
+ }
640
+ return res;
641
+ }
642
+ async #exchange(spec, stream) {
643
+ const options = spec.options ?? {};
644
+ const signal = options.signal ?? undefined;
645
+ const method = spec.method.toUpperCase();
646
+ const route = method + ' ' + spec.path;
647
+ if (signal !== undefined && signal.aborted)
648
+ throw abortError(signal, 'The request ' + route);
649
+ const query = buildQuery(spec.query);
650
+ const url = this.baseUrl + buildPath(spec.path, spec.pathParams) + (query === '' ? '' : '?' + query);
651
+ const { headers, hasIdempotencyKey } = this.#headers(spec, stream);
652
+ let body;
653
+ if (spec.rawBody !== undefined)
654
+ body = spec.rawBody;
655
+ else if (spec.body !== undefined)
656
+ body = (0, json_js_1.stringifyJSON)(spec.body);
657
+ const maxRetries = retries(options.maxRetries, this.maxRetries);
658
+ const timeout = positive(options.timeout, spec.longRunning === true ? this.longRunningTimeout : this.timeout, 'timeout', false);
659
+ for (let attempt = 0;; attempt++) {
660
+ const controller = new AbortController();
661
+ let timedOut = false;
662
+ // No timer at all for an unlimited timeout (see MAX_TIMER_MS).
663
+ const timer = startTimer(() => {
664
+ timedOut = true;
665
+ controller.abort();
666
+ }, timeout);
667
+ const onAbort = () => {
668
+ controller.abort();
669
+ };
670
+ const detach = () => {
671
+ if (signal !== undefined)
672
+ signal.removeEventListener('abort', onAbort);
673
+ };
674
+ if (signal !== undefined)
675
+ signal.addEventListener('abort', onAbort, { once: true });
676
+ const started = Date.now();
677
+ let keepOpen = false;
678
+ let failure;
679
+ let cause;
680
+ let retryAfter = null;
681
+ this.#log({ kind: 'request', method, route: spec.path, attempt: attempt + 1 });
682
+ try {
683
+ const init = { method, headers, signal: controller.signal, redirect: 'manual' };
684
+ if (body !== undefined)
685
+ init.body = body;
686
+ const response = await this.#fetchNoRedirect(url, init);
687
+ const requestId = response.headers.get('x-request-id');
688
+ const info = {
689
+ status: response.status,
690
+ headers: response.headers,
691
+ requestId: requestId === '' ? null : requestId,
692
+ rateLimit: (0, errors_js_1.parseRateLimit)(response.headers),
693
+ attempts: attempt + 1,
694
+ };
695
+ if (response.status >= 200 && response.status < 300) {
696
+ if (stream && isReplayedJSON(response.headers)) {
697
+ // A chat turn repeated with the same Idempotency-Key after it finished: the server
698
+ // answers the stored ChatTurnResult instead of a stream. The caller gets its events.
699
+ const replayed = await response.text();
700
+ const synthesized = replayAsEventStream(response, replayed, info.requestId);
701
+ if (synthesized === null) {
702
+ throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + response.status + ') replays a result that is not a chat turn', {
703
+ status: response.status,
704
+ requestId: info.requestId,
705
+ body: replayed,
706
+ });
707
+ }
708
+ info.headers = synthesized.headers;
709
+ keepOpen = true;
710
+ clearTimeout(timer);
711
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
712
+ return { info, text: '', response: synthesized.response, controller, detach };
713
+ }
714
+ if (stream) {
715
+ const contentType = (response.headers.get('content-type') ?? '').trim().toLowerCase();
716
+ if (!contentType.startsWith('text/event-stream')) {
717
+ // Not an event stream (a proxy page, a JSON body): reading it as one would yield
718
+ // zero events and look like a turn that produced nothing.
719
+ const unexpected = await response.text();
720
+ const shown = contentType === '' ? 'missing' : '"' + contentType.replace(/[^ -~]/g, '?').slice(0, 100) + '"';
721
+ throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + response.status + ') is not an event stream: its content type is ' + shown, {
722
+ status: response.status,
723
+ requestId: info.requestId,
724
+ body: unexpected,
725
+ });
726
+ }
727
+ keepOpen = true;
728
+ clearTimeout(timer);
729
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
730
+ return { info, text: '', response, controller, detach };
731
+ }
732
+ const text = await response.text();
733
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
734
+ return { info, text, response, controller, detach };
735
+ }
736
+ const text = await response.text();
737
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
738
+ const apiError = (0, errors_js_1.apiErrorFromResponse)(response.status, response.headers, text);
739
+ failure = apiError;
740
+ cause = response.status;
741
+ retryAfter = apiError.retryAfter;
742
+ }
743
+ catch (reason) {
744
+ if (signal !== undefined && signal.aborted)
745
+ throw abortError(signal, 'The request ' + route);
746
+ if (reason instanceof errors_js_1.TungoError)
747
+ throw reason;
748
+ if (timedOut) {
749
+ failure = new errors_js_1.TimeoutError('The request ' + route + ' timed out after ' + timeout + ' ms', timeout, { cause: reason });
750
+ cause = 'timeout';
751
+ }
752
+ else {
753
+ failure = new errors_js_1.ConnectionError('Could not reach the API for ' + route + ': ' + redactedCauseText(reason, this.baseUrl, url, spec), { cause: reason });
754
+ cause = 'connection_error';
755
+ }
756
+ }
757
+ finally {
758
+ if (!keepOpen) {
759
+ clearTimeout(timer);
760
+ detach();
761
+ }
762
+ }
763
+ const retry = attempt < maxRetries && shouldRetry(method, hasIdempotencyKey, cause) && (retryAfter === null || retryAfter <= exports.MAX_RETRY_AFTER_SECONDS);
764
+ if (!retry) {
765
+ this.#log({ kind: 'error', method, route: spec.path, attempt: attempt + 1, error: failure });
766
+ throw failure;
767
+ }
768
+ // A delay of zero (also an HTTP-date that has already passed) is not an order to hammer the
769
+ // server at once: the computed backoff applies.
770
+ const delayMs = retryAfter !== null && retryAfter > 0 ? Math.ceil(retryAfter * 1000) : Math.round(backoffDelay(attempt));
771
+ const event = { kind: 'retry', method, route: spec.path, attempt: attempt + 1, delayMs, error: failure };
772
+ if (failure instanceof errors_js_1.APIError && failure.status !== undefined)
773
+ event.status = failure.status;
774
+ this.#log(event);
775
+ await sleep(delayMs, signal);
776
+ }
777
+ }
778
+ }
779
+ exports.APIClient = APIClient;