@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/esm/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export * from './generated/resources.js';
2
2
  export { Tungo, Tungo as TungoClient } from './client.js';
3
3
  export { APIClient, APIPromise, StreamPromise, DEFAULT_BASE_URL, DEFAULT_LONG_RUNNING_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_STREAM_IDLE_TIMEOUT, DEFAULT_TIMEOUT, } from './core.js';
4
- export { APIError, AbortError, AuthenticationError, ConfigError, ConflictError, ConnectionError, DecodeError, GoneError, InternalServerError, InvalidRequestError, LimitError, MoneyError, NotFoundError, PaymentRequiredError, PermissionError, TimeoutError, TungoError, UnavailableError, ValidationError, WebhookVerificationError, } from './errors.js';
4
+ export { APIError, AbortError, AuthenticationError, ConfigError, ConflictError, ConnectionError, DecodeError, GoneError, InternalServerError, InvalidRequestError, LimitError, MoneyError, NotFoundError, PaymentRequiredError, PermissionError, StreamError, TimeoutError, TungoError, UnavailableError, ValidationError, WebhookVerificationError, } from './errors.js';
5
5
  export { SSEDecoder, Stream } from './streaming.js';
6
6
  export { Page, PagePromise } from './pagination.js';
7
7
  export { ChatAccumulator, ChatStream, ChatStreamPromise, accumulateChatStream, chatTurnError, } from './chat.js';
@@ -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/esm/json.js CHANGED
@@ -114,3 +114,19 @@ export function stringifyJSON(value) {
114
114
  return text;
115
115
  return text.replace(new RegExp('"\\\\u0000' + prefix + '(-?[0-9]+)"', 'g'), '$1');
116
116
  }
117
+ /**
118
+ * The JSON text of a decoded value for an error message or the `body` of an error: like
119
+ * stringifyJSON (a bigint keeps every digit), but it never throws: `undefined` and a value JSON
120
+ * cannot express give ''.
121
+ */
122
+ export function debugJSON(value) {
123
+ if (value === undefined)
124
+ return '';
125
+ try {
126
+ return stringifyJSON(value);
127
+ }
128
+ catch {
129
+ // NaN or Infinity inside, a cycle: the error is still raised, only without its body.
130
+ return '';
131
+ }
132
+ }
@@ -1,6 +1,7 @@
1
1
  // Code generated by tungo-sdkgen. DO NOT EDIT.
2
2
  import { APIPromise } from './core.js';
3
3
  import { DecodeError, TungoError } from './errors.js';
4
+ import { debugJSON } from './json.js';
4
5
  /**
5
6
  * One page of a cursor-paginated list. `data` holds the items of this page, `body` the complete
6
7
  * typed response (totals and other fields next to `data`). Iterating the page with `for await`
@@ -26,7 +27,7 @@ export class Page {
26
27
  throw new DecodeError('The response of ' + spec.method + ' ' + spec.path + ' is not a page: "data" is not an array', {
27
28
  status: result.response.status,
28
29
  requestId: result.response.requestId,
29
- body: JSON.stringify(body) ?? '',
30
+ body: debugJSON(body),
30
31
  });
31
32
  }
32
33
  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;
@@ -1,6 +1,6 @@
1
1
  // Code generated by tungo-sdkgen. DO NOT EDIT.
2
2
  import { MAX_TIMER_MS } from './core.js';
3
- import { AbortError, ConnectionError, DecodeError, TimeoutError, TungoError } from './errors.js';
3
+ import { AbortError, ConnectionError, DecodeError, StreamError, TimeoutError, TungoError } from './errors.js';
4
4
  import { parseJSON } from './json.js';
5
5
  /**
6
6
  * Incremental parser of the `text/event-stream` format (WHATWG HTML, "interpreting an event
@@ -228,11 +228,15 @@ export class Stream {
228
228
  }
229
229
  /**
230
230
  * Decodes the `data` of an event as JSON. Heart-beats (`ping`, or an event with empty data) are
231
- * skipped; data that is not valid JSON raises a DecodeError.
231
+ * skipped; data that is not valid JSON raises a DecodeError. Unless `errorIsEvent` (chat events,
232
+ * where `error` is a variant of the union), an `error` event is a failure of the stream and raises
233
+ * a StreamError, so a broken stream never looks like one that ended normally.
232
234
  */
233
- export function decodeJSONEvent(event, response) {
235
+ export function decodeJSONEvent(event, response, errorIsEvent = false) {
234
236
  if (event.event === 'ping' || event.data === '')
235
237
  return undefined;
238
+ if (event.event === 'error' && !errorIsEvent)
239
+ throw streamError(event.data, response);
236
240
  try {
237
241
  return parseJSON(event.data);
238
242
  }
@@ -245,3 +249,37 @@ export function decodeJSONEvent(event, response) {
245
249
  });
246
250
  }
247
251
  }
252
+ /**
253
+ * Reads the data of an `error` event: `{"error": "code", "message": ...}` as the contract sends it,
254
+ * or the API error envelope `{"error": {"code", "message", ...}}`. Other data still gives a StreamError.
255
+ */
256
+ function streamError(data, response) {
257
+ let root;
258
+ try {
259
+ root = parseJSON(data);
260
+ }
261
+ catch {
262
+ root = undefined;
263
+ }
264
+ const text = (value) => (typeof value === 'string' && value !== '' ? value : null);
265
+ const props = isRecord(root) ? root : {};
266
+ const inner = isRecord(props['error']) ? props['error'] : {};
267
+ const extra = {};
268
+ for (const [key, value] of Object.entries(inner))
269
+ if (key !== 'code' && key !== 'message')
270
+ extra[key] = value;
271
+ for (const [key, value] of Object.entries(props)) {
272
+ if (key !== 'error' && key !== 'code' && key !== 'message' && key !== 'request_id')
273
+ extra[key] = value;
274
+ }
275
+ return new StreamError({
276
+ code: text(props['code']) ?? text(props['error']) ?? text(inner['code']),
277
+ detail: text(props['message']) ?? text(inner['message']) ?? 'The stream reported an error',
278
+ requestId: text(props['request_id']) ?? response.requestId,
279
+ extra,
280
+ body: data,
281
+ });
282
+ }
283
+ function isRecord(value) {
284
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
285
+ }
@@ -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";
@@ -1,3 +1,3 @@
1
1
  // Code generated by tungo-sdkgen. DO NOT EDIT.
2
2
  /** Version of this SDK; sent in the User-Agent header. */
3
- export const VERSION = '0.2.0'; // x-release-version
3
+ export const 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. */
@@ -213,14 +213,24 @@ export function encodeHookPayload(payload) {
213
213
  }
214
214
  return { bytes: encoder.encode(stringifyJSON(payload)), contentType: 'application/json' };
215
215
  }
216
+ const HOOK_SIGNATURE_HEADER = /^[A-Za-z0-9-]{1,64}$/;
216
217
  /** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
217
218
  export function sendHook(client, operation, token, payload, options = {}) {
218
219
  const run = async () => {
219
- const { secret, eventId, contentType, ...requestOptions } = options;
220
+ const { secret, eventId, contentType, signatureHeader, ...requestOptions } = options;
221
+ const target = signatureHeader ?? operation.signatureHeader;
222
+ if (typeof target !== 'string' || !HOOK_SIGNATURE_HEADER.test(target)) {
223
+ throw new ValidationError("signatureHeader must be 1 to 64 Latin letters, digits or hyphens, like the hook's signature_header.");
224
+ }
220
225
  const encoded = encodeHookPayload(payload);
221
226
  const headers = {};
222
- if (secret !== undefined)
223
- headers[operation.signatureHeader] = 'sha256=' + (await signHookPayload(encoded.bytes, secret));
227
+ if (secret !== undefined) {
228
+ const lower = target.toLowerCase();
229
+ if (Object.entries(requestOptions.headers ?? {}).some(([name, value]) => name.toLowerCase() === lower && value != null)) {
230
+ throw new ValidationError(`Pass either secret or the ${target} header, not both.`);
231
+ }
232
+ headers[target] = 'sha256=' + (await signHookPayload(encoded.bytes, secret));
233
+ }
224
234
  if (eventId !== undefined && operation.eventIdHeader !== undefined)
225
235
  headers[operation.eventIdHeader] = eventId;
226
236
  return {
@@ -232,6 +242,10 @@ export function sendHook(client, operation, token, payload, options = {}) {
232
242
  headers,
233
243
  auth: 'hook',
234
244
  idempotencyHeader: operation.idempotencyHeader,
245
+ // The backend takes the id of a hook event from Idempotency-Key before X-Event-Id, so a random
246
+ // key would override the caller's event id: the event id is the default key. A key the caller
247
+ // gives (`idempotencyKey`, or the header per request or in the client's default headers) wins.
248
+ defaultIdempotencyKey: eventId,
235
249
  options: requestOptions,
236
250
  };
237
251
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tungoai/sdk",
3
- "version": "0.2.0",
3
+ "version": "1.0.0",
4
4
  "description": "Official TypeScript SDK for the Tungo Platform API",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/TungoAI/tungo-sdk-typescript#readme",