@opencx/widget 3.0.86 → 3.0.88

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 (54) hide show
  1. package/dist/designs.cjs +19 -47
  2. package/dist/designs.cjs.map +1 -1
  3. package/dist/designs.js +1297 -18475
  4. package/dist/designs.js.map +1 -1
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.js +6 -4
  8. package/dist/index.js.map +1 -1
  9. package/dist/react.cjs +1 -1
  10. package/dist/react.cjs.map +1 -1
  11. package/dist/react.js +20 -18
  12. package/dist/react.js.map +1 -1
  13. package/dist/src/designs/react/hooks/useCanvas.d.ts +3 -0
  14. package/dist/src/designs/react/hooks/useTheme.d.ts +6 -0
  15. package/dist/src/designs/react/index.d.ts +3 -2
  16. package/dist/src/designs/react/screens/chat/ChatCanvas.d.ts +2 -0
  17. package/dist/src/headless/core/__tests__/test-utils.d.ts +41 -2
  18. package/dist/src/headless/core/api/api-caller.d.ts +41 -2
  19. package/dist/src/headless/core/api/schema.d.ts +179 -75
  20. package/dist/src/headless/core/context/message.ctx.d.ts +1 -0
  21. package/dist/src/headless/core/context/session.ctx.d.ts +24 -0
  22. package/dist/src/headless/core/context/widget.ctx.d.ts +2 -0
  23. package/dist/src/headless/core/index.d.ts +1 -1
  24. package/dist/src/headless/core/types/dtos.d.ts +3 -2
  25. package/dist/src/headless/core/types/widget-config.d.ts +7 -0
  26. package/dist/src/headless/react/WidgetProvider.d.ts +4 -1
  27. package/dist/src/headless/react/hooks/useMessages.d.ts +1 -0
  28. package/dist/src/headless/react/hooks/useModes.d.ts +15 -0
  29. package/dist/src/headless/react/hooks/useSessions.d.ts +27 -0
  30. package/dist/src/headless/react/index.d.ts +2 -0
  31. package/dist/src/headless/react/types/modes.components.d.ts +11 -0
  32. package/dist/useModes-DSFNdOy3.cjs +2 -0
  33. package/dist/useModes-DSFNdOy3.cjs.map +1 -0
  34. package/dist/useModes-DleBrdDK.js +260 -0
  35. package/dist/useModes-DleBrdDK.js.map +1 -0
  36. package/dist/widget.ctx-CC3c7FPb.js +1542 -0
  37. package/dist/widget.ctx-CC3c7FPb.js.map +1 -0
  38. package/dist/widget.ctx-HuLTTMAM.cjs +5 -0
  39. package/dist/widget.ctx-HuLTTMAM.cjs.map +1 -0
  40. package/dist-embed/script.js +83 -83
  41. package/dist-embed/script.js.map +1 -1
  42. package/package.json +113 -52
  43. package/dist/is-exhaustive-9o43S91P.cjs +0 -2
  44. package/dist/is-exhaustive-9o43S91P.cjs.map +0 -1
  45. package/dist/is-exhaustive-DGJzQK69.js +0 -7
  46. package/dist/is-exhaustive-DGJzQK69.js.map +0 -1
  47. package/dist/useWidgetTrigger-Bi12WVrs.js +0 -1364
  48. package/dist/useWidgetTrigger-Bi12WVrs.js.map +0 -1
  49. package/dist/useWidgetTrigger-Bplu_1C-.cjs +0 -18
  50. package/dist/useWidgetTrigger-Bplu_1C-.cjs.map +0 -1
  51. package/dist/widget.ctx-DFFwNHvy.js +0 -673
  52. package/dist/widget.ctx-DFFwNHvy.js.map +0 -1
  53. package/dist/widget.ctx-oIT8sGvJ.cjs +0 -5
  54. package/dist/widget.ctx-oIT8sGvJ.cjs.map +0 -1
@@ -0,0 +1,1542 @@
1
+ const js = /\{[^{}]+\}/g, Ds = () => {
2
+ var r, n;
3
+ return typeof process == "object" && Number.parseInt((n = (r = process == null ? void 0 : process.versions) == null ? void 0 : r.node) == null ? void 0 : n.substring(0, 2)) >= 18 && process.versions.undici;
4
+ };
5
+ function Fs() {
6
+ return Math.random().toString(36).slice(2, 11);
7
+ }
8
+ function Ls(r) {
9
+ let {
10
+ baseUrl: n = "",
11
+ Request: o = globalThis.Request,
12
+ fetch: h = globalThis.fetch,
13
+ querySerializer: c,
14
+ bodySerializer: a,
15
+ headers: s,
16
+ requestInitExt: l = void 0,
17
+ ...d
18
+ } = { ...r };
19
+ l = Ds() ? l : void 0, n = ht(n);
20
+ const y = [];
21
+ async function g(p, f) {
22
+ const {
23
+ baseUrl: v,
24
+ fetch: F = h,
25
+ Request: j = o,
26
+ headers: q,
27
+ params: E = {},
28
+ parseAs: S = "json",
29
+ querySerializer: I,
30
+ bodySerializer: ee = a ?? zs,
31
+ body: _,
32
+ ...D
33
+ } = f || {};
34
+ v && (n = ht(v));
35
+ let k = typeof c == "function" ? c : ut(c);
36
+ I && (k = typeof I == "function" ? I : ut({
37
+ ...typeof c == "object" ? c : {},
38
+ ...I
39
+ }));
40
+ const le = _ === void 0 ? void 0 : ee(_), fe = (
41
+ // with no body, we should not to set Content-Type
42
+ le === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
43
+ le instanceof FormData ? {} : {
44
+ "Content-Type": "application/json"
45
+ }
46
+ ), de = {
47
+ redirect: "follow",
48
+ ...d,
49
+ ...D,
50
+ body: le,
51
+ headers: ks(fe, s, q, E.header)
52
+ };
53
+ let te, N, G = new o(qs(p, { baseUrl: n, params: E, querySerializer: k }), de);
54
+ for (const O in D)
55
+ O in G || (G[O] = D[O]);
56
+ if (y.length) {
57
+ te = Fs(), N = Object.freeze({
58
+ baseUrl: n,
59
+ fetch: F,
60
+ parseAs: S,
61
+ querySerializer: k,
62
+ bodySerializer: ee
63
+ });
64
+ for (const O of y)
65
+ if (O && typeof O == "object" && typeof O.onRequest == "function") {
66
+ const U = await O.onRequest({
67
+ request: G,
68
+ schemaPath: p,
69
+ params: E,
70
+ options: N,
71
+ id: te
72
+ });
73
+ if (U) {
74
+ if (!(U instanceof o))
75
+ throw new Error("onRequest: must return new Request() when modifying the request");
76
+ G = U;
77
+ }
78
+ }
79
+ }
80
+ let T;
81
+ try {
82
+ T = await F(G, l);
83
+ } catch (O) {
84
+ let U = O;
85
+ if (y.length)
86
+ for (let K = y.length - 1; K >= 0; K--) {
87
+ const ce = y[K];
88
+ if (ce && typeof ce == "object" && typeof ce.onError == "function") {
89
+ const se = await ce.onError({
90
+ request: G,
91
+ error: U,
92
+ schemaPath: p,
93
+ params: E,
94
+ options: N,
95
+ id: te
96
+ });
97
+ if (se) {
98
+ if (se instanceof Response) {
99
+ U = void 0, T = se;
100
+ break;
101
+ }
102
+ if (se instanceof Error) {
103
+ U = se;
104
+ continue;
105
+ }
106
+ throw new Error("onError: must return new Response() or instance of Error");
107
+ }
108
+ }
109
+ }
110
+ if (U)
111
+ throw U;
112
+ }
113
+ if (y.length)
114
+ for (let O = y.length - 1; O >= 0; O--) {
115
+ const U = y[O];
116
+ if (U && typeof U == "object" && typeof U.onResponse == "function") {
117
+ const K = await U.onResponse({
118
+ request: G,
119
+ response: T,
120
+ schemaPath: p,
121
+ params: E,
122
+ options: N,
123
+ id: te
124
+ });
125
+ if (K) {
126
+ if (!(K instanceof Response))
127
+ throw new Error("onResponse: must return new Response() when modifying the response");
128
+ T = K;
129
+ }
130
+ }
131
+ }
132
+ if (T.status === 204 || T.headers.get("Content-Length") === "0")
133
+ return T.ok ? { data: void 0, response: T } : { error: void 0, response: T };
134
+ if (T.ok)
135
+ return S === "stream" ? { data: T.body, response: T } : { data: await T[S](), response: T };
136
+ let ge = await T.text();
137
+ try {
138
+ ge = JSON.parse(ge);
139
+ } catch {
140
+ }
141
+ return { error: ge, response: T };
142
+ }
143
+ return {
144
+ request(p, f, v) {
145
+ return g(f, { ...v, method: p.toUpperCase() });
146
+ },
147
+ /** Call a GET endpoint */
148
+ GET(p, f) {
149
+ return g(p, { ...f, method: "GET" });
150
+ },
151
+ /** Call a PUT endpoint */
152
+ PUT(p, f) {
153
+ return g(p, { ...f, method: "PUT" });
154
+ },
155
+ /** Call a POST endpoint */
156
+ POST(p, f) {
157
+ return g(p, { ...f, method: "POST" });
158
+ },
159
+ /** Call a DELETE endpoint */
160
+ DELETE(p, f) {
161
+ return g(p, { ...f, method: "DELETE" });
162
+ },
163
+ /** Call a OPTIONS endpoint */
164
+ OPTIONS(p, f) {
165
+ return g(p, { ...f, method: "OPTIONS" });
166
+ },
167
+ /** Call a HEAD endpoint */
168
+ HEAD(p, f) {
169
+ return g(p, { ...f, method: "HEAD" });
170
+ },
171
+ /** Call a PATCH endpoint */
172
+ PATCH(p, f) {
173
+ return g(p, { ...f, method: "PATCH" });
174
+ },
175
+ /** Call a TRACE endpoint */
176
+ TRACE(p, f) {
177
+ return g(p, { ...f, method: "TRACE" });
178
+ },
179
+ /** Register middleware */
180
+ use(...p) {
181
+ for (const f of p)
182
+ if (f) {
183
+ if (typeof f != "object" || !("onRequest" in f || "onResponse" in f || "onError" in f))
184
+ throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
185
+ y.push(f);
186
+ }
187
+ },
188
+ /** Unregister middleware */
189
+ eject(...p) {
190
+ for (const f of p) {
191
+ const v = y.indexOf(f);
192
+ v !== -1 && y.splice(v, 1);
193
+ }
194
+ }
195
+ };
196
+ }
197
+ function Re(r, n, o) {
198
+ if (n == null)
199
+ return "";
200
+ if (typeof n == "object")
201
+ throw new Error(
202
+ "Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these."
203
+ );
204
+ return `${r}=${(o == null ? void 0 : o.allowReserved) === !0 ? n : encodeURIComponent(n)}`;
205
+ }
206
+ function pt(r, n, o) {
207
+ if (!n || typeof n != "object")
208
+ return "";
209
+ const h = [], c = {
210
+ simple: ",",
211
+ label: ".",
212
+ matrix: ";"
213
+ }[o.style] || "&";
214
+ if (o.style !== "deepObject" && o.explode === !1) {
215
+ for (const l in n)
216
+ h.push(l, o.allowReserved === !0 ? n[l] : encodeURIComponent(n[l]));
217
+ const s = h.join(",");
218
+ switch (o.style) {
219
+ case "form":
220
+ return `${r}=${s}`;
221
+ case "label":
222
+ return `.${s}`;
223
+ case "matrix":
224
+ return `;${r}=${s}`;
225
+ default:
226
+ return s;
227
+ }
228
+ }
229
+ for (const s in n) {
230
+ const l = o.style === "deepObject" ? `${r}[${s}]` : s;
231
+ h.push(Re(l, n[s], o));
232
+ }
233
+ const a = h.join(c);
234
+ return o.style === "label" || o.style === "matrix" ? `${c}${a}` : a;
235
+ }
236
+ function yt(r, n, o) {
237
+ if (!Array.isArray(n))
238
+ return "";
239
+ if (o.explode === !1) {
240
+ const a = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[o.style] || ",", s = (o.allowReserved === !0 ? n : n.map((l) => encodeURIComponent(l))).join(a);
241
+ switch (o.style) {
242
+ case "simple":
243
+ return s;
244
+ case "label":
245
+ return `.${s}`;
246
+ case "matrix":
247
+ return `;${r}=${s}`;
248
+ default:
249
+ return `${r}=${s}`;
250
+ }
251
+ }
252
+ const h = { simple: ",", label: ".", matrix: ";" }[o.style] || "&", c = [];
253
+ for (const a of n)
254
+ o.style === "simple" || o.style === "label" ? c.push(o.allowReserved === !0 ? a : encodeURIComponent(a)) : c.push(Re(r, a, o));
255
+ return o.style === "label" || o.style === "matrix" ? `${h}${c.join(h)}` : c.join(h);
256
+ }
257
+ function ut(r) {
258
+ return function(o) {
259
+ const h = [];
260
+ if (o && typeof o == "object")
261
+ for (const c in o) {
262
+ const a = o[c];
263
+ if (a != null) {
264
+ if (Array.isArray(a)) {
265
+ if (a.length === 0)
266
+ continue;
267
+ h.push(
268
+ yt(c, a, {
269
+ style: "form",
270
+ explode: !0,
271
+ ...r == null ? void 0 : r.array,
272
+ allowReserved: (r == null ? void 0 : r.allowReserved) || !1
273
+ })
274
+ );
275
+ continue;
276
+ }
277
+ if (typeof a == "object") {
278
+ h.push(
279
+ pt(c, a, {
280
+ style: "deepObject",
281
+ explode: !0,
282
+ ...r == null ? void 0 : r.object,
283
+ allowReserved: (r == null ? void 0 : r.allowReserved) || !1
284
+ })
285
+ );
286
+ continue;
287
+ }
288
+ h.push(Re(c, a, r));
289
+ }
290
+ }
291
+ return h.join("&");
292
+ };
293
+ }
294
+ function $s(r, n) {
295
+ let o = r;
296
+ for (const h of r.match(js) ?? []) {
297
+ let c = h.substring(1, h.length - 1), a = !1, s = "simple";
298
+ if (c.endsWith("*") && (a = !0, c = c.substring(0, c.length - 1)), c.startsWith(".") ? (s = "label", c = c.substring(1)) : c.startsWith(";") && (s = "matrix", c = c.substring(1)), !n || n[c] === void 0 || n[c] === null)
299
+ continue;
300
+ const l = n[c];
301
+ if (Array.isArray(l)) {
302
+ o = o.replace(h, yt(c, l, { style: s, explode: a }));
303
+ continue;
304
+ }
305
+ if (typeof l == "object") {
306
+ o = o.replace(h, pt(c, l, { style: s, explode: a }));
307
+ continue;
308
+ }
309
+ if (s === "matrix") {
310
+ o = o.replace(h, `;${Re(c, l)}`);
311
+ continue;
312
+ }
313
+ o = o.replace(h, s === "label" ? `.${encodeURIComponent(l)}` : encodeURIComponent(l));
314
+ }
315
+ return o;
316
+ }
317
+ function zs(r) {
318
+ return r instanceof FormData ? r : JSON.stringify(r);
319
+ }
320
+ function qs(r, n) {
321
+ var c;
322
+ let o = `${n.baseUrl}${r}`;
323
+ (c = n.params) != null && c.path && (o = $s(o, n.params.path));
324
+ let h = n.querySerializer(n.params.query ?? {});
325
+ return h.startsWith("?") && (h = h.substring(1)), h && (o += `?${h}`), o;
326
+ }
327
+ function ks(...r) {
328
+ const n = new Headers();
329
+ for (const o of r) {
330
+ if (!o || typeof o != "object")
331
+ continue;
332
+ const h = o instanceof Headers ? o.entries() : Object.entries(o);
333
+ for (const [c, a] of h)
334
+ if (a === null)
335
+ n.delete(c);
336
+ else if (Array.isArray(a))
337
+ for (const s of a)
338
+ n.append(c, s);
339
+ else a !== void 0 && n.set(c, a);
340
+ }
341
+ return n;
342
+ }
343
+ function ht(r) {
344
+ return r.endsWith("/") ? r.substring(0, r.length - 1) : r;
345
+ }
346
+ const Bs = (r) => {
347
+ console.log(r.error);
348
+ }, Hs = (r) => {
349
+ const n = Ls({
350
+ baseUrl: r.baseUrl
351
+ }), o = {
352
+ onRequest: r.onRequest,
353
+ onResponse: r.onResponse,
354
+ onError: r.onError || Bs
355
+ };
356
+ return n.use(o), n;
357
+ };
358
+ class ft {
359
+ constructor({ config: n }) {
360
+ var c, a;
361
+ this.userToken = null, this.constructClientOptions = (s) => {
362
+ const l = this.config.apiUrl || "https://api.open.cx", d = {
363
+ "X-Bot-Token": this.config.token,
364
+ "Content-Type": "application/json",
365
+ Accept: "application/json",
366
+ Authorization: s ? `Bearer ${s}` : void 0
367
+ };
368
+ return { baseUrl: l, headers: d };
369
+ }, this.createOpenAPIClient = ({
370
+ baseUrl: s,
371
+ headers: l
372
+ }) => Hs({
373
+ baseUrl: s,
374
+ onRequest: ({ request: d }) => {
375
+ Object.entries(l).forEach(([y, g]) => {
376
+ g && d.headers.set(y, g);
377
+ });
378
+ }
379
+ }), this.setAuthToken = (s) => {
380
+ this.userToken = s;
381
+ const { baseUrl: l, headers: d } = this.constructClientOptions(s);
382
+ this.client = this.createOpenAPIClient({ baseUrl: l, headers: d });
383
+ }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
384
+ params: { header: { "X-Bot-Token": this.config.token } }
385
+ }), this.widgetPrelude = async () => await this.client.GET("/backend/widget/v2/prelude", {
386
+ params: { header: { "X-Bot-Token": this.config.token } }
387
+ }), this.sendMessage = async (s, l) => await this.client.POST("/backend/widget/v2/chat/send", {
388
+ body: s,
389
+ signal: l
390
+ }), this.createUnverifiedContact = async (s) => await this.client.POST(
391
+ "/backend/widget/v2/contact/create-unverified",
392
+ {
393
+ params: { header: { "x-bot-token": this.config.token } },
394
+ body: s
395
+ }
396
+ ), this.createSession = async (s) => await this.client.POST("/backend/widget/v2/create-session", {
397
+ body: s
398
+ }), this.pollSessionAndHistory = async ({
399
+ sessionId: s,
400
+ lastMessageTimestamp: l,
401
+ abortSignal: d
402
+ }) => {
403
+ const y = l ? { lastMessageTimestamp: l } : void 0;
404
+ return await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
405
+ params: { path: { sessionId: s }, query: y },
406
+ signal: d
407
+ });
408
+ }, this.getSessions = async ({
409
+ cursor: s,
410
+ filters: l,
411
+ abortSignal: d
412
+ }) => await this.client.GET("/backend/widget/v2/sessions", {
413
+ params: { query: { cursor: s, filters: JSON.stringify(l) } },
414
+ signal: d
415
+ }), this.uploadFile = async ({
416
+ file: s,
417
+ abortSignal: l,
418
+ onProgress: d
419
+ }) => new Promise((y, g) => {
420
+ var E;
421
+ const p = new FormData();
422
+ p.append("file", s);
423
+ const f = new XMLHttpRequest();
424
+ if (l && (l.addEventListener("abort", () => {
425
+ f.abort(), g(new DOMException("Aborted", "AbortError"));
426
+ }), l.aborted)) {
427
+ g(new DOMException("Aborted", "AbortError"));
428
+ return;
429
+ }
430
+ f.upload.addEventListener("progress", (S) => {
431
+ if (S.lengthComputable && d) {
432
+ const I = Math.round(S.loaded / S.total * 100);
433
+ d(I);
434
+ }
435
+ }), f.addEventListener("load", () => {
436
+ if (f.status >= 200 && f.status < 300)
437
+ try {
438
+ const S = JSON.parse(f.responseText);
439
+ y(S);
440
+ } catch (S) {
441
+ g(new Error(`Failed to parse response: ${S}`));
442
+ }
443
+ else
444
+ g(new Error(`Upload failed with status: ${f.status}`));
445
+ }), f.addEventListener("error", () => {
446
+ g(new Error("Network error occurred"));
447
+ }), f.addEventListener("timeout", () => {
448
+ g(new Error("Upload timed out"));
449
+ });
450
+ const { baseUrl: v } = this.constructClientOptions(this.userToken), j = `${v}/backend/widget/v2/upload`;
451
+ f.open("POST", j), f.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((E = this.config.user) == null ? void 0 : E.token) ? f.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), f.send(p);
452
+ }), this.vote = async (s) => await this.client.POST("/backend/widget/v2/chat/vote", { body: s }), this.resolveSession = async (s, l) => await this.client.POST("/backend/widget/v2/session/resolve", {
453
+ body: s,
454
+ signal: l
455
+ }), this.createStateCheckpoint = async (s) => await this.client.POST("/backend/widget/v2/checkpoint", {
456
+ body: s
457
+ }), this.config = n, this.userToken = ((c = n.user) == null ? void 0 : c.token) || null;
458
+ const { baseUrl: o, headers: h } = this.constructClientOptions(
459
+ (a = n.user) == null ? void 0 : a.token
460
+ );
461
+ this.client = this.createOpenAPIClient({ baseUrl: o, headers: h });
462
+ }
463
+ }
464
+ var Ie = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
465
+ function Ns(r) {
466
+ return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r;
467
+ }
468
+ var Pe = { exports: {} };
469
+ Pe.exports;
470
+ (function(r, n) {
471
+ var o = 200, h = "__lodash_hash_undefined__", c = 1, a = 2, s = 9007199254740991, l = "[object Arguments]", d = "[object Array]", y = "[object AsyncFunction]", g = "[object Boolean]", p = "[object Date]", f = "[object Error]", v = "[object Function]", F = "[object GeneratorFunction]", j = "[object Map]", q = "[object Number]", E = "[object Null]", S = "[object Object]", I = "[object Promise]", ee = "[object Proxy]", _ = "[object RegExp]", D = "[object Set]", k = "[object String]", le = "[object Symbol]", fe = "[object Undefined]", de = "[object WeakMap]", te = "[object ArrayBuffer]", N = "[object DataView]", G = "[object Float32Array]", T = "[object Float64Array]", ge = "[object Int8Array]", O = "[object Int16Array]", U = "[object Int32Array]", K = "[object Uint8Array]", ce = "[object Uint8ClampedArray]", se = "[object Uint16Array]", bt = "[object Uint32Array]", Ct = /[\\^$.*+?()[\]{}|]/g, wt = /^\[object .+?Constructor\]$/, vt = /^(?:0|[1-9]\d*)$/, b = {};
472
+ b[G] = b[T] = b[ge] = b[O] = b[U] = b[K] = b[ce] = b[se] = b[bt] = !0, b[l] = b[d] = b[te] = b[g] = b[N] = b[p] = b[f] = b[v] = b[j] = b[q] = b[S] = b[_] = b[D] = b[k] = b[de] = !1;
473
+ var qe = typeof Ie == "object" && Ie && Ie.Object === Object && Ie, xt = typeof self == "object" && self && self.Object === Object && self, W = qe || xt || Function("return this")(), ke = n && !n.nodeType && n, Be = ke && !0 && r && !r.nodeType && r, He = Be && Be.exports === ke, Ee = He && qe.process, Ne = function() {
474
+ try {
475
+ return Ee && Ee.binding && Ee.binding("util");
476
+ } catch {
477
+ }
478
+ }(), Ge = Ne && Ne.isTypedArray;
479
+ function _t(e, t) {
480
+ for (var i = -1, u = e == null ? 0 : e.length, C = 0, m = []; ++i < u; ) {
481
+ var x = e[i];
482
+ t(x, i, e) && (m[C++] = x);
483
+ }
484
+ return m;
485
+ }
486
+ function Tt(e, t) {
487
+ for (var i = -1, u = t.length, C = e.length; ++i < u; )
488
+ e[C + i] = t[i];
489
+ return e;
490
+ }
491
+ function At(e, t) {
492
+ for (var i = -1, u = e == null ? 0 : e.length; ++i < u; )
493
+ if (t(e[i], i, e))
494
+ return !0;
495
+ return !1;
496
+ }
497
+ function It(e, t) {
498
+ for (var i = -1, u = Array(e); ++i < e; )
499
+ u[i] = t(i);
500
+ return u;
501
+ }
502
+ function Pt(e) {
503
+ return function(t) {
504
+ return e(t);
505
+ };
506
+ }
507
+ function Rt(e, t) {
508
+ return e.has(t);
509
+ }
510
+ function Et(e, t) {
511
+ return e == null ? void 0 : e[t];
512
+ }
513
+ function Ot(e) {
514
+ var t = -1, i = Array(e.size);
515
+ return e.forEach(function(u, C) {
516
+ i[++t] = [C, u];
517
+ }), i;
518
+ }
519
+ function Ut(e, t) {
520
+ return function(i) {
521
+ return e(t(i));
522
+ };
523
+ }
524
+ function Mt(e) {
525
+ var t = -1, i = Array(e.size);
526
+ return e.forEach(function(u) {
527
+ i[++t] = u;
528
+ }), i;
529
+ }
530
+ var jt = Array.prototype, Dt = Function.prototype, be = Object.prototype, Oe = W["__core-js_shared__"], Ke = Dt.toString, H = be.hasOwnProperty, We = function() {
531
+ var e = /[^.]+$/.exec(Oe && Oe.keys && Oe.keys.IE_PROTO || "");
532
+ return e ? "Symbol(src)_1." + e : "";
533
+ }(), Xe = be.toString, Ft = RegExp(
534
+ "^" + Ke.call(H).replace(Ct, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
535
+ ), Je = He ? W.Buffer : void 0, Ce = W.Symbol, Ye = W.Uint8Array, Qe = be.propertyIsEnumerable, Lt = jt.splice, ne = Ce ? Ce.toStringTag : void 0, Ze = Object.getOwnPropertySymbols, $t = Je ? Je.isBuffer : void 0, zt = Ut(Object.keys, Object), Ue = ue(W, "DataView"), pe = ue(W, "Map"), Me = ue(W, "Promise"), je = ue(W, "Set"), De = ue(W, "WeakMap"), ye = ue(Object, "create"), qt = ae(Ue), kt = ae(pe), Bt = ae(Me), Ht = ae(je), Nt = ae(De), Ve = Ce ? Ce.prototype : void 0, Fe = Ve ? Ve.valueOf : void 0;
536
+ function ie(e) {
537
+ var t = -1, i = e == null ? 0 : e.length;
538
+ for (this.clear(); ++t < i; ) {
539
+ var u = e[t];
540
+ this.set(u[0], u[1]);
541
+ }
542
+ }
543
+ function Gt() {
544
+ this.__data__ = ye ? ye(null) : {}, this.size = 0;
545
+ }
546
+ function Kt(e) {
547
+ var t = this.has(e) && delete this.__data__[e];
548
+ return this.size -= t ? 1 : 0, t;
549
+ }
550
+ function Wt(e) {
551
+ var t = this.__data__;
552
+ if (ye) {
553
+ var i = t[e];
554
+ return i === h ? void 0 : i;
555
+ }
556
+ return H.call(t, e) ? t[e] : void 0;
557
+ }
558
+ function Xt(e) {
559
+ var t = this.__data__;
560
+ return ye ? t[e] !== void 0 : H.call(t, e);
561
+ }
562
+ function Jt(e, t) {
563
+ var i = this.__data__;
564
+ return this.size += this.has(e) ? 0 : 1, i[e] = ye && t === void 0 ? h : t, this;
565
+ }
566
+ ie.prototype.clear = Gt, ie.prototype.delete = Kt, ie.prototype.get = Wt, ie.prototype.has = Xt, ie.prototype.set = Jt;
567
+ function X(e) {
568
+ var t = -1, i = e == null ? 0 : e.length;
569
+ for (this.clear(); ++t < i; ) {
570
+ var u = e[t];
571
+ this.set(u[0], u[1]);
572
+ }
573
+ }
574
+ function Yt() {
575
+ this.__data__ = [], this.size = 0;
576
+ }
577
+ function Qt(e) {
578
+ var t = this.__data__, i = ve(t, e);
579
+ if (i < 0)
580
+ return !1;
581
+ var u = t.length - 1;
582
+ return i == u ? t.pop() : Lt.call(t, i, 1), --this.size, !0;
583
+ }
584
+ function Zt(e) {
585
+ var t = this.__data__, i = ve(t, e);
586
+ return i < 0 ? void 0 : t[i][1];
587
+ }
588
+ function Vt(e) {
589
+ return ve(this.__data__, e) > -1;
590
+ }
591
+ function es(e, t) {
592
+ var i = this.__data__, u = ve(i, e);
593
+ return u < 0 ? (++this.size, i.push([e, t])) : i[u][1] = t, this;
594
+ }
595
+ X.prototype.clear = Yt, X.prototype.delete = Qt, X.prototype.get = Zt, X.prototype.has = Vt, X.prototype.set = es;
596
+ function re(e) {
597
+ var t = -1, i = e == null ? 0 : e.length;
598
+ for (this.clear(); ++t < i; ) {
599
+ var u = e[t];
600
+ this.set(u[0], u[1]);
601
+ }
602
+ }
603
+ function ts() {
604
+ this.size = 0, this.__data__ = {
605
+ hash: new ie(),
606
+ map: new (pe || X)(),
607
+ string: new ie()
608
+ };
609
+ }
610
+ function ss(e) {
611
+ var t = xe(this, e).delete(e);
612
+ return this.size -= t ? 1 : 0, t;
613
+ }
614
+ function ns(e) {
615
+ return xe(this, e).get(e);
616
+ }
617
+ function is(e) {
618
+ return xe(this, e).has(e);
619
+ }
620
+ function rs(e, t) {
621
+ var i = xe(this, e), u = i.size;
622
+ return i.set(e, t), this.size += i.size == u ? 0 : 1, this;
623
+ }
624
+ re.prototype.clear = ts, re.prototype.delete = ss, re.prototype.get = ns, re.prototype.has = is, re.prototype.set = rs;
625
+ function we(e) {
626
+ var t = -1, i = e == null ? 0 : e.length;
627
+ for (this.__data__ = new re(); ++t < i; )
628
+ this.add(e[t]);
629
+ }
630
+ function as(e) {
631
+ return this.__data__.set(e, h), this;
632
+ }
633
+ function os(e) {
634
+ return this.__data__.has(e);
635
+ }
636
+ we.prototype.add = we.prototype.push = as, we.prototype.has = os;
637
+ function Q(e) {
638
+ var t = this.__data__ = new X(e);
639
+ this.size = t.size;
640
+ }
641
+ function ls() {
642
+ this.__data__ = new X(), this.size = 0;
643
+ }
644
+ function cs(e) {
645
+ var t = this.__data__, i = t.delete(e);
646
+ return this.size = t.size, i;
647
+ }
648
+ function us(e) {
649
+ return this.__data__.get(e);
650
+ }
651
+ function hs(e) {
652
+ return this.__data__.has(e);
653
+ }
654
+ function fs(e, t) {
655
+ var i = this.__data__;
656
+ if (i instanceof X) {
657
+ var u = i.__data__;
658
+ if (!pe || u.length < o - 1)
659
+ return u.push([e, t]), this.size = ++i.size, this;
660
+ i = this.__data__ = new re(u);
661
+ }
662
+ return i.set(e, t), this.size = i.size, this;
663
+ }
664
+ Q.prototype.clear = ls, Q.prototype.delete = cs, Q.prototype.get = us, Q.prototype.has = hs, Q.prototype.set = fs;
665
+ function ds(e, t) {
666
+ var i = _e(e), u = !i && Ps(e), C = !i && !u && Le(e), m = !i && !u && !C && lt(e), x = i || u || C || m, A = x ? It(e.length, String) : [], P = A.length;
667
+ for (var w in e)
668
+ H.call(e, w) && !(x && // Safari 9 has enumerable `arguments.length` in strict mode.
669
+ (w == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
670
+ C && (w == "offset" || w == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
671
+ m && (w == "buffer" || w == "byteLength" || w == "byteOffset") || // Skip index properties.
672
+ xs(w, P))) && A.push(w);
673
+ return A;
674
+ }
675
+ function ve(e, t) {
676
+ for (var i = e.length; i--; )
677
+ if (it(e[i][0], t))
678
+ return i;
679
+ return -1;
680
+ }
681
+ function gs(e, t, i) {
682
+ var u = t(e);
683
+ return _e(e) ? u : Tt(u, i(e));
684
+ }
685
+ function me(e) {
686
+ return e == null ? e === void 0 ? fe : E : ne && ne in Object(e) ? ws(e) : Is(e);
687
+ }
688
+ function et(e) {
689
+ return Se(e) && me(e) == l;
690
+ }
691
+ function tt(e, t, i, u, C) {
692
+ return e === t ? !0 : e == null || t == null || !Se(e) && !Se(t) ? e !== e && t !== t : ps(e, t, i, u, tt, C);
693
+ }
694
+ function ps(e, t, i, u, C, m) {
695
+ var x = _e(e), A = _e(t), P = x ? d : Z(e), w = A ? d : Z(t);
696
+ P = P == l ? S : P, w = w == l ? S : w;
697
+ var L = P == S, B = w == S, M = P == w;
698
+ if (M && Le(e)) {
699
+ if (!Le(t))
700
+ return !1;
701
+ x = !0, L = !1;
702
+ }
703
+ if (M && !L)
704
+ return m || (m = new Q()), x || lt(e) ? st(e, t, i, u, C, m) : bs(e, t, P, i, u, C, m);
705
+ if (!(i & c)) {
706
+ var $ = L && H.call(e, "__wrapped__"), z = B && H.call(t, "__wrapped__");
707
+ if ($ || z) {
708
+ var V = $ ? e.value() : e, J = z ? t.value() : t;
709
+ return m || (m = new Q()), C(V, J, i, u, m);
710
+ }
711
+ }
712
+ return M ? (m || (m = new Q()), Cs(e, t, i, u, C, m)) : !1;
713
+ }
714
+ function ys(e) {
715
+ if (!ot(e) || Ts(e))
716
+ return !1;
717
+ var t = rt(e) ? Ft : wt;
718
+ return t.test(ae(e));
719
+ }
720
+ function ms(e) {
721
+ return Se(e) && at(e.length) && !!b[me(e)];
722
+ }
723
+ function Ss(e) {
724
+ if (!As(e))
725
+ return zt(e);
726
+ var t = [];
727
+ for (var i in Object(e))
728
+ H.call(e, i) && i != "constructor" && t.push(i);
729
+ return t;
730
+ }
731
+ function st(e, t, i, u, C, m) {
732
+ var x = i & c, A = e.length, P = t.length;
733
+ if (A != P && !(x && P > A))
734
+ return !1;
735
+ var w = m.get(e);
736
+ if (w && m.get(t))
737
+ return w == t;
738
+ var L = -1, B = !0, M = i & a ? new we() : void 0;
739
+ for (m.set(e, t), m.set(t, e); ++L < A; ) {
740
+ var $ = e[L], z = t[L];
741
+ if (u)
742
+ var V = x ? u(z, $, L, t, e, m) : u($, z, L, e, t, m);
743
+ if (V !== void 0) {
744
+ if (V)
745
+ continue;
746
+ B = !1;
747
+ break;
748
+ }
749
+ if (M) {
750
+ if (!At(t, function(J, oe) {
751
+ if (!Rt(M, oe) && ($ === J || C($, J, i, u, m)))
752
+ return M.push(oe);
753
+ })) {
754
+ B = !1;
755
+ break;
756
+ }
757
+ } else if (!($ === z || C($, z, i, u, m))) {
758
+ B = !1;
759
+ break;
760
+ }
761
+ }
762
+ return m.delete(e), m.delete(t), B;
763
+ }
764
+ function bs(e, t, i, u, C, m, x) {
765
+ switch (i) {
766
+ case N:
767
+ if (e.byteLength != t.byteLength || e.byteOffset != t.byteOffset)
768
+ return !1;
769
+ e = e.buffer, t = t.buffer;
770
+ case te:
771
+ return !(e.byteLength != t.byteLength || !m(new Ye(e), new Ye(t)));
772
+ case g:
773
+ case p:
774
+ case q:
775
+ return it(+e, +t);
776
+ case f:
777
+ return e.name == t.name && e.message == t.message;
778
+ case _:
779
+ case k:
780
+ return e == t + "";
781
+ case j:
782
+ var A = Ot;
783
+ case D:
784
+ var P = u & c;
785
+ if (A || (A = Mt), e.size != t.size && !P)
786
+ return !1;
787
+ var w = x.get(e);
788
+ if (w)
789
+ return w == t;
790
+ u |= a, x.set(e, t);
791
+ var L = st(A(e), A(t), u, C, m, x);
792
+ return x.delete(e), L;
793
+ case le:
794
+ if (Fe)
795
+ return Fe.call(e) == Fe.call(t);
796
+ }
797
+ return !1;
798
+ }
799
+ function Cs(e, t, i, u, C, m) {
800
+ var x = i & c, A = nt(e), P = A.length, w = nt(t), L = w.length;
801
+ if (P != L && !x)
802
+ return !1;
803
+ for (var B = P; B--; ) {
804
+ var M = A[B];
805
+ if (!(x ? M in t : H.call(t, M)))
806
+ return !1;
807
+ }
808
+ var $ = m.get(e);
809
+ if ($ && m.get(t))
810
+ return $ == t;
811
+ var z = !0;
812
+ m.set(e, t), m.set(t, e);
813
+ for (var V = x; ++B < P; ) {
814
+ M = A[B];
815
+ var J = e[M], oe = t[M];
816
+ if (u)
817
+ var ct = x ? u(oe, J, M, t, e, m) : u(J, oe, M, e, t, m);
818
+ if (!(ct === void 0 ? J === oe || C(J, oe, i, u, m) : ct)) {
819
+ z = !1;
820
+ break;
821
+ }
822
+ V || (V = M == "constructor");
823
+ }
824
+ if (z && !V) {
825
+ var Te = e.constructor, Ae = t.constructor;
826
+ Te != Ae && "constructor" in e && "constructor" in t && !(typeof Te == "function" && Te instanceof Te && typeof Ae == "function" && Ae instanceof Ae) && (z = !1);
827
+ }
828
+ return m.delete(e), m.delete(t), z;
829
+ }
830
+ function nt(e) {
831
+ return gs(e, Os, vs);
832
+ }
833
+ function xe(e, t) {
834
+ var i = e.__data__;
835
+ return _s(t) ? i[typeof t == "string" ? "string" : "hash"] : i.map;
836
+ }
837
+ function ue(e, t) {
838
+ var i = Et(e, t);
839
+ return ys(i) ? i : void 0;
840
+ }
841
+ function ws(e) {
842
+ var t = H.call(e, ne), i = e[ne];
843
+ try {
844
+ e[ne] = void 0;
845
+ var u = !0;
846
+ } catch {
847
+ }
848
+ var C = Xe.call(e);
849
+ return u && (t ? e[ne] = i : delete e[ne]), C;
850
+ }
851
+ var vs = Ze ? function(e) {
852
+ return e == null ? [] : (e = Object(e), _t(Ze(e), function(t) {
853
+ return Qe.call(e, t);
854
+ }));
855
+ } : Us, Z = me;
856
+ (Ue && Z(new Ue(new ArrayBuffer(1))) != N || pe && Z(new pe()) != j || Me && Z(Me.resolve()) != I || je && Z(new je()) != D || De && Z(new De()) != de) && (Z = function(e) {
857
+ var t = me(e), i = t == S ? e.constructor : void 0, u = i ? ae(i) : "";
858
+ if (u)
859
+ switch (u) {
860
+ case qt:
861
+ return N;
862
+ case kt:
863
+ return j;
864
+ case Bt:
865
+ return I;
866
+ case Ht:
867
+ return D;
868
+ case Nt:
869
+ return de;
870
+ }
871
+ return t;
872
+ });
873
+ function xs(e, t) {
874
+ return t = t ?? s, !!t && (typeof e == "number" || vt.test(e)) && e > -1 && e % 1 == 0 && e < t;
875
+ }
876
+ function _s(e) {
877
+ var t = typeof e;
878
+ return t == "string" || t == "number" || t == "symbol" || t == "boolean" ? e !== "__proto__" : e === null;
879
+ }
880
+ function Ts(e) {
881
+ return !!We && We in e;
882
+ }
883
+ function As(e) {
884
+ var t = e && e.constructor, i = typeof t == "function" && t.prototype || be;
885
+ return e === i;
886
+ }
887
+ function Is(e) {
888
+ return Xe.call(e);
889
+ }
890
+ function ae(e) {
891
+ if (e != null) {
892
+ try {
893
+ return Ke.call(e);
894
+ } catch {
895
+ }
896
+ try {
897
+ return e + "";
898
+ } catch {
899
+ }
900
+ }
901
+ return "";
902
+ }
903
+ function it(e, t) {
904
+ return e === t || e !== e && t !== t;
905
+ }
906
+ var Ps = et(/* @__PURE__ */ function() {
907
+ return arguments;
908
+ }()) ? et : function(e) {
909
+ return Se(e) && H.call(e, "callee") && !Qe.call(e, "callee");
910
+ }, _e = Array.isArray;
911
+ function Rs(e) {
912
+ return e != null && at(e.length) && !rt(e);
913
+ }
914
+ var Le = $t || Ms;
915
+ function Es(e, t) {
916
+ return tt(e, t);
917
+ }
918
+ function rt(e) {
919
+ if (!ot(e))
920
+ return !1;
921
+ var t = me(e);
922
+ return t == v || t == F || t == y || t == ee;
923
+ }
924
+ function at(e) {
925
+ return typeof e == "number" && e > -1 && e % 1 == 0 && e <= s;
926
+ }
927
+ function ot(e) {
928
+ var t = typeof e;
929
+ return e != null && (t == "object" || t == "function");
930
+ }
931
+ function Se(e) {
932
+ return e != null && typeof e == "object";
933
+ }
934
+ var lt = Ge ? Pt(Ge) : ms;
935
+ function Os(e) {
936
+ return Rs(e) ? ds(e) : Ss(e);
937
+ }
938
+ function Us() {
939
+ return [];
940
+ }
941
+ function Ms() {
942
+ return !1;
943
+ }
944
+ r.exports = Es;
945
+ })(Pe, Pe.exports);
946
+ var Gs = Pe.exports;
947
+ const Ks = /* @__PURE__ */ Ns(Gs);
948
+ class he {
949
+ constructor(n) {
950
+ this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (o) => {
951
+ Ks(this.state, o) || (this.state = o, this.notifySubscribers(o));
952
+ }, this.setPartial = (o) => {
953
+ if (o == null) return;
954
+ const h = { ...this.state, ...o };
955
+ this.set(h);
956
+ }, this.reset = () => {
957
+ this.set(this.initialState);
958
+ }, this.notifySubscribers = (o) => {
959
+ Array.from(this.subscribers).forEach((c) => {
960
+ try {
961
+ c(o);
962
+ } catch (a) {
963
+ console.error(a);
964
+ }
965
+ });
966
+ }, this.subscribe = (o) => (this.subscribers.add(o), () => {
967
+ this.subscribers.delete(o);
968
+ }), this.state = n, this.initialState = n;
969
+ }
970
+ }
971
+ class mt {
972
+ constructor() {
973
+ this.state = new he({
974
+ isPolling: !1,
975
+ isError: !1
976
+ }), this.abortController = new AbortController(), this.reset = () => {
977
+ var n;
978
+ this.abortController.abort("Resetting poller"), (n = this.stopPolling) == null || n.call(this), this.stopPolling = null;
979
+ }, this.stopPolling = null, this.startPolling = (n, o) => {
980
+ if (this.stopPolling) return;
981
+ const h = [], c = async () => {
982
+ this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
983
+ try {
984
+ await n(this.abortController.signal);
985
+ } catch (a) {
986
+ if (this.abortController.signal.aborted)
987
+ return;
988
+ console.error("Failed to poll:", a), this.state.setPartial({ isError: !0 });
989
+ } finally {
990
+ this.state.setPartial({ isPolling: !1 });
991
+ }
992
+ this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : h.push(setTimeout(c, o));
993
+ };
994
+ c(), this.stopPolling = () => {
995
+ h.forEach(clearTimeout), this.state.reset();
996
+ };
997
+ };
998
+ }
999
+ }
1000
+ function Ws(r) {
1001
+ try {
1002
+ const n = r();
1003
+ return n instanceof Promise ? n.then((o) => ({ data: o })).catch((o) => ({ error: o })) : { data: n };
1004
+ } catch (n) {
1005
+ return { error: n };
1006
+ }
1007
+ }
1008
+ class Xs {
1009
+ constructor({
1010
+ api: n,
1011
+ config: o,
1012
+ sessionCtx: h,
1013
+ messageCtx: c,
1014
+ sessionPollingIntervalSeconds: a
1015
+ }) {
1016
+ this.poller = new mt(), this.registerPolling = () => {
1017
+ this.sessionCtx.sessionState.subscribe(({ session: s }) => {
1018
+ s != null && s.id ? this.poller.startPolling(async (l) => {
1019
+ this.hackAndSlash(s.id, l);
1020
+ }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
1021
+ });
1022
+ }, this.hackAndSlash = async (s, l) => {
1023
+ var p;
1024
+ this.messageCtx.state.get().messages.length === 0 && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
1025
+ const d = this.messageCtx.state.get().messages, y = d.length > 0 ? (p = d[d.length - 1]) == null ? void 0 : p.timestamp : void 0, { data: g } = await this.api.pollSessionAndHistory({
1026
+ sessionId: s,
1027
+ abortSignal: l,
1028
+ lastMessageTimestamp: y
1029
+ });
1030
+ if (g != null && g.session && (this.sessionCtx.sessionState.setPartial({ session: g.session }), this.sessionCtx.setSessions([g.session])), g != null && g.history && g.history.length > 0) {
1031
+ const f = this.messageCtx.state.get().messages, v = g.history.map(this.mapHistoryToMessage).filter(
1032
+ (F) => !f.some((j) => j.id === F.id)
1033
+ );
1034
+ this.messageCtx.state.setPartial({
1035
+ messages: [...f, ...v]
1036
+ });
1037
+ }
1038
+ this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
1039
+ }, this.mapHistoryToMessage = (s) => {
1040
+ var y, g;
1041
+ const l = {
1042
+ id: s.publicId,
1043
+ timestamp: s.sentAt || "",
1044
+ attachments: s.attachments || void 0
1045
+ };
1046
+ if (s.sender.kind === "user")
1047
+ return {
1048
+ ...l,
1049
+ type: "FROM_USER",
1050
+ content: s.content.text || "",
1051
+ deliveredAt: s.sentAt || ""
1052
+ };
1053
+ if (s.sender.kind === "agent")
1054
+ return {
1055
+ ...l,
1056
+ type: "FROM_AGENT",
1057
+ component: "agent_message",
1058
+ data: {
1059
+ message: s.content.text || ""
1060
+ },
1061
+ agent: {
1062
+ name: s.sender.name || "",
1063
+ avatar: s.sender.avatar || "",
1064
+ id: null,
1065
+ isAi: !1
1066
+ }
1067
+ };
1068
+ const d = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
1069
+ return {
1070
+ ...l,
1071
+ type: "FROM_BOT",
1072
+ component: "bot_message",
1073
+ agent: {
1074
+ id: null,
1075
+ name: ((y = this.config.bot) == null ? void 0 : y.name) || "",
1076
+ isAi: !0,
1077
+ avatar: ((g = this.config.bot) == null ? void 0 : g.avatar) || ""
1078
+ },
1079
+ data: {
1080
+ message: s.content.text || "",
1081
+ action: d ? {
1082
+ name: d.actionName,
1083
+ data: this.extractActionResult(d)
1084
+ } : void 0
1085
+ }
1086
+ };
1087
+ }, this.extractActionResult = (s) => {
1088
+ const l = s.result;
1089
+ if (l === null || typeof l != "object") return l;
1090
+ if ("responseBodyText" in l && typeof l.responseBodyText == "string") {
1091
+ const d = l.responseBodyText, y = Ws(() => JSON.parse(d)).data;
1092
+ if (y) return y;
1093
+ }
1094
+ return s.result;
1095
+ }, this.api = n, this.config = o, this.sessionCtx = h, this.messageCtx = c, this.sessionPollingIntervalSeconds = a, this.registerPolling();
1096
+ }
1097
+ }
1098
+ const R = [];
1099
+ for (let r = 0; r < 256; ++r)
1100
+ R.push((r + 256).toString(16).slice(1));
1101
+ function Js(r, n = 0) {
1102
+ return (R[r[n + 0]] + R[r[n + 1]] + R[r[n + 2]] + R[r[n + 3]] + "-" + R[r[n + 4]] + R[r[n + 5]] + "-" + R[r[n + 6]] + R[r[n + 7]] + "-" + R[r[n + 8]] + R[r[n + 9]] + "-" + R[r[n + 10]] + R[r[n + 11]] + R[r[n + 12]] + R[r[n + 13]] + R[r[n + 14]] + R[r[n + 15]]).toLowerCase();
1103
+ }
1104
+ let $e;
1105
+ const Ys = new Uint8Array(16);
1106
+ function Qs() {
1107
+ if (!$e) {
1108
+ if (typeof crypto > "u" || !crypto.getRandomValues)
1109
+ throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
1110
+ $e = crypto.getRandomValues.bind(crypto);
1111
+ }
1112
+ return $e(Ys);
1113
+ }
1114
+ const Zs = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), dt = { randomUUID: Zs };
1115
+ function St(r, n, o) {
1116
+ var c;
1117
+ if (dt.randomUUID && !n && !r)
1118
+ return dt.randomUUID();
1119
+ r = r || {};
1120
+ const h = r.random ?? ((c = r.rng) == null ? void 0 : c.call(r)) ?? Qs();
1121
+ if (h.length < 16)
1122
+ throw new Error("Random bytes length must be >= 16");
1123
+ return h[6] = h[6] & 15 | 64, h[8] = h[8] & 63 | 128, Js(h);
1124
+ }
1125
+ class Vs {
1126
+ constructor({
1127
+ config: n,
1128
+ api: o,
1129
+ storageCtx: h
1130
+ }) {
1131
+ var c;
1132
+ this.shouldCollectData = () => {
1133
+ var a;
1134
+ return !!(!((a = this.state.get().contact) != null && a.token) && this.config.collectUserData);
1135
+ }, this.autoCreateUnverifiedUserIfNotExists = async () => {
1136
+ var a, s, l, d, y, g, p, f, v, F, j, q, E, S;
1137
+ if (!((a = this.config.user) != null && a.token)) {
1138
+ if (this.config.collectUserData && !((l = (s = this.config.user) == null ? void 0 : s.data) != null && l.email)) {
1139
+ if ((d = this.config.extraDataCollectionFields) != null && d.length)
1140
+ return;
1141
+ const I = await ((y = this.storageCtx) == null ? void 0 : y.getContactToken());
1142
+ I && await this.setUnverifiedContact(I);
1143
+ return;
1144
+ }
1145
+ if (!((p = (g = this.config.user) == null ? void 0 : g.data) != null && p.email)) {
1146
+ const I = await ((f = this.storageCtx) == null ? void 0 : f.getContactToken());
1147
+ if (I) {
1148
+ await this.setUnverifiedContact(I);
1149
+ return;
1150
+ }
1151
+ }
1152
+ await this.createUnverifiedContact({
1153
+ email: (F = (v = this.config.user) == null ? void 0 : v.data) == null ? void 0 : F.email,
1154
+ non_verified_name: ((q = (j = this.config.user) == null ? void 0 : j.data) == null ? void 0 : q.name) || "Anonymous",
1155
+ non_verified_custom_data: (S = (E = this.config.user) == null ? void 0 : E.data) == null ? void 0 : S.customData
1156
+ });
1157
+ }
1158
+ }, this.createUnverifiedContact = async (a, s) => {
1159
+ this.state.setPartial({ extraCollectedData: s });
1160
+ try {
1161
+ this.state.setPartial({
1162
+ isCreatingUnverifiedContact: !0,
1163
+ isErrorCreatingUnverifiedContact: !1
1164
+ });
1165
+ const { data: l } = await this.api.createUnverifiedContact(a);
1166
+ l != null && l.token ? await this.setUnverifiedContact(l.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
1167
+ } finally {
1168
+ this.state.setPartial({ isCreatingUnverifiedContact: !1 });
1169
+ }
1170
+ }, this.setUnverifiedContact = async (a) => {
1171
+ var d, y, g, p;
1172
+ const s = await ((d = this.storageCtx) == null ? void 0 : d.getExternalContactId()), l = ((y = this.config.user) == null ? void 0 : y.externalId) || s || St();
1173
+ this.api.setAuthToken(a), await ((g = this.storageCtx) == null ? void 0 : g.setContactToken(a)), await ((p = this.storageCtx) == null ? void 0 : p.setExternalContactId(l)), this.state.setPartial({ contact: { token: a, externalId: l } });
1174
+ }, this.config = n, this.storageCtx = h, this.api = o, this.state = new he({
1175
+ contact: (c = n.user) != null && c.token ? {
1176
+ token: n.user.token,
1177
+ // Set optional externalId from config... not local storage
1178
+ externalId: n.user.externalId
1179
+ } : null,
1180
+ extraCollectedData: void 0,
1181
+ isCreatingUnverifiedContact: !1,
1182
+ isErrorCreatingUnverifiedContact: !1
1183
+ }), this.autoCreateUnverifiedUserIfNotExists();
1184
+ }
1185
+ }
1186
+ function ze() {
1187
+ return St();
1188
+ }
1189
+ class en {
1190
+ constructor({
1191
+ api: n,
1192
+ contactCtx: o,
1193
+ sessionsPollingIntervalSeconds: h
1194
+ }) {
1195
+ this.sessionsRefresher = new mt(), this.sessionState = new he({
1196
+ session: null,
1197
+ isCreatingSession: !1,
1198
+ isResolvingSession: !1
1199
+ }), this.sessionsState = new he({
1200
+ data: [],
1201
+ cursor: void 0,
1202
+ isLastPage: !1,
1203
+ didStartInitialFetch: !1,
1204
+ /**
1205
+ * Initialize this as `true` so it always starts loading until the first fetch is done
1206
+ */
1207
+ isInitialFetchLoading: !0
1208
+ }), this.reset = async () => {
1209
+ this.sessionState.reset();
1210
+ }, this.registerSessionsRefresherWrapper = () => {
1211
+ var c;
1212
+ // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
1213
+ (c = this.contactCtx.state.get().contact) != null && c.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: a }) => {
1214
+ a != null && a.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
1215
+ });
1216
+ }, this.registerSessionsRefresher = () => {
1217
+ this.sessionsRefresher.startPolling(async () => {
1218
+ this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
1219
+ }, this.sessionsPollingIntervalSeconds * 1e3);
1220
+ }, this.createSession = async () => {
1221
+ var l;
1222
+ this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
1223
+ const c = (l = this.contactCtx.state.get().contact) == null ? void 0 : l.externalId, { data: a, error: s } = await this.api.createSession({
1224
+ customData: c ? {
1225
+ external_id: c
1226
+ } : void 0
1227
+ });
1228
+ return a ? (this.sessionState.setPartial({ session: a, isCreatingSession: !1 }), a) : (this.sessionState.setPartial({ isCreatingSession: !1 }), console.error("Failed to create session:", s), null);
1229
+ }, this.loadMoreSessions = async () => {
1230
+ if (this.sessionsState.get().isLastPage) return;
1231
+ const { data: c } = await this.getSessions({
1232
+ cursor: this.sessionsState.get().cursor
1233
+ });
1234
+ if (c) {
1235
+ const s = [...this.sessionsState.get().data, ...c.items].filter(
1236
+ (l, d, y) => d === y.findIndex((g) => l.id === g.id)
1237
+ );
1238
+ this.sessionsState.setPartial({
1239
+ data: s,
1240
+ cursor: c.next || void 0,
1241
+ isLastPage: c.next === null
1242
+ });
1243
+ }
1244
+ }, this.getSessions = async ({ cursor: c }) => {
1245
+ var s, l;
1246
+ if (!((s = this.contactCtx.state.get().contact) != null && s.token)) return { data: null };
1247
+ const a = (l = this.contactCtx.state.get().contact) == null ? void 0 : l.externalId;
1248
+ return await this.api.getSessions({
1249
+ cursor: c,
1250
+ filters: a ? {
1251
+ external_id: a
1252
+ } : {}
1253
+ });
1254
+ }, this.setSessions = (c) => {
1255
+ const a = [...c, ...this.sessionsState.get().data].filter(
1256
+ (s, l, d) => l === d.findIndex((y) => s.id === y.id)
1257
+ );
1258
+ this.sessionsState.setPartial({ data: a });
1259
+ }, this.refreshSessions = async () => {
1260
+ const { data: c } = await this.getSessions({ cursor: void 0 });
1261
+ c && this.setSessions(c.items);
1262
+ }, this.resolveSession = async () => {
1263
+ const c = this.sessionState.get().session;
1264
+ if (!c || !c.isOpened)
1265
+ return { success: !1, error: "Session is not opened" };
1266
+ this.sessionState.setPartial({ isResolvingSession: !0 });
1267
+ const { data: a, error: s } = await this.api.resolveSession({
1268
+ session_id: c.id
1269
+ });
1270
+ return a ? (this.sessionState.setPartial({ session: a, isResolvingSession: !1 }), { success: !0, data: a }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: s });
1271
+ }, this.createStateCheckpoint = async (c) => {
1272
+ var d;
1273
+ const a = (d = this.sessionState.get().session) == null ? void 0 : d.id;
1274
+ if (!a) return;
1275
+ const { data: s, error: l } = await this.api.createStateCheckpoint({
1276
+ session_id: a,
1277
+ payload: c
1278
+ });
1279
+ return s ? { data: s } : { success: !1, error: l };
1280
+ }, this.api = n, this.contactCtx = o, this.sessionsPollingIntervalSeconds = h, this.registerSessionsRefresherWrapper();
1281
+ }
1282
+ }
1283
+ class tn {
1284
+ constructor({
1285
+ config: n,
1286
+ api: o,
1287
+ sessionCtx: h,
1288
+ contactCtx: c
1289
+ }) {
1290
+ this.state = new he({
1291
+ messages: [],
1292
+ isSendingMessage: !1,
1293
+ lastAIResMightSolveUserIssue: !1,
1294
+ isInitialFetchLoading: !1
1295
+ }), this.sendMessageAbortController = new AbortController(), this.reset = () => {
1296
+ this.sendMessageAbortController.abort("Resetting chat"), this.state.reset();
1297
+ }, this.sendMessage = async (a) => {
1298
+ var g, p, f, v, F, j, q, E;
1299
+ if (!a.content.trim() && (!a.attachments || a.attachments.length === 0)) {
1300
+ console.warn("Cannot send an empty message of no content or attachments");
1301
+ return;
1302
+ }
1303
+ const s = this.state.get().isSendingMessage, l = ((g = this.sessionCtx.sessionState.get().session) == null ? void 0 : g.assignee.kind) === "ai", d = this.state.get().messages, y = d.length > 0 ? d[d.length - 1] : void 0;
1304
+ if (l && s || // If last message is from user, then bot response did not arrive yet
1305
+ l && (y == null ? void 0 : y.type) === "FROM_USER") {
1306
+ console.warn("Cannot send messages while awaiting AI response");
1307
+ return;
1308
+ }
1309
+ this.sendMessageAbortController = new AbortController(), this.state.setPartial({ lastAIResMightSolveUserIssue: !1 });
1310
+ try {
1311
+ this.state.setPartial({ isSendingMessage: !0 });
1312
+ const S = this.toUserMessage(
1313
+ a.content.trim(),
1314
+ a.attachments || void 0
1315
+ ), I = this.state.get().messages;
1316
+ if (this.state.setPartial({
1317
+ messages: [...I, S]
1318
+ }), !((p = this.sessionCtx.sessionState.get().session) != null && p.id)) {
1319
+ if (!await this.sessionCtx.createSession()) {
1320
+ console.error("Failed to create session");
1321
+ return;
1322
+ }
1323
+ this.sessionCtx.refreshSessions();
1324
+ }
1325
+ const ee = (f = this.sessionCtx.sessionState.get().session) == null ? void 0 : f.id;
1326
+ if (!ee) return;
1327
+ const { data: _ } = await this.api.sendMessage(
1328
+ {
1329
+ uuid: S.id,
1330
+ bot_token: this.config.token,
1331
+ headers: this.config.headers,
1332
+ query_params: this.config.queryParams,
1333
+ body_properties: this.config.bodyProperties,
1334
+ session_id: ee,
1335
+ content: S.content,
1336
+ attachments: a.attachments,
1337
+ clientContext: this.config.context,
1338
+ custom_data: {
1339
+ ...this.config.messageCustomData || {},
1340
+ ...a.customData || {}
1341
+ },
1342
+ language: this.config.language,
1343
+ exit_mode_prompt: a.exitModePrompt
1344
+ },
1345
+ this.sendMessageAbortController.signal
1346
+ );
1347
+ if (_ != null && _.success) {
1348
+ const D = this.toBotMessage(_);
1349
+ if (D) {
1350
+ const k = this.state.get().messages;
1351
+ if (!!k.some(
1352
+ (fe) => fe.id === D.id
1353
+ )) {
1354
+ this.state.setPartial({
1355
+ lastAIResMightSolveUserIssue: ((v = _.autopilotResponse) == null ? void 0 : v.mightSolveUserIssue) || ((F = _.uiResponse) == null ? void 0 : F.mightSolveUserIssue)
1356
+ });
1357
+ return;
1358
+ }
1359
+ this.state.setPartial({
1360
+ messages: [...k, D],
1361
+ lastAIResMightSolveUserIssue: ((j = _.autopilotResponse) == null ? void 0 : j.mightSolveUserIssue) || ((q = _.uiResponse) == null ? void 0 : q.mightSolveUserIssue)
1362
+ });
1363
+ }
1364
+ _.session && this.sessionCtx.sessionState.setPartial({ session: _.session });
1365
+ } else {
1366
+ const D = this.toBotErrorMessage(
1367
+ ((E = _ == null ? void 0 : _.error) == null ? void 0 : E.message) || "Unknown error occurred"
1368
+ ), k = this.state.get().messages;
1369
+ this.state.setPartial({
1370
+ messages: [...k, D]
1371
+ });
1372
+ }
1373
+ } catch (S) {
1374
+ this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", S);
1375
+ } finally {
1376
+ this.state.setPartial({ isSendingMessage: !1 });
1377
+ }
1378
+ }, this.toUserMessage = (a, s) => {
1379
+ const l = (() => {
1380
+ const d = this.contactCtx.state.get().extraCollectedData;
1381
+ return this.state.get().messages.length === 0 && d && Object.keys(d).length > 0 ? `${Object.entries(d).filter(([g, p]) => !!p).map(([g, p]) => `${g}: ${p}`).join(`
1382
+ `)}
1383
+
1384
+ ${a}` : a;
1385
+ })();
1386
+ return {
1387
+ id: ze(),
1388
+ type: "FROM_USER",
1389
+ content: l,
1390
+ deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
1391
+ attachments: s,
1392
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1393
+ };
1394
+ }, this.toBotMessage = (a) => {
1395
+ var s;
1396
+ return a.success && a.autopilotResponse ? {
1397
+ type: "FROM_BOT",
1398
+ id: a.autopilotResponse.id || ze(),
1399
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1400
+ component: "bot_message",
1401
+ agent: this.config.bot ? {
1402
+ name: this.config.bot.name || "",
1403
+ isAi: !0,
1404
+ avatar: this.config.bot.avatar || "",
1405
+ id: null
1406
+ } : void 0,
1407
+ data: {
1408
+ message: a.autopilotResponse.value.content,
1409
+ action: (s = a.uiResponse) != null && s.value.name ? {
1410
+ name: a.uiResponse.value.name,
1411
+ data: a.uiResponse.value.request_response
1412
+ } : void 0
1413
+ }
1414
+ } : null;
1415
+ }, this.toBotErrorMessage = (a) => ({
1416
+ type: "FROM_BOT",
1417
+ id: ze(),
1418
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1419
+ component: "TEXT",
1420
+ data: {
1421
+ message: a,
1422
+ variant: "error",
1423
+ action: void 0
1424
+ }
1425
+ }), this.config = n, this.api = o, this.sessionCtx = h, this.contactCtx = c;
1426
+ }
1427
+ }
1428
+ class sn {
1429
+ constructor({
1430
+ config: n,
1431
+ contactCtx: o,
1432
+ sessionCtx: h,
1433
+ resetChat: c
1434
+ }) {
1435
+ var a;
1436
+ this.registerRoutingListener = () => {
1437
+ this.contactCtx.state.subscribe(({ contact: s }) => {
1438
+ var l;
1439
+ s != null && s.token && this.state.get().screen === "welcome" && this.state.setPartial({
1440
+ screen: (l = this.config.router) != null && l.chatScreenOnly ? "chat" : "sessions"
1441
+ });
1442
+ }), this.sessionCtx.sessionsState.subscribe(
1443
+ ({ isInitialFetchLoading: s, data: l }) => {
1444
+ var d, y, g, p;
1445
+ if ((d = this.config.router) != null && d.chatScreenOnly && // Do not route to a chat if we are currently inside one already
1446
+ // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
1447
+ !((y = this.sessionCtx.sessionState.get().session) != null && y.id)) {
1448
+ const f = (g = l.find((v) => v.isOpened)) == null ? void 0 : g.id;
1449
+ return f ? this.toChatScreen(f) : void 0;
1450
+ }
1451
+ l.length || ((p = this.config.router) == null ? void 0 : p.goToChatIfNoSessions) !== !1 && !s && this.state.get().screen !== "chat" && this.toChatScreen();
1452
+ }
1453
+ );
1454
+ }, this.toSessionsScreen = () => {
1455
+ this.resetChat(), this.state.setPartial({ screen: "sessions" });
1456
+ }, this.toChatScreen = (s) => {
1457
+ if (this.resetChat(), s) {
1458
+ const l = this.sessionCtx.sessionsState.get().data.find((d) => d.id === s);
1459
+ if (!l) return;
1460
+ this.sessionCtx.sessionState.setPartial({ session: l });
1461
+ }
1462
+ this.state.setPartial({ screen: "chat" });
1463
+ }, this.config = n, this.contactCtx = o, this.sessionCtx = h, this.resetChat = c, this.state = new he({
1464
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : (a = this.config.router) != null && a.chatScreenOnly ? "chat" : "sessions"
1465
+ }), this.registerRoutingListener();
1466
+ }
1467
+ }
1468
+ class nn {
1469
+ constructor({ storage: n }) {
1470
+ this.KEYS = {
1471
+ contactToken: "opencx__widget__contactToken",
1472
+ externalContactId: "opencx__widget__externalContactId"
1473
+ }, this.setContactToken = async (o) => {
1474
+ await this.storage.set(this.KEYS.contactToken, o);
1475
+ }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken), this.setExternalContactId = async (o) => {
1476
+ await this.storage.set(this.KEYS.externalContactId, o);
1477
+ }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId), this.storage = n;
1478
+ }
1479
+ }
1480
+ const Y = class Y {
1481
+ constructor({
1482
+ config: n,
1483
+ storage: o,
1484
+ modes: h
1485
+ }) {
1486
+ if (this.modes = [], this.resetChat = () => {
1487
+ this.sessionCtx.reset(), this.messageCtx.reset();
1488
+ }, !Y.pollingIntervalsSeconds)
1489
+ throw Error(
1490
+ "Widget polling values are not defined, did you call WidgetCtx.initialize()"
1491
+ );
1492
+ this.config = n, this.api = new ft({ config: n }), this.storageCtx = o ? new nn({ storage: o }) : void 0, this.modes = h, this.contactCtx = new Vs({
1493
+ api: this.api,
1494
+ config: this.config,
1495
+ storageCtx: this.storageCtx
1496
+ }), this.sessionCtx = new en({
1497
+ api: this.api,
1498
+ contactCtx: this.contactCtx,
1499
+ sessionsPollingIntervalSeconds: Y.pollingIntervalsSeconds.sessions
1500
+ }), this.messageCtx = new tn({
1501
+ config: this.config,
1502
+ api: this.api,
1503
+ sessionCtx: this.sessionCtx,
1504
+ contactCtx: this.contactCtx
1505
+ }), this.activeSessionPollingCtx = new Xs({
1506
+ api: this.api,
1507
+ config: this.config,
1508
+ sessionCtx: this.sessionCtx,
1509
+ messageCtx: this.messageCtx,
1510
+ sessionPollingIntervalSeconds: Y.pollingIntervalsSeconds.session
1511
+ }), this.routerCtx = new sn({
1512
+ config: this.config,
1513
+ contactCtx: this.contactCtx,
1514
+ sessionCtx: this.sessionCtx,
1515
+ resetChat: this.resetChat
1516
+ });
1517
+ }
1518
+ };
1519
+ Y.pollingIntervalsSeconds = null, Y.initialize = async ({
1520
+ config: n,
1521
+ storage: o
1522
+ }) => {
1523
+ var c, a, s;
1524
+ const h = await new ft({
1525
+ config: n
1526
+ }).getExternalWidgetConfig();
1527
+ return Y.pollingIntervalsSeconds = {
1528
+ session: ((c = h.data) == null ? void 0 : c.sessionPollingIntervalSeconds) || 10,
1529
+ sessions: ((a = h.data) == null ? void 0 : a.sessionsPollingIntervalSeconds) || 60
1530
+ }, new Y({
1531
+ config: n,
1532
+ storage: o,
1533
+ modes: ((s = h.data) == null ? void 0 : s.modes) || []
1534
+ });
1535
+ };
1536
+ let gt = Y;
1537
+ export {
1538
+ he as P,
1539
+ gt as W,
1540
+ St as v
1541
+ };
1542
+ //# sourceMappingURL=widget.ctx-CC3c7FPb.js.map