@opencx/widget 3.0.47 → 3.0.49

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