@aliendesk/chat-sdk 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alien Desk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # @aliendesk/chat-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build your own chat screen on [Alien Desk](https://aliendesk.io): the AI agent that answers from your help center, acts in your product for the signed-in user (and asks before it changes anything), and hands the chat to your team when needed. The SDK draws nothing. It handles the session, sending, live events, reconnecting and the user's tool token; your app draws the messages.
4
+
5
+ Full guide: [Build your own chat](https://docs.aliendesk.io/guides/build-your-own-chat).
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @aliendesk/chat-sdk
11
+ ```
12
+
13
+ Or without a bundler:
14
+
15
+ ```html
16
+ <script src="https://widget.aliendesk.io/sdk.js"></script>
17
+ <!-- defines window.AlienDeskChat -->
18
+ ```
19
+
20
+ ## Quick start
21
+
22
+ ```js
23
+ import { createChat } from '@aliendesk/chat-sdk';
24
+
25
+ const chat = createChat({ key: 'pk_...' }); // your brand's public key
26
+
27
+ // A signed-in user. userHash is an HMAC-SHA256 of the user id with your brand's identity secret, computed on your server.
28
+ const session = await chat.identify({ userId: user.id, userHash, name: user.name, email: user.email });
29
+ // Or an anonymous visitor: await chat.start();
30
+
31
+ chat.on('message', (message) => upsert(message)); // key your list by message.id
32
+ chat.on('message.updated', (message) => upsert(message));
33
+ chat.on('delta', ({ text }) => showDraft(text)); // the answer while it is written
34
+ chat.on('confirmation', ({ message }) => askToConfirm(message.confirmation, (yes) => chat.confirm(yes)));
35
+
36
+ await chat.send('Pause my Diwali campaign');
37
+ ```
38
+
39
+ Show message text as text (`textContent` or your framework's normal binding), never as HTML.
40
+
41
+ ## Before you start
42
+
43
+ - Add every site your chat runs on to **Brand settings → Chat widget → Allowed domains** in Alien Desk. Browser calls from other sites are refused.
44
+ - Never put a secret API key (`adk_live_...`) in a page or an app.
45
+ - To let the AI agent act in your product, pass the user's short-lived tool token with `identify` and register `chat.onTokenRequest(fn)`. See [Connect your product](https://docs.aliendesk.io/guides/connect-your-product).
46
+
47
+ ## Requirements
48
+
49
+ Browsers with `fetch` and `ReadableStream`, or Node 18+. ES modules only.
50
+
51
+ ## Licence
52
+
53
+ MIT
package/dist/chat.d.ts ADDED
@@ -0,0 +1,165 @@
1
+ import { ChatError } from './errors.js';
2
+ import type { ChatConversation, ChatEvent, ChatMessage, ChatSession } from './types.js';
3
+ /** The Alien Desk app the Chat API lives on. `sdk.js` is built with the address of the app that serves it. */
4
+ export declare const DEFAULT_API_URL: string;
5
+ /** Where the session token is kept between page loads. */
6
+ export interface ChatStorage {
7
+ get(key: string): string | null;
8
+ set(key: string, value: string): void;
9
+ remove(key: string): void;
10
+ }
11
+ export interface ChatOptions {
12
+ /** The brand's public key (`pk_...`), the same one the widget uses. */
13
+ key: string;
14
+ apiUrl?: string;
15
+ /** Default: localStorage in a browser, memory elsewhere. `null`: memory only (a reload starts a new visitor). */
16
+ storage?: ChatStorage | null;
17
+ /** Read live events (default true). Off: poll `open()` yourself. */
18
+ stream?: boolean;
19
+ /** The user's language for a new session (`en`, `hi-IN`). */
20
+ locale?: string;
21
+ /** Your own fetch (Node without a global fetch, tests). */
22
+ fetch?: typeof fetch;
23
+ /** Waits before reconnecting the stream or retrying a send, in ms; the last one repeats. Default 1, 2, 5, 10, 30 s. */
24
+ retryDelaysMs?: number[];
25
+ }
26
+ /** The signed-in user, as for the widget's identify(). `userHash` is HMAC-SHA256 of `userId` with the brand's identity secret, made on your server. */
27
+ export interface ChatIdentity {
28
+ userId: string | number;
29
+ userHash: string;
30
+ /** HMAC-SHA256 of `<userId>:<email>`: the email is then trusted too. */
31
+ emailHash?: string;
32
+ name?: string;
33
+ email?: string;
34
+ phone?: string;
35
+ attrs?: Record<string, unknown>;
36
+ /** The user's short-lived token for your product's tools (connected product). */
37
+ toolToken?: string;
38
+ /** ISO date, or Unix seconds or milliseconds. */
39
+ toolTokenExpiresAt?: string | number;
40
+ }
41
+ export interface ToolTokenAnswer {
42
+ toolToken: string;
43
+ toolTokenExpiresAt?: string | number;
44
+ }
45
+ /** Your function that gets the signed-in user a fresh tool token from your server. */
46
+ export type TokenHandler = () => Promise<ToolTokenAnswer | string | null | undefined> | ToolTokenAnswer | string | null | undefined;
47
+ /** A page action the AI may trigger (`on('action')`). */
48
+ export interface ClientTool {
49
+ name: string;
50
+ description: string;
51
+ parameters?: Record<string, unknown> | null;
52
+ }
53
+ export type ConnectionState = 'connecting' | 'open' | 'reconnecting' | 'closed';
54
+ export interface ChatEventMap {
55
+ /** A session is open: after the first call, `identify()`, or opening a new one when the old one ended. */
56
+ session: ChatSession;
57
+ /** A new message: the user's own too (key your list by `message.id`: `send()` returns the same message). */
58
+ message: ChatMessage;
59
+ /** A message changed (a confirmation card answered, feedback given): replace it by id. */
60
+ 'message.updated': ChatMessage;
61
+ conversation: ChatConversation;
62
+ typing: {
63
+ conversationId: string;
64
+ who: 'ai' | 'agent';
65
+ name: string | null;
66
+ on: boolean;
67
+ };
68
+ /** The AI's answer so far, while it is written. The `message` that follows replaces it. */
69
+ delta: {
70
+ conversationId: string;
71
+ text: string;
72
+ };
73
+ step: {
74
+ conversationId: string;
75
+ title: string;
76
+ status: 'running' | 'done' | 'failed';
77
+ };
78
+ /** The AI asks the user to confirm a change: show the card, then `confirm(true | false)`. */
79
+ confirmation: {
80
+ conversationId: string;
81
+ message: ChatMessage;
82
+ };
83
+ /** The AI asks your page to do something: one of your `clientTools`. */
84
+ action: {
85
+ conversationId: string;
86
+ name: string;
87
+ args: Record<string, unknown>;
88
+ };
89
+ /** After a reconnect: the open chat as it is now (events may have been missed). Replace what you show. */
90
+ sync: {
91
+ conversation: ChatConversation;
92
+ messages: ChatMessage[];
93
+ };
94
+ connection: ConnectionState;
95
+ /** Every stream event as the server sent it. */
96
+ event: ChatEvent;
97
+ error: ChatError;
98
+ }
99
+ type Listener<K extends keyof ChatEventMap> = (payload: ChatEventMap[K]) => void;
100
+ export interface SendResult {
101
+ conversation: ChatConversation;
102
+ message: ChatMessage;
103
+ /** The message started a new chat (none was open, or the open one had been closed). */
104
+ newConversation: boolean;
105
+ }
106
+ export declare function createChat(options: ChatOptions): {
107
+ /** Open (or resume) the session now, and read its events. Every other call opens the session itself when needed. */
108
+ start(): Promise<ChatSession>;
109
+ /** Sign the user in (their signed id), with their tool token if your product is connected. Call again for another user. */
110
+ identify(input: ChatIdentity): Promise<ChatSession>;
111
+ /** The user signed out of your product: the session ends, its token is forgotten, the stream closes. */
112
+ signOut(): Promise<void>;
113
+ /** A fresh tool token for the AI's actions in your product (the user's own). Usually `onTokenRequest` does this. */
114
+ setToolToken: (toolToken: string, toolTokenExpiresAt?: string | number) => Promise<boolean>;
115
+ /** Called when the AI needs a fresh tool token, and before the current one expires. Return `{ toolToken, toolTokenExpiresAt }` or the token alone. */
116
+ onTokenRequest(fn: TokenHandler | null): void;
117
+ /** Where the user is in your product (a hint for the AI, never trusted). `null` clears it. */
118
+ context(value: Record<string, unknown> | null): Promise<void>;
119
+ /** Page actions the AI may trigger; they arrive at `on('action')`. */
120
+ clientTools(tools: ClientTool[] | null): Promise<void>;
121
+ /** The user's most recent chats, newest first. */
122
+ conversations(): Promise<ChatConversation[]>;
123
+ /** Load a chat and make it the one `send()` writes to. */
124
+ open(conversationId: string): Promise<{
125
+ conversation: ChatConversation;
126
+ messages: ChatMessage[];
127
+ }>;
128
+ /** The next `send()` starts a new chat. */
129
+ newConversation(): void;
130
+ /** The chat `send()` writes to, or null before the first message. */
131
+ readonly conversationId: string | null;
132
+ readonly session: ChatSession | null;
133
+ readonly connection: ConnectionState;
134
+ /**
135
+ * Send a message: to the open chat, or a new one. A lost answer is retried with the same id, so the message is
136
+ * never sent twice. The answer arrives as events (`delta`, `step`, then `message`).
137
+ */
138
+ send(text: string, opts?: {
139
+ conversationId?: string;
140
+ clientMessageId?: string;
141
+ }): Promise<SendResult>;
142
+ /** Yes or No for the change the AI asked about. A second answer does nothing. */
143
+ confirm(yes: boolean, conversationId?: string): Promise<void>;
144
+ /** Hand the chat to a person on the team. */
145
+ askForPerson(conversationId?: string): Promise<{
146
+ conversation: ChatConversation;
147
+ team: {
148
+ status: "online" | "away" | "offline";
149
+ };
150
+ }>;
151
+ /** Where replies go when the user leaves; a handover waiting for an email (`awaitingEmail`) goes ahead. */
152
+ setEmail(email: string, conversationId?: string): Promise<ChatConversation>;
153
+ end(conversationId?: string): Promise<ChatConversation>;
154
+ rate(label: "good" | "poor", comment?: string, conversationId?: string): Promise<ChatConversation>;
155
+ /** The user has the chat open on its latest replies (the team sees them as read). */
156
+ markRead(conversationId?: string): Promise<void>;
157
+ /** Helpful or not, on an answer from the AI. */
158
+ feedback(messageId: string, helpful: boolean): Promise<void>;
159
+ /** Listen to an event; returns the function that stops listening. */
160
+ on<K extends keyof ChatEventMap>(type: K, fn: Listener<K>): () => void;
161
+ /** Stop reading events and the token timer. The session stays: `start()` reads events again. */
162
+ close(): void;
163
+ };
164
+ export type Chat = ReturnType<typeof createChat>;
165
+ export {};
package/dist/chat.js ADDED
@@ -0,0 +1,520 @@
1
+ // createChat(): a product's own chat screen on Alien Desk. It opens the session,
2
+ // keeps its token, sends messages safely (a retry never sends twice), reads the live events and reconnects, and
3
+ // passes the user's tool token on when the AI needs a fresh one. No UI: the product draws its own.
4
+ import { ChatError } from './errors.js';
5
+ import { readEvents } from './sse.js';
6
+ import { expiryMs, refreshDelay, TOKEN_ASK_MIN_MS } from './tool-token.js';
7
+ /** The Alien Desk app the Chat API lives on. `sdk.js` is built with the address of the app that serves it. */
8
+ export const DEFAULT_API_URL = typeof __ALIENDESK_API_URL__ === 'string' ? __ALIENDESK_API_URL__ : 'https://app.aliendesk.io';
9
+ const DEFAULT_DELAYS = [1000, 2000, 5000, 10000, 30000];
10
+ function memoryStorage() {
11
+ const m = new Map();
12
+ return { get: (k) => m.get(k) ?? null, set: (k, v) => void m.set(k, v), remove: (k) => void m.delete(k) };
13
+ }
14
+ function browserStorage() {
15
+ try {
16
+ const ls = typeof window !== 'undefined' ? window.localStorage : undefined;
17
+ if (!ls)
18
+ return null;
19
+ return {
20
+ get: (k) => {
21
+ try {
22
+ return ls.getItem(k);
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ },
28
+ set: (k, v) => {
29
+ try {
30
+ ls.setItem(k, v);
31
+ }
32
+ catch {
33
+ /* private mode, full storage: the session lasts for this page only */
34
+ }
35
+ },
36
+ remove: (k) => {
37
+ try {
38
+ ls.removeItem(k);
39
+ }
40
+ catch {
41
+ /* ignore */
42
+ }
43
+ },
44
+ };
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ const newId = () => (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function' ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`);
51
+ const sleep = (ms, signal) => new Promise((resolve) => {
52
+ if (signal?.aborted)
53
+ return resolve();
54
+ const t = setTimeout(done, ms);
55
+ function done() {
56
+ clearTimeout(t);
57
+ signal?.removeEventListener('abort', done);
58
+ resolve();
59
+ }
60
+ signal?.addEventListener('abort', done, { once: true });
61
+ });
62
+ const unref = (t) => t.unref?.();
63
+ export function createChat(options) {
64
+ if (!options?.key)
65
+ throw new ChatError(0, 'bad_request', 'createChat() needs the brand\'s public key: { key: "pk_..." }.');
66
+ const apiUrl = (options.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
67
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
68
+ const storage = options.storage === null ? memoryStorage() : (options.storage ?? browserStorage() ?? memoryStorage());
69
+ const storageKey = `aliendesk.chat.${options.key}`;
70
+ const delays = options.retryDelaysMs?.length ? options.retryDelaysMs : DEFAULT_DELAYS;
71
+ const delayFor = (attempt) => delays[Math.min(attempt, delays.length - 1)];
72
+ const listeners = new Map();
73
+ let session = null;
74
+ let opening = null;
75
+ /** The proven user, in memory only: a refreshed tool token is accepted only with their signed id. */
76
+ let user = null;
77
+ let pendingHost = {};
78
+ let current = null;
79
+ const deltas = new Map();
80
+ let tokenHandler = null;
81
+ let tokenTimer = null;
82
+ let tokenExpiresAt;
83
+ let lastTokenAsk = 0;
84
+ let streamGen = 0;
85
+ let streamCtl = null;
86
+ let connection = 'closed';
87
+ function emit(type, payload) {
88
+ for (const fn of [...(listeners.get(type) ?? [])]) {
89
+ try {
90
+ fn(payload);
91
+ }
92
+ catch (e) {
93
+ // A listener's own bug never stops the chat.
94
+ if (type !== 'error')
95
+ emit('error', new ChatError(0, 'listener_failed', `An "${String(type)}" listener threw: ${String(e?.message ?? e)}`));
96
+ }
97
+ }
98
+ }
99
+ function setConnection(state) {
100
+ if (state === connection)
101
+ return;
102
+ connection = state;
103
+ emit('connection', state);
104
+ }
105
+ // ---------------------------------------------------------------------------------------------
106
+ // HTTP
107
+ // ---------------------------------------------------------------------------------------------
108
+ async function request(method, path, body, opts = {}) {
109
+ const useSession = opts.session !== false;
110
+ const s = useSession ? await ready() : null;
111
+ const headers = { accept: 'application/json' };
112
+ if (body !== undefined)
113
+ headers['content-type'] = 'application/json';
114
+ if (s)
115
+ headers.authorization = `Bearer ${s.sessionToken}`;
116
+ let res;
117
+ try {
118
+ res = await doFetch(`${apiUrl}/api/v1/chat${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
119
+ }
120
+ catch (e) {
121
+ throw new ChatError(0, 'network', 'No connection to the chat. Check the internet connection and try again.', undefined, e);
122
+ }
123
+ const data = (await res.json().catch(() => null));
124
+ if (!res.ok) {
125
+ // The session ended elsewhere (signed out, removed): open a new one and try once more.
126
+ if (res.status === 401 && s && opts.retry401 !== false) {
127
+ if (session === s)
128
+ forget();
129
+ return request(method, path, body, { ...opts, retry401: false });
130
+ }
131
+ throw new ChatError(res.status, data?.error?.code ?? 'error', data?.error?.message ?? `The chat answered ${res.status}.`, data?.error?.fields);
132
+ }
133
+ return data;
134
+ }
135
+ /** Retries a call that may not have arrived (no connection) or is still running (409), with the same body. */
136
+ async function retrying(run) {
137
+ for (let attempt = 0;; attempt++) {
138
+ try {
139
+ return await run();
140
+ }
141
+ catch (e) {
142
+ const err = e;
143
+ const again = err instanceof ChatError && (err.status === 0 || (err.status === 409 && err.code === 'in_progress'));
144
+ if (!again || attempt >= 2)
145
+ throw e;
146
+ await sleep(delayFor(attempt));
147
+ }
148
+ }
149
+ }
150
+ // ---------------------------------------------------------------------------------------------
151
+ // Session
152
+ // ---------------------------------------------------------------------------------------------
153
+ function forget() {
154
+ session = null;
155
+ storage.remove(storageKey);
156
+ }
157
+ async function openSession(extra) {
158
+ const host = pendingHost;
159
+ const body = {
160
+ key: options.key,
161
+ ...(storage.get(storageKey) ? { sessionToken: storage.get(storageKey) } : {}),
162
+ ...(options.locale ? { locale: options.locale } : {}),
163
+ ...(user ? { user: { id: user.id, hash: user.hash } } : {}),
164
+ ...host,
165
+ ...extra,
166
+ };
167
+ const s = await request('POST', '/sessions', body, { session: false });
168
+ pendingHost = {};
169
+ session = s;
170
+ storage.set(storageKey, s.sessionToken);
171
+ emit('session', s);
172
+ if (options.stream !== false)
173
+ startStream(s.stream);
174
+ return s;
175
+ }
176
+ /** The open session, opening (or resuming) one first. */
177
+ function ready() {
178
+ if (session)
179
+ return Promise.resolve(session);
180
+ opening ?? (opening = openSession({}).finally(() => (opening = null)));
181
+ return opening;
182
+ }
183
+ // ---------------------------------------------------------------------------------------------
184
+ // Tool token
185
+ // ---------------------------------------------------------------------------------------------
186
+ function scheduleToken(expiresAt) {
187
+ tokenExpiresAt = expiresAt;
188
+ if (tokenTimer)
189
+ clearTimeout(tokenTimer);
190
+ tokenTimer = null;
191
+ const wait = tokenHandler ? refreshDelay(expiresAt, Date.now()) : null;
192
+ if (wait === null)
193
+ return;
194
+ tokenTimer = setTimeout(() => void askForToken(false), wait);
195
+ unref(tokenTimer);
196
+ }
197
+ async function askForToken(onDemand) {
198
+ if (!tokenHandler || !user)
199
+ return;
200
+ if (onDemand && Date.now() - lastTokenAsk < TOKEN_ASK_MIN_MS)
201
+ return;
202
+ lastTokenAsk = Date.now();
203
+ let answer;
204
+ try {
205
+ answer = await tokenHandler();
206
+ }
207
+ catch (e) {
208
+ emit('error', new ChatError(0, 'token_request_failed', `onTokenRequest failed: ${String(e?.message ?? e)}`, undefined, e));
209
+ return;
210
+ }
211
+ // The token alone (a string), as the widget's onTokenRequest also takes.
212
+ const next = typeof answer === 'string' ? { toolToken: answer } : answer;
213
+ if (!next?.toolToken)
214
+ return;
215
+ try {
216
+ await setToolToken(next.toolToken, next.toolTokenExpiresAt);
217
+ }
218
+ catch (e) {
219
+ emit('error', e instanceof ChatError ? e : new ChatError(0, 'error', String(e)));
220
+ }
221
+ }
222
+ async function setToolToken(toolToken, toolTokenExpiresAt) {
223
+ if (!user)
224
+ throw new ChatError(0, 'not_identified', 'Call identify() with userId and userHash before passing a tool token.');
225
+ const r = await request('POST', '/sessions/current/tool-token', { user, toolToken, ...(toolTokenExpiresAt !== undefined ? { toolTokenExpiresAt } : {}) });
226
+ if (r.stored)
227
+ scheduleToken(toolTokenExpiresAt);
228
+ return r.stored;
229
+ }
230
+ // ---------------------------------------------------------------------------------------------
231
+ // Live events
232
+ // ---------------------------------------------------------------------------------------------
233
+ function stopStream() {
234
+ streamGen++;
235
+ streamCtl?.abort();
236
+ streamCtl = null;
237
+ }
238
+ function startStream(first) {
239
+ stopStream();
240
+ const gen = streamGen;
241
+ const ctl = new AbortController();
242
+ streamCtl = ctl;
243
+ void runStream(gen, ctl, first);
244
+ }
245
+ const live = (gen, ctl) => gen === streamGen && !ctl.signal.aborted;
246
+ async function runStream(gen, ctl, first) {
247
+ let ticket = first;
248
+ let attempt = 0;
249
+ let reconnect = false;
250
+ while (live(gen, ctl)) {
251
+ let expired = false;
252
+ try {
253
+ // A ticket close to its end is replaced first (it lasts an hour).
254
+ if (!ticket || (expiryMs(ticket.expiresAt) ?? 0) - Date.now() < 5000)
255
+ ticket = await request('POST', '/sessions/current/stream-ticket');
256
+ if (!live(gen, ctl))
257
+ return;
258
+ setConnection(reconnect ? 'reconnecting' : 'connecting');
259
+ const res = await doFetch(ticket.url, { headers: { accept: 'text/event-stream', authorization: `Bearer ${ticket.ticket}` }, signal: ctl.signal });
260
+ if (!res.ok || !res.body) {
261
+ const data = (await res.json().catch(() => null));
262
+ const err = new ChatError(res.status, data?.error?.code ?? 'error', data?.error?.message ?? `The event stream answered ${res.status}.`);
263
+ // This site may not read the stream: trying again won't change that.
264
+ if (res.status === 403) {
265
+ emit('error', err);
266
+ setConnection('closed');
267
+ return;
268
+ }
269
+ // An expired ticket, or a signed-out session: a new ticket (and if need be a new session) next time.
270
+ if (res.status === 401)
271
+ ticket = null;
272
+ throw err;
273
+ }
274
+ await readEvents(res.body, (type, data) => {
275
+ if (!live(gen, ctl))
276
+ return;
277
+ const e = data;
278
+ if (type === 'ready') {
279
+ attempt = 0;
280
+ setConnection('open');
281
+ if (reconnect)
282
+ void resync();
283
+ return;
284
+ }
285
+ if (type === 'expired') {
286
+ expired = true;
287
+ ticket = null;
288
+ return;
289
+ }
290
+ handle(e);
291
+ }, ctl.signal);
292
+ }
293
+ catch (e) {
294
+ if (!live(gen, ctl))
295
+ return;
296
+ if (e instanceof ChatError && e.status !== 0 && e.status !== 401)
297
+ emit('error', e);
298
+ }
299
+ if (!live(gen, ctl))
300
+ return;
301
+ reconnect = true;
302
+ setConnection('reconnecting');
303
+ // A ticket that ran out is replaced at once; a dropped connection waits a little longer each time.
304
+ if (!expired)
305
+ await sleep(delayFor(attempt++), ctl.signal);
306
+ }
307
+ }
308
+ /** After a reconnect, the open chat is read again: events sent while the stream was down are not replayed. */
309
+ async function resync() {
310
+ deltas.clear();
311
+ const id = current;
312
+ if (!id)
313
+ return;
314
+ try {
315
+ const r = await request('GET', `/conversations/${encodeURIComponent(id)}`);
316
+ if (current === id)
317
+ emit('sync', r);
318
+ }
319
+ catch (e) {
320
+ if (e instanceof ChatError)
321
+ emit('error', e);
322
+ }
323
+ }
324
+ const awaiting = (m) => m.confirmation?.status === 'awaiting_confirmation';
325
+ function handle(e) {
326
+ emit('event', e);
327
+ switch (e.type) {
328
+ case 'message.created':
329
+ if (e.message.kind === 'ai')
330
+ deltas.delete(e.conversationId);
331
+ emit('message', e.message);
332
+ if (awaiting(e.message))
333
+ emit('confirmation', { conversationId: e.conversationId, message: e.message });
334
+ break;
335
+ case 'message.updated':
336
+ emit('message.updated', e.message);
337
+ break;
338
+ case 'conversation.updated':
339
+ emit('conversation', e.conversation);
340
+ break;
341
+ case 'typing':
342
+ emit('typing', { conversationId: e.conversationId, who: e.who, name: e.name, on: e.on });
343
+ break;
344
+ case 'ai.delta': {
345
+ const text = (e.reset ? '' : (deltas.get(e.conversationId) ?? '')) + e.text;
346
+ deltas.set(e.conversationId, text);
347
+ emit('delta', { conversationId: e.conversationId, text });
348
+ break;
349
+ }
350
+ case 'ai.step':
351
+ emit('step', { conversationId: e.conversationId, title: e.title, status: e.status });
352
+ break;
353
+ case 'ai.action':
354
+ emit('action', { conversationId: e.conversationId, name: e.name, args: e.args ?? {} });
355
+ break;
356
+ case 'ai.token_request':
357
+ void askForToken(true);
358
+ break;
359
+ }
360
+ }
361
+ // ---------------------------------------------------------------------------------------------
362
+ // The chat
363
+ // ---------------------------------------------------------------------------------------------
364
+ const enc = encodeURIComponent;
365
+ const conversationOf = (id) => {
366
+ const c = id ?? current;
367
+ if (!c)
368
+ throw new ChatError(0, 'no_conversation', 'No chat is open: send a message first, or open() one.');
369
+ return c;
370
+ };
371
+ return {
372
+ /** Open (or resume) the session now, and read its events. Every other call opens the session itself when needed. */
373
+ async start() {
374
+ const s = await ready();
375
+ if (options.stream !== false && !streamCtl)
376
+ startStream(null);
377
+ return s;
378
+ },
379
+ /** Sign the user in (their signed id), with their tool token if your product is connected. Call again for another user. */
380
+ async identify(input) {
381
+ if (input?.userId === undefined || input.userId === null || input.userId === '' || !input.userHash)
382
+ throw new ChatError(0, 'bad_request', 'identify() needs userId and userHash.');
383
+ const id = String(input.userId);
384
+ if (user && user.id !== id)
385
+ current = null;
386
+ user = { id, hash: input.userHash };
387
+ if (opening)
388
+ await opening.catch(() => undefined);
389
+ const s = await openSession({
390
+ user: { id, hash: input.userHash, ...(input.emailHash ? { emailHash: input.emailHash } : {}), ...(input.name ? { name: input.name } : {}), ...(input.email ? { email: input.email } : {}), ...(input.phone ? { phone: input.phone } : {}), ...(input.attrs ? { attrs: input.attrs } : {}) },
391
+ ...(input.toolToken ? { toolToken: input.toolToken, ...(input.toolTokenExpiresAt !== undefined ? { toolTokenExpiresAt: input.toolTokenExpiresAt } : {}) } : {}),
392
+ });
393
+ if (s.toolTokenStored)
394
+ scheduleToken(input.toolTokenExpiresAt);
395
+ return s;
396
+ },
397
+ /** The user signed out of your product: the session ends, its token is forgotten, the stream closes. */
398
+ async signOut() {
399
+ const s = session;
400
+ stopStream();
401
+ if (tokenTimer)
402
+ clearTimeout(tokenTimer);
403
+ tokenTimer = null;
404
+ if (s)
405
+ await request('DELETE', '/sessions/current', undefined, { retry401: false }).catch((e) => (e instanceof ChatError && e.status === 401 ? undefined : Promise.reject(e)));
406
+ forget();
407
+ user = null;
408
+ current = null;
409
+ deltas.clear();
410
+ setConnection('closed');
411
+ },
412
+ /** A fresh tool token for the AI's actions in your product (the user's own). Usually `onTokenRequest` does this. */
413
+ setToolToken,
414
+ /** Called when the AI needs a fresh tool token, and before the current one expires. Return `{ toolToken, toolTokenExpiresAt }` or the token alone. */
415
+ onTokenRequest(fn) {
416
+ tokenHandler = fn;
417
+ scheduleToken(tokenExpiresAt);
418
+ },
419
+ /** Where the user is in your product (a hint for the AI, never trusted). `null` clears it. */
420
+ async context(value) {
421
+ if (!session) {
422
+ pendingHost.context = value;
423
+ return;
424
+ }
425
+ await request('PUT', '/sessions/current/context', { context: value });
426
+ },
427
+ /** Page actions the AI may trigger; they arrive at `on('action')`. */
428
+ async clientTools(tools) {
429
+ if (!session) {
430
+ pendingHost.clientTools = tools;
431
+ return;
432
+ }
433
+ await request('PUT', '/sessions/current/context', { clientTools: tools });
434
+ },
435
+ /** The user's most recent chats, newest first. */
436
+ async conversations() {
437
+ return (await request('GET', '/conversations')).data;
438
+ },
439
+ /** Load a chat and make it the one `send()` writes to. */
440
+ async open(conversationId) {
441
+ const r = await request('GET', `/conversations/${enc(conversationId)}`);
442
+ current = r.conversation.id;
443
+ deltas.delete(current);
444
+ return r;
445
+ },
446
+ /** The next `send()` starts a new chat. */
447
+ newConversation() {
448
+ current = null;
449
+ },
450
+ /** The chat `send()` writes to, or null before the first message. */
451
+ get conversationId() {
452
+ return current;
453
+ },
454
+ get session() {
455
+ return session;
456
+ },
457
+ get connection() {
458
+ return connection;
459
+ },
460
+ /**
461
+ * Send a message: to the open chat, or a new one. A lost answer is retried with the same id, so the message is
462
+ * never sent twice. The answer arrives as events (`delta`, `step`, then `message`).
463
+ */
464
+ async send(text, opts = {}) {
465
+ const id = opts.conversationId ?? current;
466
+ const clientMessageId = opts.clientMessageId ?? newId();
467
+ if (id) {
468
+ const r = await retrying(() => request('POST', `/conversations/${enc(id)}/messages`, { text, clientMessageId }));
469
+ current = r.conversation.id;
470
+ return r;
471
+ }
472
+ const r = await retrying(() => request('POST', '/conversations', { text, clientMessageId }));
473
+ current = r.conversation.id;
474
+ const message = r.messages.find((m) => m.kind === 'customer') ?? r.messages[r.messages.length - 1];
475
+ return { conversation: r.conversation, message, newConversation: true };
476
+ },
477
+ /** Yes or No for the change the AI asked about. A second answer does nothing. */
478
+ async confirm(yes, conversationId) {
479
+ await request('POST', `/conversations/${enc(conversationOf(conversationId))}/confirmation`, { confirm: !!yes });
480
+ },
481
+ /** Hand the chat to a person on the team. */
482
+ async askForPerson(conversationId) {
483
+ return request('POST', `/conversations/${enc(conversationOf(conversationId))}/human`, {});
484
+ },
485
+ /** Where replies go when the user leaves; a handover waiting for an email (`awaitingEmail`) goes ahead. */
486
+ async setEmail(email, conversationId) {
487
+ return (await request('POST', `/conversations/${enc(conversationOf(conversationId))}/email`, { email })).conversation;
488
+ },
489
+ async end(conversationId) {
490
+ return (await request('POST', `/conversations/${enc(conversationOf(conversationId))}/end`, {})).conversation;
491
+ },
492
+ async rate(label, comment, conversationId) {
493
+ return (await request('POST', `/conversations/${enc(conversationOf(conversationId))}/rating`, { label, ...(comment ? { comment } : {}) })).conversation;
494
+ },
495
+ /** The user has the chat open on its latest replies (the team sees them as read). */
496
+ async markRead(conversationId) {
497
+ await request('POST', `/conversations/${enc(conversationOf(conversationId))}/read`, {});
498
+ },
499
+ /** Helpful or not, on an answer from the AI. */
500
+ async feedback(messageId, helpful) {
501
+ await request('POST', `/messages/${enc(messageId)}/feedback`, { helpful: !!helpful });
502
+ },
503
+ /** Listen to an event; returns the function that stops listening. */
504
+ on(type, fn) {
505
+ let set = listeners.get(type);
506
+ if (!set)
507
+ listeners.set(type, (set = new Set()));
508
+ set.add(fn);
509
+ return () => void set.delete(fn);
510
+ },
511
+ /** Stop reading events and the token timer. The session stays: `start()` reads events again. */
512
+ close() {
513
+ stopStream();
514
+ if (tokenTimer)
515
+ clearTimeout(tokenTimer);
516
+ tokenTimer = null;
517
+ setConnection('closed');
518
+ },
519
+ };
520
+ }
@@ -0,0 +1,8 @@
1
+ /** A Chat API call that failed. `status` 0: no answer (no connection) or refused before sending. */
2
+ export declare class ChatError extends Error {
3
+ status: number;
4
+ code: string;
5
+ fields?: Record<string, string> | undefined;
6
+ cause?: unknown | undefined;
7
+ constructor(status: number, code: string, message: string, fields?: Record<string, string> | undefined, cause?: unknown | undefined);
8
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,11 @@
1
+ /** A Chat API call that failed. `status` 0: no answer (no connection) or refused before sending. */
2
+ export class ChatError extends Error {
3
+ constructor(status, code, message, fields, cause) {
4
+ super(message);
5
+ this.status = status;
6
+ this.code = code;
7
+ this.fields = fields;
8
+ this.cause = cause;
9
+ this.name = 'ChatError';
10
+ }
11
+ }
@@ -0,0 +1,4 @@
1
+ export { createChat, DEFAULT_API_URL } from './chat.js';
2
+ export type { Chat, ChatEventMap, ChatIdentity, ChatOptions, ChatStorage, ClientTool, ConnectionState, SendResult, TokenHandler, ToolTokenAnswer } from './chat.js';
3
+ export { ChatError } from './errors.js';
4
+ export type * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // @aliendesk/chat-sdk: build your own chat on Alien Desk. `createChat({ key })`, then `send()` and `on('message')`.
2
+ // The same module is `sdk.js` on the widget's host, as `window.AlienDeskChat`.
3
+ export { createChat, DEFAULT_API_URL } from './chat.js';
4
+ export { ChatError } from './errors.js';
package/dist/sse.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Reads `body` until it ends or `signal` aborts. `data` is parsed as JSON; an event whose data isn't JSON is skipped. */
2
+ export declare function readEvents(body: ReadableStream<Uint8Array>, onEvent: (type: string, data: unknown) => void, signal?: AbortSignal): Promise<void>;
package/dist/sse.js ADDED
@@ -0,0 +1,59 @@
1
+ // Server-Sent Events read from a fetch() body, so the ticket can go in a header (EventSource can't send one) and the
2
+ // same code runs in browsers and Node. Follows the format's rules: `event:` and `data:` fields, `:` comments,
3
+ // a blank line ends an event, CRLF or LF line ends.
4
+ /** Reads `body` until it ends or `signal` aborts. `data` is parsed as JSON; an event whose data isn't JSON is skipped. */
5
+ export async function readEvents(body, onEvent, signal) {
6
+ const reader = body.getReader();
7
+ const decoder = new TextDecoder();
8
+ const stop = () => void reader.cancel().catch(() => undefined);
9
+ signal?.addEventListener('abort', stop, { once: true });
10
+ let buffer = '';
11
+ let event = '';
12
+ let data = [];
13
+ const line = (text) => {
14
+ if (text === '') {
15
+ if (data.length) {
16
+ let parsed;
17
+ let ok = true;
18
+ try {
19
+ parsed = JSON.parse(data.join('\n'));
20
+ }
21
+ catch {
22
+ ok = false;
23
+ }
24
+ if (ok)
25
+ onEvent(event || 'message', parsed);
26
+ }
27
+ event = '';
28
+ data = [];
29
+ return;
30
+ }
31
+ if (text.startsWith(':'))
32
+ return;
33
+ const colon = text.indexOf(':');
34
+ const field = colon < 0 ? text : text.slice(0, colon);
35
+ let value = colon < 0 ? '' : text.slice(colon + 1);
36
+ if (value.startsWith(' '))
37
+ value = value.slice(1);
38
+ if (field === 'event')
39
+ event = value;
40
+ else if (field === 'data')
41
+ data.push(value);
42
+ };
43
+ try {
44
+ for (;;) {
45
+ const { value, done } = await reader.read();
46
+ if (done)
47
+ break;
48
+ buffer += decoder.decode(value, { stream: true });
49
+ let end;
50
+ while ((end = buffer.indexOf('\n')) >= 0) {
51
+ line(buffer.slice(0, end).replace(/\r$/, ''));
52
+ buffer = buffer.slice(end + 1);
53
+ }
54
+ }
55
+ }
56
+ finally {
57
+ signal?.removeEventListener('abort', stop);
58
+ }
59
+ }
@@ -0,0 +1,10 @@
1
+ /** Ask for the next token this long before the current one expires. */
2
+ export declare const TOKEN_REFRESH_EARLY_MS = 60000;
3
+ /** The timer never asks sooner than this after a token was stored (a short-lived or already expired token would otherwise be asked for every few seconds). */
4
+ export declare const TOKEN_REFRESH_MIN_MS = 60000;
5
+ /** When the server asks for a token (`ai.token_request`), the page is asked at most this often. */
6
+ export declare const TOKEN_ASK_MIN_MS = 5000;
7
+ /** `toolTokenExpiresAt` as the page gives it (an ISO date, or Unix seconds or milliseconds), in milliseconds. */
8
+ export declare function expiryMs(v: unknown): number | null;
9
+ /** How long to wait before asking for the next token. Null: the expiry is not known, so no timer is set. */
10
+ export declare function refreshDelay(expiresAt: unknown, now: number): number | null;
@@ -0,0 +1,21 @@
1
+ // When to ask the product's page for the user's next tool token. The same rules as the widget
2
+ // (the widget's own tool-token rules); this package can't import from the widget, so they are repeated here.
3
+ /** Ask for the next token this long before the current one expires. */
4
+ export const TOKEN_REFRESH_EARLY_MS = 60000;
5
+ /** The timer never asks sooner than this after a token was stored (a short-lived or already expired token would otherwise be asked for every few seconds). */
6
+ export const TOKEN_REFRESH_MIN_MS = 60000;
7
+ /** When the server asks for a token (`ai.token_request`), the page is asked at most this often. */
8
+ export const TOKEN_ASK_MIN_MS = 5000;
9
+ /** `toolTokenExpiresAt` as the page gives it (an ISO date, or Unix seconds or milliseconds), in milliseconds. */
10
+ export function expiryMs(v) {
11
+ if (v == null || v === '')
12
+ return null;
13
+ const n = typeof v === 'number' ? v : /^\d+(\.\d+)?$/.test(String(v).trim()) ? Number(v) : NaN;
14
+ const t = Number.isFinite(n) ? (n < 1e11 ? n * 1000 : n) : Date.parse(String(v));
15
+ return Number.isFinite(t) ? t : null;
16
+ }
17
+ /** How long to wait before asking for the next token. Null: the expiry is not known, so no timer is set. */
18
+ export function refreshDelay(expiresAt, now) {
19
+ const at = expiryMs(expiresAt);
20
+ return at === null ? null : Math.max(TOKEN_REFRESH_MIN_MS, at - now - TOKEN_REFRESH_EARLY_MS);
21
+ }
@@ -0,0 +1,166 @@
1
+ export type ConversationStatus = 'open' | 'pending' | 'solved' | 'closed';
2
+ /** `ai`: the AI agent is answering. `queued`: waiting for a person. `assigned`: a person has it. */
3
+ export type Stage = 'ai' | 'queued' | 'assigned';
4
+ export type AuthorType = 'contact' | 'membership' | 'ai' | 'system';
5
+ /** `unknown`: a change was sent to the product and no answer came back; check before trying again. */
6
+ export type ToolCallStatus = 'done' | 'failed' | 'unknown' | 'awaiting_confirmation' | 'declined' | 'expired';
7
+ export interface ChatConversation {
8
+ id: string;
9
+ /** The ticket number the team sees. */
10
+ number: number;
11
+ subject: string;
12
+ status: ConversationStatus;
13
+ stage: Stage;
14
+ /** The person handling it (first name), once one is. */
15
+ assignee: {
16
+ name: string;
17
+ } | null;
18
+ /** Start of the latest message. */
19
+ preview: string;
20
+ /** Replies the user has not read yet. */
21
+ unread: number;
22
+ /** The handover to a person waits for the user's email: send it with `setEmail()`. */
23
+ awaitingEmail: boolean;
24
+ /** The user may rate the chat now. */
25
+ ratingRequested: boolean;
26
+ csat: {
27
+ label: 'good' | 'poor' | null;
28
+ submittedAt: string | null;
29
+ } | null;
30
+ lastMessageAt: string | null;
31
+ createdAt: string | null;
32
+ }
33
+ /** A step the AI took in the product for this answer ("List campaigns"). Titles and outcome only. */
34
+ export interface ChatStep {
35
+ title: string;
36
+ status: ToolCallStatus;
37
+ }
38
+ /** A change in the product the user is asked to confirm with `confirm()`. */
39
+ export interface ChatConfirmation {
40
+ status: ToolCallStatus;
41
+ /** What will be done ("Pause campaign"). Null for an action without a card: the message text asks. */
42
+ title: string | null;
43
+ /** The user's own request, as label and value. */
44
+ fields: {
45
+ label: string;
46
+ value: string;
47
+ }[];
48
+ }
49
+ export interface ChatMessage {
50
+ id: string;
51
+ conversationId: string;
52
+ /** `customer`: the user. `ai`: the AI agent. `agent`: a person on the team. `event`: something happened (handed over, assigned, solved). */
53
+ kind: 'customer' | 'ai' | 'agent' | 'event';
54
+ author: {
55
+ type: AuthorType;
56
+ name: string | null;
57
+ };
58
+ text: string;
59
+ attachments: {
60
+ id: string;
61
+ name: string;
62
+ mime: string;
63
+ size: number;
64
+ }[];
65
+ /** Help articles or pages the answer came from. */
66
+ sources: {
67
+ title: string;
68
+ url: string | null;
69
+ articleId: string | null;
70
+ }[];
71
+ steps: ChatStep[];
72
+ confirmation: ChatConfirmation | null;
73
+ /** Short replies the user might send next. */
74
+ suggestions: string[];
75
+ /** The AI suggests talking to a person. */
76
+ offerHuman: boolean;
77
+ event: {
78
+ type: string;
79
+ data: {
80
+ name: string | null;
81
+ from: string | null;
82
+ to: string | null;
83
+ reason: string | null;
84
+ by: string | null;
85
+ } | null;
86
+ } | null;
87
+ feedback: {
88
+ helpful: boolean;
89
+ } | null;
90
+ createdAt: string | null;
91
+ }
92
+ /** Where to read the session's live events. The ticket lasts an hour; the SDK gets the next one itself. */
93
+ export interface ChatStream {
94
+ url: string;
95
+ ticket: string;
96
+ expiresAt: string;
97
+ }
98
+ /** One event of the stream, as the server sends it. */
99
+ export type ChatEvent = {
100
+ type: 'message.created';
101
+ conversationId: string;
102
+ message: ChatMessage;
103
+ } | {
104
+ type: 'message.updated';
105
+ conversationId: string;
106
+ message: ChatMessage;
107
+ } | {
108
+ type: 'conversation.updated';
109
+ conversationId: string;
110
+ conversation: ChatConversation;
111
+ } | {
112
+ type: 'typing';
113
+ conversationId: string;
114
+ who: 'ai' | 'agent';
115
+ name: string | null;
116
+ on: boolean;
117
+ } | {
118
+ type: 'ai.delta';
119
+ conversationId: string;
120
+ text: string;
121
+ reset: boolean;
122
+ } | {
123
+ type: 'ai.step';
124
+ conversationId: string;
125
+ title: string;
126
+ status: 'running' | 'done' | 'failed';
127
+ } | {
128
+ type: 'ai.action';
129
+ conversationId: string;
130
+ name: string;
131
+ args: Record<string, unknown>;
132
+ } | {
133
+ type: 'ai.token_request';
134
+ conversationId: string;
135
+ };
136
+ export type ChatStreamEvent = {
137
+ type: 'ready';
138
+ expiresAt: string;
139
+ } | {
140
+ type: 'expired';
141
+ } | ChatEvent;
142
+ export interface ChatSession {
143
+ sessionToken: string;
144
+ stream: ChatStream;
145
+ contact: {
146
+ name: string | null;
147
+ email: string | null;
148
+ verified: boolean;
149
+ };
150
+ /** The user's most recent chats, newest first. */
151
+ conversations: ChatConversation[];
152
+ brand: {
153
+ name: string;
154
+ logoUrl: string | null;
155
+ };
156
+ assistant: {
157
+ name: string;
158
+ avatarUrl: string | null;
159
+ };
160
+ team: {
161
+ status: 'online' | 'away' | 'offline';
162
+ hours: string | null;
163
+ };
164
+ /** Set when a tool token was sent: whether it is now in use. */
165
+ toolTokenStored?: boolean;
166
+ }
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ // What the Chat API answers and streams. A copy of the server's own types (`@aliendesk/shared/chat-api`), so this
2
+ // package stands alone; `types.check.ts` fails the typecheck when the two drift apart.
3
+ export {};
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@aliendesk/chat-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Build your own chat on Alien Desk: the Chat API from a browser or Node, with live events.",
5
+ "license": "MIT",
6
+ "homepage": "https://docs.aliendesk.io/guides/build-your-own-chat",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/A2Dweb/aliendesk-chat-sdk.git"
10
+ },
11
+ "bugs": "https://github.com/A2Dweb/aliendesk-chat-sdk/issues",
12
+ "keywords": [
13
+ "aliendesk",
14
+ "chat",
15
+ "support",
16
+ "ai",
17
+ "sdk",
18
+ "server-sent-events"
19
+ ],
20
+ "type": "module",
21
+ "sideEffects": false,
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.build.json",
39
+ "typecheck": "tsc -p tsconfig.json",
40
+ "test": "node --import tsx --test \"src/**/*.test.ts\"",
41
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
42
+ },
43
+ "devDependencies": {
44
+ "tsx": "4.23.15",
45
+ "@types/node": "26.6.6",
46
+ "typescript": "5.9.3"
47
+ }
48
+ }