@opencx/widget-core 4.0.11 → 4.0.13

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.
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
- import F from "openapi-fetch";
1
+ import D from "openapi-fetch";
2
2
  import L from "lodash.isequal";
3
3
  import { v4 as O } from "uuid";
4
- const q = (g) => {
4
+ const H = (g) => {
5
5
  console.log(g.error);
6
- }, B = (g) => {
7
- const a = F({
6
+ }, q = (g) => {
7
+ const n = D({
8
8
  baseUrl: g.baseUrl
9
- }), o = {
9
+ }), a = {
10
10
  onRequest: g.onRequest,
11
11
  onResponse: g.onResponse,
12
- onError: g.onError || q
12
+ onError: g.onError || H
13
13
  };
14
- return a.use(o), a;
14
+ return n.use(a), n;
15
15
  };
16
16
  class U {
17
- constructor({ config: a }) {
18
- var h, e;
17
+ constructor({ config: n }) {
18
+ var d, e;
19
19
  this.userToken = null, this.constructClientOptions = (t) => {
20
20
  const s = this.config.apiUrl || "https://api.open.cx", i = {
21
21
  "X-Bot-Token": this.config.token,
@@ -27,11 +27,11 @@ class U {
27
27
  }, this.createOpenAPIClient = ({
28
28
  baseUrl: t,
29
29
  headers: s
30
- }) => B({
30
+ }) => q({
31
31
  baseUrl: t,
32
32
  onRequest: ({ request: i }) => {
33
- Object.entries(s).forEach(([r, n]) => {
34
- n && i.headers.set(r, n);
33
+ Object.entries(s).forEach(([o, r]) => {
34
+ r && i.headers.set(o, r);
35
35
  });
36
36
  }
37
37
  }), this.setAuthToken = (t) => {
@@ -58,9 +58,9 @@ class U {
58
58
  lastMessageTimestamp: s,
59
59
  abortSignal: i
60
60
  }) => {
61
- const r = s ? { lastMessageTimestamp: s } : void 0;
61
+ const o = s ? { lastMessageTimestamp: s } : void 0;
62
62
  return await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
63
- params: { path: { sessionId: t }, query: r },
63
+ params: { path: { sessionId: t }, query: o },
64
64
  signal: i
65
65
  });
66
66
  }, this.getSessions = async ({
@@ -74,91 +74,91 @@ class U {
74
74
  file: t,
75
75
  abortSignal: s,
76
76
  onProgress: i
77
- }) => new Promise((r, n) => {
78
- var b;
79
- const d = new FormData();
80
- d.append("file", t);
81
- const l = new XMLHttpRequest();
77
+ }) => new Promise((o, r) => {
78
+ var w;
79
+ const l = new FormData();
80
+ l.append("file", t);
81
+ const h = new XMLHttpRequest();
82
82
  if (s && (s.addEventListener("abort", () => {
83
- l.abort(), n(new DOMException("Aborted", "AbortError"));
83
+ h.abort(), r(new DOMException("Aborted", "AbortError"));
84
84
  }), s.aborted)) {
85
- n(new DOMException("Aborted", "AbortError"));
85
+ r(new DOMException("Aborted", "AbortError"));
86
86
  return;
87
87
  }
88
- l.upload.addEventListener("progress", (f) => {
88
+ h.upload.addEventListener("progress", (f) => {
89
89
  if (f.lengthComputable && i) {
90
- const C = Math.round(f.loaded / f.total * 100);
91
- i(C);
90
+ const S = Math.round(f.loaded / f.total * 100);
91
+ i(S);
92
92
  }
93
- }), l.addEventListener("load", () => {
94
- if (l.status >= 200 && l.status < 300)
93
+ }), h.addEventListener("load", () => {
94
+ if (h.status >= 200 && h.status < 300)
95
95
  try {
96
- const f = JSON.parse(l.responseText);
97
- r(f);
96
+ const f = JSON.parse(h.responseText);
97
+ o(f);
98
98
  } catch (f) {
99
- n(new Error(`Failed to parse response: ${f}`));
99
+ r(new Error(`Failed to parse response: ${f}`));
100
100
  }
101
101
  else
102
- n(new Error(`Upload failed with status: ${l.status}`));
103
- }), l.addEventListener("error", () => {
104
- n(new Error("Network error occurred"));
105
- }), l.addEventListener("timeout", () => {
106
- n(new Error("Upload timed out"));
102
+ r(new Error(`Upload failed with status: ${h.status}`));
103
+ }), h.addEventListener("error", () => {
104
+ r(new Error("Network error occurred"));
105
+ }), h.addEventListener("timeout", () => {
106
+ r(new Error("Upload timed out"));
107
107
  });
108
- const { baseUrl: m } = this.constructClientOptions(this.userToken), x = `${m}/backend/widget/v2/upload`;
109
- l.open("POST", x), l.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((b = this.config.user) == null ? void 0 : b.token) ? l.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), l.send(d);
108
+ const { baseUrl: m } = this.constructClientOptions(this.userToken), C = `${m}/backend/widget/v2/upload`;
109
+ h.open("POST", C), h.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((w = this.config.user) == null ? void 0 : w.token) ? h.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), h.send(l);
110
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
111
  body: t,
112
112
  signal: s
113
113
  }), this.createStateCheckpoint = async (t) => await this.client.POST("/backend/widget/v2/checkpoint", {
114
114
  body: t
115
- }), this.submitCsat = async (t) => await this.client.POST("/backend/widget/v2/submit-csat", { body: t }), this.config = a, this.userToken = ((h = a.user) == null ? void 0 : h.token) || null;
116
- const { baseUrl: o, headers: c } = this.constructClientOptions(
117
- (e = a.user) == null ? void 0 : e.token
115
+ }), this.submitCsat = async (t) => await this.client.POST("/backend/widget/v2/submit-csat", { body: t }), this.config = n, this.userToken = ((d = n.user) == null ? void 0 : d.token) || null;
116
+ const { baseUrl: a, headers: c } = this.constructClientOptions(
117
+ (e = n.user) == null ? void 0 : e.token
118
118
  );
119
- this.client = this.createOpenAPIClient({ baseUrl: o, headers: c });
119
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: c });
120
120
  }
121
121
  }
122
- function $(g, a) {
123
- console.error(`Missing case for ${g} in ${a}`);
122
+ function B(g, n) {
123
+ console.error(`Missing case for ${g} in ${n}`);
124
124
  }
125
125
  class y {
126
- constructor(a) {
127
- this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (o) => {
128
- L(this.state, o) || (this.state = o, this.notifySubscribers(o));
129
- }, this.setPartial = (o) => {
130
- if (o == null) return;
131
- const c = { ...this.state, ...o };
126
+ constructor(n) {
127
+ this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
128
+ L(this.state, a) || (this.state = a, this.notifySubscribers(a));
129
+ }, this.setPartial = (a) => {
130
+ if (a == null) return;
131
+ const c = { ...this.state, ...a };
132
132
  this.set(c);
133
133
  }, this.reset = () => {
134
134
  this.set(this.initialState);
135
- }, this.notifySubscribers = (o) => {
136
- Array.from(this.subscribers).forEach((h) => {
135
+ }, this.notifySubscribers = (a) => {
136
+ Array.from(this.subscribers).forEach((d) => {
137
137
  try {
138
- h(o);
138
+ d(a);
139
139
  } catch (e) {
140
140
  console.error(e);
141
141
  }
142
142
  });
143
- }, this.subscribe = (o) => (this.subscribers.add(o), () => {
144
- this.subscribers.delete(o);
145
- }), this.state = a, this.initialState = a;
143
+ }, this.subscribe = (a) => (this.subscribers.add(a), () => {
144
+ this.subscribers.delete(a);
145
+ }), this.state = n, this.initialState = n;
146
146
  }
147
147
  }
148
- class _ {
148
+ class F {
149
149
  constructor() {
150
150
  this.state = new y({
151
151
  isPolling: !1,
152
152
  isError: !1
153
153
  }), this.abortController = new AbortController(), this.reset = () => {
154
- var a;
155
- this.abortController.abort("Resetting poller"), (a = this.stopPolling) == null || a.call(this), this.stopPolling = null;
156
- }, this.stopPolling = null, this.startPolling = (a, o) => {
154
+ var n;
155
+ this.abortController.abort("Resetting poller"), (n = this.stopPolling) == null || n.call(this), this.stopPolling = null;
156
+ }, this.stopPolling = null, this.startPolling = (n, a) => {
157
157
  if (this.stopPolling) return;
158
- const c = [], h = async () => {
158
+ const c = [], d = async () => {
159
159
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
160
160
  try {
161
- await a(this.abortController.signal);
161
+ await n(this.abortController.signal);
162
162
  } catch (e) {
163
163
  if (this.abortController.signal.aborted)
164
164
  return;
@@ -166,55 +166,72 @@ class _ {
166
166
  } finally {
167
167
  this.state.setPartial({ isPolling: !1 });
168
168
  }
169
- this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : c.push(setTimeout(h, o));
169
+ this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : c.push(setTimeout(d, a));
170
170
  };
171
- h(), this.stopPolling = () => {
171
+ d(), this.stopPolling = () => {
172
172
  c.forEach(clearTimeout), this.state.reset();
173
173
  };
174
174
  };
175
175
  }
176
176
  }
177
- function N(g) {
177
+ function $(g) {
178
178
  try {
179
- const a = g();
180
- return a instanceof Promise ? a.then((o) => ({ data: o })).catch((o) => ({ error: o })) : { data: a };
181
- } catch (a) {
182
- return { error: a };
179
+ const n = g();
180
+ return n instanceof Promise ? n.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: n };
181
+ } catch (n) {
182
+ return { error: n };
183
183
  }
184
184
  }
185
- class Y {
185
+ class N {
186
186
  constructor({
187
- api: a,
188
- config: o,
187
+ api: n,
188
+ config: a,
189
189
  sessionCtx: c,
190
- messageCtx: h,
190
+ messageCtx: d,
191
191
  sessionPollingIntervalSeconds: e
192
192
  }) {
193
- this.poller = new _(), this.registerPolling = () => {
193
+ this.poller = new F(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.registerPolling = () => {
194
194
  this.sessionCtx.sessionState.subscribe(({ session: t }) => {
195
195
  t != null && t.id ? this.poller.startPolling(async (s) => {
196
- this.hackAndSlash(t.id, s);
196
+ this.fetchSessionAndHistory({ sessionId: t.id, abortSignal: s });
197
197
  }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
198
+ }), this.sessionCtx.sessionState.subscribe(({ session: t }) => {
199
+ if (t != null && t.id && !t.isOpened)
200
+ try {
201
+ this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.fetchSessionAndHistory({
202
+ sessionId: t.id,
203
+ abortSignal: this.fetchSessionAndFullHistoryAbortController.signal,
204
+ fetchFullHistory: !0
205
+ });
206
+ } catch (s) {
207
+ this.fetchSessionAndFullHistoryAbortController.signal.aborted || console.error("Failed to fetch session and full history:", s);
208
+ }
209
+ else
210
+ this.fetchSessionAndFullHistoryAbortController.abort();
198
211
  });
199
- }, this.hackAndSlash = async (t, s) => {
200
- var d;
212
+ }, this.fetchSessionAndHistory = async ({
213
+ sessionId: t,
214
+ abortSignal: s,
215
+ fetchFullHistory: i = !1
216
+ }) => {
217
+ var h;
201
218
  this.messageCtx.state.get().messages.length === 0 && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
202
- const i = this.messageCtx.state.get().messages, r = i.length > 0 ? ((d = i[i.length - 1]) == null ? void 0 : d.timestamp) ?? void 0 : void 0, { data: n } = await this.api.pollSessionAndHistory({
219
+ const o = this.messageCtx.state.get().messages, r = o.length > 0 ? ((h = o[o.length - 1]) == null ? void 0 : h.timestamp) ?? void 0 : void 0, { data: l } = await this.api.pollSessionAndHistory({
203
220
  sessionId: t,
204
221
  abortSignal: s,
205
- lastMessageTimestamp: r
222
+ lastMessageTimestamp: i ? void 0 : r
206
223
  });
207
- if (n != null && n.session && (this.sessionCtx.sessionState.setPartial({ session: n.session }), this.sessionCtx.setSessions([n.session])), n != null && n.history && n.history.length > 0) {
208
- const l = this.messageCtx.state.get().messages, m = n.history.map(this.mapHistoryToMessage).filter((S) => S !== null).filter(
209
- (S) => !l.some((x) => x.id === S.id)
224
+ 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) {
225
+ const m = this.messageCtx.state.get().messages, v = l.history.map(this.mapHistoryToMessage).filter((C) => C !== null).filter(
226
+ (C) => !m.some((x) => x.id === C.id)
210
227
  );
211
228
  this.messageCtx.state.setPartial({
212
- messages: [...l, ...m]
229
+ messages: [...m, ...v]
213
230
  });
214
231
  }
215
232
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
216
233
  }, this.mapHistoryToMessage = (t) => {
217
- var i, r;
234
+ var i, o;
218
235
  const s = {
219
236
  id: t.publicId,
220
237
  timestamp: t.sentAt || "",
@@ -243,7 +260,7 @@ class Y {
243
260
  }
244
261
  };
245
262
  if (t.sender.kind === "ai") {
246
- const n = t.actionCalls && t.actionCalls.length > 0 ? t.actionCalls[t.actionCalls.length - 1] : void 0;
263
+ const r = t.actionCalls && t.actionCalls.length > 0 ? t.actionCalls[t.actionCalls.length - 1] : void 0;
247
264
  return {
248
265
  ...s,
249
266
  type: "AI",
@@ -252,20 +269,20 @@ class Y {
252
269
  id: null,
253
270
  name: ((i = this.config.bot) == null ? void 0 : i.name) || "",
254
271
  isAi: !0,
255
- avatar: ((r = this.config.bot) == null ? void 0 : r.avatar) || ""
272
+ avatar: ((o = this.config.bot) == null ? void 0 : o.avatar) || ""
256
273
  },
257
274
  data: {
258
275
  message: t.content.text || "",
259
- action: n ? {
260
- name: n.actionName,
261
- data: this.extractActionResult(n)
276
+ action: r ? {
277
+ name: r.actionName,
278
+ data: this.extractActionResult(r)
262
279
  } : void 0
263
280
  }
264
281
  };
265
282
  }
266
283
  if (t.sender.kind === "system") {
267
- const n = this.constructSystemMessage(t);
268
- return n === null ? null : { ...n };
284
+ const r = this.constructSystemMessage(t);
285
+ return r === null ? null : { ...r };
269
286
  }
270
287
  return null;
271
288
  }, this.constructSystemMessage = (t) => {
@@ -306,7 +323,7 @@ class Y {
306
323
  case "none":
307
324
  return null;
308
325
  default:
309
- return $(
326
+ return B(
310
327
  t.systemMessagePayload,
311
328
  this.constructSystemMessage.name
312
329
  ), null;
@@ -315,44 +332,44 @@ class Y {
315
332
  const s = t.result;
316
333
  if (s === null || typeof s != "object") return s;
317
334
  if ("responseBodyText" in s && typeof s.responseBodyText == "string") {
318
- const i = s.responseBodyText, r = N(() => JSON.parse(i)).data;
319
- if (r) return r;
335
+ const i = s.responseBodyText, o = $(() => JSON.parse(i)).data;
336
+ if (o) return o;
320
337
  }
321
338
  return t.result;
322
- }, this.api = a, this.config = o, this.sessionCtx = c, this.messageCtx = h, this.sessionPollingIntervalSeconds = e, this.registerPolling();
339
+ }, this.api = n, this.config = a, this.sessionCtx = c, this.messageCtx = d, this.sessionPollingIntervalSeconds = e, this.registerPolling();
323
340
  }
324
341
  }
325
- class H {
342
+ class Y {
326
343
  constructor({
327
- config: a,
328
- api: o,
344
+ config: n,
345
+ api: a,
329
346
  storageCtx: c
330
347
  }) {
331
- var h;
348
+ var d;
332
349
  this.shouldCollectData = () => {
333
350
  var e;
334
351
  return !!(!((e = this.state.get().contact) != null && e.token) && this.config.collectUserData);
335
352
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
336
- var e, t, s, i, r, n, d, l, m, S, x, w, b, f;
353
+ var e, t, s, i, o, r, l, h, m, v, C, x, w, f;
337
354
  if (!((e = this.config.user) != null && e.token)) {
338
355
  if (this.config.collectUserData && !((s = (t = this.config.user) == null ? void 0 : t.data) != null && s.email)) {
339
356
  if ((i = this.config.extraDataCollectionFields) != null && i.length)
340
357
  return;
341
- const C = await ((r = this.storageCtx) == null ? void 0 : r.getContactToken());
342
- C && await this.setUnverifiedContact(C);
358
+ const S = await ((o = this.storageCtx) == null ? void 0 : o.getContactToken());
359
+ S && await this.setUnverifiedContact(S);
343
360
  return;
344
361
  }
345
- if (!((d = (n = this.config.user) == null ? void 0 : n.data) != null && d.email)) {
346
- const C = await ((l = this.storageCtx) == null ? void 0 : l.getContactToken());
347
- if (C) {
348
- await this.setUnverifiedContact(C);
362
+ if (!((l = (r = this.config.user) == null ? void 0 : r.data) != null && l.email)) {
363
+ const S = await ((h = this.storageCtx) == null ? void 0 : h.getContactToken());
364
+ if (S) {
365
+ await this.setUnverifiedContact(S);
349
366
  return;
350
367
  }
351
368
  }
352
369
  await this.createUnverifiedContact({
353
- email: (S = (m = this.config.user) == null ? void 0 : m.data) == null ? void 0 : S.email,
354
- non_verified_name: ((w = (x = this.config.user) == null ? void 0 : x.data) == null ? void 0 : w.name) || "Anonymous",
355
- non_verified_custom_data: (f = (b = this.config.user) == null ? void 0 : b.data) == null ? void 0 : f.customData
370
+ email: (v = (m = this.config.user) == null ? void 0 : m.data) == null ? void 0 : v.email,
371
+ non_verified_name: ((x = (C = this.config.user) == null ? void 0 : C.data) == null ? void 0 : x.name) || "Anonymous",
372
+ non_verified_custom_data: (f = (w = this.config.user) == null ? void 0 : w.data) == null ? void 0 : f.customData
356
373
  });
357
374
  }
358
375
  }, this.createUnverifiedContact = async (e, t) => {
@@ -368,14 +385,14 @@ class H {
368
385
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
369
386
  }
370
387
  }, this.setUnverifiedContact = async (e) => {
371
- var i, r, n, d;
372
- const t = await ((i = this.storageCtx) == null ? void 0 : i.getExternalContactId()), s = ((r = this.config.user) == null ? void 0 : r.externalId) || t || O();
373
- this.api.setAuthToken(e), await ((n = this.storageCtx) == null ? void 0 : n.setContactToken(e)), await ((d = this.storageCtx) == null ? void 0 : d.setExternalContactId(s)), this.state.setPartial({ contact: { token: e, externalId: s } });
374
- }, this.config = a, this.storageCtx = c, this.api = o, this.state = new y({
375
- contact: (h = a.user) != null && h.token ? {
376
- token: a.user.token,
388
+ var i, o, r, l;
389
+ const t = await ((i = this.storageCtx) == null ? void 0 : i.getExternalContactId()), s = ((o = this.config.user) == null ? void 0 : o.externalId) || t || O();
390
+ this.api.setAuthToken(e), await ((r = this.storageCtx) == null ? void 0 : r.setContactToken(e)), await ((l = this.storageCtx) == null ? void 0 : l.setExternalContactId(s)), this.state.setPartial({ contact: { token: e, externalId: s } });
391
+ }, this.config = n, this.storageCtx = c, this.api = a, this.state = new y({
392
+ contact: (d = n.user) != null && d.token ? {
393
+ token: n.user.token,
377
394
  // Set optional externalId from config... not local storage
378
- externalId: a.user.externalId
395
+ externalId: n.user.externalId
379
396
  } : null,
380
397
  extraCollectedData: void 0,
381
398
  isCreatingUnverifiedContact: !1,
@@ -383,22 +400,22 @@ class H {
383
400
  }), this.autoCreateUnverifiedUserIfNotExists();
384
401
  }
385
402
  }
386
- function P() {
403
+ function I() {
387
404
  return O();
388
405
  }
389
406
  class X {
390
407
  constructor({
391
- config: a,
392
- api: o,
408
+ config: n,
409
+ api: a,
393
410
  sessionCtx: c,
394
- messageCtx: h
411
+ messageCtx: d
395
412
  }) {
396
413
  this.submitCsat = async (e) => {
397
- var n;
398
- const t = (n = this.sessionCtx.sessionState.get().session) == null ? void 0 : n.id;
414
+ var r;
415
+ const t = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
399
416
  if (!t)
400
417
  return { data: null, error: "No session id found" };
401
- const s = P();
418
+ const s = I();
402
419
  this.messageCtx.state.setPartial({
403
420
  messages: [
404
421
  ...this.messageCtx.state.get().messages,
@@ -416,23 +433,23 @@ class X {
416
433
  }
417
434
  ]
418
435
  });
419
- const { data: i, error: r } = await this.api.submitCsat({
436
+ const { data: i, error: o } = await this.api.submitCsat({
420
437
  ...e,
421
438
  system_message_uuid: s,
422
439
  session_id: t
423
440
  });
424
- return { data: i, error: r };
425
- }, this.config = a, this.api = o, this.sessionCtx = c, this.messageCtx = h;
441
+ return { data: i, error: o };
442
+ }, this.config = n, this.api = a, this.sessionCtx = c, this.messageCtx = d;
426
443
  }
427
444
  }
428
445
  class G {
429
446
  constructor({
430
- config: a,
431
- api: o,
447
+ config: n,
448
+ api: a,
432
449
  contactCtx: c,
433
- sessionsPollingIntervalSeconds: h
450
+ sessionsPollingIntervalSeconds: d
434
451
  }) {
435
- this.sessionsRefresher = new _(), this.sessionState = new y({
452
+ this.sessionsRefresher = new F(), this.sessionState = new y({
436
453
  session: null,
437
454
  isCreatingSession: !1,
438
455
  isResolvingSession: !1
@@ -458,9 +475,9 @@ class G {
458
475
  this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
459
476
  }, this.sessionsPollingIntervalSeconds * 1e3);
460
477
  }, this.createSession = async () => {
461
- var r;
478
+ var o;
462
479
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
463
- const e = (r = this.contactCtx.state.get().contact) == null ? void 0 : r.externalId, t = {
480
+ const e = (o = this.contactCtx.state.get().contact) == null ? void 0 : o.externalId, t = {
464
481
  ...this.config.sessionCustomData,
465
482
  ...e ? { external_id: e } : {}
466
483
  }, { data: s, error: i } = await this.api.createSession({
@@ -474,7 +491,7 @@ class G {
474
491
  });
475
492
  if (e) {
476
493
  const s = [...this.sessionsState.get().data, ...e.items].filter(
477
- (i, r, n) => r === n.findIndex((d) => i.id === d.id)
494
+ (i, o, r) => o === r.findIndex((l) => i.id === l.id)
478
495
  );
479
496
  this.sessionsState.setPartial({
480
497
  data: s,
@@ -494,7 +511,7 @@ class G {
494
511
  });
495
512
  }, this.setSessions = (e) => {
496
513
  const t = [...e, ...this.sessionsState.get().data].filter(
497
- (s, i, r) => i === r.findIndex((n) => s.id === n.id)
514
+ (s, i, o) => i === o.findIndex((r) => s.id === r.id)
498
515
  );
499
516
  this.sessionsState.setPartial({ data: t });
500
517
  }, this.refreshSessions = async () => {
@@ -510,23 +527,23 @@ class G {
510
527
  });
511
528
  return t ? (this.sessionState.setPartial({ session: t, isResolvingSession: !1 }), { success: !0, data: t }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: s });
512
529
  }, this.createStateCheckpoint = async (e) => {
513
- var r;
514
- const t = (r = this.sessionState.get().session) == null ? void 0 : r.id;
530
+ var o;
531
+ const t = (o = this.sessionState.get().session) == null ? void 0 : o.id;
515
532
  if (!t) return;
516
533
  const { data: s, error: i } = await this.api.createStateCheckpoint({
517
534
  session_id: t,
518
535
  payload: e
519
536
  });
520
537
  return s ? { data: s } : { success: !1, error: i };
521
- }, this.config = a, this.api = o, this.contactCtx = c, this.sessionsPollingIntervalSeconds = h, this.registerSessionsRefresherWrapper();
538
+ }, this.config = n, this.api = a, this.contactCtx = c, this.sessionsPollingIntervalSeconds = d, this.registerSessionsRefresherWrapper();
522
539
  }
523
540
  }
524
541
  class K {
525
542
  constructor({
526
- config: a,
527
- api: o,
543
+ config: n,
544
+ api: a,
528
545
  sessionCtx: c,
529
- contactCtx: h
546
+ contactCtx: d
530
547
  }) {
531
548
  this.state = new y({
532
549
  messages: [],
@@ -536,7 +553,7 @@ class K {
536
553
  }), this.sendMessageAbortController = new AbortController(), this.reset = () => {
537
554
  this.sendMessageAbortController.abort("Resetting chat"), this.state.reset();
538
555
  }, this.sendMessage = async (e) => {
539
- var t, s, i, r, n, d, l, m, S, x;
556
+ var t, s, i, o, r, l, h, m, v, C;
540
557
  try {
541
558
  if (!e.content.trim() && (!e.attachments || e.attachments.length === 0)) {
542
559
  console.warn(
@@ -544,16 +561,16 @@ class K {
544
561
  );
545
562
  return;
546
563
  }
547
- const w = this.state.get().isSendingMessage, b = ((t = this.sessionCtx.sessionState.get().session) == null ? void 0 : t.assignee.kind) === "ai", f = this.state.get().messages, C = f.length > 0 ? f[f.length - 1] : void 0;
548
- if (b && w || // If last message is from user, then bot response did not arrive yet
549
- b && (C == null ? void 0 : C.type) === "USER") {
564
+ const x = this.state.get().isSendingMessage, w = ((t = this.sessionCtx.sessionState.get().session) == null ? void 0 : t.assignee.kind) === "ai", f = this.state.get().messages, S = f.length > 0 ? f[f.length - 1] : void 0;
565
+ if (w && x || // If last message is from user, then bot response did not arrive yet
566
+ w && (S == null ? void 0 : S.type) === "USER") {
550
567
  console.warn("Cannot send messages while awaiting AI response");
551
568
  return;
552
569
  }
553
570
  this.sendMessageAbortController = new AbortController(), this.state.setPartial({ lastAIResMightSolveUserIssue: !1 }), this.state.setPartial({ isSendingMessage: !0 });
554
- const A = this.state.get().messages, E = !((s = this.sessionCtx.sessionState.get().session) != null && s.id) && A.length === 0 && ((i = this.config.advancedInitialMessages) == null ? void 0 : i.some((u) => u.persistent)), M = E ? (this.config.advancedInitialMessages || []).filter((u) => u.persistent).map(
571
+ const A = this.state.get().messages, M = !((s = this.sessionCtx.sessionState.get().session) != null && s.id) && A.length === 0 && ((i = this.config.advancedInitialMessages) == null ? void 0 : i.some((u) => u.persistent)), E = M ? (this.config.advancedInitialMessages || []).filter((u) => u.persistent).map(
555
572
  (u) => ({
556
- id: P(),
573
+ id: I(),
557
574
  component: "bot_message",
558
575
  type: "AI",
559
576
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -567,18 +584,18 @@ class K {
567
584
  );
568
585
  if (this.state.setPartial({
569
586
  messages: [
570
- ...M,
587
+ ...E,
571
588
  ...A,
572
589
  k
573
590
  ]
574
- }), !((r = this.sessionCtx.sessionState.get().session) != null && r.id)) {
591
+ }), !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
575
592
  if (!await this.sessionCtx.createSession()) {
576
593
  console.error("Failed to create session");
577
594
  return;
578
595
  }
579
596
  this.sessionCtx.refreshSessions();
580
597
  }
581
- const T = (n = this.sessionCtx.sessionState.get().session) == null ? void 0 : n.id;
598
+ const T = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
582
599
  if (!T) return;
583
600
  const { data: p } = await this.api.sendMessage(
584
601
  {
@@ -597,7 +614,7 @@ class K {
597
614
  },
598
615
  language: this.config.language,
599
616
  exit_mode_prompt: e.exitModePrompt,
600
- initial_messages: E ? M.map((u) => ({
617
+ initial_messages: M ? E.map((u) => ({
601
618
  uuid: u.id,
602
619
  content: u.data.message
603
620
  })) : void 0
@@ -607,44 +624,44 @@ class K {
607
624
  if (p != null && p.success) {
608
625
  const u = this.toBotMessage(p);
609
626
  if (u) {
610
- const I = this.state.get().messages;
611
- if (!!I.some(
612
- (D) => D.id === u.id
627
+ const P = this.state.get().messages;
628
+ if (!!P.some(
629
+ (_) => _.id === u.id
613
630
  )) {
614
631
  this.state.setPartial({
615
- lastAIResMightSolveUserIssue: ((d = p.autopilotResponse) == null ? void 0 : d.mightSolveUserIssue) || ((l = p.uiResponse) == null ? void 0 : l.mightSolveUserIssue)
632
+ lastAIResMightSolveUserIssue: ((l = p.autopilotResponse) == null ? void 0 : l.mightSolveUserIssue) || ((h = p.uiResponse) == null ? void 0 : h.mightSolveUserIssue)
616
633
  });
617
634
  return;
618
635
  }
619
636
  this.state.setPartial({
620
- messages: [...I, u],
621
- lastAIResMightSolveUserIssue: ((m = p.autopilotResponse) == null ? void 0 : m.mightSolveUserIssue) || ((S = p.uiResponse) == null ? void 0 : S.mightSolveUserIssue)
637
+ messages: [...P, u],
638
+ lastAIResMightSolveUserIssue: ((m = p.autopilotResponse) == null ? void 0 : m.mightSolveUserIssue) || ((v = p.uiResponse) == null ? void 0 : v.mightSolveUserIssue)
622
639
  });
623
640
  }
624
641
  p.session && this.sessionCtx.sessionState.setPartial({ session: p.session });
625
642
  } else {
626
643
  const u = this.toBotErrorMessage(
627
- ((x = p == null ? void 0 : p.error) == null ? void 0 : x.message) || "Unknown error occurred"
628
- ), I = this.state.get().messages;
644
+ ((C = p == null ? void 0 : p.error) == null ? void 0 : C.message) || "Unknown error occurred"
645
+ ), P = this.state.get().messages;
629
646
  this.state.setPartial({
630
- messages: [...I, u]
647
+ messages: [...P, u]
631
648
  });
632
649
  }
633
- } catch (w) {
634
- this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", w);
650
+ } catch (x) {
651
+ this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", x);
635
652
  } finally {
636
653
  this.state.setPartial({ isSendingMessage: !1 });
637
654
  }
638
655
  }, this.toUserMessage = (e, t) => {
639
656
  const s = (() => {
640
657
  const i = this.contactCtx.state.get().extraCollectedData;
641
- return this.state.get().messages.length === 0 && i && Object.keys(i).length > 0 ? `${Object.entries(i).filter(([n, d]) => !!d).map(([n, d]) => `${n}: ${d}`).join(`
658
+ return this.state.get().messages.length === 0 && i && Object.keys(i).length > 0 ? `${Object.entries(i).filter(([r, l]) => !!l).map(([r, l]) => `${r}: ${l}`).join(`
642
659
  `)}
643
660
 
644
661
  ${e}` : e;
645
662
  })();
646
663
  return {
647
- id: P(),
664
+ id: I(),
648
665
  type: "USER",
649
666
  content: s,
650
667
  deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -655,7 +672,7 @@ ${e}` : e;
655
672
  var t;
656
673
  return e.success && e.autopilotResponse ? {
657
674
  type: "AI",
658
- id: e.autopilotResponse.id || P(),
675
+ id: e.autopilotResponse.id || I(),
659
676
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
660
677
  component: "bot_message",
661
678
  agent: this.config.bot ? {
@@ -674,7 +691,7 @@ ${e}` : e;
674
691
  } : null;
675
692
  }, this.toBotErrorMessage = (e) => ({
676
693
  type: "AI",
677
- id: P(),
694
+ id: I(),
678
695
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
679
696
  component: "TEXT",
680
697
  data: {
@@ -682,15 +699,15 @@ ${e}` : e;
682
699
  variant: "error",
683
700
  action: void 0
684
701
  }
685
- }), this.config = a, this.api = o, this.sessionCtx = c, this.contactCtx = h;
702
+ }), this.config = n, this.api = a, this.sessionCtx = c, this.contactCtx = d;
686
703
  }
687
704
  }
688
705
  class z {
689
706
  constructor({
690
- config: a,
691
- contactCtx: o,
707
+ config: n,
708
+ contactCtx: a,
692
709
  sessionCtx: c,
693
- resetChat: h
710
+ resetChat: d
694
711
  }) {
695
712
  var e;
696
713
  this.registerRoutingListener = () => {
@@ -701,14 +718,14 @@ class z {
701
718
  });
702
719
  }), this.sessionCtx.sessionsState.subscribe(
703
720
  ({ isInitialFetchLoading: t, data: s }) => {
704
- var i, r, n, d;
721
+ var i, o, r, l;
705
722
  if ((i = this.config.router) != null && i.chatScreenOnly && // Do not route to a chat if we are currently inside one already
706
723
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
707
- !((r = this.sessionCtx.sessionState.get().session) != null && r.id)) {
708
- const l = (n = s.find((m) => m.isOpened)) == null ? void 0 : n.id;
709
- return l ? this.toChatScreen(l) : void 0;
724
+ !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
725
+ const h = (r = s.find((m) => m.isOpened)) == null ? void 0 : r.id;
726
+ return h ? this.toChatScreen(h) : void 0;
710
727
  }
711
- s.length || ((d = this.config.router) == null ? void 0 : d.goToChatIfNoSessions) !== !1 && !t && this.state.get().screen !== "chat" && this.toChatScreen();
728
+ s.length || ((l = this.config.router) == null ? void 0 : l.goToChatIfNoSessions) !== !1 && !t && this.state.get().screen !== "chat" && this.toChatScreen();
712
729
  }
713
730
  );
714
731
  }, this.toSessionsScreen = () => {
@@ -720,15 +737,15 @@ class z {
720
737
  this.sessionCtx.sessionState.setPartial({ session: s });
721
738
  }
722
739
  this.state.setPartial({ screen: "chat" });
723
- }, this.config = a, this.contactCtx = o, this.sessionCtx = c, this.resetChat = h, this.state = new y({
740
+ }, this.config = n, this.contactCtx = a, this.sessionCtx = c, this.resetChat = d, this.state = new y({
724
741
  screen: this.contactCtx.shouldCollectData() ? "welcome" : (e = this.config.router) != null && e.chatScreenOnly ? "chat" : "sessions"
725
742
  }), this.registerRoutingListener();
726
743
  }
727
744
  }
728
745
  class j {
729
746
  constructor({
730
- storage: a,
731
- config: o
747
+ storage: n,
748
+ config: a
732
749
  }) {
733
750
  this.KEYS = {
734
751
  contactToken: (c) => `opencx-widget:org-token-${c}:contact-token`,
@@ -737,22 +754,22 @@ class j {
737
754
  await this.storage.set(this.KEYS.contactToken(this.config.token), c);
738
755
  }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken(this.config.token)), this.setExternalContactId = async (c) => {
739
756
  await this.storage.set(this.KEYS.externalContactId(this.config.token), c);
740
- }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.storage = a, this.config = o;
757
+ }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.storage = n, this.config = a;
741
758
  }
742
759
  }
743
- const v = class v {
760
+ const b = class b {
744
761
  constructor({
745
- config: a,
746
- storage: o,
762
+ config: n,
763
+ storage: a,
747
764
  modes: c
748
765
  }) {
749
766
  if (this.modes = [], this.resetChat = () => {
750
767
  this.sessionCtx.reset(), this.messageCtx.reset();
751
- }, !v.pollingIntervalsSeconds)
768
+ }, !b.pollingIntervalsSeconds)
752
769
  throw Error(
753
770
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
754
771
  );
755
- this.config = a, this.api = new U({ config: a }), this.storageCtx = o ? new j({ storage: o, config: a }) : void 0, this.modes = c, this.contactCtx = new H({
772
+ this.config = n, this.api = new U({ config: n }), this.storageCtx = a ? new j({ storage: a, config: n }) : void 0, this.modes = c, this.contactCtx = new Y({
756
773
  api: this.api,
757
774
  config: this.config,
758
775
  storageCtx: this.storageCtx
@@ -760,7 +777,7 @@ const v = class v {
760
777
  config: this.config,
761
778
  api: this.api,
762
779
  contactCtx: this.contactCtx,
763
- sessionsPollingIntervalSeconds: v.pollingIntervalsSeconds.sessions
780
+ sessionsPollingIntervalSeconds: b.pollingIntervalsSeconds.sessions
764
781
  }), this.messageCtx = new K({
765
782
  config: this.config,
766
783
  api: this.api,
@@ -771,12 +788,12 @@ const v = class v {
771
788
  api: this.api,
772
789
  sessionCtx: this.sessionCtx,
773
790
  messageCtx: this.messageCtx
774
- }), this.activeSessionPollingCtx = new Y({
791
+ }), this.activeSessionPollingCtx = new N({
775
792
  api: this.api,
776
793
  config: this.config,
777
794
  sessionCtx: this.sessionCtx,
778
795
  messageCtx: this.messageCtx,
779
- sessionPollingIntervalSeconds: v.pollingIntervalsSeconds.session
796
+ sessionPollingIntervalSeconds: b.pollingIntervalsSeconds.session
780
797
  }), this.routerCtx = new z({
781
798
  config: this.config,
782
799
  contactCtx: this.contactCtx,
@@ -785,27 +802,27 @@ const v = class v {
785
802
  });
786
803
  }
787
804
  };
788
- v.pollingIntervalsSeconds = null, v.initialize = async ({
789
- config: a,
790
- storage: o
805
+ b.pollingIntervalsSeconds = null, b.initialize = async ({
806
+ config: n,
807
+ storage: a
791
808
  }) => {
792
- var h, e, t;
809
+ var d, e, t;
793
810
  const c = await new U({
794
- config: a
811
+ config: n
795
812
  }).getExternalWidgetConfig();
796
- return v.pollingIntervalsSeconds = {
797
- session: ((h = c.data) == null ? void 0 : h.sessionPollingIntervalSeconds) || 10,
813
+ return b.pollingIntervalsSeconds = {
814
+ session: ((d = c.data) == null ? void 0 : d.sessionPollingIntervalSeconds) || 10,
798
815
  sessions: ((e = c.data) == null ? void 0 : e.sessionsPollingIntervalSeconds) || 60
799
- }, new v({
800
- config: a,
801
- storage: o,
816
+ }, new b({
817
+ config: n,
818
+ storage: a,
802
819
  modes: ((t = c.data) == null ? void 0 : t.modes) || []
803
820
  });
804
821
  };
805
- let R = v;
822
+ let R = b;
806
823
  export {
807
824
  y as PrimitiveState,
808
825
  R as WidgetCtx,
809
- $ as isExhaustive
826
+ B as isExhaustive
810
827
  };
811
828
  //# sourceMappingURL=index.js.map