@tungoai/sdk 0.2.0 → 1.0.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 (47) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.kk.md +7 -5
  3. package/README.md +9 -7
  4. package/README.ru.md +7 -5
  5. package/dist/cjs/chat.js +3 -2
  6. package/dist/cjs/client.d.ts +6 -1
  7. package/dist/cjs/client.js +11 -3
  8. package/dist/cjs/core.d.ts +9 -2
  9. package/dist/cjs/core.js +191 -17
  10. package/dist/cjs/errors.d.ts +25 -0
  11. package/dist/cjs/errors.js +39 -3
  12. package/dist/cjs/generated/resources.d.ts +191 -2
  13. package/dist/cjs/generated/resources.js +197 -2
  14. package/dist/cjs/generated/types.d.ts +957 -428
  15. package/dist/cjs/index.d.ts +1 -1
  16. package/dist/cjs/index.js +3 -2
  17. package/dist/cjs/json.d.ts +6 -0
  18. package/dist/cjs/json.js +17 -0
  19. package/dist/cjs/pagination.js +2 -1
  20. package/dist/cjs/streaming.d.ts +4 -2
  21. package/dist/cjs/streaming.js +40 -2
  22. package/dist/cjs/version.d.ts +1 -1
  23. package/dist/cjs/version.js +1 -1
  24. package/dist/cjs/webhooks.d.ts +5 -0
  25. package/dist/cjs/webhooks.js +17 -3
  26. package/dist/esm/chat.js +3 -2
  27. package/dist/esm/client.d.ts +6 -1
  28. package/dist/esm/client.js +11 -3
  29. package/dist/esm/core.d.ts +9 -2
  30. package/dist/esm/core.js +191 -17
  31. package/dist/esm/errors.d.ts +25 -0
  32. package/dist/esm/errors.js +36 -1
  33. package/dist/esm/generated/resources.d.ts +191 -2
  34. package/dist/esm/generated/resources.js +194 -1
  35. package/dist/esm/generated/types.d.ts +957 -428
  36. package/dist/esm/index.d.ts +1 -1
  37. package/dist/esm/index.js +1 -1
  38. package/dist/esm/json.d.ts +6 -0
  39. package/dist/esm/json.js +16 -0
  40. package/dist/esm/pagination.js +2 -1
  41. package/dist/esm/streaming.d.ts +4 -2
  42. package/dist/esm/streaming.js +41 -3
  43. package/dist/esm/version.d.ts +1 -1
  44. package/dist/esm/version.js +1 -1
  45. package/dist/esm/webhooks.d.ts +5 -0
  46. package/dist/esm/webhooks.js +17 -3
  47. package/package.json +1 -1
@@ -2,7 +2,7 @@ export type * from './generated/types.js';
2
2
  export * from './generated/resources.js';
3
3
  export { Tungo, Tungo as TungoClient, type ChatInput, type WaitOptions } from './client.js';
4
4
  export { APIClient, APIPromise, StreamPromise, DEFAULT_BASE_URL, DEFAULT_LONG_RUNNING_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_STREAM_IDLE_TIMEOUT, DEFAULT_TIMEOUT, type ClientOptions, type Fetch, type LogEvent, type RequestOptions, type RequestSpec, type WithResponse, } from './core.js';
5
- export { APIError, AbortError, AuthenticationError, ConfigError, ConflictError, ConnectionError, DecodeError, GoneError, InternalServerError, InvalidRequestError, LimitError, MoneyError, NotFoundError, PaymentRequiredError, PermissionError, TimeoutError, TungoError, UnavailableError, ValidationError, WebhookVerificationError, type APIErrorType, type APIFieldError, type RateLimit, type WebhookVerificationReason, } from './errors.js';
5
+ export { APIError, AbortError, AuthenticationError, ConfigError, ConflictError, ConnectionError, DecodeError, GoneError, InternalServerError, InvalidRequestError, LimitError, MoneyError, NotFoundError, PaymentRequiredError, PermissionError, StreamError, TimeoutError, TungoError, UnavailableError, ValidationError, WebhookVerificationError, type APIErrorType, type APIFieldError, type RateLimit, type WebhookVerificationReason, } from './errors.js';
6
6
  export { SSEDecoder, Stream, type ResponseInfo, type ServerSentEvent } from './streaming.js';
7
7
  export { Page, PagePromise, type CursorPageBody } from './pagination.js';
8
8
  export { ChatAccumulator, ChatStream, ChatStreamPromise, accumulateChatStream, chatTurnError, type ChatStreamCallbacks, type ChatStreamResult, } from './chat.js';
package/dist/cjs/index.js CHANGED
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.stringifyJSON = exports.parseJSON = exports.isValidBinIin = exports.TungoMoney = exports.TungoKazakhstan = exports.verifyWebhook = exports.verifyHookSignature = exports.signHookPayload = exports.TungoWebhooks = exports.TungoHooks = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = exports.chatTurnError = exports.accumulateChatStream = exports.ChatStreamPromise = exports.ChatStream = exports.ChatAccumulator = exports.PagePromise = exports.Page = exports.Stream = exports.SSEDecoder = exports.WebhookVerificationError = exports.ValidationError = exports.UnavailableError = exports.TungoError = exports.TimeoutError = exports.PermissionError = exports.PaymentRequiredError = exports.NotFoundError = exports.MoneyError = exports.LimitError = exports.InvalidRequestError = exports.InternalServerError = exports.GoneError = exports.DecodeError = exports.ConnectionError = exports.ConflictError = exports.ConfigError = exports.AuthenticationError = exports.AbortError = exports.APIError = exports.DEFAULT_TIMEOUT = exports.DEFAULT_STREAM_IDLE_TIMEOUT = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_LONG_RUNNING_TIMEOUT = exports.DEFAULT_BASE_URL = exports.StreamPromise = exports.APIPromise = exports.APIClient = exports.TungoClient = exports.Tungo = void 0;
18
- exports.VERSION = void 0;
17
+ exports.parseJSON = exports.isValidBinIin = exports.TungoMoney = exports.TungoKazakhstan = exports.verifyWebhook = exports.verifyHookSignature = exports.signHookPayload = exports.TungoWebhooks = exports.TungoHooks = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = exports.chatTurnError = exports.accumulateChatStream = exports.ChatStreamPromise = exports.ChatStream = exports.ChatAccumulator = exports.PagePromise = exports.Page = exports.Stream = exports.SSEDecoder = exports.WebhookVerificationError = exports.ValidationError = exports.UnavailableError = exports.TungoError = exports.TimeoutError = exports.StreamError = exports.PermissionError = exports.PaymentRequiredError = exports.NotFoundError = exports.MoneyError = exports.LimitError = exports.InvalidRequestError = exports.InternalServerError = exports.GoneError = exports.DecodeError = exports.ConnectionError = exports.ConflictError = exports.ConfigError = exports.AuthenticationError = exports.AbortError = exports.APIError = exports.DEFAULT_TIMEOUT = exports.DEFAULT_STREAM_IDLE_TIMEOUT = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_LONG_RUNNING_TIMEOUT = exports.DEFAULT_BASE_URL = exports.StreamPromise = exports.APIPromise = exports.APIClient = exports.TungoClient = exports.Tungo = void 0;
18
+ exports.VERSION = exports.stringifyJSON = void 0;
19
19
  __exportStar(require("./generated/resources.js"), exports);
20
20
  var client_js_1 = require("./client.js");
21
21
  Object.defineProperty(exports, "Tungo", { enumerable: true, get: function () { return client_js_1.Tungo; } });
@@ -45,6 +45,7 @@ Object.defineProperty(exports, "MoneyError", { enumerable: true, get: function (
45
45
  Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
46
46
  Object.defineProperty(exports, "PaymentRequiredError", { enumerable: true, get: function () { return errors_js_1.PaymentRequiredError; } });
47
47
  Object.defineProperty(exports, "PermissionError", { enumerable: true, get: function () { return errors_js_1.PermissionError; } });
48
+ Object.defineProperty(exports, "StreamError", { enumerable: true, get: function () { return errors_js_1.StreamError; } });
48
49
  Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return errors_js_1.TimeoutError; } });
49
50
  Object.defineProperty(exports, "TungoError", { enumerable: true, get: function () { return errors_js_1.TungoError; } });
50
51
  Object.defineProperty(exports, "UnavailableError", { enumerable: true, get: function () { return errors_js_1.UnavailableError; } });
@@ -8,3 +8,9 @@ export declare function parseJSON(text: string): unknown;
8
8
  * NaN and Infinity (which JSON cannot express) and unserialisable values raise a ValidationError.
9
9
  */
10
10
  export declare function stringifyJSON(value: unknown): string;
11
+ /**
12
+ * The JSON text of a decoded value for an error message or the `body` of an error: like
13
+ * stringifyJSON (a bigint keeps every digit), but it never throws: `undefined` and a value JSON
14
+ * cannot express give ''.
15
+ */
16
+ export declare function debugJSON(value: unknown): string;
package/dist/cjs/json.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseJSON = parseJSON;
4
4
  exports.stringifyJSON = stringifyJSON;
5
+ exports.debugJSON = debugJSON;
5
6
  // Code generated by tungo-sdkgen. DO NOT EDIT.
6
7
  const errors_js_1 = require("./errors.js");
7
8
  // JSON numbers are IEEE doubles in JavaScript, so an integer beyond 2^53 would silently lose its
@@ -118,3 +119,19 @@ function stringifyJSON(value) {
118
119
  return text;
119
120
  return text.replace(new RegExp('"\\\\u0000' + prefix + '(-?[0-9]+)"', 'g'), '$1');
120
121
  }
122
+ /**
123
+ * The JSON text of a decoded value for an error message or the `body` of an error: like
124
+ * stringifyJSON (a bigint keeps every digit), but it never throws: `undefined` and a value JSON
125
+ * cannot express give ''.
126
+ */
127
+ function debugJSON(value) {
128
+ if (value === undefined)
129
+ return '';
130
+ try {
131
+ return stringifyJSON(value);
132
+ }
133
+ catch {
134
+ // NaN or Infinity inside, a cycle: the error is still raised, only without its body.
135
+ return '';
136
+ }
137
+ }
@@ -5,6 +5,7 @@ exports.requestPage = requestPage;
5
5
  // Code generated by tungo-sdkgen. DO NOT EDIT.
6
6
  const core_js_1 = require("./core.js");
7
7
  const errors_js_1 = require("./errors.js");
8
+ const json_js_1 = require("./json.js");
8
9
  /**
9
10
  * One page of a cursor-paginated list. `data` holds the items of this page, `body` the complete
10
11
  * typed response (totals and other fields next to `data`). Iterating the page with `for await`
@@ -30,7 +31,7 @@ class Page {
30
31
  throw new errors_js_1.DecodeError('The response of ' + spec.method + ' ' + spec.path + ' is not a page: "data" is not an array', {
31
32
  status: result.response.status,
32
33
  requestId: result.response.requestId,
33
- body: JSON.stringify(body) ?? '',
34
+ body: (0, json_js_1.debugJSON)(body),
34
35
  });
35
36
  }
36
37
  const next = body.next_cursor;
@@ -69,6 +69,8 @@ export declare class Stream<T> implements AsyncIterable<T> {
69
69
  }
70
70
  /**
71
71
  * Decodes the `data` of an event as JSON. Heart-beats (`ping`, or an event with empty data) are
72
- * skipped; data that is not valid JSON raises a DecodeError.
72
+ * skipped; data that is not valid JSON raises a DecodeError. Unless `errorIsEvent` (chat events,
73
+ * where `error` is a variant of the union), an `error` event is a failure of the stream and raises
74
+ * a StreamError, so a broken stream never looks like one that ended normally.
73
75
  */
74
- export declare function decodeJSONEvent<T>(event: ServerSentEvent, response: ResponseInfo): T | undefined;
76
+ export declare function decodeJSONEvent<T>(event: ServerSentEvent, response: ResponseInfo, errorIsEvent?: boolean): T | undefined;
@@ -234,11 +234,15 @@ class Stream {
234
234
  exports.Stream = Stream;
235
235
  /**
236
236
  * Decodes the `data` of an event as JSON. Heart-beats (`ping`, or an event with empty data) are
237
- * skipped; data that is not valid JSON raises a DecodeError.
237
+ * skipped; data that is not valid JSON raises a DecodeError. Unless `errorIsEvent` (chat events,
238
+ * where `error` is a variant of the union), an `error` event is a failure of the stream and raises
239
+ * a StreamError, so a broken stream never looks like one that ended normally.
238
240
  */
239
- function decodeJSONEvent(event, response) {
241
+ function decodeJSONEvent(event, response, errorIsEvent = false) {
240
242
  if (event.event === 'ping' || event.data === '')
241
243
  return undefined;
244
+ if (event.event === 'error' && !errorIsEvent)
245
+ throw streamError(event.data, response);
242
246
  try {
243
247
  return (0, json_js_1.parseJSON)(event.data);
244
248
  }
@@ -251,3 +255,37 @@ function decodeJSONEvent(event, response) {
251
255
  });
252
256
  }
253
257
  }
258
+ /**
259
+ * Reads the data of an `error` event: `{"error": "code", "message": ...}` as the contract sends it,
260
+ * or the API error envelope `{"error": {"code", "message", ...}}`. Other data still gives a StreamError.
261
+ */
262
+ function streamError(data, response) {
263
+ let root;
264
+ try {
265
+ root = (0, json_js_1.parseJSON)(data);
266
+ }
267
+ catch {
268
+ root = undefined;
269
+ }
270
+ const text = (value) => (typeof value === 'string' && value !== '' ? value : null);
271
+ const props = isRecord(root) ? root : {};
272
+ const inner = isRecord(props['error']) ? props['error'] : {};
273
+ const extra = {};
274
+ for (const [key, value] of Object.entries(inner))
275
+ if (key !== 'code' && key !== 'message')
276
+ extra[key] = value;
277
+ for (const [key, value] of Object.entries(props)) {
278
+ if (key !== 'error' && key !== 'code' && key !== 'message' && key !== 'request_id')
279
+ extra[key] = value;
280
+ }
281
+ return new errors_js_1.StreamError({
282
+ code: text(props['code']) ?? text(props['error']) ?? text(inner['code']),
283
+ detail: text(props['message']) ?? text(inner['message']) ?? 'The stream reported an error',
284
+ requestId: text(props['request_id']) ?? response.requestId,
285
+ extra,
286
+ body: data,
287
+ });
288
+ }
289
+ function isRecord(value) {
290
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
291
+ }
@@ -1,2 +1,2 @@
1
1
  /** Version of this SDK; sent in the User-Agent header. */
2
- export declare const VERSION = "0.2.0";
2
+ export declare const VERSION = "1.0.0";
@@ -3,4 +3,4 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.VERSION = void 0;
5
5
  /** Version of this SDK; sent in the User-Agent header. */
6
- exports.VERSION = '0.2.0'; // x-release-version
6
+ exports.VERSION = '1.0.0'; // x-release-version
@@ -65,6 +65,11 @@ export interface HookOperation {
65
65
  export interface SendHookOptions extends RequestOptions {
66
66
  /** The hook's signing secret. When given, the exact bytes sent are signed in the signature header. */
67
67
  secret?: string | undefined;
68
+ /**
69
+ * The header the hook reads its signature from: the `signature_header` it was created with.
70
+ * Default `X-Signature`.
71
+ */
72
+ signatureHeader?: string | undefined;
68
73
  /** Your id of the event, for de-duplication on the server. */
69
74
  eventId?: string | undefined;
70
75
  /** Content type of the body. Default: `application/json` for text and JSON values, `application/octet-stream` for bytes. */
@@ -222,14 +222,24 @@ function encodeHookPayload(payload) {
222
222
  }
223
223
  return { bytes: encoder.encode((0, json_js_1.stringifyJSON)(payload)), contentType: 'application/json' };
224
224
  }
225
+ const HOOK_SIGNATURE_HEADER = /^[A-Za-z0-9-]{1,64}$/;
225
226
  /** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
226
227
  function sendHook(client, operation, token, payload, options = {}) {
227
228
  const run = async () => {
228
- const { secret, eventId, contentType, ...requestOptions } = options;
229
+ const { secret, eventId, contentType, signatureHeader, ...requestOptions } = options;
230
+ const target = signatureHeader ?? operation.signatureHeader;
231
+ if (typeof target !== 'string' || !HOOK_SIGNATURE_HEADER.test(target)) {
232
+ throw new errors_js_1.ValidationError("signatureHeader must be 1 to 64 Latin letters, digits or hyphens, like the hook's signature_header.");
233
+ }
229
234
  const encoded = encodeHookPayload(payload);
230
235
  const headers = {};
231
- if (secret !== undefined)
232
- headers[operation.signatureHeader] = 'sha256=' + (await signHookPayload(encoded.bytes, secret));
236
+ if (secret !== undefined) {
237
+ const lower = target.toLowerCase();
238
+ if (Object.entries(requestOptions.headers ?? {}).some(([name, value]) => name.toLowerCase() === lower && value != null)) {
239
+ throw new errors_js_1.ValidationError(`Pass either secret or the ${target} header, not both.`);
240
+ }
241
+ headers[target] = 'sha256=' + (await signHookPayload(encoded.bytes, secret));
242
+ }
233
243
  if (eventId !== undefined && operation.eventIdHeader !== undefined)
234
244
  headers[operation.eventIdHeader] = eventId;
235
245
  return {
@@ -241,6 +251,10 @@ function sendHook(client, operation, token, payload, options = {}) {
241
251
  headers,
242
252
  auth: 'hook',
243
253
  idempotencyHeader: operation.idempotencyHeader,
254
+ // The backend takes the id of a hook event from Idempotency-Key before X-Event-Id, so a random
255
+ // key would override the caller's event id: the event id is the default key. A key the caller
256
+ // gives (`idempotencyKey`, or the header per request or in the client's default headers) wins.
257
+ defaultIdempotencyKey: eventId,
244
258
  options: requestOptions,
245
259
  };
246
260
  };
package/dist/esm/chat.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Code generated by tungo-sdkgen. DO NOT EDIT.
2
2
  import { StreamPromise } from './core.js';
3
+ import { debugJSON } from './json.js';
3
4
  import { DecodeError, makeAPIError, parseErrorDetail } from './errors.js';
4
5
  import { Stream, decodeJSONEvent } from './streaming.js';
5
6
  /** Folds the events of one chat turn into a {@link ChatStreamResult}. */
@@ -82,7 +83,7 @@ export function chatTurnError(error, requestId, response) {
82
83
  retryAfter: null,
83
84
  rateLimit: response?.rateLimit ?? null,
84
85
  headers: response?.headers ?? new Headers(),
85
- body: JSON.stringify(error) ?? '',
86
+ body: debugJSON(error),
86
87
  extra: detail?.extra ?? {},
87
88
  envelope: detail !== null,
88
89
  });
@@ -123,7 +124,7 @@ export class ChatStream extends Stream {
123
124
  /** Turn number from the `X-Turn-No` response header; null when absent. */
124
125
  turnNo;
125
126
  constructor(init) {
126
- super(init, (event, response) => decodeJSONEvent(event, response));
127
+ super(init, (event, response) => decodeJSONEvent(event, response, true));
127
128
  const dialogId = init.response.headers.get('x-dialog-id');
128
129
  this.dialogId = dialogId === null || dialogId === '' ? null : dialogId;
129
130
  const turnNo = init.response.headers.get('x-turn-no');
@@ -54,6 +54,10 @@ export declare class Tungo {
54
54
  readonly onec: R.OnecResource;
55
55
  /** Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ */
56
56
  readonly automations: R.AutomationsResource;
57
+ /** Публичная проверка электронной подписи документов Tungo: по коду, по файлу, по блоку QR и ключи подписи (без ключа API) */
58
+ readonly verification: R.VerificationResource;
59
+ /** Публичный список загрузок: расширение 1С и Tungo Connector (без ключа API) */
60
+ readonly releases: R.ReleasesResource;
57
61
  constructor(options?: ClientOptions);
58
62
  /** Base URL the client talks to. */
59
63
  get baseUrl(): string;
@@ -87,7 +91,8 @@ export declare class Tungo {
87
91
  }): APIPromise<T.BatchJob>;
88
92
  /**
89
93
  * Sends an event to an incoming automation hook (`/hooks/{token}`). With `secret`, the exact
90
- * bytes sent are signed in the `X-Signature: sha256=<hex>` header. The API key is not sent.
94
+ * bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
95
+ * hook created with its own `signature_header`. The API key is not sent.
91
96
  * Same as `client.automations.postHook`.
92
97
  */
93
98
  sendHook(token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<T.AutomationHookAccepted>;
@@ -2,6 +2,7 @@
2
2
  import { APIClient, sleep, startTimer } from './core.js';
3
3
  import { chatTurnError } from './chat.js';
4
4
  import { AbortError, DecodeError, TimeoutError } from './errors.js';
5
+ import { debugJSON } from './json.js';
5
6
  import { bytesToBase64, verifyWebhook } from './webhooks.js';
6
7
  import * as R from './generated/resources.js';
7
8
  const RUN_FINAL_STATES = ['done', 'error', 'skipped', 'cancelled'];
@@ -42,6 +43,10 @@ export class Tungo {
42
43
  onec;
43
44
  /** Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ */
44
45
  automations;
46
+ /** Публичная проверка электронной подписи документов Tungo: по коду, по файлу, по блоку QR и ключи подписи (без ключа API) */
47
+ verification;
48
+ /** Публичный список загрузок: расширение 1С и Tungo Connector (без ключа API) */
49
+ releases;
45
50
  #client;
46
51
  constructor(options = {}) {
47
52
  const client = new APIClient(options);
@@ -59,6 +64,8 @@ export class Tungo {
59
64
  this.forms = new R.FormsResource(client);
60
65
  this.onec = new R.OnecResource(client);
61
66
  this.automations = new R.AutomationsResource(client);
67
+ this.verification = new R.VerificationResource(client);
68
+ this.releases = new R.ReleasesResource(client);
62
69
  }
63
70
  /** Base URL the client talks to. */
64
71
  get baseUrl() {
@@ -123,7 +130,8 @@ export class Tungo {
123
130
  }
124
131
  /**
125
132
  * Sends an event to an incoming automation hook (`/hooks/{token}`). With `secret`, the exact
126
- * bytes sent are signed in the `X-Signature: sha256=<hex>` header. The API key is not sent.
133
+ * bytes sent are signed in the `X-Signature: sha256=<hex>` header, or in `signatureHeader` for a
134
+ * hook created with its own `signature_header`. The API key is not sent.
127
135
  * Same as `client.automations.postHook`.
128
136
  */
129
137
  sendHook(token, payload, options) {
@@ -151,7 +159,7 @@ export class Tungo {
151
159
  return this.#poll('the automation run to finish', (requestOptions) => this.automations.getRun(companyId, runId, requestOptions).withResponse(), (run, response) => {
152
160
  const state = run?.state;
153
161
  if (typeof state !== 'string') {
154
- throw new DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body: JSON.stringify(run) ?? '' });
162
+ throw new DecodeError('The automation run has no "state"', { status: response.status, requestId: response.requestId, body: debugJSON(run) });
155
163
  }
156
164
  return RUN_FINAL_STATES.includes(state);
157
165
  }, options);
@@ -161,7 +169,7 @@ export class Tungo {
161
169
  return this.#poll('the batch job to finish', (requestOptions) => this.batches.get(companyId, batchId, requestOptions).withResponse(), (job, response) => {
162
170
  const running = job?.running;
163
171
  if (typeof running !== 'boolean') {
164
- throw new DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body: JSON.stringify(job) ?? '' });
172
+ throw new DecodeError('The batch job has no "running" flag', { status: response.status, requestId: response.requestId, body: debugJSON(job) });
165
173
  }
166
174
  return !running;
167
175
  }, options);
@@ -78,7 +78,10 @@ export interface RequestOptions {
78
78
  maxRetries?: number | undefined;
79
79
  /** Extra headers; a null value removes a default header. */
80
80
  headers?: Record<string, string | null | undefined> | undefined;
81
- /** Your own `Idempotency-Key`. Without it the SDK generates one for operations that declare the header. */
81
+ /**
82
+ * Your own `Idempotency-Key` for an operation that declares the header (without it the SDK
83
+ * generates one). Other operations do not send it and are not retried because of it.
84
+ */
82
85
  idempotencyKey?: string | undefined;
83
86
  /** Cancels the request (and its retries and waits). It is combined with the timeout. */
84
87
  signal?: AbortSignal | undefined;
@@ -106,6 +109,11 @@ export interface RequestSpec {
106
109
  auth?: 'key' | 'public' | 'hook' | undefined;
107
110
  /** Wire name of the idempotency header when the operation declares one. */
108
111
  idempotencyHeader?: string | undefined;
112
+ /**
113
+ * Key sent in the idempotency header when the caller gives none (neither `idempotencyKey` nor the
114
+ * header itself, per request or in the client's default headers). Default: a random UUID.
115
+ */
116
+ defaultIdempotencyKey?: string | undefined;
109
117
  /** Use the long-running timeout by default. */
110
118
  longRunning?: boolean | undefined;
111
119
  /** The success response has no body. */
@@ -117,7 +125,6 @@ export interface WithResponse<T> {
117
125
  data: T;
118
126
  response: ResponseInfo;
119
127
  }
120
- /** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
121
128
  export declare function readEnv(name: string): string | undefined;
122
129
  /** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
123
130
  export declare function uuid4(): string;
package/dist/esm/core.js CHANGED
@@ -21,6 +21,87 @@ export const MAX_RETRY_AFTER_SECONDS = 60;
21
21
  export const MAX_TIMER_MS = 2_147_483_647;
22
22
  const USER_AGENT = 'tungo-sdk-typescript/' + VERSION;
23
23
  /** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
24
+ /** Whether a stream call was answered with a stored result replayed by Idempotency-Key. */
25
+ function isReplayedJSON(headers) {
26
+ const mediaType = (headers.get('content-type') ?? '').split(';')[0] ?? '';
27
+ return mediaType.trim().toLowerCase() === 'application/json' && (headers.get('idempotent-replayed') ?? '').trim().toLowerCase() === 'true';
28
+ }
29
+ function isObject(value) {
30
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
31
+ }
32
+ /**
33
+ * Turns a replayed ChatTurnResult into the event stream of the turn it stands for: text (the
34
+ * answer), proposal, question, citation, error, choice and next events, then done. The dialog id and
35
+ * the turn number, which a replay carries only in the body, become the X-Dialog-Id and X-Turn-No
36
+ * headers when they are missing: `headers` are those of the response with them, the other headers
37
+ * (Idempotent-Replayed among them) unchanged. Returns null when the body is not a chat turn result.
38
+ */
39
+ function replayAsEventStream(response, text, requestId) {
40
+ let result;
41
+ try {
42
+ result = parseJSON(text);
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ if (!isObject(result))
48
+ return null;
49
+ const dialogId = result['dialog_id'];
50
+ if (typeof dialogId !== 'string')
51
+ return null;
52
+ const headers = new Headers(response.headers);
53
+ if ((headers.get('x-dialog-id') ?? '') === '')
54
+ headers.set('x-dialog-id', dialogId);
55
+ const turnNo = result['turn_no'];
56
+ if ((headers.get('x-turn-no') ?? '') === '' && (typeof turnNo === 'number' || typeof turnNo === 'bigint'))
57
+ headers.set('x-turn-no', String(turnNo));
58
+ const entries = (key) => {
59
+ const list = result[key];
60
+ return Array.isArray(list) ? list.filter(isObject) : [];
61
+ };
62
+ let body = '';
63
+ const emit = (type, event) => {
64
+ body += 'event: ' + type + '\ndata: ' + stringifyJSON({ ...event, type }) + '\n\n';
65
+ };
66
+ const answerValue = result['answer'];
67
+ const answer = typeof answerValue === 'string' ? answerValue : '';
68
+ if (answer !== '')
69
+ emit('text', { delta: answer });
70
+ for (const { id, ...rest } of entries('proposals'))
71
+ emit('proposal', { ...rest, proposal_id: id });
72
+ for (const question of entries('questions'))
73
+ emit('question', question);
74
+ for (const citation of entries('citations'))
75
+ emit('citation', citation);
76
+ for (const error of entries('errors'))
77
+ emit('error', { error, request_id: requestId });
78
+ const done = { answer };
79
+ const stopReason = result['stop_reason'];
80
+ if (typeof stopReason === 'string')
81
+ done['stop_reason'] = stopReason;
82
+ const usageValue = result['usage'];
83
+ if (isObject(usageValue)) {
84
+ const { cost_tiyn: cost, ...usage } = usageValue;
85
+ done['usage'] = usage;
86
+ if (cost !== undefined)
87
+ done['cost_tiyn'] = cost;
88
+ }
89
+ const pending = result['pending_question'];
90
+ if (isObject(pending)) {
91
+ emit('choice', pending);
92
+ done['choice_id'] = pending['choice_id'];
93
+ }
94
+ // A live turn ends its finished answer with next right before done; the stored result keeps it
95
+ // as followups and next_action.
96
+ const followups = Array.isArray(result['followups']) ? result['followups'] : [];
97
+ const action = result['next_action'];
98
+ if (followups.length > 0 || isObject(action))
99
+ emit('next', { followups, action: isObject(action) ? action : null });
100
+ emit('done', done);
101
+ const streamHeaders = new Headers(headers);
102
+ streamHeaders.set('content-type', 'text/event-stream');
103
+ return { response: new Response(body, { status: response.status, headers: streamHeaders }), headers };
104
+ }
24
105
  export function readEnv(name) {
25
106
  try {
26
107
  const scope = globalThis;
@@ -36,6 +117,21 @@ export function readEnv(name) {
36
117
  }
37
118
  return undefined;
38
119
  }
120
+ /**
121
+ * The `idempotency_key` field of a JSON object body (approving a proposal documents it as the same
122
+ * as the header), trimmed like the API trims it. The API prefers the header over the field, so a
123
+ * generated header would make the caller's own key useless. A key that cannot travel in a header
124
+ * (outside printable ASCII) is ignored here.
125
+ */
126
+ function bodyIdempotencyKey(body) {
127
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
128
+ return undefined;
129
+ const value = body['idempotency_key'];
130
+ if (typeof value !== 'string')
131
+ return undefined;
132
+ const key = value.trim();
133
+ return key !== '' && /^[\x20-\x7e]+$/.test(key) ? key : undefined;
134
+ }
39
135
  /** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
40
136
  export function uuid4() {
41
137
  const bytes = new Uint8Array(16);
@@ -188,6 +284,29 @@ function causeText(cause) {
188
284
  }
189
285
  return cause.message;
190
286
  }
287
+ /**
288
+ * The text of a transport failure without the request URL: a custom fetch (node-fetch, a proxy
289
+ * or tracing wrapper) may put the full URL into its message, and the path can carry a hook token
290
+ * and the query search text. The URL and the concrete path become the route template, and any
291
+ * other absolute URL and every path parameter value are cut out.
292
+ */
293
+ function redactedCauseText(cause, baseUrl, url, spec) {
294
+ let text = causeText(cause);
295
+ const path = buildPath(spec.path, spec.pathParams);
296
+ const pathAndQuery = url.slice(baseUrl.length);
297
+ for (const concrete of [url, url.split('?')[0] ?? url, pathAndQuery, path]) {
298
+ if (concrete !== '' && concrete !== '/')
299
+ text = text.split(concrete).join(spec.path);
300
+ }
301
+ text = text.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*/gi, '[url]');
302
+ for (const value of Object.values(spec.pathParams ?? {})) {
303
+ if (typeof value !== 'string' || value === '')
304
+ continue;
305
+ for (const form of new Set([value, encodeURIComponent(value)]))
306
+ text = text.split(form).join('[redacted]');
307
+ }
308
+ return text;
309
+ }
191
310
  function positive(value, fallback, name, zeroAllowed) {
192
311
  if (value === undefined)
193
312
  return fallback;
@@ -204,10 +323,23 @@ function retries(value, fallback) {
204
323
  }
205
324
  return value;
206
325
  }
326
+ /**
327
+ * Whether a header value can be sent at all: fetch refuses CR, LF and NUL, and a character above
328
+ * U+00FF (a Cyrillic look-alike pasted into a key) is not a byte, so fetch would throw a
329
+ * TypeError that looks like a network failure.
330
+ */
331
+ function sendableHeaderValue(value) {
332
+ for (let i = 0; i < value.length; i++) {
333
+ const code = value.charCodeAt(i);
334
+ if (code === 0 || code === 10 || code === 13 || code > 0xff)
335
+ return false;
336
+ }
337
+ return true;
338
+ }
207
339
  class HeaderBag {
208
340
  #map = new Map();
209
341
  set(name, value) {
210
- if (value.includes('\r') || value.includes('\n') || value.includes('\0') || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
342
+ if (!sendableHeaderValue(value) || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
211
343
  throw new ValidationError('The header "' + name.replace(/[^ -~]/g, '?') + '" has an invalid name or value');
212
344
  }
213
345
  this.#map.set(name.toLowerCase(), [name, value]);
@@ -360,16 +492,29 @@ export class APIClient {
360
492
  return new APIPromise(this.#requestJSON(spec));
361
493
  }
362
494
  /** 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
- }));
495
+ async openStream(spec, make) {
496
+ // Checked before anything is sent: once the turn is posted it runs (and is billed) on the
497
+ // server, so a bad option found afterwards would cost a turn and leave the connection open.
498
+ const idleTimeout = positive(spec.options?.streamIdleTimeout, this.streamIdleTimeout, 'streamIdleTimeout', true);
499
+ const x = await this.#exchange(spec, true);
500
+ try {
501
+ return make({
502
+ response: x.info,
503
+ body: x.response.body,
504
+ controller: x.controller,
505
+ signal: spec.options?.signal ?? undefined,
506
+ detach: x.detach,
507
+ idleTimeout,
508
+ route: spec.method.toUpperCase() + ' ' + spec.path,
509
+ });
510
+ }
511
+ catch (error) {
512
+ // The stream object never came to be: nobody else can close the connection.
513
+ x.detach();
514
+ x.controller.abort();
515
+ x.response.body?.cancel().catch(() => undefined);
516
+ throw error;
517
+ }
373
518
  }
374
519
  async #requestJSON(spec) {
375
520
  const x = await this.#exchange(spec, false);
@@ -428,19 +573,30 @@ export class APIClient {
428
573
  if (key === undefined) {
429
574
  throw new ConfigError('No API key: pass "apiKey" to the client or set the TUNGO_API_KEY environment variable');
430
575
  }
576
+ if (!sendableHeaderValue(key)) {
577
+ // Never the key itself: only what is wrong with it.
578
+ throw new 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');
579
+ }
431
580
  if (this.#bearer)
432
581
  bag.set('Authorization', 'Bearer ' + key);
433
582
  else
434
583
  bag.set('x-api-key', key);
435
584
  }
436
- const headerName = spec.idempotencyHeader ?? 'Idempotency-Key';
585
+ if (options.idempotencyKey === '')
586
+ throw new ValidationError('The idempotency key must not be empty');
587
+ const headerName = spec.idempotencyHeader;
588
+ if (headerName === undefined) {
589
+ // The API ignores a key on an operation that declares none: sending one would make a retry
590
+ // look safe when it repeats the action.
591
+ bag.delete('Idempotency-Key');
592
+ return { headers: bag.toRecord(), hasIdempotencyKey: false };
593
+ }
437
594
  if (options.idempotencyKey !== undefined) {
438
- if (options.idempotencyKey === '')
439
- throw new ValidationError('The idempotency key must not be empty');
440
595
  bag.set(headerName, options.idempotencyKey);
441
596
  }
442
- else if (spec.idempotencyHeader !== undefined && !bag.has(headerName)) {
443
- bag.set(headerName, uuid4());
597
+ else if (!bag.has(headerName)) {
598
+ const fallback = spec.defaultIdempotencyKey !== undefined && spec.defaultIdempotencyKey !== '' ? spec.defaultIdempotencyKey : bodyIdempotencyKey(spec.body);
599
+ bag.set(headerName, fallback ?? uuid4());
444
600
  }
445
601
  return { headers: bag.toRecord(), hasIdempotencyKey: bag.has(headerName) };
446
602
  }
@@ -522,6 +678,24 @@ export class APIClient {
522
678
  attempts: attempt + 1,
523
679
  };
524
680
  if (response.status >= 200 && response.status < 300) {
681
+ if (stream && isReplayedJSON(response.headers)) {
682
+ // A chat turn repeated with the same Idempotency-Key after it finished: the server
683
+ // answers the stored ChatTurnResult instead of a stream. The caller gets its events.
684
+ const replayed = await response.text();
685
+ const synthesized = replayAsEventStream(response, replayed, info.requestId);
686
+ if (synthesized === null) {
687
+ throw new DecodeError('The response of ' + route + ' (status ' + response.status + ') replays a result that is not a chat turn', {
688
+ status: response.status,
689
+ requestId: info.requestId,
690
+ body: replayed,
691
+ });
692
+ }
693
+ info.headers = synthesized.headers;
694
+ keepOpen = true;
695
+ clearTimeout(timer);
696
+ this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
697
+ return { info, text: '', response: synthesized.response, controller, detach };
698
+ }
525
699
  if (stream) {
526
700
  const contentType = (response.headers.get('content-type') ?? '').trim().toLowerCase();
527
701
  if (!contentType.startsWith('text/event-stream')) {
@@ -561,7 +735,7 @@ export class APIClient {
561
735
  cause = 'timeout';
562
736
  }
563
737
  else {
564
- failure = new ConnectionError('Could not reach the API for ' + route + ': ' + causeText(reason), { cause: reason });
738
+ failure = new ConnectionError('Could not reach the API for ' + route + ': ' + redactedCauseText(reason, this.baseUrl, url, spec), { cause: reason });
565
739
  cause = 'connection_error';
566
740
  }
567
741
  }