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

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