priori-chat-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,947 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // src/client/core/params.ts
6
+ var extraPrefixesMap = {
7
+ $body_: "body",
8
+ $headers_: "headers",
9
+ $path_: "path",
10
+ $query_: "query"
11
+ };
12
+ var extraPrefixes = Object.entries(extraPrefixesMap);
13
+
14
+ // src/client/client/client.ts
15
+ import axios from "axios";
16
+
17
+ // src/client/core/auth.ts
18
+ var getAuthToken = async (auth, callback) => {
19
+ const token = typeof callback === "function" ? await callback(auth) : callback;
20
+ if (!token) {
21
+ return;
22
+ }
23
+ if (auth.scheme === "bearer") {
24
+ return `Bearer ${token}`;
25
+ }
26
+ if (auth.scheme === "basic") {
27
+ return `Basic ${btoa(token)}`;
28
+ }
29
+ return token;
30
+ };
31
+
32
+ // src/client/core/pathSerializer.ts
33
+ var separatorArrayExplode = (style) => {
34
+ switch (style) {
35
+ case "label":
36
+ return ".";
37
+ case "matrix":
38
+ return ";";
39
+ case "simple":
40
+ return ",";
41
+ default:
42
+ return "&";
43
+ }
44
+ };
45
+ var separatorArrayNoExplode = (style) => {
46
+ switch (style) {
47
+ case "form":
48
+ return ",";
49
+ case "pipeDelimited":
50
+ return "|";
51
+ case "spaceDelimited":
52
+ return "%20";
53
+ default:
54
+ return ",";
55
+ }
56
+ };
57
+ var separatorObjectExplode = (style) => {
58
+ switch (style) {
59
+ case "label":
60
+ return ".";
61
+ case "matrix":
62
+ return ";";
63
+ case "simple":
64
+ return ",";
65
+ default:
66
+ return "&";
67
+ }
68
+ };
69
+ var serializeArrayParam = ({
70
+ allowReserved,
71
+ explode,
72
+ name,
73
+ style,
74
+ value
75
+ }) => {
76
+ if (!explode) {
77
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
78
+ switch (style) {
79
+ case "label":
80
+ return `.${joinedValues2}`;
81
+ case "matrix":
82
+ return `;${name}=${joinedValues2}`;
83
+ case "simple":
84
+ return joinedValues2;
85
+ default:
86
+ return `${name}=${joinedValues2}`;
87
+ }
88
+ }
89
+ const separator = separatorArrayExplode(style);
90
+ const joinedValues = value.map((v) => {
91
+ if (style === "label" || style === "simple") {
92
+ return allowReserved ? v : encodeURIComponent(v);
93
+ }
94
+ return serializePrimitiveParam({
95
+ allowReserved,
96
+ name,
97
+ value: v
98
+ });
99
+ }).join(separator);
100
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
101
+ };
102
+ var serializePrimitiveParam = ({
103
+ allowReserved,
104
+ name,
105
+ value
106
+ }) => {
107
+ if (value === void 0 || value === null) {
108
+ return "";
109
+ }
110
+ if (typeof value === "object") {
111
+ throw new Error(
112
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
113
+ );
114
+ }
115
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
116
+ };
117
+ var serializeObjectParam = ({
118
+ allowReserved,
119
+ explode,
120
+ name,
121
+ style,
122
+ value,
123
+ valueOnly
124
+ }) => {
125
+ if (value instanceof Date) {
126
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
127
+ }
128
+ if (style !== "deepObject" && !explode) {
129
+ let values = [];
130
+ Object.entries(value).forEach(([key, v]) => {
131
+ values = [
132
+ ...values,
133
+ key,
134
+ allowReserved ? v : encodeURIComponent(v)
135
+ ];
136
+ });
137
+ const joinedValues2 = values.join(",");
138
+ switch (style) {
139
+ case "form":
140
+ return `${name}=${joinedValues2}`;
141
+ case "label":
142
+ return `.${joinedValues2}`;
143
+ case "matrix":
144
+ return `;${name}=${joinedValues2}`;
145
+ default:
146
+ return joinedValues2;
147
+ }
148
+ }
149
+ const separator = separatorObjectExplode(style);
150
+ const joinedValues = Object.entries(value).map(
151
+ ([key, v]) => serializePrimitiveParam({
152
+ allowReserved,
153
+ name: style === "deepObject" ? `${name}[${key}]` : key,
154
+ value: v
155
+ })
156
+ ).join(separator);
157
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
158
+ };
159
+
160
+ // src/client/client/utils.ts
161
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
162
+ var defaultPathSerializer = ({ path, url: _url }) => {
163
+ let url = _url;
164
+ const matches = _url.match(PATH_PARAM_RE);
165
+ if (matches) {
166
+ for (const match of matches) {
167
+ let explode = false;
168
+ let name = match.substring(1, match.length - 1);
169
+ let style = "simple";
170
+ if (name.endsWith("*")) {
171
+ explode = true;
172
+ name = name.substring(0, name.length - 1);
173
+ }
174
+ if (name.startsWith(".")) {
175
+ name = name.substring(1);
176
+ style = "label";
177
+ } else if (name.startsWith(";")) {
178
+ name = name.substring(1);
179
+ style = "matrix";
180
+ }
181
+ const value = path[name];
182
+ if (value === void 0 || value === null) {
183
+ continue;
184
+ }
185
+ if (Array.isArray(value)) {
186
+ url = url.replace(
187
+ match,
188
+ serializeArrayParam({ explode, name, style, value })
189
+ );
190
+ continue;
191
+ }
192
+ if (typeof value === "object") {
193
+ url = url.replace(
194
+ match,
195
+ serializeObjectParam({
196
+ explode,
197
+ name,
198
+ style,
199
+ value,
200
+ valueOnly: true
201
+ })
202
+ );
203
+ continue;
204
+ }
205
+ if (style === "matrix") {
206
+ url = url.replace(
207
+ match,
208
+ `;${serializePrimitiveParam({
209
+ name,
210
+ value
211
+ })}`
212
+ );
213
+ continue;
214
+ }
215
+ const replaceValue = encodeURIComponent(
216
+ style === "label" ? `.${value}` : value
217
+ );
218
+ url = url.replace(match, replaceValue);
219
+ }
220
+ }
221
+ return url;
222
+ };
223
+ var createQuerySerializer = ({
224
+ allowReserved,
225
+ array,
226
+ object
227
+ } = {}) => {
228
+ const querySerializer = (queryParams) => {
229
+ const search = [];
230
+ if (queryParams && typeof queryParams === "object") {
231
+ for (const name in queryParams) {
232
+ const value = queryParams[name];
233
+ if (value === void 0 || value === null) {
234
+ continue;
235
+ }
236
+ if (Array.isArray(value)) {
237
+ const serializedArray = serializeArrayParam({
238
+ allowReserved,
239
+ explode: true,
240
+ name,
241
+ style: "form",
242
+ value,
243
+ ...array
244
+ });
245
+ if (serializedArray) search.push(serializedArray);
246
+ } else if (typeof value === "object") {
247
+ const serializedObject = serializeObjectParam({
248
+ allowReserved,
249
+ explode: true,
250
+ name,
251
+ style: "deepObject",
252
+ value,
253
+ ...object
254
+ });
255
+ if (serializedObject) search.push(serializedObject);
256
+ } else {
257
+ const serializedPrimitive = serializePrimitiveParam({
258
+ allowReserved,
259
+ name,
260
+ value
261
+ });
262
+ if (serializedPrimitive) search.push(serializedPrimitive);
263
+ }
264
+ }
265
+ }
266
+ return search.join("&");
267
+ };
268
+ return querySerializer;
269
+ };
270
+ var setAuthParams = async ({
271
+ security,
272
+ ...options
273
+ }) => {
274
+ for (const auth of security) {
275
+ const token = await getAuthToken(auth, options.auth);
276
+ if (!token) {
277
+ continue;
278
+ }
279
+ const name = auth.name ?? "Authorization";
280
+ switch (auth.in) {
281
+ case "query":
282
+ if (!options.query) {
283
+ options.query = {};
284
+ }
285
+ options.query[name] = token;
286
+ break;
287
+ case "cookie": {
288
+ const value = `${name}=${token}`;
289
+ if ("Cookie" in options.headers && options.headers["Cookie"]) {
290
+ options.headers["Cookie"] = `${options.headers["Cookie"]}; ${value}`;
291
+ } else {
292
+ options.headers["Cookie"] = value;
293
+ }
294
+ break;
295
+ }
296
+ case "header":
297
+ default:
298
+ options.headers[name] = token;
299
+ break;
300
+ }
301
+ return;
302
+ }
303
+ };
304
+ var buildUrl = (options) => {
305
+ const url = getUrl({
306
+ path: options.path,
307
+ // let `paramsSerializer()` handle query params if it exists
308
+ query: !options.paramsSerializer ? options.query : void 0,
309
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
310
+ url: options.url
311
+ });
312
+ return url;
313
+ };
314
+ var getUrl = ({
315
+ path,
316
+ query,
317
+ querySerializer,
318
+ url: _url
319
+ }) => {
320
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
321
+ let url = pathUrl;
322
+ if (path) {
323
+ url = defaultPathSerializer({ path, url });
324
+ }
325
+ let search = query ? querySerializer(query) : "";
326
+ if (search.startsWith("?")) {
327
+ search = search.substring(1);
328
+ }
329
+ if (search) {
330
+ url += `?${search}`;
331
+ }
332
+ return url;
333
+ };
334
+ var mergeConfigs = (a, b) => {
335
+ const config = { ...a, ...b };
336
+ config.headers = mergeHeaders(a.headers, b.headers);
337
+ return config;
338
+ };
339
+ var axiosHeadersKeywords = [
340
+ "common",
341
+ "delete",
342
+ "get",
343
+ "head",
344
+ "patch",
345
+ "post",
346
+ "put"
347
+ ];
348
+ var mergeHeaders = (...headers) => {
349
+ const mergedHeaders = {};
350
+ for (const header of headers) {
351
+ if (!header || typeof header !== "object") {
352
+ continue;
353
+ }
354
+ const iterator = Object.entries(header);
355
+ for (const [key, value] of iterator) {
356
+ if (axiosHeadersKeywords.includes(
357
+ key
358
+ ) && typeof value === "object") {
359
+ mergedHeaders[key] = {
360
+ ...mergedHeaders[key],
361
+ ...value
362
+ };
363
+ } else if (value === null) {
364
+ delete mergedHeaders[key];
365
+ } else if (Array.isArray(value)) {
366
+ for (const v of value) {
367
+ mergedHeaders[key] = [...mergedHeaders[key] ?? [], v];
368
+ }
369
+ } else if (value !== void 0) {
370
+ mergedHeaders[key] = typeof value === "object" ? JSON.stringify(value) : value;
371
+ }
372
+ }
373
+ }
374
+ return mergedHeaders;
375
+ };
376
+ var createConfig = (override = {}) => ({
377
+ ...override
378
+ });
379
+
380
+ // src/client/client/client.ts
381
+ var createClient = (config = {}) => {
382
+ let _config = mergeConfigs(createConfig(), config);
383
+ const { auth, ...configWithoutAuth } = _config;
384
+ const instance = axios.create(configWithoutAuth);
385
+ const getConfig = () => ({ ..._config });
386
+ const setConfig = (config2) => {
387
+ _config = mergeConfigs(_config, config2);
388
+ instance.defaults = {
389
+ ...instance.defaults,
390
+ ..._config,
391
+ // @ts-expect-error
392
+ headers: mergeHeaders(instance.defaults.headers, _config.headers)
393
+ };
394
+ return getConfig();
395
+ };
396
+ const request = async (options) => {
397
+ const opts = {
398
+ ..._config,
399
+ ...options,
400
+ axios: options.axios ?? _config.axios ?? instance,
401
+ headers: mergeHeaders(_config.headers, options.headers)
402
+ };
403
+ if (opts.security) {
404
+ await setAuthParams({
405
+ ...opts,
406
+ security: opts.security
407
+ });
408
+ }
409
+ if (opts.requestValidator) {
410
+ await opts.requestValidator(opts);
411
+ }
412
+ if (opts.body && opts.bodySerializer) {
413
+ opts.body = opts.bodySerializer(opts.body);
414
+ }
415
+ const url = buildUrl(opts);
416
+ try {
417
+ const _axios = opts.axios;
418
+ const { auth: auth2, ...optsWithoutAuth } = opts;
419
+ const response = await _axios({
420
+ ...optsWithoutAuth,
421
+ baseURL: opts.baseURL,
422
+ data: opts.body,
423
+ headers: opts.headers,
424
+ // let `paramsSerializer()` handle query params if it exists
425
+ params: opts.paramsSerializer ? opts.query : void 0,
426
+ url
427
+ });
428
+ let { data } = response;
429
+ if (opts.responseType === "json") {
430
+ if (opts.responseValidator) {
431
+ await opts.responseValidator(data);
432
+ }
433
+ if (opts.responseTransformer) {
434
+ data = await opts.responseTransformer(data);
435
+ }
436
+ }
437
+ return {
438
+ ...response,
439
+ data: data ?? {}
440
+ };
441
+ } catch (error) {
442
+ const e = error;
443
+ if (opts.throwOnError) {
444
+ throw e;
445
+ }
446
+ e.error = e.response?.data ?? {};
447
+ return e;
448
+ }
449
+ };
450
+ return {
451
+ buildUrl,
452
+ delete: (options) => request({ ...options, method: "DELETE" }),
453
+ get: (options) => request({ ...options, method: "GET" }),
454
+ getConfig,
455
+ head: (options) => request({ ...options, method: "HEAD" }),
456
+ instance,
457
+ options: (options) => request({ ...options, method: "OPTIONS" }),
458
+ patch: (options) => request({ ...options, method: "PATCH" }),
459
+ post: (options) => request({ ...options, method: "POST" }),
460
+ put: (options) => request({ ...options, method: "PUT" }),
461
+ request,
462
+ setConfig
463
+ };
464
+ };
465
+
466
+ // src/client/client.gen.ts
467
+ var client = createClient(
468
+ createConfig({
469
+ throwOnError: true
470
+ })
471
+ );
472
+
473
+ // src/client/sdk.gen.ts
474
+ var listConversations = (options) => {
475
+ return (options?.client ?? client).get({
476
+ responseType: "json",
477
+ url: "/api/conversations",
478
+ ...options
479
+ });
480
+ };
481
+ var createConversation = (options) => {
482
+ return (options.client ?? client).post({
483
+ responseType: "json",
484
+ url: "/api/conversations",
485
+ ...options,
486
+ headers: {
487
+ "Content-Type": "application/json",
488
+ ...options.headers
489
+ }
490
+ });
491
+ };
492
+ var getConversation = (options) => {
493
+ return (options.client ?? client).get({
494
+ responseType: "json",
495
+ url: "/api/conversations/{id}",
496
+ ...options
497
+ });
498
+ };
499
+ var sendMessage = (options) => {
500
+ return (options.client ?? client).post({
501
+ url: "/api/conversations/{id}/messages",
502
+ ...options,
503
+ headers: {
504
+ "Content-Type": "application/json",
505
+ ...options.headers
506
+ }
507
+ });
508
+ };
509
+
510
+ // src/methods/conversations.ts
511
+ async function createConversationImpl(options) {
512
+ const result = await createConversation({
513
+ body: {
514
+ bot_id: options.bot_id,
515
+ user_id: options.user_id,
516
+ create_user_if_not_exists: options.create_user_if_not_exists,
517
+ with_messages: options.with_messages?.map((msg) => ({
518
+ ...msg,
519
+ attached_media: msg.attached_media ? { content_id: "", url: msg.attached_media.url } : void 0
520
+ }))
521
+ }
522
+ });
523
+ return result.data;
524
+ }
525
+ async function listConversationsImpl(options) {
526
+ const result = await listConversations({
527
+ query: options ? {
528
+ bot_id: options.bot_id,
529
+ user_id: options.user_id
530
+ } : void 0
531
+ });
532
+ return result.data;
533
+ }
534
+ async function getConversationImpl(options) {
535
+ const result = await getConversation({
536
+ path: {
537
+ id: options.id
538
+ }
539
+ });
540
+ return result.data;
541
+ }
542
+
543
+ // src/conversation.ts
544
+ var Conversation = class _Conversation {
545
+ constructor(client2, options, callbacks = {}) {
546
+ __publicField(this, "client");
547
+ __publicField(this, "conversationId");
548
+ __publicField(this, "pollingInterval");
549
+ __publicField(this, "pollingTimer");
550
+ __publicField(this, "lastKnownMessageCount", 0);
551
+ __publicField(this, "callbacks", {});
552
+ __publicField(this, "isInitialized", false);
553
+ this.client = client2;
554
+ this.pollingInterval = options.pollingInterval || 500;
555
+ this.callbacks = callbacks;
556
+ }
557
+ /**
558
+ * Creates a new conversation instance and initializes it.
559
+ * @param client - The PrioriChat client instance
560
+ * @param options - Configuration options for the conversation
561
+ * @param callbacks - Event callbacks for handling conversation events
562
+ * @returns Promise resolving to the conversation instance and initial data containing message history
563
+ * @example
564
+ * ```ts
565
+ * const client = new PrioriChat("your-api-key");
566
+ *
567
+ * const { conversation, initialData } = await Conversation.create(
568
+ * client,
569
+ * { user_id: "user-123", bot_id: "12345678-1234-1234-1234-123456789012" },
570
+ * {
571
+ * onNewMessage: (message) => {
572
+ * console.log(`${message.from_bot ? 'Bot' : 'User'}: ${message.text}`);
573
+ * },
574
+ * onError: (error) => {
575
+ * console.error("Error:", error);
576
+ * }
577
+ * }
578
+ * );
579
+ *
580
+ * // Print message history
581
+ * initialData.messages.forEach(msg => {
582
+ * console.log(`${msg.from_bot ? 'Bot' : 'User'}: ${msg.text}`);
583
+ * });
584
+ * ```
585
+ */
586
+ static async create(client2, options, callbacks = {}) {
587
+ const instance = new _Conversation(client2, options, callbacks);
588
+ const initialData = await instance.initialize(options);
589
+ return { conversation: instance, initialData };
590
+ }
591
+ async initialize(options) {
592
+ try {
593
+ if ("conversation_id" in options) {
594
+ this.conversationId = options.conversation_id;
595
+ } else {
596
+ const existingConversations = await this.client.listConversations({
597
+ user_id: options.user_id,
598
+ bot_id: options.bot_id
599
+ });
600
+ if (existingConversations.conversations.length > 0) {
601
+ this.conversationId = existingConversations.conversations[0].id;
602
+ } else {
603
+ const conversation = await this.client.createConversation({
604
+ user_id: options.user_id,
605
+ bot_id: options.bot_id,
606
+ create_user_if_not_exists: true
607
+ });
608
+ this.conversationId = conversation.conversation.id;
609
+ }
610
+ }
611
+ const initialData = await this.client.getConversation({
612
+ id: this.conversationId
613
+ });
614
+ this.lastKnownMessageCount = initialData.messages.length;
615
+ this.isInitialized = true;
616
+ if (this.callbacks.onInitialData) {
617
+ this.callbacks.onInitialData(initialData);
618
+ }
619
+ this.startPolling();
620
+ return initialData;
621
+ } catch (error) {
622
+ if (this.callbacks.onError) {
623
+ this.callbacks.onError(error);
624
+ }
625
+ throw error;
626
+ }
627
+ }
628
+ startPolling() {
629
+ if (this.pollingTimer) {
630
+ clearInterval(this.pollingTimer);
631
+ }
632
+ this.pollingTimer = setInterval(async () => {
633
+ try {
634
+ const data = await this.client.getConversation({
635
+ id: this.conversationId
636
+ });
637
+ if (data.messages.length > this.lastKnownMessageCount) {
638
+ const newMessages = data.messages.slice(this.lastKnownMessageCount);
639
+ this.lastKnownMessageCount = data.messages.length;
640
+ if (this.callbacks.onNewMessage) {
641
+ newMessages.forEach((apiMessage) => {
642
+ const message = {
643
+ id: apiMessage.id || void 0,
644
+ text: apiMessage.text,
645
+ from_bot: apiMessage.from_bot,
646
+ attached_media: apiMessage.attached_media ? { url: apiMessage.attached_media.url } : void 0,
647
+ timestamp: /* @__PURE__ */ new Date()
648
+ };
649
+ this.callbacks.onNewMessage(message);
650
+ });
651
+ }
652
+ }
653
+ } catch (error) {
654
+ if (this.callbacks.onError) {
655
+ this.callbacks.onError(error);
656
+ }
657
+ }
658
+ }, this.pollingInterval);
659
+ }
660
+ /**
661
+ * Sends a message to the conversation
662
+ * @param text - The text content of the message
663
+ * @param attachedMedia - Optional attached media content
664
+ * @returns Promise that resolves when message is sent
665
+ * @example
666
+ * ```ts
667
+ * // Send a simple text message
668
+ * await conversation.sendMessage("Hello, how can you help me?");
669
+ *
670
+ * // Send a message with media attachment
671
+ * await conversation.sendMessage("Here's an image", {
672
+ * url: "https://example.com/image.jpg"
673
+ * });
674
+ *
675
+ * // Continue the conversation by sending more messages
676
+ * // The onNewMessage callback will handle bot responses
677
+ * ```
678
+ */
679
+ async sendMessage(text, attachedMedia) {
680
+ if (!this.isInitialized) {
681
+ throw new Error("Conversation not initialized");
682
+ }
683
+ const message = {
684
+ text,
685
+ from_bot: false,
686
+ attached_media: attachedMedia,
687
+ id: `temp-${Date.now()}`,
688
+ timestamp: /* @__PURE__ */ new Date()
689
+ };
690
+ if (this.callbacks.onNewMessage) {
691
+ this.callbacks.onNewMessage(message);
692
+ }
693
+ try {
694
+ await sendMessage({
695
+ path: {
696
+ id: this.conversationId
697
+ },
698
+ body: {
699
+ message: {
700
+ text,
701
+ from_bot: false,
702
+ attached_media: attachedMedia ? { content_id: "", url: attachedMedia.url } : void 0
703
+ }
704
+ }
705
+ });
706
+ this.lastKnownMessageCount++;
707
+ } catch (error) {
708
+ if (this.callbacks.onError) {
709
+ this.callbacks.onError(error);
710
+ }
711
+ throw error;
712
+ }
713
+ }
714
+ /**
715
+ * Stops polling for new messages and cleans up resources.
716
+ * Call this method when you're done with the conversation to prevent memory leaks.
717
+ * @example
718
+ * ```ts
719
+ * // Always disconnect when done
720
+ * conversation.disconnect();
721
+ *
722
+ * // Or use in React useEffect cleanup
723
+ * useEffect(() => {
724
+ * const setupConversation = async () => {
725
+ * const { conversation } = await client.conversation(...);
726
+ * setConversation(conversation);
727
+ * };
728
+ *
729
+ * setupConversation();
730
+ *
731
+ * return () => {
732
+ * conversation?.disconnect();
733
+ * };
734
+ * }, []);
735
+ * ```
736
+ */
737
+ disconnect() {
738
+ if (this.pollingTimer) {
739
+ clearInterval(this.pollingTimer);
740
+ this.pollingTimer = void 0;
741
+ }
742
+ }
743
+ // /**
744
+ // * Updates the polling interval
745
+ // * @param interval - New polling interval in milliseconds
746
+ // */
747
+ // setPollingInterval(interval: number) {
748
+ // this.pollingInterval = interval;
749
+ // if (this.pollingTimer && this.isInitialized) {
750
+ // this.startPolling();
751
+ // }
752
+ // }
753
+ /**
754
+ * Gets the current conversation ID.
755
+ * @returns The conversation ID string
756
+ * @example
757
+ * ```ts
758
+ * console.log(`Current conversation: ${conversation.id}`);
759
+ * // Output: Current conversation: 87654321-4321-4321-4321-210987654321
760
+ * ```
761
+ */
762
+ get id() {
763
+ return this.conversationId;
764
+ }
765
+ };
766
+
767
+ // src/client.ts
768
+ var ApiError = class extends Error {
769
+ constructor({
770
+ message,
771
+ status,
772
+ method,
773
+ url,
774
+ payload
775
+ }) {
776
+ super(message);
777
+ __publicField(this, "name", "ApiError");
778
+ __publicField(this, "status");
779
+ __publicField(this, "method");
780
+ __publicField(this, "url");
781
+ __publicField(this, "payload");
782
+ this.status = status;
783
+ this.method = method;
784
+ this.url = url;
785
+ this.payload = payload;
786
+ }
787
+ };
788
+ var PrioriChat = class {
789
+ constructor(api_token, baseURL) {
790
+ __publicField(this, "client", client);
791
+ __publicField(this, "apiToken");
792
+ this.apiToken = api_token;
793
+ this.client.setConfig({
794
+ baseURL: baseURL || "https://api.prioros.com/v3/",
795
+ throwOnError: true
796
+ });
797
+ this.setupErrorInterceptor();
798
+ }
799
+ setupErrorInterceptor() {
800
+ this.client.instance.interceptors.response.use(
801
+ (response) => response,
802
+ (error) => {
803
+ const res = error.response;
804
+ const req = res?.config;
805
+ const data = res?.data;
806
+ const status = res?.status;
807
+ const method = req?.method?.toUpperCase();
808
+ const url = req?.url;
809
+ const hasJsonBody = res?.headers?.["content-type"]?.includes("application/json");
810
+ const hasMessageField = data && typeof data === "object" && "message" in data;
811
+ if (hasJsonBody && hasMessageField) {
812
+ throw new ApiError({
813
+ message: `[${status} ${res.statusText}] ${method} ${url} ? ${String(data.message)}`,
814
+ status,
815
+ method,
816
+ url,
817
+ payload: data
818
+ });
819
+ }
820
+ const parts = [];
821
+ if (status) parts.push(`[${status} ${res.statusText}]`);
822
+ if (method && url) parts.push(`${method} ${url}`);
823
+ if (data?.error) parts.push(`? ${String(data.error)}`);
824
+ error.message = parts.join(" ") || error.message;
825
+ error.meta = {
826
+ status,
827
+ method,
828
+ url,
829
+ payload: data,
830
+ response: res
831
+ };
832
+ return Promise.reject(error);
833
+ }
834
+ );
835
+ }
836
+ /**
837
+ * Creates a new conversation between a user and bot
838
+ * @param options - The conversation creation options
839
+ * @param options.bot_id - ID of the bot to associate with this conversation
840
+ * @param options.user_id - ID of the user to associate with this conversation
841
+ * @param options.create_user_if_not_exists - Whether to create the user if they don't exist (defaults to true)
842
+ * @param options.with_messages - Optional list of initial messages for the conversation
843
+ * @returns Promise resolving to the created conversation
844
+ * @example
845
+ * ```ts
846
+ * const client = new PrioriChat("your-api-key");
847
+ *
848
+ * const result = await client.createConversation({
849
+ * bot_id: "12345678-1234-1234-1234-123456789012",
850
+ * user_id: "user-123",
851
+ * create_user_if_not_exists: true
852
+ * });
853
+ *
854
+ * console.log(`Created conversation: ${result.conversation.id}`);
855
+ * ```
856
+ */
857
+ async createConversation(options) {
858
+ return createConversationImpl.call(this, options);
859
+ }
860
+ /**
861
+ * Lists conversations with optional filtering
862
+ * @param options - Optional filtering options
863
+ * @param options.bot_id - Filter conversations by bot ID
864
+ * @param options.user_id - Filter conversations by user ID
865
+ * @returns Promise resolving to list of conversations
866
+ * @example
867
+ * ```ts
868
+ * const client = new PrioriChat("your-api-key");
869
+ *
870
+ * // List all conversations
871
+ * const allConversations = await client.listConversations();
872
+ *
873
+ * // List conversations for a specific user and bot
874
+ * const userConversations = await client.listConversations({
875
+ * user_id: "user-123",
876
+ * bot_id: "12345678-1234-1234-1234-123456789012"
877
+ * });
878
+ * ```
879
+ */
880
+ async listConversations(options) {
881
+ return listConversationsImpl.call(this, options);
882
+ }
883
+ /**
884
+ * Retrieves a specific conversation by ID
885
+ * @param options - The conversation retrieval options
886
+ * @param options.id - The ID of the conversation to retrieve
887
+ * @returns Promise resolving to the conversation details
888
+ * @example
889
+ * ```ts
890
+ * const client = new PrioriChat("your-api-key");
891
+ *
892
+ * const conversation = await client.getConversation({
893
+ * id: "87654321-4321-4321-4321-210987654321"
894
+ * });
895
+ *
896
+ * console.log(`Found ${conversation.messages.length} messages`);
897
+ * ```
898
+ */
899
+ async getConversation(options) {
900
+ return getConversationImpl.call(this, options);
901
+ }
902
+ /**
903
+ * Creates a new Conversation instance for real-time messaging
904
+ * @param options - Conversation initialization options (conversation_id OR user_id + bot_id)
905
+ * @param callbacks - Event callbacks for handling messages and errors
906
+ * @returns Promise resolving to conversation instance and initial data
907
+ * @example
908
+ * ```ts
909
+ * const client = new PrioriChat("your-api-key");
910
+ *
911
+ * const { conversation, initialData } = await client.conversation(
912
+ * { user_id: "user-123", bot_id: "12345678-1234-1234-1234-123456789012" },
913
+ * {
914
+ * onNewMessage: (message) => {
915
+ * if (message.from_bot) {
916
+ * console.log(`Bot: ${message.text}`);
917
+ * }
918
+ * },
919
+ * onError: (error) => {
920
+ * console.error("Conversation error:", error);
921
+ * }
922
+ * }
923
+ * );
924
+ *
925
+ * // Print initial message history
926
+ * console.log(`Loaded ${initialData.messages.length} previous messages`);
927
+ * initialData.messages.forEach(msg => {
928
+ * const sender = msg.from_bot ? "Bot" : "User";
929
+ * console.log(`${sender}: ${msg.text}`);
930
+ * });
931
+ *
932
+ * // Send a message to start/continue the conversation
933
+ * await conversation.sendMessage("Hello!");
934
+ *
935
+ * // Continue the conversation by sending more messages
936
+ * // The onNewMessage callback will handle incoming bot responses
937
+ * ```
938
+ */
939
+ async conversation(options, callbacks) {
940
+ return Conversation.create(this, options, callbacks);
941
+ }
942
+ };
943
+ export {
944
+ ApiError,
945
+ Conversation,
946
+ PrioriChat
947
+ };