@opencx/widget 2.5.1 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/basic.cjs +1 -1
  2. package/dist/basic.cjs.map +1 -1
  3. package/dist/basic.js +1 -1
  4. package/dist/basic.js.map +1 -1
  5. package/dist/core/client/api.d.ts +1 -1
  6. package/dist/core/client/chat.d.ts +37 -2
  7. package/dist/core/client/contact.d.ts +2 -2
  8. package/dist/core/errors/index.d.ts +6 -0
  9. package/dist/core/platform/audio.d.ts +38 -0
  10. package/dist/core/platform/index.d.ts +6 -2
  11. package/dist/core/platform/storage.d.ts +8 -2
  12. package/dist/core/tests/client/integration.test.d.ts +1 -0
  13. package/dist/core/tests/platform/audio.test.d.ts +1 -0
  14. package/dist/core/tests/platform/logger.test.d.ts +1 -0
  15. package/dist/core/tests/platform/storage.test.d.ts +1 -0
  16. package/dist/core/tests/test-utils.d.ts +2 -0
  17. package/dist/core/tests/types/pub-sub.test.d.ts +1 -0
  18. package/dist/core/tests/utils/create-fetch.test.d.ts +1 -0
  19. package/dist/core/types/helpers.d.ts +2 -2
  20. package/dist/core/types/pub-sub.d.ts +1 -0
  21. package/dist/core/types/schemas-v2.d.ts +3 -0
  22. package/dist/core/utils/create-fetch.d.ts +2 -1
  23. package/dist/{genUuid-CDpI3ugS.js → genUuid-C12yFv3j.js} +2 -1
  24. package/dist/genUuid-C12yFv3j.js.map +1 -0
  25. package/dist/genUuid-DdeSE04H.cjs +2 -0
  26. package/dist/genUuid-DdeSE04H.cjs.map +1 -0
  27. package/dist/{index-D84Xc70r.js → index-C87obATS.js} +531 -524
  28. package/dist/index-C87obATS.js.map +1 -0
  29. package/dist/index-ChwS_h0D.cjs +18 -0
  30. package/dist/index-ChwS_h0D.cjs.map +1 -0
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.js +668 -471
  34. package/dist/index.js.map +1 -1
  35. package/dist/package.json.d.ts +2 -1
  36. package/dist/react.cjs +1 -1
  37. package/dist/react.js +2 -2
  38. package/dist-embed/script.js +20 -20
  39. package/dist-embed/script.js.map +1 -1
  40. package/package.json +2 -1
  41. package/dist/genUuid-BkZtn1k9.cjs +0 -2
  42. package/dist/genUuid-BkZtn1k9.cjs.map +0 -1
  43. package/dist/genUuid-CDpI3ugS.js.map +0 -1
  44. package/dist/index-1bY4_hBw.cjs +0 -18
  45. package/dist/index-1bY4_hBw.cjs.map +0 -1
  46. package/dist/index-D84Xc70r.js.map +0 -1
  47. /package/dist/core/{utils/genId.test.d.ts → tests/client/integration-perisitance.test.d.ts} +0 -0
package/dist/index.js CHANGED
@@ -1,369 +1,568 @@
1
1
  var j = Object.defineProperty;
2
- var D = (t) => {
3
- throw TypeError(t);
2
+ var k = (s) => {
3
+ throw TypeError(s);
4
4
  };
5
- var B = (t, e, s) => e in t ? j(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
6
- var h = (t, e, s) => B(t, typeof e != "symbol" ? e + "" : e, s), R = (t, e, s) => e.has(t) || D("Cannot " + s);
7
- var S = (t, e, s) => (R(t, e, "read from private field"), s ? s.call(t) : e.get(t)), M = (t, e, s) => e.has(t) ? D("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(t) : e.set(t, s), _ = (t, e, s, i) => (R(t, e, "write to private field"), i ? i.call(t, s) : e.set(t, s), s);
5
+ var B = (s, e, t) => e in s ? j(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
6
+ var E = (s, e, t) => B(s, typeof e != "symbol" ? e + "" : e, t), $ = (s, e, t) => e.has(s) || k("Cannot " + t);
7
+ var h = (s, e, t) => ($(s, e, "read from private field"), t ? t.call(s) : e.get(s)), N = (s, e, t) => e.has(s) ? k("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(s) : e.set(s, t), _ = (s, e, t, n) => ($(s, e, "write to private field"), n ? n.call(s, t) : e.set(s, t), t);
8
8
  import H from "lodash.isequal";
9
- import { g as L } from "./genUuid-CDpI3ugS.js";
10
- import { M as me, c as ge } from "./genUuid-CDpI3ugS.js";
11
- var G = /* @__PURE__ */ ((t) => (t.INIT = "init", t.STATE_CHANGE = "stateChange", t.BEFORE_UPDATE = "beforeUpdate", t.AFTER_UPDATE = "afterUpdate", t.DESTROY = "destroy", t.ERROR = "error", t))(G || {}), y, T;
12
- class C {
9
+ import { g as F } from "./genUuid-C12yFv3j.js";
10
+ import { M as ye, c as Pe } from "./genUuid-C12yFv3j.js";
11
+ import "whatwg-fetch";
12
+ var J = /* @__PURE__ */ ((s) => (s.INIT = "init", s.STATE_CHANGE = "stateChange", s.BEFORE_UPDATE = "beforeUpdate", s.AFTER_UPDATE = "afterUpdate", s.DESTROY = "destroy", s.ERROR = "error", s))(J || {}), P, v;
13
+ class U {
13
14
  constructor(e) {
14
- h(this, "subscribers", /* @__PURE__ */ new Set());
15
- M(this, y);
16
- h(this, "initialState");
17
- M(this, T);
18
- h(this, "lifecycleListeners", /* @__PURE__ */ new Map());
19
- h(this, "emitLifecycle", (e, s) => {
20
- const i = this.lifecycleListeners.get(e);
21
- if (i) {
22
- const m = {
15
+ E(this, "subscribers", /* @__PURE__ */ new Set());
16
+ N(this, P);
17
+ E(this, "initialState");
18
+ N(this, v);
19
+ E(this, "lifecycleListeners", /* @__PURE__ */ new Map());
20
+ E(this, "emitLifecycle", (e, t) => {
21
+ const n = this.lifecycleListeners.get(e);
22
+ if (n) {
23
+ const f = {
23
24
  type: e,
24
25
  timestamp: Date.now(),
25
- data: s
26
+ data: t
26
27
  };
27
- i.forEach((n) => n(m));
28
+ n.forEach((i) => {
29
+ try {
30
+ i(f);
31
+ } catch (r) {
32
+ console.error("Error in lifecycle listener:", r);
33
+ }
34
+ });
28
35
  }
29
36
  });
37
+ E(this, "notifySubscribers", (e) => {
38
+ Array.from(this.subscribers).forEach((n) => {
39
+ try {
40
+ n(e);
41
+ } catch (f) {
42
+ this.emitLifecycle("error", { error: f }), console.error("Error in subscriber:", f);
43
+ }
44
+ });
45
+ });
30
46
  /**
31
47
  * Subscribe to state changes
32
48
  * @param callback Function to call when state changes
33
49
  * @returns Unsubscribe function
34
50
  */
35
- h(this, "subscribe", (e) => (this.subscribers.add(e), e(S(this, y)), () => {
51
+ E(this, "subscribe", (e) => (this.subscribers.add(e), () => {
36
52
  this.subscribers.delete(e);
37
53
  }));
38
- h(this, "onLifecycle", (e, s) => {
54
+ E(this, "onLifecycle", (e, t) => {
39
55
  this.lifecycleListeners.has(e) || this.lifecycleListeners.set(e, /* @__PURE__ */ new Set());
40
- const i = this.lifecycleListeners.get(e);
41
- return i.add(s), () => {
42
- i.delete(s), i.size === 0 && this.lifecycleListeners.delete(e);
56
+ const n = this.lifecycleListeners.get(e);
57
+ return n.add(t), () => {
58
+ n.delete(t), n.size === 0 && this.lifecycleListeners.delete(e);
43
59
  };
44
60
  });
45
61
  /**
46
62
  * Get the current state
47
63
  */
48
- h(this, "getState", () => S(this, y));
64
+ E(this, "getState", () => h(this, P));
49
65
  /**
50
66
  * Set the state and notify subscribers if the state changes
51
67
  * @param newState The new state to set
52
68
  */
53
- h(this, "setState", (e) => {
69
+ E(this, "setState", (e) => {
54
70
  this.emitLifecycle("beforeUpdate", {
55
- previousState: S(this, y),
71
+ previousState: h(this, P),
56
72
  nextState: e
57
- }), H(S(this, y), e) || (_(this, y, e), _(this, T, Date.now()), this.emitLifecycle("stateChange", { state: e }), this.subscribers.forEach((s) => {
58
- try {
59
- s(e);
60
- } catch (i) {
61
- this.emitLifecycle("error", { error: i });
62
- }
63
- })), this.emitLifecycle("afterUpdate", { state: e });
73
+ }), H(h(this, P), e) || (_(this, P, e), _(this, v, Date.now()), this.emitLifecycle("stateChange", { state: e }), this.notifySubscribers(e)), this.emitLifecycle("afterUpdate", { state: e });
64
74
  });
65
- h(this, "setStatePartial", (e) => {
66
- const s = { ...S(this, y), ...e };
67
- this.setState(s);
75
+ E(this, "setStatePartial", (e) => {
76
+ if (e == null) return;
77
+ const t = { ...h(this, P), ...e };
78
+ this.setState(t);
68
79
  });
69
80
  /**
70
81
  * Clear all subscriptions
71
82
  */
72
- h(this, "clear", () => {
83
+ E(this, "clear", () => {
73
84
  this.emitLifecycle(
74
85
  "destroy"
75
86
  /* DESTROY */
76
- ), this.subscribers.clear(), this.lifecycleListeners.clear();
87
+ ), this.subscribers = /* @__PURE__ */ new Set(), this.lifecycleListeners = /* @__PURE__ */ new Map();
77
88
  });
78
- h(this, "reset", () => {
89
+ E(this, "reset", () => {
79
90
  this.setState(this.initialState);
80
91
  });
81
- h(this, "lastUpdated", () => S(this, T));
82
- _(this, y, e), this.initialState = e, _(this, T, Date.now()), this.emitLifecycle("init", { initialState: S(this, y) });
92
+ E(this, "lastUpdated", () => h(this, v));
93
+ _(this, P, e), this.initialState = e, _(this, v, Date.now()), this.emitLifecycle("init", { initialState: h(this, P) });
83
94
  }
84
95
  }
85
- y = new WeakMap(), T = new WeakMap();
86
- function ee(t) {
87
- return new C(t);
96
+ P = new WeakMap(), v = new WeakMap();
97
+ function ae(s) {
98
+ return new U(s);
88
99
  }
89
- class v extends Error {
100
+ class I extends Error {
90
101
  constructor(e) {
91
102
  super(e), this.name = "OpenCXError";
92
103
  }
93
104
  }
94
- class te extends v {
105
+ class ne extends I {
95
106
  constructor(e = "Connection failed") {
96
107
  super(e), this.name = "ConnectionError";
97
108
  }
98
109
  }
99
- class se extends v {
110
+ class oe extends I {
100
111
  constructor(e = "Authentication failed") {
101
112
  super(e), this.name = "AuthenticationError";
102
113
  }
103
114
  }
104
- class J extends v {
115
+ class X extends I {
105
116
  constructor(e = "Session error occurred") {
106
117
  super(e), this.name = "SessionError";
107
118
  }
108
119
  }
109
- class re extends J {
120
+ class ie extends X {
110
121
  constructor(e = "Session not defined") {
111
122
  super(e), this.name = "SessionNotDefinedError";
112
123
  }
113
124
  }
114
- class ae extends v {
125
+ class le extends I {
115
126
  constructor(e = "Transport error occurred") {
116
127
  super(e), this.name = "TransportError";
117
128
  }
118
129
  }
119
- class ne extends v {
130
+ class ce extends I {
120
131
  constructor(e = "File upload failed") {
121
132
  super(e), this.name = "FileUploadError";
122
133
  }
123
134
  }
124
- function P(t) {
125
- if (!t) return !1;
135
+ class K extends I {
136
+ constructor(e = "Storage is not available") {
137
+ super(e), this.name = "StorageNotAvailableError";
138
+ }
139
+ }
140
+ class V extends I {
141
+ constructor(e = "External ID is not defined") {
142
+ super(e), this.name = "ExternalIdNotDefinedError";
143
+ }
144
+ }
145
+ function L(s) {
146
+ if (!s) return !1;
126
147
  try {
127
- return typeof t.isAvailable == "function" ? t.isAvailable() : !0;
148
+ return typeof s.isAvailable == "function" ? s.isAvailable() : !0;
128
149
  } catch {
129
150
  return !1;
130
151
  }
131
152
  }
132
- async function O(t, e) {
153
+ async function M(s, e) {
133
154
  try {
134
- return { success: !0, result: await t() };
135
- } catch (s) {
136
- return console.error(e, s), {
155
+ return { success: !0, result: await s(), error: null };
156
+ } catch (t) {
157
+ return console.error(e, t), {
137
158
  success: !1,
138
- error: s instanceof Error ? s : new Error(e)
159
+ result: null,
160
+ error: {
161
+ message: t instanceof Error ? t.message || "Unknown error" : (t == null ? void 0 : t.toString()) || "Unknown error",
162
+ code: "STORAGE_OPERATION_FAILED",
163
+ context: e
164
+ }
139
165
  };
140
166
  }
141
167
  }
142
- const k = {
168
+ function ue(s = {}) {
169
+ const {
170
+ level: e = "info",
171
+ prefix: t = "[openCx]",
172
+ enabled: n = !0
173
+ } = s;
174
+ let f = e;
175
+ const i = {
176
+ debug: 0,
177
+ info: 1,
178
+ warn: 2,
179
+ error: 3
180
+ };
181
+ function r(u) {
182
+ return n && i[u] >= i[f];
183
+ }
184
+ function l(u) {
185
+ return `${t} ${u}`;
186
+ }
187
+ function c(u) {
188
+ return u.map((a) => {
189
+ if (a instanceof Error)
190
+ return {
191
+ name: a.name,
192
+ message: a.message,
193
+ stack: a.stack
194
+ };
195
+ if (typeof a == "object")
196
+ try {
197
+ return JSON.stringify(a, null, 2);
198
+ } catch {
199
+ return a;
200
+ }
201
+ return a;
202
+ });
203
+ }
204
+ return {
205
+ debug(u, ...a) {
206
+ r("debug") && console.debug(l(u), ...c(a));
207
+ },
208
+ info(u, ...a) {
209
+ r("info") && console.info(l(u), ...c(a));
210
+ },
211
+ warn(u, ...a) {
212
+ r("warn") && console.warn(l(u), ...c(a));
213
+ },
214
+ error(u, ...a) {
215
+ r("error") && console.error(l(u), ...c(a));
216
+ },
217
+ setLevel(u) {
218
+ f = u;
219
+ }
220
+ };
221
+ }
222
+ function fe(s) {
223
+ if (!s) return !1;
224
+ try {
225
+ return typeof s.isAvailable == "function" ? s.isAvailable() : !0;
226
+ } catch {
227
+ return !1;
228
+ }
229
+ }
230
+ async function de(s, e) {
231
+ try {
232
+ return await s(), { success: !0, error: null };
233
+ } catch (t) {
234
+ return console.error(e, t), {
235
+ success: !1,
236
+ error: {
237
+ message: t instanceof Error ? t.message || "Unknown error" : (t == null ? void 0 : t.toString()) || "Unknown error",
238
+ code: "AUDIO_OPERATION_FAILED",
239
+ context: e
240
+ }
241
+ };
242
+ }
243
+ }
244
+ const D = {
143
245
  SESSION: 1e4,
144
246
  // every 10 seconds
145
247
  MESSAGES: 5e3
146
248
  // every 5 seconds
147
249
  };
148
- function x(t) {
149
- var s;
250
+ function G(s) {
150
251
  const e = {
151
- id: t.publicId || L(),
152
- timestamp: t.sentAt || "",
153
- attachments: t.attachments || void 0
252
+ id: s.publicId,
253
+ timestamp: s.sentAt || "",
254
+ attachments: s.attachments || void 0
154
255
  };
155
- return t.sender.kind === "user" ? {
256
+ return s.sender.kind === "user" ? {
156
257
  ...e,
157
258
  type: "FROM_USER",
158
- content: t.content.text || "",
159
- deliveredAt: t.sentAt || ""
160
- } : t.sender.kind === "agent" ? {
161
- id: t.publicId || L(),
259
+ content: s.content.text || "",
260
+ deliveredAt: s.sentAt || ""
261
+ } : s.sender.kind === "agent" ? {
262
+ id: s.publicId,
162
263
  type: "FROM_AGENT",
163
- component: t.type,
264
+ component: s.type,
164
265
  data: {
165
- text: t.content.text
266
+ text: s.content.text
166
267
  },
167
- timestamp: (s = t.sentAt) == null ? void 0 : s.toISOString(),
168
- attachments: t.attachments || void 0
268
+ timestamp: s.sentAt || "",
269
+ attachments: s.attachments || void 0
169
270
  } : {
170
271
  ...e,
171
272
  type: "FROM_BOT",
172
273
  component: "TEXT",
173
274
  agent: {
174
275
  id: null,
175
- name: t.sender.name || "",
176
- is_ai: t.sender.kind === "ai",
177
- profile_picture: t.sender.avatar
276
+ name: s.sender.name || "",
277
+ is_ai: s.sender.kind === "ai",
278
+ profile_picture: s.sender.avatar
178
279
  },
179
280
  data: {
180
- message: t.content.text
281
+ message: s.content.text
181
282
  }
182
283
  };
183
284
  }
184
- function X(t, e, s) {
185
- async function i(o) {
186
- const l = e.getState().messages;
187
- if (l.length === 0) {
188
- s == null || s.debug("No messages yet, fetching all history", { sessionId: o.id });
189
- const g = await t.getSessionHistory(o.id, "");
190
- g && g.length > 0 && e.setStatePartial({
191
- messages: g.map(x)
285
+ function z(s, e, t) {
286
+ async function n(l) {
287
+ var o;
288
+ const c = e.getState().messages;
289
+ if (c.length === 0) {
290
+ t == null || t.debug("No messages yet, fetching all history", { sessionId: l.id });
291
+ const m = await s.getSessionHistory(l.id, "");
292
+ m && m.length > 0 && e.setStatePartial({
293
+ messages: m.map(G)
192
294
  });
193
295
  return;
194
296
  }
195
- const c = l[l.length - 1], r = new Date(c.timestamp);
196
- r.setSeconds(r.getSeconds() + 1);
197
- const u = r.toISOString();
198
- s == null || s.debug("Fetching history messages after timestamp", {
199
- sessionId: o.id,
297
+ const u = (o = e.getState().messages.at(-1)) == null ? void 0 : o.timestamp;
298
+ t == null || t.debug("Fetching history messages after timestamp", {
299
+ sessionId: l.id,
200
300
  lastMessageTimestamp: u,
201
- currentMessageCount: l.length
301
+ currentMessageCount: c.length
202
302
  });
203
- const E = await t.getSessionHistory(o.id, u);
204
- if (E && E.length > 0) {
205
- const g = E.map(x).filter((p) => !l.some((I) => I.id === p.id));
206
- g.length > 0 && (s == null || s.debug("Adding new messages to state", {
207
- count: g.length,
208
- messageIds: g.map((p) => p.id),
209
- messageTypes: g.map((p) => p.type)
303
+ const a = await s.getSessionHistory(l.id, u);
304
+ if (a && a.length > 0) {
305
+ const m = a.map(G).filter((p) => !c.some((y) => y.id === p.id));
306
+ m.length > 0 && (t == null || t.debug("Adding new messages to state", {
307
+ count: m.length,
308
+ messageIds: m.map((p) => p.id),
309
+ messageTypes: m.map((p) => p.type)
210
310
  }), e.setStatePartial({
211
- messages: [...l, ...g]
311
+ messages: [...c, ...m]
212
312
  }));
213
313
  }
214
314
  }
215
- function m(o, l) {
315
+ function f(l, c) {
216
316
  return {
217
- id: L(),
317
+ id: F(),
218
318
  type: "FROM_USER",
219
- content: o,
319
+ content: l,
220
320
  deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
221
- attachments: l,
321
+ attachments: c,
222
322
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
223
323
  };
224
324
  }
225
- function n(o) {
226
- if (o.success && o.autopilotResponse)
325
+ function i(l) {
326
+ if (l.success && l.autopilotResponse)
227
327
  return {
228
328
  type: "FROM_BOT",
229
- id: o.autopilotResponse.id || L(),
329
+ id: l.autopilotResponse.id || F(),
230
330
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
231
331
  component: "TEXT",
232
332
  data: {
233
- message: o.autopilotResponse.value.content
333
+ message: l.autopilotResponse.value.content
234
334
  }
235
335
  };
236
- if (o.success && o.uiResponse) {
237
- const l = o.uiResponse.value;
336
+ if (l.success && l.uiResponse) {
337
+ const c = l.uiResponse.value;
238
338
  return {
239
339
  type: "FROM_BOT",
240
- id: L(),
340
+ id: F(),
241
341
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
242
- component: l.name,
243
- data: l.request_response
342
+ component: c.name,
343
+ data: c.request_response
244
344
  };
245
345
  }
246
346
  return null;
247
347
  }
248
- function a(o) {
348
+ function r(l) {
249
349
  return {
250
350
  type: "FROM_BOT",
251
- id: L(),
351
+ id: F(),
252
352
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
253
353
  component: "TEXT",
254
354
  data: {
255
- message: o,
355
+ message: l,
256
356
  variant: "error"
257
357
  }
258
358
  };
259
359
  }
260
360
  return {
261
- fetchHistoryMessages: i,
262
- addUserMessage: m,
263
- addBotMessage: n,
264
- addErrorMessage: a
361
+ fetchHistoryMessages: n,
362
+ addUserMessage: f,
363
+ addBotMessage: i,
364
+ addErrorMessage: r
265
365
  };
266
366
  }
267
- function z(t, e, s, i, m, n) {
268
- var U, N;
269
- const a = (U = n.platform) == null ? void 0 : U.logger;
270
- let o = null;
271
- const l = (N = n.platform) == null ? void 0 : N.storage, c = `${m.getConfig().user.external_id}:${m.getConfig().token}:session`, r = n.config.getSettings().persistSession;
272
- async function u() {
273
- if (l)
367
+ function Y(s, e, t, n, f, i) {
368
+ var O, x;
369
+ const r = (O = i.platform) == null ? void 0 : O.logger;
370
+ let l = null;
371
+ const c = (x = i.platform) == null ? void 0 : x.storage, u = f.getSettings().persistSession;
372
+ if (u && !L(c))
373
+ throw new K();
374
+ if (u && !f.getConfig().user.external_id)
375
+ throw new V("session persistence is enabled but external id is not defined");
376
+ const a = `${f.getConfig().user.external_id}:${f.getConfig().token}:session`;
377
+ async function o() {
378
+ if (c)
274
379
  try {
275
- a == null || a.debug("Attempting to restore session from storage");
276
- const d = await l.getItem(c);
380
+ r == null || r.debug("Attempting to restore session from storage");
381
+ const d = await c.getItem(a);
277
382
  if (d) {
278
- const f = JSON.parse(d);
279
- a == null || a.info("Session restored from storage", { sessionId: f.id }), e.setState(f), await i.fetchHistoryMessages(f), g();
383
+ const g = JSON.parse(d);
384
+ r == null || r.info("Session restored from storage", { sessionId: g.id }), e.setState(g), await n.fetchHistoryMessages(g), p();
280
385
  }
281
386
  } catch (d) {
282
- a == null || a.error("Error restoring session from storage:", d);
387
+ r == null || r.error("Error restoring session from storage:", d);
283
388
  }
284
389
  }
285
- function E() {
286
- l && (a == null || a.debug("Setting up session persistence"), e.subscribe(async (d) => {
390
+ function m() {
391
+ c && (r == null || r.debug("Setting up session persistence"), e.subscribe(async (d) => {
287
392
  try {
288
- d ? (await l.setItem(c, JSON.stringify(d)), a == null || a.debug("Session persisted to storage", { sessionId: d.id })) : (await l.removeItem(c), a == null || a.debug("Session removed from storage"));
289
- } catch (f) {
290
- a == null || a.error("Error persisting session:", f), s.setStatePartial({
393
+ d ? (await c.setItem(a, JSON.stringify(d)), r == null || r.debug("Session persisted to storage", { sessionId: d.id })) : (await c.removeItem(a), r == null || r.debug("Session removed from storage"));
394
+ } catch (g) {
395
+ r == null || r.error("Error persisting session:", g), t.setStatePartial({
291
396
  error: {
292
397
  hasError: !0,
293
- message: f instanceof Error ? f.message : "Failed to persist session",
398
+ message: g instanceof Error ? g.message : "Failed to persist session",
294
399
  code: "SESSION_PERSISTENCE_FAILED"
295
400
  }
296
401
  });
297
402
  }
298
403
  }));
299
404
  }
300
- function g() {
301
- if (o) return;
302
- a == null || a.debug("Starting polling");
405
+ function p() {
406
+ if (l) return;
407
+ r == null || r.debug("Starting polling");
303
408
  const d = [];
304
409
  d.push(
305
410
  setInterval(async () => {
306
- const f = e.getState();
307
- if (f != null && f.id)
411
+ const g = e.getState();
412
+ if (g != null && g.id)
308
413
  try {
309
- const w = await t.getSession(f.id);
310
- w && e.setState(w);
311
- } catch (w) {
312
- a == null || a.error("Error polling session:", w);
414
+ const S = /* @__PURE__ */ new Date();
415
+ t.setStatePartial({
416
+ polling: {
417
+ ...t.getState().polling,
418
+ session: {
419
+ isPolling: !0,
420
+ lastPollTime: S.toISOString(),
421
+ nextPollTime: new Date(S.getTime() + D.SESSION).toISOString(),
422
+ error: { hasError: !1 }
423
+ }
424
+ }
425
+ });
426
+ const R = await s.getSession(g.id);
427
+ R && e.setState(R), t.setStatePartial({
428
+ polling: {
429
+ ...t.getState().polling,
430
+ session: {
431
+ ...t.getState().polling.session,
432
+ isPolling: !1
433
+ }
434
+ }
435
+ });
436
+ } catch (S) {
437
+ r == null || r.error("Error polling session:", S), t.setStatePartial({
438
+ polling: {
439
+ ...t.getState().polling,
440
+ session: {
441
+ ...t.getState().polling.session,
442
+ isPolling: !1,
443
+ error: {
444
+ hasError: !0,
445
+ message: S instanceof Error ? S.message : "Failed to poll session",
446
+ code: "SESSION_POLLING_FAILED"
447
+ }
448
+ }
449
+ }
450
+ });
313
451
  }
314
- }, k.SESSION)
452
+ }, D.SESSION)
315
453
  ), d.push(
316
454
  setInterval(async () => {
317
- const f = e.getState();
318
- if (f != null && f.id)
455
+ const g = e.getState();
456
+ if (g != null && g.id)
319
457
  try {
320
- await i.fetchHistoryMessages(f);
321
- } catch (w) {
322
- a == null || a.error("Error polling messages:", w);
458
+ const S = /* @__PURE__ */ new Date();
459
+ t.setStatePartial({
460
+ polling: {
461
+ ...t.getState().polling,
462
+ messages: {
463
+ isPolling: !0,
464
+ lastPollTime: S.toISOString(),
465
+ nextPollTime: new Date(S.getTime() + D.MESSAGES).toISOString(),
466
+ error: { hasError: !1 }
467
+ }
468
+ }
469
+ }), await n.fetchHistoryMessages(g), t.setStatePartial({
470
+ polling: {
471
+ ...t.getState().polling,
472
+ messages: {
473
+ ...t.getState().polling.messages,
474
+ isPolling: !1
475
+ }
476
+ }
477
+ });
478
+ } catch (S) {
479
+ r == null || r.error("Error polling messages:", S), t.setStatePartial({
480
+ polling: {
481
+ ...t.getState().polling,
482
+ messages: {
483
+ ...t.getState().polling.messages,
484
+ isPolling: !1,
485
+ error: {
486
+ hasError: !0,
487
+ message: S instanceof Error ? S.message : "Failed to poll messages",
488
+ code: "MESSAGES_POLLING_FAILED"
489
+ }
490
+ }
491
+ }
492
+ });
493
+ }
494
+ }, D.MESSAGES)
495
+ ), l = () => {
496
+ r == null || r.debug("Stopping polling"), d.forEach(clearInterval), t.setStatePartial({
497
+ polling: {
498
+ session: {
499
+ isPolling: !1,
500
+ lastPollTime: null,
501
+ nextPollTime: null,
502
+ error: { hasError: !1 }
503
+ },
504
+ messages: {
505
+ isPolling: !1,
506
+ lastPollTime: null,
507
+ nextPollTime: null,
508
+ error: { hasError: !1 }
323
509
  }
324
- }, k.MESSAGES)
325
- ), o = () => {
326
- a == null || a.debug("Stopping polling"), d.forEach(clearInterval);
510
+ }
511
+ });
327
512
  };
328
513
  }
329
- async function p() {
514
+ async function y() {
330
515
  try {
331
- a == null || a.info("Creating new session"), s.setStatePartial({
516
+ r == null || r.info("Creating new session"), t.setStatePartial({
332
517
  loading: { isLoading: !0, reason: "creating_session" },
333
518
  error: { hasError: !1 }
334
519
  });
335
- const d = await t.createSession();
336
- return a == null || a.info("Session created successfully", { sessionId: d.id }), e.setState(d), g(), d;
520
+ const d = await s.createSession();
521
+ return r == null || r.info("Session created successfully", { sessionId: d.id }), e.setState(d), p(), d;
337
522
  } catch (d) {
338
- a == null || a.error("Failed to create session:", d);
339
- const f = {
523
+ r == null || r.error("Failed to create session:", d);
524
+ const g = {
340
525
  hasError: !0,
341
526
  message: d instanceof Error ? d.message : "Failed to create session",
342
527
  code: "SESSION_CREATION_FAILED"
343
528
  };
344
- return s.setStatePartial({ error: f }), null;
529
+ return t.setStatePartial({ error: g }), null;
345
530
  } finally {
346
- s.setStatePartial({
531
+ t.setStatePartial({
347
532
  loading: { isLoading: !1, reason: null }
348
533
  });
349
534
  }
350
535
  }
351
- async function I() {
352
- var f;
536
+ async function C() {
537
+ var g;
353
538
  const d = e.getState();
354
539
  if (d != null && d.id)
355
540
  try {
356
- o && (o(), o = null), e.setState(null), r && l && P(l) && l.removeItem(c), s.setState({
541
+ l && (l(), l = null), e.setState(null), u && c && await c.removeItem(a), t.setState({
357
542
  messages: [],
358
543
  keyboard: null,
359
- loading: { isLoading: !1 },
360
- error: { hasError: !1 }
361
- }), (f = n.onSessionDestroy) == null || f.call(n);
362
- } catch (w) {
363
- console.error("Error clearing session:", w), s.setStatePartial({
544
+ loading: { isLoading: !1, reason: null },
545
+ error: { hasError: !1 },
546
+ polling: {
547
+ session: {
548
+ isPolling: !1,
549
+ lastPollTime: null,
550
+ nextPollTime: null,
551
+ error: { hasError: !1 }
552
+ },
553
+ messages: {
554
+ isPolling: !1,
555
+ lastPollTime: null,
556
+ nextPollTime: null,
557
+ error: { hasError: !1 }
558
+ }
559
+ }
560
+ }), (g = i.onSessionDestroy) == null || g.call(i);
561
+ } catch (S) {
562
+ console.error("Error clearing session:", S), t.setStatePartial({
364
563
  error: {
365
564
  hasError: !0,
366
- message: w instanceof Error ? w.message : "Failed to clear session",
565
+ message: S instanceof Error ? S.message : "Failed to clear session",
367
566
  code: "SESSION_CLEAR_FAILED"
368
567
  }
369
568
  });
@@ -371,321 +570,368 @@ function z(t, e, s, i, m, n) {
371
570
  }
372
571
  function A(d = !1) {
373
572
  try {
374
- o && (o(), o = null), d && r && l && P(l) && l.removeItem(c), s.setState({
573
+ l && (l(), l = null), d && u && c && L(c) && c.removeItem(a), t.setState({
375
574
  messages: [],
376
575
  keyboard: null,
377
- loading: { isLoading: !1 },
378
- error: { hasError: !1 }
379
- }), e.setState(null), s.clear(), e.clear();
380
- } catch (f) {
381
- console.error("Error in cleanup:", f), s.setStatePartial({
576
+ loading: { isLoading: !1, reason: null },
577
+ error: { hasError: !1 },
578
+ polling: {
579
+ session: {
580
+ isPolling: !1,
581
+ lastPollTime: null,
582
+ nextPollTime: null,
583
+ error: { hasError: !1 }
584
+ },
585
+ messages: {
586
+ isPolling: !1,
587
+ lastPollTime: null,
588
+ nextPollTime: null,
589
+ error: { hasError: !1 }
590
+ }
591
+ }
592
+ }), e.setState(null), t.clear(), e.clear();
593
+ } catch (g) {
594
+ console.error("Error in cleanup:", g), t.setStatePartial({
382
595
  error: {
383
596
  hasError: !0,
384
- message: f instanceof Error ? f.message : "Failed to cleanup",
597
+ message: g instanceof Error ? g.message : "Failed to cleanup",
385
598
  code: "SESSION_CLEAR_FAILED"
386
599
  }
387
600
  });
388
601
  }
389
602
  }
390
- async function F(d) {
391
- return t.getSession(d);
603
+ async function w(d) {
604
+ return s.getSession(d);
392
605
  }
393
- async function q() {
606
+ async function T() {
394
607
  const d = e.getState();
395
608
  if (!(d != null && d.id)) return;
396
- const f = await F(d.id);
397
- return f && e.setState(f), f;
609
+ const g = await w(d.id);
610
+ return g && e.setState(g), g;
398
611
  }
399
- return r && P(l) && (u(), E()), {
400
- createSession: p,
401
- clearSession: I,
612
+ return u && L(c) && (o(), m()), {
613
+ createSession: y,
614
+ clearSession: C,
402
615
  cleanup: A,
403
- startPolling: g,
404
- fetchSession: F,
405
- refetchSession: q
616
+ startPolling: p,
617
+ fetchSession: w,
618
+ refetchSession: T,
619
+ sessionStorageKey: a
406
620
  };
407
621
  }
408
- function ie(t) {
409
- var o;
410
- const e = (o = t.platform) == null ? void 0 : o.logger;
411
- e == null || e.info("Initializing chat");
412
- const s = new C({
622
+ function ge(s) {
623
+ var c;
624
+ const e = (c = s.platform) == null ? void 0 : c.logger, t = {
413
625
  messages: [],
414
626
  keyboard: null,
415
- loading: { isLoading: !1 },
416
- error: { hasError: !1 }
417
- }), i = new C(null), m = X(t.api, s, e), n = z(
418
- t.api,
627
+ loading: { isLoading: !1, reason: null },
628
+ error: { hasError: !1 },
629
+ polling: {
630
+ session: {
631
+ isPolling: !1,
632
+ lastPollTime: null,
633
+ nextPollTime: null,
634
+ error: { hasError: !1 }
635
+ },
636
+ messages: {
637
+ isPolling: !1,
638
+ lastPollTime: null,
639
+ nextPollTime: null,
640
+ error: { hasError: !1 }
641
+ }
642
+ }
643
+ }, n = new U(t), f = new U(null), i = z(s.api, n, e), r = Y(
644
+ s.api,
645
+ f,
646
+ n,
419
647
  i,
420
- s,
421
- m,
422
- t.config,
423
- t
648
+ s.config,
649
+ s
424
650
  );
425
- async function a(l) {
426
- var r;
427
- let c = i.getState();
428
- if (!(c != null && c.id) && (e == null || e.debug("No active session, creating new session"), c = await n.createSession(), !c))
429
- return !1;
430
- c.assignee.kind === "ai" && (c = await n.refetchSession() ?? c);
651
+ async function l(u, a) {
652
+ var p;
653
+ let o = f.getState(), m = !1;
654
+ if (!(o != null && o.id)) {
655
+ if (e == null || e.debug("No active session, creating new session"), o = await r.createSession(), !o) return {
656
+ success: !1,
657
+ createdSession: m
658
+ };
659
+ m = !0;
660
+ }
661
+ o.assignee.kind === "ai" && (o = await r.refetchSession() ?? o);
431
662
  try {
432
- e == null || e.debug("Sending message", { sessionId: c.id }), c.assignee.kind === "ai" ? s.setStatePartial({
663
+ e == null || e.debug("Sending message", { sessionId: o.id }), o.assignee.kind === "ai" ? n.setStatePartial({
433
664
  loading: { isLoading: !0, reason: "sending_message_to_bot" },
434
665
  error: { hasError: !1 }
435
- }) : s.setStatePartial({
666
+ }) : n.setStatePartial({
436
667
  loading: { isLoading: !0, reason: "sending_message_to_agent" },
437
668
  error: { hasError: !1 }
438
669
  });
439
- const u = m.addUserMessage(l.content, l.attachments || void 0), E = s.getState().messages;
440
- s.setStatePartial({
441
- messages: [...E, u]
442
- });
443
- const g = t.config.getConfig(), p = await t.api.handleMessage({
444
- bot_token: g.token,
445
- headers: g.headers,
446
- query_params: g.queryParams,
447
- session_id: c.id,
448
- user: g.user,
449
- ...l
670
+ const y = i.addUserMessage(u.content, u.attachments || void 0), C = n.getState().messages;
671
+ n.setStatePartial({
672
+ messages: [...C, y]
450
673
  });
451
- if (p.success) {
674
+ const A = s.config.getConfig(), w = await s.api.handleMessage({
675
+ uuid: u.uuid || F(),
676
+ bot_token: A.token,
677
+ headers: A.headers,
678
+ query_params: A.queryParams,
679
+ session_id: o.id,
680
+ user: A.user,
681
+ ...u
682
+ }, a);
683
+ if (w.success) {
452
684
  e == null || e.debug("Message sent successfully");
453
- const I = m.addBotMessage(p);
454
- if (I) {
455
- const A = s.getState().messages;
456
- s.setStatePartial({
457
- messages: [...A, I]
685
+ const T = i.addBotMessage(w);
686
+ if (T) {
687
+ const O = n.getState().messages;
688
+ n.setStatePartial({
689
+ messages: [...O, T]
458
690
  });
459
691
  }
692
+ return {
693
+ success: !0,
694
+ createdSession: m,
695
+ botMessage: T
696
+ };
460
697
  } else {
461
- e == null || e.warn("Message send failed", p.error);
462
- const I = m.addErrorMessage(((r = p.error) == null ? void 0 : r.message) || "Unknown error occurred"), A = s.getState().messages;
463
- s.setStatePartial({
464
- messages: [...A, I]
465
- });
698
+ e == null || e.warn("Message send failed", w.error);
699
+ const T = i.addErrorMessage(((p = w.error) == null ? void 0 : p.message) || "Unknown error occurred"), O = n.getState().messages;
700
+ return n.setStatePartial({
701
+ messages: [...O, T]
702
+ }), {
703
+ success: !1,
704
+ createdSession: m,
705
+ error: w.error
706
+ };
466
707
  }
467
- return !0;
468
- } catch (u) {
469
- return e == null || e.error("Error sending message:", u), s.setStatePartial({
708
+ } catch (y) {
709
+ return e == null || e.error("Error sending message:", y), n.setStatePartial({
470
710
  error: {
471
711
  hasError: !0,
472
- message: u instanceof Error ? u.message : "Failed to send message",
712
+ message: y instanceof Error ? y.message : "Failed to send message",
473
713
  code: "MESSAGE_SEND_FAILED"
474
714
  }
475
- }), !1;
715
+ }), {
716
+ success: !1,
717
+ createdSession: m,
718
+ error: y
719
+ };
476
720
  } finally {
477
- s.setStatePartial({
721
+ n.setStatePartial({
478
722
  loading: { isLoading: !1, reason: null }
479
723
  });
480
724
  }
481
725
  }
482
726
  return {
483
- chatState: s,
484
- sessionState: i,
485
- sendMessage: a,
486
- createSession: n.createSession,
487
- clearSession: n.clearSession,
488
- cleanup: (l = !1) => n.cleanup(l)
727
+ chatState: n,
728
+ sessionState: f,
729
+ sendMessage: l,
730
+ createSession: r.createSession,
731
+ clearSession: r.clearSession,
732
+ cleanup: r.cleanup,
733
+ initialState: t,
734
+ sessionStorageKey: r.sessionStorageKey
489
735
  };
490
736
  }
491
- function oe(t) {
492
- const e = t.config.getConfig();
493
- t.config.getConfig;
494
- const s = `${e.token}:contact:${e.user.external_id}`, i = P(t.platform.storage) ? t.platform.storage : void 0;
495
- let m = null;
496
- i && O(
737
+ function me(s) {
738
+ const e = s.config.getConfig();
739
+ s.config.getConfig;
740
+ const t = `${e.token}:contact:${e.user.external_id}`, n = L(s.platform.storage) ? s.platform.storage : void 0;
741
+ let f = null;
742
+ n && M(
497
743
  async () => {
498
- const r = await i.getItem(s);
499
- return r ? JSON.parse(r) : null;
744
+ const a = await n.getItem(t);
745
+ return a ? JSON.parse(a) : null;
500
746
  },
501
747
  "Error loading contact from storage"
502
- ).then((r) => {
503
- r.success && (m = r.result);
748
+ ).then((a) => {
749
+ a.success && (f = a.result);
504
750
  });
505
- const n = new C({
506
- contact: m,
507
- loading: { isLoading: !1 },
751
+ const i = new U({
752
+ contact: f,
753
+ loading: { isLoading: !1, reason: null },
508
754
  error: { hasError: !1 }
509
755
  });
510
- P(i) && n.subscribe((r) => {
511
- O(
756
+ L(n) && i.subscribe((a) => {
757
+ M(
512
758
  async () => {
513
- r.contact ? await i.setItem(s, JSON.stringify(r.contact)) : i.removeItem(s);
759
+ a.contact ? await n.setItem(t, JSON.stringify(a.contact)) : n.removeItem(t);
514
760
  },
515
761
  "Error persisting contact state"
516
- ).then((u) => {
517
- u.success || n.setStatePartial({
762
+ ).then((o) => {
763
+ o.success || i.setStatePartial({
518
764
  error: {
519
765
  hasError: !0,
520
- message: u.error.message,
766
+ message: o.error.message,
521
767
  code: "CONTACT_PERSISTENCE_FAILED"
522
768
  }
523
769
  });
524
770
  });
525
771
  });
526
- async function a() {
772
+ async function r() {
527
773
  try {
528
- if (n.setStatePartial({
774
+ if (i.setStatePartial({
529
775
  loading: { isLoading: !0, reason: "loading_contact" },
530
776
  error: { hasError: !1 }
531
- }), i) {
532
- const r = await O(
777
+ }), n) {
778
+ const a = await M(
533
779
  async () => {
534
- const u = await i.getItem(s);
535
- return u ? JSON.parse(u) : null;
780
+ const o = await n.getItem(t);
781
+ return o ? JSON.parse(o) : null;
536
782
  },
537
783
  "Error loading contact"
538
784
  );
539
- if (!r.success)
540
- throw r.error;
541
- return n.setStatePartial({
542
- contact: r.result,
785
+ if (!a.success)
786
+ throw a.error;
787
+ return i.setStatePartial({
788
+ contact: a.result,
543
789
  error: { hasError: !1 }
544
- }), r.result;
790
+ }), a.result;
545
791
  }
546
- return n.getState().contact;
547
- } catch (r) {
548
- return n.setStatePartial({
792
+ return i.getState().contact;
793
+ } catch (a) {
794
+ return i.setStatePartial({
549
795
  error: {
550
796
  hasError: !0,
551
- message: r instanceof Error ? r.message : "Failed to load contact",
797
+ message: a instanceof Error ? a.message : "Failed to load contact",
552
798
  code: "CONTACT_LOAD_FAILED"
553
799
  }
554
800
  }), null;
555
801
  } finally {
556
- n.setStatePartial({
802
+ i.setStatePartial({
557
803
  loading: { isLoading: !1, reason: null }
558
804
  });
559
805
  }
560
806
  }
561
- async function o(r) {
807
+ async function l(a) {
562
808
  try {
563
- n.setStatePartial({
809
+ i.setStatePartial({
564
810
  loading: { isLoading: !0, reason: "saving_contact" },
565
811
  error: { hasError: !1 }
566
812
  });
567
- const u = n.getState().contact, E = {
568
- id: r.id || (u == null ? void 0 : u.id) || "",
569
- name: r.name ?? (u == null ? void 0 : u.name) ?? null,
570
- created_at: r.created_at || (u == null ? void 0 : u.created_at) || (/* @__PURE__ */ new Date()).toISOString(),
571
- avatar_url: r.avatar_url ?? (u == null ? void 0 : u.avatar_url) ?? null,
572
- email: r.email ?? (u == null ? void 0 : u.email) ?? null
813
+ const o = i.getState().contact, m = {
814
+ id: a.id || (o == null ? void 0 : o.id) || "",
815
+ name: a.name ?? (o == null ? void 0 : o.name) ?? null,
816
+ created_at: a.created_at || (o == null ? void 0 : o.created_at) || (/* @__PURE__ */ new Date()).toISOString(),
817
+ avatar_url: a.avatar_url ?? (o == null ? void 0 : o.avatar_url) ?? null,
818
+ email: a.email ?? (o == null ? void 0 : o.email) ?? null
573
819
  };
574
- if (P(i)) {
575
- const g = await O(
576
- () => i.setItem(s, JSON.stringify(E)),
820
+ if (L(n)) {
821
+ const p = await M(
822
+ () => n.setItem(t, JSON.stringify(m)),
577
823
  "Error saving contact"
578
824
  );
579
- if (!g.success)
580
- throw g.error;
825
+ if (!p.success)
826
+ throw p.error;
581
827
  }
582
- return n.setStatePartial({
583
- contact: E,
828
+ return i.setStatePartial({
829
+ contact: m,
584
830
  error: { hasError: !1 }
585
- }), E;
586
- } catch (u) {
587
- return n.setStatePartial({
831
+ }), m;
832
+ } catch (o) {
833
+ return i.setStatePartial({
588
834
  error: {
589
835
  hasError: !0,
590
- message: u instanceof Error ? u.message : "Failed to save contact",
836
+ message: o instanceof Error ? o.message : "Failed to save contact",
591
837
  code: "CONTACT_SAVE_FAILED"
592
838
  }
593
839
  }), null;
594
840
  } finally {
595
- n.setStatePartial({
841
+ i.setStatePartial({
596
842
  loading: { isLoading: !1, reason: null }
597
843
  });
598
844
  }
599
845
  }
600
- function l() {
601
- var u;
602
- return !((u = n.getState().contact) != null && u.id) && e.collectUserData ? {
846
+ function c() {
847
+ var o;
848
+ return !((o = i.getState().contact) != null && o.id) && e.collectUserData ? {
603
849
  should: !0,
604
850
  reason: "No contact id and collectUserData is true"
605
851
  } : {
606
852
  should: !1
607
853
  };
608
854
  }
609
- async function c() {
855
+ async function u() {
610
856
  try {
611
- if (n.setStatePartial({
857
+ if (i.setStatePartial({
612
858
  loading: { isLoading: !0, reason: "cleaning_up" },
613
859
  error: { hasError: !1 }
614
- }), i) {
615
- const r = await O(
616
- () => i.removeItem(s),
860
+ }), n) {
861
+ const a = await M(
862
+ () => n.removeItem(t),
617
863
  "Error removing contact data"
618
864
  );
619
- if (!r.success)
620
- throw r.error;
865
+ if (!a.success)
866
+ throw a.error;
621
867
  }
622
- n.setState({
868
+ i.setState({
623
869
  contact: null,
624
- loading: { isLoading: !1 },
870
+ loading: { isLoading: !1, reason: null },
625
871
  error: { hasError: !1 }
626
- }), n.clear();
627
- } catch (r) {
628
- console.error("Error cleaning up contact:", r), n.setStatePartial({
872
+ }), i.clear();
873
+ } catch (a) {
874
+ console.error("Error cleaning up contact:", a), i.setStatePartial({
629
875
  error: {
630
876
  hasError: !0,
631
- message: r instanceof Error ? r.message : "Failed to cleanup contact data",
877
+ message: a instanceof Error ? a.message : "Failed to cleanup contact data",
632
878
  code: "CONTACT_CLEANUP_FAILED"
633
879
  }
634
880
  });
635
881
  } finally {
636
- n.setStatePartial({
882
+ i.setStatePartial({
637
883
  loading: { isLoading: !1, reason: null }
638
884
  });
639
885
  }
640
886
  }
641
887
  return {
642
- contactState: n,
643
- shouldCollectData: l,
644
- loadContact: a,
645
- saveContact: o,
646
- cleanup: c
888
+ contactState: i,
889
+ shouldCollectData: c,
890
+ loadContact: r,
891
+ saveContact: l,
892
+ cleanup: u
647
893
  };
648
894
  }
649
- const V = {
895
+ const Q = {
650
896
  messageArrived: "https://cloud.opencopilot.so/sfx/notification3.mp3"
651
- }, $ = {
897
+ }, q = {
652
898
  primaryColor: "hsl(211,65%,59%)",
653
899
  triggerOffset: "20px"
654
- }, K = 1e3 * 3;
655
- function ce(t) {
656
- var s, i, m, n, a, o, l, c, r;
657
- if (!t.token)
900
+ }, W = 1e3 * 3;
901
+ function Se(s) {
902
+ var t, n, f, i, r, l, c, u, a;
903
+ if (!s.token)
658
904
  throw new Error("Token is required");
659
- if (t.pollingInterval && t.pollingInterval < K)
905
+ if (s.pollingInterval && s.pollingInterval < W)
660
906
  throw new Error("Polling interval must be at least 3 seconds");
661
907
  const e = {
662
- ...t,
663
- collectUserData: t.collectUserData ?? !1,
664
- apiUrl: t.apiUrl ?? "https://api-v2.opencopilot.so/backend",
665
- pollingInterval: t.pollingInterval ?? 3e3,
666
- headers: t.headers ?? {},
667
- queryParams: t.queryParams ?? {},
668
- pathParams: t.pathParams ?? {},
908
+ ...s,
909
+ collectUserData: s.collectUserData ?? !1,
910
+ apiUrl: s.apiUrl ?? "https://api.open.cx/backend",
911
+ pollingInterval: s.pollingInterval ?? 3e3,
912
+ headers: s.headers ?? {},
913
+ queryParams: s.queryParams ?? {},
914
+ pathParams: s.pathParams ?? {},
669
915
  bot: {
670
- name: ((s = t.bot) == null ? void 0 : s.name) ?? "Bot",
671
- avatarUrl: (i = t.bot) == null ? void 0 : i.avatarUrl,
672
- id: ((m = t.bot) == null ? void 0 : m.id) ?? null,
673
- is_ai: ((n = t.bot) == null ? void 0 : n.is_ai) ?? !0
916
+ name: ((t = s.bot) == null ? void 0 : t.name) ?? "Bot",
917
+ avatarUrl: (n = s.bot) == null ? void 0 : n.avatarUrl,
918
+ id: ((f = s.bot) == null ? void 0 : f.id) ?? null,
919
+ is_ai: ((i = s.bot) == null ? void 0 : i.is_ai) ?? !0
674
920
  },
675
- contactToken: t.contactToken,
676
- debug: t.debug ?? !1,
677
- language: t.language ?? "en",
678
- user: t.user ?? {},
921
+ contactToken: s.contactToken,
922
+ debug: s.debug ?? !1,
923
+ language: s.language ?? "en",
924
+ user: s.user ?? {},
679
925
  soundEffectFiles: {
680
- messageArrived: ((a = t.soundEffectFiles) == null ? void 0 : a.messageArrived) ?? V.messageArrived
926
+ messageArrived: ((r = s.soundEffectFiles) == null ? void 0 : r.messageArrived) ?? Q.messageArrived
681
927
  },
682
928
  theme: {
683
- primaryColor: ((o = t.theme) == null ? void 0 : o.primaryColor) ?? $.primaryColor,
684
- triggerOffset: ((l = t.theme) == null ? void 0 : l.triggerOffset) ?? $.triggerOffset
929
+ primaryColor: ((l = s.theme) == null ? void 0 : l.primaryColor) ?? q.primaryColor,
930
+ triggerOffset: ((c = s.theme) == null ? void 0 : c.triggerOffset) ?? q.triggerOffset
685
931
  },
686
932
  settings: {
687
- persistSession: ((c = t.settings) == null ? void 0 : c.persistSession) ?? !1,
688
- useSoundEffects: ((r = t.settings) == null ? void 0 : r.useSoundEffects) ?? !1
933
+ persistSession: ((u = s.settings) == null ? void 0 : u.persistSession) ?? !1,
934
+ useSoundEffects: ((a = s.settings) == null ? void 0 : a.useSoundEffects) ?? !1
689
935
  }
690
936
  };
691
937
  return {
@@ -706,172 +952,123 @@ function ce(t) {
706
952
  getDebugMode: () => e.debug
707
953
  };
708
954
  }
709
- function Y(t = {}) {
710
- const e = [], s = [], i = [], m = async (n, a = {}) => {
711
- let o = {
712
- ...t,
713
- ...a,
955
+ function Z(s = {}, e = globalThis.fetch) {
956
+ const t = [], n = [], f = [], i = async (r, l = {}) => {
957
+ let c = {
958
+ ...s,
959
+ ...l,
714
960
  headers: {
715
- ...t.headers,
716
- ...a.headers
961
+ ...s.headers,
962
+ ...l.headers
717
963
  }
718
964
  };
719
965
  try {
720
- for (const u of e)
721
- o = await u(o);
722
- const l = o.params ? "?" + new URLSearchParams(o.params).toString() : "", c = o.baseURL ? `${o.baseURL}${n}${l}`.replace(/([^:]\/)\/+/g, "$1") : `${n}${l}`;
723
- let r = await fetch(c, o);
724
- for (const u of s)
725
- r = await u(r);
726
- return r;
727
- } catch (l) {
728
- let c = l;
729
- for (const r of i)
730
- c = await r(c);
731
- throw c;
966
+ for (const m of t)
967
+ c = await m(c);
968
+ const u = c.params ? "?" + new URLSearchParams(c.params).toString() : "", a = c.baseURL ? `${c.baseURL}${r}${u}`.replace(/([^:]\/)\/+/g, "$1") : `${r}${u}`;
969
+ let o = await e(a, c);
970
+ for (const m of n)
971
+ o = await m(o);
972
+ return o;
973
+ } catch (u) {
974
+ let a = u;
975
+ for (const o of f)
976
+ a = await o(a);
977
+ throw a;
732
978
  }
733
979
  };
734
- return m.interceptors = {
980
+ return i.interceptors = {
735
981
  request: {
736
- use: (n) => (e.push(n), e.length - 1),
737
- eject: (n) => {
738
- e.splice(n, 1);
982
+ use: (r) => (t.push(r), t.length - 1),
983
+ eject: (r) => {
984
+ t.splice(r, 1);
739
985
  }
740
986
  },
741
987
  response: {
742
- use: (n, a) => (s.push(n), a && i.push(a), s.length - 1),
743
- eject: (n) => {
744
- s.splice(n, 1), i.splice(n, 1);
988
+ use: (r, l) => (n.push(r), l && f.push(l), n.length - 1),
989
+ eject: (r) => {
990
+ n.splice(r, 1), f.splice(r, 1);
745
991
  }
746
992
  }
747
- }, m;
993
+ }, i;
748
994
  }
749
995
  var b;
750
- class le {
996
+ class pe {
751
997
  constructor(e) {
752
- M(this, b);
998
+ N(this, b);
753
999
  this.options = e;
754
- const s = this.options.config.user, i = {
1000
+ const t = this.options.config.user, n = {
755
1001
  claim: "",
756
1002
  value: ""
757
1003
  };
758
- s != null && s.email ? (i.claim = "email", i.value = s.email) : s != null && s.phone && (i.claim = "phone", i.value = s.phone);
759
- const m = {
1004
+ t != null && t.email ? (n.claim = "email", n.value = t.email) : t != null && t.phone && (n.claim = "phone", n.value = t.phone);
1005
+ const f = {
760
1006
  "X-Bot-Token": this.options.config.token,
761
- "X-Consumer-Id": `${i.claim}:${i.value}`,
1007
+ "X-Consumer-Id": `${n.claim}:${n.value}`,
762
1008
  "Content-Type": "application/json",
763
1009
  Accept: "application/json"
764
1010
  };
765
- this.options.config.contactToken && (m.Authorization = `Bearer ${this.options.config.contactToken}`), _(this, b, Y({
1011
+ this.options.config.contactToken && (f.Authorization = `Bearer ${this.options.config.contactToken}`), _(this, b, Z({
766
1012
  baseURL: `${this.options.config.apiUrl}/widget/v2`,
767
- headers: m
1013
+ headers: f
768
1014
  }));
769
1015
  }
770
1016
  async me() {
771
- return (await S(this, b).call(this, "/me")).json();
1017
+ return (await h(this, b).call(this, "/me")).json();
772
1018
  }
773
1019
  async widgetPrelude() {
774
- return (await S(this, b).call(this, "/prelude")).json();
1020
+ return (await h(this, b).call(this, "/prelude")).json();
775
1021
  }
776
- async handleMessage(e) {
777
- return (await S(this, b).call(this, "/chat/send", {
1022
+ async handleMessage(e, t) {
1023
+ return (await h(this, b).call(this, "/chat/send", {
778
1024
  method: "POST",
779
- body: JSON.stringify(e)
1025
+ body: JSON.stringify(e),
1026
+ signal: t
780
1027
  })).json();
781
1028
  }
782
- async getSessionHistory(e, s) {
783
- const i = new URLSearchParams({
784
- lastMessageTimestamp: s || ""
785
- }), m = `/session/history/${e}?${i.toString()}`;
786
- return (await S(this, b).call(this, m, {
1029
+ async getSessionHistory(e, t) {
1030
+ const n = new URLSearchParams({
1031
+ lastMessageTimestamp: t || ""
1032
+ }), f = `/session/history/${e}?${n.toString()}`;
1033
+ return (await h(this, b).call(this, f, {
787
1034
  method: "GET"
788
1035
  })).json();
789
1036
  }
790
1037
  async createSession() {
791
- return (await S(this, b).call(this, "/create-session", {
1038
+ return (await h(this, b).call(this, "/create-session", {
792
1039
  method: "POST"
793
1040
  })).json();
794
1041
  }
795
1042
  async getSession(e) {
796
- return (await S(this, b).call(this, `/session/${e}`, {
1043
+ return (await h(this, b).call(this, `/session/${e}`, {
797
1044
  method: "GET"
798
1045
  })).json();
799
1046
  }
800
1047
  }
801
1048
  b = new WeakMap();
802
- function ue(t = {}) {
803
- const {
804
- level: e = "info",
805
- prefix: s = "[openCx]",
806
- enabled: i = !0
807
- } = t;
808
- let m = e;
809
- const n = {
810
- debug: 0,
811
- info: 1,
812
- warn: 2,
813
- error: 3
814
- };
815
- function a(c) {
816
- return i && n[c] >= n[m];
817
- }
818
- function o(c) {
819
- return `${s} ${c}`;
820
- }
821
- function l(c) {
822
- return c.map((r) => {
823
- if (r instanceof Error)
824
- return {
825
- name: r.name,
826
- message: r.message,
827
- stack: r.stack
828
- };
829
- if (typeof r == "object")
830
- try {
831
- return JSON.stringify(r, null, 2);
832
- } catch {
833
- return r;
834
- }
835
- return r;
836
- });
837
- }
838
- return {
839
- debug(c, ...r) {
840
- a("debug") && console.debug(o(c), ...l(r));
841
- },
842
- info(c, ...r) {
843
- a("info") && console.info(o(c), ...l(r));
844
- },
845
- warn(c, ...r) {
846
- a("warn") && console.warn(o(c), ...l(r));
847
- },
848
- error(c, ...r) {
849
- a("error") && console.error(o(c), ...l(r));
850
- },
851
- setLevel(c) {
852
- m = c;
853
- }
854
- };
855
- }
856
1049
  export {
857
- le as ApiCaller,
858
- se as AuthenticationError,
859
- te as ConnectionError,
860
- ne as FileUploadError,
861
- G as LifecycleEvent,
862
- me as MessageTypeEnum,
863
- v as OpenCXError,
864
- C as PubSub,
865
- J as SessionError,
866
- re as SessionNotDefinedError,
867
- ae as TransportError,
868
- ge as chatAttachmentSchema,
869
- ie as createChat,
870
- ce as createConfig,
871
- oe as createContact,
1050
+ pe as ApiCaller,
1051
+ oe as AuthenticationError,
1052
+ ne as ConnectionError,
1053
+ V as ExternalIdNotDefinedError,
1054
+ ce as FileUploadError,
1055
+ J as LifecycleEvent,
1056
+ ye as MessageTypeEnum,
1057
+ I as OpenCXError,
1058
+ U as PubSub,
1059
+ X as SessionError,
1060
+ ie as SessionNotDefinedError,
1061
+ K as StorageNotAvailableError,
1062
+ le as TransportError,
1063
+ Pe as chatAttachmentSchema,
1064
+ ge as createChat,
1065
+ Se as createConfig,
1066
+ me as createContact,
872
1067
  ue as createLogger,
873
- ee as createPubSub,
874
- P as isStorageAvailable,
875
- O as safeStorageOperation
1068
+ ae as createPubSub,
1069
+ fe as isAudioAvailable,
1070
+ L as isStorageAvailable,
1071
+ de as safeAudioOperation,
1072
+ M as safeStorageOperation
876
1073
  };
877
1074
  //# sourceMappingURL=index.js.map