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