@opencx/widget 3.0.37 → 3.0.39

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