@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,76 @@
1
+ import { type RateLimit } from './errors.js';
2
+ /** Status and headers of one HTTP response. */
3
+ export interface ResponseInfo {
4
+ /** HTTP status code. */
5
+ status: number;
6
+ /** Response headers. */
7
+ headers: Headers;
8
+ /** Value of the `x-request-id` header; quote it to support. */
9
+ requestId: string | null;
10
+ /** Rate-limit headers of THIS response (`x-ratelimit-*`), or null when absent. */
11
+ rateLimit: RateLimit | null;
12
+ /** How many attempts the request took (1 = no retries). */
13
+ attempts: number;
14
+ }
15
+ /** One dispatched server-sent event. */
16
+ export interface ServerSentEvent {
17
+ /** Event name; `message` when the stream did not name it. */
18
+ event: string;
19
+ /** The `data` lines joined with a line feed. */
20
+ data: string;
21
+ /** The last event id seen so far, or null. */
22
+ id: string | null;
23
+ /** Reconnection time in milliseconds, when this event's block set it. */
24
+ retry?: number;
25
+ }
26
+ /**
27
+ * Incremental parser of the `text/event-stream` format (WHATWG HTML, "interpreting an event
28
+ * stream"). Feed it the bytes as they arrive; it returns the events completed by each chunk.
29
+ * LF, CRLF and bare CR line endings, a leading BOM, comments, multi-line data and UTF-8
30
+ * sequences split across chunks are handled. An unterminated last event is dropped.
31
+ */
32
+ export declare class SSEDecoder {
33
+ #private;
34
+ /** Consumes one chunk and returns the events it completed. */
35
+ feed(chunk: Uint8Array): ServerSentEvent[];
36
+ }
37
+ /** What a {@link Stream} is built from. Created by the client; not meant to be constructed by hand. */
38
+ export interface StreamInit {
39
+ response: ResponseInfo;
40
+ body: ReadableStream<Uint8Array> | null;
41
+ /** Aborting it closes the connection. */
42
+ controller: AbortController;
43
+ /** The caller's signal, when one was passed. */
44
+ signal: AbortSignal | undefined;
45
+ /** Removes the listener that links the caller's signal to the controller. */
46
+ detach: () => void;
47
+ /** Milliseconds without a single byte after which the stream fails; 0 or Infinity disables the check. */
48
+ idleTimeout: number;
49
+ /** `METHOD /path/template` for error messages. */
50
+ route: string;
51
+ }
52
+ /**
53
+ * A server-sent event stream. Iterate it with `for await` to receive typed events as they arrive.
54
+ * Leaving the loop early, or calling {@link Stream.close}, closes the connection. A stream can be
55
+ * consumed once.
56
+ */
57
+ export declare class Stream<T> implements AsyncIterable<T> {
58
+ #private;
59
+ /** Status and headers of the response that opened the stream. */
60
+ readonly response: ResponseInfo;
61
+ constructor(init: StreamInit, decode: (event: ServerSentEvent, response: ResponseInfo) => T | undefined);
62
+ /** The id of the last event received so far (send it as `Last-Event-ID` to resume). */
63
+ get lastEventId(): string | null;
64
+ /** Closes the connection. Safe to call more than once; a running iteration ends quietly. */
65
+ close(): void;
66
+ /** The raw server-sent events (name, data text, id), including heart-beats. */
67
+ events(): AsyncGenerator<ServerSentEvent, void, undefined>;
68
+ [Symbol.asyncIterator](): AsyncGenerator<T, void, undefined>;
69
+ }
70
+ /**
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. 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.
75
+ */
76
+ export declare function decodeJSONEvent<T>(event: ServerSentEvent, response: ResponseInfo, errorIsEvent?: boolean): T | undefined;
@@ -0,0 +1,291 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Stream = exports.SSEDecoder = void 0;
4
+ exports.decodeJSONEvent = decodeJSONEvent;
5
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
6
+ const core_js_1 = require("./core.js");
7
+ const errors_js_1 = require("./errors.js");
8
+ const json_js_1 = require("./json.js");
9
+ /**
10
+ * Incremental parser of the `text/event-stream` format (WHATWG HTML, "interpreting an event
11
+ * stream"). Feed it the bytes as they arrive; it returns the events completed by each chunk.
12
+ * LF, CRLF and bare CR line endings, a leading BOM, comments, multi-line data and UTF-8
13
+ * sequences split across chunks are handled. An unterminated last event is dropped.
14
+ */
15
+ class SSEDecoder {
16
+ #pending = [];
17
+ #pendingLength = 0;
18
+ #skipLineFeed = false;
19
+ #firstLine = true;
20
+ #text = new TextDecoder('utf-8', { ignoreBOM: true });
21
+ #data = [];
22
+ #hasData = false;
23
+ #event = '';
24
+ #lastId = null;
25
+ #retry;
26
+ /** Consumes one chunk and returns the events it completed. */
27
+ feed(chunk) {
28
+ const out = [];
29
+ let start = 0;
30
+ if (this.#skipLineFeed && chunk.length > 0) {
31
+ if (chunk[0] === 10)
32
+ start = 1;
33
+ this.#skipLineFeed = false;
34
+ }
35
+ for (let i = start; i < chunk.length; i++) {
36
+ const byte = chunk[i];
37
+ if (byte !== 10 && byte !== 13)
38
+ continue;
39
+ this.#line(this.#take(chunk.subarray(start, i)), out);
40
+ if (byte === 13) {
41
+ if (i + 1 < chunk.length) {
42
+ if (chunk[i + 1] === 10)
43
+ i++;
44
+ }
45
+ else {
46
+ this.#skipLineFeed = true;
47
+ }
48
+ }
49
+ start = i + 1;
50
+ }
51
+ if (start < chunk.length) {
52
+ const rest = chunk.subarray(start);
53
+ this.#pending.push(rest);
54
+ this.#pendingLength += rest.length;
55
+ }
56
+ return out;
57
+ }
58
+ #take(tail) {
59
+ let bytes = tail;
60
+ if (this.#pendingLength > 0) {
61
+ bytes = new Uint8Array(this.#pendingLength + tail.length);
62
+ let offset = 0;
63
+ for (const part of this.#pending) {
64
+ bytes.set(part, offset);
65
+ offset += part.length;
66
+ }
67
+ bytes.set(tail, offset);
68
+ this.#pending = [];
69
+ this.#pendingLength = 0;
70
+ }
71
+ let line = this.#text.decode(bytes);
72
+ if (this.#firstLine) {
73
+ this.#firstLine = false;
74
+ if (line.charCodeAt(0) === 0xfeff)
75
+ line = line.slice(1);
76
+ }
77
+ return line;
78
+ }
79
+ #line(line, out) {
80
+ if (line === '') {
81
+ if (this.#hasData) {
82
+ const event = {
83
+ event: this.#event === '' ? 'message' : this.#event,
84
+ data: this.#data.join('\n'),
85
+ id: this.#lastId,
86
+ };
87
+ if (this.#retry !== undefined)
88
+ event.retry = this.#retry;
89
+ out.push(event);
90
+ }
91
+ this.#data = [];
92
+ this.#hasData = false;
93
+ this.#event = '';
94
+ this.#retry = undefined;
95
+ return;
96
+ }
97
+ if (line.charCodeAt(0) === 58)
98
+ return;
99
+ const colon = line.indexOf(':');
100
+ const field = colon === -1 ? line : line.slice(0, colon);
101
+ let value = colon === -1 ? '' : line.slice(colon + 1);
102
+ if (value.charCodeAt(0) === 32)
103
+ value = value.slice(1);
104
+ switch (field) {
105
+ case 'event':
106
+ this.#event = value;
107
+ break;
108
+ case 'data':
109
+ this.#data.push(value);
110
+ this.#hasData = true;
111
+ break;
112
+ case 'id':
113
+ if (!value.includes('\u0000'))
114
+ this.#lastId = value;
115
+ break;
116
+ case 'retry':
117
+ if (/^[0-9]+$/.test(value))
118
+ this.#retry = Number(value);
119
+ break;
120
+ default:
121
+ break;
122
+ }
123
+ }
124
+ }
125
+ exports.SSEDecoder = SSEDecoder;
126
+ function causeText(cause) {
127
+ return cause instanceof Error ? cause.message : String(cause);
128
+ }
129
+ /**
130
+ * A server-sent event stream. Iterate it with `for await` to receive typed events as they arrive.
131
+ * Leaving the loop early, or calling {@link Stream.close}, closes the connection. A stream can be
132
+ * consumed once.
133
+ */
134
+ class Stream {
135
+ /** Status and headers of the response that opened the stream. */
136
+ response;
137
+ #init;
138
+ #decode;
139
+ #started = false;
140
+ #closed = false;
141
+ #lastEventId = null;
142
+ constructor(init, decode) {
143
+ this.response = init.response;
144
+ this.#init = init;
145
+ this.#decode = decode;
146
+ }
147
+ /** The id of the last event received so far (send it as `Last-Event-ID` to resume). */
148
+ get lastEventId() {
149
+ return this.#lastEventId;
150
+ }
151
+ /** Closes the connection. Safe to call more than once; a running iteration ends quietly. */
152
+ close() {
153
+ if (this.#closed)
154
+ return;
155
+ this.#closed = true;
156
+ this.#init.detach();
157
+ this.#init.controller.abort();
158
+ if (!this.#started && this.#init.body !== null) {
159
+ this.#init.body.cancel().catch(() => undefined);
160
+ }
161
+ }
162
+ /** The raw server-sent events (name, data text, id), including heart-beats. */
163
+ async *events() {
164
+ if (this.#started)
165
+ throw new errors_js_1.TungoError('The stream has already been consumed');
166
+ this.#started = true;
167
+ const body = this.#init.body;
168
+ if (body === null || this.#closed)
169
+ return;
170
+ const reader = body.getReader();
171
+ const decoder = new SSEDecoder();
172
+ try {
173
+ for (;;) {
174
+ const chunk = await this.#read(reader);
175
+ if (chunk.done)
176
+ break;
177
+ for (const event of decoder.feed(chunk.value)) {
178
+ if (event.id !== null)
179
+ this.#lastEventId = event.id;
180
+ yield event;
181
+ }
182
+ }
183
+ }
184
+ finally {
185
+ this.#closed = true;
186
+ this.#init.detach();
187
+ try {
188
+ await reader.cancel();
189
+ }
190
+ catch {
191
+ // The connection is already gone.
192
+ }
193
+ this.#init.controller.abort();
194
+ }
195
+ }
196
+ async #read(reader) {
197
+ const idleTimeout = this.#init.idleTimeout;
198
+ let timer;
199
+ try {
200
+ // 0, Infinity and delays no timer can count disable the idle check.
201
+ if (!(idleTimeout > 0) || idleTimeout > core_js_1.MAX_TIMER_MS)
202
+ return await reader.read();
203
+ const idle = new Promise((_resolve, reject) => {
204
+ timer = setTimeout(() => {
205
+ reject(new errors_js_1.TimeoutError('No data was received for ' + idleTimeout + ' ms on the stream of ' + this.#init.route, idleTimeout));
206
+ }, idleTimeout);
207
+ });
208
+ return await Promise.race([reader.read(), idle]);
209
+ }
210
+ catch (cause) {
211
+ if (cause instanceof errors_js_1.TungoError)
212
+ throw cause;
213
+ const signal = this.#init.signal;
214
+ if (signal !== undefined && signal.aborted) {
215
+ throw new errors_js_1.AbortError('The stream of ' + this.#init.route + ' was aborted', { cause: signal.reason });
216
+ }
217
+ if (this.#closed)
218
+ return { done: true, value: undefined };
219
+ throw new errors_js_1.ConnectionError('The stream of ' + this.#init.route + ' was interrupted: ' + causeText(cause), { cause });
220
+ }
221
+ finally {
222
+ if (timer !== undefined)
223
+ clearTimeout(timer);
224
+ }
225
+ }
226
+ async *[Symbol.asyncIterator]() {
227
+ for await (const event of this.events()) {
228
+ const value = this.#decode(event, this.response);
229
+ if (value !== undefined)
230
+ yield value;
231
+ }
232
+ }
233
+ }
234
+ exports.Stream = Stream;
235
+ /**
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. 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.
240
+ */
241
+ function decodeJSONEvent(event, response, errorIsEvent = false) {
242
+ if (event.event === 'ping' || event.data === '')
243
+ return undefined;
244
+ if (event.event === 'error' && !errorIsEvent)
245
+ throw streamError(event.data, response);
246
+ try {
247
+ return (0, json_js_1.parseJSON)(event.data);
248
+ }
249
+ catch (cause) {
250
+ throw new errors_js_1.DecodeError('The data of the "' + event.event + '" stream event is not valid JSON', {
251
+ status: response.status,
252
+ requestId: response.requestId,
253
+ body: event.data,
254
+ cause,
255
+ });
256
+ }
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
+ }
@@ -0,0 +1,2 @@
1
+ /** Version of this SDK; sent in the User-Agent header. */
2
+ export declare const VERSION = "0.3.0";
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ // Code generated by tungo-sdkgen. DO NOT EDIT.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.VERSION = void 0;
5
+ /** Version of this SDK; sent in the User-Agent header. */
6
+ exports.VERSION = '0.3.0'; // x-release-version
@@ -0,0 +1,79 @@
1
+ import { APIPromise, type APIClient, type RequestOptions } from './core.js';
2
+ import type { WebhookEvent } from './generated/types.js';
3
+ /** Default tolerance for the webhook timestamp, in seconds (both directions). */
4
+ export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
5
+ /**
6
+ * Header containers accepted by the webhook helpers: a fetch `Headers` object, a plain object
7
+ * (Node.js `req.headers`, with string or string[] values), a Map, or an array of pairs.
8
+ * Names are matched case-insensitively.
9
+ */
10
+ export type HeadersLike = Headers | Iterable<readonly [string, string]> | Record<string, string | readonly string[] | undefined>;
11
+ /** Options of `verifyWebhook`. */
12
+ export interface VerifyWebhookOptions {
13
+ /** Maximum distance between the timestamp and the clock, in seconds. Default 300; must be positive. */
14
+ toleranceSeconds?: number | undefined;
15
+ /** The clock: unix seconds, a Date, or a function returning unix seconds. Default: the system clock. */
16
+ now?: number | Date | (() => number) | undefined;
17
+ }
18
+ /**
19
+ * Verifies an outgoing Tungo webhook (Standard Webhooks / Svix) and returns the typed event.
20
+ *
21
+ * Pass the RAW request body (the exact bytes, before any JSON parsing), the request headers
22
+ * (`webhook-*` or `svix-*`) and the endpoint's signing secret (`whsec_...`). The signature is
23
+ * checked in constant time and the timestamp must be within the tolerance of the clock.
24
+ * Every problem is reported as a {@link WebhookVerificationError}.
25
+ */
26
+ export declare function verifyWebhook(body: string | Uint8Array | ArrayBuffer, headers: HeadersLike, secret: string, options?: VerifyWebhookOptions): Promise<WebhookEvent>;
27
+ /**
28
+ * Computes the signature of an incoming-hook body: lower-case hex of HMAC-SHA256(secret, body).
29
+ * Send it as `X-Signature: sha256=<hex>`. An empty secret is rejected.
30
+ */
31
+ export declare function signHookPayload(body: string | Uint8Array | ArrayBuffer, secret: string): Promise<string>;
32
+ /**
33
+ * Checks a hook signature (hex in any case, with or without the `sha256=` prefix) in constant
34
+ * time. Returns false for an empty secret or a malformed signature; it never throws for those.
35
+ */
36
+ export declare function verifyHookSignature(body: string | Uint8Array | ArrayBuffer, signature: string, secret: string): Promise<boolean>;
37
+ /** Encodes bytes as base64 without relying on Node.js APIs. */
38
+ export declare function bytesToBase64(bytes: Uint8Array): string;
39
+ /** Helpers for incoming automation hooks (`/hooks/{token}`). */
40
+ export declare const TungoHooks: {
41
+ readonly sign: typeof signHookPayload;
42
+ readonly verify: typeof verifyHookSignature;
43
+ };
44
+ /** Helpers for outgoing webhooks. */
45
+ export declare const TungoWebhooks: {
46
+ readonly verify: typeof verifyWebhook;
47
+ };
48
+ /** What `sendHook` accepts as a payload: text or bytes are sent as they are, anything else as JSON. */
49
+ export type HookPayload = string | Uint8Array | ArrayBuffer | Record<string, unknown> | readonly unknown[] | number | boolean | null;
50
+ /** Turns a hook payload into the exact bytes to send and their default content type. */
51
+ export declare function encodeHookPayload(payload: HookPayload): {
52
+ bytes: Uint8Array;
53
+ contentType: string;
54
+ };
55
+ /** The contract details of the incoming-hook operation; supplied by the generated resource. */
56
+ export interface HookOperation {
57
+ method: string;
58
+ path: string;
59
+ tokenParam: string;
60
+ signatureHeader: string;
61
+ eventIdHeader: string | undefined;
62
+ idempotencyHeader: string | undefined;
63
+ }
64
+ /** Options of `sendHook` / `automations.postHook`. */
65
+ export interface SendHookOptions extends RequestOptions {
66
+ /** The hook's signing secret. When given, the exact bytes sent are signed in the signature header. */
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;
73
+ /** Your id of the event, for de-duplication on the server. */
74
+ eventId?: string | undefined;
75
+ /** Content type of the body. Default: `application/json` for text and JSON values, `application/octet-stream` for bytes. */
76
+ contentType?: string | undefined;
77
+ }
78
+ /** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
79
+ export declare function sendHook<R>(client: APIClient, operation: HookOperation, token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<R>;