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

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