@opencx/widget 3.0.57 → 3.0.59

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