@tungoai/sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -0
- package/LICENSE +21 -0
- package/README.kk.md +327 -0
- package/README.md +346 -2
- package/README.ru.md +327 -0
- package/dist/cjs/chat.d.ts +85 -0
- package/dist/cjs/chat.js +151 -0
- package/dist/cjs/client.d.ts +116 -0
- package/dist/cjs/client.js +223 -0
- package/dist/cjs/core.d.ts +210 -0
- package/dist/cjs/core.js +605 -0
- package/dist/cjs/errors.d.ts +212 -0
- package/dist/cjs/errors.js +410 -0
- package/dist/cjs/generated/resources.d.ts +1059 -0
- package/dist/cjs/generated/resources.js +1064 -0
- package/dist/cjs/generated/types.d.ts +4927 -0
- package/dist/cjs/generated/types.js +11 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +80 -0
- package/dist/cjs/json.d.ts +10 -0
- package/dist/cjs/json.js +120 -0
- package/dist/cjs/money.d.ts +32 -0
- package/dist/cjs/money.js +141 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +47 -0
- package/dist/cjs/pagination.js +113 -0
- package/dist/cjs/streaming.d.ts +74 -0
- package/dist/cjs/streaming.js +253 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cjs/webhooks.d.ts +74 -0
- package/dist/cjs/webhooks.js +248 -0
- package/dist/esm/chat.d.ts +85 -0
- package/dist/esm/chat.js +143 -0
- package/dist/esm/client.d.ts +116 -0
- package/dist/esm/client.js +219 -0
- package/dist/esm/core.d.ts +210 -0
- package/dist/esm/core.js +589 -0
- package/dist/esm/errors.d.ts +212 -0
- package/dist/esm/errors.js +381 -0
- package/dist/esm/generated/resources.d.ts +1059 -0
- package/dist/esm/generated/resources.js +1048 -0
- package/dist/esm/generated/types.d.ts +4927 -0
- package/dist/esm/generated/types.js +10 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/json.d.ts +10 -0
- package/dist/esm/json.js +116 -0
- package/dist/esm/money.d.ts +32 -0
- package/dist/esm/money.js +137 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pagination.d.ts +47 -0
- package/dist/esm/pagination.js +107 -0
- package/dist/esm/streaming.d.ts +74 -0
- package/dist/esm/streaming.js +247 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/webhooks.d.ts +74 -0
- package/dist/esm/webhooks.js +239 -0
- package/package.json +67 -4
|
@@ -0,0 +1,253 @@
|
|
|
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.
|
|
238
|
+
*/
|
|
239
|
+
function decodeJSONEvent(event, response) {
|
|
240
|
+
if (event.event === 'ping' || event.data === '')
|
|
241
|
+
return undefined;
|
|
242
|
+
try {
|
|
243
|
+
return (0, json_js_1.parseJSON)(event.data);
|
|
244
|
+
}
|
|
245
|
+
catch (cause) {
|
|
246
|
+
throw new errors_js_1.DecodeError('The data of the "' + event.event + '" stream event is not valid JSON', {
|
|
247
|
+
status: response.status,
|
|
248
|
+
requestId: response.requestId,
|
|
249
|
+
body: event.data,
|
|
250
|
+
cause,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
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
|
+
/** Your id of the event, for de-duplication on the server. */
|
|
69
|
+
eventId?: string | undefined;
|
|
70
|
+
/** Content type of the body. Default: `application/json` for text and JSON values, `application/octet-stream` for bytes. */
|
|
71
|
+
contentType?: string | undefined;
|
|
72
|
+
}
|
|
73
|
+
/** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
|
|
74
|
+
export declare function sendHook<R>(client: APIClient, operation: HookOperation, token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<R>;
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TungoWebhooks = exports.TungoHooks = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = void 0;
|
|
4
|
+
exports.verifyWebhook = verifyWebhook;
|
|
5
|
+
exports.signHookPayload = signHookPayload;
|
|
6
|
+
exports.verifyHookSignature = verifyHookSignature;
|
|
7
|
+
exports.bytesToBase64 = bytesToBase64;
|
|
8
|
+
exports.encodeHookPayload = encodeHookPayload;
|
|
9
|
+
exports.sendHook = sendHook;
|
|
10
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
11
|
+
const errors_js_1 = require("./errors.js");
|
|
12
|
+
const core_js_1 = require("./core.js");
|
|
13
|
+
const json_js_1 = require("./json.js");
|
|
14
|
+
/** Default tolerance for the webhook timestamp, in seconds (both directions). */
|
|
15
|
+
exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
16
|
+
const encoder = new TextEncoder();
|
|
17
|
+
function toBytes(body) {
|
|
18
|
+
if (typeof body === 'string')
|
|
19
|
+
return encoder.encode(body);
|
|
20
|
+
if (body instanceof ArrayBuffer)
|
|
21
|
+
return new Uint8Array(body);
|
|
22
|
+
if (ArrayBuffer.isView(body)) {
|
|
23
|
+
const copy = new Uint8Array(body.byteLength);
|
|
24
|
+
copy.set(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
|
|
25
|
+
return copy;
|
|
26
|
+
}
|
|
27
|
+
throw new errors_js_1.ValidationError('The body must be a string, a Uint8Array or an ArrayBuffer (the raw bytes as received)');
|
|
28
|
+
}
|
|
29
|
+
function concat(a, b) {
|
|
30
|
+
const out = new Uint8Array(a.length + b.length);
|
|
31
|
+
out.set(a, 0);
|
|
32
|
+
out.set(b, a.length);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
function decodeBase64(text) {
|
|
36
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text))
|
|
37
|
+
return null;
|
|
38
|
+
let binary;
|
|
39
|
+
try {
|
|
40
|
+
binary = atob(text);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
const out = new Uint8Array(binary.length);
|
|
46
|
+
for (let i = 0; i < binary.length; i++)
|
|
47
|
+
out[i] = binary.charCodeAt(i);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
function decodeHex(text) {
|
|
51
|
+
if (text.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(text))
|
|
52
|
+
return null;
|
|
53
|
+
const out = new Uint8Array(text.length / 2);
|
|
54
|
+
for (let i = 0; i < out.length; i++)
|
|
55
|
+
out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
function encodeHex(bytes) {
|
|
59
|
+
let out = '';
|
|
60
|
+
for (const b of bytes)
|
|
61
|
+
out += b.toString(16).padStart(2, '0');
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
function hmacKey(key, usage) {
|
|
65
|
+
return crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
|
|
66
|
+
}
|
|
67
|
+
function findHeader(headers, name) {
|
|
68
|
+
const wanted = name.toLowerCase();
|
|
69
|
+
const iterable = headers;
|
|
70
|
+
if (typeof iterable[Symbol.iterator] === 'function') {
|
|
71
|
+
for (const pair of headers) {
|
|
72
|
+
if (Array.isArray(pair) && typeof pair[0] === 'string' && pair[0].toLowerCase() === wanted && typeof pair[1] === 'string') {
|
|
73
|
+
return pair[1];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
79
|
+
if (key.toLowerCase() !== wanted)
|
|
80
|
+
continue;
|
|
81
|
+
if (typeof value === 'string')
|
|
82
|
+
return value;
|
|
83
|
+
if (Array.isArray(value) && typeof value[0] === 'string')
|
|
84
|
+
return value[0];
|
|
85
|
+
}
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
function clock(now) {
|
|
89
|
+
if (now === undefined)
|
|
90
|
+
return Math.floor(Date.now() / 1000);
|
|
91
|
+
if (typeof now === 'number')
|
|
92
|
+
return now;
|
|
93
|
+
if (now instanceof Date)
|
|
94
|
+
return Math.floor(now.getTime() / 1000);
|
|
95
|
+
return now();
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Verifies an outgoing Tungo webhook (Standard Webhooks / Svix) and returns the typed event.
|
|
99
|
+
*
|
|
100
|
+
* Pass the RAW request body (the exact bytes, before any JSON parsing), the request headers
|
|
101
|
+
* (`webhook-*` or `svix-*`) and the endpoint's signing secret (`whsec_...`). The signature is
|
|
102
|
+
* checked in constant time and the timestamp must be within the tolerance of the clock.
|
|
103
|
+
* Every problem is reported as a {@link WebhookVerificationError}.
|
|
104
|
+
*/
|
|
105
|
+
async function verifyWebhook(body, headers, secret, options = {}) {
|
|
106
|
+
const tolerance = options.toleranceSeconds ?? exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
|
|
107
|
+
if (typeof tolerance !== 'number' || !(tolerance > 0) || !Number.isFinite(tolerance)) {
|
|
108
|
+
throw new errors_js_1.WebhookVerificationError('invalid_tolerance', 'The webhook tolerance must be a positive number of seconds');
|
|
109
|
+
}
|
|
110
|
+
if (typeof secret !== 'string') {
|
|
111
|
+
throw new errors_js_1.WebhookVerificationError('invalid_secret', 'The webhook secret must be a string');
|
|
112
|
+
}
|
|
113
|
+
const encoded = secret.startsWith('whsec_') ? secret.slice(6) : secret;
|
|
114
|
+
const key = encoded === '' ? null : decodeBase64(encoded);
|
|
115
|
+
if (key === null || key.length === 0) {
|
|
116
|
+
throw new errors_js_1.WebhookVerificationError('invalid_secret', 'The webhook secret is empty or is not base64 (expected "whsec_" followed by base64)');
|
|
117
|
+
}
|
|
118
|
+
if (headers === null || typeof headers !== 'object') {
|
|
119
|
+
throw new errors_js_1.WebhookVerificationError('missing_header', 'The webhook headers are missing');
|
|
120
|
+
}
|
|
121
|
+
const get = (suffix) => findHeader(headers, 'svix-' + suffix) ?? findHeader(headers, 'webhook-' + suffix);
|
|
122
|
+
const id = get('id');
|
|
123
|
+
const timestamp = get('timestamp');
|
|
124
|
+
const signature = get('signature');
|
|
125
|
+
if (id === undefined || timestamp === undefined || signature === undefined) {
|
|
126
|
+
throw new errors_js_1.WebhookVerificationError('missing_header', 'A webhook header is missing (webhook-id, webhook-timestamp and webhook-signature are required)');
|
|
127
|
+
}
|
|
128
|
+
if (!/^[0-9]+$/.test(timestamp) || !Number.isSafeInteger(Number(timestamp))) {
|
|
129
|
+
throw new errors_js_1.WebhookVerificationError('malformed_timestamp', 'The webhook timestamp is not a whole number of seconds');
|
|
130
|
+
}
|
|
131
|
+
const sent = Number(timestamp);
|
|
132
|
+
const now = clock(options.now);
|
|
133
|
+
if (now - sent > tolerance) {
|
|
134
|
+
throw new errors_js_1.WebhookVerificationError('timestamp_too_old', 'The webhook timestamp is older than the tolerance of ' + tolerance + ' s');
|
|
135
|
+
}
|
|
136
|
+
if (sent - now > tolerance) {
|
|
137
|
+
throw new errors_js_1.WebhookVerificationError('timestamp_too_new', 'The webhook timestamp is further in the future than the tolerance of ' + tolerance + ' s');
|
|
138
|
+
}
|
|
139
|
+
let bytes;
|
|
140
|
+
try {
|
|
141
|
+
bytes = toBytes(body);
|
|
142
|
+
}
|
|
143
|
+
catch (cause) {
|
|
144
|
+
throw new errors_js_1.WebhookVerificationError('invalid_payload', 'The webhook body must be the raw request body (string or bytes)', { cause });
|
|
145
|
+
}
|
|
146
|
+
const signed = concat(encoder.encode(id + '.' + timestamp + '.'), bytes);
|
|
147
|
+
let matched = false;
|
|
148
|
+
try {
|
|
149
|
+
const cryptoKey = await hmacKey(key, 'verify');
|
|
150
|
+
for (const part of signature.split(/[ \t\r\n\f\v]+/)) {
|
|
151
|
+
const comma = part.indexOf(',');
|
|
152
|
+
if (comma === -1 || part.slice(0, comma) !== 'v1')
|
|
153
|
+
continue;
|
|
154
|
+
const candidate = decodeBase64(part.slice(comma + 1));
|
|
155
|
+
if (candidate === null)
|
|
156
|
+
continue;
|
|
157
|
+
// SubtleCrypto.verify compares the MAC in constant time.
|
|
158
|
+
if (await crypto.subtle.verify('HMAC', cryptoKey, candidate, signed))
|
|
159
|
+
matched = true;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
catch (cause) {
|
|
163
|
+
throw new errors_js_1.WebhookVerificationError('signature_mismatch', 'The webhook signature could not be checked', { cause });
|
|
164
|
+
}
|
|
165
|
+
if (!matched) {
|
|
166
|
+
throw new errors_js_1.WebhookVerificationError('signature_mismatch', 'No webhook signature matches the body: check the secret and pass the raw body');
|
|
167
|
+
}
|
|
168
|
+
let event;
|
|
169
|
+
try {
|
|
170
|
+
event = (0, json_js_1.parseJSON)(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
171
|
+
}
|
|
172
|
+
catch (cause) {
|
|
173
|
+
throw new errors_js_1.WebhookVerificationError('invalid_payload', 'The webhook signature is valid but the body is not JSON', { cause });
|
|
174
|
+
}
|
|
175
|
+
if (typeof event !== 'object' || event === null || typeof event.type !== 'string') {
|
|
176
|
+
throw new errors_js_1.WebhookVerificationError('invalid_payload', 'The webhook signature is valid but the body is not an event object');
|
|
177
|
+
}
|
|
178
|
+
return event;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Computes the signature of an incoming-hook body: lower-case hex of HMAC-SHA256(secret, body).
|
|
182
|
+
* Send it as `X-Signature: sha256=<hex>`. An empty secret is rejected.
|
|
183
|
+
*/
|
|
184
|
+
async function signHookPayload(body, secret) {
|
|
185
|
+
if (typeof secret !== 'string' || secret === '')
|
|
186
|
+
throw new errors_js_1.ValidationError('The hook secret must not be empty');
|
|
187
|
+
const key = await hmacKey(encoder.encode(secret), 'sign');
|
|
188
|
+
return encodeHex(new Uint8Array(await crypto.subtle.sign('HMAC', key, toBytes(body))));
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Checks a hook signature (hex in any case, with or without the `sha256=` prefix) in constant
|
|
192
|
+
* time. Returns false for an empty secret or a malformed signature; it never throws for those.
|
|
193
|
+
*/
|
|
194
|
+
async function verifyHookSignature(body, signature, secret) {
|
|
195
|
+
if (typeof secret !== 'string' || secret === '' || typeof signature !== 'string')
|
|
196
|
+
return false;
|
|
197
|
+
const hex = signature.slice(0, 7).toLowerCase() === 'sha256=' ? signature.slice(7) : signature;
|
|
198
|
+
const given = decodeHex(hex);
|
|
199
|
+
if (given === null || given.length !== 32)
|
|
200
|
+
return false;
|
|
201
|
+
const key = await hmacKey(encoder.encode(secret), 'verify');
|
|
202
|
+
return crypto.subtle.verify('HMAC', key, given, toBytes(body));
|
|
203
|
+
}
|
|
204
|
+
/** Encodes bytes as base64 without relying on Node.js APIs. */
|
|
205
|
+
function bytesToBase64(bytes) {
|
|
206
|
+
let binary = '';
|
|
207
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
208
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
209
|
+
}
|
|
210
|
+
return btoa(binary);
|
|
211
|
+
}
|
|
212
|
+
/** Helpers for incoming automation hooks (`/hooks/{token}`). */
|
|
213
|
+
exports.TungoHooks = { sign: signHookPayload, verify: verifyHookSignature };
|
|
214
|
+
/** Helpers for outgoing webhooks. */
|
|
215
|
+
exports.TungoWebhooks = { verify: verifyWebhook };
|
|
216
|
+
/** Turns a hook payload into the exact bytes to send and their default content type. */
|
|
217
|
+
function encodeHookPayload(payload) {
|
|
218
|
+
if (typeof payload === 'string')
|
|
219
|
+
return { bytes: encoder.encode(payload), contentType: 'application/json' };
|
|
220
|
+
if (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload)) {
|
|
221
|
+
return { bytes: toBytes(payload), contentType: 'application/octet-stream' };
|
|
222
|
+
}
|
|
223
|
+
return { bytes: encoder.encode((0, json_js_1.stringifyJSON)(payload)), contentType: 'application/json' };
|
|
224
|
+
}
|
|
225
|
+
/** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
|
|
226
|
+
function sendHook(client, operation, token, payload, options = {}) {
|
|
227
|
+
const run = async () => {
|
|
228
|
+
const { secret, eventId, contentType, ...requestOptions } = options;
|
|
229
|
+
const encoded = encodeHookPayload(payload);
|
|
230
|
+
const headers = {};
|
|
231
|
+
if (secret !== undefined)
|
|
232
|
+
headers[operation.signatureHeader] = 'sha256=' + (await signHookPayload(encoded.bytes, secret));
|
|
233
|
+
if (eventId !== undefined && operation.eventIdHeader !== undefined)
|
|
234
|
+
headers[operation.eventIdHeader] = eventId;
|
|
235
|
+
return {
|
|
236
|
+
method: operation.method,
|
|
237
|
+
path: operation.path,
|
|
238
|
+
pathParams: { [operation.tokenParam]: token },
|
|
239
|
+
rawBody: encoded.bytes,
|
|
240
|
+
contentType: contentType ?? encoded.contentType,
|
|
241
|
+
headers,
|
|
242
|
+
auth: 'hook',
|
|
243
|
+
idempotencyHeader: operation.idempotencyHeader,
|
|
244
|
+
options: requestOptions,
|
|
245
|
+
};
|
|
246
|
+
};
|
|
247
|
+
return new core_js_1.APIPromise(run().then((spec) => client.request(spec).withResponse()));
|
|
248
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { StreamPromise } from './core.js';
|
|
2
|
+
import { type APIError } from './errors.js';
|
|
3
|
+
import { Stream, type ResponseInfo, type StreamInit } from './streaming.js';
|
|
4
|
+
import type * as T from './generated/types.js';
|
|
5
|
+
/** Callbacks invoked while a chat stream is being accumulated. */
|
|
6
|
+
export interface ChatStreamCallbacks {
|
|
7
|
+
/** Every event, in order. */
|
|
8
|
+
onEvent?: ((event: T.ChatEvent) => void) | undefined;
|
|
9
|
+
/** A piece of the answer text. */
|
|
10
|
+
onTextDelta?: ((delta: string, event: T.ChatEventText) => void) | undefined;
|
|
11
|
+
/** A piece of the model's reasoning. */
|
|
12
|
+
onThinkingDelta?: ((delta: string, event: T.ChatEventThinking) => void) | undefined;
|
|
13
|
+
/** A tool call started, finished or failed. */
|
|
14
|
+
onTool?: ((event: T.ChatEventTool) => void) | undefined;
|
|
15
|
+
/** The text of a step turned out to be an intermediate remark, not part of the answer. */
|
|
16
|
+
onProgress?: ((event: T.ChatEventProgress) => void) | undefined;
|
|
17
|
+
}
|
|
18
|
+
/** A chat turn assembled from its stream. */
|
|
19
|
+
export interface ChatStreamResult {
|
|
20
|
+
/**
|
|
21
|
+
* The final answer: `done.answer` when the server sent it, otherwise the text deltas joined,
|
|
22
|
+
* without the deltas of steps that a later `progress` event marked as intermediate.
|
|
23
|
+
*/
|
|
24
|
+
text: string;
|
|
25
|
+
/** Dialog id from the `X-Dialog-Id` response header. */
|
|
26
|
+
dialogId: string | null;
|
|
27
|
+
/** Turn number from the `X-Turn-No` response header. */
|
|
28
|
+
turnNo: number | null;
|
|
29
|
+
/** `done.stop_reason`; null when absent (and in the partial result of a stream that ended without `done`). */
|
|
30
|
+
stopReason: string | null;
|
|
31
|
+
/** `done.cost_tiyn`; null when absent. A `bigint` beyond 2^53, like every 64-bit integer of the API. */
|
|
32
|
+
costTiyn: number | bigint | null;
|
|
33
|
+
/** `done.usage`; null when absent. */
|
|
34
|
+
usage: T.ChatUsage | null;
|
|
35
|
+
/** `done.choice_id`: the question to answer with `chat.answer`; null when absent. */
|
|
36
|
+
choiceId: string | null;
|
|
37
|
+
/** Every event received, heart-beats excluded. */
|
|
38
|
+
events: T.ChatEvent[];
|
|
39
|
+
/** The first `error` event of the turn, or null. */
|
|
40
|
+
error: T.ChatEventError | null;
|
|
41
|
+
}
|
|
42
|
+
/** Folds the events of one chat turn into a {@link ChatStreamResult}. */
|
|
43
|
+
export declare class ChatAccumulator {
|
|
44
|
+
#private;
|
|
45
|
+
/** Adds one event. Unknown event types are kept in `events` and otherwise ignored. */
|
|
46
|
+
push(event: T.ChatEvent, callbacks?: ChatStreamCallbacks): void;
|
|
47
|
+
/** True once the `done` event has arrived: the server finished the turn. */
|
|
48
|
+
get completed(): boolean;
|
|
49
|
+
/** The turn as accumulated so far. */
|
|
50
|
+
result(meta?: {
|
|
51
|
+
dialogId?: string | null;
|
|
52
|
+
turnNo?: number | null;
|
|
53
|
+
}): ChatStreamResult;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Converts a chat `error` object (`{ type, code, message, ... }`, from a stream event or from
|
|
57
|
+
* `ChatTurnResult.errors`) into the typed error of the class an HTTP error response with the same
|
|
58
|
+
* `error.type` produces. Its `status` is undefined: the HTTP response that carried the turn was
|
|
59
|
+
* successful, so there is no error status to report. `response` supplies the headers, the request
|
|
60
|
+
* id and the rate limit.
|
|
61
|
+
*/
|
|
62
|
+
export declare function chatTurnError(error: unknown, requestId: string | null, response?: ResponseInfo): APIError;
|
|
63
|
+
/**
|
|
64
|
+
* Consumes a chat event stream to its end and returns the assembled turn. A mid-stream `error`
|
|
65
|
+
* event makes it throw the matching typed {@link APIError}, and a stream that ends without its
|
|
66
|
+
* `done` event (a dropped connection, a proxy that cut it) a {@link DecodeError}: a partial text
|
|
67
|
+
* is never returned as a finished turn. Both errors carry what was accumulated in `partialResult`.
|
|
68
|
+
* When `events` is a {@link ChatStream}, `dialogId` and `turnNo` are filled from the response headers.
|
|
69
|
+
*/
|
|
70
|
+
export declare function accumulateChatStream(events: AsyncIterable<T.ChatEvent> | Iterable<T.ChatEvent>, callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
|
|
71
|
+
/** The event stream of one chat turn (or of a batch job, which reports with the same events). */
|
|
72
|
+
export declare class ChatStream extends Stream<T.ChatEvent> {
|
|
73
|
+
/** Dialog id from the `X-Dialog-Id` response header; null when the operation does not send it. */
|
|
74
|
+
readonly dialogId: string | null;
|
|
75
|
+
/** Turn number from the `X-Turn-No` response header; null when absent. */
|
|
76
|
+
readonly turnNo: number | null;
|
|
77
|
+
constructor(init: StreamInit);
|
|
78
|
+
/** Reads the stream to its end and returns the assembled turn; throws on a mid-stream `error` event and when the stream ends without `done`. */
|
|
79
|
+
finalResult(callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
|
|
80
|
+
}
|
|
81
|
+
/** A promise of a {@link ChatStream} that can be iterated directly or reduced with `finalResult()`. */
|
|
82
|
+
export declare class ChatStreamPromise extends StreamPromise<T.ChatEvent, ChatStream> {
|
|
83
|
+
/** Opens the stream, reads it to its end and returns the assembled turn. */
|
|
84
|
+
finalResult(callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
|
|
85
|
+
}
|