@opencx/widget-core 5.0.0 → 5.2.0

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,66 +1,66 @@
1
- import { z as m } from "zod";
1
+ import { z as h } from "zod";
2
2
  import te from "openapi-fetch";
3
3
  import se from "lodash.isequal";
4
4
  import { v4 as N } from "uuid";
5
- const Wa = (i) => i.type === "data-keepalive", $a = (i) => i.type === "data-turn-steered", L = m.object({ const: m.string(), title: m.string().optional() }), oe = m.object({
6
- type: m.enum(["string", "number", "integer", "boolean", "array"]),
7
- title: m.string().optional(),
8
- description: m.string().optional(),
9
- default: m.union([m.string(), m.number(), m.boolean(), m.array(m.string())]).optional(),
10
- enum: m.array(m.string()).optional(),
11
- oneOf: m.array(L).optional(),
12
- items: m.object({
13
- enum: m.array(m.string()).optional(),
14
- anyOf: m.array(L).optional()
5
+ const Wa = (i) => i.type === "data-keepalive", $a = (i) => i.type === "data-turn-steered", L = h.object({ const: h.string(), title: h.string().optional() }), oe = h.object({
6
+ type: h.enum(["string", "number", "integer", "boolean", "array"]),
7
+ title: h.string().optional(),
8
+ description: h.string().optional(),
9
+ default: h.union([h.string(), h.number(), h.boolean(), h.array(h.string())]).optional(),
10
+ enum: h.array(h.string()).optional(),
11
+ oneOf: h.array(L).optional(),
12
+ items: h.object({
13
+ enum: h.array(h.string()).optional(),
14
+ anyOf: h.array(L).optional()
15
15
  }).optional(),
16
- minItems: m.number().int().nonnegative().optional(),
17
- maxItems: m.number().int().nonnegative().optional(),
18
- minimum: m.number().optional(),
19
- maximum: m.number().optional(),
20
- minLength: m.number().optional(),
21
- maxLength: m.number().optional(),
22
- format: m.string().optional()
23
- }), ne = m.array(
24
- m.object({
25
- id: m.string(),
26
- serverId: m.string(),
27
- serverName: m.string(),
28
- expiresAt: m.number(),
29
- approvalKey: m.string().optional(),
30
- form: m.object({
31
- message: m.string(),
32
- requestedSchema: m.object({
33
- properties: m.record(m.string(), oe),
34
- required: m.array(m.string()).optional()
16
+ minItems: h.number().int().nonnegative().optional(),
17
+ maxItems: h.number().int().nonnegative().optional(),
18
+ minimum: h.number().optional(),
19
+ maximum: h.number().optional(),
20
+ minLength: h.number().optional(),
21
+ maxLength: h.number().optional(),
22
+ format: h.string().optional()
23
+ }), ne = h.array(
24
+ h.object({
25
+ id: h.string(),
26
+ serverId: h.string(),
27
+ serverName: h.string(),
28
+ expiresAt: h.number(),
29
+ approvalKey: h.string().optional(),
30
+ form: h.object({
31
+ message: h.string(),
32
+ requestedSchema: h.object({
33
+ properties: h.record(h.string(), oe),
34
+ required: h.array(h.string()).optional()
35
35
  })
36
36
  })
37
37
  })
38
- ), ie = m.array(
39
- m.object({
40
- key: m.string(),
41
- serverId: m.string(),
42
- serverName: m.string(),
43
- message: m.string(),
44
- toolName: m.string()
38
+ ), ie = h.array(
39
+ h.object({
40
+ key: h.string(),
41
+ serverId: h.string(),
42
+ serverName: h.string(),
43
+ message: h.string(),
44
+ toolName: h.string()
45
45
  })
46
- ), F = "[opencx]", g = {
46
+ ), O = "[opencx]", k = {
47
47
  warn: (i, ...e) => {
48
- console.warn(`${F} ${i}`, ...e);
48
+ console.warn(`${O} ${i}`, ...e);
49
49
  },
50
50
  error: (i, ...e) => {
51
- console.error(`${F} ${i}`, ...e);
51
+ console.error(`${O} ${i}`, ...e);
52
52
  }
53
53
  }, re = (i) => {
54
- g.error("request failed", i.error);
54
+ k.error("request failed", i.error);
55
55
  }, _e = (i) => {
56
56
  const e = te({
57
57
  baseUrl: i.baseUrl
58
- }), a = {
58
+ }), t = {
59
59
  onRequest: i.onRequest,
60
60
  onResponse: i.onResponse,
61
61
  onError: i.onError || re
62
62
  };
63
- return e.use(a), e;
63
+ return e.use(t), e;
64
64
  };
65
65
  class le extends Error {
66
66
  constructor() {
@@ -72,51 +72,51 @@ class ce extends Error {
72
72
  super("This connection attempt is no longer available."), this.name = "ConnectionAttemptUnavailableError";
73
73
  }
74
74
  }
75
- const pe = "/backend/widget/v5/chat/stream", de = "/backend/widget/v5/chat/{sessionId}/stream", O = (i, e, a) => `${i.replace(/\/$/, "")}${a ? e.replace("{sessionId}", encodeURIComponent(a)) : e}`;
75
+ const pe = "/backend/widget/v5/chat/stream", de = "/backend/widget/v5/chat/{sessionId}/stream", F = (i, e, t) => `${i.replace(/\/$/, "")}${t ? e.replace("{sessionId}", encodeURIComponent(t)) : e}`;
76
76
  class U {
77
77
  constructor({ config: e }) {
78
- var r, l;
78
+ var r, c;
79
79
  this.userToken = null, this.constructClientOptions = (s) => {
80
- const t = this.config.apiUrl || "https://api.open.cx", n = {
80
+ const a = this.config.apiUrl || "https://api.open.cx", n = {
81
81
  "X-Bot-Token": this.config.token,
82
82
  "Content-Type": "application/json",
83
83
  Accept: "application/json",
84
84
  Authorization: s ? `Bearer ${s}` : void 0
85
85
  };
86
- return { baseUrl: t, headers: n };
86
+ return { baseUrl: a, headers: n };
87
87
  }, this.createOpenAPIClient = ({
88
88
  baseUrl: s,
89
- headers: t
89
+ headers: a
90
90
  }) => _e({
91
91
  baseUrl: s,
92
92
  onRequest: ({ request: n }) => {
93
- Object.entries(t).forEach(([c, d]) => {
94
- d && n.headers.set(c, d);
93
+ Object.entries(a).forEach(([l, d]) => {
94
+ d && n.headers.set(l, d);
95
95
  });
96
96
  }
97
97
  }), this.listApprovalPreferences = async () => {
98
- const { baseUrl: s, headers: t } = this.getStreamAuthContext(), n = await fetch(
98
+ const { baseUrl: s, headers: a } = this.getStreamAuthContext(), n = await fetch(
99
99
  `${s}/backend/widget/v5/connections/approval-preferences`,
100
- { headers: t }
100
+ { headers: a }
101
101
  );
102
102
  if (!n.ok) throw new Error("Could not load permissions.");
103
103
  return ie.parse(await n.json());
104
- }, this.revokeApprovalPreference = async (s, t) => {
105
- const { baseUrl: n, headers: c } = this.getStreamAuthContext();
104
+ }, this.revokeApprovalPreference = async (s, a) => {
105
+ const { baseUrl: n, headers: l } = this.getStreamAuthContext();
106
106
  if (!(await fetch(
107
- `${n}/backend/widget/v5/connections/${encodeURIComponent(s)}/approval-preferences/${encodeURIComponent(t)}`,
108
- { method: "DELETE", headers: c }
107
+ `${n}/backend/widget/v5/connections/${encodeURIComponent(s)}/approval-preferences/${encodeURIComponent(a)}`,
108
+ { method: "DELETE", headers: l }
109
109
  )).ok) throw new Error("Could not reset permission.");
110
- }, this.listElicitations = async (s, t) => {
111
- const { baseUrl: n, headers: c } = this.getStreamAuthContext(), d = await fetch(
110
+ }, this.listElicitations = async (s, a) => {
111
+ const { baseUrl: n, headers: l } = this.getStreamAuthContext(), d = await fetch(
112
112
  `${n}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}`,
113
- { headers: c, signal: t }
113
+ { headers: l, signal: a }
114
114
  );
115
115
  if (!d.ok) throw new Error("Could not load the request.");
116
116
  return ne.parse(await d.json());
117
- }, this.answerElicitation = async (s, t, n) => {
118
- const { baseUrl: c, headers: d } = this.getStreamAuthContext(), _ = await fetch(
119
- `${c}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}/${encodeURIComponent(t)}`,
117
+ }, this.answerElicitation = async (s, a, n) => {
118
+ const { baseUrl: l, headers: d } = this.getStreamAuthContext(), _ = await fetch(
119
+ `${l}/backend/widget/v5/connections/elicitation/${encodeURIComponent(s)}/${encodeURIComponent(a)}`,
120
120
  {
121
121
  method: "POST",
122
122
  headers: { ...d, "Content-Type": "application/json" },
@@ -128,89 +128,89 @@ class U {
128
128
  _.status === 400 ? "Check your answers and try again." : "This request has ended. Ask the agent to try again."
129
129
  );
130
130
  }, this.listConnections = async (s) => {
131
- const { data: t, error: n } = await this.client.GET(
131
+ const { data: a, error: n } = await this.client.GET(
132
132
  "/backend/widget/v5/connections",
133
133
  { signal: s }
134
134
  );
135
- if (n || !t)
135
+ if (n || !a)
136
136
  throw new Error("Could not load connections. Sign in and try again.");
137
- return t;
138
- }, this.startConnection = async (s, t, n) => {
139
- const { data: c, error: d, response: _ } = await this.client.POST(
137
+ return a;
138
+ }, this.startConnection = async (s, a, n) => {
139
+ const { data: l, error: d, response: _ } = await this.client.POST(
140
140
  "/backend/widget/v5/connections/{serverId}/start",
141
141
  {
142
142
  params: { path: { serverId: s } },
143
- body: { request_id: t },
143
+ body: { request_id: a },
144
144
  signal: n
145
145
  }
146
146
  );
147
147
  if (_.status === 410) throw new le();
148
148
  if (_.status === 404)
149
149
  throw new Error("This connection request is no longer available.");
150
- if (d || !c)
150
+ if (d || !l)
151
151
  throw new Error("Could not start this connection. Please try again.");
152
- return c;
153
- }, this.getConnectionAttempt = async (s, t, n) => {
154
- const { data: c, error: d, response: _ } = await this.client.GET(
152
+ return l;
153
+ }, this.getConnectionAttempt = async (s, a, n) => {
154
+ const { data: l, error: d, response: _ } = await this.client.GET(
155
155
  "/backend/widget/v5/connections/{serverId}/attempts/{attemptId}",
156
156
  {
157
- params: { path: { serverId: s, attemptId: t } },
157
+ params: { path: { serverId: s, attemptId: a } },
158
158
  signal: n
159
159
  }
160
160
  );
161
161
  if ([401, 403, 404].includes(_.status))
162
162
  throw new ce();
163
- if (d || !c)
163
+ if (d || !l)
164
164
  throw new Error(`Could not check the connection (${_.status}).`);
165
- return c.status;
165
+ return l.status;
166
166
  }, this.disconnectConnection = async (s) => {
167
- const { error: t } = await this.client.DELETE(
167
+ const { error: a } = await this.client.DELETE(
168
168
  "/backend/widget/v5/connections/{serverId}",
169
169
  {
170
170
  params: { path: { serverId: s } }
171
171
  }
172
172
  );
173
- if (t) throw new Error("Could not disconnect. Please try again.");
173
+ if (a) throw new Error("Could not disconnect. Please try again.");
174
174
  }, this.setAuthToken = (s) => {
175
175
  this.userToken = s;
176
- const { baseUrl: t, headers: n } = this.constructClientOptions(s);
177
- this.client = this.createOpenAPIClient({ baseUrl: t, headers: n });
176
+ const { baseUrl: a, headers: n } = this.constructClientOptions(s);
177
+ this.client = this.createOpenAPIClient({ baseUrl: a, headers: n });
178
178
  }, this.getStreamAuthContext = () => {
179
- const { baseUrl: s, headers: t } = this.constructClientOptions(this.userToken), n = {};
180
- for (const [c, d] of Object.entries(t))
181
- typeof d == "string" && (["content-type", "accept"].includes(c.toLowerCase()) || (n[c] = d));
179
+ const { baseUrl: s, headers: a } = this.constructClientOptions(this.userToken), n = {};
180
+ for (const [l, d] of Object.entries(a))
181
+ typeof d == "string" && (["content-type", "accept"].includes(l.toLowerCase()) || (n[l] = d));
182
182
  return { baseUrl: s, headers: n };
183
183
  }, this.getStreamTransportOptions = () => {
184
- const { baseUrl: s, headers: t } = this.getStreamAuthContext();
184
+ const { baseUrl: s, headers: a } = this.getStreamAuthContext();
185
185
  return {
186
- api: O(s, pe),
187
- reconnectApi: (n) => O(s, de, n),
188
- headers: t
186
+ api: F(s, pe),
187
+ reconnectApi: (n) => F(s, de, n),
188
+ headers: a
189
189
  };
190
190
  }, this.stopStream = async (s) => {
191
- const { response: t } = await this.client.POST(
191
+ const { response: a } = await this.client.POST(
192
192
  "/backend/widget/v5/chat/{sessionId}/stop",
193
193
  { params: { path: { sessionId: s } } }
194
194
  );
195
- if (!t.ok)
196
- throw new Error(`Failed to stop stream: ${t.status}`);
197
- }, this.sendPageReply = async (s, t) => {
195
+ if (!a.ok)
196
+ throw new Error(`Failed to stop stream: ${a.status}`);
197
+ }, this.sendPageReply = async (s, a) => {
198
198
  try {
199
199
  await this.client.POST("/backend/widget/v5/chat/{sessionId}/page-reply", {
200
200
  params: { path: { sessionId: s } },
201
- body: t
201
+ body: a
202
202
  });
203
203
  } catch {
204
204
  }
205
- }, this.getAgentTurnMessages = async (s, t) => {
206
- const { data: n, response: c } = await this.client.GET(
205
+ }, this.getAgentTurnMessages = async (s, a) => {
206
+ const { data: n, response: l } = await this.client.GET(
207
207
  "/backend/widget/v5/chat/{sessionId}/messages",
208
208
  {
209
209
  params: {
210
210
  path: { sessionId: s },
211
211
  query: {
212
- toolActivity: t == null ? void 0 : t.toolActivity,
213
- reasoning: (t == null ? void 0 : t.reasoning) === void 0 ? void 0 : t.reasoning ? "true" : "false"
212
+ toolActivity: a == null ? void 0 : a.toolActivity,
213
+ reasoning: (a == null ? void 0 : a.reasoning) === void 0 ? void 0 : a.reasoning ? "true" : "false"
214
214
  }
215
215
  }
216
216
  }
@@ -218,78 +218,78 @@ class U {
218
218
  return n ? {
219
219
  ...n,
220
220
  handled_connection_request_ids: n.handled_connection_request_ids ?? []
221
- } : (g.warn("agent turn messages fetch failed", c.status), null);
221
+ } : (k.warn("agent turn messages fetch failed", l.status), null);
222
222
  }, this.createDictationSession = async ({
223
223
  language: s
224
224
  }) => {
225
- const { data: t, response: n } = await this.client.POST(
225
+ const { data: a, response: n } = await this.client.POST(
226
226
  "/backend/widget/v5/dictation/sessions",
227
227
  { body: s ? { language: s } : {} }
228
228
  );
229
- if (!t)
229
+ if (!a)
230
230
  throw new Error(`Failed to start dictation: ${n.status}`);
231
- return t;
231
+ return a;
232
232
  }, this.getExternalWidgetConfig = async () => await this.client.GET("/backend/widget/v2/config", {
233
233
  params: {
234
234
  header: { "x-bot-token": this.config.token }
235
235
  }
236
- }), this.sendMessage = async (s, t) => await this.client.POST("/backend/widget/v2/chat/send", {
236
+ }), this.sendMessage = async (s, a) => await this.client.POST("/backend/widget/v2/chat/send", {
237
237
  body: s,
238
- signal: t
238
+ signal: a
239
239
  }), this.createUnverifiedContact = async (s) => await this.client.POST(
240
240
  "/backend/widget/v2/contact/create-unverified",
241
241
  {
242
242
  params: { header: { "x-bot-token": this.config.token } },
243
243
  body: s
244
244
  }
245
- ), this.createSession = async (s, t) => await this.client.POST("/backend/widget/v2/create-session", {
245
+ ), this.createSession = async (s, a) => await this.client.POST("/backend/widget/v2/create-session", {
246
246
  body: s,
247
- signal: t
247
+ signal: a
248
248
  }), this.pollSessionAndHistory = async ({
249
249
  sessionId: s,
250
- abortSignal: t
250
+ abortSignal: a
251
251
  }) => await this.client.GET("/backend/widget/v2/poll/{sessionId}", {
252
252
  params: { path: { sessionId: s } },
253
- signal: t
253
+ signal: a
254
254
  }), this.getSessions = async ({
255
255
  cursor: s,
256
- filters: t,
256
+ filters: a,
257
257
  abortSignal: n
258
258
  }) => await this.client.GET("/backend/widget/v2/sessions", {
259
259
  params: {
260
260
  query: {
261
261
  offset: s,
262
- filters: JSON.stringify(t)
262
+ filters: JSON.stringify(a)
263
263
  }
264
264
  },
265
265
  signal: n
266
266
  }), this.uploadFile = async ({
267
267
  file: s,
268
- abortSignal: t,
268
+ abortSignal: a,
269
269
  onProgress: n
270
- }) => new Promise((c, d) => {
270
+ }) => new Promise((l, d) => {
271
271
  var f;
272
272
  const _ = new FormData();
273
273
  _.append("file", s);
274
274
  const p = new XMLHttpRequest();
275
- if (t && (t.addEventListener("abort", () => {
275
+ if (a && (a.addEventListener("abort", () => {
276
276
  p.abort(), d(new DOMException("Aborted", "AbortError"));
277
- }), t.aborted)) {
277
+ }), a.aborted)) {
278
278
  d(new DOMException("Aborted", "AbortError"));
279
279
  return;
280
280
  }
281
- p.upload.addEventListener("progress", (b) => {
282
- if (b.lengthComputable && n) {
283
- const y = Math.round(b.loaded / b.total * 100);
281
+ p.upload.addEventListener("progress", (v) => {
282
+ if (v.lengthComputable && n) {
283
+ const y = Math.round(v.loaded / v.total * 100);
284
284
  n(y);
285
285
  }
286
286
  }), p.addEventListener("load", () => {
287
287
  if (p.status >= 200 && p.status < 300)
288
288
  try {
289
- const b = JSON.parse(p.responseText);
290
- c(b);
291
- } catch (b) {
292
- d(new Error(`Failed to parse response: ${b}`));
289
+ const v = JSON.parse(p.responseText);
290
+ l(v);
291
+ } catch (v) {
292
+ d(new Error(`Failed to parse response: ${v}`));
293
293
  }
294
294
  else
295
295
  d(new Error(`Upload failed with status: ${p.status}`));
@@ -298,43 +298,43 @@ class U {
298
298
  }), p.addEventListener("timeout", () => {
299
299
  d(new Error("Upload timed out"));
300
300
  });
301
- const { baseUrl: u } = this.constructClientOptions(this.userToken), k = `${u}/backend/widget/v2/upload`;
302
- p.open("POST", k), p.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((f = this.config.user) == null ? void 0 : f.token) ? p.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : g.error("user token not set"), p.send(_);
303
- }), this.vote = async (s) => await this.client.POST("/backend/widget/v2/chat/vote", { body: s }), this.resolveSession = async (s, t) => await this.client.POST("/backend/widget/v2/session/resolve", {
301
+ const { baseUrl: u } = this.constructClientOptions(this.userToken), g = `${u}/backend/widget/v2/upload`;
302
+ p.open("POST", g), p.setRequestHeader("X-Bot-Token", this.config.token), this.userToken ?? ((f = this.config.user) == null ? void 0 : f.token) ? p.setRequestHeader("Authorization", `Bearer ${this.userToken}`) : k.error("user token not set"), p.send(_);
303
+ }), this.vote = async (s) => await this.client.POST("/backend/widget/v2/chat/vote", { body: s }), this.resolveSession = async (s, a) => await this.client.POST("/backend/widget/v2/session/resolve", {
304
304
  body: s,
305
- signal: t
305
+ signal: a
306
306
  }), this.createStateCheckpoint = async (s) => await this.client.POST("/backend/widget/v2/checkpoint", {
307
307
  body: s
308
308
  }), this.submitCsat = async (s) => await this.client.POST("/backend/widget/v2/submit-csat", { body: s }), this.config = e, this.userToken = ((r = e.user) == null ? void 0 : r.token) || null;
309
- const { baseUrl: a, headers: o } = this.constructClientOptions(
310
- (l = e.user) == null ? void 0 : l.token
309
+ const { baseUrl: t, headers: o } = this.constructClientOptions(
310
+ (c = e.user) == null ? void 0 : c.token
311
311
  );
312
- this.client = this.createOpenAPIClient({ baseUrl: a, headers: o });
312
+ this.client = this.createOpenAPIClient({ baseUrl: t, headers: o });
313
313
  }
314
314
  }
315
315
  function ue(i, e) {
316
- g.error(`missing case for ${i} in ${e}`);
316
+ k.error(`missing case for ${i} in ${e}`);
317
317
  }
318
318
  class S {
319
319
  constructor(e) {
320
- this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (a) => {
321
- se(this.state, a) || (this.state = a, this.notifySubscribers(a));
322
- }, this.setPartial = (a) => {
323
- if (a == null) return;
324
- const o = { ...this.state, ...a };
320
+ this.subscribers = /* @__PURE__ */ new Set(), this.get = () => this.state, this.set = (t) => {
321
+ se(this.state, t) || (this.state = t, this.notifySubscribers(t));
322
+ }, this.setPartial = (t) => {
323
+ if (t == null) return;
324
+ const o = { ...this.state, ...t };
325
325
  this.set(o);
326
326
  }, this.reset = () => {
327
327
  this.set(this.initialState);
328
- }, this.notifySubscribers = (a) => {
328
+ }, this.notifySubscribers = (t) => {
329
329
  Array.from(this.subscribers).forEach((r) => {
330
330
  try {
331
- r(a);
332
- } catch (l) {
333
- g.error("state subscriber threw", l);
331
+ r(t);
332
+ } catch (c) {
333
+ k.error("state subscriber threw", c);
334
334
  }
335
335
  });
336
- }, this.subscribe = (a) => (this.subscribers.add(a), () => {
337
- this.subscribers.delete(a);
336
+ }, this.subscribe = (t) => (this.subscribers.add(t), () => {
337
+ this.subscribers.delete(t);
338
338
  }), this.state = e, this.initialState = e;
339
339
  }
340
340
  }
@@ -346,20 +346,20 @@ class Z {
346
346
  }), this.abortController = new AbortController(), this.reset = () => {
347
347
  var e;
348
348
  this.abortController.abort("Resetting poller"), (e = this.stopPolling) == null || e.call(this), this.stopPolling = null;
349
- }, this.stopPolling = null, this.startPolling = (e, a) => {
349
+ }, this.stopPolling = null, this.startPolling = (e, t) => {
350
350
  if (this.stopPolling) return;
351
351
  const o = [], r = async () => {
352
352
  this.abortController = new AbortController(), this.state.setPartial({ isPolling: !0 });
353
353
  try {
354
354
  await e(this.abortController.signal);
355
- } catch (l) {
355
+ } catch (c) {
356
356
  if (this.abortController.signal.aborted)
357
357
  return;
358
- g.error("failed to poll", l), this.state.setPartial({ isError: !0 });
358
+ k.error("failed to poll", c), this.state.setPartial({ isError: !0 });
359
359
  } finally {
360
360
  this.state.setPartial({ isPolling: !1 });
361
361
  }
362
- this.abortController.signal.aborted || o.push(setTimeout(r, a));
362
+ this.abortController.signal.aborted || o.push(setTimeout(r, t));
363
363
  };
364
364
  r(), this.stopPolling = () => {
365
365
  o.forEach(clearTimeout), this.state.reset();
@@ -370,7 +370,7 @@ class Z {
370
370
  function W(i) {
371
371
  try {
372
372
  const e = i();
373
- return e instanceof Promise ? e.then((a) => ({ data: a })).catch((a) => ({ error: a })) : { data: e };
373
+ return e instanceof Promise ? e.then((t) => ({ data: t })).catch((t) => ({ error: t })) : { data: e };
374
374
  } catch (e) {
375
375
  return { error: e };
376
376
  }
@@ -378,18 +378,18 @@ function W(i) {
378
378
  class me {
379
379
  constructor({
380
380
  api: e,
381
- config: a,
381
+ config: t,
382
382
  sessionCtx: o,
383
383
  messageCtx: r,
384
- sessionPollingIntervalSeconds: l
384
+ sessionPollingIntervalSeconds: c
385
385
  }) {
386
386
  this.poller = new Z(), this.fetchSessionAndFullHistoryAbortController = new AbortController(), this.reconcileAbortController = new AbortController(), this.subscriptions = [], this.reconcilingSessionId = null, this.registerPolling = () => {
387
387
  this.subscriptions.push(
388
388
  this.sessionCtx.sessionState.subscribe(({ session: s }) => {
389
- s != null && s.id ? this.poller.startPolling(async (t) => {
389
+ s != null && s.id ? this.poller.startPolling(async (a) => {
390
390
  this.fetchSessionAndHistory({
391
391
  sessionId: s.id,
392
- abortSignal: t
392
+ abortSignal: a
393
393
  });
394
394
  }, this.sessionPollingIntervalSeconds * 1e3) : this.poller.reset();
395
395
  })
@@ -401,8 +401,8 @@ class me {
401
401
  sessionId: s.id,
402
402
  abortSignal: this.fetchSessionAndFullHistoryAbortController.signal
403
403
  });
404
- } catch (t) {
405
- this.fetchSessionAndFullHistoryAbortController.signal.aborted || g.error("failed to fetch session and full history", t);
404
+ } catch (a) {
405
+ this.fetchSessionAndFullHistoryAbortController.signal.aborted || k.error("failed to fetch session and full history", a);
406
406
  }
407
407
  else
408
408
  this.fetchSessionAndFullHistoryAbortController.abort();
@@ -416,27 +416,28 @@ class me {
416
416
  this.poller.reset(), this.fetchSessionAndFullHistoryAbortController.abort(), this.reconcileAbortController.abort(), this.reconcilingSessionId = null, this.subscriptions.forEach((s) => s()), this.subscriptions = [];
417
417
  }, this.reconcileAfterStream = async (s) => {
418
418
  this.reconcileAbortController.abort(), this.reconcileAbortController = new AbortController();
419
- const { signal: t } = this.reconcileAbortController;
419
+ const { signal: a } = this.reconcileAbortController;
420
420
  this.reconcilingSessionId = s;
421
421
  try {
422
- await this.fetchSessionAndHistory({ sessionId: s, abortSignal: t });
422
+ await this.fetchSessionAndHistory({ sessionId: s, abortSignal: a });
423
423
  } catch (n) {
424
- if (!t.aborted) throw n;
424
+ if (!a.aborted) throw n;
425
425
  } finally {
426
426
  this.reconcilingSessionId === s && (this.reconcilingSessionId = null);
427
427
  }
428
428
  }, this.fetchSessionAndHistory = async ({
429
429
  sessionId: s,
430
- abortSignal: t
430
+ abortSignal: a
431
431
  }) => {
432
432
  const n = this.messageCtx.state.get().messages.length === 0;
433
433
  n && this.messageCtx.state.setPartial({ isInitialFetchLoading: !0 });
434
- const { data: c } = await this.api.pollSessionAndHistory({
434
+ const { data: l } = await this.api.pollSessionAndHistory({
435
435
  sessionId: s,
436
- abortSignal: t
436
+ abortSignal: a
437
437
  });
438
- if (c != null && c.session && (this.sessionCtx.sessionState.setPartial({ session: c.session }), this.sessionCtx.setSessions([c.session])), c != null && c.history && c.history.length > 0) {
439
- const d = this.messageCtx.state.get().messages, _ = c.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
438
+ if (l != null && l.session && (this.sessionCtx.sessionState.setPartial({ session: l.session }), this.sessionCtx.setSessions([l.session])), l != null && l.history && l.history.length > 0) {
439
+ this.reconcileOptionPicks(l.history);
440
+ const d = this.messageCtx.state.get().messages, _ = l.history.map(this.mapHistoryToMessage).filter((p) => p !== null).filter(
440
441
  (p) => !d.some((u) => u.id === p.id)
441
442
  );
442
443
  if (_.length > 0)
@@ -451,25 +452,31 @@ class me {
451
452
  this.messageCtx.dispatchToOnMessageReceivedHook(p);
452
453
  }
453
454
  this.messageCtx.state.get().isInitialFetchLoading && this.messageCtx.state.setPartial({ isInitialFetchLoading: !1 });
455
+ }, this.reconcileOptionPicks = (s) => {
456
+ var a;
457
+ for (const n of s) {
458
+ const l = (a = n.messageOptions) == null ? void 0 : a.pickedOptionId;
459
+ l && this.messageCtx.setMessageOptionPick(n.publicId, l);
460
+ }
454
461
  }, this.mapHistoryToMessage = (s) => {
455
462
  var n;
456
- const t = {
463
+ const a = {
457
464
  id: s.publicId,
458
465
  timestamp: s.sentAt || "",
459
466
  attachments: s.attachments || void 0
460
467
  };
461
468
  if (s.sender.kind === "user")
462
469
  return {
463
- ...t,
470
+ ...a,
464
471
  type: "USER",
465
- deliveredAt: t.timestamp,
472
+ deliveredAt: a.timestamp,
466
473
  content: s.content.text || "",
467
474
  // Backend field name (schema.ts) → widget vocabulary.
468
475
  markedElements: s.pickedElements
469
476
  };
470
477
  if (s.sender.kind === "agent")
471
478
  return {
472
- ...t,
479
+ ...a,
473
480
  type: "AGENT",
474
481
  component: "agent_message",
475
482
  data: {
@@ -484,12 +491,13 @@ class me {
484
491
  id: null,
485
492
  isAi: !1
486
493
  },
487
- ...this.constructReplyTo(s)
494
+ ...this.constructReplyTo(s),
495
+ ...s.messageOptions ? { messageOptions: s.messageOptions } : {}
488
496
  };
489
497
  if (s.sender.kind === "ai") {
490
- const c = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
498
+ const l = s.actionCalls && s.actionCalls.length > 0 ? s.actionCalls[s.actionCalls.length - 1] : void 0;
491
499
  return {
492
- ...t,
500
+ ...a,
493
501
  type: "AI",
494
502
  component: "bot_message",
495
503
  agent: {
@@ -502,27 +510,27 @@ class me {
502
510
  },
503
511
  data: {
504
512
  message: s.content.text || "",
505
- action: c ? {
506
- name: c.actionName,
507
- data: this.extractActionResult(c)
513
+ action: l ? {
514
+ name: l.actionName,
515
+ data: this.extractActionResult(l)
508
516
  } : void 0
509
517
  },
510
518
  ...this.constructReplyTo(s)
511
519
  };
512
520
  }
513
521
  if (s.sender.kind === "system") {
514
- const c = this.constructSystemMessage(s);
515
- return c === null ? null : { ...c };
522
+ const l = this.constructSystemMessage(s);
523
+ return l === null ? null : { ...l };
516
524
  }
517
525
  return null;
518
526
  }, this.constructReplyTo = (s) => {
519
527
  if (!s.replyTo) return {};
520
- const { publicId: t, text: n, sender: c } = s.replyTo;
528
+ const { publicId: a, text: n, sender: l } = s.replyTo;
521
529
  return {
522
530
  replyTo: {
523
- id: t,
531
+ id: a,
524
532
  text: n,
525
- sender: c
533
+ sender: l
526
534
  }
527
535
  };
528
536
  }, this.constructSystemMessage = (s) => {
@@ -569,33 +577,33 @@ class me {
569
577
  ), null;
570
578
  }
571
579
  }, this.extractActionResult = (s) => {
572
- const t = s.result;
573
- if (t === null || typeof t != "object") return t;
574
- if ("responseBodyText" in t && typeof t.responseBodyText == "string") {
575
- const n = t.responseBodyText, c = W(() => JSON.parse(n)).data;
576
- if (c) return c;
580
+ const a = s.result;
581
+ if (a === null || typeof a != "object") return a;
582
+ if ("responseBodyText" in a && typeof a.responseBodyText == "string") {
583
+ const n = a.responseBodyText, l = W(() => JSON.parse(n)).data;
584
+ if (l) return l;
577
585
  }
578
586
  return s.result;
579
- }, this.api = e, this.config = a, this.sessionCtx = o, this.messageCtx = r, this.sessionPollingIntervalSeconds = l, this.registerPolling();
587
+ }, this.api = e, this.config = t, this.sessionCtx = o, this.messageCtx = r, this.sessionPollingIntervalSeconds = c, this.registerPolling();
580
588
  }
581
589
  }
582
590
  class he {
583
591
  constructor({
584
592
  config: e,
585
- api: a,
593
+ api: t,
586
594
  storageCtx: o
587
595
  }) {
588
596
  var r;
589
597
  this.shouldCollectData = () => {
590
- var l;
591
- return !!(!((l = this.state.get().contact) != null && l.token) && this.config.collectUserData);
598
+ var c;
599
+ return !!(!((c = this.state.get().contact) != null && c.token) && this.config.collectUserData);
592
600
  }, this.autoCreateUnverifiedUserIfNotExists = async () => {
593
- var l, s, t, n, c, d, _, p, u, h, k, v, f, b;
594
- if (!((l = this.config.user) != null && l.token)) {
595
- if (this.config.collectUserData && !((t = (s = this.config.user) == null ? void 0 : s.data) != null && t.email)) {
601
+ var c, s, a, n, l, d, _, p, u, m, g, b, f, v;
602
+ if (!((c = this.config.user) != null && c.token)) {
603
+ if (this.config.collectUserData && !((a = (s = this.config.user) == null ? void 0 : s.data) != null && a.email)) {
596
604
  if ((n = this.config.extraDataCollectionFields) != null && n.length)
597
605
  return;
598
- const y = await ((c = this.storageCtx) == null ? void 0 : c.getContactToken());
606
+ const y = await ((l = this.storageCtx) == null ? void 0 : l.getContactToken());
599
607
  y && await this.setUnverifiedContact(y);
600
608
  return;
601
609
  }
@@ -607,48 +615,48 @@ class he {
607
615
  }
608
616
  }
609
617
  await this.createUnverifiedContact({
610
- email: (h = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : h.email,
611
- non_verified_name: (v = (k = this.config.user) == null ? void 0 : k.data) == null ? void 0 : v.name,
612
- non_verified_custom_data: (b = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : b.customData
618
+ email: (m = (u = this.config.user) == null ? void 0 : u.data) == null ? void 0 : m.email,
619
+ non_verified_name: (b = (g = this.config.user) == null ? void 0 : g.data) == null ? void 0 : b.name,
620
+ non_verified_custom_data: (v = (f = this.config.user) == null ? void 0 : f.data) == null ? void 0 : v.customData
613
621
  });
614
622
  }
615
- }, this.createUnverifiedContact = async (l, s) => {
623
+ }, this.createUnverifiedContact = async (c, s) => {
616
624
  this.state.setPartial({ extraCollectedData: s });
617
625
  try {
618
626
  this.state.setPartial({
619
627
  isCreatingUnverifiedContact: !0,
620
628
  isErrorCreatingUnverifiedContact: !1
621
629
  });
622
- const { data: t } = await this.api.createUnverifiedContact(l);
623
- t != null && t.token ? await this.setUnverifiedContact(t.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
624
- } catch (t) {
625
- this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), g.error("failed to create an unverified contact", {
626
- _e: t instanceof Error ? t.message : String(t)
630
+ const { data: a } = await this.api.createUnverifiedContact(c);
631
+ a != null && a.token ? await this.setUnverifiedContact(a.token) : this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 });
632
+ } catch (a) {
633
+ this.state.setPartial({ isErrorCreatingUnverifiedContact: !0 }), k.error("failed to create an unverified contact", {
634
+ _e: a instanceof Error ? a.message : String(a)
627
635
  });
628
636
  } finally {
629
637
  this.state.setPartial({ isCreatingUnverifiedContact: !1 });
630
638
  }
631
639
  }, this.recoverFromStaleToken = async () => {
632
- var l, s, t, n, c, d, _, p, u, h;
633
- if ((l = this.config.user) != null && l.token) return !1;
640
+ var c, s, a, n, l, d, _, p, u, m;
641
+ if ((c = this.config.user) != null && c.token) return !1;
634
642
  this.api.setAuthToken(""), this.state.setPartial({ contact: null });
635
643
  try {
636
- await ((s = this.storageCtx) == null ? void 0 : s.clearContactToken()), await ((t = this.storageCtx) == null ? void 0 : t.clearActiveSessionId());
637
- } catch (k) {
638
- g.warn("failed to clear a stale contact token", {
639
- error: k instanceof Error ? k.message : String(k)
644
+ await ((s = this.storageCtx) == null ? void 0 : s.clearContactToken()), await ((a = this.storageCtx) == null ? void 0 : a.clearActiveSessionId());
645
+ } catch (g) {
646
+ k.warn("failed to clear a stale contact token", {
647
+ error: g instanceof Error ? g.message : String(g)
640
648
  });
641
649
  }
642
650
  return await this.createUnverifiedContact({
643
- email: (c = (n = this.config.user) == null ? void 0 : n.data) == null ? void 0 : c.email,
651
+ email: (l = (n = this.config.user) == null ? void 0 : n.data) == null ? void 0 : l.email,
644
652
  non_verified_name: (_ = (d = this.config.user) == null ? void 0 : d.data) == null ? void 0 : _.name,
645
653
  non_verified_custom_data: (u = (p = this.config.user) == null ? void 0 : p.data) == null ? void 0 : u.customData
646
- }), !!((h = this.state.get().contact) != null && h.token);
647
- }, this.setUnverifiedContact = async (l) => {
648
- var n, c, d, _;
649
- const s = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), t = ((c = this.config.user) == null ? void 0 : c.externalId) || s || N();
650
- this.api.setAuthToken(l), await ((d = this.storageCtx) == null ? void 0 : d.setContactToken(l)), await ((_ = this.storageCtx) == null ? void 0 : _.setExternalContactId(t)), this.state.setPartial({ contact: { token: l, externalId: t } });
651
- }, this.config = e, this.storageCtx = o, this.api = a, this.state = new S({
654
+ }), !!((m = this.state.get().contact) != null && m.token);
655
+ }, this.setUnverifiedContact = async (c) => {
656
+ var n, l, d, _;
657
+ const s = await ((n = this.storageCtx) == null ? void 0 : n.getExternalContactId()), a = ((l = this.config.user) == null ? void 0 : l.externalId) || s || N();
658
+ this.api.setAuthToken(c), await ((d = this.storageCtx) == null ? void 0 : d.setContactToken(c)), await ((_ = this.storageCtx) == null ? void 0 : _.setExternalContactId(a)), this.state.setPartial({ contact: { token: c, externalId: a } });
659
+ }, this.config = e, this.storageCtx = o, this.api = t, this.state = new S({
652
660
  contact: (r = e.user) != null && r.token ? {
653
661
  token: e.user.token,
654
662
  // Set optional externalId from config... not local storage
@@ -662,8 +670,8 @@ class he {
662
670
  }
663
671
  class ge {
664
672
  constructor(e) {
665
- this.api = e, this.state = new S([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (a) => {
666
- const o = a.map(
673
+ this.api = e, this.state = new S([]), this.controllers = /* @__PURE__ */ new Map(), this.appendFiles = (t) => {
674
+ const o = t.map(
667
675
  (r) => ({
668
676
  file: r,
669
677
  id: N(),
@@ -672,25 +680,25 @@ class ge {
672
680
  })
673
681
  );
674
682
  this.state.set([...this.state.get(), ...o]), o.forEach((r) => void this.upload(r));
675
- }, this.cancel = (a) => {
683
+ }, this.cancel = (t) => {
676
684
  var o;
677
- (o = this.controllers.get(a)) == null || o.abort(), this.controllers.delete(a), this.state.set(this.state.get().filter((r) => r.id !== a));
685
+ (o = this.controllers.get(t)) == null || o.abort(), this.controllers.delete(t), this.state.set(this.state.get().filter((r) => r.id !== t));
678
686
  }, this.reset = () => {
679
- this.controllers.forEach((a) => a.abort()), this.controllers.clear(), this.state.reset();
687
+ this.controllers.forEach((t) => t.abort()), this.controllers.clear(), this.state.reset();
680
688
  };
681
689
  }
682
- update(e, a) {
690
+ update(e, t) {
683
691
  this.state.set(
684
- this.state.get().map((o) => o.id === e ? { ...o, ...a } : o)
692
+ this.state.get().map((o) => o.id === e ? { ...o, ...t } : o)
685
693
  );
686
694
  }
687
695
  async upload(e) {
688
- const a = new AbortController();
689
- this.controllers.set(e.id, a), this.update(e.id, { status: "uploading" });
696
+ const t = new AbortController();
697
+ this.controllers.set(e.id, t), this.update(e.id, { status: "uploading" });
690
698
  try {
691
699
  const o = await this.api.uploadFile({
692
700
  file: e.file,
693
- abortSignal: a.signal,
701
+ abortSignal: t.signal,
694
702
  onProgress: (r) => this.update(e.id, { progress: r })
695
703
  });
696
704
  this.update(e.id, {
@@ -699,7 +707,7 @@ class ge {
699
707
  progress: 100
700
708
  });
701
709
  } catch (o) {
702
- a.signal.aborted || this.update(e.id, {
710
+ t.signal.aborted || this.update(e.id, {
703
711
  status: "error",
704
712
  progress: 0,
705
713
  error: o instanceof Error ? o.message : "Upload failed"
@@ -715,13 +723,13 @@ function q() {
715
723
  class ke {
716
724
  constructor({
717
725
  api: e,
718
- sessionCtx: a,
726
+ sessionCtx: t,
719
727
  messageCtx: o
720
728
  }) {
721
729
  this.submitCsat = async (r) => {
722
- var c;
723
- const l = (c = this.sessionCtx.sessionState.get().session) == null ? void 0 : c.id;
724
- if (!l)
730
+ var l;
731
+ const c = (l = this.sessionCtx.sessionState.get().session) == null ? void 0 : l.id;
732
+ if (!c)
725
733
  return { data: null, error: "No session id found" };
726
734
  const s = q();
727
735
  this.messageCtx.state.setPartial({
@@ -741,13 +749,13 @@ class ke {
741
749
  }
742
750
  ]
743
751
  });
744
- const { data: t, error: n } = await this.api.submitCsat({
752
+ const { data: a, error: n } = await this.api.submitCsat({
745
753
  ...r,
746
754
  system_message_uuid: s,
747
- session_id: l
755
+ session_id: c
748
756
  });
749
- return { data: t, error: n };
750
- }, this.api = e, this.sessionCtx = a, this.messageCtx = o;
757
+ return { data: a, error: n };
758
+ }, this.api = e, this.sessionCtx = t, this.messageCtx = o;
751
759
  }
752
760
  }
753
761
  const be = [
@@ -842,16 +850,16 @@ function ye(i) {
842
850
  function we(i) {
843
851
  const e = be.flatMap(
844
852
  (r) => i.flatMap(
845
- (l) => r.phrases[l].map((s) => ({ phrase: s, action: r.action }))
853
+ (c) => r.phrases[c].map((s) => ({ phrase: s, action: r.action }))
846
854
  )
847
- ), a = e.map((r) => ye(r.phrase)).sort((r, l) => l.length - r.length).join("|"), o = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
855
+ ), t = e.map((r) => ye(r.phrase)).sort((r, c) => c.length - r.length).join("|"), o = String.raw`(?<=^\s{0,3}|[.!?\n]\s{0,3})`;
848
856
  return {
849
857
  regex: new RegExp(
850
- `${o}(${a})` + String.raw`([.,!?;:])(?=\s|$)`,
858
+ `${o}(${t})` + String.raw`([.,!?;:])(?=\s|$)`,
851
859
  "giu"
852
860
  ),
853
861
  finalRegex: new RegExp(
854
- `${o}(${a})` + String.raw`([.,!?;:]?)(?=\s|$)`,
862
+ `${o}(${t})` + String.raw`([.,!?;:]?)(?=\s|$)`,
855
863
  "giu"
856
864
  ),
857
865
  phraseToAction: new Map(
@@ -862,24 +870,24 @@ function we(i) {
862
870
  }
863
871
  const B = /* @__PURE__ */ new Map();
864
872
  function M(i) {
865
- const e = i && fe(i) && i !== "en" ? i : null, a = e ?? "en";
866
- let o = B.get(a);
867
- return o || (o = we(e ? ["en", e] : ["en"]), B.set(a, o)), o;
873
+ const e = i && fe(i) && i !== "en" ? i : null, t = e ?? "en";
874
+ let o = B.get(t);
875
+ return o || (o = we(e ? ["en", e] : ["en"]), B.set(t, o)), o;
868
876
  }
869
877
  function je(i) {
870
878
  const e = i.replace(/\s+$/, "");
871
879
  if (!e) return "";
872
- const a = e.replace(/[.!?]+$/, "");
880
+ const t = e.replace(/[.!?]+$/, "");
873
881
  let o = -1;
874
- for (let r = a.length - 1; r >= 0; r--) {
875
- const l = a[r];
876
- if (l === "." || l === "!" || l === "?" || l === `
882
+ for (let r = t.length - 1; r >= 0; r--) {
883
+ const c = t[r];
884
+ if (c === "." || c === "!" || c === "?" || c === `
877
885
  `) {
878
886
  o = r + 1;
879
887
  break;
880
888
  }
881
889
  }
882
- return o === -1 ? "" : `${a.slice(0, o)} `.replace(/\n $/, `
890
+ return o === -1 ? "" : `${t.slice(0, o)} `.replace(/\n $/, `
883
891
  `);
884
892
  }
885
893
  const Se = new RegExp(
@@ -889,7 +897,7 @@ const Se = new RegExp(
889
897
  function ze(i) {
890
898
  return i.replace(
891
899
  Se,
892
- (e, a, o) => a + o.toUpperCase()
900
+ (e, t, o) => t + o.toUpperCase()
893
901
  );
894
902
  }
895
903
  function Ce(i) {
@@ -901,31 +909,31 @@ class E {
901
909
  * Pure and deterministic: always called with the entire raw string so the
902
910
  * result never depends on delta chunking.
903
911
  */
904
- static process(e, a) {
905
- const o = M(a == null ? void 0 : a.language), r = a != null && a.final ? "" : E.commandPrefixTail(e, a == null ? void 0 : a.language), l = e.slice(0, e.length - r.length), s = a != null && a.final ? o.finalRegex : o.regex;
906
- let t = "", n = null, c = 0;
907
- for (const _ of Array.from(l.matchAll(s))) {
912
+ static process(e, t) {
913
+ const o = M(t == null ? void 0 : t.language), r = t != null && t.final ? "" : E.commandPrefixTail(e, t == null ? void 0 : t.language), c = e.slice(0, e.length - r.length), s = t != null && t.final ? o.finalRegex : o.regex;
914
+ let a = "", n = null, l = 0;
915
+ for (const _ of Array.from(c.matchAll(s))) {
908
916
  const [, p = ""] = _, u = o.phraseToAction.get(p.toLowerCase());
909
917
  if (u)
910
- if (t += l.slice(c, _.index), c = _.index + _[0].length, u === "newline") t = `${t.replace(/[ \t]+$/, "")}
918
+ if (a += c.slice(l, _.index), l = _.index + _[0].length, u === "newline") a = `${a.replace(/[ \t]+$/, "")}
911
919
  `;
912
920
  else if (u === "newparagraph")
913
- t = `${t.replace(/[ \t]+$/, "")}
921
+ a = `${a.replace(/[ \t]+$/, "")}
914
922
 
915
923
  `;
916
924
  else if (u === "bullet") {
917
- const h = t.replace(/[ \t]+$/, "");
918
- t = h === "" || h.endsWith(`
919
- `) ? `${h}- ` : `${h}
925
+ const m = a.replace(/[ \t]+$/, "");
926
+ a = m === "" || m.endsWith(`
927
+ `) ? `${m}- ` : `${m}
920
928
  - `;
921
- } else if (u === "scratch") t = je(t);
929
+ } else if (u === "scratch") a = je(a);
922
930
  else {
923
931
  n = u === "send" ? "send" : "stop";
924
932
  break;
925
933
  }
926
934
  }
927
- return n === null && (t += l.slice(c)), { text: ze(
928
- t.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
935
+ return n === null && (a += c.slice(l)), { text: ze(
936
+ a.replace(/^\s+/, "").replace(/[ \t]+\n/g, `
929
937
  `).replace(/\n[ \t]+/g, `
930
938
  `).replace(/(^|\n)- +/g, "$1- ").replace(/ {2,}/g, " ").replace(/\n{3,}/g, `
931
939
 
@@ -941,16 +949,16 @@ class E {
941
949
  * control command from an intermediate delta would stop or submit
942
950
  * mid-sentence.
943
951
  */
944
- static commandPrefixTail(e, a) {
945
- const o = M(a), r = Math.min(e.length, o.longestPhrase + 2);
946
- for (let l = r; l > 0; l--) {
947
- const s = e.length - l;
952
+ static commandPrefixTail(e, t) {
953
+ const o = M(t), r = Math.min(e.length, o.longestPhrase + 2);
954
+ for (let c = r; c > 0; c--) {
955
+ const s = e.length - c;
948
956
  if (!Ce(e.slice(0, s))) continue;
949
- const t = e.slice(s).toLowerCase(), n = t.replace(/^\s+/, "");
957
+ const a = e.slice(s).toLowerCase(), n = a.replace(/^\s+/, "");
950
958
  if (n) {
951
- for (const c of Array.from(o.phraseToAction.keys()))
952
- if (c.startsWith(n))
953
- return e.slice(s + (t.length - n.length));
959
+ for (const l of Array.from(o.phraseToAction.keys()))
960
+ if (l.startsWith(n))
961
+ return e.slice(s + (a.length - n.length));
954
962
  }
955
963
  }
956
964
  return "";
@@ -960,9 +968,9 @@ class E {
960
968
  * prefix) — i.e. a silence pause would resolve it into a command. Used by
961
969
  * the manager's silence timer.
962
970
  */
963
- static pendingTailIsCompletePhrase(e, a) {
964
- const o = E.commandPrefixTail(e, a).trim().toLowerCase();
965
- return o ? M(a).phraseToAction.has(o) : !1;
971
+ static pendingTailIsCompletePhrase(e, t) {
972
+ const o = E.commandPrefixTail(e, t).trim().toLowerCase();
973
+ return o ? M(t).phraseToAction.has(o) : !1;
966
974
  }
967
975
  }
968
976
  const xe = 55, qe = 90;
@@ -975,23 +983,23 @@ class V {
975
983
  */
976
984
  static nextDripText({
977
985
  displayed: e,
978
- processed: a
986
+ processed: t
979
987
  }) {
980
- if (a.length <= e.length) return a;
981
- const o = a.length - e.length;
988
+ if (t.length <= e.length) return t;
989
+ const o = t.length - e.length;
982
990
  if (o > qe)
983
- return a.slice(0, e.length + Math.ceil(o / 3));
991
+ return t.slice(0, e.length + Math.ceil(o / 3));
984
992
  let r = e.length;
985
- for (; r < a.length && /\s/.test(a.charAt(r)); ) r++;
986
- for (; r < a.length && !/\s/.test(a.charAt(r)); ) r++;
987
- return r - e.length > 12 && (r = e.length + 6), a.slice(0, Math.max(r, e.length + 1));
993
+ for (; r < t.length && /\s/.test(t.charAt(r)); ) r++;
994
+ for (; r < t.length && !/\s/.test(t.charAt(r)); ) r++;
995
+ return r - e.length > 12 && (r = e.length + 6), t.slice(0, Math.max(r, e.length + 1));
988
996
  }
989
997
  /** Normalize a BCP-47 browser locale into the hint OpenAI accepts. */
990
998
  static languageHint(e) {
991
999
  if (!e) return;
992
- const a = e.toLowerCase();
993
- if (/^zh-(cn|tw|hk)$/.test(a)) return a;
994
- const o = a.split("-")[0];
1000
+ const t = e.toLowerCase();
1001
+ if (/^zh-(cn|tw|hk)$/.test(t)) return t;
1002
+ const o = t.split("-")[0];
995
1003
  return o && /^[a-z]{2,3}$/.test(o) ? o : void 0;
996
1004
  }
997
1005
  }
@@ -1011,8 +1019,8 @@ class Ae {
1011
1019
  * click reuses the same in-flight promise instead of double-minting).
1012
1020
  */
1013
1021
  async resolve(e) {
1014
- const a = this.get();
1015
- return a || (this.inflight || (this.inflight = e().then((o) => (this.cached = o, o)).finally(() => {
1022
+ const t = this.get();
1023
+ return t || (this.inflight || (this.inflight = e().then((o) => (this.cached = o, o)).finally(() => {
1016
1024
  this.inflight = null;
1017
1025
  })), this.inflight);
1018
1026
  }
@@ -1039,12 +1047,12 @@ class T extends Error {
1039
1047
  class Ne {
1040
1048
  constructor({
1041
1049
  mintToken: e,
1042
- onDelta: a,
1050
+ onDelta: t,
1043
1051
  onState: o,
1044
1052
  onError: r,
1045
- onLevel: l
1053
+ onLevel: c
1046
1054
  }) {
1047
- 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 = o, this.onError = r, this.onLevel = l;
1055
+ 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 = r, this.onLevel = c;
1048
1056
  }
1049
1057
  async start() {
1050
1058
  if (this.state === "idle") {
@@ -1059,17 +1067,17 @@ class Ne {
1059
1067
  this.isTornDown() || this.stream && this.stream !== d ? d.getTracks().forEach((_) => _.stop()) : this.stream = d;
1060
1068
  }).catch(() => {
1061
1069
  });
1062
- const [a, o] = await Promise.all([e, this.mintToken()]);
1070
+ const [t, o] = await Promise.all([e, this.mintToken()]);
1063
1071
  if (this.isTornDown()) {
1064
- a.getTracks().forEach((d) => d.stop());
1072
+ t.getTracks().forEach((d) => d.stop());
1065
1073
  return;
1066
1074
  }
1067
- this.stream = a, this.startLevelMeter(a);
1075
+ this.stream = t, this.startLevelMeter(t);
1068
1076
  const r = new RTCPeerConnection();
1069
1077
  this.pc = r;
1070
- const [l] = a.getAudioTracks();
1071
- if (!l) throw new T("No audio track");
1072
- r.addTrack(l, a);
1078
+ const [c] = t.getAudioTracks();
1079
+ if (!c) throw new T("No audio track");
1080
+ r.addTrack(c, t);
1073
1081
  const s = r.createDataChannel("oai-events");
1074
1082
  this.dc = s, s.addEventListener(
1075
1083
  "message",
@@ -1087,23 +1095,23 @@ class Ne {
1087
1095
  }, De)
1088
1096
  );
1089
1097
  });
1090
- const t = await r.createOffer();
1091
- if (this.isTornDown() || (await r.setLocalDescription(t), this.isTornDown())) return;
1098
+ const a = await r.createOffer();
1099
+ if (this.isTornDown() || (await r.setLocalDescription(a), this.isTornDown())) return;
1092
1100
  const n = await fetch(Te, {
1093
1101
  method: "POST",
1094
1102
  headers: {
1095
1103
  Authorization: `Bearer ${o.token}`,
1096
1104
  "Content-Type": "application/sdp"
1097
1105
  },
1098
- body: t.sdp
1106
+ body: a.sdp
1099
1107
  });
1100
1108
  if (!n.ok)
1101
1109
  throw new Error(`Realtime handshake failed (${n.status})`);
1102
- const c = await n.text();
1110
+ const l = await n.text();
1103
1111
  if (this.isTornDown()) return;
1104
- await r.setRemoteDescription({ type: "answer", sdp: c });
1112
+ await r.setRemoteDescription({ type: "answer", sdp: l });
1105
1113
  } catch (e) {
1106
- e instanceof T ? this.fail("microphone") : (g.error("dictation session failed to start", {
1114
+ e instanceof T ? this.fail("microphone") : (k.error("dictation session failed to start", {
1107
1115
  _e: e instanceof Error ? e.message : String(e)
1108
1116
  }), this.fail("unavailable"));
1109
1117
  }
@@ -1124,60 +1132,60 @@ class Ne {
1124
1132
  autoGainControl: !0
1125
1133
  }
1126
1134
  });
1127
- } catch (a) {
1135
+ } catch (t) {
1128
1136
  throw new T(
1129
- a instanceof DOMException ? a.name : "Could not access the microphone"
1137
+ t instanceof DOMException ? t.name : "Could not access the microphone"
1130
1138
  );
1131
1139
  }
1132
1140
  }
1133
1141
  handleServerEvent(e) {
1134
1142
  if (typeof e != "string") return;
1135
- let a;
1143
+ let t;
1136
1144
  try {
1137
- a = JSON.parse(e);
1145
+ t = JSON.parse(e);
1138
1146
  } catch {
1139
- this.loggedParseFailure || (this.loggedParseFailure = !0, g.error("dictation server event was not valid JSON", {
1147
+ this.loggedParseFailure || (this.loggedParseFailure = !0, k.error("dictation server event was not valid JSON", {
1140
1148
  snippet: e.slice(0, 120)
1141
1149
  }));
1142
1150
  return;
1143
1151
  }
1144
- const o = Pe(a);
1152
+ const o = Pe(t);
1145
1153
  if (!o) return;
1146
- const { type: r, delta: l } = o;
1154
+ const { type: r, delta: c } = o;
1147
1155
  if (r === "session.created" || r === "transcription_session.created") {
1148
1156
  this.setState("listening");
1149
1157
  return;
1150
1158
  }
1151
- if (r === "conversation.item.input_audio_transcription.delta" && l) {
1152
- this.state === "connecting" && this.setState("listening"), this.onDelta(l);
1159
+ if (r === "conversation.item.input_audio_transcription.delta" && c) {
1160
+ this.state === "connecting" && this.setState("listening"), this.onDelta(c);
1153
1161
  return;
1154
1162
  }
1155
- r === "error" && (g.error("dictation server event error", {
1163
+ r === "error" && (k.error("dictation server event error", {
1156
1164
  _e: o.errorMessage ?? "unknown"
1157
1165
  }), this.fail("unavailable"));
1158
1166
  }
1159
1167
  startLevelMeter(e) {
1160
1168
  if (this.onLevel)
1161
1169
  try {
1162
- const a = new AudioContext();
1163
- this.audioContext = a;
1164
- const o = a.createMediaStreamSource(e), r = a.createAnalyser();
1170
+ const t = new AudioContext();
1171
+ this.audioContext = t;
1172
+ const o = t.createMediaStreamSource(e), r = t.createAnalyser();
1165
1173
  r.fftSize = 512, o.connect(r);
1166
- const l = new Uint8Array(r.frequencyBinCount), s = () => {
1167
- var c;
1168
- r.getByteTimeDomainData(l);
1169
- let t = 0;
1170
- for (let d = 0; d < l.length; d++) {
1171
- const _ = ((l[d] ?? 128) - 128) / 128;
1172
- t += _ * _;
1174
+ const c = new Uint8Array(r.frequencyBinCount), s = () => {
1175
+ var l;
1176
+ r.getByteTimeDomainData(c);
1177
+ let a = 0;
1178
+ for (let d = 0; d < c.length; d++) {
1179
+ const _ = ((c[d] ?? 128) - 128) / 128;
1180
+ a += _ * _;
1173
1181
  }
1174
- const n = Math.sqrt(t / l.length);
1175
- (c = this.onLevel) == null || c.call(this, Math.min(1, n * 4)), this.levelRaf = requestAnimationFrame(s);
1182
+ const n = Math.sqrt(a / c.length);
1183
+ (l = this.onLevel) == null || l.call(this, Math.min(1, n * 4)), this.levelRaf = requestAnimationFrame(s);
1176
1184
  };
1177
1185
  this.levelRaf = requestAnimationFrame(s);
1178
- } catch (a) {
1179
- g.error("dictation level meter unavailable", {
1180
- _e: a instanceof Error ? a.message : String(a)
1186
+ } catch (t) {
1187
+ k.error("dictation level meter unavailable", {
1188
+ _e: t instanceof Error ? t.message : String(t)
1181
1189
  });
1182
1190
  }
1183
1191
  }
@@ -1188,10 +1196,10 @@ class Ne {
1188
1196
  this.isTornDown() || (this.teardown(), this.setState("error"), this.onError(e));
1189
1197
  }
1190
1198
  teardown() {
1191
- var e, a, o, r;
1192
- 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, (o = this.stream) == null || o.getTracks().forEach((l) => l.stop()), this.stream = null, (r = this.audioContext) == null || r.close().catch((l) => {
1193
- g.error("failed to close dictation audio context", {
1194
- _e: String(l)
1199
+ var e, t, o, r;
1200
+ this.timers.forEach((c) => clearTimeout(c)), 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((c) => c.stop()), this.stream = null, (r = this.audioContext) == null || r.close().catch((c) => {
1201
+ k.error("failed to close dictation audio context", {
1202
+ _e: String(c)
1195
1203
  });
1196
1204
  }), this.audioContext = null;
1197
1205
  }
@@ -1201,10 +1209,10 @@ class Ne {
1201
1209
  }
1202
1210
  const Re = 1300, Ke = { status: "idle", error: null };
1203
1211
  class Le {
1204
- constructor({ api: e, config: a }) {
1212
+ constructor({ api: e, config: t }) {
1205
1213
  this.state = new S(Ke), this.levelRef = { current: 0 }, this.mintCache = new Ae(), 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 = () => {
1206
1214
  this.mintToken().catch((o) => {
1207
- this.mintCache.clear(), g.error("dictation token prewarm failed", {
1215
+ this.mintCache.clear(), k.error("dictation token prewarm failed", {
1208
1216
  _e: o instanceof Error ? o.message : String(o)
1209
1217
  });
1210
1218
  });
@@ -1214,22 +1222,22 @@ class Le {
1214
1222
  ), this.prefix = o.getValue(), this.raw = "", this.processed = "", this.displayed = "";
1215
1223
  const r = new Ne({
1216
1224
  mintToken: this.mintToken,
1217
- onLevel: (l) => {
1218
- this.levelRef.current = l;
1225
+ onLevel: (c) => {
1226
+ this.levelRef.current = c;
1219
1227
  },
1220
- onState: (l) => {
1221
- r === this.session && (l === "connecting" && this.state.set({ status: "connecting", error: null }), l === "listening" && this.state.set({ status: "listening", error: null }), l === "stopped" && this.teardown());
1228
+ onState: (c) => {
1229
+ r === this.session && (c === "connecting" && this.state.set({ status: "connecting", error: null }), c === "listening" && this.state.set({ status: "listening", error: null }), c === "stopped" && this.teardown());
1222
1230
  },
1223
- onError: (l) => {
1224
- r === this.session && (this.mintCache.clear(), this.teardown({ error: l, executeFinalCommand: !1 }));
1231
+ onError: (c) => {
1232
+ r === this.session && (this.mintCache.clear(), this.teardown({ error: c, executeFinalCommand: !1 }));
1225
1233
  },
1226
- onDelta: (l) => {
1234
+ onDelta: (c) => {
1227
1235
  if (r !== this.session || !this.target) return;
1228
1236
  if (!this.isConsistent()) {
1229
1237
  this.teardown();
1230
1238
  return;
1231
1239
  }
1232
- this.raw += l;
1240
+ this.raw += c;
1233
1241
  const s = this.ingest();
1234
1242
  if (s === "stop") {
1235
1243
  this.teardown();
@@ -1245,8 +1253,8 @@ class Le {
1245
1253
  ) && (this.silenceTimer = setTimeout(() => {
1246
1254
  if (r !== this.session) return;
1247
1255
  this.raw = `${this.raw}.`;
1248
- const t = this.ingest();
1249
- t === "stop" ? this.teardown() : t === "send" && this.teardown({ send: !0 });
1256
+ const a = this.ingest();
1257
+ a === "stop" ? this.teardown() : a === "send" && this.teardown({ send: !0 });
1250
1258
  }, Re));
1251
1259
  }
1252
1260
  });
@@ -1268,7 +1276,7 @@ class Le {
1268
1276
  this.session && this.teardown(o);
1269
1277
  }, this.mintToken = async () => this.mintCache.resolve(
1270
1278
  () => this.api.createDictationSession({ language: this.language })
1271
- ), this.api = e, this.config = a;
1279
+ ), this.api = e, this.config = t;
1272
1280
  }
1273
1281
  /** Applied text = prefix + dictated. A mismatch means the visitor edited. */
1274
1282
  isConsistent() {
@@ -1280,28 +1288,28 @@ class Le {
1280
1288
  /** Process the transcript and apply the outcome. Shared by the delta path,
1281
1289
  * the silence timer, and (with `final`) teardown. Returns the control. */
1282
1290
  ingest(e) {
1283
- const a = E.process(this.raw, {
1291
+ const t = E.process(this.raw, {
1284
1292
  language: this.language,
1285
1293
  final: e == null ? void 0 : e.final
1286
1294
  });
1287
- return this.processed = a.text, a.text.startsWith(this.displayed) || this.applyDisplayed(a.text), a.control;
1295
+ return this.processed = t.text, t.text.startsWith(this.displayed) || this.applyDisplayed(t.text), t.control;
1288
1296
  }
1289
1297
  stopSilenceTimer() {
1290
1298
  this.silenceTimer && clearTimeout(this.silenceTimer), this.silenceTimer = null;
1291
1299
  }
1292
1300
  teardown(e) {
1293
- var l;
1294
- const a = this.session, o = this.target;
1301
+ var c;
1302
+ const t = this.session, o = this.target;
1295
1303
  this.dripTimer && clearInterval(this.dripTimer), this.dripTimer = null, this.stopSilenceTimer();
1296
1304
  let r = (e == null ? void 0 : e.send) ?? !1;
1297
1305
  if (o && this.isConsistent()) {
1298
1306
  const s = this.ingest({ final: !0 });
1299
1307
  (e == null ? void 0 : e.executeFinalCommand) !== !1 && s === "send" && (r = !0), this.processed !== this.displayed && this.applyDisplayed(this.processed);
1300
1308
  }
1301
- 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 }), r && ((l = o == null ? void 0 : o.onSend) == null || l.call(o));
1309
+ 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 }), r && ((c = o == null ? void 0 : o.onSend) == null || c.call(o));
1302
1310
  }
1303
1311
  }
1304
- const Fe = {
1312
+ const Oe = {
1305
1313
  write_a_message_placeholder: "اكتب رسالة...",
1306
1314
  your_issue_has_been_resolved: "تم حل مشكلتك!",
1307
1315
  new_conversation: "محادثة جديدة",
@@ -1410,7 +1418,7 @@ const Fe = {
1410
1418
  zoom_out: "تصغير",
1411
1419
  reset_zoom: "إعادة تعيين التكبير",
1412
1420
  support_chat_aria_label: "دردشة الدعم"
1413
- }, Oe = {
1421
+ }, Fe = {
1414
1422
  write_a_message_placeholder: "একটি বার্তা লিখুন...",
1415
1423
  your_issue_has_been_resolved: "আপনার সমস্যা সমাধান হয়েছে!",
1416
1424
  new_conversation: "নতুন কথোপকথন",
@@ -5012,8 +5020,8 @@ const Fe = {
5012
5020
  reset_zoom: "Obnoviť priblíženie",
5013
5021
  support_chat_aria_label: "Chat podpory"
5014
5022
  }, J = {
5015
- ar: Fe,
5016
- bn: Oe,
5023
+ ar: Oe,
5024
+ bn: Fe,
5017
5025
  bg: Ue,
5018
5026
  cs: Be,
5019
5027
  da: Ve,
@@ -5061,29 +5069,29 @@ function Ja(i) {
5061
5069
  function Ca(i) {
5062
5070
  return Sa(i) ? i : "en";
5063
5071
  }
5064
- function xa(i, e, a, o) {
5065
- var l;
5066
- const r = ((l = a == null ? void 0 : a[e]) == null ? void 0 : l[i]) || J[e][i] || $[i] || i;
5072
+ function xa(i, e, t, o) {
5073
+ var c;
5074
+ const r = ((c = t == null ? void 0 : t[e]) == null ? void 0 : c[i]) || J[e][i] || $[i] || i;
5067
5075
  return o ? r.replace(
5068
5076
  /\{(\w+)\}/g,
5069
- (s, t) => t in o ? String(o[t]) : s
5077
+ (s, a) => a in o ? String(o[a]) : s
5070
5078
  ) : r;
5071
5079
  }
5072
- function qa(i, e, a) {
5080
+ function qa(i, e, t) {
5073
5081
  return xa(
5074
5082
  e,
5075
5083
  Ca(i.language),
5076
5084
  i.translationOverrides,
5077
- a
5085
+ t
5078
5086
  );
5079
5087
  }
5080
5088
  class Ea {
5081
5089
  constructor({
5082
5090
  config: e,
5083
- api: a,
5091
+ api: t,
5084
5092
  contactCtx: o,
5085
5093
  storageCtx: r,
5086
- sessionsPollingIntervalSeconds: l,
5094
+ sessionsPollingIntervalSeconds: c,
5087
5095
  sharedSessions: s
5088
5096
  }) {
5089
5097
  this.sessionsRefresher = new Z(), this.persistedSessionId = null, this.sessionAbortController = new AbortController(), this.sessionState = new S({
@@ -5104,20 +5112,20 @@ class Ea {
5104
5112
  this.persistSession
5105
5113
  ));
5106
5114
  }, this.restoreActiveSessionTracking = () => {
5107
- var t;
5108
- (t = this.stopPersistingSession) == null || t.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
5109
- }, this.trackActiveSession = (t) => {
5115
+ var a;
5116
+ (a = this.stopPersistingSession) == null || a.call(this), this.stopPersistingSession = void 0, this.registerActiveSessionPersistence();
5117
+ }, this.trackActiveSession = (a) => {
5110
5118
  var n;
5111
- (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = t.sessionState.subscribe(
5119
+ (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = a.sessionState.subscribe(
5112
5120
  this.persistSession
5113
- ), this.persistSession(t.sessionState.get());
5114
- }, this.persistSession = ({ session: t }) => {
5121
+ ), this.persistSession(a.sessionState.get());
5122
+ }, this.persistSession = ({ session: a }) => {
5115
5123
  const n = this.storageCtx;
5116
5124
  if (!n) return;
5117
- const c = t != null && t.isOpened ? t.id : null;
5118
- if (c === this.persistedSessionId || !c && this.persistedSessionId === null) return;
5119
- this.persistedSessionId = c, (c ? n.setActiveSessionId(c) : n.clearActiveSessionId()).catch((_) => {
5120
- g.warn("failed to persist the active session", {
5125
+ const l = a != null && a.isOpened ? a.id : null;
5126
+ if (l === this.persistedSessionId || !l && this.persistedSessionId === null) return;
5127
+ this.persistedSessionId = l, (l ? n.setActiveSessionId(l) : n.clearActiveSessionId()).catch((_) => {
5128
+ k.warn("failed to persist the active session", {
5121
5129
  error: _ instanceof Error ? _.message : String(_)
5122
5130
  });
5123
5131
  });
@@ -5131,9 +5139,9 @@ class Ea {
5131
5139
  }, this.reset = async () => {
5132
5140
  this.sessionAbortController.abort(), this.sessionAbortController = new AbortController(), this.sessionState.reset();
5133
5141
  }, this.registerSessionsRefresherWrapper = () => {
5134
- var t;
5142
+ var a;
5135
5143
  // If the widget config was initially provided with a contact token, no state change would be triggered, so we just fetch
5136
- (t = this.contactCtx.state.get().contact) != null && t.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.stopWaitingForContact = this.contactCtx.state.subscribe(
5144
+ (a = this.contactCtx.state.get().contact) != null && a.token && !this.sessionsState.get().didStartInitialFetch ? this.registerSessionsRefresher() : this.stopWaitingForContact = this.contactCtx.state.subscribe(
5137
5145
  ({ contact: n }) => {
5138
5146
  n != null && n.token && !this.sessionsState.get().didStartInitialFetch && this.registerSessionsRefresher();
5139
5147
  }
@@ -5142,42 +5150,42 @@ class Ea {
5142
5150
  this.sessionsRefresher.startPolling(async () => {
5143
5151
  this.sessionsState.get().didStartInitialFetch === !1 && this.sessionsState.setPartial({ didStartInitialFetch: !0 }), await this.refreshSessions(), this.sessionsState.get().isInitialFetchLoading === !0 && this.sessionsState.setPartial({ isInitialFetchLoading: !1 });
5144
5152
  }, this.sessionsPollingIntervalSeconds * 1e3);
5145
- }, this.dispose = ({ clearActiveSession: t = !1 } = {}) => {
5146
- var n, c;
5147
- if (this.sessionsRefresher.reset(), this.sessionAbortController.abort(), (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = void 0, (c = this.stopWaitingForContact) == null || c.call(this), this.stopWaitingForContact = void 0, this.sessionState.reset(), t && this.storageCtx)
5153
+ }, this.dispose = ({ clearActiveSession: a = !1 } = {}) => {
5154
+ var n, l;
5155
+ if (this.sessionsRefresher.reset(), this.sessionAbortController.abort(), (n = this.stopPersistingSession) == null || n.call(this), this.stopPersistingSession = void 0, (l = this.stopWaitingForContact) == null || l.call(this), this.stopWaitingForContact = void 0, this.sessionState.reset(), a && this.storageCtx)
5148
5156
  return this.persistedSessionId = null, this.storageCtx.clearActiveSessionId().catch((d) => {
5149
- g.warn("failed to clear the replaced session", {
5157
+ k.warn("failed to clear the replaced session", {
5150
5158
  error: d instanceof Error ? d.message : String(d)
5151
5159
  });
5152
5160
  });
5153
5161
  }, this.getParsedCustomData = () => Object.fromEntries(
5154
5162
  Object.entries(this.config.sessionCustomData || {}).map(
5155
- ([t, n]) => {
5156
- var c;
5157
- return typeof n == "string" ? [t, n] : typeof n == "boolean" ? [t, n] : typeof n == "number" ? [t, n] : [t, ((c = W(() => JSON.stringify(n))) == null ? void 0 : c.data) || ""];
5163
+ ([a, n]) => {
5164
+ var l;
5165
+ return typeof n == "string" ? [a, n] : typeof n == "boolean" ? [a, n] : typeof n == "number" ? [a, n] : [a, ((l = W(() => JSON.stringify(n))) == null ? void 0 : l.data) || ""];
5158
5166
  }
5159
5167
  )
5160
5168
  ), this.createSession = async () => {
5161
- const { signal: t } = this.sessionAbortController;
5169
+ const { signal: a } = this.sessionAbortController;
5162
5170
  this.sessionState.setPartial({ session: null, isCreatingSession: !0 });
5163
5171
  try {
5164
- const n = await this.requestSession(t);
5165
- if (t.aborted) return null;
5172
+ const n = await this.requestSession(a);
5173
+ if (a.aborted) return null;
5166
5174
  if (n.session) return n.session;
5167
5175
  if (n.status === 401 && await this.contactCtx.recoverFromStaleToken()) {
5168
- if (t.aborted) return null;
5169
- const c = await this.requestSession(t);
5170
- return t.aborted ? null : c.session ? c.session : (g.error("failed to create session", c.error), null);
5176
+ if (a.aborted) return null;
5177
+ const l = await this.requestSession(a);
5178
+ return a.aborted ? null : l.session ? l.session : (k.error("failed to create session", l.error), null);
5171
5179
  }
5172
- return g.error("failed to create session", n.error), null;
5180
+ return k.error("failed to create session", n.error), null;
5173
5181
  } catch (n) {
5174
- return t.aborted || g.error("failed to create session", n), null;
5182
+ return a.aborted || k.error("failed to create session", n), null;
5175
5183
  } finally {
5176
- t.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
5184
+ a.aborted || this.sessionState.setPartial({ isCreatingSession: !1 });
5177
5185
  }
5178
- }, this.requestSession = async (t) => {
5179
- var u, h, k;
5180
- const n = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, c = {
5186
+ }, this.requestSession = async (a) => {
5187
+ var u, m, g;
5188
+ const n = (u = this.contactCtx.state.get().contact) == null ? void 0 : u.externalId, l = {
5181
5189
  ...this.getParsedCustomData(),
5182
5190
  ...n ? { external_id: n } : {}
5183
5191
  }, {
@@ -5186,124 +5194,124 @@ class Ea {
5186
5194
  response: p
5187
5195
  } = await this.api.createSession(
5188
5196
  {
5189
- customData: Object.keys(c).length > 0 ? c : void 0
5197
+ customData: Object.keys(l).length > 0 ? l : void 0
5190
5198
  },
5191
- t
5199
+ a
5192
5200
  );
5193
- if (t.aborted || !d)
5201
+ if (a.aborted || !d)
5194
5202
  return { session: null, status: p == null ? void 0 : p.status, error: _ };
5195
5203
  this.sessionState.setPartial({ session: d });
5196
5204
  try {
5197
- (k = (h = this.config.hooks) == null ? void 0 : h.onSessionCreated) == null || k.call(h, { session: d });
5198
- } catch (v) {
5199
- g.error("onSessionCreated hook failed", v);
5205
+ (g = (m = this.config.hooks) == null ? void 0 : m.onSessionCreated) == null || g.call(m, { session: d });
5206
+ } catch (b) {
5207
+ k.error("onSessionCreated hook failed", b);
5200
5208
  }
5201
5209
  return { session: d, status: p.status, error: void 0 };
5202
5210
  }, this.loadMoreSessions = async () => {
5203
5211
  if (this.sessionsState.get().isLastPage) return;
5204
- const { data: t } = await this.getSessions({
5212
+ const { data: a } = await this.getSessions({
5205
5213
  cursor: this.sessionsState.get().cursor
5206
5214
  });
5207
- if (t) {
5208
- const c = [...this.sessionsState.get().data, ...t.items].filter(
5215
+ if (a) {
5216
+ const l = [...this.sessionsState.get().data, ...a.items].filter(
5209
5217
  (d, _, p) => _ === p.findIndex((u) => d.id === u.id)
5210
5218
  );
5211
5219
  this.sessionsState.setPartial({
5212
- data: c,
5213
- cursor: t.next || void 0,
5214
- isLastPage: t.next === null
5220
+ data: l,
5221
+ cursor: a.next || void 0,
5222
+ isLastPage: a.next === null
5215
5223
  });
5216
5224
  }
5217
- }, this.getSessions = async ({ cursor: t }) => {
5218
- var c, d;
5219
- if (!((c = this.contactCtx.state.get().contact) != null && c.token)) return { data: null };
5225
+ }, this.getSessions = async ({ cursor: a }) => {
5226
+ var l, d;
5227
+ if (!((l = this.contactCtx.state.get().contact) != null && l.token)) return { data: null };
5220
5228
  const n = (d = this.contactCtx.state.get().contact) == null ? void 0 : d.externalId;
5221
5229
  return await this.api.getSessions({
5222
- cursor: t,
5230
+ cursor: a,
5223
5231
  filters: n ? {
5224
5232
  external_id: n
5225
5233
  } : {}
5226
5234
  });
5227
- }, this.setSessions = (t) => {
5228
- const n = [...t, ...this.sessionsState.get().data].filter(
5229
- (c, d, _) => d === _.findIndex((p) => c.id === p.id)
5235
+ }, this.setSessions = (a) => {
5236
+ const n = [...a, ...this.sessionsState.get().data].filter(
5237
+ (l, d, _) => d === _.findIndex((p) => l.id === p.id)
5230
5238
  );
5231
5239
  this.sessionsState.setPartial({ data: n });
5232
5240
  }, this.refreshSessions = async () => {
5233
- const { data: t } = await this.getSessions({ cursor: void 0 });
5234
- t && this.setSessions(t.items);
5241
+ const { data: a } = await this.getSessions({ cursor: void 0 });
5242
+ a && this.setSessions(a.items);
5235
5243
  }, this.resolveSession = async () => {
5236
- const t = this.sessionState.get().session;
5237
- if (!t || !t.isOpened)
5244
+ const a = this.sessionState.get().session;
5245
+ if (!a || !a.isOpened)
5238
5246
  return { success: !1, error: "Session is not opened" };
5239
5247
  this.sessionState.setPartial({ isResolvingSession: !0 });
5240
- const { signal: n } = this.sessionAbortController, c = await this.api.resolveSession({ session_id: t.id }, n).catch((p) => {
5248
+ const { signal: n } = this.sessionAbortController, l = await this.api.resolveSession({ session_id: a.id }, n).catch((p) => {
5241
5249
  if (n.aborted) return null;
5242
5250
  throw p;
5243
5251
  });
5244
- if (!c || n.aborted)
5252
+ if (!l || n.aborted)
5245
5253
  return { success: !1, error: "Session was reset" };
5246
- const { data: d, error: _ } = c;
5254
+ const { data: d, error: _ } = l;
5247
5255
  return d ? (this.sessionState.setPartial({ session: d, isResolvingSession: !1 }), { success: !0, data: d }) : (this.sessionState.setPartial({ isResolvingSession: !1 }), { success: !1, error: _ });
5248
- }, this.createStateCheckpoint = async (t) => {
5256
+ }, this.createStateCheckpoint = async (a) => {
5249
5257
  var d;
5250
5258
  const n = (d = this.sessionState.get().session) == null ? void 0 : d.id;
5251
5259
  if (!n) return;
5252
- const { data: c } = await this.api.createStateCheckpoint({
5260
+ const { data: l } = await this.api.createStateCheckpoint({
5253
5261
  session_id: n,
5254
- payload: t
5262
+ payload: a
5255
5263
  });
5256
- return c != null && c.success ? { success: !0 } : { success: !1 };
5257
- }, this.config = e, this.api = a, this.contactCtx = o, this.storageCtx = r, this.sessionsPollingIntervalSeconds = l, s ? this.sessionsState = s : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
5264
+ return l != null && l.success ? { success: !0 } : { success: !1 };
5265
+ }, this.config = e, this.api = t, this.contactCtx = o, this.storageCtx = r, this.sessionsPollingIntervalSeconds = c, s ? this.sessionsState = s : this.registerSessionsRefresherWrapper(), this.registerActiveSessionPersistence();
5258
5266
  }
5259
5267
  }
5260
- const Aa = (i, e, { sendsPageContext: a }) => {
5261
- const o = Ia(i), r = a && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(Pa) } : void 0, l = a && (e.clientContext || r) ? { ...o, ...e.clientContext, ...r } : o, s = e.connectionRequestId ? {
5262
- ...l,
5268
+ const Aa = (i, e, { sendsPageContext: t }) => {
5269
+ const o = Ia(i), r = t && e.mentions && e.mentions.length > 0 ? { mentions: e.mentions.map(Pa) } : void 0, c = t && (e.clientContext || r) ? { ...o, ...e.clientContext, ...r } : o, s = e.connectionRequestId ? {
5270
+ ...c,
5263
5271
  opencx__connection_request_id: e.connectionRequestId
5264
- } : l, t = e.withPageEntity === !1 && s && "entity" in s ? Ta(s, "entity") : s;
5272
+ } : c, a = e.withPageEntity === !1 && s && "entity" in s ? Ta(s, "entity") : s;
5265
5273
  return {
5266
- clientContext: e.background ? { ...t, opencx__background: !0 } : t,
5274
+ clientContext: e.background ? { ...a, opencx__background: !0 } : a,
5267
5275
  custom_data: {
5268
5276
  ...i.messageCustomData || {},
5269
5277
  ...e.customData || {}
5270
5278
  }
5271
5279
  };
5272
- }, Pa = ({ type: i, id: e, title: a, meta: o }) => ({
5280
+ }, Pa = ({ type: i, id: e, title: t, meta: o }) => ({
5273
5281
  type: i,
5274
5282
  id: e,
5275
- title: a,
5283
+ title: t,
5276
5284
  ...o ? { meta: o } : {}
5277
5285
  }), Ta = (i, e) => {
5278
- const { [e]: a, ...o } = i;
5286
+ const { [e]: t, ...o } = i;
5279
5287
  return Object.keys(o).length > 0 ? o : void 0;
5280
5288
  }, Ia = (i) => {
5281
5289
  if (typeof i.context != "function") return i.context;
5282
5290
  try {
5283
5291
  return i.context();
5284
5292
  } catch (e) {
5285
- g.error("context getter threw; sending without context", e);
5293
+ k.error("context getter threw; sending without context", e);
5286
5294
  return;
5287
5295
  }
5288
5296
  }, Ma = (i) => {
5289
- const e = i.features, a = {
5297
+ const e = i.features, t = {
5290
5298
  page_context: (e == null ? void 0 : e.pageContext) === !0,
5291
5299
  client_tools: (e == null ? void 0 : e.pageContext) === !0 && (e == null ? void 0 : e.clientTools) === !0,
5292
5300
  page_actions: (e == null ? void 0 : e.pageContext) === !0 && (e == null ? void 0 : e.clientTools) === !0 && (e == null ? void 0 : e.pageActions) === !0
5293
5301
  };
5294
- return e && (e.preamble !== void 0 && (a.preamble = e.preamble), e.inlineUi !== void 0 && (a.inline_ui = e.inlineUi)), a;
5302
+ return e && (e.preamble !== void 0 && (t.preamble = e.preamble), e.inlineUi !== void 0 && (t.inline_ui = e.inlineUi)), t;
5295
5303
  }, Da = ({
5296
5304
  config: i,
5297
5305
  input: e,
5298
- uuid: a,
5306
+ uuid: t,
5299
5307
  sessionId: o,
5300
5308
  content: r,
5301
- initialMessages: l,
5309
+ initialMessages: c,
5302
5310
  sendsPageContext: s
5303
5311
  }) => {
5304
- var t, n, c, d;
5312
+ var a, n, l, d;
5305
5313
  return {
5306
- uuid: a,
5314
+ uuid: t,
5307
5315
  bot_token: i.token,
5308
5316
  headers: i.headers,
5309
5317
  query_params: i.queryParams,
@@ -5316,25 +5324,29 @@ const Aa = (i, e, { sendsPageContext: a }) => {
5316
5324
  features: Ma(i),
5317
5325
  presentation: i.presentation,
5318
5326
  capabilities: {
5319
- connections: ((t = i.capabilities) == null ? void 0 : t.connections) === !0,
5327
+ connections: ((a = i.capabilities) == null ? void 0 : a.connections) === !0,
5320
5328
  structured_questions: (n = i.capabilities) == null ? void 0 : n.structuredQuestions,
5321
- rich_replies: (c = i.capabilities) == null ? void 0 : c.richReplies,
5329
+ rich_replies: (l = i.capabilities) == null ? void 0 : l.richReplies,
5322
5330
  page_effects: (d = i.capabilities) == null ? void 0 : d.pageEffects
5323
5331
  },
5324
5332
  exit_mode_prompt: e.exitModePrompt,
5325
- initial_messages: l.length > 0 ? l.map((_) => ({ uuid: _.id, content: _.data.message })) : void 0
5333
+ option_reply: e.optionReply ? {
5334
+ message_id: e.optionReply.messageId,
5335
+ option_id: e.optionReply.optionId
5336
+ } : void 0,
5337
+ initial_messages: c.length > 0 ? c.map((_) => ({ uuid: _.id, content: _.data.message })) : void 0
5326
5338
  };
5327
5339
  }, x = class x {
5328
5340
  constructor({
5329
5341
  config: e,
5330
- api: a,
5342
+ api: t,
5331
5343
  sessionCtx: o,
5332
5344
  contactCtx: r,
5333
- streaming: l,
5345
+ streaming: c,
5334
5346
  sendsPageContext: s,
5335
- getClientCapabilities: t,
5347
+ getClientCapabilities: a,
5336
5348
  getRequestConfig: n,
5337
- isStreaming: c,
5349
+ isStreaming: l,
5338
5350
  getSendsPageContext: d
5339
5351
  }) {
5340
5352
  this.state = new S({
@@ -5364,24 +5376,24 @@ const Aa = (i, e, { sendsPageContext: a }) => {
5364
5376
  }, this.unregisterAgentHandlers = (_) => {
5365
5377
  this.agentHandlers === _ && (this.agentHandlers = null);
5366
5378
  }, this.dispatchToOnMessageReceivedHook = (_) => {
5367
- var u, h;
5379
+ var u, m;
5368
5380
  if (_.type === "USER" || this.messageIdsDispatchedToOnMessageReceivedHook.has(_.id))
5369
5381
  return;
5370
5382
  const p = this.sessionCtx.sessionState.get().session;
5371
- p && (this.messageIdsDispatchedToOnMessageReceivedHook.add(_.id), (h = (u = this.config.hooks) == null ? void 0 : u.onMessageReceived) == null || h.call(u, { message: _, session: p }));
5383
+ p && (this.messageIdsDispatchedToOnMessageReceivedHook.add(_.id), (m = (u = this.config.hooks) == null ? void 0 : u.onMessageReceived) == null || m.call(u, { message: _, session: p }));
5372
5384
  }, this.markAsDispatchedToOnMessageReceivedHook = (_) => {
5373
5385
  _.forEach(
5374
5386
  (p) => this.messageIdsDispatchedToOnMessageReceivedHook.add(p)
5375
5387
  );
5376
5388
  }, this.buildPersistentInitialMessages = () => {
5377
5389
  var p, u;
5378
- return !((p = this.sessionCtx.sessionState.get().session) != null && p.id) && this.state.get().messages.length === 0 && ((u = this.config.advancedInitialMessages) == null ? void 0 : u.some((h) => h.persistent)) ? (this.config.advancedInitialMessages || []).filter((h) => h.persistent).map(
5379
- (h) => ({
5390
+ return !((p = this.sessionCtx.sessionState.get().session) != null && p.id) && this.state.get().messages.length === 0 && ((u = this.config.advancedInitialMessages) == null ? void 0 : u.some((m) => m.persistent)) ? (this.config.advancedInitialMessages || []).filter((m) => m.persistent).map(
5391
+ (m) => ({
5380
5392
  id: q(),
5381
5393
  component: "bot_message",
5382
5394
  type: "AI",
5383
5395
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5384
- data: { message: h.message },
5396
+ data: { message: m.message },
5385
5397
  agent: this.config.bot ? { ...this.config.bot, isAi: !0, id: null } : void 0
5386
5398
  })
5387
5399
  ) : [];
@@ -5394,46 +5406,50 @@ const Aa = (i, e, { sendsPageContext: a }) => {
5394
5406
  return ((p = this.sessionCtx.sessionState.get().session) == null ? void 0 : p.id) ?? null;
5395
5407
  }, this.rollbackOptimisticMessages = (_) => {
5396
5408
  if (_.length === 0) return;
5397
- const p = new Set(_), u = this.state.get().messages, h = u.filter((k) => !p.has(k.id));
5398
- h.length !== u.length && this.state.setPartial({ messages: h });
5409
+ const p = new Set(_), u = this.state.get().messages, m = u.filter((g) => !p.has(g.id));
5410
+ m.length !== u.length && this.state.setPartial({ messages: m });
5399
5411
  }, this.notifySendAccepted = (_) => {
5400
5412
  var p;
5413
+ _.optionReply && this.setMessageOptionPick(
5414
+ _.optionReply.messageId,
5415
+ _.optionReply.optionId
5416
+ );
5401
5417
  try {
5402
5418
  (p = _.onAccepted) == null || p.call(_);
5403
5419
  } catch (u) {
5404
- g.error("send acceptance callback failed", u);
5420
+ k.error("send acceptance callback failed", u);
5405
5421
  }
5406
5422
  }, this.stageUserTurn = async (_, { pending: p }) => {
5407
- const u = this.captureConversation(), h = this.buildUserMessage(_);
5408
- if (!h) return null;
5409
- const k = p ? { ...h, pending: !0 } : h, v = this.buildPersistentInitialMessages(), f = [
5410
- ...v.map((y) => y.id),
5411
- k.id
5423
+ const u = this.captureConversation(), m = this.buildUserMessage(_);
5424
+ if (!m) return null;
5425
+ const g = p ? { ...m, pending: !0 } : m, b = this.buildPersistentInitialMessages(), f = [
5426
+ ...b.map((y) => y.id),
5427
+ g.id
5412
5428
  ];
5413
5429
  this.state.setPartial({
5414
5430
  messages: [
5415
- ...v,
5431
+ ...b,
5416
5432
  ...this.state.get().messages,
5417
- ...k.background ? [] : [k]
5433
+ ...g.background ? [] : [g]
5418
5434
  ]
5419
5435
  });
5420
- let b;
5436
+ let v;
5421
5437
  try {
5422
- b = await this.ensureSessionId();
5438
+ v = await this.ensureSessionId();
5423
5439
  } catch (y) {
5424
5440
  if (!u()) return null;
5425
5441
  throw this.rollbackOptimisticMessages(f), y;
5426
5442
  }
5427
- return u() ? b ? { sessionId: b, userMessage: k, initialMessages: v } : (this.rollbackOptimisticMessages(f), null) : null;
5443
+ return u() ? v ? { sessionId: v, userMessage: g, initialMessages: b } : (this.rollbackOptimisticMessages(f), null) : null;
5428
5444
  }, this.buildQueuedUserMessage = (_) => {
5429
- var h;
5445
+ var m;
5430
5446
  const p = this.buildUserMessage(_);
5431
5447
  if (!p) return null;
5432
- const u = (h = this.sessionCtx.sessionState.get().session) == null ? void 0 : h.id;
5448
+ const u = (m = this.sessionCtx.sessionState.get().session) == null ? void 0 : m.id;
5433
5449
  return u ? { sessionId: u, userMessage: { ...p, pending: !0 } } : null;
5434
5450
  }, this.buildUserMessage = (_) => {
5435
5451
  var p;
5436
- return !_.content.trim() && (!_.attachments || _.attachments.length === 0) ? (g.warn("cannot send an empty message of no content or attachments"), null) : {
5452
+ return !_.content.trim() && (!_.attachments || _.attachments.length === 0) ? (k.warn("cannot send an empty message of no content or attachments"), null) : {
5437
5453
  ...this.toUserMessage(
5438
5454
  _.content.trim(),
5439
5455
  _.attachments || void 0,
@@ -5448,17 +5464,30 @@ const Aa = (i, e, { sendsPageContext: a }) => {
5448
5464
  p.some((u) => u.id === _.id) || this.state.setPartial({ messages: [...p, _] });
5449
5465
  }, this.markUserMessageDelivered = (_) => {
5450
5466
  const p = this.state.get().messages, u = p.findIndex(
5451
- (v) => v.id === _ && v.type === "USER" && v.pending
5467
+ (b) => b.id === _ && b.type === "USER" && b.pending
5452
5468
  );
5453
5469
  if (u === -1) return;
5454
- const h = p[u];
5455
- if (!h || h.type !== "USER") return;
5456
- const k = [...p];
5457
- k[u] = { ...h, pending: !1 }, this.state.setPartial({
5458
- messages: k
5470
+ const m = p[u];
5471
+ if (!m || m.type !== "USER") return;
5472
+ const g = [...p];
5473
+ g[u] = { ...m, pending: !1 }, this.state.setPartial({
5474
+ messages: g
5459
5475
  });
5476
+ }, this.setMessageOptionPick = (_, p) => {
5477
+ const u = this.state.get().messages, m = u.findIndex((f) => f.id === _), g = u[m];
5478
+ if (!g || g.type !== "AGENT" || !g.messageOptions || g.messageOptions.pickedOptionId === p) return;
5479
+ const b = [...u];
5480
+ b[m] = {
5481
+ ...g,
5482
+ messageOptions: { ...g.messageOptions, pickedOptionId: p }
5483
+ }, this.state.setPartial({ messages: b });
5484
+ }, this.releaseFailedOptionPick = (_) => {
5485
+ var g;
5486
+ if (!_.optionReply) return;
5487
+ const { messageId: p, optionId: u } = _.optionReply, m = this.state.get().messages.find((b) => b.id === p);
5488
+ (m == null ? void 0 : m.type) !== "AGENT" || ((g = m.messageOptions) == null ? void 0 : g.pickedOptionId) !== u || this.setMessageOptionPick(p, null);
5460
5489
  }, this.sendMessage = async (_) => {
5461
- var u, h, k, v, f;
5490
+ var u, m, g, b, f;
5462
5491
  if (this.streaming) {
5463
5492
  if (!this.agentHandlers) {
5464
5493
  this.bufferedAgentSends.push(_);
@@ -5469,16 +5498,16 @@ const Aa = (i, e, { sendsPageContext: a }) => {
5469
5498
  }
5470
5499
  let p;
5471
5500
  try {
5472
- const b = this.sessionCtx.sessionState.get().session, z = (b == null ? void 0 : b.assignee.kind) === "ai", X = this.state.get().isSendingMessageToAI, A = this.state.get().messages.at(-1);
5501
+ const v = this.sessionCtx.sessionState.get().session, z = (v == null ? void 0 : v.assignee.kind) === "ai", X = this.state.get().isSendingMessageToAI, A = this.state.get().messages.at(-1);
5473
5502
  if (this.blocksSendWhileAwaitingReply && (X || // If last message is from user, then bot response did not arrive yet
5474
5503
  z && (A == null ? void 0 : A.type) === "USER" && A.id !== this.state.get().settledAgentUserMessageId)) {
5475
- g.warn("cannot send messages while awaiting AI response");
5504
+ k.warn("cannot send messages while awaiting AI response");
5476
5505
  return;
5477
5506
  }
5478
5507
  this.sendMessageAbortController.abort("Superseded by a newer message"), this.sendMessageAbortController = new AbortController(), p = this.sendMessageAbortController, this.state.setPartial({
5479
5508
  lastAIResMightSolveUserIssue: !1,
5480
5509
  isSendingMessage: !0,
5481
- isSendingMessageToAI: !!z || !b
5510
+ isSendingMessageToAI: !!z || !v
5482
5511
  });
5483
5512
  const R = await this.stageUserTurn(_, { pending: !1 });
5484
5513
  if (!R) return;
@@ -5507,17 +5536,18 @@ const Aa = (i, e, { sendsPageContext: a }) => {
5507
5536
  (ae) => ae.id === C.id
5508
5537
  )) {
5509
5538
  this.state.setPartial({
5510
- lastAIResMightSolveUserIssue: ((u = w.autopilotResponse) == null ? void 0 : u.mightSolveUserIssue) || ((h = w.uiResponse) == null ? void 0 : h.mightSolveUserIssue)
5539
+ lastAIResMightSolveUserIssue: ((u = w.autopilotResponse) == null ? void 0 : u.mightSolveUserIssue) || ((m = w.uiResponse) == null ? void 0 : m.mightSolveUserIssue)
5511
5540
  });
5512
5541
  return;
5513
5542
  }
5514
5543
  this.state.setPartial({
5515
5544
  messages: [...P, C],
5516
- lastAIResMightSolveUserIssue: ((k = w.autopilotResponse) == null ? void 0 : k.mightSolveUserIssue) || ((v = w.uiResponse) == null ? void 0 : v.mightSolveUserIssue)
5545
+ lastAIResMightSolveUserIssue: ((g = w.autopilotResponse) == null ? void 0 : g.mightSolveUserIssue) || ((b = w.uiResponse) == null ? void 0 : b.mightSolveUserIssue)
5517
5546
  }), this.dispatchToOnMessageReceivedHook(C);
5518
5547
  }
5519
5548
  w.session && this.sessionCtx.sessionState.setPartial({ session: w.session });
5520
5549
  } else {
5550
+ this.releaseFailedOptionPick(_);
5521
5551
  const C = this.toBotErrorMessage(
5522
5552
  ((f = w == null ? void 0 : w.error) == null ? void 0 : f.message) || qa(this.config, "turn_failed_message")
5523
5553
  ), P = this.state.get().messages;
@@ -5525,31 +5555,31 @@ const Aa = (i, e, { sendsPageContext: a }) => {
5525
5555
  messages: [...P, C]
5526
5556
  });
5527
5557
  }
5528
- } catch (b) {
5529
- p != null && p.signal.aborted || g.error("failed to send message", b);
5558
+ } catch (v) {
5559
+ p != null && p.signal.aborted || (this.releaseFailedOptionPick(_), k.error("failed to send message", v));
5530
5560
  } finally {
5531
5561
  p != null && p.signal.aborted || this.state.setPartial({
5532
5562
  isSendingMessage: !1,
5533
5563
  isSendingMessageToAI: !1
5534
5564
  });
5535
5565
  }
5536
- }, this.toUserMessage = (_, p, u, h) => {
5537
- const k = (() => {
5566
+ }, this.toUserMessage = (_, p, u, m) => {
5567
+ const g = (() => {
5538
5568
  const f = this.contactCtx.state.get().extraCollectedData;
5539
5569
  return this.state.get().messages.length === 0 && f && Object.keys(f).length > 0 ? `${Object.entries(f).filter(([y, z]) => !!z).map(([y, z]) => `${y}: ${z}`).join(`
5540
5570
  `)}
5541
5571
 
5542
5572
  ${_}` : _;
5543
- })(), v = (/* @__PURE__ */ new Date()).toISOString();
5573
+ })(), b = (/* @__PURE__ */ new Date()).toISOString();
5544
5574
  return {
5545
5575
  id: q(),
5546
5576
  type: "USER",
5547
- deliveredAt: v,
5548
- content: k,
5577
+ deliveredAt: b,
5578
+ content: g,
5549
5579
  attachments: p,
5550
5580
  markedElements: u,
5551
- mentions: h,
5552
- timestamp: v
5581
+ mentions: m,
5582
+ timestamp: b
5553
5583
  };
5554
5584
  }, this.toBotMessage = (_) => {
5555
5585
  var p;
@@ -5584,7 +5614,7 @@ ${_}` : _;
5584
5614
  variant: "error",
5585
5615
  action: void 0
5586
5616
  }
5587
- }), this.config = e, this.getClientCapabilities = t ?? (() => this.getRequestConfig().capabilities), this.api = a, this.sessionCtx = o, this.contactCtx = r, this.isStreaming = c ?? (() => l), this.getRequestConfig = n ?? (() => this.config), this.getSendsPageContext = d ?? (() => s);
5617
+ }), this.config = e, this.getClientCapabilities = a ?? (() => this.getRequestConfig().capabilities), this.api = t, this.sessionCtx = o, this.contactCtx = r, this.isStreaming = l ?? (() => c), this.getRequestConfig = n ?? (() => this.config), this.getSendsPageContext = d ?? (() => s);
5588
5618
  }
5589
5619
  /**
5590
5620
  * Current transport choice. The org or this embed may request polling
@@ -5597,18 +5627,18 @@ ${_}` : _;
5597
5627
  return this.getSendsPageContext();
5598
5628
  }
5599
5629
  /** Hand a send to the streaming engine; its failure can never propagate. */
5600
- static dispatchToEngine(e, a) {
5630
+ static dispatchToEngine(e, t) {
5601
5631
  try {
5602
- Promise.resolve(e.send(a)).catch((o) => {
5603
- g.error("streaming send failed", o);
5632
+ Promise.resolve(e.send(t)).catch((o) => {
5633
+ k.error("streaming send failed", o);
5604
5634
  });
5605
5635
  } catch (o) {
5606
- g.error("streaming send failed", o);
5636
+ k.error("streaming send failed", o);
5607
5637
  }
5608
5638
  }
5609
5639
  get hasPendingAgentWork() {
5610
- var e, a;
5611
- return this.bufferedAgentSends.length > 0 || (((a = (e = this.agentHandlers) == null ? void 0 : e.hasPendingWork) == null ? void 0 : a.call(e)) ?? !1);
5640
+ var e, t;
5641
+ return this.bufferedAgentSends.length > 0 || (((t = (e = this.agentHandlers) == null ? void 0 : e.hasPendingWork) == null ? void 0 : t.call(e)) ?? !1);
5612
5642
  }
5613
5643
  /**
5614
5644
  * Defensive read of `clientContext.page_marks` → the user bubble's context
@@ -5618,18 +5648,18 @@ ${_}` : _;
5618
5648
  * without a usable name are dropped.
5619
5649
  */
5620
5650
  static markedElementNames(e) {
5621
- const a = e == null ? void 0 : e.page_marks;
5622
- if (!Array.isArray(a)) return;
5623
- const o = a.flatMap((r) => {
5651
+ const t = e == null ? void 0 : e.page_marks;
5652
+ if (!Array.isArray(t)) return;
5653
+ const o = t.flatMap((r) => {
5624
5654
  if (typeof r != "object" || r === null) return [];
5625
- const l = r.elements, s = Array.isArray(l) ? l[0] : void 0, t = typeof s == "object" && s !== null && "name" in s ? s.name : void 0;
5626
- if (typeof t != "string" || t.length === 0) return [];
5627
- const n = r.note, c = r.snapshotUrl;
5655
+ const c = r.elements, s = Array.isArray(c) ? c[0] : void 0, a = typeof s == "object" && s !== null && "name" in s ? s.name : void 0;
5656
+ if (typeof a != "string" || a.length === 0) return [];
5657
+ const n = r.note, l = r.snapshotUrl;
5628
5658
  return [
5629
5659
  {
5630
- name: t,
5660
+ name: a,
5631
5661
  ...typeof n == "string" && n.length > 0 ? { note: n } : {},
5632
- ...typeof c == "string" && c.length > 0 ? { snapshotUrl: c } : {},
5662
+ ...typeof l == "string" && l.length > 0 ? { snapshotUrl: l } : {},
5633
5663
  mark: r
5634
5664
  }
5635
5665
  ];
@@ -5648,7 +5678,7 @@ x.SENT_TEXT_HISTORY_MAX = 50;
5648
5678
  let D = x;
5649
5679
  class Na {
5650
5680
  constructor(e) {
5651
- var a, o;
5681
+ var t, o;
5652
5682
  this.widget = e, this.subscriptions = [], this.disposed = !1, this.restorableSessionId = null, this.didReadStoredSession = !1, this.readStoredSession = () => {
5653
5683
  if (!this.shouldRestoreLastSession) {
5654
5684
  this.didReadStoredSession = !0;
@@ -5662,9 +5692,9 @@ class Na {
5662
5692
  }, this.registerRoutingListener = () => {
5663
5693
  this.subscriptions.push(
5664
5694
  this.contactCtx.state.subscribe(({ contact: r }) => {
5665
- var l;
5695
+ var c;
5666
5696
  r != null && r.token && this.state.get().screen === "welcome" && this.state.setPartial({
5667
- screen: (l = this.config.router) != null && l.chatScreenOnly ? "chat" : "sessions"
5697
+ screen: (c = this.config.router) != null && c.chatScreenOnly ? "chat" : "sessions"
5668
5698
  });
5669
5699
  })
5670
5700
  ), this.subscriptions.push(
@@ -5672,12 +5702,12 @@ class Na {
5672
5702
  );
5673
5703
  }, this.routeFromSessions = ({
5674
5704
  isInitialFetchLoading: r,
5675
- data: l
5705
+ data: c
5676
5706
  }) => {
5677
- var s, t, n, c, d;
5707
+ var s, a, n, l, d;
5678
5708
  if (!(this.disposed || !this.didReadStoredSession)) {
5679
5709
  if (this.restorableSessionId && !((s = this.sessionCtx.sessionState.get().session) != null && s.id)) {
5680
- const _ = l.find(
5710
+ const _ = c.find(
5681
5711
  (p) => p.id === this.restorableSessionId && p.isOpened
5682
5712
  );
5683
5713
  if (_) {
@@ -5687,37 +5717,37 @@ class Na {
5687
5717
  if (r) return;
5688
5718
  this.restorableSessionId = null;
5689
5719
  }
5690
- if ((t = this.config.router) != null && t.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5720
+ if ((a = this.config.router) != null && a.chatScreenOnly && // Do not route to a chat if we are currently inside one already
5691
5721
  // This also applies to newly created sessions; the new session will be in `sessionState` before it is refreshed and included in `sessionsState`
5692
5722
  !((n = this.sessionCtx.sessionState.get().session) != null && n.id)) {
5693
- const _ = (c = l.find((p) => p.isOpened)) == null ? void 0 : c.id;
5723
+ const _ = (l = c.find((p) => p.isOpened)) == null ? void 0 : l.id;
5694
5724
  return _ ? this.toChatScreen(_) : void 0;
5695
5725
  }
5696
- l.length || ((d = this.config.router) == null ? void 0 : d.goToChatIfNoSessions) !== !1 && !r && this.state.get().screen !== "chat" && this.toChatScreen();
5726
+ c.length || ((d = this.config.router) == null ? void 0 : d.goToChatIfNoSessions) !== !1 && !r && this.state.get().screen !== "chat" && this.toChatScreen();
5697
5727
  }
5698
5728
  }, this.dispose = () => {
5699
5729
  this.disposed = !0, this.subscriptions.forEach((r) => r()), this.subscriptions = [], this.navigateConversation = void 0;
5700
5730
  }, this.toSessionsScreen = () => {
5701
5731
  this.navigateConversation || this.resetChat(), this.state.setPartial({ screen: "sessions" });
5702
5732
  }, this.toChatScreen = (r) => {
5703
- var s, t;
5733
+ var s, a;
5704
5734
  if (this.navigateConversation) return this.navigateConversation(r);
5705
5735
  this.resetChat();
5706
- let l;
5736
+ let c;
5707
5737
  if (r) {
5708
- if (l = this.sessionCtx.sessionsState.get().data.find((n) => n.id === r), !l) return;
5709
- this.sessionCtx.sessionState.setPartial({ session: l });
5738
+ if (c = this.sessionCtx.sessionsState.get().data.find((n) => n.id === r), !c) return;
5739
+ this.sessionCtx.sessionState.setPartial({ session: c });
5710
5740
  }
5711
- return this.state.setPartial({ screen: "chat" }), (t = (s = this.config.hooks) == null ? void 0 : s.onNavigateToChat) == null || t.call(s, { session: l }), this.widget;
5741
+ return this.state.setPartial({ screen: "chat" }), (a = (s = this.config.hooks) == null ? void 0 : s.onNavigateToChat) == null || a.call(s, { session: c }), this.widget;
5712
5742
  }, this.config = e.config, this.contactCtx = e.contactCtx, this.sessionCtx = e.sessionCtx, this.resetChat = e.resetChat, this.state = new S({
5713
- screen: this.contactCtx.shouldCollectData() ? "welcome" : (a = this.config.router) != null && a.chatScreenOnly ? "chat" : "sessions"
5743
+ screen: this.contactCtx.shouldCollectData() ? "welcome" : (t = this.config.router) != null && t.chatScreenOnly ? "chat" : "sessions"
5714
5744
  }), this.shouldRestoreLastSession = ((o = this.config.router) == null ? void 0 : o.restoreLastSession) ?? !1, this.readStoredSession(), this.registerRoutingListener();
5715
5745
  }
5716
5746
  }
5717
5747
  class Ra {
5718
5748
  constructor({
5719
5749
  storage: e,
5720
- config: a
5750
+ config: t
5721
5751
  }) {
5722
5752
  this.KEYS = {
5723
5753
  contactToken: (o) => `opencx-widget:org-token-${o}:contact-token`,
@@ -5737,8 +5767,8 @@ class Ra {
5737
5767
  }, 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) => {
5738
5768
  const r = await this.storage.get(o);
5739
5769
  if (r === null) return null;
5740
- const l = Number(r);
5741
- return Number.isFinite(l) ? l : null;
5770
+ const c = Number(r);
5771
+ return Number.isFinite(c) ? c : null;
5742
5772
  }, this.getCompanionPillOffsetX = async () => this.getFiniteNumber(this.companionKey("pill-offset-x")), this.setCompanionPillOffsetX = async (o) => {
5743
5773
  Number.isFinite(o) && await this.storage.set(this.companionKey("pill-offset-x"), String(o));
5744
5774
  }, this.getCompanionSidebarWidth = async () => this.getFiniteNumber(this.companionKey("sidebar-width")), this.setCompanionSidebarWidth = async (o) => {
@@ -5758,7 +5788,7 @@ class Ra {
5758
5788
  return o === "docked" || o === "floating" ? o : null;
5759
5789
  }, this.setCompanionSidebarMode = async (o) => {
5760
5790
  await this.storage.set(this.companionKey("sidebar-mode"), o);
5761
- }, this.storage = e, this.config = a;
5791
+ }, this.storage = e, this.config = t;
5762
5792
  }
5763
5793
  }
5764
5794
  function Ka({
@@ -5793,34 +5823,34 @@ function Ka({
5793
5823
  function La(i, e) {
5794
5824
  return i && e !== !1;
5795
5825
  }
5796
- function Fa(i, e) {
5797
- const a = e.features;
5826
+ function Oa(i, e) {
5827
+ const t = e.features;
5798
5828
  return {
5799
- dictation: La(i.features.dictation, a == null ? void 0 : a.dictation),
5829
+ dictation: La(i.features.dictation, t == null ? void 0 : t.dictation),
5800
5830
  attachments: i.features.attachments,
5801
- pageContext: i.features.pageContext && (a == null ? void 0 : a.pageContext) === !0,
5802
- clientTools: i.features.clientTools && i.features.pageContext && (a == null ? void 0 : a.pageContext) === !0 && (a == null ? void 0 : a.clientTools) === !0,
5803
- pageActions: i.features.pageActions && i.features.clientTools && i.features.pageContext && (a == null ? void 0 : a.pageContext) === !0 && (a == null ? void 0 : a.clientTools) === !0 && (a == null ? void 0 : a.pageActions) === !0
5831
+ pageContext: i.features.pageContext && (t == null ? void 0 : t.pageContext) === !0,
5832
+ clientTools: i.features.clientTools && i.features.pageContext && (t == null ? void 0 : t.pageContext) === !0 && (t == null ? void 0 : t.clientTools) === !0,
5833
+ pageActions: i.features.pageActions && i.features.clientTools && i.features.pageContext && (t == null ? void 0 : t.pageContext) === !0 && (t == null ? void 0 : t.clientTools) === !0 && (t == null ? void 0 : t.pageActions) === !0
5804
5834
  };
5805
5835
  }
5806
- class Oa extends Error {
5807
- constructor(e, a, o) {
5808
- super(a), this.name = "WidgetInitializationError", this.code = e, this.details = o;
5836
+ class Fa extends Error {
5837
+ constructor(e, t, o) {
5838
+ super(t), this.name = "WidgetInitializationError", this.code = e, this.details = o;
5809
5839
  }
5810
5840
  }
5811
5841
  const j = class j {
5812
5842
  constructor({
5813
5843
  config: e,
5814
- storage: a,
5844
+ storage: t,
5815
5845
  getClientCapabilities: o,
5816
5846
  getRequestConfig: r,
5817
- modes: l,
5847
+ modes: c,
5818
5848
  org: s,
5819
- agent: t,
5849
+ agent: a,
5820
5850
  parent: n
5821
5851
  }) {
5822
5852
  if (this.modes = [], this.disposed = !1, this.createConversation = () => {
5823
- const c = new j({
5853
+ const l = new j({
5824
5854
  config: {
5825
5855
  ...this.config,
5826
5856
  router: {
@@ -5837,21 +5867,21 @@ const j = class j {
5837
5867
  getRequestConfig: this.getRequestConfig,
5838
5868
  getClientCapabilities: this.getClientCapabilities
5839
5869
  });
5840
- return c.routerCtx.state.setPartial({
5870
+ return l.routerCtx.state.setPartial({
5841
5871
  screen: this.contactCtx.shouldCollectData() ? "welcome" : "chat"
5842
- }), c;
5843
- }, this.releaseConversation = () => this.dispose(), this.dispose = ({ clearActiveSession: c = !1 } = {}) => {
5872
+ }), l;
5873
+ }, this.releaseConversation = () => this.dispose(), this.dispose = ({ clearActiveSession: l = !1 } = {}) => {
5844
5874
  if (this.disposed) return;
5845
5875
  this.disposed = !0, this.routerCtx.dispose(), this.activeSessionPollingCtx.dispose();
5846
- const d = this.sessionCtx.dispose({ clearActiveSession: c });
5876
+ const d = this.sessionCtx.dispose({ clearActiveSession: l });
5847
5877
  return this.messageCtx.reset(), this.uploadCtx.reset(), this.dictationCtx.stop({ executeFinalCommand: !1 }), d;
5848
5878
  }, this.resetChat = () => {
5849
5879
  this.sessionCtx.reset(), this.messageCtx.reset(), this.uploadCtx.reset();
5850
- }, this.reconcileAfterStream = (c) => this.activeSessionPollingCtx.reconcileAfterStream(c), !j.pollingIntervalsSeconds)
5880
+ }, this.reconcileAfterStream = (l) => this.activeSessionPollingCtx.reconcileAfterStream(l), !j.pollingIntervalsSeconds)
5851
5881
  throw Error(
5852
5882
  "Widget polling values are not defined, did you call WidgetCtx.initialize()"
5853
5883
  );
5854
- this.config = e, this.getRequestConfig = r ?? (() => this.config), this.getClientCapabilities = o, this.org = s, this.agent = t, this.api = (n == null ? void 0 : n.api) ?? new U({ config: e }), this.storageCtx = (n == null ? void 0 : n.storageCtx) ?? (a ? new Ra({ storage: a, config: e }) : void 0), this.modes = l, this.contactCtx = (n == null ? void 0 : n.contactCtx) ?? new he({
5884
+ this.config = e, this.getRequestConfig = r ?? (() => this.config), this.getClientCapabilities = o, this.org = s, this.agent = a, this.api = (n == null ? void 0 : n.api) ?? new U({ config: e }), this.storageCtx = (n == null ? void 0 : n.storageCtx) ?? (t ? new Ra({ storage: t, config: e }) : void 0), this.modes = c, this.contactCtx = (n == null ? void 0 : n.contactCtx) ?? new he({
5855
5885
  api: this.api,
5856
5886
  config: this.config,
5857
5887
  storageCtx: this.storageCtx
@@ -5892,47 +5922,47 @@ const j = class j {
5892
5922
  }), this.routerCtx = new Na(this);
5893
5923
  }
5894
5924
  get streaming() {
5895
- var e, a;
5896
- return (e = this.messageCtx) != null && e.hasPendingAgentWork ? !0 : (a = this.messageCtx) != null && a.state.get().isSendingMessage ? !1 : this.agent.streaming && this.getRequestConfig().streaming === !0;
5925
+ var e, t;
5926
+ return (e = this.messageCtx) != null && e.hasPendingAgentWork ? !0 : (t = this.messageCtx) != null && t.state.get().isSendingMessage ? !1 : this.agent.streaming && this.getRequestConfig().streaming === !0;
5897
5927
  }
5898
5928
  /**
5899
5929
  * The org's features narrowed by this embed's `config.features` — the
5900
5930
  * answers the UI asks for, resolved against the current options.
5901
5931
  */
5902
5932
  get features() {
5903
- return Fa(this.agent, this.getRequestConfig());
5933
+ return Oa(this.agent, this.getRequestConfig());
5904
5934
  }
5905
5935
  };
5906
5936
  j.pollingIntervalsSeconds = null, j.initialize = async ({
5907
5937
  config: e,
5908
- storage: a,
5938
+ storage: t,
5909
5939
  getClientCapabilities: o,
5910
5940
  getRequestConfig: r
5911
5941
  }) => {
5912
- var s, t;
5913
- const l = await new U({
5942
+ var s, a;
5943
+ const c = await new U({
5914
5944
  config: e
5915
5945
  }).getExternalWidgetConfig();
5916
- if (!l.data)
5917
- throw g.error("widget config fetch failed", l.error), new Oa(
5946
+ if (!c.data)
5947
+ throw k.error("widget config fetch failed", c.error), new Fa(
5918
5948
  "config-fetch-failed",
5919
5949
  "Failed to fetch widget config",
5920
- l.error
5950
+ c.error
5921
5951
  );
5922
5952
  return j.pollingIntervalsSeconds = {
5923
- session: ((s = l.data) == null ? void 0 : s.sessionPollingIntervalSeconds) || 10,
5924
- sessions: ((t = l.data) == null ? void 0 : t.sessionsPollingIntervalSeconds) || 60
5953
+ session: ((s = c.data) == null ? void 0 : s.sessionPollingIntervalSeconds) || 10,
5954
+ sessions: ((a = c.data) == null ? void 0 : a.sessionsPollingIntervalSeconds) || 60
5925
5955
  }, new j({
5926
5956
  config: e,
5927
- storage: a,
5957
+ storage: t,
5928
5958
  getClientCapabilities: o,
5929
5959
  getRequestConfig: r,
5930
- modes: l.data.modes || [],
5960
+ modes: c.data.modes || [],
5931
5961
  org: {
5932
- id: l.data.org.id,
5933
- name: l.data.org.name
5962
+ id: c.data.org.id,
5963
+ name: c.data.org.name
5934
5964
  },
5935
- agent: Ka(l.data)
5965
+ agent: Ka(c.data)
5936
5966
  });
5937
5967
  };
5938
5968
  let G = j;
@@ -5944,8 +5974,8 @@ function Ya(i, e) {
5944
5974
  } : e;
5945
5975
  }
5946
5976
  class Xa {
5947
- constructor({ attack: e, release: a }) {
5948
- this.value = 0, this.attack = e, this.release = a;
5977
+ constructor({ attack: e, release: t }) {
5978
+ this.value = 0, this.attack = e, this.release = t;
5949
5979
  }
5950
5980
  next(e) {
5951
5981
  return this.value += (e - this.value) * (e > this.value ? this.attack : this.release), this.value;
@@ -5966,9 +5996,9 @@ function Y(i) {
5966
5996
  }
5967
5997
  function Qa(i) {
5968
5998
  if (!Array.isArray(i)) return I;
5969
- const e = [], a = /* @__PURE__ */ new Set();
5999
+ const e = [], t = /* @__PURE__ */ new Set();
5970
6000
  for (const o of i)
5971
- !Y(o) || a.has(o) || (a.add(o), e.push(o));
6001
+ !Y(o) || t.has(o) || (t.add(o), e.push(o));
5972
6002
  return e.length > 0 ? e : I;
5973
6003
  }
5974
6004
  function et(i, e) {
@@ -5986,7 +6016,7 @@ export {
5986
6016
  Xa as DictationLevelSmoother,
5987
6017
  S as PrimitiveState,
5988
6018
  G as WidgetCtx,
5989
- Oa as WidgetInitializationError,
6019
+ Fa as WidgetInitializationError,
5990
6020
  Da as buildSendMessageBody,
5991
6021
  q as genUuid,
5992
6022
  xa as getTranslation,
@@ -5996,7 +6026,7 @@ export {
5996
6026
  Ja as isRtlLanguage,
5997
6027
  Sa as isSupportedLanguage,
5998
6028
  $a as isTurnSteeredPart,
5999
- g as log,
6029
+ k as log,
6000
6030
  Qa as normalizeCompanionLayouts,
6001
6031
  Ya as resolveClientPresentation,
6002
6032
  et as resolveCompanionDefaultLayout,