@opencx/widget 3.0.89 → 3.0.91

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