@opencx/widget-core 5.0.0-beta.1 → 5.0.0-beta.2

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,130 +1,131 @@
1
- import Y from "openapi-fetch";
2
- import Q from "lodash.isequal";
3
- import { v4 as B } from "uuid";
4
- const Na = (i) => i.type === "data-keepalive", Ra = (i) => i.type === "data-turn-steered", N = "[opencx]", u = {
5
- warn: (i, ...e) => {
6
- console.warn(`${N} ${i}`, ...e);
1
+ import Q from "openapi-fetch";
2
+ import X from "lodash.isequal";
3
+ import { v4 as I } from "uuid";
4
+ const Ra = (_) => _.type === "data-keepalive", Ka = (_) => _.type === "data-turn-steered", R = "[opencx]", m = {
5
+ warn: (_, ...e) => {
6
+ console.warn(`${R} ${_}`, ...e);
7
7
  },
8
- error: (i, ...e) => {
9
- console.error(`${N} ${i}`, ...e);
8
+ error: (_, ...e) => {
9
+ console.error(`${R} ${_}`, ...e);
10
10
  }
11
- }, X = (i) => {
12
- u.error("request failed", i.error);
13
- }, ee = (i) => {
14
- const e = Y({
15
- baseUrl: i.baseUrl
16
- }), t = {
17
- onRequest: i.onRequest,
18
- onResponse: i.onResponse,
19
- onError: i.onError || X
11
+ }, ee = (_) => {
12
+ m.error("request failed", _.error);
13
+ }, ae = (_) => {
14
+ const e = Q({
15
+ baseUrl: _.baseUrl
16
+ }), a = {
17
+ onRequest: _.onRequest,
18
+ onResponse: _.onResponse,
19
+ onError: _.onError || ee
20
20
  };
21
- return e.use(t), e;
22
- }, ae = "/backend/widget/v5/chat/stream", te = "/backend/widget/v5/chat/{sessionId}/stream", R = (i, e, t) => `${i.replace(/\/$/, "")}${t ? e.replace("{sessionId}", encodeURIComponent(t)) : e}`;
23
- class K {
21
+ return e.use(a), e;
22
+ }, te = "/backend/widget/v5/chat/stream", se = "/backend/widget/v5/chat/{sessionId}/stream", K = (_, e, a) => `${_.replace(/\/$/, "")}${a ? e.replace("{sessionId}", encodeURIComponent(a)) : e}`;
23
+ class L {
24
24
  constructor({ config: e }) {
25
- var _, l;
26
- this.userToken = null, this.constructClientOptions = (a) => {
27
- const n = this.config.apiUrl || "https://api.open.cx", s = {
25
+ var i, l;
26
+ this.userToken = null, this.constructClientOptions = (o) => {
27
+ const t = this.config.apiUrl || "https://api.open.cx", s = {
28
28
  "X-Bot-Token": this.config.token,
29
29
  "Content-Type": "application/json",
30
30
  Accept: "application/json",
31
- Authorization: a ? `Bearer ${a}` : void 0
31
+ Authorization: o ? `Bearer ${o}` : void 0
32
32
  };
33
- return { baseUrl: n, headers: s };
33
+ return { baseUrl: t, headers: s };
34
34
  }, this.createOpenAPIClient = ({
35
- baseUrl: a,
36
- headers: n
37
- }) => ee({
38
- baseUrl: a,
35
+ baseUrl: o,
36
+ headers: t
37
+ }) => ae({
38
+ baseUrl: o,
39
39
  onRequest: ({ request: s }) => {
40
- Object.entries(n).forEach(([r, c]) => {
40
+ Object.entries(t).forEach(([r, c]) => {
41
41
  c && s.headers.set(r, c);
42
42
  });
43
43
  }
44
- }), this.setAuthToken = (a) => {
45
- this.userToken = a;
46
- const { baseUrl: n, headers: s } = this.constructClientOptions(a);
47
- this.client = this.createOpenAPIClient({ baseUrl: n, headers: s });
44
+ }), this.setAuthToken = (o) => {
45
+ this.userToken = o;
46
+ const { baseUrl: t, headers: s } = this.constructClientOptions(o);
47
+ this.client = this.createOpenAPIClient({ baseUrl: t, headers: s });
48
48
  }, this.getStreamAuthContext = () => {
49
- const { baseUrl: a, headers: n } = this.constructClientOptions(this.userToken), s = {};
50
- for (const [r, c] of Object.entries(n))
49
+ const { baseUrl: o, headers: t } = this.constructClientOptions(this.userToken), s = {};
50
+ for (const [r, c] of Object.entries(t))
51
51
  typeof c == "string" && (["content-type", "accept"].includes(r.toLowerCase()) || (s[r] = c));
52
- return { baseUrl: a, headers: s };
52
+ return { baseUrl: o, headers: s };
53
53
  }, this.getStreamTransportOptions = () => {
54
- const { baseUrl: a, headers: n } = this.getStreamAuthContext();
54
+ const { baseUrl: o, headers: t } = this.getStreamAuthContext();
55
55
  return {
56
- api: R(a, ae),
57
- reconnectApi: (s) => R(a, te, s),
58
- headers: n
56
+ api: K(o, te),
57
+ reconnectApi: (s) => K(o, se, s),
58
+ headers: t
59
59
  };
60
- }, this.stopStream = async (a) => {
61
- const { response: n } = await this.client.POST(
60
+ }, this.stopStream = async (o) => {
61
+ const { response: t } = await this.client.POST(
62
62
  "/backend/widget/v5/chat/{sessionId}/stop",
63
- { params: { path: { sessionId: a } } }
63
+ { params: { path: { sessionId: o } } }
64
64
  );
65
- if (!n.ok)
66
- throw new Error(`Failed to stop stream: ${n.status}`);
67
- }, this.getAgentTurnMessages = async (a) => {
68
- const { data: n, response: s } = await this.client.GET(
65
+ if (!t.ok)
66
+ throw new Error(`Failed to stop stream: ${t.status}`);
67
+ }, this.getAgentTurnMessages = async (o) => {
68
+ const { data: t, response: s } = await this.client.GET(
69
69
  "/backend/widget/v5/chat/{sessionId}/messages",
70
- { params: { path: { sessionId: a } } }
70
+ { params: { path: { sessionId: o } } }
71
71
  );
72
- return n || (u.warn("agent turn messages fetch failed", s.status), null);
72
+ return t || (m.warn("agent turn messages fetch failed", s.status), null);
73
73
  }, this.createDictationSession = async ({
74
- language: a
74
+ language: o
75
75
  }) => {
76
- const { data: n, response: s } = await this.client.POST(
76
+ const { data: t, response: s } = await this.client.POST(
77
77
  "/backend/widget/v5/dictation/sessions",
78
- { body: a ? { language: a } : {} }
78
+ { body: o ? { language: o } : {} }
79
79
  );
80
- if (!n)
80
+ if (!t)
81
81
  throw new Error(`Failed to start dictation: ${s.status}`);
82
- return n;
82
+ return t;
83
83
  }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
84
84
  params: {
85
85
  header: { "x-bot-token": this.config.token }
86
86
  }
87
- }), this.sendMessage = async (a, n) => await this.client.POST("/backend/widget/v2/chat/send", {
88
- body: a,
89
- signal: n
90
- }), this.createUnverifiedContact = async (a) => await this.client.POST(
87
+ }), this.sendMessage = async (o, t) => await this.client.POST("/backend/widget/v2/chat/send", {
88
+ body: o,
89
+ signal: t
90
+ }), this.createUnverifiedContact = async (o) => await this.client.POST(
91
91
  "/backend/widget/v2/contact/create-unverified",
92
92
  {
93
93
  params: { header: { "x-bot-token": this.config.token } },
94
- body: a
94
+ body: o
95
95
  }
96
- ), this.createSession = async (a) => await this.client.POST("/backend/widget/v2/create-session", {
97
- body: a
96
+ ), this.createSession = async (o, t) => await this.client.POST("/backend/widget/v2/create-session", {
97
+ body: o,
98
+ signal: t
98
99
  }), this.pollSessionAndHistory = async ({
99
- sessionId: a,
100
- abortSignal: n
100
+ sessionId: o,
101
+ abortSignal: t
101
102
  }) => await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
102
- params: { path: { sessionId: a } },
103
- signal: n
103
+ params: { path: { sessionId: o } },
104
+ signal: t
104
105
  }), this.getSessions = async ({
105
- cursor: a,
106
- filters: n,
106
+ cursor: o,
107
+ filters: t,
107
108
  abortSignal: s
108
109
  }) => await this.client.GET("/backend/widget/v2/sessions", {
109
110
  params: {
110
111
  query: {
111
- offset: a,
112
- filters: JSON.stringify(n)
112
+ offset: o,
113
+ filters: JSON.stringify(t)
113
114
  }
114
115
  },
115
116
  signal: s
116
117
  }), this.uploadFile = async ({
117
- file: a,
118
- abortSignal: n,
118
+ file: o,
119
+ abortSignal: t,
119
120
  onProgress: s
120
121
  }) => new Promise((r, c) => {
121
- var w;
122
+ var j;
122
123
  const p = new FormData();
123
- p.append("file", a);
124
+ p.append("file", o);
124
125
  const d = new XMLHttpRequest();
125
- if (n && (n.addEventListener("abort", () => {
126
+ if (t && (t.addEventListener("abort", () => {
126
127
  d.abort(), c(new DOMException("Aborted", "AbortError"));
127
- }), n.aborted)) {
128
+ }), t.aborted)) {
128
129
  c(new DOMException("Aborted", "AbortError"));
129
130
  return;
130
131
  }
@@ -148,135 +149,135 @@ class K {
148
149
  }), d.addEventListener("timeout", () => {
149
150
  c(new Error("Upload timed out"));
150
151
  });
151
- const { baseUrl: m } = this.constructClientOptions(this.userToken), g = `${m}/backend/widget/v2/upload`;
152
- d.open("POST", g), 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}`) : u.error("user token not set"), d.send(p);
153
- }), this.vote = async (a) => await this.client.POST("/backend/widget/v2/chat/vote", { body: a }), this.resolveSession = async (a, n) => await this.client.POST("/backend/widget/v2/session/resolve", {
154
- body: a,
155
- signal: n
156
- }), this.createStateCheckpoint = async (a) => await this.client.POST("/backend/widget/v2/checkpoint", {
157
- body: a
158
- }), this.submitCsat = async (a) => await this.client.POST("/backend/widget/v2/submit-csat", { body: a }), this.config = e, this.userToken = ((_ = e.user) == null ? void 0 : _.token) || null;
159
- const { baseUrl: t, headers: o } = this.constructClientOptions(
152
+ const { baseUrl: u } = this.constructClientOptions(this.userToken), h = `${u}/backend/widget/v2/upload`;
153
+ d.open("POST", h), d.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((j = this.config.user) == null ? void 0 : j.token) ? d.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : m.error("user token not set"), d.send(p);
154
+ }), this.vote = async (o) => await this.client.POST("/backend/widget/v2/chat/vote", { body: o }), this.resolveSession = async (o, t) => await this.client.POST("/backend/widget/v2/session/resolve", {
155
+ body: o,
156
+ signal: t
157
+ }), this.createStateCheckpoint = async (o) => await this.client.POST("/backend/widget/v2/checkpoint", {
158
+ body: o
159
+ }), this.submitCsat = async (o) => await this.client.POST("/backend/widget/v2/submit-csat", { body: o }), this.config = e, this.userToken = ((i = e.user) == null ? void 0 : i.token) || null;
160
+ const { baseUrl: a, headers: n } = this.constructClientOptions(
160
161
  (l = e.user) == null ? void 0 : l.token
161
162
  );
162
- this.client = this.createOpenAPIClient({ baseUrl: t, headers: o });
163
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: n });
163
164
  }
164
165
  }
165
- function se(i, e) {
166
- u.error(`missing case for ${i} in ${e}`);
166
+ function ne(_, e) {
167
+ m.error(`missing case for ${_} in ${e}`);
167
168
  }
168
- class j {
169
+ class w {
169
170
  constructor(e) {
170
- this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (t) => {
171
- Q(this.state, t) || (this.state = t, this.notifySubscribers(t));
172
- }, this.setPartial = (t) => {
173
- if (t == null) return;
174
- const o = { ...this.state, ...t };
175
- this.set(o);
171
+ this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
172
+ X(this.state, a) || (this.state = a, this.notifySubscribers(a));
173
+ }, this.setPartial = (a) => {
174
+ if (a == null) return;
175
+ const n = { ...this.state, ...a };
176
+ this.set(n);
176
177
  }, this.reset = () => {
177
178
  this.set(this.initialState);
178
- }, this.notifySubscribers = (t) => {
179
- Array.from(this.subscribers).forEach((_) => {
179
+ }, this.notifySubscribers = (a) => {
180
+ Array.from(this.subscribers).forEach((i) => {
180
181
  try {
181
- _(t);
182
+ i(a);
182
183
  } catch (l) {
183
- u.error("state subscriber threw", l);
184
+ m.error("state subscriber threw", l);
184
185
  }
185
186
  });
186
- }, this.subscribe = (t) => (this.subscribers.add(t), () => {
187
- this.subscribers.delete(t);
187
+ }, this.subscribe = (a) => (this.subscribers.add(a), () => {
188
+ this.subscribers.delete(a);
188
189
  }), this.state = e, this.initialState = e;
189
190
  }
190
191
  }
191
192
  class V {
192
193
  constructor() {
193
- this.state = new j({
194
+ this.state = new w({
194
195
  isPolling: !1,
195
196
  isError: !1
196
197
  }), this.abortController = new AbortController(), this.reset = () => {
197
198
  var e;
198
199
  this.abortController.abort("Resetting poller"), (e = this.stopPolling) == null || e.call(this), this.stopPolling = null;
199
- }, this.stopPolling = null, this.startPolling = (e, t) => {
200
+ }, this.stopPolling = null, this.startPolling = (e, a) => {
200
201
  if (this.stopPolling) return;
201
- const o = [], _ = async () => {
202
+ const n = [], i = async () => {
202
203
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
203
204
  try {
204
205
  await e(this.abortController.signal);
205
206
  } catch (l) {
206
207
  if (this.abortController.signal.aborted)
207
208
  return;
208
- u.error("failed to poll", l), this.state.setPartial({ isError: !0 });
209
+ m.error("failed to poll", l), this.state.setPartial({ isError: !0 });
209
210
  } finally {
210
211
  this.state.setPartial({ isPolling: !1 });
211
212
  }
212
- this.abortController.signal.aborted || o.push(setTimeout(_, t));
213
+ this.abortController.signal.aborted || n.push(setTimeout(i, a));
213
214
  };
214
- _(), this.stopPolling = () => {
215
- o.forEach(clearTimeout), this.state.reset();
215
+ i(), this.stopPolling = () => {
216
+ n.forEach(clearTimeout), this.state.reset();
216
217
  };
217
218
  };
218
219
  }
219
220
  }
220
- function H(i) {
221
+ function H(_) {
221
222
  try {
222
- const e = i();
223
- return e instanceof Promise ? e.then((t) => ({ data: t })).catch((t) => ({ error: t })) : { data: e };
223
+ const e = _();
224
+ return e instanceof Promise ? e.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: e };
224
225
  } catch (e) {
225
226
  return { error: e };
226
227
  }
227
228
  }
228
- class ne {
229
+ class oe {
229
230
  constructor({
230
231
  api: e,
231
- config: t,
232
- sessionCtx: o,
233
- messageCtx: _,
232
+ config: a,
233
+ sessionCtx: n,
234
+ messageCtx: i,
234
235
  sessionPollingIntervalSeconds: l
235
236
  }) {
236
237
  this.poller = new V(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.reconcilingSessionId = null, this.registerPolling = () => {
237
- this.sessionCtx.sessionState.subscribe(({ session: a }) => {
238
- a != null && a.id ? this.poller.startPolling(async (n) => {
239
- this.fetchSessionAndHistory({ sessionId: a.id, abortSignal: n });
238
+ this.sessionCtx.sessionState.subscribe(({ session: o }) => {
239
+ o != null && o.id ? this.poller.startPolling(async (t) => {
240
+ this.fetchSessionAndHistory({ sessionId: o.id, abortSignal: t });
240
241
  }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
241
- }), this.sessionCtx.sessionState.subscribe(({ session: a }) => {
242
- if (a != null && a.id && !a.isOpened)
242
+ }), this.sessionCtx.sessionState.subscribe(({ session: o }) => {
243
+ if (o != null && o.id && !o.isOpened)
243
244
  try {
244
245
  this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.fetchSessionAndHistory({
245
- sessionId: a.id,
246
+ sessionId: o.id,
246
247
  abortSignal: this.fetchSessionAndFullHistoryAbortController.signal
247
248
  });
248
- } catch (n) {
249
- this.fetchSessionAndFullHistoryAbortController.signal.aborted || u.error("failed to fetch session and full history", n);
249
+ } catch (t) {
250
+ this.fetchSessionAndFullHistoryAbortController.signal.aborted || m.error("failed to fetch session and full history", t);
250
251
  }
251
252
  else
252
253
  this.fetchSessionAndFullHistoryAbortController.abort();
253
- }), this.sessionCtx.sessionState.subscribe(({ session: a }) => {
254
- this.reconcilingSessionId !== null && (a == null ? void 0 : a.id) !== this.reconcilingSessionId && this.reconcileAbortController.abort();
254
+ }), this.sessionCtx.sessionState.subscribe(({ session: o }) => {
255
+ this.reconcilingSessionId !== null && (o == null ? void 0 : o.id) !== this.reconcilingSessionId && this.reconcileAbortController.abort();
255
256
  });
256
- }, this.reconcileAfterStream = async (a) => {
257
+ }, this.reconcileAfterStream = async (o) => {
257
258
  this.reconcileAbortController.abort(), this.reconcileAbortController = new AbortController();
258
- const { signal: n } = this.reconcileAbortController;
259
- this.reconcilingSessionId = a;
259
+ const { signal: t } = this.reconcileAbortController;
260
+ this.reconcilingSessionId = o;
260
261
  try {
261
- await this.fetchSessionAndHistory({ sessionId: a, abortSignal: n });
262
+ await this.fetchSessionAndHistory({ sessionId: o, abortSignal: t });
262
263
  } catch (s) {
263
- if (!n.aborted) throw s;
264
+ if (!t.aborted) throw s;
264
265
  } finally {
265
- this.reconcilingSessionId === a && (this.reconcilingSessionId = null);
266
+ this.reconcilingSessionId === o && (this.reconcilingSessionId = null);
266
267
  }
267
268
  }, this.fetchSessionAndHistory = async ({
268
- sessionId: a,
269
- abortSignal: n
269
+ sessionId: o,
270
+ abortSignal: t
270
271
  }) => {
271
272
  const s = this.messageCtx.state.get().messages.length === 0;
272
273
  s && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
273
274
  const { data: r } = await this.api.pollSessionAndHistory({
274
- sessionId: a,
275
- abortSignal: n
275
+ sessionId: o,
276
+ abortSignal: t
276
277
  });
277
278
  if (r != null && r.session && (this.sessionCtx.sessionState.setPartial({ session: r.session }), this.sessionCtx.setSessions([r.session])), r != null && r.history && r.history.length > 0) {
278
279
  const c = this.messageCtx.state.get().messages, p = r.history.map(this.mapHistoryToMessage).filter((d) => d !== null).filter(
279
- (d) => !c.some((m) => m.id === d.id)
280
+ (d) => !c.some((u) => u.id === d.id)
280
281
  );
281
282
  if (p.length > 0)
282
283
  if (this.messageCtx.state.setPartial({
@@ -290,43 +291,43 @@ class ne {
290
291
  this.messageCtx.dispatchToOnMessageReceivedHook(d);
291
292
  }
292
293
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
293
- }, this.mapHistoryToMessage = (a) => {
294
+ }, this.mapHistoryToMessage = (o) => {
294
295
  var s;
295
- const n = {
296
- id: a.publicId,
297
- timestamp: a.sentAt || "",
298
- attachments: a.attachments || void 0
296
+ const t = {
297
+ id: o.publicId,
298
+ timestamp: o.sentAt || "",
299
+ attachments: o.attachments || void 0
299
300
  };
300
- if (a.sender.kind === "user")
301
+ if (o.sender.kind === "user")
301
302
  return {
302
- ...n,
303
+ ...t,
303
304
  type: "USER",
304
- content: a.content.text || "",
305
+ content: o.content.text || "",
305
306
  // Backend field name (schema.ts) → widget vocabulary.
306
- markedElements: a.pickedElements
307
+ markedElements: o.pickedElements
307
308
  };
308
- if (a.sender.kind === "agent")
309
+ if (o.sender.kind === "agent")
309
310
  return {
310
- ...n,
311
+ ...t,
311
312
  type: "AGENT",
312
313
  component: "agent_message",
313
314
  data: {
314
- message: a.content.text || ""
315
+ message: o.content.text || ""
315
316
  },
316
317
  agent: {
317
- name: a.sender.name || "",
318
+ name: o.sender.name || "",
318
319
  // Do not set avatarUrl from config here... let it be taken from the config at render time
319
320
  // Only set avatar url from the backend's response
320
- avatarUrl: a.sender.avatar || null,
321
- avatar: a.sender.avatar || null,
321
+ avatarUrl: o.sender.avatar || null,
322
+ avatar: o.sender.avatar || null,
322
323
  id: null,
323
324
  isAi: !1
324
325
  }
325
326
  };
326
- if (a.sender.kind === "ai") {
327
- const r = a.actionCalls && a.actionCalls.length > 0 ? a.actionCalls[a.actionCalls.length - 1] : void 0;
327
+ if (o.sender.kind === "ai") {
328
+ const r = o.actionCalls && o.actionCalls.length > 0 ? o.actionCalls[o.actionCalls.length - 1] : void 0;
328
329
  return {
329
- ...n,
330
+ ...t,
330
331
  type: "AI",
331
332
  component: "bot_message",
332
333
  agent: {
@@ -338,7 +339,7 @@ class ne {
338
339
  avatar: null
339
340
  },
340
341
  data: {
341
- message: a.content.text || "",
342
+ message: o.content.text || "",
342
343
  action: r ? {
343
344
  name: r.actionName,
344
345
  data: this.extractActionResult(r)
@@ -346,79 +347,79 @@ class ne {
346
347
  }
347
348
  };
348
349
  }
349
- if (a.sender.kind === "system") {
350
- const r = this.constructSystemMessage(a);
350
+ if (o.sender.kind === "system") {
351
+ const r = this.constructSystemMessage(o);
351
352
  return r === null ? null : { ...r };
352
353
  }
353
354
  return null;
354
- }, this.constructSystemMessage = (a) => {
355
- if (!a || !a.systemMessagePayload) return null;
356
- switch (a.systemMessagePayload.type) {
355
+ }, this.constructSystemMessage = (o) => {
356
+ if (!o || !o.systemMessagePayload) return null;
357
+ switch (o.systemMessagePayload.type) {
357
358
  case "state_checkpoint":
358
359
  return {
359
- id: a.publicId,
360
+ id: o.publicId,
360
361
  type: "SYSTEM",
361
362
  subtype: "state_checkpoint",
362
- data: { payload: a.systemMessagePayload.payload },
363
- timestamp: a.sentAt || "",
363
+ data: { payload: o.systemMessagePayload.payload },
364
+ timestamp: o.sentAt || "",
364
365
  attachments: void 0
365
366
  };
366
367
  case "csat_requested":
367
368
  return {
368
- id: a.publicId,
369
+ id: o.publicId,
369
370
  type: "SYSTEM",
370
371
  subtype: "csat_requested",
371
372
  data: { payload: void 0 },
372
- timestamp: a.sentAt || "",
373
+ timestamp: o.sentAt || "",
373
374
  attachments: void 0
374
375
  };
375
376
  case "csat_submitted":
376
377
  return {
377
- id: a.publicId,
378
+ id: o.publicId,
378
379
  type: "SYSTEM",
379
380
  subtype: "csat_submitted",
380
381
  data: {
381
382
  payload: {
382
- score: a.systemMessagePayload.payload.score ?? void 0,
383
- feedback: a.systemMessagePayload.payload.feedback ?? void 0
383
+ score: o.systemMessagePayload.payload.score ?? void 0,
384
+ feedback: o.systemMessagePayload.payload.feedback ?? void 0
384
385
  }
385
386
  },
386
- timestamp: a.sentAt || "",
387
+ timestamp: o.sentAt || "",
387
388
  attachments: void 0
388
389
  };
389
390
  case "none":
390
391
  return null;
391
392
  default:
392
- return se(
393
- a.systemMessagePayload,
393
+ return ne(
394
+ o.systemMessagePayload,
394
395
  this.constructSystemMessage.name
395
396
  ), null;
396
397
  }
397
- }, this.extractActionResult = (a) => {
398
- const n = a.result;
399
- if (n === null || typeof n != "object") return n;
400
- if ("responseBodyText" in n && typeof n.responseBodyText == "string") {
401
- const s = n.responseBodyText, r = H(() => JSON.parse(s)).data;
398
+ }, this.extractActionResult = (o) => {
399
+ const t = o.result;
400
+ if (t === null || typeof t != "object") return t;
401
+ if ("responseBodyText" in t && typeof t.responseBodyText == "string") {
402
+ const s = t.responseBodyText, r = H(() => JSON.parse(s)).data;
402
403
  if (r) return r;
403
404
  }
404
- return a.result;
405
- }, this.api = e, this.config = t, this.sessionCtx = o, this.messageCtx = _, this.sessionPollingIntervalSeconds = l, this.registerPolling();
405
+ return o.result;
406
+ }, this.api = e, this.config = a, this.sessionCtx = n, this.messageCtx = i, this.sessionPollingIntervalSeconds = l, this.registerPolling();
406
407
  }
407
408
  }
408
- class oe {
409
+ class ie {
409
410
  constructor({
410
411
  config: e,
411
- api: t,
412
- storageCtx: o
412
+ api: a,
413
+ storageCtx: n
413
414
  }) {
414
- var _;
415
+ var i;
415
416
  this.shouldCollectData = () => {
416
417
  var l;
417
418
  return !!(!((l = this.state.get().contact) != null && l.token) && this.config.collectUserData);
418
419
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
419
- var l, a, n, s, r, c, p, d, m, h, g, y, w, b;
420
+ var l, o, t, s, r, c, p, d, u, g, h, v, j, b;
420
421
  if (!((l = this.config.user) != null && l.token)) {
421
- if (this.config.collectUserData && !((n = (a = this.config.user) == null ? void 0 : a.data) != null && n.email)) {
422
+ if (this.config.collectUserData && !((t = (o = this.config.user) == null ? void 0 : o.data) != null && t.email)) {
422
423
  if ((s = this.config.extraDataCollectionFields) != null && s.length)
423
424
  return;
424
425
  const f = await ((r = this.storageCtx) == null ? void 0 : r.getContactToken());
@@ -433,49 +434,49 @@ class oe {
433
434
  }
434
435
  }
435
436
  await this.createUnverifiedContact({
436
- email: (h = (m = this.config.user) == null ? void 0 : m.data) == null ? void 0 : h.email,
437
- non_verified_name: (y = (g = this.config.user) == null ? void 0 : g.data) == null ? void 0 : y.name,
438
- non_verified_custom_data: (b = (w = this.config.user) == null ? void 0 : w.data) == null ? void 0 : b.customData
437
+ email: (g = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : g.email,
438
+ non_verified_name: (v = (h = this.config.user) == null ? void 0 : h.data) == null ? void 0 : v.name,
439
+ non_verified_custom_data: (b = (j = this.config.user) == null ? void 0 : j.data) == null ? void 0 : b.customData
439
440
  });
440
441
  }
441
- }, this.createUnverifiedContact = async (l, a) => {
442
- this.state.setPartial({ extraCollectedData: a });
442
+ }, this.createUnverifiedContact = async (l, o) => {
443
+ this.state.setPartial({ extraCollectedData: o });
443
444
  try {
444
445
  this.state.setPartial({
445
446
  isCreatingUnverifiedContact: !0,
446
447
  isErrorCreatingUnverifiedContact: !1
447
448
  });
448
- const { data: n } = await this.api.createUnverifiedContact(l);
449
- n != null && n.token ? await this.setUnverifiedContact(n.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
450
- } catch (n) {
451
- this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), u.error("failed to create an unverified contact", {
452
- _e: n instanceof Error ? n.message : String(n)
449
+ const { data: t } = await this.api.createUnverifiedContact(l);
450
+ t != null && t.token ? await this.setUnverifiedContact(t.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
451
+ } catch (t) {
452
+ this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), m.error("failed to create an unverified contact", {
453
+ _e: t instanceof Error ? t.message : String(t)
453
454
  });
454
455
  } finally {
455
456
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
456
457
  }
457
458
  }, this.recoverFromStaleToken = async () => {
458
- var l, a, n, s, r, c, p, d, m, h;
459
+ var l, o, t, s, r, c, p, d, u, g;
459
460
  if ((l = this.config.user) != null && l.token) return !1;
460
461
  this.api.setAuthToken(""), this.state.setPartial({ contact: null });
461
462
  try {
462
- await ((a = this.storageCtx) == null ? void 0 : a.clearContactToken()), await ((n = this.storageCtx) == null ? void 0 : n.clearActiveSessionId());
463
- } catch (g) {
464
- u.warn("failed to clear a stale contact token", {
465
- error: g instanceof Error ? g.message : String(g)
463
+ await ((o = this.storageCtx) == null ? void 0 : o.clearContactToken()), await ((t = this.storageCtx) == null ? void 0 : t.clearActiveSessionId());
464
+ } catch (h) {
465
+ m.warn("failed to clear a stale contact token", {
466
+ error: h instanceof Error ? h.message : String(h)
466
467
  });
467
468
  }
468
469
  return await this.createUnverifiedContact({
469
470
  email: (r = (s = this.config.user) == null ? void 0 : s.data) == null ? void 0 : r.email,
470
471
  non_verified_name: (p = (c = this.config.user) == null ? void 0 : c.data) == null ? void 0 : p.name,
471
- non_verified_custom_data: (m = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : m.customData
472
- }), !!((h = this.state.get().contact) != null && h.token);
472
+ non_verified_custom_data: (u = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : u.customData
473
+ }), !!((g = this.state.get().contact) != null && g.token);
473
474
  }, this.setUnverifiedContact = async (l) => {
474
475
  var s, r, c, p;
475
- const a = await ((s = this.storageCtx) == null ? void 0 : s.getExternalContactId()), n = ((r = this.config.user) == null ? void 0 : r.externalId) || a || B();
476
- this.api.setAuthToken(l), await ((c = this.storageCtx) == null ? void 0 : c.setContactToken(l)), await ((p = this.storageCtx) == null ? void 0 : p.setExternalContactId(n)), this.state.setPartial({ contact: { token: l, externalId: n } });
477
- }, this.config = e, this.storageCtx = o, this.api = t, this.state = new j({
478
- contact: (_ = e.user) != null && _.token ? {
476
+ const o = await ((s = this.storageCtx) == null ? void 0 : s.getExternalContactId()), t = ((r = this.config.user) == null ? void 0 : r.externalId) || o || I();
477
+ this.api.setAuthToken(l), await ((c = this.storageCtx) == null ? void 0 : c.setContactToken(l)), await ((p = this.storageCtx) == null ? void 0 : p.setExternalContactId(t)), this.state.setPartial({ contact: { token: l, externalId: t } });
478
+ }, this.config = e, this.storageCtx = n, this.api = a, this.state = new w({
479
+ contact: (i = e.user) != null && i.token ? {
479
480
  token: e.user.token,
480
481
  // Set optional externalId from config... not local storage
481
482
  externalId: e.user.externalId
@@ -486,48 +487,97 @@ class oe {
486
487
  }), this.autoCreateUnverifiedUserIfNotExists();
487
488
  }
488
489
  }
489
- function x() {
490
- return B();
490
+ class re {
491
+ constructor(e) {
492
+ this.api = e, this.state = new w([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (a) => {
493
+ const n = a.map(
494
+ (i) => ({
495
+ file: i,
496
+ id: I(),
497
+ status: "pending",
498
+ progress: 0
499
+ })
500
+ );
501
+ this.state.set([...this.state.get(), ...n]), n.forEach((i) => void this.upload(i));
502
+ }, this.cancel = (a) => {
503
+ var n;
504
+ (n = this.controllers.get(a)) == null || n.abort(), this.controllers.delete(a), this.state.set(this.state.get().filter((i) => i.id !== a));
505
+ }, this.reset = () => {
506
+ this.controllers.forEach((a) => a.abort()), this.controllers.clear(), this.state.reset();
507
+ };
508
+ }
509
+ update(e, a) {
510
+ this.state.set(
511
+ this.state.get().map((n) => n.id === e ? { ...n, ...a } : n)
512
+ );
513
+ }
514
+ async upload(e) {
515
+ const a = new AbortController();
516
+ this.controllers.set(e.id, a), this.update(e.id, { status: "uploading" });
517
+ try {
518
+ const n = await this.api.uploadFile({
519
+ file: e.file,
520
+ abortSignal: a.signal,
521
+ onProgress: (i) => this.update(e.id, { progress: i })
522
+ });
523
+ this.update(e.id, {
524
+ status: "success",
525
+ fileUrl: n.fileUrl,
526
+ progress: 100
527
+ });
528
+ } catch (n) {
529
+ a.signal.aborted || this.update(e.id, {
530
+ status: "error",
531
+ progress: 0,
532
+ error: n instanceof Error ? n.message : "Upload failed"
533
+ });
534
+ } finally {
535
+ this.controllers.delete(e.id);
536
+ }
537
+ }
538
+ }
539
+ function z() {
540
+ return I();
491
541
  }
492
- class ie {
542
+ class _e {
493
543
  constructor({
494
544
  api: e,
495
- sessionCtx: t,
496
- messageCtx: o
545
+ sessionCtx: a,
546
+ messageCtx: n
497
547
  }) {
498
- this.submitCsat = async (_) => {
548
+ this.submitCsat = async (i) => {
499
549
  var r;
500
550
  const l = (r = this.sessionCtx.sessionState.get().session) == null ? void 0 : r.id;
501
551
  if (!l)
502
552
  return { data: null, error: "No session id found" };
503
- const a = x();
553
+ const o = z();
504
554
  this.messageCtx.state.setPartial({
505
555
  messages: [
506
556
  ...this.messageCtx.state.get().messages,
507
557
  {
508
- id: a,
558
+ id: o,
509
559
  type: "SYSTEM",
510
560
  subtype: "csat_submitted",
511
561
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
512
562
  data: {
513
563
  payload: {
514
- score: _.score,
515
- feedback: _.feedback
564
+ score: i.score,
565
+ feedback: i.feedback
516
566
  }
517
567
  }
518
568
  }
519
569
  ]
520
570
  });
521
- const { data: n, error: s } = await this.api.submitCsat({
522
- ..._,
523
- system_message_uuid: a,
571
+ const { data: t, error: s } = await this.api.submitCsat({
572
+ ...i,
573
+ system_message_uuid: o,
524
574
  session_id: l
525
575
  });
526
- return { data: n, error: s };
527
- }, this.api = e, this.sessionCtx = t, this.messageCtx = o;
576
+ return { data: t, error: s };
577
+ }, this.api = e, this.sessionCtx = a, this.messageCtx = n;
528
578
  }
529
579
  }
530
- const re = [
580
+ const le = [
531
581
  {
532
582
  action: "newparagraph",
533
583
  phrases: {
@@ -602,7 +652,7 @@ const re = [
602
652
  it: ["invia messaggio"]
603
653
  }
604
654
  }
605
- ], _e = [
655
+ ], ce = [
606
656
  "en",
607
657
  "es",
608
658
  "fr",
@@ -610,67 +660,67 @@ const re = [
610
660
  "pt",
611
661
  "it"
612
662
  ];
613
- function le(i) {
614
- return _e.includes(i);
663
+ function pe(_) {
664
+ return ce.includes(_);
615
665
  }
616
- function ce(i) {
617
- return i.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
666
+ function de(_) {
667
+ return _.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
618
668
  }
619
- function pe(i) {
620
- const e = re.flatMap(
621
- (_) => i.flatMap(
622
- (l) => _.phrases[l].map((a) => ({ phrase: a, action: _.action }))
669
+ function ue(_) {
670
+ const e = le.flatMap(
671
+ (i) => _.flatMap(
672
+ (l) => i.phrases[l].map((o) => ({ phrase: o, action: i.action }))
623
673
  )
624
- ), t = e.map((_) => ce(_.phrase)).sort((_, l) => l.length - _.length).join("|"), o = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
674
+ ), a = e.map((i) => de(i.phrase)).sort((i, l) => l.length - i.length).join("|"), n = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
625
675
  return {
626
676
  regex: new RegExp(
627
- `${o}(${t})` + String.raw`([.,!?;:])(?=\s|$)`,
677
+ `${n}(${a})` + String.raw`([.,!?;:])(?=\s|$)`,
628
678
  "giu"
629
679
  ),
630
680
  finalRegex: new RegExp(
631
- `${o}(${t})` + String.raw`([.,!?;:]?)(?=\s|$)`,
681
+ `${n}(${a})` + String.raw`([.,!?;:]?)(?=\s|$)`,
632
682
  "giu"
633
683
  ),
634
684
  phraseToAction: new Map(
635
- e.map((_) => [_.phrase.toLowerCase(), _.action])
685
+ e.map((i) => [i.phrase.toLowerCase(), i.action])
636
686
  ),
637
- longestPhrase: Math.max(...e.map((_) => _.phrase.length))
687
+ longestPhrase: Math.max(...e.map((i) => i.phrase.length))
638
688
  };
639
689
  }
640
- const L = /* @__PURE__ */ new Map();
641
- function T(i) {
642
- const e = i && le(i) && i !== "en" ? i : null, t = e ?? "en";
643
- let o = L.get(t);
644
- return o || (o = pe(e ? ["en", e] : ["en"]), L.set(t, o)), o;
690
+ const F = /* @__PURE__ */ new Map();
691
+ function A(_) {
692
+ const e = _ && pe(_) && _ !== "en" ? _ : null, a = e ?? "en";
693
+ let n = F.get(a);
694
+ return n || (n = ue(e ? ["en", e] : ["en"]), F.set(a, n)), n;
645
695
  }
646
- function de(i) {
647
- const e = i.replace(/\s+$/, "");
696
+ function me(_) {
697
+ const e = _.replace(/\s+$/, "");
648
698
  if (!e) return "";
649
- const t = e.replace(/[.!?]+$/, "");
650
- let o = -1;
651
- for (let _ = t.length - 1; _ >= 0; _--) {
652
- const l = t[_];
699
+ const a = e.replace(/[.!?]+$/, "");
700
+ let n = -1;
701
+ for (let i = a.length - 1; i >= 0; i--) {
702
+ const l = a[i];
653
703
  if (l === "." || l === "!" || l === "?" || l === `
654
704
  `) {
655
- o = _ + 1;
705
+ n = i + 1;
656
706
  break;
657
707
  }
658
708
  }
659
- return o === -1 ? "" : `${t.slice(0, o)} `.replace(/\n $/, `
709
+ return n === -1 ? "" : `${a.slice(0, n)} `.replace(/\n $/, `
660
710
  `);
661
711
  }
662
- const me = new RegExp(
712
+ const he = new RegExp(
663
713
  String.raw`(^- |\n(?:- )?)(\p{Ll})`,
664
714
  "gu"
665
715
  );
666
- function ue(i) {
667
- return i.replace(
668
- me,
669
- (e, t, o) => t + o.toUpperCase()
716
+ function ge(_) {
717
+ return _.replace(
718
+ he,
719
+ (e, a, n) => a + n.toUpperCase()
670
720
  );
671
721
  }
672
- function he(i) {
673
- return i.length <= 3 && /^\s*$/.test(i) ? !0 : /[.!?\n]\s{0,3}$/.test(i.slice(-6));
722
+ function ke(_) {
723
+ return _.length <= 3 && /^\s*$/.test(_) ? !0 : /[.!?\n]\s{0,3}$/.test(_.slice(-6));
674
724
  }
675
725
  class C {
676
726
  /**
@@ -678,36 +728,36 @@ class C {
678
728
  * Pure and deterministic: always called with the entire raw string so the
679
729
  * result never depends on delta chunking.
680
730
  */
681
- static process(e, t) {
682
- const o = T(t == null ? void 0 : t.language), _ = t != null && t.final ? "" : C.commandPrefixTail(e, t == null ? void 0 : t.language), l = e.slice(0, e.length - _.length), a = t != null && t.final ? o.finalRegex : o.regex;
683
- let n = "", s = null, r = 0;
684
- for (const p of Array.from(l.matchAll(a))) {
685
- const [, d = ""] = p, m = o.phraseToAction.get(d.toLowerCase());
686
- if (m)
687
- if (n += l.slice(r, p.index), r = p.index + p[0].length, m === "newline") n = `${n.replace(/[ \t]+$/, "")}
731
+ static process(e, a) {
732
+ const n = A(a == null ? void 0 : a.language), i = a != null && a.final ? "" : C.commandPrefixTail(e, a == null ? void 0 : a.language), l = e.slice(0, e.length - i.length), o = a != null && a.final ? n.finalRegex : n.regex;
733
+ let t = "", s = null, r = 0;
734
+ for (const p of Array.from(l.matchAll(o))) {
735
+ const [, d = ""] = p, u = n.phraseToAction.get(d.toLowerCase());
736
+ if (u)
737
+ if (t += l.slice(r, p.index), r = p.index + p[0].length, u === "newline") t = `${t.replace(/[ \t]+$/, "")}
688
738
  `;
689
- else if (m === "newparagraph")
690
- n = `${n.replace(/[ \t]+$/, "")}
739
+ else if (u === "newparagraph")
740
+ t = `${t.replace(/[ \t]+$/, "")}
691
741
 
692
742
  `;
693
- else if (m === "bullet") {
694
- const h = n.replace(/[ \t]+$/, "");
695
- n = h === "" || h.endsWith(`
696
- `) ? `${h}- ` : `${h}
743
+ else if (u === "bullet") {
744
+ const g = t.replace(/[ \t]+$/, "");
745
+ t = g === "" || g.endsWith(`
746
+ `) ? `${g}- ` : `${g}
697
747
  - `;
698
- } else if (m === "scratch") n = de(n);
748
+ } else if (u === "scratch") t = me(t);
699
749
  else {
700
- s = m === "send" ? "send" : "stop";
750
+ s = u === "send" ? "send" : "stop";
701
751
  break;
702
752
  }
703
753
  }
704
- return s === null && (n += l.slice(r)), { text: ue(
705
- n.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
754
+ return s === null && (t += l.slice(r)), { text: ge(
755
+ t.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
706
756
  `).replace(/\n[ \t]+/g, `
707
757
  `).replace(/(^|\n)- +/g, "$1- ").replace(/ {2,}/g, " ").replace(/\n{3,}/g, `
708
758
 
709
759
  `)
710
- ), pendingTail: _, control: s };
760
+ ), pendingTail: i, control: s };
711
761
  }
712
762
  /**
713
763
  * Longest suffix of `raw` that could still become a command — a proper
@@ -718,16 +768,16 @@ class C {
718
768
  * control command from an intermediate delta would stop or submit
719
769
  * mid-sentence.
720
770
  */
721
- static commandPrefixTail(e, t) {
722
- const o = T(t), _ = Math.min(e.length, o.longestPhrase + 2);
723
- for (let l = _; l > 0; l--) {
724
- const a = e.length - l;
725
- if (!he(e.slice(0, a))) continue;
726
- const n = e.slice(a).toLowerCase(), s = n.replace(/^\s+/, "");
771
+ static commandPrefixTail(e, a) {
772
+ const n = A(a), i = Math.min(e.length, n.longestPhrase + 2);
773
+ for (let l = i; l > 0; l--) {
774
+ const o = e.length - l;
775
+ if (!ke(e.slice(0, o))) continue;
776
+ const t = e.slice(o).toLowerCase(), s = t.replace(/^\s+/, "");
727
777
  if (s) {
728
- for (const r of Array.from(o.phraseToAction.keys()))
778
+ for (const r of Array.from(n.phraseToAction.keys()))
729
779
  if (r.startsWith(s))
730
- return e.slice(a + (n.length - s.length));
780
+ return e.slice(o + (t.length - s.length));
731
781
  }
732
782
  }
733
783
  return "";
@@ -737,13 +787,13 @@ class C {
737
787
  * prefix) — i.e. a silence pause would resolve it into a command. Used by
738
788
  * the manager's silence timer.
739
789
  */
740
- static pendingTailIsCompletePhrase(e, t) {
741
- const o = C.commandPrefixTail(e, t).trim().toLowerCase();
742
- return o ? T(t).phraseToAction.has(o) : !1;
790
+ static pendingTailIsCompletePhrase(e, a) {
791
+ const n = C.commandPrefixTail(e, a).trim().toLowerCase();
792
+ return n ? A(a).phraseToAction.has(n) : !1;
743
793
  }
744
794
  }
745
- const ge = 55, ke = 90;
746
- class F {
795
+ const be = 55, fe = 90;
796
+ class O {
747
797
  /**
748
798
  * Next paced step toward `processed`: normally one word per tick so text
749
799
  * flows evenly instead of landing in bursty chunks; proportionally larger
@@ -752,28 +802,28 @@ class F {
752
802
  */
753
803
  static nextDripText({
754
804
  displayed: e,
755
- processed: t
805
+ processed: a
756
806
  }) {
757
- if (t.length <= e.length) return t;
758
- const o = t.length - e.length;
759
- if (o > ke)
760
- return t.slice(0, e.length + Math.ceil(o / 3));
761
- let _ = e.length;
762
- for (; _ < t.length && /\s/.test(t.charAt(_)); ) _++;
763
- for (; _ < t.length && !/\s/.test(t.charAt(_)); ) _++;
764
- return _ - e.length > 12 && (_ = e.length + 6), t.slice(0, Math.max(_, e.length + 1));
807
+ if (a.length <= e.length) return a;
808
+ const n = a.length - e.length;
809
+ if (n > fe)
810
+ return a.slice(0, e.length + Math.ceil(n / 3));
811
+ let i = e.length;
812
+ for (; i < a.length && /\s/.test(a.charAt(i)); ) i++;
813
+ for (; i < a.length && !/\s/.test(a.charAt(i)); ) i++;
814
+ return i - e.length > 12 && (i = e.length + 6), a.slice(0, Math.max(i, e.length + 1));
765
815
  }
766
816
  /** Normalize a BCP-47 browser locale into the hint OpenAI accepts. */
767
817
  static languageHint(e) {
768
818
  if (!e) return;
769
- const t = e.toLowerCase();
770
- if (/^zh-(cn|tw|hk)$/.test(t)) return t;
771
- const o = t.split("-")[0];
772
- return o && /^[a-z]{2,3}$/.test(o) ? o : void 0;
819
+ const a = e.toLowerCase();
820
+ if (/^zh-(cn|tw|hk)$/.test(a)) return a;
821
+ const n = a.split("-")[0];
822
+ return n && /^[a-z]{2,3}$/.test(n) ? n : void 0;
773
823
  }
774
824
  }
775
- const be = 2e4;
776
- class fe {
825
+ const ve = 2e4;
826
+ class ye {
777
827
  constructor() {
778
828
  this.cached = null, this.inflight = null;
779
829
  }
@@ -781,15 +831,15 @@ class fe {
781
831
  get() {
782
832
  if (!this.cached) return null;
783
833
  const e = Date.parse(this.cached.expiresAt);
784
- return Number.isNaN(e) || e - Date.now() < be ? (this.cached = null, null) : this.cached;
834
+ return Number.isNaN(e) || e - Date.now() < ve ? (this.cached = null, null) : this.cached;
785
835
  }
786
836
  /**
787
837
  * Resolve a mint, deduping concurrent requests (hover-prewarm racing a
788
838
  * click reuses the same in-flight promise instead of double-minting).
789
839
  */
790
840
  async resolve(e) {
791
- const t = this.get();
792
- return t || (this.inflight || (this.inflight = e().then((o) => (this.cached = o, o)).finally(() => {
841
+ const a = this.get();
842
+ return a || (this.inflight || (this.inflight = e().then((n) => (this.cached = n, n)).finally(() => {
793
843
  this.inflight = null;
794
844
  })), this.inflight);
795
845
  }
@@ -798,89 +848,89 @@ class fe {
798
848
  this.cached = null;
799
849
  }
800
850
  }
801
- function O(i) {
802
- return typeof i == "object" && i !== null && !Array.isArray(i);
851
+ function U(_) {
852
+ return typeof _ == "object" && _ !== null && !Array.isArray(_);
803
853
  }
804
- function ve(i) {
805
- if (!O(i) || typeof i.type != "string") return null;
806
- const e = O(i.error) ? i.error : null;
854
+ function we(_) {
855
+ if (!U(_) || typeof _.type != "string") return null;
856
+ const e = U(_.error) ? _.error : null;
807
857
  return {
808
- type: i.type,
809
- delta: typeof i.delta == "string" ? i.delta : void 0,
858
+ type: _.type,
859
+ delta: typeof _.delta == "string" ? _.delta : void 0,
810
860
  errorMessage: e && typeof e.message == "string" ? e.message : void 0
811
861
  };
812
862
  }
813
- const ye = "https://api.openai.com/v1/realtime/calls", we = 10 * 60 * 1e3, je = 15e3, Se = 5e3;
863
+ const je = "https://api.openai.com/v1/realtime/calls", Se = 10 * 60 * 1e3, xe = 15e3, ze = 5e3;
814
864
  class E extends Error {
815
865
  }
816
- class ze {
866
+ class Ce {
817
867
  constructor({
818
868
  mintToken: e,
819
- onDelta: t,
820
- onState: o,
821
- onError: _,
869
+ onDelta: a,
870
+ onState: n,
871
+ onError: i,
822
872
  onLevel: l
823
873
  }) {
824
- this.state = "idle", this.pc = null, this.dc = null, this.stream = null, this.audioContext = null, this.levelRaf = 0, this.timers = [], this.loggedParseFailure = !1, this.mintToken = e, this.onDelta = t, this.onState = o, this.onError = _, this.onLevel = l;
874
+ this.state = "idle", this.pc = null, this.dc = null, this.stream = null, this.audioContext = null, this.levelRaf = 0, this.timers = [], this.loggedParseFailure = !1, this.mintToken = e, this.onDelta = a, this.onState = n, this.onError = i, this.onLevel = l;
825
875
  }
826
876
  async start() {
827
877
  if (this.state === "idle") {
828
878
  this.setState("connecting"), this.timers.push(
829
879
  setTimeout(() => {
830
880
  this.state === "connecting" && this.fail("unavailable");
831
- }, je)
832
- ), this.timers.push(setTimeout(() => this.stop(), we));
881
+ }, xe)
882
+ ), this.timers.push(setTimeout(() => this.stop(), Se));
833
883
  try {
834
884
  const e = this.requestMicrophone();
835
885
  e.then((c) => {
836
886
  (this.isTornDown() || this.stream && this.stream !== c) && c.getTracks().forEach((p) => p.stop());
837
887
  }).catch(() => {
838
888
  });
839
- const [t, o] = await Promise.all([e, this.mintToken()]);
889
+ const [a, n] = await Promise.all([e, this.mintToken()]);
840
890
  if (this.isTornDown()) {
841
- t.getTracks().forEach((c) => c.stop());
891
+ a.getTracks().forEach((c) => c.stop());
842
892
  return;
843
893
  }
844
- this.stream = t, this.startLevelMeter(t);
845
- const _ = new RTCPeerConnection();
846
- this.pc = _;
847
- const [l] = t.getAudioTracks();
894
+ this.stream = a, this.startLevelMeter(a);
895
+ const i = new RTCPeerConnection();
896
+ this.pc = i;
897
+ const [l] = a.getAudioTracks();
848
898
  if (!l) throw new E("No audio track");
849
- _.addTrack(l, t);
850
- const a = _.createDataChannel("oai-events");
851
- this.dc = a, a.addEventListener(
899
+ i.addTrack(l, a);
900
+ const o = i.createDataChannel("oai-events");
901
+ this.dc = o, o.addEventListener(
852
902
  "message",
853
903
  (c) => this.handleServerEvent(c.data)
854
- ), a.addEventListener("open", () => {
904
+ ), o.addEventListener("open", () => {
855
905
  this.state === "connecting" && this.setState("listening");
856
- }), _.addEventListener("connectionstatechange", () => {
857
- if (_.connectionState === "failed") {
906
+ }), i.addEventListener("connectionstatechange", () => {
907
+ if (i.connectionState === "failed") {
858
908
  this.fail("unavailable");
859
909
  return;
860
910
  }
861
- _.connectionState === "disconnected" && this.timers.push(
911
+ i.connectionState === "disconnected" && this.timers.push(
862
912
  setTimeout(() => {
863
- this.pc === _ && _.connectionState !== "connected" && this.fail("unavailable");
864
- }, Se)
913
+ this.pc === i && i.connectionState !== "connected" && this.fail("unavailable");
914
+ }, ze)
865
915
  );
866
916
  });
867
- const n = await _.createOffer();
868
- await _.setLocalDescription(n);
869
- const s = await fetch(ye, {
917
+ const t = await i.createOffer();
918
+ await i.setLocalDescription(t);
919
+ const s = await fetch(je, {
870
920
  method: "POST",
871
921
  headers: {
872
- Authorization: `Bearer ${o.token}`,
922
+ Authorization: `Bearer ${n.token}`,
873
923
  "Content-Type": "application/sdp"
874
924
  },
875
- body: n.sdp
925
+ body: t.sdp
876
926
  });
877
927
  if (!s.ok)
878
928
  throw new Error(`Realtime handshake failed (${s.status})`);
879
929
  const r = await s.text();
880
930
  if (this.isTornDown()) return;
881
- await _.setRemoteDescription({ type: "answer", sdp: r });
931
+ await i.setRemoteDescription({ type: "answer", sdp: r });
882
932
  } catch (e) {
883
- e instanceof E ? this.fail("microphone") : (u.error("dictation session failed to start", {
933
+ e instanceof E ? this.fail("microphone") : (m.error("dictation session failed to start", {
884
934
  _e: e instanceof Error ? e.message : String(e)
885
935
  }), this.fail("unavailable"));
886
936
  }
@@ -901,60 +951,60 @@ class ze {
901
951
  autoGainControl: !0
902
952
  }
903
953
  });
904
- } catch (t) {
954
+ } catch (a) {
905
955
  throw new E(
906
- t instanceof DOMException ? t.name : "Could not access the microphone"
956
+ a instanceof DOMException ? a.name : "Could not access the microphone"
907
957
  );
908
958
  }
909
959
  }
910
960
  handleServerEvent(e) {
911
961
  if (typeof e != "string") return;
912
- let t;
962
+ let a;
913
963
  try {
914
- t = JSON.parse(e);
964
+ a = JSON.parse(e);
915
965
  } catch {
916
- this.loggedParseFailure || (this.loggedParseFailure = !0, u.error("dictation server event was not valid JSON", {
966
+ this.loggedParseFailure || (this.loggedParseFailure = !0, m.error("dictation server event was not valid JSON", {
917
967
  snippet: e.slice(0, 120)
918
968
  }));
919
969
  return;
920
970
  }
921
- const o = ve(t);
922
- if (!o) return;
923
- const { type: _, delta: l } = o;
924
- if (_ === "session.created" || _ === "transcription_session.created") {
971
+ const n = we(a);
972
+ if (!n) return;
973
+ const { type: i, delta: l } = n;
974
+ if (i === "session.created" || i === "transcription_session.created") {
925
975
  this.setState("listening");
926
976
  return;
927
977
  }
928
- if (_ === "conversation.item.input_audio_transcription.delta" && l) {
978
+ if (i === "conversation.item.input_audio_transcription.delta" && l) {
929
979
  this.state === "connecting" && this.setState("listening"), this.onDelta(l);
930
980
  return;
931
981
  }
932
- _ === "error" && (u.error("dictation server event error", {
933
- _e: o.errorMessage ?? "unknown"
982
+ i === "error" && (m.error("dictation server event error", {
983
+ _e: n.errorMessage ?? "unknown"
934
984
  }), this.fail("unavailable"));
935
985
  }
936
986
  startLevelMeter(e) {
937
987
  if (this.onLevel)
938
988
  try {
939
- const t = new AudioContext();
940
- this.audioContext = t;
941
- const o = t.createMediaStreamSource(e), _ = t.createAnalyser();
942
- _.fftSize = 512, o.connect(_);
943
- const l = new Uint8Array(_.frequencyBinCount), a = () => {
989
+ const a = new AudioContext();
990
+ this.audioContext = a;
991
+ const n = a.createMediaStreamSource(e), i = a.createAnalyser();
992
+ i.fftSize = 512, n.connect(i);
993
+ const l = new Uint8Array(i.frequencyBinCount), o = () => {
944
994
  var r;
945
- _.getByteTimeDomainData(l);
946
- let n = 0;
995
+ i.getByteTimeDomainData(l);
996
+ let t = 0;
947
997
  for (let c = 0; c < l.length; c++) {
948
998
  const p = ((l[c] ?? 128) - 128) / 128;
949
- n += p * p;
999
+ t += p * p;
950
1000
  }
951
- const s = Math.sqrt(n / l.length);
952
- (r = this.onLevel) == null || r.call(this, Math.min(1, s * 4)), this.levelRaf = requestAnimationFrame(a);
1001
+ const s = Math.sqrt(t / l.length);
1002
+ (r = this.onLevel) == null || r.call(this, Math.min(1, s * 4)), this.levelRaf = requestAnimationFrame(o);
953
1003
  };
954
- this.levelRaf = requestAnimationFrame(a);
955
- } catch (t) {
956
- u.error("dictation level meter unavailable", {
957
- _e: t instanceof Error ? t.message : String(t)
1004
+ this.levelRaf = requestAnimationFrame(o);
1005
+ } catch (a) {
1006
+ m.error("dictation level meter unavailable", {
1007
+ _e: a instanceof Error ? a.message : String(a)
958
1008
  });
959
1009
  }
960
1010
  }
@@ -965,9 +1015,9 @@ class ze {
965
1015
  this.isTornDown() || (this.teardown(), this.setState("error"), this.onError(e));
966
1016
  }
967
1017
  teardown() {
968
- var e, t, o, _;
969
- this.timers.forEach((l) => clearTimeout(l)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (e = this.dc) == null || e.close(), this.dc = null, (t = this.pc) == null || t.close(), this.pc = null, (o = this.stream) == null || o.getTracks().forEach((l) => l.stop()), this.stream = null, (_ = this.audioContext) == null || _.close().catch((l) => {
970
- u.error("failed to close dictation audio context", {
1018
+ var e, a, n, i;
1019
+ this.timers.forEach((l) => clearTimeout(l)), this.timers = [], this.levelRaf && cancelAnimationFrame(this.levelRaf), this.levelRaf = 0, (e = this.dc) == null || e.close(), this.dc = null, (a = this.pc) == null || a.close(), this.pc = null, (n = this.stream) == null || n.getTracks().forEach((l) => l.stop()), this.stream = null, (i = this.audioContext) == null || i.close().catch((l) => {
1020
+ m.error("failed to close dictation audio context", {
971
1021
  _e: String(l)
972
1022
  });
973
1023
  }), this.audioContext = null;
@@ -976,43 +1026,43 @@ class ze {
976
1026
  this.state !== e && (this.state = e, this.onState(e));
977
1027
  }
978
1028
  }
979
- const xe = 1300, Ce = { status: "idle", error: null };
980
- class qe {
981
- constructor({ api: e, config: t }) {
982
- this.state = new j(Ce), this.levelRef = { current: 0 }, this.mintCache = new fe(), this.session = null, this.target = null, this.prefix = "", this.raw = "", this.processed = "", this.displayed = "", this.dripTimer = null, this.silenceTimer = null, this.isActive = () => this.session !== null, this.prewarm = () => {
983
- this.mintToken().catch((o) => {
984
- this.mintCache.clear(), u.error("dictation token prewarm failed", {
985
- _e: o instanceof Error ? o.message : String(o)
1029
+ const qe = 1300, Ee = { status: "idle", error: null };
1030
+ class Pe {
1031
+ constructor({ api: e, config: a }) {
1032
+ this.state = new w(Ee), this.levelRef = { current: 0 }, this.mintCache = new ye(), this.session = null, this.target = null, this.prefix = "", this.raw = "", this.processed = "", this.displayed = "", this.dripTimer = null, this.silenceTimer = null, this.isActive = () => this.session !== null, this.prewarm = () => {
1033
+ this.mintToken().catch((n) => {
1034
+ this.mintCache.clear(), m.error("dictation token prewarm failed", {
1035
+ _e: n instanceof Error ? n.message : String(n)
986
1036
  });
987
1037
  });
988
- }, this.start = (o) => {
989
- this.session && this.teardown(), this.target = o, this.language = F.languageHint(
1038
+ }, this.start = (n) => {
1039
+ this.session && this.teardown(), this.target = n, this.language = O.languageHint(
990
1040
  this.config.language ?? navigator.language
991
- ), this.prefix = o.getValue(), this.raw = "", this.processed = "", this.displayed = "";
992
- const _ = new ze({
1041
+ ), this.prefix = n.getValue(), this.raw = "", this.processed = "", this.displayed = "";
1042
+ const i = new Ce({
993
1043
  mintToken: this.mintToken,
994
1044
  onLevel: (l) => {
995
1045
  this.levelRef.current = l;
996
1046
  },
997
1047
  onState: (l) => {
998
- _ === this.session && (l === "connecting" && this.state.set({ status: "connecting", error: null }), l === "listening" && this.state.set({ status: "listening", error: null }), l === "stopped" && this.teardown());
1048
+ i === this.session && (l === "connecting" && this.state.set({ status: "connecting", error: null }), l === "listening" && this.state.set({ status: "listening", error: null }), l === "stopped" && this.teardown());
999
1049
  },
1000
1050
  onError: (l) => {
1001
- _ === this.session && (this.mintCache.clear(), this.teardown({ error: l, executeFinalCommand: !1 }));
1051
+ i === this.session && (this.mintCache.clear(), this.teardown({ error: l, executeFinalCommand: !1 }));
1002
1052
  },
1003
1053
  onDelta: (l) => {
1004
- if (_ !== this.session || !this.target) return;
1054
+ if (i !== this.session || !this.target) return;
1005
1055
  if (!this.isConsistent()) {
1006
1056
  this.teardown();
1007
1057
  return;
1008
1058
  }
1009
1059
  this.raw += l;
1010
- const a = this.ingest();
1011
- if (a === "stop") {
1060
+ const o = this.ingest();
1061
+ if (o === "stop") {
1012
1062
  this.teardown();
1013
1063
  return;
1014
1064
  }
1015
- if (a === "send") {
1065
+ if (o === "send") {
1016
1066
  this.teardown({ send: !0 });
1017
1067
  return;
1018
1068
  }
@@ -1020,32 +1070,32 @@ class qe {
1020
1070
  this.raw,
1021
1071
  this.language
1022
1072
  ) && (this.silenceTimer = setTimeout(() => {
1023
- if (_ !== this.session) return;
1073
+ if (i !== this.session) return;
1024
1074
  this.raw = `${this.raw}.`;
1025
- const n = this.ingest();
1026
- n === "stop" ? this.teardown() : n === "send" && this.teardown({ send: !0 });
1027
- }, xe));
1075
+ const t = this.ingest();
1076
+ t === "stop" ? this.teardown() : t === "send" && this.teardown({ send: !0 });
1077
+ }, qe));
1028
1078
  }
1029
1079
  });
1030
- this.session = _, this.state.set({ status: "connecting", error: null }), this.dripTimer = setInterval(() => {
1080
+ this.session = i, this.state.set({ status: "connecting", error: null }), this.dripTimer = setInterval(() => {
1031
1081
  if (this.target && this.processed !== this.displayed) {
1032
1082
  if (!this.isConsistent()) {
1033
1083
  this.teardown();
1034
1084
  return;
1035
1085
  }
1036
1086
  this.applyDisplayed(
1037
- F.nextDripText({
1087
+ O.nextDripText({
1038
1088
  displayed: this.displayed,
1039
1089
  processed: this.processed
1040
1090
  })
1041
1091
  );
1042
1092
  }
1043
- }, ge), _.start();
1093
+ }, be), i.start();
1044
1094
  }, this.stop = () => {
1045
1095
  this.session && this.teardown();
1046
1096
  }, this.mintToken = async () => this.mintCache.resolve(
1047
1097
  () => this.api.createDictationSession({ language: this.language })
1048
- ), this.api = e, this.config = t;
1098
+ ), this.api = e, this.config = a;
1049
1099
  }
1050
1100
  /** Applied text = prefix + dictated. A mismatch means the visitor edited. */
1051
1101
  isConsistent() {
@@ -1057,28 +1107,28 @@ class qe {
1057
1107
  /** Process the transcript and apply the outcome. Shared by the delta path,
1058
1108
  * the silence timer, and (with `final`) teardown. Returns the control. */
1059
1109
  ingest(e) {
1060
- const t = C.process(this.raw, {
1110
+ const a = C.process(this.raw, {
1061
1111
  language: this.language,
1062
1112
  final: e == null ? void 0 : e.final
1063
1113
  });
1064
- return this.processed = t.text, t.text.startsWith(this.displayed) || this.applyDisplayed(t.text), t.control;
1114
+ return this.processed = a.text, a.text.startsWith(this.displayed) || this.applyDisplayed(a.text), a.control;
1065
1115
  }
1066
1116
  stopSilenceTimer() {
1067
1117
  this.silenceTimer && clearTimeout(this.silenceTimer), this.silenceTimer = null;
1068
1118
  }
1069
1119
  teardown(e) {
1070
1120
  var l;
1071
- const t = this.session, o = this.target;
1121
+ const a = this.session, n = this.target;
1072
1122
  this.dripTimer && clearInterval(this.dripTimer), this.dripTimer = null, this.stopSilenceTimer();
1073
- let _ = (e == null ? void 0 : e.send) ?? !1;
1074
- if (o && this.isConsistent()) {
1075
- const a = this.ingest({ final: !0 });
1076
- (e == null ? void 0 : e.executeFinalCommand) !== !1 && a === "send" && (_ = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1123
+ let i = (e == null ? void 0 : e.send) ?? !1;
1124
+ if (n && this.isConsistent()) {
1125
+ const o = this.ingest({ final: !0 });
1126
+ (e == null ? void 0 : e.executeFinalCommand) !== !1 && o === "send" && (i = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1077
1127
  }
1078
- this.session = null, this.target = null, t == null || t.stop(), this.levelRef.current = 0, this.state.set({ status: "idle", error: (e == null ? void 0 : e.error) ?? null }), _ && ((l = o == null ? void 0 : o.onSend) == null || l.call(o));
1128
+ this.session = null, this.target = null, a == null || a.stop(), this.levelRef.current = 0, this.state.set({ status: "idle", error: (e == null ? void 0 : e.error) ?? null }), i && ((l = n == null ? void 0 : n.onSend) == null || l.call(n));
1079
1129
  }
1080
1130
  }
1081
- const Ee = {
1131
+ const Ae = {
1082
1132
  write_a_message_placeholder: "اكتب رسالة...",
1083
1133
  your_issue_has_been_resolved: "تم حل مشكلتك!",
1084
1134
  new_conversation: "محادثة جديدة",
@@ -1102,7 +1152,19 @@ const Ee = {
1102
1152
  companion_layout_floating: "عائم",
1103
1153
  companion_layout_sidebar: "الشريط الجانبي",
1104
1154
  companion_layout_fullscreen: "ملء الشاشة",
1155
+ companion_close_chat: "إغلاق {title}",
1105
1156
  companion_close: "إغلاق",
1157
+ companion_switch_chat: "تبديل المحادثة",
1158
+ companion_viewing: "تعرض الآن",
1159
+ companion_working: "قيد العمل",
1160
+ companion_open: "مفتوحة",
1161
+ companion_closed: "مغلقة",
1162
+ companion_draft: "مسودة",
1163
+ companion_chats: "الجلسات النشطة",
1164
+ companion_chat_number: "محادثة {count}",
1165
+ companion_active_chats: "{count} جلسات نشطة",
1166
+ companion_other_sessions: "الجلسات المفتوحة الأخرى: {count}",
1167
+ companion_working_chats: "{count} قيد العمل",
1106
1168
  companion_history: "سجل المحادثات",
1107
1169
  companion_expand_chat: "توسيع المحادثة",
1108
1170
  companion_sidebar_dock_label: "الإرساء",
@@ -1166,7 +1228,7 @@ const Ee = {
1166
1228
  questions_send: "إرسال",
1167
1229
  questions_type_answer: "سأكتبها بنفسي",
1168
1230
  questions_answer_placeholder: "اكتب إجابتك…"
1169
- }, Pe = {
1231
+ }, Te = {
1170
1232
  write_a_message_placeholder: "একটি বার্তা লিখুন...",
1171
1233
  your_issue_has_been_resolved: "আপনার সমস্যা সমাধান হয়েছে!",
1172
1234
  new_conversation: "নতুন কথোপকথন",
@@ -1254,7 +1316,7 @@ const Ee = {
1254
1316
  questions_send: "পাঠান",
1255
1317
  questions_type_answer: "আমি লিখে দিচ্ছি",
1256
1318
  questions_answer_placeholder: "আপনার উত্তর লিখুন…"
1257
- }, Te = {
1319
+ }, Me = {
1258
1320
  write_a_message_placeholder: "Напишете съобщение...",
1259
1321
  your_issue_has_been_resolved: "Вашият проблем е разрешен!",
1260
1322
  new_conversation: "Нов разговор",
@@ -1342,7 +1404,7 @@ const Ee = {
1342
1404
  questions_send: "Изпрати",
1343
1405
  questions_type_answer: "Ще напиша сам",
1344
1406
  questions_answer_placeholder: "Напишете отговора си…"
1345
- }, Ae = {
1407
+ }, Ie = {
1346
1408
  write_a_message_placeholder: "Napište zprávu...",
1347
1409
  your_issue_has_been_resolved: "Váš problém byl vyřešen!",
1348
1410
  new_conversation: "Nová konverzace",
@@ -1430,7 +1492,7 @@ const Ee = {
1430
1492
  questions_send: "Odeslat",
1431
1493
  questions_type_answer: "Napíšu to sám",
1432
1494
  questions_answer_placeholder: "Napište svou odpověď…"
1433
- }, Me = {
1495
+ }, De = {
1434
1496
  write_a_message_placeholder: "Skriv en besked...",
1435
1497
  your_issue_has_been_resolved: "Dit problem er løst!",
1436
1498
  new_conversation: "Ny samtale",
@@ -1518,7 +1580,7 @@ const Ee = {
1518
1580
  questions_send: "Send",
1519
1581
  questions_type_answer: "Jeg skriver det selv",
1520
1582
  questions_answer_placeholder: "Skriv dit svar…"
1521
- }, Ie = {
1583
+ }, Ne = {
1522
1584
  write_a_message_placeholder: "Γράψτε ένα μήνυμα...",
1523
1585
  your_issue_has_been_resolved: "Το πρόβλημά σας επιλύθηκε!",
1524
1586
  new_conversation: "Νέα συνομιλία",
@@ -1606,7 +1668,7 @@ const Ee = {
1606
1668
  questions_send: "Αποστολή",
1607
1669
  questions_type_answer: "Θα το γράψω",
1608
1670
  questions_answer_placeholder: "Γράψτε την απάντησή σας…"
1609
- }, De = {
1671
+ }, Re = {
1610
1672
  write_a_message_placeholder: "Nachricht schreiben...",
1611
1673
  your_issue_has_been_resolved: "Ihr Problem wurde gelöst!",
1612
1674
  new_conversation: "Neue Konversation",
@@ -1694,7 +1756,7 @@ const Ee = {
1694
1756
  questions_send: "Senden",
1695
1757
  questions_type_answer: "Ich schreibe es selbst",
1696
1758
  questions_answer_placeholder: "Antwort eingeben…"
1697
- }, Ne = {
1759
+ }, G = {
1698
1760
  write_a_message_placeholder: "Write a message...",
1699
1761
  your_issue_has_been_resolved: "Your issue has been resolved!",
1700
1762
  new_conversation: "New conversation",
@@ -1718,7 +1780,19 @@ const Ee = {
1718
1780
  companion_layout_floating: "Floating",
1719
1781
  companion_layout_sidebar: "Sidebar",
1720
1782
  companion_layout_fullscreen: "Fullscreen",
1783
+ companion_close_chat: "Close {title}",
1721
1784
  companion_close: "Close",
1785
+ companion_switch_chat: "Switch chat",
1786
+ companion_viewing: "Viewing",
1787
+ companion_working: "Working",
1788
+ companion_open: "Open",
1789
+ companion_closed: "Closed",
1790
+ companion_draft: "Draft",
1791
+ companion_chats: "Active sessions",
1792
+ companion_chat_number: "Chat {count}",
1793
+ companion_active_chats: "{count} active sessions",
1794
+ companion_other_sessions: "Other open sessions: {count}",
1795
+ companion_working_chats: "{count} working",
1722
1796
  companion_history: "Conversation history",
1723
1797
  companion_expand_chat: "Expand chat",
1724
1798
  companion_sidebar_dock_label: "Dock",
@@ -1782,7 +1856,7 @@ const Ee = {
1782
1856
  questions_send: "Send",
1783
1857
  questions_type_answer: "I'll type it",
1784
1858
  questions_answer_placeholder: "Type your answer…"
1785
- }, Re = {
1859
+ }, Ke = {
1786
1860
  write_a_message_placeholder: "Escribe un mensaje...",
1787
1861
  your_issue_has_been_resolved: "¡Tu problema fue resuelto!",
1788
1862
  new_conversation: "Nueva conversación",
@@ -1870,7 +1944,7 @@ const Ee = {
1870
1944
  questions_send: "Enviar",
1871
1945
  questions_type_answer: "Lo escribo yo",
1872
1946
  questions_answer_placeholder: "Escribe tu respuesta…"
1873
- }, Ke = {
1947
+ }, Le = {
1874
1948
  write_a_message_placeholder: "Magsulat ng mensahe...",
1875
1949
  your_issue_has_been_resolved: "Nalutas na ang iyong isyu!",
1876
1950
  new_conversation: "Bagong usapan",
@@ -1958,7 +2032,7 @@ const Ee = {
1958
2032
  questions_send: "Ipadala",
1959
2033
  questions_type_answer: "Ako na ang magta-type",
1960
2034
  questions_answer_placeholder: "I-type ang iyong sagot…"
1961
- }, Le = {
2035
+ }, Fe = {
1962
2036
  write_a_message_placeholder: "Kirjoita viesti...",
1963
2037
  your_issue_has_been_resolved: "Ongelmasi on ratkaistu!",
1964
2038
  new_conversation: "Uusi keskustelu",
@@ -2046,7 +2120,7 @@ const Ee = {
2046
2120
  questions_send: "Lähetä",
2047
2121
  questions_type_answer: "Kirjoitan itse",
2048
2122
  questions_answer_placeholder: "Kirjoita vastauksesi…"
2049
- }, Fe = {
2123
+ }, Oe = {
2050
2124
  write_a_message_placeholder: "Écrivez un message...",
2051
2125
  your_issue_has_been_resolved: "Votre problème a été résolu !",
2052
2126
  new_conversation: "Nouvelle conversation",
@@ -2134,7 +2208,7 @@ const Ee = {
2134
2208
  questions_send: "Envoyer",
2135
2209
  questions_type_answer: "Je préfère écrire",
2136
2210
  questions_answer_placeholder: "Écrivez votre réponse…"
2137
- }, Oe = {
2211
+ }, Ue = {
2138
2212
  write_a_message_placeholder: "एक संदेश लिखें...",
2139
2213
  your_issue_has_been_resolved: "आपकी समस्या हल हो गई है!",
2140
2214
  new_conversation: "नई बातचीत",
@@ -2222,7 +2296,7 @@ const Ee = {
2222
2296
  questions_send: "भेजें",
2223
2297
  questions_type_answer: "मैं खुद लिखूंगा",
2224
2298
  questions_answer_placeholder: "अपना उत्तर लिखें…"
2225
- }, Ue = {
2299
+ }, Be = {
2226
2300
  write_a_message_placeholder: "Scrivi un messaggio...",
2227
2301
  your_issue_has_been_resolved: "Il tuo problema è stato risolto!",
2228
2302
  new_conversation: "Nuova conversazione",
@@ -2310,7 +2384,7 @@ const Ee = {
2310
2384
  questions_send: "Invia",
2311
2385
  questions_type_answer: "Lo scrivo io",
2312
2386
  questions_answer_placeholder: "Scrivi la tua risposta…"
2313
- }, Be = {
2387
+ }, Ve = {
2314
2388
  write_a_message_placeholder: "メッセージを入力...",
2315
2389
  your_issue_has_been_resolved: "問題が解決しました!",
2316
2390
  new_conversation: "新しい会話",
@@ -2398,7 +2472,7 @@ const Ee = {
2398
2472
  questions_send: "送信",
2399
2473
  questions_type_answer: "自分で入力する",
2400
2474
  questions_answer_placeholder: "回答を入力してください…"
2401
- }, Ve = {
2475
+ }, He = {
2402
2476
  write_a_message_placeholder: "메시지를 입력하세요...",
2403
2477
  your_issue_has_been_resolved: "문제가 해결되었습니다!",
2404
2478
  new_conversation: "새 대화",
@@ -2486,7 +2560,7 @@ const Ee = {
2486
2560
  questions_send: "보내기",
2487
2561
  questions_type_answer: "직접 입력할게요",
2488
2562
  questions_answer_placeholder: "답변을 입력하세요…"
2489
- }, He = {
2563
+ }, Ge = {
2490
2564
  write_a_message_placeholder: "Schrijf een bericht...",
2491
2565
  your_issue_has_been_resolved: "Uw probleem is opgelost!",
2492
2566
  new_conversation: "Nieuw gesprek",
@@ -2574,7 +2648,7 @@ const Ee = {
2574
2648
  questions_send: "Verzenden",
2575
2649
  questions_type_answer: "Ik typ het zelf",
2576
2650
  questions_answer_placeholder: "Typ je antwoord…"
2577
- }, Ge = {
2651
+ }, We = {
2578
2652
  write_a_message_placeholder: "Skriv en melding...",
2579
2653
  your_issue_has_been_resolved: "Problemet ditt er løst!",
2580
2654
  new_conversation: "Ny samtale",
@@ -2662,7 +2736,7 @@ const Ee = {
2662
2736
  questions_send: "Send",
2663
2737
  questions_type_answer: "Jeg skriver det selv",
2664
2738
  questions_answer_placeholder: "Skriv svaret ditt…"
2665
- }, We = {
2739
+ }, $e = {
2666
2740
  write_a_message_placeholder: "Napisz wiadomość...",
2667
2741
  your_issue_has_been_resolved: "Twój problem został rozwiązany!",
2668
2742
  new_conversation: "Nowa rozmowa",
@@ -2750,7 +2824,7 @@ const Ee = {
2750
2824
  questions_send: "Wyślij",
2751
2825
  questions_type_answer: "Napiszę sam",
2752
2826
  questions_answer_placeholder: "Wpisz swoją odpowiedź…"
2753
- }, $e = {
2827
+ }, Ze = {
2754
2828
  write_a_message_placeholder: "Escreva uma mensagem...",
2755
2829
  your_issue_has_been_resolved: "Seu problema foi resolvido!",
2756
2830
  new_conversation: "Nova conversa",
@@ -2838,7 +2912,7 @@ const Ee = {
2838
2912
  questions_send: "Enviar",
2839
2913
  questions_type_answer: "Prefiro escrever",
2840
2914
  questions_answer_placeholder: "Escreva a sua resposta…"
2841
- }, Ze = {
2915
+ }, Je = {
2842
2916
  write_a_message_placeholder: "Scrie un mesaj...",
2843
2917
  your_issue_has_been_resolved: "Problema ta a fost rezolvată!",
2844
2918
  new_conversation: "Conversație nouă",
@@ -2926,7 +3000,7 @@ const Ee = {
2926
3000
  questions_send: "Trimite",
2927
3001
  questions_type_answer: "Scriu eu",
2928
3002
  questions_answer_placeholder: "Scrieți răspunsul dvs.…"
2929
- }, Je = {
3003
+ }, Ye = {
2930
3004
  write_a_message_placeholder: "Skriv ett meddelande...",
2931
3005
  your_issue_has_been_resolved: "Ditt problem har lösts!",
2932
3006
  new_conversation: "Ny konversation",
@@ -3014,7 +3088,7 @@ const Ee = {
3014
3088
  questions_send: "Skicka",
3015
3089
  questions_type_answer: "Jag skriver själv",
3016
3090
  questions_answer_placeholder: "Skriv ditt svar…"
3017
- }, Ye = {
3091
+ }, Qe = {
3018
3092
  write_a_message_placeholder: "Напишите сообщение...",
3019
3093
  your_issue_has_been_resolved: "Ваша проблема решена!",
3020
3094
  new_conversation: "Новый разговор",
@@ -3102,7 +3176,7 @@ const Ee = {
3102
3176
  questions_send: "Отправить",
3103
3177
  questions_type_answer: "Напишу сам",
3104
3178
  questions_answer_placeholder: "Напишите ваш ответ…"
3105
- }, Qe = {
3179
+ }, Xe = {
3106
3180
  write_a_message_placeholder: "เขียนข้อความ...",
3107
3181
  your_issue_has_been_resolved: "ปัญหาของคุณได้รับการแก้ไขแล้ว!",
3108
3182
  new_conversation: "การสนทนาใหม่",
@@ -3190,7 +3264,7 @@ const Ee = {
3190
3264
  questions_send: "ส่ง",
3191
3265
  questions_type_answer: "ขอพิมพ์เอง",
3192
3266
  questions_answer_placeholder: "พิมพ์คำตอบของคุณ…"
3193
- }, Xe = {
3267
+ }, ea = {
3194
3268
  write_a_message_placeholder: "Bir mesaj yazın...",
3195
3269
  your_issue_has_been_resolved: "Sorununuz çözüldü!",
3196
3270
  new_conversation: "Yeni konuşma",
@@ -3278,7 +3352,7 @@ const Ee = {
3278
3352
  questions_send: "Gönder",
3279
3353
  questions_type_answer: "Kendim yazayım",
3280
3354
  questions_answer_placeholder: "Yanıtınızı yazın…"
3281
- }, ea = {
3355
+ }, aa = {
3282
3356
  write_a_message_placeholder: "پیغام لکھیں...",
3283
3357
  your_issue_has_been_resolved: "آپ کا مسئلہ حل ہو گیا ہے!",
3284
3358
  new_conversation: "نئی گفتگو",
@@ -3366,7 +3440,7 @@ const Ee = {
3366
3440
  questions_send: "بھیجیں",
3367
3441
  questions_type_answer: "میں خود لکھوں گا",
3368
3442
  questions_answer_placeholder: "اپنا جواب لکھیں…"
3369
- }, aa = {
3443
+ }, ta = {
3370
3444
  write_a_message_placeholder: "Viết tin nhắn...",
3371
3445
  your_issue_has_been_resolved: "Vấn đề của bạn đã được giải quyết!",
3372
3446
  new_conversation: "Cuộc trò chuyện mới",
@@ -3454,7 +3528,7 @@ const Ee = {
3454
3528
  questions_send: "Gửi",
3455
3529
  questions_type_answer: "Tôi sẽ tự nhập",
3456
3530
  questions_answer_placeholder: "Nhập câu trả lời của bạn…"
3457
- }, ta = {
3531
+ }, sa = {
3458
3532
  write_a_message_placeholder: "写一条消息...",
3459
3533
  your_issue_has_been_resolved: "您的问题已解决!",
3460
3534
  new_conversation: "新对话",
@@ -3542,7 +3616,7 @@ const Ee = {
3542
3616
  questions_send: "发送",
3543
3617
  questions_type_answer: "我自己输入",
3544
3618
  questions_answer_placeholder: "输入你的回答…"
3545
- }, sa = {
3619
+ }, na = {
3546
3620
  write_a_message_placeholder: "Napišite poruku...",
3547
3621
  your_issue_has_been_resolved: "Vaš problem je riješen!",
3548
3622
  new_conversation: "Novi razgovor",
@@ -3630,7 +3704,7 @@ const Ee = {
3630
3704
  questions_send: "Pošalji",
3631
3705
  questions_type_answer: "Napisat ću sam",
3632
3706
  questions_answer_placeholder: "Napišite svoj odgovor…"
3633
- }, na = {
3707
+ }, oa = {
3634
3708
  write_a_message_placeholder: "Kirjuta sõnum...",
3635
3709
  your_issue_has_been_resolved: "Teie probleem on lahendatud!",
3636
3710
  new_conversation: "Uus vestlus",
@@ -3718,7 +3792,7 @@ const Ee = {
3718
3792
  questions_send: "Saada",
3719
3793
  questions_type_answer: "Kirjutan ise",
3720
3794
  questions_answer_placeholder: "Kirjutage oma vastus…"
3721
- }, oa = {
3795
+ }, ia = {
3722
3796
  write_a_message_placeholder: "Írjon üzenetet...",
3723
3797
  your_issue_has_been_resolved: "A problémája megoldódott!",
3724
3798
  new_conversation: "Új beszélgetés",
@@ -3806,7 +3880,7 @@ const Ee = {
3806
3880
  questions_send: "Küldés",
3807
3881
  questions_type_answer: "Inkább leírom",
3808
3882
  questions_answer_placeholder: "Írja le a válaszát…"
3809
- }, ia = {
3883
+ }, ra = {
3810
3884
  write_a_message_placeholder: "Skrifaðu skilaboð...",
3811
3885
  your_issue_has_been_resolved: "Málið þitt hefur verið leyst!",
3812
3886
  new_conversation: "Nýtt samtal",
@@ -3894,7 +3968,7 @@ const Ee = {
3894
3968
  questions_send: "Senda",
3895
3969
  questions_type_answer: "Ég skrifa það",
3896
3970
  questions_answer_placeholder: "Skrifaðu svarið þitt…"
3897
- }, ra = {
3971
+ }, _a = {
3898
3972
  write_a_message_placeholder: "Rakstiet ziņojumu...",
3899
3973
  your_issue_has_been_resolved: "Jūsu problēma ir atrisināta!",
3900
3974
  new_conversation: "Jauna saruna",
@@ -3982,7 +4056,7 @@ const Ee = {
3982
4056
  questions_send: "Sūtīt",
3983
4057
  questions_type_answer: "Rakstīšu pats",
3984
4058
  questions_answer_placeholder: "Ierakstiet savu atbildi…"
3985
- }, _a = {
4059
+ }, la = {
3986
4060
  write_a_message_placeholder: "Parašykite žinutę...",
3987
4061
  your_issue_has_been_resolved: "Jūsų problema išspręsta!",
3988
4062
  new_conversation: "Naujas pokalbis",
@@ -4070,7 +4144,7 @@ const Ee = {
4070
4144
  questions_send: "Siųsti",
4071
4145
  questions_type_answer: "Parašysiu pats",
4072
4146
  questions_answer_placeholder: "Parašykite savo atsakymą…"
4073
- }, la = {
4147
+ }, ca = {
4074
4148
  write_a_message_placeholder: "Schreift eng Noriicht...",
4075
4149
  your_issue_has_been_resolved: "Äert Problem gouf geléist!",
4076
4150
  new_conversation: "Nei Konversatioun",
@@ -4158,7 +4232,7 @@ const Ee = {
4158
4232
  questions_send: "Schécken",
4159
4233
  questions_type_answer: "Ech schreiwen et selwer",
4160
4234
  questions_answer_placeholder: "Schreift Är Äntwert…"
4161
- }, ca = {
4235
+ }, pa = {
4162
4236
  write_a_message_placeholder: "Ikteb messaġġ...",
4163
4237
  your_issue_has_been_resolved: "Il-problema tiegħek ġiet riżolta!",
4164
4238
  new_conversation: "Konversazzjoni ġdida",
@@ -4246,7 +4320,7 @@ const Ee = {
4246
4320
  questions_send: "Ibgħat",
4247
4321
  questions_type_answer: "Nikteb jien",
4248
4322
  questions_answer_placeholder: "Ikteb it-tweġiba tiegħek…"
4249
- }, pa = {
4323
+ }, da = {
4250
4324
  write_a_message_placeholder: "Skriv en melding...",
4251
4325
  your_issue_has_been_resolved: "Saken din er løst!",
4252
4326
  new_conversation: "Ny samtale",
@@ -4334,7 +4408,7 @@ const Ee = {
4334
4408
  questions_send: "Send",
4335
4409
  questions_type_answer: "Jeg skriver det selv",
4336
4410
  questions_answer_placeholder: "Skriv svaret ditt…"
4337
- }, da = {
4411
+ }, ua = {
4338
4412
  write_a_message_placeholder: "Napíšte správu...",
4339
4413
  your_issue_has_been_resolved: "Váš problém bol vyriešený!",
4340
4414
  new_conversation: "Nová konverzácia",
@@ -4422,85 +4496,86 @@ const Ee = {
4422
4496
  questions_send: "Odoslať",
4423
4497
  questions_type_answer: "Napíšem to sám",
4424
4498
  questions_answer_placeholder: "Napíšte svoju odpoveď…"
4425
- }, G = {
4426
- ar: Ee,
4427
- bn: Pe,
4428
- bg: Te,
4429
- cs: Ae,
4430
- da: Me,
4431
- de: De,
4432
- el: Ie,
4433
- en: Ne,
4434
- es: Re,
4435
- et: na,
4436
- fi: Le,
4437
- fil: Ke,
4438
- fr: Fe,
4439
- hi: Oe,
4440
- hr: sa,
4441
- hu: oa,
4442
- is: ia,
4443
- it: Ue,
4444
- ja: Be,
4445
- ko: Ve,
4446
- lb: la,
4447
- lt: _a,
4448
- lv: ra,
4449
- mt: ca,
4450
- nb: pa,
4451
- nl: He,
4452
- no: Ge,
4453
- pl: We,
4454
- pt: $e,
4455
- ro: Ze,
4456
- ru: Ye,
4457
- sk: da,
4458
- sv: Je,
4459
- th: Qe,
4460
- tr: Xe,
4461
- ur: ea,
4462
- vi: aa,
4463
- "zh-cn": ta
4464
- }, ma = Object.keys(G);
4465
- function ua(i) {
4466
- return ma.includes(i);
4499
+ }, W = {
4500
+ ar: Ae,
4501
+ bn: Te,
4502
+ bg: Me,
4503
+ cs: Ie,
4504
+ da: De,
4505
+ de: Re,
4506
+ el: Ne,
4507
+ en: G,
4508
+ es: Ke,
4509
+ et: oa,
4510
+ fi: Fe,
4511
+ fil: Le,
4512
+ fr: Oe,
4513
+ hi: Ue,
4514
+ hr: na,
4515
+ hu: ia,
4516
+ is: ra,
4517
+ it: Be,
4518
+ ja: Ve,
4519
+ ko: He,
4520
+ lb: ca,
4521
+ lt: la,
4522
+ lv: _a,
4523
+ mt: pa,
4524
+ nb: da,
4525
+ nl: Ge,
4526
+ no: We,
4527
+ pl: $e,
4528
+ pt: Ze,
4529
+ ro: Je,
4530
+ ru: Qe,
4531
+ sk: ua,
4532
+ sv: Ye,
4533
+ th: Xe,
4534
+ tr: ea,
4535
+ ur: aa,
4536
+ vi: ta,
4537
+ "zh-cn": sa
4538
+ }, ma = Object.keys(W);
4539
+ function ha(_) {
4540
+ return ma.includes(_);
4467
4541
  }
4468
- const ha = /* @__PURE__ */ new Set(["ar", "ur"]);
4469
- function Ka(i) {
4470
- return ha.has(i);
4542
+ const ga = /* @__PURE__ */ new Set(["ar", "ur"]);
4543
+ function La(_) {
4544
+ return ga.has(_);
4471
4545
  }
4472
- function ga(i) {
4473
- return ua(i) ? i : "en";
4546
+ function ka(_) {
4547
+ return ha(_) ? _ : "en";
4474
4548
  }
4475
- function ka(i, e, t, o) {
4549
+ function ba(_, e, a, n) {
4476
4550
  var l;
4477
- const _ = ((l = t == null ? void 0 : t[e]) == null ? void 0 : l[i]) || G[e][i];
4478
- return o ? _.replace(
4551
+ const i = ((l = a == null ? void 0 : a[e]) == null ? void 0 : l[_]) || W[e][_] || G[_] || _;
4552
+ return n ? i.replace(
4479
4553
  /\{(\w+)\}/g,
4480
- (a, n) => n in o ? String(o[n]) : a
4481
- ) : _;
4554
+ (o, t) => t in n ? String(n[t]) : o
4555
+ ) : i;
4482
4556
  }
4483
- function ba(i, e, t) {
4484
- return ka(
4557
+ function fa(_, e, a) {
4558
+ return ba(
4485
4559
  e,
4486
- ga(i.language),
4487
- i.translationOverrides,
4488
- t
4560
+ ka(_.language),
4561
+ _.translationOverrides,
4562
+ a
4489
4563
  );
4490
4564
  }
4491
- class fa {
4565
+ class va {
4492
4566
  constructor({
4493
4567
  config: e,
4494
- api: t,
4495
- contactCtx: o,
4496
- storageCtx: _,
4497
- sessionsPollingIntervalSeconds: l
4568
+ api: a,
4569
+ contactCtx: n,
4570
+ storageCtx: i,
4571
+ sessionsPollingIntervalSeconds: l,
4572
+ sharedSessions: o
4498
4573
  }) {
4499
- this.sessionsRefresher = new V(), this.persistedSessionId = null, this.sessionState = new j({
4574
+ this.sessionsRefresher = new V(), this.persistedSessionId = null, this.sessionAbortController = new AbortController(), this.sessionState = new w({
4500
4575
  session: null,
4501
4576
  isCreatingSession: !1,
4502
4577
  isResolvingSession: !1
4503
- }), this.sessionsState = new j({
4578
+ }), this.sessionsState = new w({
4504
4579
  data: [],
4505
4580
  cursor: void 0,
4506
4581
  isLastPage: !1,
@@ -4510,14 +4585,25 @@ class fa {
4510
4585
  */
4511
4586
  isInitialFetchLoading: !0
4512
4587
  }), this.registerActiveSessionPersistence = () => {
4513
- const a = this.storageCtx;
4514
- a && this.sessionState.subscribe(({ session: n }) => {
4515
- const s = n != null && n.isOpened ? n.id : null;
4516
- if (s === this.persistedSessionId || !s && this.persistedSessionId === null) return;
4517
- this.persistedSessionId = s, (s ? a.setActiveSessionId(s) : a.clearActiveSessionId()).catch((c) => {
4518
- u.warn("failed to persist the active session", {
4519
- error: c instanceof Error ? c.message : String(c)
4520
- });
4588
+ this.storageCtx && (this.stopPersistingSession = this.sessionState.subscribe(
4589
+ this.persistSession
4590
+ ));
4591
+ }, this.restoreActiveSessionTracking = () => {
4592
+ var t;
4593
+ (t = this.stopPersistingSession) == null || t.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
4594
+ }, this.trackActiveSession = (t) => {
4595
+ var s;
4596
+ (s = this.stopPersistingSession) == null || s.call(this), this.stopPersistingSession = t.sessionState.subscribe(
4597
+ this.persistSession
4598
+ ), this.persistSession(t.sessionState.get());
4599
+ }, this.persistSession = ({ session: t }) => {
4600
+ const s = this.storageCtx;
4601
+ if (!s) return;
4602
+ const r = t != null && t.isOpened ? t.id : null;
4603
+ if (r === this.persistedSessionId || !r && this.persistedSessionId === null) return;
4604
+ this.persistedSessionId = r, (r ? s.setActiveSessionId(r) : s.clearActiveSessionId()).catch((p) => {
4605
+ m.warn("failed to persist the active session", {
4606
+ error: p instanceof Error ? p.message : String(p)
4521
4607
  });
4522
4608
  });
4523
4609
  }, this.getLastActiveSessionId = async () => {
@@ -4528,12 +4614,12 @@ class fa {
4528
4614
  return null;
4529
4615
  }
4530
4616
  }, this.reset = async () => {
4531
- this.sessionState.reset();
4617
+ this.sessionAbortController.abort(), this.sessionAbortController = new AbortController(), this.sessionState.reset();
4532
4618
  }, this.registerSessionsRefresherWrapper = () => {
4533
- var a;
4619
+ var t;
4534
4620
  // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
4535
- (a = this.contactCtx.state.get().contact) != null && a.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: n }) => {
4536
- n != null && n.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
4621
+ (t = this.contactCtx.state.get().contact) != null && t.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.contactCtx.state.subscribe(({ contact: s }) => {
4622
+ s != null && s.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
4537
4623
  });
4538
4624
  }, this.registerSessionsRefresher = () => {
4539
4625
  this.sessionsRefresher.startPolling(async () => {
@@ -4541,182 +4627,196 @@ class fa {
4541
4627
  }, this.sessionsPollingIntervalSeconds * 1e3);
4542
4628
  }, this.getParsedCustomData = () => Object.fromEntries(
4543
4629
  Object.entries(this.config.sessionCustomData || {}).map(
4544
- ([a, n]) => {
4545
- var s;
4546
- return typeof n == "string" ? [a, n] : typeof n == "boolean" ? [a, n] : typeof n == "number" ? [a, n] : [a, ((s = H(() => JSON.stringify(n))) == null ? void 0 : s.data) || ""];
4630
+ ([t, s]) => {
4631
+ var r;
4632
+ return typeof s == "string" ? [t, s] : typeof s == "boolean" ? [t, s] : typeof s == "number" ? [t, s] : [t, ((r = H(() => JSON.stringify(s))) == null ? void 0 : r.data) || ""];
4547
4633
  }
4548
4634
  )
4549
4635
  ), this.createSession = async () => {
4636
+ const { signal: t } = this.sessionAbortController;
4550
4637
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
4551
4638
  try {
4552
- const a = await this.requestSession();
4553
- if (a.session) return a.session;
4554
- if (a.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
4555
- const n = await this.requestSession();
4556
- return n.session ? n.session : (u.error("failed to create session", n.error), null);
4639
+ const s = await this.requestSession(t);
4640
+ if (t.aborted) return null;
4641
+ if (s.session) return s.session;
4642
+ if (s.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
4643
+ if (t.aborted) return null;
4644
+ const r = await this.requestSession(t);
4645
+ return t.aborted ? null : r.session ? r.session : (m.error("failed to create session", r.error), null);
4557
4646
  }
4558
- return u.error("failed to create session", a.error), null;
4559
- } catch (a) {
4560
- return u.error("failed to create session", a), null;
4647
+ return m.error("failed to create session", s.error), null;
4648
+ } catch (s) {
4649
+ return t.aborted || m.error("failed to create session", s), null;
4561
4650
  } finally {
4562
- this.sessionState.setPartial({ isCreatingSession: !1 });
4651
+ t.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
4563
4652
  }
4564
- }, this.requestSession = async () => {
4565
- var p, d, m;
4566
- const a = (p = this.contactCtx.state.get().contact) == null ? void 0 : p.externalId, n = {
4653
+ }, this.requestSession = async (t) => {
4654
+ var u, g, h;
4655
+ const s = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, r = {
4567
4656
  ...this.getParsedCustomData(),
4568
- ...a ? { external_id: a } : {}
4657
+ ...s ? { external_id: s } : {}
4569
4658
  }, {
4570
- data: s,
4571
- error: r,
4572
- response: c
4573
- } = await this.api.createSession({
4574
- customData: Object.keys(n).length > 0 ? n : void 0
4575
- });
4576
- if (!s) return { session: null, status: c == null ? void 0 : c.status, error: r };
4577
- this.sessionState.setPartial({ session: s });
4659
+ data: c,
4660
+ error: p,
4661
+ response: d
4662
+ } = await this.api.createSession(
4663
+ {
4664
+ customData: Object.keys(r).length > 0 ? r : void 0
4665
+ },
4666
+ t
4667
+ );
4668
+ if (t.aborted || !c)
4669
+ return { session: null, status: d == null ? void 0 : d.status, error: p };
4670
+ this.sessionState.setPartial({ session: c });
4578
4671
  try {
4579
- (m = (d = this.config.hooks) == null ? void 0 : d.onSessionCreated) == null || m.call(d, { session: s });
4580
- } catch (h) {
4581
- u.error("onSessionCreated hook failed", h);
4672
+ (h = (g = this.config.hooks) == null ? void 0 : g.onSessionCreated) == null || h.call(g, { session: c });
4673
+ } catch (v) {
4674
+ m.error("onSessionCreated hook failed", v);
4582
4675
  }
4583
- return { session: s, status: c.status, error: void 0 };
4676
+ return { session: c, status: d.status, error: void 0 };
4584
4677
  }, this.loadMoreSessions = async () => {
4585
4678
  if (this.sessionsState.get().isLastPage) return;
4586
- const { data: a } = await this.getSessions({
4679
+ const { data: t } = await this.getSessions({
4587
4680
  cursor: this.sessionsState.get().cursor
4588
4681
  });
4589
- if (a) {
4590
- const s = [...this.sessionsState.get().data, ...a.items].filter(
4591
- (r, c, p) => c === p.findIndex((d) => r.id === d.id)
4682
+ if (t) {
4683
+ const r = [...this.sessionsState.get().data, ...t.items].filter(
4684
+ (c, p, d) => p === d.findIndex((u) => c.id === u.id)
4592
4685
  );
4593
4686
  this.sessionsState.setPartial({
4594
- data: s,
4595
- cursor: a.next || void 0,
4596
- isLastPage: a.next === null
4687
+ data: r,
4688
+ cursor: t.next || void 0,
4689
+ isLastPage: t.next === null
4597
4690
  });
4598
4691
  }
4599
- }, this.getSessions = async ({ cursor: a }) => {
4600
- var s, r;
4601
- if (!((s = this.contactCtx.state.get().contact) != null && s.token)) return { data: null };
4602
- const n = (r = this.contactCtx.state.get().contact) == null ? void 0 : r.externalId;
4692
+ }, this.getSessions = async ({ cursor: t }) => {
4693
+ var r, c;
4694
+ if (!((r = this.contactCtx.state.get().contact) != null && r.token)) return { data: null };
4695
+ const s = (c = this.contactCtx.state.get().contact) == null ? void 0 : c.externalId;
4603
4696
  return await this.api.getSessions({
4604
- cursor: a,
4605
- filters: n ? {
4606
- external_id: n
4697
+ cursor: t,
4698
+ filters: s ? {
4699
+ external_id: s
4607
4700
  } : {}
4608
4701
  });
4609
- }, this.setSessions = (a) => {
4610
- const n = [...a, ...this.sessionsState.get().data].filter(
4611
- (s, r, c) => r === c.findIndex((p) => s.id === p.id)
4702
+ }, this.setSessions = (t) => {
4703
+ const s = [...t, ...this.sessionsState.get().data].filter(
4704
+ (r, c, p) => c === p.findIndex((d) => r.id === d.id)
4612
4705
  );
4613
- this.sessionsState.setPartial({ data: n });
4706
+ this.sessionsState.setPartial({ data: s });
4614
4707
  }, this.refreshSessions = async () => {
4615
- const { data: a } = await this.getSessions({ cursor: void 0 });
4616
- a && this.setSessions(a.items);
4708
+ const { data: t } = await this.getSessions({ cursor: void 0 });
4709
+ t && this.setSessions(t.items);
4617
4710
  }, this.resolveSession = async () => {
4618
- const a = this.sessionState.get().session;
4619
- if (!a || !a.isOpened)
4711
+ const t = this.sessionState.get().session;
4712
+ if (!t || !t.isOpened)
4620
4713
  return { success: !1, error: "Session is not opened" };
4621
4714
  this.sessionState.setPartial({ isResolvingSession: !0 });
4622
- const { data: n, error: s } = await this.api.resolveSession({
4623
- session_id: a.id
4715
+ const { signal: s } = this.sessionAbortController, r = await this.api.resolveSession({ session_id: t.id }, s).catch((d) => {
4716
+ if (s.aborted) return null;
4717
+ throw d;
4624
4718
  });
4625
- return n ? (this.sessionState.setPartial({ session: n, isResolvingSession: !1 }), { success: !0, data: n }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: s });
4626
- }, this.createStateCheckpoint = async (a) => {
4627
- var r;
4628
- const n = (r = this.sessionState.get().session) == null ? void 0 : r.id;
4629
- if (!n) return;
4630
- const { data: s } = await this.api.createStateCheckpoint({
4631
- session_id: n,
4632
- payload: a
4719
+ if (!r || s.aborted)
4720
+ return { success: !1, error: "Session was reset" };
4721
+ const { data: c, error: p } = r;
4722
+ return c ? (this.sessionState.setPartial({ session: c, isResolvingSession: !1 }), { success: !0, data: c }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: p });
4723
+ }, this.createStateCheckpoint = async (t) => {
4724
+ var c;
4725
+ const s = (c = this.sessionState.get().session) == null ? void 0 : c.id;
4726
+ if (!s) return;
4727
+ const { data: r } = await this.api.createStateCheckpoint({
4728
+ session_id: s,
4729
+ payload: t
4633
4730
  });
4634
- return s != null && s.success ? { success: !0 } : { success: !1 };
4635
- }, this.config = e, this.api = t, this.contactCtx = o, this.storageCtx = _, this.sessionsPollingIntervalSeconds = l, this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
4731
+ return r != null && r.success ? { success: !0 } : { success: !1 };
4732
+ }, this.config = e, this.api = a, this.contactCtx = n, this.storageCtx = i, this.sessionsPollingIntervalSeconds = l, o ? this.sessionsState = o : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
4636
4733
  }
4637
4734
  }
4638
- const va = (i, e, { sendsPageContext: t }) => {
4639
- const o = ja(i), _ = t && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(ya) } : void 0, l = t && (e.clientContext || _) ? { ...o, ...e.clientContext, ..._ } : o;
4735
+ const ya = (_, e, { sendsPageContext: a }) => {
4736
+ const n = Sa(_), i = a && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(wa) } : void 0, l = a && (e.clientContext || i) ? { ...n, ...e.clientContext, ...i } : n;
4640
4737
  return {
4641
- clientContext: e.withPageEntity === !1 && l && "entity" in l ? wa(l, "entity") : l,
4738
+ clientContext: e.withPageEntity === !1 && l && "entity" in l ? ja(l, "entity") : l,
4642
4739
  custom_data: {
4643
- ...i.messageCustomData || {},
4740
+ ..._.messageCustomData || {},
4644
4741
  ...e.customData || {}
4645
4742
  }
4646
4743
  };
4647
- }, ya = ({ type: i, id: e, title: t, meta: o }) => ({
4648
- type: i,
4744
+ }, wa = ({ type: _, id: e, title: a, meta: n }) => ({
4745
+ type: _,
4649
4746
  id: e,
4650
- title: t,
4651
- ...o ? { meta: o } : {}
4652
- }), wa = (i, e) => {
4653
- const { [e]: t, ...o } = i;
4654
- return Object.keys(o).length > 0 ? o : void 0;
4655
- }, ja = (i) => {
4656
- if (typeof i.context != "function") return i.context;
4747
+ title: a,
4748
+ ...n ? { meta: n } : {}
4749
+ }), ja = (_, e) => {
4750
+ const { [e]: a, ...n } = _;
4751
+ return Object.keys(n).length > 0 ? n : void 0;
4752
+ }, Sa = (_) => {
4753
+ if (typeof _.context != "function") return _.context;
4657
4754
  try {
4658
- return i.context();
4755
+ return _.context();
4659
4756
  } catch (e) {
4660
- u.error("context getter threw; sending without context", e);
4757
+ m.error("context getter threw; sending without context", e);
4661
4758
  return;
4662
4759
  }
4663
- }, Sa = (i) => {
4664
- const e = i.features;
4760
+ }, xa = (_) => {
4761
+ const e = _.features;
4665
4762
  if (!e) return;
4666
- const t = {};
4667
- return e.preamble !== void 0 && (t.preamble = e.preamble), e.inlineUi !== void 0 && (t.inline_ui = e.inlineUi), e.pageContext !== void 0 && (t.page_context = e.pageContext), e.clientTools !== void 0 && (t.client_tools = e.clientTools), Object.keys(t).length > 0 ? t : void 0;
4763
+ const a = {};
4764
+ return e.preamble !== void 0 && (a.preamble = e.preamble), e.inlineUi !== void 0 && (a.inline_ui = e.inlineUi), e.pageContext !== void 0 && (a.page_context = e.pageContext), e.clientTools !== void 0 && (a.client_tools = e.clientTools), Object.keys(a).length > 0 ? a : void 0;
4668
4765
  }, za = ({
4669
- config: i,
4766
+ config: _,
4670
4767
  input: e,
4671
- uuid: t,
4672
- sessionId: o,
4673
- content: _,
4768
+ uuid: a,
4769
+ sessionId: n,
4770
+ content: i,
4674
4771
  initialMessages: l,
4675
- sendsPageContext: a
4772
+ sendsPageContext: o
4676
4773
  }) => {
4677
- var n;
4774
+ var t;
4678
4775
  return {
4679
- uuid: t,
4680
- bot_token: i.token,
4681
- headers: i.headers,
4682
- query_params: i.queryParams,
4683
- body_properties: i.bodyProperties,
4684
- session_id: o,
4685
- content: _,
4776
+ uuid: a,
4777
+ bot_token: _.token,
4778
+ headers: _.headers,
4779
+ query_params: _.queryParams,
4780
+ body_properties: _.bodyProperties,
4781
+ session_id: n,
4782
+ content: i,
4686
4783
  attachments: e.attachments,
4687
- ...va(i, e, { sendsPageContext: a }),
4688
- language: i.language,
4689
- features: Sa(i),
4690
- capabilities: ((n = i.capabilities) == null ? void 0 : n.structuredQuestions) === void 0 ? void 0 : { structured_questions: i.capabilities.structuredQuestions },
4784
+ ...ya(_, e, { sendsPageContext: o }),
4785
+ language: _.language,
4786
+ features: xa(_),
4787
+ capabilities: ((t = _.capabilities) == null ? void 0 : t.structuredQuestions) === void 0 ? void 0 : { structured_questions: _.capabilities.structuredQuestions },
4691
4788
  exit_mode_prompt: e.exitModePrompt,
4692
4789
  initial_messages: l.length > 0 ? l.map((s) => ({ uuid: s.id, content: s.data.message })) : void 0
4693
4790
  };
4694
- }, z = class z {
4791
+ }, x = class x {
4695
4792
  constructor({
4696
4793
  config: e,
4697
- api: t,
4698
- sessionCtx: o,
4699
- contactCtx: _,
4794
+ api: a,
4795
+ sessionCtx: n,
4796
+ contactCtx: i,
4700
4797
  streaming: l,
4701
- sendsPageContext: a,
4702
- getClientCapabilities: n
4798
+ sendsPageContext: o,
4799
+ getClientCapabilities: t
4703
4800
  }) {
4704
- this.state = new j({
4801
+ this.state = new w({
4705
4802
  messages: [],
4706
4803
  isSendingMessage: !1,
4707
4804
  isSendingMessageToAI: !1,
4708
4805
  lastAIResMightSolveUserIssue: !1,
4709
4806
  isInitialFetchLoading: !1
4807
+ }), this.draftState = new w({
4808
+ text: "",
4809
+ mentions: []
4710
4810
  }), this.agentHandlers = null, this.bufferedAgentSends = [], this.sendMessageAbortController = new AbortController(), this.messageIdsDispatchedToOnMessageReceivedHook = /* @__PURE__ */ new Set(), this.sentTextHistory = [], this.reset = () => {
4711
- this.sendMessageAbortController.abort("Resetting chat"), this.bufferedAgentSends = [], this.state.reset(), this.messageIdsDispatchedToOnMessageReceivedHook.clear(), this.sentTextHistory = [];
4811
+ this.sendMessageAbortController.abort("Resetting chat"), this.bufferedAgentSends = [], this.state.reset(), this.messageIdsDispatchedToOnMessageReceivedHook.clear(), this.sentTextHistory = [], this.draftState.reset();
4712
4812
  }, this.rememberSentText = (s) => {
4713
4813
  const r = s.trim();
4714
- !r || this.sentTextHistory.at(-1) === r || (this.sentTextHistory.push(r), this.sentTextHistory.length > z.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
4814
+ !r || this.sentTextHistory.at(-1) === r || (this.sentTextHistory.push(r), this.sentTextHistory.length > x.SENT_TEXT_HISTORY_MAX && this.sentTextHistory.shift());
4715
4815
  }, this.getSentTextHistory = () => this.sentTextHistory, this.registerAgentHandlers = (s) => {
4716
4816
  this.agentHandlers = s;
4717
4817
  const r = this.bufferedAgentSends;
4718
4818
  this.bufferedAgentSends = [], r.forEach((c) => {
4719
- z.dispatchToEngine(s, c);
4819
+ x.dispatchToEngine(s, c);
4720
4820
  });
4721
4821
  }, this.unregisterAgentHandlers = (s) => {
4722
4822
  this.agentHandlers === s && (this.agentHandlers = null);
@@ -4734,7 +4834,7 @@ const va = (i, e, { sendsPageContext: t }) => {
4734
4834
  var r, c;
4735
4835
  return !((r = this.sessionCtx.sessionState.get().session) != null && r.id) && this.state.get().messages.length === 0 && ((c = this.config.advancedInitialMessages) == null ? void 0 : c.some((p) => p.persistent)) ? (this.config.advancedInitialMessages || []).filter((p) => p.persistent).map(
4736
4836
  (p) => ({
4737
- id: x(),
4837
+ id: z(),
4738
4838
  component: "bot_message",
4739
4839
  type: "AI",
4740
4840
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -4758,25 +4858,25 @@ const va = (i, e, { sendsPageContext: t }) => {
4758
4858
  try {
4759
4859
  (r = s.onAccepted) == null || r.call(s);
4760
4860
  } catch (c) {
4761
- u.error("send acceptance callback failed", c);
4861
+ m.error("send acceptance callback failed", c);
4762
4862
  }
4763
4863
  }, this.stageUserTurn = async (s, { pending: r }) => {
4764
4864
  const c = this.buildUserMessage(s);
4765
4865
  if (!c) return null;
4766
- const p = r ? { ...c, pending: !0 } : c, d = this.buildPersistentInitialMessages(), m = [
4767
- ...d.map((g) => g.id),
4866
+ const p = r ? { ...c, pending: !0 } : c, d = this.buildPersistentInitialMessages(), u = [
4867
+ ...d.map((h) => h.id),
4768
4868
  p.id
4769
4869
  ];
4770
4870
  this.state.setPartial({
4771
4871
  messages: [...d, ...this.state.get().messages, p]
4772
4872
  });
4773
- let h;
4873
+ let g;
4774
4874
  try {
4775
- h = await this.ensureSessionId();
4776
- } catch (g) {
4777
- throw this.rollbackOptimisticMessages(m), g;
4875
+ g = await this.ensureSessionId();
4876
+ } catch (h) {
4877
+ throw this.rollbackOptimisticMessages(u), h;
4778
4878
  }
4779
- return h ? { sessionId: h, userMessage: p, initialMessages: d } : (this.rollbackOptimisticMessages(m), null);
4879
+ return g ? { sessionId: g, userMessage: p, initialMessages: d } : (this.rollbackOptimisticMessages(u), null);
4780
4880
  }, this.buildQueuedUserMessage = (s) => {
4781
4881
  var p;
4782
4882
  const r = this.buildUserMessage(s);
@@ -4785,10 +4885,10 @@ const va = (i, e, { sendsPageContext: t }) => {
4785
4885
  return c ? { sessionId: c, userMessage: { ...r, pending: !0 } } : null;
4786
4886
  }, this.buildUserMessage = (s) => {
4787
4887
  var r;
4788
- return !s.content.trim() && (!s.attachments || s.attachments.length === 0) ? (u.warn("cannot send an empty message of no content or attachments"), null) : this.toUserMessage(
4888
+ return !s.content.trim() && (!s.attachments || s.attachments.length === 0) ? (m.warn("cannot send an empty message of no content or attachments"), null) : this.toUserMessage(
4789
4889
  s.content.trim(),
4790
4890
  s.attachments || void 0,
4791
- this.sendsPageContext ? z.markedElementNames(s.clientContext) : void 0,
4891
+ this.sendsPageContext ? x.markedElementNames(s.clientContext) : void 0,
4792
4892
  this.sendsPageContext && ((r = s.mentions) != null && r.length) ? s.mentions : void 0
4793
4893
  );
4794
4894
  }, this.appendUserMessageIfAbsent = (s) => {
@@ -4796,7 +4896,7 @@ const va = (i, e, { sendsPageContext: t }) => {
4796
4896
  r.some((c) => c.id === s.id) || this.state.setPartial({ messages: [...r, s] });
4797
4897
  }, this.markUserMessageDelivered = (s) => {
4798
4898
  const r = this.state.get().messages, c = r.findIndex(
4799
- (m) => m.id === s && m.type === "USER" && m.pending
4899
+ (u) => u.id === s && u.type === "USER" && u.pending
4800
4900
  );
4801
4901
  if (c === -1) return;
4802
4902
  const p = r[c];
@@ -4806,7 +4906,7 @@ const va = (i, e, { sendsPageContext: t }) => {
4806
4906
  messages: d
4807
4907
  });
4808
4908
  }, this.sendMessage = async (s) => {
4809
- var c, p, d, m, h;
4909
+ var c, p, d, u, g;
4810
4910
  if (this.streaming) {
4811
4911
  if (!this.agentHandlers) {
4812
4912
  this.bufferedAgentSends.push(s);
@@ -4817,20 +4917,20 @@ const va = (i, e, { sendsPageContext: t }) => {
4817
4917
  }
4818
4918
  let r;
4819
4919
  try {
4820
- const g = this.sessionCtx.sessionState.get().session, w = (g == null ? void 0 : g.assignee.kind) === "ai", b = this.state.get().isSendingMessageToAI, f = this.state.get().messages.at(-1);
4920
+ const h = this.sessionCtx.sessionState.get().session, j = (h == null ? void 0 : h.assignee.kind) === "ai", b = this.state.get().isSendingMessageToAI, f = this.state.get().messages.at(-1);
4821
4921
  if (this.blocksSendWhileAwaitingReply && (b || // If last message is from user, then bot response did not arrive yet
4822
- w && (f == null ? void 0 : f.type) === "USER")) {
4823
- u.warn("cannot send messages while awaiting AI response");
4922
+ j && (f == null ? void 0 : f.type) === "USER")) {
4923
+ m.warn("cannot send messages while awaiting AI response");
4824
4924
  return;
4825
4925
  }
4826
4926
  this.sendMessageAbortController.abort("Superseded by a newer message"), this.sendMessageAbortController = new AbortController(), r = this.sendMessageAbortController, this.state.setPartial({
4827
4927
  lastAIResMightSolveUserIssue: !1,
4828
4928
  isSendingMessage: !0,
4829
- isSendingMessageToAI: !!w || !g
4929
+ isSendingMessageToAI: !!j || !h
4830
4930
  });
4831
- const I = await this.stageUserTurn(s, { pending: !1 });
4832
- if (!I) return;
4833
- const { sessionId: $, userMessage: D, initialMessages: Z } = I;
4931
+ const D = await this.stageUserTurn(s, { pending: !1 });
4932
+ if (!D) return;
4933
+ const { sessionId: Z, userMessage: N, initialMessages: J } = D;
4834
4934
  this.notifySendAccepted(s);
4835
4935
  const { data: k } = await this.api.sendMessage(
4836
4936
  za({
@@ -4839,10 +4939,10 @@ const va = (i, e, { sendsPageContext: t }) => {
4839
4939
  capabilities: this.getClientCapabilities()
4840
4940
  },
4841
4941
  input: s,
4842
- uuid: D.id,
4843
- sessionId: $,
4844
- content: D.content,
4845
- initialMessages: Z,
4942
+ uuid: N.id,
4943
+ sessionId: Z,
4944
+ content: N.content,
4945
+ initialMessages: J,
4846
4946
  sendsPageContext: this.sendsPageContext
4847
4947
  }),
4848
4948
  r.signal
@@ -4852,7 +4952,7 @@ const va = (i, e, { sendsPageContext: t }) => {
4852
4952
  if (S) {
4853
4953
  const q = this.state.get().messages;
4854
4954
  if (!!q.some(
4855
- (J) => J.id === S.id
4955
+ (Y) => Y.id === S.id
4856
4956
  )) {
4857
4957
  this.state.setPartial({
4858
4958
  lastAIResMightSolveUserIssue: ((c = k.autopilotResponse) == null ? void 0 : c.mightSolveUserIssue) || ((p = k.uiResponse) == null ? void 0 : p.mightSolveUserIssue)
@@ -4861,20 +4961,20 @@ const va = (i, e, { sendsPageContext: t }) => {
4861
4961
  }
4862
4962
  this.state.setPartial({
4863
4963
  messages: [...q, S],
4864
- lastAIResMightSolveUserIssue: ((d = k.autopilotResponse) == null ? void 0 : d.mightSolveUserIssue) || ((m = k.uiResponse) == null ? void 0 : m.mightSolveUserIssue)
4964
+ lastAIResMightSolveUserIssue: ((d = k.autopilotResponse) == null ? void 0 : d.mightSolveUserIssue) || ((u = k.uiResponse) == null ? void 0 : u.mightSolveUserIssue)
4865
4965
  }), this.dispatchToOnMessageReceivedHook(S);
4866
4966
  }
4867
4967
  k.session && this.sessionCtx.sessionState.setPartial({ session: k.session });
4868
4968
  } else {
4869
4969
  const S = this.toBotErrorMessage(
4870
- ((h = k == null ? void 0 : k.error) == null ? void 0 : h.message) || ba(this.config, "turn_failed_message")
4970
+ ((g = k == null ? void 0 : k.error) == null ? void 0 : g.message) || fa(this.config, "turn_failed_message")
4871
4971
  ), q = this.state.get().messages;
4872
4972
  this.state.setPartial({
4873
4973
  messages: [...q, S]
4874
4974
  });
4875
4975
  }
4876
- } catch (g) {
4877
- r != null && r.signal.aborted || u.error("failed to send message", g);
4976
+ } catch (h) {
4977
+ r != null && r.signal.aborted || m.error("failed to send message", h);
4878
4978
  } finally {
4879
4979
  r != null && r.signal.aborted || this.state.setPartial({
4880
4980
  isSendingMessage: !1,
@@ -4883,14 +4983,14 @@ const va = (i, e, { sendsPageContext: t }) => {
4883
4983
  }
4884
4984
  }, this.toUserMessage = (s, r, c, p) => {
4885
4985
  const d = (() => {
4886
- const m = this.contactCtx.state.get().extraCollectedData;
4887
- return this.state.get().messages.length === 0 && m && Object.keys(m).length > 0 ? `${Object.entries(m).filter(([g, y]) => !!y).map(([g, y]) => `${g}: ${y}`).join(`
4986
+ const u = this.contactCtx.state.get().extraCollectedData;
4987
+ return this.state.get().messages.length === 0 && u && Object.keys(u).length > 0 ? `${Object.entries(u).filter(([h, v]) => !!v).map(([h, v]) => `${h}: ${v}`).join(`
4888
4988
  `)}
4889
4989
 
4890
4990
  ${s}` : s;
4891
4991
  })();
4892
4992
  return {
4893
- id: x(),
4993
+ id: z(),
4894
4994
  type: "USER",
4895
4995
  content: d,
4896
4996
  attachments: r,
@@ -4902,7 +5002,7 @@ ${s}` : s;
4902
5002
  var r;
4903
5003
  return s.success && s.autopilotResponse ? {
4904
5004
  type: "AI",
4905
- id: s.autopilotResponse.id || x(),
5005
+ id: s.autopilotResponse.id || z(),
4906
5006
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4907
5007
  component: "bot_message",
4908
5008
  agent: this.config.bot ? {
@@ -4923,7 +5023,7 @@ ${s}` : s;
4923
5023
  } : null;
4924
5024
  }, this.toBotErrorMessage = (s) => ({
4925
5025
  type: "AI",
4926
- id: x(),
5026
+ id: z(),
4927
5027
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4928
5028
  component: "bot_message",
4929
5029
  data: {
@@ -4931,16 +5031,16 @@ ${s}` : s;
4931
5031
  variant: "error",
4932
5032
  action: void 0
4933
5033
  }
4934
- }), this.config = e, this.getClientCapabilities = n ?? (() => this.config.capabilities), this.api = t, this.sessionCtx = o, this.contactCtx = _, this.streaming = l, this.sendsPageContext = a;
5034
+ }), this.config = e, this.getClientCapabilities = t ?? (() => this.config.capabilities), this.api = a, this.sessionCtx = n, this.contactCtx = i, this.streaming = l, this.sendsPageContext = o;
4935
5035
  }
4936
5036
  /** Hand a send to the streaming engine; its failure can never propagate. */
4937
- static dispatchToEngine(e, t) {
5037
+ static dispatchToEngine(e, a) {
4938
5038
  try {
4939
- Promise.resolve(e.send(t)).catch((o) => {
4940
- u.error("streaming send failed", o);
5039
+ Promise.resolve(e.send(a)).catch((n) => {
5040
+ m.error("streaming send failed", n);
4941
5041
  });
4942
- } catch (o) {
4943
- u.error("streaming send failed", o);
5042
+ } catch (n) {
5043
+ m.error("streaming send failed", n);
4944
5044
  }
4945
5045
  }
4946
5046
  /**
@@ -4951,23 +5051,23 @@ ${s}` : s;
4951
5051
  * without a usable name are dropped.
4952
5052
  */
4953
5053
  static markedElementNames(e) {
4954
- const t = e == null ? void 0 : e.page_marks;
4955
- if (!Array.isArray(t)) return;
4956
- const o = t.flatMap((_) => {
4957
- if (typeof _ != "object" || _ === null) return [];
4958
- const l = _.elements, a = Array.isArray(l) ? l[0] : void 0, n = typeof a == "object" && a !== null && "name" in a ? a.name : void 0;
4959
- if (typeof n != "string" || n.length === 0) return [];
4960
- const s = _.note, r = _.snapshotUrl;
5054
+ const a = e == null ? void 0 : e.page_marks;
5055
+ if (!Array.isArray(a)) return;
5056
+ const n = a.flatMap((i) => {
5057
+ if (typeof i != "object" || i === null) return [];
5058
+ const l = i.elements, o = Array.isArray(l) ? l[0] : void 0, t = typeof o == "object" && o !== null && "name" in o ? o.name : void 0;
5059
+ if (typeof t != "string" || t.length === 0) return [];
5060
+ const s = i.note, r = i.snapshotUrl;
4961
5061
  return [
4962
5062
  {
4963
- name: n,
5063
+ name: t,
4964
5064
  ...typeof s == "string" && s.length > 0 ? { note: s } : {},
4965
5065
  ...typeof r == "string" && r.length > 0 ? { snapshotUrl: r } : {},
4966
- mark: _
5066
+ mark: i
4967
5067
  }
4968
5068
  ];
4969
5069
  });
4970
- return o.length > 0 ? o : void 0;
5070
+ return n.length > 0 ? n : void 0;
4971
5071
  }
4972
5072
  /**
4973
5073
  * The blocking engine refuses a send while the AI reply is pending unless
@@ -4977,125 +5077,125 @@ ${s}` : s;
4977
5077
  return !this.streaming && this.config.disableSendingWhenAwaitingAIReply !== !1;
4978
5078
  }
4979
5079
  };
4980
- z.SENT_TEXT_HISTORY_MAX = 50;
4981
- let M = z;
4982
- class xa {
4983
- constructor({
4984
- config: e,
4985
- contactCtx: t,
4986
- sessionCtx: o,
4987
- resetChat: _
4988
- }) {
4989
- var l, a;
4990
- this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
5080
+ x.SENT_TEXT_HISTORY_MAX = 50;
5081
+ let M = x;
5082
+ class Ca {
5083
+ constructor(e) {
5084
+ var a, n;
5085
+ this.widget = e, this.subscriptions = [], this.disposed = !1, this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
4991
5086
  if (!this.shouldRestoreLastSession) {
4992
5087
  this.didReadStoredSession = !0;
4993
5088
  return;
4994
5089
  }
4995
- this.sessionCtx.getLastActiveSessionId().then((n) => {
4996
- this.restorableSessionId = n;
5090
+ this.sessionCtx.getLastActiveSessionId().then((i) => {
5091
+ this.restorableSessionId = i;
4997
5092
  }).finally(() => {
4998
5093
  this.didReadStoredSession = !0, this.routeFromSessions(this.sessionCtx.sessionsState.get());
4999
5094
  });
5000
5095
  }, this.registerRoutingListener = () => {
5001
- this.contactCtx.state.subscribe(({ contact: n }) => {
5002
- var s;
5003
- n != null && n.token && this.state.get().screen === "welcome" && this.state.setPartial({
5004
- screen: (s = this.config.router) != null && s.chatScreenOnly ? "chat" : "sessions"
5005
- });
5006
- }), this.sessionCtx.sessionsState.subscribe(this.routeFromSessions);
5096
+ this.subscriptions.push(
5097
+ this.contactCtx.state.subscribe(({ contact: i }) => {
5098
+ var l;
5099
+ i != null && i.token && this.state.get().screen === "welcome" && this.state.setPartial({
5100
+ screen: (l = this.config.router) != null && l.chatScreenOnly ? "chat" : "sessions"
5101
+ });
5102
+ })
5103
+ ), this.subscriptions.push(
5104
+ this.sessionCtx.sessionsState.subscribe(this.routeFromSessions)
5105
+ );
5007
5106
  }, this.routeFromSessions = ({
5008
- isInitialFetchLoading: n,
5009
- data: s
5107
+ isInitialFetchLoading: i,
5108
+ data: l
5010
5109
  }) => {
5011
- var r, c, p, d, m;
5012
- if (this.didReadStoredSession) {
5013
- if (this.restorableSessionId && !((r = this.sessionCtx.sessionState.get().session) != null && r.id)) {
5014
- const h = s.find(
5015
- (g) => g.id === this.restorableSessionId && g.isOpened
5110
+ var o, t, s, r, c;
5111
+ if (!(this.disposed || !this.didReadStoredSession)) {
5112
+ if (this.restorableSessionId && !((o = this.sessionCtx.sessionState.get().session) != null && o.id)) {
5113
+ const p = l.find(
5114
+ (d) => d.id === this.restorableSessionId && d.isOpened
5016
5115
  );
5017
- if (h) {
5018
- this.restorableSessionId = null, this.toChatScreen(h.id);
5116
+ if (p) {
5117
+ this.restorableSessionId = null, this.toChatScreen(p.id);
5019
5118
  return;
5020
5119
  }
5021
- if (n) return;
5120
+ if (i) return;
5022
5121
  this.restorableSessionId = null;
5023
5122
  }
5024
- if ((c = this.config.router) != null && c.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5123
+ if ((t = this.config.router) != null && t.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5025
5124
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
5026
- !((p = this.sessionCtx.sessionState.get().session) != null && p.id)) {
5027
- const h = (d = s.find((g) => g.isOpened)) == null ? void 0 : d.id;
5028
- return h ? this.toChatScreen(h) : void 0;
5125
+ !((s = this.sessionCtx.sessionState.get().session) != null && s.id)) {
5126
+ const p = (r = l.find((d) => d.isOpened)) == null ? void 0 : r.id;
5127
+ return p ? this.toChatScreen(p) : void 0;
5029
5128
  }
5030
- s.length || ((m = this.config.router) == null ? void 0 : m.goToChatIfNoSessions) !== !1 && !n && this.state.get().screen !== "chat" && this.toChatScreen();
5129
+ l.length || ((c = this.config.router) == null ? void 0 : c.goToChatIfNoSessions) !== !1 && !i && this.state.get().screen !== "chat" && this.toChatScreen();
5031
5130
  }
5131
+ }, this.dispose = () => {
5132
+ this.disposed = !0, this.subscriptions.forEach((i) => i()), this.subscriptions = [], this.navigateConversation = void 0;
5032
5133
  }, this.toSessionsScreen = () => {
5033
- this.resetChat(), this.state.setPartial({ screen: "sessions" });
5034
- }, this.toChatScreen = (n) => {
5035
- var r, c;
5134
+ this.navigateConversation || this.resetChat(), this.state.setPartial({ screen: "sessions" });
5135
+ }, this.toChatScreen = (i) => {
5136
+ var o, t;
5137
+ if (this.navigateConversation) return this.navigateConversation(i);
5036
5138
  this.resetChat();
5037
- let s;
5038
- if (n) {
5039
- if (s = this.sessionCtx.sessionsState.get().data.find((p) => p.id === n), !s) return;
5040
- this.sessionCtx.sessionState.setPartial({ session: s });
5139
+ let l;
5140
+ if (i) {
5141
+ if (l = this.sessionCtx.sessionsState.get().data.find((s) => s.id === i), !l) return;
5142
+ this.sessionCtx.sessionState.setPartial({ session: l });
5041
5143
  }
5042
- this.state.setPartial({ screen: "chat" }), (c = (r = this.config.hooks) == null ? void 0 : r.onNavigateToChat) == null || c.call(r, {
5043
- session: s
5044
- });
5045
- }, this.config = e, this.contactCtx = t, this.sessionCtx = o, this.resetChat = _, this.state = new j({
5046
- screen: this.contactCtx.shouldCollectData() ? "welcome" : (l = this.config.router) != null && l.chatScreenOnly ? "chat" : "sessions"
5047
- }), this.shouldRestoreLastSession = ((a = this.config.router) == null ? void 0 : a.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5144
+ return this.state.setPartial({ screen: "chat" }), (t = (o = this.config.hooks) == null ? void 0 : o.onNavigateToChat) == null || t.call(o, { session: l }), this.widget;
5145
+ }, this.config = e.config, this.contactCtx = e.contactCtx, this.sessionCtx = e.sessionCtx, this.resetChat = e.resetChat, this.state = new w({
5146
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : (a = this.config.router) != null && a.chatScreenOnly ? "chat" : "sessions"
5147
+ }), this.shouldRestoreLastSession = ((n = this.config.router) == null ? void 0 : n.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5048
5148
  }
5049
5149
  }
5050
- class Ca {
5150
+ class qa {
5051
5151
  constructor({
5052
5152
  storage: e,
5053
- config: t
5153
+ config: a
5054
5154
  }) {
5055
5155
  this.KEYS = {
5056
- contactToken: (o) => `opencx-widget:org-token-${o}:contact-token`,
5057
- externalContactId: (o) => `opencx-widget:org-token-${o}:external-contact-id`,
5058
- companionPreference: (o, _) => `opencx-widget:org-token-${o}:companion-${_}`,
5059
- activeSession: (o) => `opencx-widget:org-token-${o}:active-session`
5060
- }, this.setContactToken = async (o) => {
5061
- await this.storage.set(this.KEYS.contactToken(this.config.token), o);
5156
+ contactToken: (n) => `opencx-widget:org-token-${n}:contact-token`,
5157
+ externalContactId: (n) => `opencx-widget:org-token-${n}:external-contact-id`,
5158
+ companionPreference: (n, i) => `opencx-widget:org-token-${n}:companion-${i}`,
5159
+ activeSession: (n) => `opencx-widget:org-token-${n}:active-session`
5160
+ }, this.setContactToken = async (n) => {
5161
+ await this.storage.set(this.KEYS.contactToken(this.config.token), n);
5062
5162
  }, this.getContactToken = async () => this.storage.get(this.KEYS.contactToken(this.config.token)), this.clearContactToken = async () => {
5063
5163
  await this.storage.remove(this.KEYS.contactToken(this.config.token));
5064
- }, this.activeSessionKey = () => this.KEYS.activeSession(this.config.token), this.getActiveSessionId = async () => this.storage.get(this.activeSessionKey()), this.setActiveSessionId = async (o) => {
5065
- await this.storage.set(this.activeSessionKey(), o);
5164
+ }, this.activeSessionKey = () => this.KEYS.activeSession(this.config.token), this.getActiveSessionId = async () => this.storage.get(this.activeSessionKey()), this.setActiveSessionId = async (n) => {
5165
+ await this.storage.set(this.activeSessionKey(), n);
5066
5166
  }, this.clearActiveSessionId = async () => {
5067
5167
  await this.storage.remove(this.activeSessionKey());
5068
- }, this.setExternalContactId = async (o) => {
5069
- await this.storage.set(this.KEYS.externalContactId(this.config.token), o);
5070
- }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.companionKey = (o) => this.KEYS.companionPreference(this.config.token, o), this.getFiniteNumber = async (o) => {
5071
- const _ = await this.storage.get(o);
5072
- if (_ === null) return null;
5073
- const l = Number(_);
5168
+ }, this.setExternalContactId = async (n) => {
5169
+ await this.storage.set(this.KEYS.externalContactId(this.config.token), n);
5170
+ }, this.getExternalContactId = async () => this.storage.get(this.KEYS.externalContactId(this.config.token)), this.companionKey = (n) => this.KEYS.companionPreference(this.config.token, n), this.getFiniteNumber = async (n) => {
5171
+ const i = await this.storage.get(n);
5172
+ if (i === null) return null;
5173
+ const l = Number(i);
5074
5174
  return Number.isFinite(l) ? l : null;
5075
- }, this.getCompanionPillOffsetX = async () => this.getFiniteNumber(this.companionKey("pill-offset-x")), this.setCompanionPillOffsetX = async (o) => {
5076
- Number.isFinite(o) && await this.storage.set(this.companionKey("pill-offset-x"), String(o));
5077
- }, this.getCompanionSidebarWidth = async () => this.getFiniteNumber(this.companionKey("sidebar-width")), this.setCompanionSidebarWidth = async (o) => {
5078
- Number.isFinite(o) && await this.storage.set(this.companionKey("sidebar-width"), String(o));
5175
+ }, this.getCompanionPillOffsetX = async () => this.getFiniteNumber(this.companionKey("pill-offset-x")), this.setCompanionPillOffsetX = async (n) => {
5176
+ Number.isFinite(n) && await this.storage.set(this.companionKey("pill-offset-x"), String(n));
5177
+ }, this.getCompanionSidebarWidth = async () => this.getFiniteNumber(this.companionKey("sidebar-width")), this.setCompanionSidebarWidth = async (n) => {
5178
+ Number.isFinite(n) && await this.storage.set(this.companionKey("sidebar-width"), String(n));
5079
5179
  }, this.getCompanionSidebarSide = async () => {
5080
- const o = await this.storage.get(this.companionKey("sidebar-side"));
5081
- return o === "left" || o === "right" ? o : null;
5082
- }, this.setCompanionSidebarSide = async (o) => {
5083
- await this.storage.set(this.companionKey("sidebar-side"), o);
5180
+ const n = await this.storage.get(this.companionKey("sidebar-side"));
5181
+ return n === "left" || n === "right" ? n : null;
5182
+ }, this.setCompanionSidebarSide = async (n) => {
5183
+ await this.storage.set(this.companionKey("sidebar-side"), n);
5084
5184
  }, this.getCompanionLayout = async () => {
5085
- const o = await this.storage.get(this.companionKey("layout"));
5086
- return o === "compact" || o === "sidebar" ? o : null;
5087
- }, this.setCompanionLayout = async (o) => {
5088
- await this.storage.set(this.companionKey("layout"), o);
5185
+ const n = await this.storage.get(this.companionKey("layout"));
5186
+ return n === "compact" || n === "sidebar" ? n : null;
5187
+ }, this.setCompanionLayout = async (n) => {
5188
+ await this.storage.set(this.companionKey("layout"), n);
5089
5189
  }, this.getCompanionSidebarMode = async () => {
5090
- const o = await this.storage.get(this.companionKey("sidebar-mode"));
5091
- return o === "docked" || o === "floating" ? o : null;
5092
- }, this.setCompanionSidebarMode = async (o) => {
5093
- await this.storage.set(this.companionKey("sidebar-mode"), o);
5094
- }, this.storage = e, this.config = t;
5190
+ const n = await this.storage.get(this.companionKey("sidebar-mode"));
5191
+ return n === "docked" || n === "floating" ? n : null;
5192
+ }, this.setCompanionSidebarMode = async (n) => {
5193
+ await this.storage.set(this.companionKey("sidebar-mode"), n);
5194
+ }, this.storage = e, this.config = a;
5095
5195
  }
5096
5196
  }
5097
- function qa({
5098
- org: i,
5197
+ function Ea({
5198
+ org: _,
5099
5199
  agent: e
5100
5200
  }) {
5101
5201
  return e ? {
@@ -5109,7 +5209,7 @@ function qa({
5109
5209
  clientTools: e.features.client_tools
5110
5210
  }
5111
5211
  } : {
5112
- name: i.name,
5212
+ name: _.name,
5113
5213
  avatarUrl: null,
5114
5214
  streaming: !1,
5115
5215
  features: {
@@ -5120,55 +5220,78 @@ function qa({
5120
5220
  }
5121
5221
  };
5122
5222
  }
5123
- function A(i, e) {
5124
- return i && e !== !1;
5223
+ function T(_, e) {
5224
+ return _ && e !== !1;
5125
5225
  }
5126
- function Ea(i, e) {
5127
- const t = e.features;
5226
+ function Pa(_, e) {
5227
+ const a = e.features;
5128
5228
  return {
5129
- dictation: A(i.features.dictation, t == null ? void 0 : t.dictation),
5130
- attachments: i.features.attachments,
5131
- pageContext: A(
5132
- i.features.pageContext,
5133
- t == null ? void 0 : t.pageContext
5229
+ dictation: T(_.features.dictation, a == null ? void 0 : a.dictation),
5230
+ attachments: _.features.attachments,
5231
+ pageContext: T(
5232
+ _.features.pageContext,
5233
+ a == null ? void 0 : a.pageContext
5134
5234
  ),
5135
- clientTools: A(
5136
- i.features.clientTools,
5137
- t == null ? void 0 : t.clientTools
5235
+ clientTools: T(
5236
+ _.features.clientTools,
5237
+ a == null ? void 0 : a.clientTools
5138
5238
  )
5139
5239
  };
5140
5240
  }
5141
- class Pa extends Error {
5142
- constructor(e, t, o) {
5143
- super(t), this.name = "WidgetInitializationError", this.code = e, this.details = o;
5241
+ class Aa extends Error {
5242
+ constructor(e, a, n) {
5243
+ super(a), this.name = "WidgetInitializationError", this.code = e, this.details = n;
5144
5244
  }
5145
5245
  }
5146
- const v = class v {
5246
+ const y = class y {
5147
5247
  constructor({
5148
5248
  config: e,
5149
- storage: t,
5150
- getClientCapabilities: o,
5151
- modes: _,
5249
+ storage: a,
5250
+ getClientCapabilities: n,
5251
+ modes: i,
5152
5252
  org: l,
5153
- agent: a
5253
+ agent: o,
5254
+ parent: t
5154
5255
  }) {
5155
- if (this.modes = [], this.resetChat = () => {
5156
- this.sessionCtx.reset(), this.messageCtx.reset();
5157
- }, this.reconcileAfterStream = (n) => this.activeSessionPollingCtx.reconcileAfterStream(n), !v.pollingIntervalsSeconds)
5256
+ if (this.modes = [], this.createConversation = () => {
5257
+ const s = new y({
5258
+ config: {
5259
+ ...this.config,
5260
+ router: {
5261
+ ...this.config.router,
5262
+ restoreLastSession: !1,
5263
+ chatScreenOnly: !1,
5264
+ goToChatIfNoSessions: !1
5265
+ }
5266
+ },
5267
+ modes: this.modes,
5268
+ org: this.org,
5269
+ agent: this.agent,
5270
+ parent: this
5271
+ });
5272
+ return s.routerCtx.state.setPartial({
5273
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : "chat"
5274
+ }), s;
5275
+ }, this.releaseConversation = () => {
5276
+ this.routerCtx.dispose(), this.resetChat();
5277
+ }, this.resetChat = () => {
5278
+ this.sessionCtx.reset(), this.messageCtx.reset(), this.uploadCtx.reset();
5279
+ }, this.reconcileAfterStream = (s) => this.activeSessionPollingCtx.reconcileAfterStream(s), !y.pollingIntervalsSeconds)
5158
5280
  throw Error(
5159
5281
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
5160
5282
  );
5161
- this.config = e, this.org = l, this.agent = a, this.features = Ea(a, e), this.api = new K({ config: e }), this.storageCtx = t ? new Ca({ storage: t, config: e }) : void 0, this.modes = _, this.contactCtx = new oe({
5283
+ this.config = e, this.org = l, this.agent = o, this.features = Pa(o, e), this.api = (t == null ? void 0 : t.api) ?? new L({ config: e }), this.storageCtx = (t == null ? void 0 : t.storageCtx) ?? (a ? new qa({ storage: a, config: e }) : void 0), this.modes = i, this.contactCtx = (t == null ? void 0 : t.contactCtx) ?? new ie({
5162
5284
  api: this.api,
5163
5285
  config: this.config,
5164
5286
  storageCtx: this.storageCtx
5165
- }), this.sessionCtx = new fa({
5287
+ }), this.sessionCtx = new va({
5166
5288
  config: this.config,
5167
5289
  api: this.api,
5168
5290
  contactCtx: this.contactCtx,
5169
5291
  // Remembers the open conversation so a reload can return to it.
5170
- storageCtx: this.storageCtx,
5171
- sessionsPollingIntervalSeconds: v.pollingIntervalsSeconds.sessions
5292
+ storageCtx: t ? void 0 : this.storageCtx,
5293
+ sharedSessions: t == null ? void 0 : t.sessionCtx.sessionsState,
5294
+ sessionsPollingIntervalSeconds: y.pollingIntervalsSeconds.sessions
5172
5295
  }), this.messageCtx = new M({
5173
5296
  config: this.config,
5174
5297
  api: this.api,
@@ -5178,26 +5301,21 @@ const v = class v {
5178
5301
  // the blocking bot-chat send.
5179
5302
  streaming: this.streaming,
5180
5303
  sendsPageContext: this.features.pageContext,
5181
- getClientCapabilities: o
5182
- }), this.csatCtx = new ie({
5304
+ getClientCapabilities: n
5305
+ }), this.uploadCtx = new re(this.api), this.csatCtx = new _e({
5183
5306
  api: this.api,
5184
5307
  sessionCtx: this.sessionCtx,
5185
5308
  messageCtx: this.messageCtx
5186
- }), this.dictationCtx = new qe({
5309
+ }), this.dictationCtx = new Pe({
5187
5310
  api: this.api,
5188
5311
  config: this.config
5189
- }), this.activeSessionPollingCtx = new ne({
5312
+ }), this.activeSessionPollingCtx = new oe({
5190
5313
  api: this.api,
5191
5314
  config: this.config,
5192
5315
  sessionCtx: this.sessionCtx,
5193
5316
  messageCtx: this.messageCtx,
5194
- sessionPollingIntervalSeconds: v.pollingIntervalsSeconds.session
5195
- }), this.routerCtx = new xa({
5196
- config: this.config,
5197
- contactCtx: this.contactCtx,
5198
- sessionCtx: this.sessionCtx,
5199
- resetChat: this.resetChat
5200
- });
5317
+ sessionPollingIntervalSeconds: y.pollingIntervalsSeconds.session
5318
+ }), this.routerCtx = new Ca(this);
5201
5319
  }
5202
5320
  /**
5203
5321
  * Whether turns stream (the v5 agent-chat engine) or use the blocking
@@ -5208,40 +5326,40 @@ const v = class v {
5208
5326
  return this.agent.streaming;
5209
5327
  }
5210
5328
  };
5211
- v.pollingIntervalsSeconds = null, v.initialize = async ({
5329
+ y.pollingIntervalsSeconds = null, y.initialize = async ({
5212
5330
  config: e,
5213
- storage: t,
5214
- getClientCapabilities: o
5331
+ storage: a,
5332
+ getClientCapabilities: n
5215
5333
  }) => {
5216
- var l, a;
5217
- const _ = await new K({
5334
+ var l, o;
5335
+ const i = await new L({
5218
5336
  config: e
5219
5337
  }).getExternalWidgetConfig();
5220
- if (!_.data)
5221
- throw u.error("widget config fetch failed", _.error), new Pa(
5338
+ if (!i.data)
5339
+ throw m.error("widget config fetch failed", i.error), new Aa(
5222
5340
  "config-fetch-failed",
5223
5341
  "Failed to fetch widget config",
5224
- _.error
5342
+ i.error
5225
5343
  );
5226
- return v.pollingIntervalsSeconds = {
5227
- session: ((l = _.data) == null ? void 0 : l.sessionPollingIntervalSeconds) || 10,
5228
- sessions: ((a = _.data) == null ? void 0 : a.sessionsPollingIntervalSeconds) || 60
5229
- }, new v({
5344
+ return y.pollingIntervalsSeconds = {
5345
+ session: ((l = i.data) == null ? void 0 : l.sessionPollingIntervalSeconds) || 10,
5346
+ sessions: ((o = i.data) == null ? void 0 : o.sessionsPollingIntervalSeconds) || 60
5347
+ }, new y({
5230
5348
  config: e,
5231
- storage: t,
5232
- getClientCapabilities: o,
5233
- modes: _.data.modes || [],
5349
+ storage: a,
5350
+ getClientCapabilities: n,
5351
+ modes: i.data.modes || [],
5234
5352
  org: {
5235
- id: _.data.org.id,
5236
- name: _.data.org.name
5353
+ id: i.data.org.id,
5354
+ name: i.data.org.name
5237
5355
  },
5238
- agent: qa(_.data)
5356
+ agent: Ea(i.data)
5239
5357
  });
5240
5358
  };
5241
- let U = v;
5242
- class La {
5243
- constructor({ attack: e, release: t }) {
5244
- this.value = 0, this.attack = e, this.release = t;
5359
+ let B = y;
5360
+ class Fa {
5361
+ constructor({ attack: e, release: a }) {
5362
+ this.value = 0, this.attack = e, this.release = a;
5245
5363
  }
5246
5364
  next(e) {
5247
5365
  return this.value += (e - this.value) * (e > this.value ? this.attack : this.release), this.value;
@@ -5257,46 +5375,46 @@ const P = [
5257
5375
  ], Ta = new Set(
5258
5376
  P
5259
5377
  );
5260
- function W(i) {
5261
- return Ta.has(i);
5378
+ function $(_) {
5379
+ return Ta.has(_);
5262
5380
  }
5263
- function Fa(i) {
5264
- if (!Array.isArray(i)) return P;
5265
- const e = [], t = /* @__PURE__ */ new Set();
5266
- for (const o of i)
5267
- !W(o) || t.has(o) || (t.add(o), e.push(o));
5381
+ function Oa(_) {
5382
+ if (!Array.isArray(_)) return P;
5383
+ const e = [], a = /* @__PURE__ */ new Set();
5384
+ for (const n of _)
5385
+ !$(n) || a.has(n) || (a.add(n), e.push(n));
5268
5386
  return e.length > 0 ? e : P;
5269
5387
  }
5270
- function Oa(i, e) {
5271
- return W(i) && e.includes(i) ? i : e[0] ?? P[0];
5388
+ function Ua(_, e) {
5389
+ return $(_) && e.includes(_) ? _ : e[0] ?? P[0];
5272
5390
  }
5273
- function Ua(i, e) {
5274
- return i === "left" || i === "right" ? i : e === "rtl" ? "left" : "right";
5391
+ function Ba(_, e) {
5392
+ return _ === "left" || _ === "right" ? _ : e === "rtl" ? "left" : "right";
5275
5393
  }
5276
- function Ba(i) {
5277
- return i === "docked" ? "docked" : "floating";
5394
+ function Va(_) {
5395
+ return _ === "docked" ? "docked" : "floating";
5278
5396
  }
5279
5397
  export {
5280
- La as DictationLevelSmoother,
5281
- j as PrimitiveState,
5282
- U as WidgetCtx,
5283
- Pa as WidgetInitializationError,
5398
+ Fa as DictationLevelSmoother,
5399
+ w as PrimitiveState,
5400
+ B as WidgetCtx,
5401
+ Aa as WidgetInitializationError,
5284
5402
  za as buildSendMessageBody,
5285
- x as genUuid,
5286
- ka as getTranslation,
5287
- Na as isAgentStreamKeepalive,
5288
- se as isExhaustive,
5289
- O as isRecord,
5290
- Ka as isRtlLanguage,
5291
- ua as isSupportedLanguage,
5292
- Ra as isTurnSteeredPart,
5293
- u as log,
5294
- Fa as normalizeCompanionLayouts,
5295
- Oa as resolveCompanionDefaultLayout,
5296
- ja as resolveConfigContext,
5297
- ga as resolveLanguage,
5298
- Ba as resolveSidebarMode,
5299
- Ua as resolveSidebarSide,
5300
- ba as translate
5403
+ z as genUuid,
5404
+ ba as getTranslation,
5405
+ Ra as isAgentStreamKeepalive,
5406
+ ne as isExhaustive,
5407
+ U as isRecord,
5408
+ La as isRtlLanguage,
5409
+ ha as isSupportedLanguage,
5410
+ Ka as isTurnSteeredPart,
5411
+ m as log,
5412
+ Oa as normalizeCompanionLayouts,
5413
+ Ua as resolveCompanionDefaultLayout,
5414
+ Sa as resolveConfigContext,
5415
+ ka as resolveLanguage,
5416
+ Va as resolveSidebarMode,
5417
+ Ba as resolveSidebarSide,
5418
+ fa as translate
5301
5419
  };
5302
5420
  //# sourceMappingURL=index.js.map