@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
@@ -1,673 +0,0 @@
1
- import M from "openapi-fetch";
2
- import O from "lodash.isequal";
3
- import { v4 as E } from "uuid";
4
- const F = (d) => {
5
- console.log(d.error);
6
- }, _ = (d) => {
7
- const n = M({
8
- baseUrl: d.baseUrl
9
- }), a = {
10
- onRequest: d.onRequest,
11
- onResponse: d.onResponse,
12
- onError: d.onError || F
13
- };
14
- return n.use(a), n;
15
- };
16
- class T {
17
- constructor({ config: n }) {
18
- var o, e;
19
- this.userToken = null, this.constructClientOptions = (t) => {
20
- const s = this.config.apiUrl || "https://api.open.cx", i = {
21
- "X-Bot-Token": this.config.token,
22
- "Content-Type": "application/json",
23
- Accept: "application/json",
24
- Authorization: t ? `Bearer ${t}` : void 0
25
- };
26
- return { baseUrl: s, headers: i };
27
- }, this.createOpenAPIClient = ({
28
- baseUrl: t,
29
- headers: s
30
- }) => _({
31
- baseUrl: t,
32
- onRequest: ({ request: i }) => {
33
- Object.entries(s).forEach(([c, r]) => {
34
- r && i.headers.set(c, r);
35
- });
36
- }
37
- }), this.setAuthToken = (t) => {
38
- this.userToken = t;
39
- const { baseUrl: s, headers: i } = this.constructClientOptions(t);
40
- this.client = this.createOpenAPIClient({ baseUrl: s, headers: i });
41
- }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
42
- params: { header: { "X-Bot-Token": this.config.token } }
43
- }), this.widgetPrelude = async () => await this.client.GET("/backend/widget/v2/prelude", {
44
- params: { header: { "X-Bot-Token": this.config.token } }
45
- }), this.sendMessage = async (t, s) => await this.client.POST("/backend/widget/v2/chat/send", {
46
- body: t,
47
- signal: s
48
- }), this.createUnverifiedContact = async (t) => await this.client.POST(
49
- "/backend/widget/v2/contact/create-unverified",
50
- {
51
- params: { header: { "x-bot-token": this.config.token } },
52
- body: t
53
- }
54
- ), this.createSession = async (t) => await this.client.POST("/backend/widget/v2/create-session", {
55
- body: t
56
- }), this.pollSessionAndHistory = async ({
57
- sessionId: t,
58
- lastMessageTimestamp: s,
59
- abortSignal: i
60
- }) => {
61
- const c = s ? { lastMessageTimestamp: s } : void 0;
62
- return await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
63
- params: { path: { sessionId: t }, query: c },
64
- signal: i
65
- });
66
- }, this.getSessions = async ({
67
- cursor: t,
68
- filters: s,
69
- abortSignal: i
70
- }) => await this.client.GET("/backend/widget/v2/sessions", {
71
- params: { query: { cursor: t, filters: JSON.stringify(s) } },
72
- signal: i
73
- }), this.uploadFile = async ({
74
- file: t,
75
- abortSignal: s,
76
- onProgress: i
77
- }) => new Promise((c, r) => {
78
- var v;
79
- const h = new FormData();
80
- h.append("file", t);
81
- const l = new XMLHttpRequest();
82
- if (s && (s.addEventListener("abort", () => {
83
- l.abort(), r(new DOMException("Aborted", "AbortError"));
84
- }), s.aborted)) {
85
- r(new DOMException("Aborted", "AbortError"));
86
- return;
87
- }
88
- l.upload.addEventListener("progress", (u) => {
89
- if (u.lengthComputable && i) {
90
- const S = Math.round(u.loaded / u.total * 100);
91
- i(S);
92
- }
93
- }), l.addEventListener("load", () => {
94
- if (l.status >= 200 && l.status < 300)
95
- try {
96
- const u = JSON.parse(l.responseText);
97
- c(u);
98
- } catch (u) {
99
- r(new Error(`Failed to parse response: ${u}`));
100
- }
101
- else
102
- r(new Error(`Upload failed with status: ${l.status}`));
103
- }), l.addEventListener("error", () => {
104
- r(new Error("Network error occurred"));
105
- }), l.addEventListener("timeout", () => {
106
- r(new Error("Upload timed out"));
107
- });
108
- const { baseUrl: f } = this.constructClientOptions(this.userToken), p = `${f}/backend/widget/v2/upload`;
109
- l.open("POST", p), l.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((v = this.config.user) == null ? void 0 : v.token) ? l.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), l.send(h);
110
- }), this.vote = async (t) => await this.client.POST("/backend/widget/v2/chat/vote", { body: t }), this.resolveSession = async (t, s) => await this.client.POST("/backend/widget/v2/session/resolve", {
111
- body: t,
112
- signal: s
113
- }), this.config = n, this.userToken = ((o = n.user) == null ? void 0 : o.token) || null;
114
- const { baseUrl: a, headers: g } = this.constructClientOptions(
115
- (e = n.user) == null ? void 0 : e.token
116
- );
117
- this.client = this.createOpenAPIClient({ baseUrl: a, headers: g });
118
- }
119
- }
120
- class P {
121
- constructor(n) {
122
- this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
123
- O(this.state, a) || (this.state = a, this.notifySubscribers(a));
124
- }, this.setPartial = (a) => {
125
- if (a == null) return;
126
- const g = { ...this.state, ...a };
127
- this.set(g);
128
- }, this.reset = () => {
129
- this.set(this.initialState);
130
- }, this.notifySubscribers = (a) => {
131
- Array.from(this.subscribers).forEach((o) => {
132
- try {
133
- o(a);
134
- } catch (e) {
135
- console.error(e);
136
- }
137
- });
138
- }, this.subscribe = (a) => (this.subscribers.add(a), () => {
139
- this.subscribers.delete(a);
140
- }), this.state = n, this.initialState = n;
141
- }
142
- }
143
- class R {
144
- constructor() {
145
- this.state = new P({
146
- isPolling: !1,
147
- isError: !1
148
- }), this.abortController = new AbortController(), this.reset = () => {
149
- var n;
150
- this.abortController.abort("Resetting poller"), (n = this.stopPolling) == null || n.call(this), this.stopPolling = null;
151
- }, this.stopPolling = null, this.startPolling = (n, a) => {
152
- if (this.stopPolling) return;
153
- const g = [], o = async () => {
154
- this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
155
- try {
156
- await n(this.abortController.signal);
157
- } catch (e) {
158
- if (this.abortController.signal.aborted)
159
- return;
160
- console.error("Failed to poll:", e), this.state.setPartial({ isError: !0 });
161
- } finally {
162
- this.state.setPartial({ isPolling: !1 });
163
- }
164
- this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : g.push(setTimeout(o, a));
165
- };
166
- o(), this.stopPolling = () => {
167
- g.forEach(clearTimeout), this.state.reset();
168
- };
169
- };
170
- }
171
- }
172
- function D(d) {
173
- try {
174
- const n = d();
175
- return n instanceof Promise ? n.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: n };
176
- } catch (n) {
177
- return { error: n };
178
- }
179
- }
180
- class L {
181
- constructor({
182
- api: n,
183
- config: a,
184
- sessionCtx: g,
185
- messageCtx: o,
186
- sessionPollingIntervalSeconds: e
187
- }) {
188
- this.poller = new R(), this.registerPolling = () => {
189
- this.sessionCtx.sessionState.subscribe(({ session: t }) => {
190
- t != null && t.id ? this.poller.startPolling(async (s) => {
191
- this.hackAndSlash(t.id, s);
192
- }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
193
- });
194
- }, this.hackAndSlash = async (t, s) => {
195
- var h;
196
- this.messageCtx.state.get().messages.length === 0 && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
197
- const i = this.messageCtx.state.get().messages, c = i.length > 0 ? (h = i[i.length - 1]) == null ? void 0 : h.timestamp : void 0, { data: r } = await this.api.pollSessionAndHistory({
198
- sessionId: t,
199
- abortSignal: s,
200
- lastMessageTimestamp: c
201
- });
202
- if (r != null && r.session && (this.sessionCtx.sessionState.setPartial({ session: r.session }), this.sessionCtx.setSessions([r.session])), r != null && r.history && r.history.length > 0) {
203
- const l = this.messageCtx.state.get().messages, f = r.history.map(this.mapHistoryToMessage).filter(
204
- (x) => !l.some((p) => p.id === x.id)
205
- );
206
- this.messageCtx.state.setPartial({
207
- messages: [...l, ...f]
208
- });
209
- }
210
- this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
211
- }, this.mapHistoryToMessage = (t) => {
212
- var c, r;
213
- const s = {
214
- id: t.publicId,
215
- timestamp: t.sentAt || "",
216
- attachments: t.attachments || void 0
217
- };
218
- if (t.sender.kind === "user")
219
- return {
220
- ...s,
221
- type: "FROM_USER",
222
- content: t.content.text || "",
223
- deliveredAt: t.sentAt || ""
224
- };
225
- if (t.sender.kind === "agent")
226
- return {
227
- ...s,
228
- type: "FROM_AGENT",
229
- component: "agent_message",
230
- data: {
231
- message: t.content.text || ""
232
- },
233
- agent: {
234
- name: t.sender.name || "",
235
- avatar: t.sender.avatar || "",
236
- id: null,
237
- isAi: !1
238
- }
239
- };
240
- const i = t.actionCalls && t.actionCalls.length > 0 ? t.actionCalls[t.actionCalls.length - 1] : void 0;
241
- return {
242
- ...s,
243
- type: "FROM_BOT",
244
- component: "bot_message",
245
- agent: {
246
- id: null,
247
- name: ((c = this.config.bot) == null ? void 0 : c.name) || "",
248
- isAi: !0,
249
- avatar: ((r = this.config.bot) == null ? void 0 : r.avatar) || ""
250
- },
251
- data: {
252
- message: t.content.text || "",
253
- action: i ? {
254
- name: i.actionName,
255
- data: this.extractActionResult(i)
256
- } : void 0
257
- }
258
- };
259
- }, this.extractActionResult = (t) => {
260
- const s = t.result;
261
- if (s === null || typeof s != "object") return s;
262
- if ("responseBodyText" in s && typeof s.responseBodyText == "string") {
263
- const i = s.responseBodyText, c = D(() => JSON.parse(i)).data;
264
- if (c) return c;
265
- }
266
- return t.result;
267
- }, this.api = n, this.config = a, this.sessionCtx = g, this.messageCtx = o, this.sessionPollingIntervalSeconds = e, this.registerPolling();
268
- }
269
- }
270
- class B {
271
- constructor({
272
- config: n,
273
- api: a,
274
- storageCtx: g
275
- }) {
276
- var o;
277
- this.shouldCollectData = () => {
278
- var e;
279
- return !!(!((e = this.state.get().contact) != null && e.token) && this.config.collectUserData);
280
- }, this.autoCreateUnverifiedUserIfNotExists = async () => {
281
- var e, t, s, i, c, r, h, l, f, x, p, b, v, u;
282
- if (!((e = this.config.user) != null && e.token)) {
283
- if (this.config.collectUserData && !((s = (t = this.config.user) == null ? void 0 : t.data) != null && s.email)) {
284
- if ((i = this.config.extraDataCollectionFields) != null && i.length)
285
- return;
286
- const S = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
287
- S && await this.setUnverifiedContact(S);
288
- return;
289
- }
290
- if (!((h = (r = this.config.user) == null ? void 0 : r.data) != null && h.email)) {
291
- const S = await ((l = this.storageCtx) == null ? void 0 : l.getContactToken());
292
- if (S) {
293
- await this.setUnverifiedContact(S);
294
- return;
295
- }
296
- }
297
- await this.createUnverifiedContact({
298
- email: (x = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : x.email,
299
- non_verified_name: ((b = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : b.name) || "Anonymous",
300
- non_verified_custom_data: (u = (v = this.config.user) == null ? void 0 : v.data) == null ? void 0 : u.customData
301
- });
302
- }
303
- }, this.createUnverifiedContact = async (e, t) => {
304
- this.state.setPartial({ extraCollectedData: t });
305
- try {
306
- this.state.setPartial({
307
- isCreatingUnverifiedContact: !0,
308
- isErrorCreatingUnverifiedContact: !1
309
- });
310
- const { data: s } = await this.api.createUnverifiedContact(e);
311
- s != null && s.token ? await this.setUnverifiedContact(s.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
312
- } finally {
313
- this.state.setPartial({ isCreatingUnverifiedContact: !1 });
314
- }
315
- }, this.setUnverifiedContact = async (e) => {
316
- var i, c, r, h;
317
- const t = await ((i = this.storageCtx) == null ? void 0 : i.getExternalContactId()), s = ((c = this.config.user) == null ? void 0 : c.externalId) || t || E();
318
- this.api.setAuthToken(e), await ((r = this.storageCtx) == null ? void 0 : r.setContactToken(e)), await ((h = this.storageCtx) == null ? void 0 : h.setExternalContactId(s)), this.state.setPartial({ contact: { token: e, externalId: s } });
319
- }, this.config = n, this.storageCtx = g, this.api = a, this.state = new P({
320
- contact: (o = n.user) != null && o.token ? {
321
- token: n.user.token,
322
- // Set optional externalId from config... not local storage
323
- externalId: n.user.externalId
324
- } : null,
325
- extraCollectedData: void 0,
326
- isCreatingUnverifiedContact: !1,
327
- isErrorCreatingUnverifiedContact: !1
328
- }), this.autoCreateUnverifiedUserIfNotExists();
329
- }
330
- }
331
- function y() {
332
- return E();
333
- }
334
- class q {
335
- constructor({
336
- api: n,
337
- contactCtx: a,
338
- sessionsPollingIntervalSeconds: g
339
- }) {
340
- this.sessionsRefresher = new R(), this.sessionState = new P({
341
- session: null,
342
- isCreatingSession: !1,
343
- isResolvingSession: !1
344
- }), this.sessionsState = new P({
345
- data: [],
346
- cursor: void 0,
347
- isLastPage: !1,
348
- didStartInitialFetch: !1,
349
- /**
350
- * Initialize this as `true` so it always starts loading until the first fetch is done
351
- */
352
- isInitialFetchLoading: !0
353
- }), this.reset = async () => {
354
- this.sessionState.reset();
355
- }, this.registerSessionsRefresherWrapper = () => {
356
- var o;
357
- // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
358
- (o = this.contactCtx.state.get().contact) != null && o.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: e }) => {
359
- e != null && e.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
360
- });
361
- }, this.registerSessionsRefresher = () => {
362
- this.sessionsRefresher.startPolling(async () => {
363
- this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
364
- }, this.sessionsPollingIntervalSeconds * 1e3);
365
- }, this.createSession = async () => {
366
- var s;
367
- this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
368
- const o = (s = this.contactCtx.state.get().contact) == null ? void 0 : s.externalId, { data: e, error: t } = await this.api.createSession({
369
- customData: o ? {
370
- external_id: o
371
- } : void 0
372
- });
373
- return e ? (this.sessionState.setPartial({ session: e, isCreatingSession: !1 }), e) : (this.sessionState.setPartial({ isCreatingSession: !1 }), console.error("Failed to create session:", t), null);
374
- }, this.loadMoreSessions = async () => {
375
- if (this.sessionsState.get().isLastPage) return;
376
- const { data: o } = await this.getSessions({
377
- cursor: this.sessionsState.get().cursor
378
- });
379
- if (o) {
380
- const t = [...this.sessionsState.get().data, ...o.items].filter(
381
- (s, i, c) => i === c.findIndex((r) => s.id === r.id)
382
- );
383
- this.sessionsState.setPartial({
384
- data: t,
385
- cursor: o.next || void 0,
386
- isLastPage: o.next === null
387
- });
388
- }
389
- }, this.getSessions = async ({ cursor: o }) => {
390
- var t, s;
391
- if (!((t = this.contactCtx.state.get().contact) != null && t.token)) return { data: null };
392
- const e = (s = this.contactCtx.state.get().contact) == null ? void 0 : s.externalId;
393
- return await this.api.getSessions({
394
- cursor: o,
395
- filters: e ? {
396
- external_id: e
397
- } : {}
398
- });
399
- }, this.setSessions = (o) => {
400
- const e = [...o, ...this.sessionsState.get().data].filter(
401
- (t, s, i) => s === i.findIndex((c) => t.id === c.id)
402
- );
403
- this.sessionsState.setPartial({ data: e });
404
- }, this.refreshSessions = async () => {
405
- const { data: o } = await this.getSessions({ cursor: void 0 });
406
- o && this.setSessions(o.items);
407
- }, this.resolveSession = async () => {
408
- const o = this.sessionState.get().session;
409
- if (!o || !o.isOpened)
410
- return { success: !1, error: "Session is not opened" };
411
- this.sessionState.setPartial({ isResolvingSession: !0 });
412
- const { data: e, error: t } = await this.api.resolveSession({
413
- session_id: o.id
414
- });
415
- return e ? (this.sessionState.setPartial({ session: e, isResolvingSession: !1 }), { success: !0, data: e }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: t });
416
- }, this.api = n, this.contactCtx = a, this.sessionsPollingIntervalSeconds = g, this.registerSessionsRefresherWrapper();
417
- }
418
- }
419
- class $ {
420
- constructor({
421
- config: n,
422
- api: a,
423
- sessionCtx: g,
424
- contactCtx: o
425
- }) {
426
- this.state = new P({
427
- messages: [],
428
- isSendingMessage: !1,
429
- lastAIResMightSolveUserIssue: !1,
430
- isInitialFetchLoading: !1
431
- }), this.sendMessageAbortController = new AbortController(), this.reset = () => {
432
- this.sendMessageAbortController.abort("Resetting chat"), this.state.reset();
433
- }, this.sendMessage = async (e) => {
434
- var r, h, l, f, x, p, b, v;
435
- if (!e.content.trim() && (!e.attachments || e.attachments.length === 0)) {
436
- console.warn("Cannot send an empty message of no content or attachments");
437
- return;
438
- }
439
- const t = this.state.get().isSendingMessage, s = ((r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.assignee.kind) === "ai", i = this.state.get().messages, c = i.length > 0 ? i[i.length - 1] : void 0;
440
- if (s && t || // If last message is from user, then bot response did not arrive yet
441
- s && (c == null ? void 0 : c.type) === "FROM_USER") {
442
- console.warn("Cannot send messages while awaiting AI response");
443
- return;
444
- }
445
- this.sendMessageAbortController = new AbortController(), this.state.setPartial({ lastAIResMightSolveUserIssue: !1 });
446
- try {
447
- this.state.setPartial({ isSendingMessage: !0 });
448
- const u = this.toUserMessage(
449
- e.content.trim(),
450
- e.attachments || void 0
451
- ), S = this.state.get().messages;
452
- if (this.state.setPartial({
453
- messages: [...S, u]
454
- }), !((h = this.sessionCtx.sessionState.get().session) != null && h.id)) {
455
- if (!await this.sessionCtx.createSession()) {
456
- console.error("Failed to create session");
457
- return;
458
- }
459
- this.sessionCtx.refreshSessions();
460
- }
461
- const k = (l = this.sessionCtx.sessionState.get().session) == null ? void 0 : l.id;
462
- if (!k) return;
463
- const { data: C } = await this.api.sendMessage(
464
- {
465
- uuid: u.id,
466
- bot_token: this.config.token,
467
- headers: this.config.headers,
468
- query_params: this.config.queryParams,
469
- body_properties: this.config.bodyProperties,
470
- session_id: k,
471
- content: u.content,
472
- attachments: e.attachments,
473
- clientContext: this.config.context,
474
- custom_data: {
475
- ...this.config.messageCustomData || {},
476
- ...e.customData || {}
477
- },
478
- language: this.config.language
479
- },
480
- this.sendMessageAbortController.signal
481
- );
482
- if (C != null && C.success) {
483
- const w = this.toBotMessage(C);
484
- if (w) {
485
- const I = this.state.get().messages;
486
- if (!!I.some(
487
- (A) => A.id === w.id
488
- )) {
489
- this.state.setPartial({
490
- lastAIResMightSolveUserIssue: ((f = C.autopilotResponse) == null ? void 0 : f.mightSolveUserIssue) || ((x = C.uiResponse) == null ? void 0 : x.mightSolveUserIssue)
491
- });
492
- return;
493
- }
494
- this.state.setPartial({
495
- messages: [...I, w],
496
- lastAIResMightSolveUserIssue: ((p = C.autopilotResponse) == null ? void 0 : p.mightSolveUserIssue) || ((b = C.uiResponse) == null ? void 0 : b.mightSolveUserIssue)
497
- });
498
- }
499
- } else {
500
- const w = this.toBotErrorMessage(
501
- ((v = C == null ? void 0 : C.error) == null ? void 0 : v.message) || "Unknown error occurred"
502
- ), I = this.state.get().messages;
503
- this.state.setPartial({
504
- messages: [...I, w]
505
- });
506
- }
507
- } catch (u) {
508
- this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", u);
509
- } finally {
510
- this.state.setPartial({ isSendingMessage: !1 });
511
- }
512
- }, this.toUserMessage = (e, t) => {
513
- const s = (() => {
514
- const i = this.contactCtx.state.get().extraCollectedData;
515
- return this.state.get().messages.length === 0 && i && Object.keys(i).length > 0 ? `${Object.entries(i).filter(([r, h]) => !!h).map(([r, h]) => `${r}: ${h}`).join(`
516
- `)}
517
-
518
- ${e}` : e;
519
- })();
520
- return {
521
- id: y(),
522
- type: "FROM_USER",
523
- content: s,
524
- deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
525
- attachments: t,
526
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
527
- };
528
- }, this.toBotMessage = (e) => {
529
- var t;
530
- return e.success && e.autopilotResponse ? {
531
- type: "FROM_BOT",
532
- id: e.autopilotResponse.id || y(),
533
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
534
- component: "bot_message",
535
- agent: this.config.bot ? {
536
- name: this.config.bot.name || "",
537
- isAi: !0,
538
- avatar: this.config.bot.avatar || "",
539
- id: null
540
- } : void 0,
541
- data: {
542
- message: e.autopilotResponse.value.content,
543
- action: (t = e.uiResponse) != null && t.value.name ? {
544
- name: e.uiResponse.value.name,
545
- data: e.uiResponse.value.request_response
546
- } : void 0
547
- }
548
- } : null;
549
- }, this.toBotErrorMessage = (e) => ({
550
- type: "FROM_BOT",
551
- id: y(),
552
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
553
- component: "TEXT",
554
- data: {
555
- message: e,
556
- variant: "error",
557
- action: void 0
558
- }
559
- }), this.config = n, this.api = a, this.sessionCtx = g, this.contactCtx = o;
560
- }
561
- }
562
- class N {
563
- constructor({
564
- config: n,
565
- contactCtx: a,
566
- sessionCtx: g,
567
- resetChat: o
568
- }) {
569
- var e;
570
- this.registerRoutingListener = () => {
571
- this.contactCtx.state.subscribe(({ contact: t }) => {
572
- var s;
573
- t != null && t.token && this.state.get().screen === "welcome" && this.state.setPartial({
574
- screen: (s = this.config.router) != null && s.chatScreenOnly ? "chat" : "sessions"
575
- });
576
- }), this.sessionCtx.sessionsState.subscribe(
577
- ({ isInitialFetchLoading: t, data: s }) => {
578
- var i, c, r, h;
579
- if ((i = this.config.router) != null && i.chatScreenOnly && // Do not route to a chat if we are currently inside one already
580
- // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
581
- !((c = this.sessionCtx.sessionState.get().session) != null && c.id)) {
582
- const l = (r = s.find((f) => f.isOpened)) == null ? void 0 : r.id;
583
- return l ? this.toChatScreen(l) : void 0;
584
- }
585
- s.length || ((h = this.config.router) == null ? void 0 : h.goToChatIfNoSessions) !== !1 && !t && this.state.get().screen !== "chat" && this.toChatScreen();
586
- }
587
- );
588
- }, this.toSessionsScreen = () => {
589
- this.resetChat(), this.state.setPartial({ screen: "sessions" });
590
- }, this.toChatScreen = (t) => {
591
- if (this.resetChat(), t) {
592
- const s = this.sessionCtx.sessionsState.get().data.find((i) => i.id === t);
593
- if (!s) return;
594
- this.sessionCtx.sessionState.setPartial({ session: s });
595
- }
596
- this.state.setPartial({ screen: "chat" });
597
- }, this.config = n, this.contactCtx = a, this.sessionCtx = g, this.resetChat = o, this.state = new P({
598
- screen: this.contactCtx.shouldCollectData() ? "welcome" : (e = this.config.router) != null && e.chatScreenOnly ? "chat" : "sessions"
599
- }), this.registerRoutingListener();
600
- }
601
- }
602
- class H {
603
- constructor({ storage: n }) {
604
- this.KEYS = {
605
- contactToken: "opencx__widget__contactToken",
606
- externalContactId: "opencx__widget__externalContactId"
607
- }, this.setContactToken = async (a) => {
608
- await this.storage.set(this.KEYS.contactToken, a);
609
- }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken), this.setExternalContactId = async (a) => {
610
- await this.storage.set(this.KEYS.externalContactId, a);
611
- }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId), this.storage = n;
612
- }
613
- }
614
- const m = class m {
615
- constructor({
616
- config: n,
617
- storage: a
618
- }) {
619
- if (this.resetChat = () => {
620
- this.sessionCtx.reset(), this.messageCtx.reset();
621
- }, !m.pollingIntervalsSeconds)
622
- throw Error(
623
- "Widget polling values are not defined, did you call WidgetCtx.initialize()"
624
- );
625
- this.config = n, this.api = new T({ config: n }), this.storageCtx = a ? new H({ storage: a }) : void 0, this.contactCtx = new B({
626
- api: this.api,
627
- config: this.config,
628
- storageCtx: this.storageCtx
629
- }), this.sessionCtx = new q({
630
- api: this.api,
631
- contactCtx: this.contactCtx,
632
- sessionsPollingIntervalSeconds: m.pollingIntervalsSeconds.sessions
633
- }), this.messageCtx = new $({
634
- config: this.config,
635
- api: this.api,
636
- sessionCtx: this.sessionCtx,
637
- contactCtx: this.contactCtx
638
- }), this.activeSessionPollingCtx = new L({
639
- api: this.api,
640
- config: this.config,
641
- sessionCtx: this.sessionCtx,
642
- messageCtx: this.messageCtx,
643
- sessionPollingIntervalSeconds: m.pollingIntervalsSeconds.session
644
- }), this.routerCtx = new N({
645
- config: this.config,
646
- contactCtx: this.contactCtx,
647
- sessionCtx: this.sessionCtx,
648
- resetChat: this.resetChat
649
- });
650
- }
651
- };
652
- m.pollingIntervalsSeconds = null, m.initialize = async ({
653
- config: n,
654
- storage: a
655
- }) => {
656
- var o, e;
657
- const g = await new T({
658
- config: n
659
- }).getExternalWidgetConfig();
660
- return m.pollingIntervalsSeconds = {
661
- session: ((o = g.data) == null ? void 0 : o.sessionPollingIntervalSeconds) || 10,
662
- sessions: ((e = g.data) == null ? void 0 : e.sessionsPollingIntervalSeconds) || 60
663
- }, new m({
664
- config: n,
665
- storage: a
666
- });
667
- };
668
- let U = m;
669
- export {
670
- P,
671
- U as W
672
- };
673
- //# sourceMappingURL=widget.ctx-DFFwNHvy.js.map