@opencx/widget-core 4.0.17 → 4.0.18

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,129 +1,129 @@
1
- import D from "openapi-fetch";
2
- import L from "lodash.isequal";
1
+ import L from "openapi-fetch";
2
+ import N from "lodash.isequal";
3
3
  import { v4 as O } from "uuid";
4
- const H = (g) => {
5
- console.log(g.error);
6
- }, q = (g) => {
7
- const n = D({
8
- baseUrl: g.baseUrl
4
+ const z = (h) => {
5
+ console.log(h.error);
6
+ }, B = (h) => {
7
+ const i = L({
8
+ baseUrl: h.baseUrl
9
9
  }), a = {
10
- onRequest: g.onRequest,
11
- onResponse: g.onResponse,
12
- onError: g.onError || H
10
+ onRequest: h.onRequest,
11
+ onResponse: h.onResponse,
12
+ onError: h.onError || z
13
13
  };
14
- return n.use(a), n;
14
+ return i.use(a), i;
15
15
  };
16
- class U {
17
- constructor({ config: n }) {
18
- var h, e;
19
- this.userToken = null, this.constructClientOptions = (t) => {
20
- const s = this.config.apiUrl || "https://api.open.cx", i = {
16
+ class M {
17
+ constructor({ config: i }) {
18
+ var d, s;
19
+ this.userToken = null, this.constructClientOptions = (e) => {
20
+ const t = this.config.apiUrl || "https://api.open.cx", n = {
21
21
  "X-Bot-Token": this.config.token,
22
22
  "Content-Type": "application/json",
23
23
  Accept: "application/json",
24
- Authorization: t ? `Bearer ${t}` : void 0
24
+ Authorization: e ? `Bearer ${e}` : void 0
25
25
  };
26
- return { baseUrl: s, headers: i };
26
+ return { baseUrl: t, headers: n };
27
27
  }, this.createOpenAPIClient = ({
28
- baseUrl: t,
29
- headers: s
30
- }) => q({
31
- baseUrl: t,
32
- onRequest: ({ request: i }) => {
33
- Object.entries(s).forEach(([o, r]) => {
34
- r && i.headers.set(o, r);
28
+ baseUrl: e,
29
+ headers: t
30
+ }) => B({
31
+ baseUrl: e,
32
+ onRequest: ({ request: n }) => {
33
+ Object.entries(t).forEach(([o, r]) => {
34
+ r && n.headers.set(o, r);
35
35
  });
36
36
  }
37
- }), this.setAuthToken = (t) => {
38
- this.userToken = t;
39
- const { baseUrl: s, headers: i } = this.constructClientOptions(t);
40
- this.client = this.createOpenAPIClient({ baseUrl: s, headers: i });
37
+ }), this.setAuthToken = (e) => {
38
+ this.userToken = e;
39
+ const { baseUrl: t, headers: n } = this.constructClientOptions(e);
40
+ this.client = this.createOpenAPIClient({ baseUrl: t, headers: n });
41
41
  }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
42
42
  params: { header: { "X-Bot-Token": this.config.token } }
43
- }), this.sendMessage = async (t, s) => await this.client.POST("/backend/widget/v2/chat/send", {
44
- body: t,
45
- signal: s
46
- }), this.createUnverifiedContact = async (t) => await this.client.POST(
43
+ }), this.sendMessage = async (e, t) => await this.client.POST("/backend/widget/v2/chat/send", {
44
+ body: e,
45
+ signal: t
46
+ }), this.createUnverifiedContact = async (e) => await this.client.POST(
47
47
  "/backend/widget/v2/contact/create-unverified",
48
48
  {
49
49
  params: { header: { "x-bot-token": this.config.token } },
50
- body: t
50
+ body: e
51
51
  }
52
- ), this.createSession = async (t) => await this.client.POST("/backend/widget/v2/create-session", {
53
- body: t
52
+ ), this.createSession = async (e) => await this.client.POST("/backend/widget/v2/create-session", {
53
+ body: e
54
54
  }), this.pollSessionAndHistory = async ({
55
- sessionId: t,
56
- lastMessageTimestamp: s,
57
- abortSignal: i
55
+ sessionId: e,
56
+ lastMessageTimestamp: t,
57
+ abortSignal: n
58
58
  }) => {
59
- const o = s ? { lastMessageTimestamp: s } : void 0;
59
+ const o = t ? { lastMessageTimestamp: t } : void 0;
60
60
  return await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
61
- params: { path: { sessionId: t }, query: o },
62
- signal: i
61
+ params: { path: { sessionId: e }, query: o },
62
+ signal: n
63
63
  });
64
64
  }, this.getSessions = async ({
65
- cursor: t,
66
- filters: s,
67
- abortSignal: i
65
+ cursor: e,
66
+ filters: t,
67
+ abortSignal: n
68
68
  }) => await this.client.GET("/backend/widget/v2/sessions", {
69
- params: { query: { cursor: t, filters: JSON.stringify(s) } },
70
- signal: i
69
+ params: { query: { cursor: e, filters: JSON.stringify(t) } },
70
+ signal: n
71
71
  }), this.uploadFile = async ({
72
- file: t,
73
- abortSignal: s,
74
- onProgress: i
72
+ file: e,
73
+ abortSignal: t,
74
+ onProgress: n
75
75
  }) => new Promise((o, r) => {
76
76
  var w;
77
77
  const l = new FormData();
78
- l.append("file", t);
79
- const d = new XMLHttpRequest();
80
- if (s && (s.addEventListener("abort", () => {
81
- d.abort(), r(new DOMException("Aborted", "AbortError"));
82
- }), s.aborted)) {
78
+ l.append("file", e);
79
+ const u = new XMLHttpRequest();
80
+ if (t && (t.addEventListener("abort", () => {
81
+ u.abort(), r(new DOMException("Aborted", "AbortError"));
82
+ }), t.aborted)) {
83
83
  r(new DOMException("Aborted", "AbortError"));
84
84
  return;
85
85
  }
86
- d.upload.addEventListener("progress", (f) => {
87
- if (f.lengthComputable && i) {
88
- const S = Math.round(f.loaded / f.total * 100);
89
- i(S);
86
+ u.upload.addEventListener("progress", (p) => {
87
+ if (p.lengthComputable && n) {
88
+ const C = Math.round(p.loaded / p.total * 100);
89
+ n(C);
90
90
  }
91
- }), d.addEventListener("load", () => {
92
- if (d.status >= 200 && d.status < 300)
91
+ }), u.addEventListener("load", () => {
92
+ if (u.status >= 200 && u.status < 300)
93
93
  try {
94
- const f = JSON.parse(d.responseText);
95
- o(f);
96
- } catch (f) {
97
- r(new Error(`Failed to parse response: ${f}`));
94
+ const p = JSON.parse(u.responseText);
95
+ o(p);
96
+ } catch (p) {
97
+ r(new Error(`Failed to parse response: ${p}`));
98
98
  }
99
99
  else
100
- r(new Error(`Upload failed with status: ${d.status}`));
101
- }), d.addEventListener("error", () => {
100
+ r(new Error(`Upload failed with status: ${u.status}`));
101
+ }), u.addEventListener("error", () => {
102
102
  r(new Error("Network error occurred"));
103
- }), d.addEventListener("timeout", () => {
103
+ }), u.addEventListener("timeout", () => {
104
104
  r(new Error("Upload timed out"));
105
105
  });
106
- const { baseUrl: p } = this.constructClientOptions(this.userToken), C = `${p}/backend/widget/v2/upload`;
107
- d.open("POST", C), d.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((w = this.config.user) == null ? void 0 : w.token) ? d.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), d.send(l);
108
- }), 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", {
109
- body: t,
110
- signal: s
111
- }), this.createStateCheckpoint = async (t) => await this.client.POST("/backend/widget/v2/checkpoint", {
112
- body: t
113
- }), this.submitCsat = async (t) => await this.client.POST("/backend/widget/v2/submit-csat", { body: t }), this.config = n, this.userToken = ((h = n.user) == null ? void 0 : h.token) || null;
106
+ const { baseUrl: _ } = this.constructClientOptions(this.userToken), f = `${_}/backend/widget/v2/upload`;
107
+ u.open("POST", f), u.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((w = this.config.user) == null ? void 0 : w.token) ? u.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : console.error("User token not set"), u.send(l);
108
+ }), this.vote = async (e) => await this.client.POST("/backend/widget/v2/chat/vote", { body: e }), this.resolveSession = async (e, t) => await this.client.POST("/backend/widget/v2/session/resolve", {
109
+ body: e,
110
+ signal: t
111
+ }), this.createStateCheckpoint = async (e) => await this.client.POST("/backend/widget/v2/checkpoint", {
112
+ body: e
113
+ }), this.submitCsat = async (e) => await this.client.POST("/backend/widget/v2/submit-csat", { body: e }), this.config = i, this.userToken = ((d = i.user) == null ? void 0 : d.token) || null;
114
114
  const { baseUrl: a, headers: c } = this.constructClientOptions(
115
- (e = n.user) == null ? void 0 : e.token
115
+ (s = i.user) == null ? void 0 : s.token
116
116
  );
117
117
  this.client = this.createOpenAPIClient({ baseUrl: a, headers: c });
118
118
  }
119
119
  }
120
- function $(g, n) {
121
- console.error(`Missing case for ${g} in ${n}`);
120
+ function H(h, i) {
121
+ console.error(`Missing case for ${h} in ${i}`);
122
122
  }
123
123
  class y {
124
- constructor(n) {
124
+ constructor(i) {
125
125
  this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
126
- L(this.state, a) || (this.state = a, this.notifySubscribers(a));
126
+ N(this.state, a) || (this.state = a, this.notifySubscribers(a));
127
127
  }, this.setPartial = (a) => {
128
128
  if (a == null) return;
129
129
  const c = { ...this.state, ...a };
@@ -131,146 +131,146 @@ class y {
131
131
  }, this.reset = () => {
132
132
  this.set(this.initialState);
133
133
  }, this.notifySubscribers = (a) => {
134
- Array.from(this.subscribers).forEach((h) => {
134
+ Array.from(this.subscribers).forEach((d) => {
135
135
  try {
136
- h(a);
137
- } catch (e) {
138
- console.error(e);
136
+ d(a);
137
+ } catch (s) {
138
+ console.error(s);
139
139
  }
140
140
  });
141
141
  }, this.subscribe = (a) => (this.subscribers.add(a), () => {
142
142
  this.subscribers.delete(a);
143
- }), this.state = n, this.initialState = n;
143
+ }), this.state = i, this.initialState = i;
144
144
  }
145
145
  }
146
- class F {
146
+ class R {
147
147
  constructor() {
148
148
  this.state = new y({
149
149
  isPolling: !1,
150
150
  isError: !1
151
151
  }), this.abortController = new AbortController(), this.reset = () => {
152
- var n;
153
- this.abortController.abort("Resetting poller"), (n = this.stopPolling) == null || n.call(this), this.stopPolling = null;
154
- }, this.stopPolling = null, this.startPolling = (n, a) => {
152
+ var i;
153
+ this.abortController.abort("Resetting poller"), (i = this.stopPolling) == null || i.call(this), this.stopPolling = null;
154
+ }, this.stopPolling = null, this.startPolling = (i, a) => {
155
155
  if (this.stopPolling) return;
156
- const c = [], h = async () => {
156
+ const c = [], d = async () => {
157
157
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
158
158
  try {
159
- await n(this.abortController.signal);
160
- } catch (e) {
159
+ await i(this.abortController.signal);
160
+ } catch (s) {
161
161
  if (this.abortController.signal.aborted)
162
162
  return;
163
- console.error("Failed to poll:", e), this.state.setPartial({ isError: !0 });
163
+ console.error("Failed to poll:", s), this.state.setPartial({ isError: !0 });
164
164
  } finally {
165
165
  this.state.setPartial({ isPolling: !1 });
166
166
  }
167
- this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : c.push(setTimeout(h, a));
167
+ this.abortController.signal.aborted ? console.log("Poller aborted, not scheduling anymore") : c.push(setTimeout(d, a));
168
168
  };
169
- h(), this.stopPolling = () => {
169
+ d(), this.stopPolling = () => {
170
170
  c.forEach(clearTimeout), this.state.reset();
171
171
  };
172
172
  };
173
173
  }
174
174
  }
175
- function B(g) {
175
+ function q(h) {
176
176
  try {
177
- const n = g();
178
- return n instanceof Promise ? n.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: n };
179
- } catch (n) {
180
- return { error: n };
177
+ const i = h();
178
+ return i instanceof Promise ? i.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: i };
179
+ } catch (i) {
180
+ return { error: i };
181
181
  }
182
182
  }
183
- class N {
183
+ class j {
184
184
  constructor({
185
- api: n,
185
+ api: i,
186
186
  config: a,
187
187
  sessionCtx: c,
188
- messageCtx: h,
189
- sessionPollingIntervalSeconds: e
188
+ messageCtx: d,
189
+ sessionPollingIntervalSeconds: s
190
190
  }) {
191
- this.poller = new F(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.registerPolling = () => {
192
- this.sessionCtx.sessionState.subscribe(({ session: t }) => {
193
- t != null && t.id ? this.poller.startPolling(async (s) => {
194
- this.fetchSessionAndHistory({ sessionId: t.id, abortSignal: s });
191
+ this.poller = new R(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.registerPolling = () => {
192
+ this.sessionCtx.sessionState.subscribe(({ session: e }) => {
193
+ e != null && e.id ? this.poller.startPolling(async (t) => {
194
+ this.fetchSessionAndHistory({ sessionId: e.id, abortSignal: t });
195
195
  }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
196
- }), this.sessionCtx.sessionState.subscribe(({ session: t }) => {
197
- if (t != null && t.id && !t.isOpened)
196
+ }), this.sessionCtx.sessionState.subscribe(({ session: e }) => {
197
+ if (e != null && e.id && !e.isOpened)
198
198
  try {
199
199
  this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.fetchSessionAndHistory({
200
- sessionId: t.id,
200
+ sessionId: e.id,
201
201
  abortSignal: this.fetchSessionAndFullHistoryAbortController.signal,
202
202
  fetchFullHistory: !0
203
203
  });
204
- } catch (s) {
205
- this.fetchSessionAndFullHistoryAbortController.signal.aborted || console.error("Failed to fetch session and full history:", s);
204
+ } catch (t) {
205
+ this.fetchSessionAndFullHistoryAbortController.signal.aborted || console.error("Failed to fetch session and full history:", t);
206
206
  }
207
207
  else
208
208
  this.fetchSessionAndFullHistoryAbortController.abort();
209
209
  });
210
210
  }, this.fetchSessionAndHistory = async ({
211
- sessionId: t,
212
- abortSignal: s,
213
- fetchFullHistory: i = !1
211
+ sessionId: e,
212
+ abortSignal: t,
213
+ fetchFullHistory: n = !1
214
214
  }) => {
215
- var d;
215
+ var u;
216
216
  this.messageCtx.state.get().messages.length === 0 && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
217
- const o = this.messageCtx.state.get().messages, r = o.length > 0 ? ((d = o[o.length - 1]) == null ? void 0 : d.timestamp) ?? void 0 : void 0, { data: l } = await this.api.pollSessionAndHistory({
218
- sessionId: t,
219
- abortSignal: s,
220
- lastMessageTimestamp: i ? void 0 : r
217
+ const o = this.messageCtx.state.get().messages, r = o.length > 0 ? ((u = o[o.length - 1]) == null ? void 0 : u.timestamp) ?? void 0 : void 0, { data: l } = await this.api.pollSessionAndHistory({
218
+ sessionId: e,
219
+ abortSignal: t,
220
+ lastMessageTimestamp: n ? void 0 : r
221
221
  });
222
222
  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) {
223
- const p = this.messageCtx.state.get().messages, v = l.history.map(this.mapHistoryToMessage).filter((C) => C !== null).filter(
224
- (C) => !p.some((x) => x.id === C.id)
223
+ const _ = this.messageCtx.state.get().messages, b = l.history.map(this.mapHistoryToMessage).filter((f) => f !== null).filter(
224
+ (f) => !_.some((S) => S.id === f.id)
225
225
  );
226
226
  this.messageCtx.state.setPartial({
227
- messages: [...p, ...v]
227
+ messages: [..._, ...b]
228
228
  });
229
229
  }
230
230
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
231
- }, this.mapHistoryToMessage = (t) => {
232
- var i, o;
233
- const s = {
234
- id: t.publicId,
235
- timestamp: t.sentAt || "",
236
- attachments: t.attachments || void 0
231
+ }, this.mapHistoryToMessage = (e) => {
232
+ var n, o;
233
+ const t = {
234
+ id: e.publicId,
235
+ timestamp: e.sentAt || "",
236
+ attachments: e.attachments || void 0
237
237
  };
238
- if (t.sender.kind === "user")
238
+ if (e.sender.kind === "user")
239
239
  return {
240
- ...s,
240
+ ...t,
241
241
  type: "USER",
242
- content: t.content.text || "",
243
- deliveredAt: t.sentAt || ""
242
+ content: e.content.text || "",
243
+ deliveredAt: e.sentAt || ""
244
244
  };
245
- if (t.sender.kind === "agent")
245
+ if (e.sender.kind === "agent")
246
246
  return {
247
- ...s,
247
+ ...t,
248
248
  type: "AGENT",
249
249
  component: "agent_message",
250
250
  data: {
251
- message: t.content.text || ""
251
+ message: e.content.text || ""
252
252
  },
253
253
  agent: {
254
- name: t.sender.name || "",
255
- avatar: t.sender.avatar || "",
254
+ name: e.sender.name || "",
255
+ avatar: e.sender.avatar || "",
256
256
  id: null,
257
257
  isAi: !1
258
258
  }
259
259
  };
260
- if (t.sender.kind === "ai") {
261
- const r = t.actionCalls && t.actionCalls.length > 0 ? t.actionCalls[t.actionCalls.length - 1] : void 0;
260
+ if (e.sender.kind === "ai") {
261
+ const r = e.actionCalls && e.actionCalls.length > 0 ? e.actionCalls[e.actionCalls.length - 1] : void 0;
262
262
  return {
263
- ...s,
263
+ ...t,
264
264
  type: "AI",
265
265
  component: "bot_message",
266
266
  agent: {
267
267
  id: null,
268
- name: ((i = this.config.bot) == null ? void 0 : i.name) || "",
268
+ name: ((n = this.config.bot) == null ? void 0 : n.name) || "",
269
269
  isAi: !0,
270
270
  avatar: ((o = this.config.bot) == null ? void 0 : o.avatar) || ""
271
271
  },
272
272
  data: {
273
- message: t.content.text || "",
273
+ message: e.content.text || "",
274
274
  action: r ? {
275
275
  name: r.actionName,
276
276
  data: this.extractActionResult(r)
@@ -278,119 +278,119 @@ class N {
278
278
  }
279
279
  };
280
280
  }
281
- if (t.sender.kind === "system") {
282
- const r = this.constructSystemMessage(t);
281
+ if (e.sender.kind === "system") {
282
+ const r = this.constructSystemMessage(e);
283
283
  return r === null ? null : { ...r };
284
284
  }
285
285
  return null;
286
- }, this.constructSystemMessage = (t) => {
287
- if (!t || !t.systemMessagePayload) return null;
288
- switch (t.systemMessagePayload.type) {
286
+ }, this.constructSystemMessage = (e) => {
287
+ if (!e || !e.systemMessagePayload) return null;
288
+ switch (e.systemMessagePayload.type) {
289
289
  case "state_checkpoint":
290
290
  return {
291
- id: t.publicId,
291
+ id: e.publicId,
292
292
  type: "SYSTEM",
293
293
  subtype: "state_checkpoint",
294
- data: { payload: t.systemMessagePayload.payload },
295
- timestamp: t.sentAt || "",
294
+ data: { payload: e.systemMessagePayload.payload },
295
+ timestamp: e.sentAt || "",
296
296
  attachments: void 0
297
297
  };
298
298
  case "csat_requested":
299
299
  return {
300
- id: t.publicId,
300
+ id: e.publicId,
301
301
  type: "SYSTEM",
302
302
  subtype: "csat_requested",
303
303
  data: { payload: void 0 },
304
- timestamp: t.sentAt || "",
304
+ timestamp: e.sentAt || "",
305
305
  attachments: void 0
306
306
  };
307
307
  case "csat_submitted":
308
308
  return {
309
- id: t.publicId,
309
+ id: e.publicId,
310
310
  type: "SYSTEM",
311
311
  subtype: "csat_submitted",
312
312
  data: {
313
313
  payload: {
314
- score: t.systemMessagePayload.payload.score ?? void 0,
315
- feedback: t.systemMessagePayload.payload.feedback ?? void 0
314
+ score: e.systemMessagePayload.payload.score ?? void 0,
315
+ feedback: e.systemMessagePayload.payload.feedback ?? void 0
316
316
  }
317
317
  },
318
- timestamp: t.sentAt || "",
318
+ timestamp: e.sentAt || "",
319
319
  attachments: void 0
320
320
  };
321
321
  case "none":
322
322
  return null;
323
323
  default:
324
- return $(
325
- t.systemMessagePayload,
324
+ return H(
325
+ e.systemMessagePayload,
326
326
  this.constructSystemMessage.name
327
327
  ), null;
328
328
  }
329
- }, this.extractActionResult = (t) => {
330
- const s = t.result;
331
- if (s === null || typeof s != "object") return s;
332
- if ("responseBodyText" in s && typeof s.responseBodyText == "string") {
333
- const i = s.responseBodyText, o = B(() => JSON.parse(i)).data;
329
+ }, this.extractActionResult = (e) => {
330
+ const t = e.result;
331
+ if (t === null || typeof t != "object") return t;
332
+ if ("responseBodyText" in t && typeof t.responseBodyText == "string") {
333
+ const n = t.responseBodyText, o = q(() => JSON.parse(n)).data;
334
334
  if (o) return o;
335
335
  }
336
- return t.result;
337
- }, this.api = n, this.config = a, this.sessionCtx = c, this.messageCtx = h, this.sessionPollingIntervalSeconds = e, this.registerPolling();
336
+ return e.result;
337
+ }, this.api = i, this.config = a, this.sessionCtx = c, this.messageCtx = d, this.sessionPollingIntervalSeconds = s, this.registerPolling();
338
338
  }
339
339
  }
340
340
  class Y {
341
341
  constructor({
342
- config: n,
342
+ config: i,
343
343
  api: a,
344
344
  storageCtx: c
345
345
  }) {
346
- var h;
346
+ var d;
347
347
  this.shouldCollectData = () => {
348
- var e;
349
- return !!(!((e = this.state.get().contact) != null && e.token) && this.config.collectUserData);
348
+ var s;
349
+ return !!(!((s = this.state.get().contact) != null && s.token) && this.config.collectUserData);
350
350
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
351
- var e, t, s, i, o, r, l, d, p, v, C, x, w, f;
352
- if (!((e = this.config.user) != null && e.token)) {
353
- if (this.config.collectUserData && !((s = (t = this.config.user) == null ? void 0 : t.data) != null && s.email)) {
354
- if ((i = this.config.extraDataCollectionFields) != null && i.length)
351
+ var s, e, t, n, o, r, l, u, _, b, f, S, w, p;
352
+ if (!((s = this.config.user) != null && s.token)) {
353
+ if (this.config.collectUserData && !((t = (e = this.config.user) == null ? void 0 : e.data) != null && t.email)) {
354
+ if ((n = this.config.extraDataCollectionFields) != null && n.length)
355
355
  return;
356
- const S = await ((o = this.storageCtx) == null ? void 0 : o.getContactToken());
357
- S && await this.setUnverifiedContact(S);
356
+ const C = await ((o = this.storageCtx) == null ? void 0 : o.getContactToken());
357
+ C && await this.setUnverifiedContact(C);
358
358
  return;
359
359
  }
360
360
  if (!((l = (r = this.config.user) == null ? void 0 : r.data) != null && l.email)) {
361
- const S = await ((d = this.storageCtx) == null ? void 0 : d.getContactToken());
362
- if (S) {
363
- await this.setUnverifiedContact(S);
361
+ const C = await ((u = this.storageCtx) == null ? void 0 : u.getContactToken());
362
+ if (C) {
363
+ await this.setUnverifiedContact(C);
364
364
  return;
365
365
  }
366
366
  }
367
367
  await this.createUnverifiedContact({
368
- email: (v = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : v.email,
369
- non_verified_name: ((x = (C = this.config.user) == null ? void 0 : C.data) == null ? void 0 : x.name) || "Anonymous",
370
- non_verified_custom_data: (f = (w = this.config.user) == null ? void 0 : w.data) == null ? void 0 : f.customData
368
+ email: (b = (_ = this.config.user) == null ? void 0 : _.data) == null ? void 0 : b.email,
369
+ non_verified_name: ((S = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : S.name) || "Anonymous",
370
+ non_verified_custom_data: (p = (w = this.config.user) == null ? void 0 : w.data) == null ? void 0 : p.customData
371
371
  });
372
372
  }
373
- }, this.createUnverifiedContact = async (e, t) => {
374
- this.state.setPartial({ extraCollectedData: t });
373
+ }, this.createUnverifiedContact = async (s, e) => {
374
+ this.state.setPartial({ extraCollectedData: e });
375
375
  try {
376
376
  this.state.setPartial({
377
377
  isCreatingUnverifiedContact: !0,
378
378
  isErrorCreatingUnverifiedContact: !1
379
379
  });
380
- const { data: s } = await this.api.createUnverifiedContact(e);
381
- s != null && s.token ? await this.setUnverifiedContact(s.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
380
+ const { data: t } = await this.api.createUnverifiedContact(s);
381
+ t != null && t.token ? await this.setUnverifiedContact(t.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
382
382
  } finally {
383
383
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
384
384
  }
385
- }, this.setUnverifiedContact = async (e) => {
386
- var i, o, r, l;
387
- const t = await ((i = this.storageCtx) == null ? void 0 : i.getExternalContactId()), s = ((o = this.config.user) == null ? void 0 : o.externalId) || t || O();
388
- 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 } });
389
- }, this.config = n, this.storageCtx = c, this.api = a, this.state = new y({
390
- contact: (h = n.user) != null && h.token ? {
391
- token: n.user.token,
385
+ }, this.setUnverifiedContact = async (s) => {
386
+ var n, o, r, l;
387
+ const e = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), t = ((o = this.config.user) == null ? void 0 : o.externalId) || e || O();
388
+ this.api.setAuthToken(s), await ((r = this.storageCtx) == null ? void 0 : r.setContactToken(s)), await ((l = this.storageCtx) == null ? void 0 : l.setExternalContactId(t)), this.state.setPartial({ contact: { token: s, externalId: t } });
389
+ }, this.config = i, this.storageCtx = c, this.api = a, this.state = new y({
390
+ contact: (d = i.user) != null && d.token ? {
391
+ token: i.user.token,
392
392
  // Set optional externalId from config... not local storage
393
- externalId: n.user.externalId
393
+ externalId: i.user.externalId
394
394
  } : null,
395
395
  extraCollectedData: void 0,
396
396
  isCreatingUnverifiedContact: !1,
@@ -398,56 +398,56 @@ class Y {
398
398
  }), this.autoCreateUnverifiedUserIfNotExists();
399
399
  }
400
400
  }
401
- function I() {
401
+ function x() {
402
402
  return O();
403
403
  }
404
- class K {
404
+ class $ {
405
405
  constructor({
406
- config: n,
406
+ config: i,
407
407
  api: a,
408
408
  sessionCtx: c,
409
- messageCtx: h
409
+ messageCtx: d
410
410
  }) {
411
- this.submitCsat = async (e) => {
411
+ this.submitCsat = async (s) => {
412
412
  var r;
413
- const t = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
414
- if (!t)
413
+ const e = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
414
+ if (!e)
415
415
  return { data: null, error: "No session id found" };
416
- const s = I();
416
+ const t = x();
417
417
  this.messageCtx.state.setPartial({
418
418
  messages: [
419
419
  ...this.messageCtx.state.get().messages,
420
420
  {
421
- id: s,
421
+ id: t,
422
422
  type: "SYSTEM",
423
423
  subtype: "csat_submitted",
424
424
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
425
425
  data: {
426
426
  payload: {
427
- score: e.score,
428
- feedback: e.feedback
427
+ score: s.score,
428
+ feedback: s.feedback
429
429
  }
430
430
  }
431
431
  }
432
432
  ]
433
433
  });
434
- const { data: i, error: o } = await this.api.submitCsat({
435
- ...e,
436
- system_message_uuid: s,
437
- session_id: t
434
+ const { data: n, error: o } = await this.api.submitCsat({
435
+ ...s,
436
+ system_message_uuid: t,
437
+ session_id: e
438
438
  });
439
- return { data: i, error: o };
440
- }, this.config = n, this.api = a, this.sessionCtx = c, this.messageCtx = h;
439
+ return { data: n, error: o };
440
+ }, this.config = i, this.api = a, this.sessionCtx = c, this.messageCtx = d;
441
441
  }
442
442
  }
443
- class X {
443
+ class K {
444
444
  constructor({
445
- config: n,
445
+ config: i,
446
446
  api: a,
447
447
  contactCtx: c,
448
- sessionsPollingIntervalSeconds: h
448
+ sessionsPollingIntervalSeconds: d
449
449
  }) {
450
- this.sessionsRefresher = new F(), this.sessionState = new y({
450
+ this.sessionsRefresher = new R(), this.sessionState = new y({
451
451
  session: null,
452
452
  isCreatingSession: !1,
453
453
  isResolvingSession: !1
@@ -463,10 +463,10 @@ class X {
463
463
  }), this.reset = async () => {
464
464
  this.sessionState.reset();
465
465
  }, this.registerSessionsRefresherWrapper = () => {
466
- var e;
466
+ var s;
467
467
  // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
468
- (e = this.contactCtx.state.get().contact) != null && e.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: t }) => {
469
- t != null && t.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
468
+ (s = this.contactCtx.state.get().contact) != null && s.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: e }) => {
469
+ e != null && e.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
470
470
  });
471
471
  }, this.registerSessionsRefresher = () => {
472
472
  this.sessionsRefresher.startPolling(async () => {
@@ -475,73 +475,73 @@ class X {
475
475
  }, this.createSession = async () => {
476
476
  var o;
477
477
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
478
- const e = (o = this.contactCtx.state.get().contact) == null ? void 0 : o.externalId, t = {
478
+ const s = (o = this.contactCtx.state.get().contact) == null ? void 0 : o.externalId, e = {
479
479
  ...this.config.sessionCustomData,
480
- ...e ? { external_id: e } : {}
481
- }, { data: s, error: i } = await this.api.createSession({
482
- customData: Object.keys(t).length > 0 ? t : void 0
480
+ ...s ? { external_id: s } : {}
481
+ }, { data: t, error: n } = await this.api.createSession({
482
+ customData: Object.keys(e).length > 0 ? e : void 0
483
483
  });
484
- return s ? (this.sessionState.setPartial({ session: s, isCreatingSession: !1 }), s) : (this.sessionState.setPartial({ isCreatingSession: !1 }), console.error("Failed to create session:", i), null);
484
+ return t ? (this.sessionState.setPartial({ session: t, isCreatingSession: !1 }), t) : (this.sessionState.setPartial({ isCreatingSession: !1 }), console.error("Failed to create session:", n), null);
485
485
  }, this.loadMoreSessions = async () => {
486
486
  if (this.sessionsState.get().isLastPage) return;
487
- const { data: e } = await this.getSessions({
487
+ const { data: s } = await this.getSessions({
488
488
  cursor: this.sessionsState.get().cursor
489
489
  });
490
- if (e) {
491
- const s = [...this.sessionsState.get().data, ...e.items].filter(
492
- (i, o, r) => o === r.findIndex((l) => i.id === l.id)
490
+ if (s) {
491
+ const t = [...this.sessionsState.get().data, ...s.items].filter(
492
+ (n, o, r) => o === r.findIndex((l) => n.id === l.id)
493
493
  );
494
494
  this.sessionsState.setPartial({
495
- data: s,
496
- cursor: e.next || void 0,
497
- isLastPage: e.next === null
495
+ data: t,
496
+ cursor: s.next || void 0,
497
+ isLastPage: s.next === null
498
498
  });
499
499
  }
500
- }, this.getSessions = async ({ cursor: e }) => {
501
- var s, i;
502
- if (!((s = this.contactCtx.state.get().contact) != null && s.token)) return { data: null };
503
- const t = (i = this.contactCtx.state.get().contact) == null ? void 0 : i.externalId;
500
+ }, this.getSessions = async ({ cursor: s }) => {
501
+ var t, n;
502
+ if (!((t = this.contactCtx.state.get().contact) != null && t.token)) return { data: null };
503
+ const e = (n = this.contactCtx.state.get().contact) == null ? void 0 : n.externalId;
504
504
  return await this.api.getSessions({
505
- cursor: e,
506
- filters: t ? {
507
- external_id: t
505
+ cursor: s,
506
+ filters: e ? {
507
+ external_id: e
508
508
  } : {}
509
509
  });
510
- }, this.setSessions = (e) => {
511
- const t = [...e, ...this.sessionsState.get().data].filter(
512
- (s, i, o) => i === o.findIndex((r) => s.id === r.id)
510
+ }, this.setSessions = (s) => {
511
+ const e = [...s, ...this.sessionsState.get().data].filter(
512
+ (t, n, o) => n === o.findIndex((r) => t.id === r.id)
513
513
  );
514
- this.sessionsState.setPartial({ data: t });
514
+ this.sessionsState.setPartial({ data: e });
515
515
  }, this.refreshSessions = async () => {
516
- const { data: e } = await this.getSessions({ cursor: void 0 });
517
- e && this.setSessions(e.items);
516
+ const { data: s } = await this.getSessions({ cursor: void 0 });
517
+ s && this.setSessions(s.items);
518
518
  }, this.resolveSession = async () => {
519
- const e = this.sessionState.get().session;
520
- if (!e || !e.isOpened)
519
+ const s = this.sessionState.get().session;
520
+ if (!s || !s.isOpened)
521
521
  return { success: !1, error: "Session is not opened" };
522
522
  this.sessionState.setPartial({ isResolvingSession: !0 });
523
- const { data: t, error: s } = await this.api.resolveSession({
524
- session_id: e.id
523
+ const { data: e, error: t } = await this.api.resolveSession({
524
+ session_id: s.id
525
525
  });
526
- return t ? (this.sessionState.setPartial({ session: t, isResolvingSession: !1 }), { success: !0, data: t }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: s });
527
- }, this.createStateCheckpoint = async (e) => {
526
+ return e ? (this.sessionState.setPartial({ session: e, isResolvingSession: !1 }), { success: !0, data: e }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: t });
527
+ }, this.createStateCheckpoint = async (s) => {
528
528
  var o;
529
- const t = (o = this.sessionState.get().session) == null ? void 0 : o.id;
530
- if (!t) return;
531
- const { data: s, error: i } = await this.api.createStateCheckpoint({
532
- session_id: t,
533
- payload: e
529
+ const e = (o = this.sessionState.get().session) == null ? void 0 : o.id;
530
+ if (!e) return;
531
+ const { data: t, error: n } = await this.api.createStateCheckpoint({
532
+ session_id: e,
533
+ payload: s
534
534
  });
535
- return s ? { data: s } : { success: !1, error: i };
536
- }, this.config = n, this.api = a, this.contactCtx = c, this.sessionsPollingIntervalSeconds = h, this.registerSessionsRefresherWrapper();
535
+ return t != null && t.success ? { success: !0 } : { success: !1 };
536
+ }, this.config = i, this.api = a, this.contactCtx = c, this.sessionsPollingIntervalSeconds = d, this.registerSessionsRefresherWrapper();
537
537
  }
538
538
  }
539
- class z {
539
+ class G {
540
540
  constructor({
541
- config: n,
541
+ config: i,
542
542
  api: a,
543
543
  sessionCtx: c,
544
- contactCtx: h
544
+ contactCtx: d
545
545
  }) {
546
546
  this.state = new y({
547
547
  messages: [],
@@ -550,41 +550,41 @@ class z {
550
550
  isInitialFetchLoading: !1
551
551
  }), this.sendMessageAbortController = new AbortController(), this.reset = () => {
552
552
  this.sendMessageAbortController.abort("Resetting chat"), this.state.reset();
553
- }, this.sendMessage = async (e) => {
554
- var t, s, i, o, r, l, d, p, v, C;
553
+ }, this.sendMessage = async (s) => {
554
+ var e, t, n, o, r, l, u, _, b, f;
555
555
  try {
556
- if (!e.content.trim() && (!e.attachments || e.attachments.length === 0)) {
556
+ if (!s.content.trim() && (!s.attachments || s.attachments.length === 0)) {
557
557
  console.warn(
558
558
  "Cannot send an empty message of no content or attachments"
559
559
  );
560
560
  return;
561
561
  }
562
- 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;
563
- if (w && x || // If last message is from user, then bot response did not arrive yet
564
- w && (S == null ? void 0 : S.type) === "USER") {
562
+ const S = this.state.get().isSendingMessage, w = ((e = this.sessionCtx.sessionState.get().session) == null ? void 0 : e.assignee.kind) === "ai", p = this.state.get().messages, C = p.length > 0 ? p[p.length - 1] : void 0;
563
+ if (w && S || // If last message is from user, then bot response did not arrive yet
564
+ w && (C == null ? void 0 : C.type) === "USER") {
565
565
  console.warn("Cannot send messages while awaiting AI response");
566
566
  return;
567
567
  }
568
568
  this.sendMessageAbortController = new AbortController(), this.state.setPartial({ lastAIResMightSolveUserIssue: !1 }), this.state.setPartial({ isSendingMessage: !0 });
569
- 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(
570
- (u) => ({
571
- id: I(),
569
+ const P = this.state.get().messages, A = !((t = this.sessionCtx.sessionState.get().session) != null && t.id) && P.length === 0 && ((n = this.config.advancedInitialMessages) == null ? void 0 : n.some((g) => g.persistent)), E = A ? (this.config.advancedInitialMessages || []).filter((g) => g.persistent).map(
570
+ (g) => ({
571
+ id: x(),
572
572
  component: "bot_message",
573
573
  type: "AI",
574
574
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
575
575
  data: {
576
- message: u.message
576
+ message: g.message
577
577
  }
578
578
  })
579
- ) : [], k = this.toUserMessage(
580
- e.content.trim(),
581
- e.attachments || void 0
579
+ ) : [], I = this.toUserMessage(
580
+ s.content.trim(),
581
+ s.attachments || void 0
582
582
  );
583
583
  if (this.state.setPartial({
584
584
  messages: [
585
585
  ...E,
586
- ...A,
587
- k
586
+ ...P,
587
+ I
588
588
  ]
589
589
  }), !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
590
590
  if (!await this.sessionCtx.createSession()) {
@@ -597,80 +597,80 @@ class z {
597
597
  if (!T) return;
598
598
  const { data: m } = await this.api.sendMessage(
599
599
  {
600
- uuid: k.id,
600
+ uuid: I.id,
601
601
  bot_token: this.config.token,
602
602
  headers: this.config.headers,
603
603
  query_params: this.config.queryParams,
604
604
  body_properties: this.config.bodyProperties,
605
605
  session_id: T,
606
- content: k.content,
607
- attachments: e.attachments,
606
+ content: I.content,
607
+ attachments: s.attachments,
608
608
  clientContext: this.config.context,
609
609
  custom_data: {
610
610
  ...this.config.messageCustomData || {},
611
- ...e.customData || {}
611
+ ...s.customData || {}
612
612
  },
613
613
  language: this.config.language,
614
- exit_mode_prompt: e.exitModePrompt,
615
- initial_messages: M ? E.map((u) => ({
616
- uuid: u.id,
617
- content: u.data.message
614
+ exit_mode_prompt: s.exitModePrompt,
615
+ initial_messages: A ? E.map((g) => ({
616
+ uuid: g.id,
617
+ content: g.data.message
618
618
  })) : void 0
619
619
  },
620
620
  this.sendMessageAbortController.signal
621
621
  );
622
622
  if (m != null && m.success) {
623
- const u = this.toBotMessage(m);
624
- if (u) {
625
- const P = this.state.get().messages;
626
- if (!!P.some(
627
- (_) => _.id === u.id
623
+ const g = this.toBotMessage(m);
624
+ if (g) {
625
+ const k = this.state.get().messages;
626
+ if (!!k.some(
627
+ (D) => D.id === g.id
628
628
  )) {
629
629
  this.state.setPartial({
630
- lastAIResMightSolveUserIssue: ((l = m.autopilotResponse) == null ? void 0 : l.mightSolveUserIssue) || ((d = m.uiResponse) == null ? void 0 : d.mightSolveUserIssue)
630
+ lastAIResMightSolveUserIssue: ((l = m.autopilotResponse) == null ? void 0 : l.mightSolveUserIssue) || ((u = m.uiResponse) == null ? void 0 : u.mightSolveUserIssue)
631
631
  });
632
632
  return;
633
633
  }
634
634
  this.state.setPartial({
635
- messages: [...P, u],
636
- lastAIResMightSolveUserIssue: ((p = m.autopilotResponse) == null ? void 0 : p.mightSolveUserIssue) || ((v = m.uiResponse) == null ? void 0 : v.mightSolveUserIssue)
635
+ messages: [...k, g],
636
+ lastAIResMightSolveUserIssue: ((_ = m.autopilotResponse) == null ? void 0 : _.mightSolveUserIssue) || ((b = m.uiResponse) == null ? void 0 : b.mightSolveUserIssue)
637
637
  });
638
638
  }
639
639
  m.session && this.sessionCtx.sessionState.setPartial({ session: m.session });
640
640
  } else {
641
- const u = this.toBotErrorMessage(
642
- ((C = m == null ? void 0 : m.error) == null ? void 0 : C.message) || "Unknown error occurred"
643
- ), P = this.state.get().messages;
641
+ const g = this.toBotErrorMessage(
642
+ ((f = m == null ? void 0 : m.error) == null ? void 0 : f.message) || "Unknown error occurred"
643
+ ), k = this.state.get().messages;
644
644
  this.state.setPartial({
645
- messages: [...P, u]
645
+ messages: [...k, g]
646
646
  });
647
647
  }
648
- } catch (x) {
649
- this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", x);
648
+ } catch (S) {
649
+ this.sendMessageAbortController.signal.aborted || console.error("Failed to send message:", S);
650
650
  } finally {
651
651
  this.state.setPartial({ isSendingMessage: !1 });
652
652
  }
653
- }, this.toUserMessage = (e, t) => {
654
- const s = (() => {
655
- const i = this.contactCtx.state.get().extraCollectedData;
656
- 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(`
653
+ }, this.toUserMessage = (s, e) => {
654
+ const t = (() => {
655
+ const n = this.contactCtx.state.get().extraCollectedData;
656
+ return this.state.get().messages.length === 0 && n && Object.keys(n).length > 0 ? `${Object.entries(n).filter(([r, l]) => !!l).map(([r, l]) => `${r}: ${l}`).join(`
657
657
  `)}
658
658
 
659
- ${e}` : e;
659
+ ${s}` : s;
660
660
  })();
661
661
  return {
662
- id: I(),
662
+ id: x(),
663
663
  type: "USER",
664
- content: s,
664
+ content: t,
665
665
  deliveredAt: (/* @__PURE__ */ new Date()).toISOString(),
666
- attachments: t,
666
+ attachments: e,
667
667
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
668
668
  };
669
- }, this.toBotMessage = (e) => {
670
- var t;
671
- return e.success && e.autopilotResponse ? {
669
+ }, this.toBotMessage = (s) => {
670
+ var e;
671
+ return s.success && s.autopilotResponse ? {
672
672
  type: "AI",
673
- id: e.autopilotResponse.id || I(),
673
+ id: s.autopilotResponse.id || x(),
674
674
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
675
675
  component: "bot_message",
676
676
  agent: this.config.bot ? {
@@ -680,69 +680,69 @@ ${e}` : e;
680
680
  id: null
681
681
  } : void 0,
682
682
  data: {
683
- message: e.autopilotResponse.value.content,
684
- action: (t = e.uiResponse) != null && t.value.name ? {
685
- name: e.uiResponse.value.name,
686
- data: e.uiResponse.value.request_response
683
+ message: s.autopilotResponse.value.content,
684
+ action: (e = s.uiResponse) != null && e.value.name ? {
685
+ name: s.uiResponse.value.name,
686
+ data: s.uiResponse.value.request_response
687
687
  } : void 0
688
688
  }
689
689
  } : null;
690
- }, this.toBotErrorMessage = (e) => ({
690
+ }, this.toBotErrorMessage = (s) => ({
691
691
  type: "AI",
692
- id: I(),
692
+ id: x(),
693
693
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
694
694
  component: "TEXT",
695
695
  data: {
696
- message: e,
696
+ message: s,
697
697
  variant: "error",
698
698
  action: void 0
699
699
  }
700
- }), this.config = n, this.api = a, this.sessionCtx = c, this.contactCtx = h;
700
+ }), this.config = i, this.api = a, this.sessionCtx = c, this.contactCtx = d;
701
701
  }
702
702
  }
703
- class G {
703
+ class W {
704
704
  constructor({
705
- config: n,
705
+ config: i,
706
706
  contactCtx: a,
707
707
  sessionCtx: c,
708
- resetChat: h
708
+ resetChat: d
709
709
  }) {
710
- var e;
710
+ var s;
711
711
  this.registerRoutingListener = () => {
712
- this.contactCtx.state.subscribe(({ contact: t }) => {
713
- var s;
714
- t != null && t.token && this.state.get().screen === "welcome" && this.state.setPartial({
715
- screen: (s = this.config.router) != null && s.chatScreenOnly ? "chat" : "sessions"
712
+ this.contactCtx.state.subscribe(({ contact: e }) => {
713
+ var t;
714
+ e != null && e.token && this.state.get().screen === "welcome" && this.state.setPartial({
715
+ screen: (t = this.config.router) != null && t.chatScreenOnly ? "chat" : "sessions"
716
716
  });
717
717
  }), this.sessionCtx.sessionsState.subscribe(
718
- ({ isInitialFetchLoading: t, data: s }) => {
719
- var i, o, r, l;
720
- if ((i = this.config.router) != null && i.chatScreenOnly && // Do not route to a chat if we are currently inside one already
718
+ ({ isInitialFetchLoading: e, data: t }) => {
719
+ var n, o, r, l;
720
+ if ((n = this.config.router) != null && n.chatScreenOnly && // Do not route to a chat if we are currently inside one already
721
721
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
722
722
  !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
723
- const d = (r = s.find((p) => p.isOpened)) == null ? void 0 : r.id;
724
- return d ? this.toChatScreen(d) : void 0;
723
+ const u = (r = t.find((_) => _.isOpened)) == null ? void 0 : r.id;
724
+ return u ? this.toChatScreen(u) : void 0;
725
725
  }
726
- s.length || ((l = this.config.router) == null ? void 0 : l.goToChatIfNoSessions) !== !1 && !t && this.state.get().screen !== "chat" && this.toChatScreen();
726
+ t.length || ((l = this.config.router) == null ? void 0 : l.goToChatIfNoSessions) !== !1 && !e && this.state.get().screen !== "chat" && this.toChatScreen();
727
727
  }
728
728
  );
729
729
  }, this.toSessionsScreen = () => {
730
730
  this.resetChat(), this.state.setPartial({ screen: "sessions" });
731
- }, this.toChatScreen = (t) => {
732
- if (this.resetChat(), t) {
733
- const s = this.sessionCtx.sessionsState.get().data.find((i) => i.id === t);
734
- if (!s) return;
735
- this.sessionCtx.sessionState.setPartial({ session: s });
731
+ }, this.toChatScreen = (e) => {
732
+ if (this.resetChat(), e) {
733
+ const t = this.sessionCtx.sessionsState.get().data.find((n) => n.id === e);
734
+ if (!t) return;
735
+ this.sessionCtx.sessionState.setPartial({ session: t });
736
736
  }
737
737
  this.state.setPartial({ screen: "chat" });
738
- }, this.config = n, this.contactCtx = a, this.sessionCtx = c, this.resetChat = h, this.state = new y({
739
- screen: this.contactCtx.shouldCollectData() ? "welcome" : (e = this.config.router) != null && e.chatScreenOnly ? "chat" : "sessions"
738
+ }, this.config = i, this.contactCtx = a, this.sessionCtx = c, this.resetChat = d, this.state = new y({
739
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : (s = this.config.router) != null && s.chatScreenOnly ? "chat" : "sessions"
740
740
  }), this.registerRoutingListener();
741
741
  }
742
742
  }
743
- class j {
743
+ class V {
744
744
  constructor({
745
- storage: n,
745
+ storage: i,
746
746
  config: a
747
747
  }) {
748
748
  this.KEYS = {
@@ -752,48 +752,48 @@ class j {
752
752
  await this.storage.set(this.KEYS.contactToken(this.config.token), c);
753
753
  }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken(this.config.token)), this.setExternalContactId = async (c) => {
754
754
  await this.storage.set(this.KEYS.externalContactId(this.config.token), c);
755
- }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.storage = n, this.config = a;
755
+ }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.storage = i, this.config = a;
756
756
  }
757
757
  }
758
- const b = class b {
758
+ const v = class v {
759
759
  constructor({
760
- config: n,
760
+ config: i,
761
761
  storage: a,
762
762
  modes: c,
763
- org: h
763
+ org: d
764
764
  }) {
765
765
  if (this.modes = [], this.resetChat = () => {
766
766
  this.sessionCtx.reset(), this.messageCtx.reset();
767
- }, !b.pollingIntervalsSeconds)
767
+ }, !v.pollingIntervalsSeconds)
768
768
  throw Error(
769
769
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
770
770
  );
771
- this.config = n, this.org = h, this.api = new U({ config: n }), this.storageCtx = a ? new j({ storage: a, config: n }) : void 0, this.modes = c, this.contactCtx = new Y({
771
+ this.config = i, this.org = d, this.api = new M({ config: i }), this.storageCtx = a ? new V({ storage: a, config: i }) : void 0, this.modes = c, this.contactCtx = new Y({
772
772
  api: this.api,
773
773
  config: this.config,
774
774
  storageCtx: this.storageCtx
775
- }), this.sessionCtx = new X({
775
+ }), this.sessionCtx = new K({
776
776
  config: this.config,
777
777
  api: this.api,
778
778
  contactCtx: this.contactCtx,
779
- sessionsPollingIntervalSeconds: b.pollingIntervalsSeconds.sessions
780
- }), this.messageCtx = new z({
779
+ sessionsPollingIntervalSeconds: v.pollingIntervalsSeconds.sessions
780
+ }), this.messageCtx = new G({
781
781
  config: this.config,
782
782
  api: this.api,
783
783
  sessionCtx: this.sessionCtx,
784
784
  contactCtx: this.contactCtx
785
- }), this.csatCtx = new K({
785
+ }), this.csatCtx = new $({
786
786
  config: this.config,
787
787
  api: this.api,
788
788
  sessionCtx: this.sessionCtx,
789
789
  messageCtx: this.messageCtx
790
- }), this.activeSessionPollingCtx = new N({
790
+ }), this.activeSessionPollingCtx = new j({
791
791
  api: this.api,
792
792
  config: this.config,
793
793
  sessionCtx: this.sessionCtx,
794
794
  messageCtx: this.messageCtx,
795
- sessionPollingIntervalSeconds: b.pollingIntervalsSeconds.session
796
- }), this.routerCtx = new G({
795
+ sessionPollingIntervalSeconds: v.pollingIntervalsSeconds.session
796
+ }), this.routerCtx = new W({
797
797
  config: this.config,
798
798
  contactCtx: this.contactCtx,
799
799
  sessionCtx: this.sessionCtx,
@@ -801,33 +801,180 @@ const b = class b {
801
801
  });
802
802
  }
803
803
  };
804
- b.pollingIntervalsSeconds = null, b.initialize = async ({
805
- config: n,
804
+ v.pollingIntervalsSeconds = null, v.initialize = async ({
805
+ config: i,
806
806
  storage: a
807
807
  }) => {
808
- var h, e, t;
809
- const c = await new U({
810
- config: n
808
+ var d, s, e;
809
+ const c = await new M({
810
+ config: i
811
811
  }).getExternalWidgetConfig();
812
812
  if (!c.data)
813
813
  throw new Error("Failed to fetch widget config");
814
- return b.pollingIntervalsSeconds = {
815
- session: ((h = c.data) == null ? void 0 : h.sessionPollingIntervalSeconds) || 10,
816
- sessions: ((e = c.data) == null ? void 0 : e.sessionsPollingIntervalSeconds) || 60
817
- }, new b({
818
- config: n,
814
+ return v.pollingIntervalsSeconds = {
815
+ session: ((d = c.data) == null ? void 0 : d.sessionPollingIntervalSeconds) || 10,
816
+ sessions: ((s = c.data) == null ? void 0 : s.sessionsPollingIntervalSeconds) || 60
817
+ }, new v({
818
+ config: i,
819
819
  storage: a,
820
- modes: ((t = c.data) == null ? void 0 : t.modes) || [],
820
+ modes: ((e = c.data) == null ? void 0 : e.modes) || [],
821
821
  org: {
822
822
  id: c.data.org.id,
823
823
  name: c.data.org.name
824
824
  }
825
825
  });
826
826
  };
827
- let R = b;
827
+ let U = v;
828
+ const X = {
829
+ write_a_message_placeholder: "اكتب رسالة...",
830
+ your_issue_has_been_resolved: "تم حل مشكلتك!",
831
+ new_conversation: "محادثة جديدة",
832
+ welcome_screen_title: "مرحبًا بك في دردشة الدعم الخاصة بنا",
833
+ welcome_screen_description: "نحن هنا للمساعدة! ابدأ محادثة وسنرد عليك في أقرب وقت ممكن.",
834
+ your_name_placeholder: "اسمك",
835
+ your_email_placeholder: "عنوان بريدك الإلكتروني",
836
+ start_chat_button: "تحدث إلى الدعم",
837
+ start_chat_button_loading: "جاري الاتصال...",
838
+ i_need_more_help: "أحتاج المزيد من المساعدة",
839
+ this_was_helpful: "كان هذا مفيدًا",
840
+ optional: "اختياري",
841
+ no_conversations_yet: "لا يوجد محادثات",
842
+ back_to_conversations: "العودة إلى المحادثات",
843
+ closed_conversations: "المحادثات المغلقة"
844
+ }, J = {
845
+ write_a_message_placeholder: "Nachricht schreiben...",
846
+ your_issue_has_been_resolved: "Ihr Problem wurde gelöst!",
847
+ new_conversation: "Neue Konversation",
848
+ welcome_screen_title: "Willkommen in unserem Support-Chat",
849
+ welcome_screen_description: "Wir sind hier, um zu helfen! Beginnen Sie ein Gesprách und wir werden so schnell wie mogelijk antworten.",
850
+ your_name_placeholder: "Ihr Name",
851
+ your_email_placeholder: "Ihre E-Mail-Adresse",
852
+ start_chat_button: "Mit dem Support sprechen",
853
+ start_chat_button_loading: "Verbindung wird hergestellt...",
854
+ i_need_more_help: "Ich brauche weitere Hilfe",
855
+ this_was_helpful: "Dies war hilfreich",
856
+ optional: "Optional",
857
+ no_conversations_yet: "noch keine Gespräche",
858
+ back_to_conversations: "Zurück zur Konversationen",
859
+ closed_conversations: "Geschlossene Konversationen"
860
+ }, Z = {
861
+ write_a_message_placeholder: "Write a message...",
862
+ your_issue_has_been_resolved: "Your issue has been resolved!",
863
+ new_conversation: "New conversation",
864
+ welcome_screen_title: "Welcome to our support chat",
865
+ welcome_screen_description: "We're here to help! Start a conversation and we'll get back to you as soon as possible.",
866
+ your_name_placeholder: "Your name",
867
+ your_email_placeholder: "Your email address",
868
+ start_chat_button: "Talk to support",
869
+ start_chat_button_loading: "Connecting...",
870
+ i_need_more_help: "I need more help",
871
+ this_was_helpful: "This was helpful",
872
+ optional: "Optional",
873
+ no_conversations_yet: "No conversations yet",
874
+ back_to_conversations: "Back to conversations",
875
+ closed_conversations: "Closed conversations"
876
+ }, Q = {
877
+ write_a_message_placeholder: "Écrivez un message...",
878
+ your_issue_has_been_resolved: "Votre problème a été résolu !",
879
+ new_conversation: "Nouvelle conversation",
880
+ welcome_screen_title: "Bienvenue dans notre chat de support",
881
+ welcome_screen_description: "Nous sommes là pour vous aider ! Commencez une conversation et nous vous répondrons dès que possible.",
882
+ your_name_placeholder: "Votre nom",
883
+ your_email_placeholder: "Votre adresse e-mail",
884
+ start_chat_button: "Parler au support",
885
+ start_chat_button_loading: "Connexion...",
886
+ i_need_more_help: "Je besoin d'aide plus",
887
+ this_was_helpful: "C'était utile",
888
+ optional: "Optionnel",
889
+ no_conversations_yet: "Aucune conversation pour le moment",
890
+ back_to_conversations: "Retour aux conversations",
891
+ closed_conversations: "Conversations fermées"
892
+ }, ee = {
893
+ write_a_message_placeholder: "Schrijf een bericht...",
894
+ your_issue_has_been_resolved: "Uw probleem is opgelost!",
895
+ new_conversation: "Nieuw gesprek",
896
+ welcome_screen_title: "Welkom bij onze supportchat",
897
+ welcome_screen_description: "We zijn hier om te helpen! Begin een gesprek en we nemen zo snel mogelijk contact met u op.",
898
+ your_name_placeholder: "Uw naam",
899
+ your_email_placeholder: "Uw e-mailadres",
900
+ start_chat_button: "Praat met ondersteuning",
901
+ start_chat_button_loading: "Verbinding maken...",
902
+ i_need_more_help: "Ik heb nog meer hulp nodig",
903
+ this_was_helpful: "Mijn vraag is opgelost",
904
+ optional: "Optioneel",
905
+ no_conversations_yet: "Nog geen gesprekken",
906
+ back_to_conversations: "Terug naar gesprekken",
907
+ closed_conversations: "Afgesloten gesprekken"
908
+ }, te = {
909
+ write_a_message_placeholder: "Escreva uma mensagem...",
910
+ your_issue_has_been_resolved: "Seu problema foi resolvido!",
911
+ new_conversation: "Nova conversa",
912
+ welcome_screen_title: "Bem-vindo ao nosso chat de suporte",
913
+ welcome_screen_description: "Estamos aqui para ajudar! Inicie uma conversa e responderemos o mais rápido possível.",
914
+ your_name_placeholder: "Seu nome",
915
+ your_email_placeholder: "Seu endereço de email",
916
+ start_chat_button: "Falar com o suporte",
917
+ start_chat_button_loading: "Conectando...",
918
+ i_need_more_help: "preciso de mais ajuda",
919
+ this_was_helpful: "Isso foi útil",
920
+ optional: "Opcional",
921
+ no_conversations_yet: "Nenhuma conversa ainda",
922
+ back_to_conversations: "Voltar para conversas",
923
+ closed_conversations: "Conversas fechadas"
924
+ }, se = {
925
+ write_a_message_placeholder: "Escribe un mensaje...",
926
+ your_issue_has_been_resolved: "¡Tu problema fue resuelto!",
927
+ new_conversation: "Nueva conversación",
928
+ welcome_screen_title: "Bienvenido a nuestro chat de soporte",
929
+ welcome_screen_description: "¡Estamos aquí para ayudarte! Inicia una conversación y responderemos lo antes posible.",
930
+ your_name_placeholder: "Tu nombre",
931
+ your_email_placeholder: "Tu correo electrónico",
932
+ start_chat_button: "Hablar con soporte",
933
+ start_chat_button_loading: "Conectando...",
934
+ i_need_more_help: "Necesito más ayuda",
935
+ this_was_helpful: "Esto fue útil",
936
+ optional: "Opcional",
937
+ no_conversations_yet: "Sin conversaciones aún",
938
+ back_to_conversations: "Volver a conversaciones",
939
+ closed_conversations: "Conversaciones cerradas"
940
+ }, ie = {
941
+ write_a_message_placeholder: "Bir mesaj yazın...",
942
+ your_issue_has_been_resolved: "Sorununuz çözüldü!",
943
+ new_conversation: "Yeni konuşma",
944
+ welcome_screen_title: "Destek sohbetimize hoş geldiniz",
945
+ welcome_screen_description: "Yardım etmek için buradayız! Bir konuşma başlatın, en kısa sürede size geri döneceğiz.",
946
+ your_name_placeholder: "Adınız",
947
+ your_email_placeholder: "E-posta adresiniz",
948
+ start_chat_button: "Destekle konuş",
949
+ start_chat_button_loading: "Bağlanıyor...",
950
+ i_need_more_help: "Daha fazla yardıma ihtiyacım var",
951
+ this_was_helpful: "Bu yardımcı oldu",
952
+ optional: "İsteğe bağlı",
953
+ no_conversations_yet: "Henüz konuşma yok",
954
+ back_to_conversations: "Konuşmalara geri dön",
955
+ closed_conversations: "Kapatılan konuşmalar"
956
+ }, F = {
957
+ en: Z,
958
+ ar: X,
959
+ nl: ee,
960
+ fr: Q,
961
+ de: J,
962
+ pt: te,
963
+ es: se,
964
+ tr: ie
965
+ }, ne = Object.keys(F);
966
+ function le(h) {
967
+ return ne.includes(h);
968
+ }
969
+ function he(h, i, a) {
970
+ var c;
971
+ return ((c = a == null ? void 0 : a[i]) == null ? void 0 : c[h]) || F[i][h] || "";
972
+ }
828
973
  export {
829
974
  y as PrimitiveState,
830
- R as WidgetCtx,
831
- $ as isExhaustive
975
+ U as WidgetCtx,
976
+ he as getTranslation,
977
+ H as isExhaustive,
978
+ le as isSupportedLanguage
832
979
  };
833
980
  //# sourceMappingURL=index.js.map