@osvi-ai/chat 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -3
  3. package/dist/core.js +10 -0
  4. package/dist/core.js.map +1 -0
  5. package/dist/index-BsRyQwUM.js +1331 -0
  6. package/dist/index-BsRyQwUM.js.map +1 -0
  7. package/dist/types/core/client.d.ts +65 -0
  8. package/dist/types/core/connection.d.ts +78 -0
  9. package/dist/types/core/errors.d.ts +14 -0
  10. package/dist/types/core/http.d.ts +38 -0
  11. package/dist/types/core/index.d.ts +7 -0
  12. package/dist/types/core/interactions.d.ts +50 -0
  13. package/dist/types/core/protocol/envelope.d.ts +2 -0
  14. package/dist/types/core/protocol/readers.d.ts +14 -0
  15. package/dist/types/core/protocol/types.d.ts +118 -0
  16. package/dist/types/core/protocol/validators.d.ts +10 -0
  17. package/dist/types/core/state.d.ts +23 -0
  18. package/dist/types/core/storage.d.ts +10 -0
  19. package/dist/types/core/version.d.ts +1 -0
  20. package/dist/types/ui/define.d.ts +1 -0
  21. package/dist/types/ui/index.d.ts +9 -0
  22. package/dist/types/ui/osvi-chat.d.ts +69 -0
  23. package/dist/types/ui/panel/attrs.d.ts +6 -0
  24. package/dist/types/ui/panel/composer.d.ts +10 -0
  25. package/dist/types/ui/panel/linkify.d.ts +7 -0
  26. package/dist/types/ui/panel/transcript.d.ts +4 -0
  27. package/dist/types/ui/strings.d.ts +27 -0
  28. package/dist/types/ui/styles.d.ts +1 -0
  29. package/dist/types/ui/theme.d.ts +22 -0
  30. package/dist/types/ui/tools/base.d.ts +14 -0
  31. package/dist/types/ui/tools/osvi-buttons.d.ts +10 -0
  32. package/dist/types/ui/tools/osvi-carousel.d.ts +16 -0
  33. package/dist/types/ui/tools/osvi-date-picker.d.ts +17 -0
  34. package/dist/types/widget/config.d.ts +22 -0
  35. package/dist/types/widget/index.d.ts +1 -0
  36. package/dist/types/widget/launcher.d.ts +35 -0
  37. package/dist/types/widget/widget.d.ts +13 -0
  38. package/dist/ui.js +49 -0
  39. package/dist/ui.js.map +1 -0
  40. package/dist/ui.mjs +570 -0
  41. package/dist/ui.mjs.map +1 -0
  42. package/dist/widget.js +59 -0
  43. package/dist/widget.js.map +1 -0
  44. package/package.json +60 -4
@@ -0,0 +1,1331 @@
1
+ const nt = "0.1.0", rt = /* @__PURE__ */ new Set([
2
+ "origin_not_allowed",
3
+ "agent_inactive",
4
+ "agent_archived",
5
+ "agent_not_found",
6
+ "session_not_found",
7
+ "session_closed",
8
+ "invalid_customer_id",
9
+ "invalid_token",
10
+ "session_unavailable",
11
+ "stream_unavailable",
12
+ "token_failed",
13
+ "rate_limited",
14
+ "network",
15
+ "interaction_not_pending",
16
+ "interaction_suspended",
17
+ "invalid_interaction",
18
+ "unknown"
19
+ ]), ot = /* @__PURE__ */ new Set(["rate_limited", "network", "session_unavailable", "stream_unavailable", "token_failed"]);
20
+ function f(i, t) {
21
+ const e = i && rt.has(i) ? i : "unknown";
22
+ return { code: e, message: t || e, retryable: ot.has(e) };
23
+ }
24
+ class m extends Error {
25
+ constructor(t, e) {
26
+ super(t.message), this.error = t, this.status = e, this.name = "ChatRequestError";
27
+ }
28
+ }
29
+ const at = 3e5;
30
+ function X(i, t = Date.now()) {
31
+ return typeof i != "number" || !Number.isFinite(i) ? t + at : i < 1e12 ? i * 1e3 : i;
32
+ }
33
+ class ct {
34
+ constructor(t, e = (...s) => globalThis.fetch.bind(globalThis)(...s)) {
35
+ this.fetchImpl = e, this.base = t.replace(/\/+$/, "");
36
+ }
37
+ resolveUrl(t) {
38
+ return `${this.base}${t}`;
39
+ }
40
+ bootstrap(t, e, s) {
41
+ const n = `?customer_id=${encodeURIComponent(e)}`;
42
+ return this.request(`/public/chat/agents/${encodeURIComponent(t)}/bootstrap${n}`, { signal: s });
43
+ }
44
+ createSession(t, e) {
45
+ return this.request(`/public/chat/agents/${encodeURIComponent(t)}/session`, {
46
+ method: "POST",
47
+ body: JSON.stringify({ customer_id: e })
48
+ });
49
+ }
50
+ async mintPublicToken(t) {
51
+ const e = await this.request(
52
+ `/public/chat/session/${encodeURIComponent(t)}/ws_token`,
53
+ { method: "POST", body: "{}" }
54
+ );
55
+ if (!e?.token || !e?.ws_url) throw new m(f("stream_unavailable"), 200);
56
+ return { token: e.token, wsUrl: e.ws_url, expiresAt: X(e.expires_at) };
57
+ }
58
+ snapshot(t, e) {
59
+ return this.request(`/public/chat/session/${encodeURIComponent(t)}/snapshot`, {
60
+ headers: { Authorization: `Bearer ${e}` }
61
+ });
62
+ }
63
+ async request(t, e = {}) {
64
+ let s;
65
+ try {
66
+ const r = this.fetchImpl, o = { ...e.headers };
67
+ e.body !== void 0 && (o["Content-Type"] = "application/json"), s = await r(this.resolveUrl(t), { ...e, credentials: "omit", headers: o });
68
+ } catch (r) {
69
+ throw r?.name === "AbortError" ? r : new m(f("network", "Network error"), 0);
70
+ }
71
+ let n = null;
72
+ try {
73
+ n = await s.json();
74
+ } catch {
75
+ n = null;
76
+ }
77
+ if (!s.ok || n?.success === !1) {
78
+ const r = f(
79
+ typeof n?.error == "string" ? n.error : void 0,
80
+ typeof n?.message == "string" ? n.message : void 0
81
+ );
82
+ if (typeof n?.origin == "string" && (r.origin = n.origin), s.status === 429) {
83
+ r.code = "rate_limited", r.retryable = !0;
84
+ const o = Number(s.headers.get("Retry-After")), a = Number(n?.retry_after), h = Number.isFinite(o) && o > 0 ? o : a;
85
+ Number.isFinite(h) && h > 0 && (r.retryAfterSeconds = h);
86
+ }
87
+ throw new m(r, s.status);
88
+ }
89
+ return n?.data ?? n;
90
+ }
91
+ }
92
+ const $ = [
93
+ { tool_type: "ui_buttons", schema_version: 1 },
94
+ { tool_type: "ui_buttons", schema_version: 2 },
95
+ { tool_type: "ui_carousel", schema_version: 1 },
96
+ { tool_type: "ui_date_picker", schema_version: 1 }
97
+ ], ht = 65536, dt = 2e3, lt = 8192, B = 2048, j = /^[A-Za-z0-9_-]{1,64}$/, w = (i) => !!i && typeof i == "object" && !Array.isArray(i), S = (i, t) => Object.keys(i).every((e) => t.includes(e)), ut = (i) => [...i].length, Q = (i) => new TextEncoder().encode(i).length, pt = (i) => [...i].some((t) => {
98
+ const e = t.codePointAt(0) ?? 0;
99
+ return e === 127 || e < 32 && e !== 9 && e !== 10 && e !== 13;
100
+ }), ft = (i) => [...i].some((t) => {
101
+ const e = t.codePointAt(0) ?? 0;
102
+ return e <= 32 || e === 127;
103
+ }), g = (i, t, e = !1) => typeof i == "string" && ut(i) <= t && !pt(i) && (!e || i.trim().length > 0), V = (i) => Array.isArray(i) ? i.map(V) : w(i) ? Object.fromEntries(Object.keys(i).sort().map((t) => [t, V(i[t])])) : i, G = (i) => {
104
+ try {
105
+ return Q(JSON.stringify(V(i))) <= ht;
106
+ } catch {
107
+ return !1;
108
+ }
109
+ };
110
+ function gt(i) {
111
+ return typeof i == "string" && /^\/public\/chat\/images\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/(?:0|[1-9][0-9]*)$/i.test(i);
112
+ }
113
+ function mt(i) {
114
+ if (typeof i != "string" || i.length === 0 || i.length > B || ft(i)) return !1;
115
+ try {
116
+ const t = new URL(i), e = t.hostname.toLowerCase();
117
+ return t.protocol !== "https:" || t.username || t.password || t.hash || t.port || !e || e === "localhost" || e.endsWith(".localhost") || e.endsWith(".local") || e.endsWith(".internal") || e.startsWith("[") || /^\d{1,3}(?:\.\d{1,3}){3}$/.test(e) ? !1 : t.toString().length <= B;
118
+ } catch {
119
+ return !1;
120
+ }
121
+ }
122
+ function O(i, t) {
123
+ if (!w(i) || !S(i, ["label", "description", "options"]) || !g(i.label, 160, !0) || "description" in i && i.description !== void 0 && !g(i.description, 240) || !Array.isArray(i.options) || i.options.length === 0 || t !== void 0) return !1;
124
+ const e = /* @__PURE__ */ new Set();
125
+ let s = 0;
126
+ for (const n of i.options) {
127
+ if (!w(n) || !S(n, ["id", "label", "description", "allow_input", "input_placeholder"]) || typeof n.id != "string" || !j.test(n.id) || e.has(n.id) || !g(n.label, 80, !0) || "description" in n && n.description !== void 0 && !g(n.description, 240)) return !1;
128
+ const r = n.allow_input === !0;
129
+ if ("allow_input" in n && !r || "input_placeholder" in n && (!r || !g(n.input_placeholder, 160, !0)) || (r && (s += 1), s > 1)) return !1;
130
+ e.add(n.id);
131
+ }
132
+ return G(i);
133
+ }
134
+ function Z(i, t) {
135
+ return O(i, t) && i.options.every((e) => !Object.prototype.hasOwnProperty.call(e, "allow_input") && !Object.prototype.hasOwnProperty.call(e, "input_placeholder"));
136
+ }
137
+ function tt(i, t, e = !1) {
138
+ if (!w(i) || !S(i, ["label", "description", "items"]) || !g(i.label, 160, !0) || "description" in i && i.description !== void 0 && !g(i.description, 240) || !Array.isArray(i.items) || i.items.length === 0 || t !== void 0) return !1;
139
+ const s = /* @__PURE__ */ new Set();
140
+ for (const n of i.items) {
141
+ if (!w(n) || !S(n, ["id", "title", "description", "image", "action_label"]) || typeof n.id != "string" || !j.test(n.id) || s.has(n.id) || !g(n.title, 120, !0) || "description" in n && n.description !== void 0 && !g(n.description, 500) || "action_label" in n && n.action_label !== void 0 && !g(n.action_label, 80, !0) || "image" in n && n.image !== void 0 && (!w(n.image) || !S(n.image, ["url", "alt"]) || !(mt(n.image.url) || e && gt(n.image.url)) || !g(n.image.alt, 240, !0)))
142
+ return !1;
143
+ s.add(n.id);
144
+ }
145
+ return G(i);
146
+ }
147
+ function P(i) {
148
+ if (typeof i != "string" || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(i)) return !1;
149
+ const t = Number(i.slice(0, 4)), e = Number(i.slice(5, 7)), s = Number(i.slice(8, 10));
150
+ if (t < 1 || t > 9999 || e < 1 || e > 12 || s < 1) return !1;
151
+ const r = [31, t % 4 === 0 && (t % 100 !== 0 || t % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
152
+ return s <= r[e - 1];
153
+ }
154
+ function L(i) {
155
+ return !w(i) || !S(i, ["label", "description", "min_date", "max_date", "confirm_label", "selection_mode"]) || !g(i.label, 160, !0) || !["single", "range"].includes(String(i.selection_mode)) || "description" in i && i.description !== void 0 && !g(i.description, 240) || "confirm_label" in i && i.confirm_label !== void 0 && !g(i.confirm_label, 80, !0) || "min_date" in i && i.min_date !== void 0 && !P(i.min_date) || "max_date" in i && i.max_date !== void 0 && !P(i.max_date) || typeof i.min_date == "string" && typeof i.max_date == "string" && i.min_date > i.max_date ? !1 : G(i);
156
+ }
157
+ function $t(i, t) {
158
+ return i.tool_type === "ui_buttons" && i.schema_version === 1 ? Z(t) : i.tool_type === "ui_buttons" && i.schema_version === 2 ? O(t) : i.tool_type === "ui_carousel" && i.schema_version === 1 ? tt(t, void 0, !0) : i.tool_type === "ui_date_picker" && i.schema_version === 1 ? L(t) : !1;
159
+ }
160
+ function et(i, t) {
161
+ return !w(t) || !S(t, ["kind", "value"]) || Object.keys(t).length !== 2 ? !1 : t.kind === "date_range" ? i.tool_type === "ui_date_picker" && i.schema_version === 1 && w(t.value) && S(t.value, ["start_date", "end_date"]) && Object.keys(t.value).length === 2 && P(t.value.start_date) && P(t.value.end_date) && t.value.start_date < t.value.end_date : typeof t.value != "string" ? !1 : t.kind === "selection" ? (i.tool_type === "ui_buttons" || i.tool_type === "ui_carousel") && j.test(t.value) : t.kind === "text" ? i.tool_type === "ui_buttons" && i.schema_version === 2 && t.value === t.value.trim() && g(t.value, dt, !0) && Q(t.value) <= lt : t.kind === "date" ? i.tool_type === "ui_date_picker" && i.schema_version === 1 && P(t.value) : !1;
162
+ }
163
+ const W = (i) => i !== null && typeof i == "object" && !Array.isArray(i), _t = /* @__PURE__ */ new Set(["preparing", "pending", "accepted", "resumed", "cancelled", "expired"]);
164
+ function b(i) {
165
+ if (!W(i) || i.type !== "interaction" || typeof i.id != "string" || !i.id || i.role !== "assistant" || typeof i.content != "string" || typeof i.interaction_id != "string" || !i.interaction_id || typeof i.tool_type != "string" || !Number.isSafeInteger(i.schema_version) || Number(i.schema_version) < 1 || !Number.isSafeInteger(i.interaction_revision) || Number(i.interaction_revision) < 1 || !_t.has(String(i.interaction_status)) || !W(i.presentation)) return null;
166
+ const t = { tool_type: i.tool_type, schema_version: Number(i.schema_version) }, e = i.response_payload;
167
+ return e != null && !et(t, e) ? null : {
168
+ id: i.id,
169
+ type: "interaction",
170
+ role: "assistant",
171
+ content: i.content,
172
+ interaction_id: i.interaction_id,
173
+ tool_type: i.tool_type,
174
+ schema_version: Number(i.schema_version),
175
+ presentation: i.presentation,
176
+ interaction_status: i.interaction_status,
177
+ interaction_revision: Number(i.interaction_revision),
178
+ ...typeof i.created_at == "string" ? { created_at: i.created_at } : {},
179
+ ...typeof i.selected_option_id == "string" ? { selected_option_id: i.selected_option_id } : {},
180
+ ...e !== void 0 ? { response_payload: e } : {}
181
+ };
182
+ }
183
+ function y(i) {
184
+ if (!W(i) || typeof i.id != "string" && typeof i.id != "number" || typeof i.content != "string" || !["assistant", "user", "operator", "system"].includes(String(i.role))) return null;
185
+ const t = b({ ...i, id: String(i.id) });
186
+ return {
187
+ id: String(i.id),
188
+ content: i.content,
189
+ type: i.type === "interaction" ? "interaction" : "message",
190
+ ts: typeof i.created_at == "string" ? i.created_at : typeof i.ts == "string" ? i.ts : (/* @__PURE__ */ new Date()).toISOString(),
191
+ ...t ?? {},
192
+ role: i.role
193
+ };
194
+ }
195
+ function R(i) {
196
+ return typeof i == "string" && /^\d+$/.test(i) ? i.replace(/^0+(?=\d)/, "") : null;
197
+ }
198
+ function k(i, t) {
199
+ return i.length === t.length ? i === t ? 0 : i > t ? 1 : -1 : i.length > t.length ? 1 : -1;
200
+ }
201
+ function M(i, t) {
202
+ const e = [...i];
203
+ for (const s of t) {
204
+ const n = e.findIndex((r) => r.id === s.id || s.interaction_id && r.interaction_id === s.interaction_id);
205
+ if (n < 0) e.push(s);
206
+ else {
207
+ const r = e[n], o = (h) => h.interaction_status === "preparing" ? 0 : h.interaction_status === "pending" ? 1 : h.interaction_status === "accepted" ? 2 : 3;
208
+ !(s.interaction_revision === r.interaction_revision && o(s) < o(r)) && (!s.interaction_revision || !r.interaction_revision || s.interaction_revision >= r.interaction_revision) && (e[n] = { ...r, ...s });
209
+ }
210
+ }
211
+ return e;
212
+ }
213
+ const yt = /* @__PURE__ */ new Set(["user", "ai", "assistant", "operator", "support", "system"]);
214
+ function N(i) {
215
+ if (!i || typeof i != "object") return null;
216
+ const t = i, e = typeof t.id == "number" ? String(t.id) : t.id;
217
+ if (typeof e != "string" || e === "" || typeof t.content != "string" || typeof t.role != "string" || !yt.has(t.role)) return null;
218
+ const s = { id: e, role: t.role, content: t.content };
219
+ return typeof t.created_at == "string" && (s.created_at = t.created_at), (t.type === "interaction" || t.type === "message") && (s.type = t.type), s;
220
+ }
221
+ const v = (i) => ["pending", "accepted"].includes(i.interaction_status);
222
+ class wt {
223
+ constructor(t) {
224
+ this.host = t, this._active = null, this._cursor = "0", this._pending = !1, this._error = null, this.operations = /* @__PURE__ */ new Map(), this.operation = null, this.generation = 0, this.refreshInFlight = !1, this.recoveryCursor = null;
225
+ }
226
+ get active() {
227
+ return this._active;
228
+ }
229
+ get cursor() {
230
+ return this._cursor;
231
+ }
232
+ get pending() {
233
+ return this._pending;
234
+ }
235
+ get error() {
236
+ return this._error;
237
+ }
238
+ setActive(t) {
239
+ this._active = t, this.host.onChange();
240
+ }
241
+ setCursor(t) {
242
+ this._cursor = t, this.host.onChange();
243
+ }
244
+ setSelectionPending(t) {
245
+ this._pending = t, this.host.onChange();
246
+ }
247
+ setInteractionError(t) {
248
+ this._error = t, this.host.onChange();
249
+ }
250
+ setRows(t) {
251
+ this.host.updateItems((e) => {
252
+ let s = e.length;
253
+ for (; s > 0 && e[s - 1].kind !== "divider"; ) s -= 1;
254
+ const n = e.slice(s);
255
+ return [...e.slice(0, s), ...kt(t(St(n)), n)];
256
+ });
257
+ }
258
+ reset() {
259
+ this.generation += 1, this.refreshInFlight = !1, this.recoveryCursor = null, this.setActive(null), this._cursor = "0", this.setCursor("0"), this.operations.clear(), this.operation = null, this.setSelectionPending(!1), this.setInteractionError(null);
260
+ }
261
+ reject(t, e) {
262
+ this.operations.delete(t.interactionId), this.operations.size === 0 && (this.recoveryCursor = null), this.operation === t && (this.operation = null), this.setSelectionPending(!1), this.setInteractionError(e);
263
+ const s = this._active, n = s?.interaction_id === t.interactionId && s.interaction_revision <= t.original.interaction_revision;
264
+ n && this.setActive(t.original), this.setRows((r) => r.filter((o) => o.id !== t.messageId).map((o) => n && o.interaction_id === t.interactionId ? y(t.original) : o));
265
+ }
266
+ mergeProjection(t, e) {
267
+ const s = y(e), n = t && this.operations.get(t.interaction_id);
268
+ n && s?.role === "user" && (this.operations.delete(n.interactionId), this.operations.size === 0 && (this.recoveryCursor = null), this.operation === n && (this.operation = null), this.setSelectionPending(!1), this.setInteractionError(null));
269
+ const r = [t && y(t), s?.role === "user" ? s : null].filter((o) => o !== null);
270
+ this.setRows((o) => {
271
+ const a = n && s?.role === "user" && o.some((h) => h.id === n.messageId) ? o.flatMap((h) => h.id === n.messageId ? [s] : h.id === s.id ? [] : [h]) : o;
272
+ return M(a, r);
273
+ });
274
+ }
275
+ refreshMissingOutcome(t) {
276
+ if (this.operations.size === 0) {
277
+ this.recoveryCursor = null;
278
+ return;
279
+ }
280
+ if ((this.recoveryCursor === null || k(t, this.recoveryCursor) > 0) && (this.recoveryCursor = t), this.refreshInFlight) return;
281
+ const e = this.recoveryCursor, s = [...this.operations.values()], n = (a) => this.operations.get(a.interactionId) === a, r = this.generation, o = this.host.sessionId();
282
+ this.refreshInFlight = !0, this.setSelectionPending(!0), this.host.refreshSnapshot().then((a) => {
283
+ if (!a) throw new Error("Snapshot unavailable");
284
+ if (r !== this.generation || o !== this.host.sessionId() || a.session !== null && a.session.id !== o || !s.some(n)) return;
285
+ const h = R(a.interaction_cursor);
286
+ if (h === null || k(h, this.recoveryCursor ?? e) < 0 || k(h, this._cursor) < 0) return;
287
+ const c = a.active_interaction === null ? null : b(a.active_interaction);
288
+ if (a.active_interaction !== null && (!c || !v(c))) return;
289
+ const l = a.messages.map(y).filter((d) => d !== null), _ = y(a.interaction_response_message);
290
+ c && l.push(y(c)), _?.role === "user" && l.push(_);
291
+ const u = s.filter((d) => n(d) && (c?.interaction_id !== d.interactionId || c.interaction_status === "accepted" && _?.role === "user")), p = new Set(u.map((d) => d.messageId));
292
+ this.setRows((d) => M(d.filter((I) => !p.has(I.id)), l).sort((I, it) => Date.parse(I.ts) - Date.parse(it.ts) || 0)), u.forEach((d) => this.operations.delete(d.interactionId)), this.operation && u.includes(this.operation) && (this.operation = null), this._cursor = h, this.recoveryCursor = null, this.setCursor(h), this.setActive(c), this.setSelectionPending(this.operation !== null), this.setInteractionError(null);
293
+ }).catch(() => {
294
+ r === this.generation && s.some(n) && this.setInteractionError({ code: "network", message: "Reconnecting to confirm your selection…" });
295
+ }).finally(() => {
296
+ if (r === this.generation) {
297
+ if (this.refreshInFlight = !1, this.operations.size === 0) {
298
+ this.recoveryCursor = null;
299
+ return;
300
+ }
301
+ const a = this.recoveryCursor;
302
+ a !== null && k(a, e) > 0 && this.refreshMissingOutcome(a);
303
+ }
304
+ });
305
+ }
306
+ hasMissingOutcome(t) {
307
+ return [...this.operations.values()].some((e) => !t || e.interactionId !== t.interaction_id);
308
+ }
309
+ applySnapshot(t) {
310
+ const e = R(t.interaction_cursor);
311
+ if (e === null || !Object.prototype.hasOwnProperty.call(t, "active_interaction")) return;
312
+ const s = k(e, this._cursor);
313
+ if (s < 0) return;
314
+ const n = t.active_interaction === null ? null : b(t.active_interaction);
315
+ if (!(t.active_interaction !== null && (!n || !v(n)))) {
316
+ if (s > 0 && this.hasMissingOutcome(n)) {
317
+ this.refreshMissingOutcome(e);
318
+ return;
319
+ }
320
+ s === 0 && (this.operation || n && this.operations.has(n.interaction_id) || n === null && this._active) || (this._cursor = e, this.setCursor(e), this.setActive(n), this.mergeProjection(n, t.interaction_response_message), (!n || this.operation?.interactionId !== n.interaction_id) && (this.operation = null, this.setSelectionPending(!1)));
321
+ }
322
+ }
323
+ applyEvent(t) {
324
+ if (!["interaction_published", "interaction_updated", "interaction_closed"].includes(t.type)) return !1;
325
+ if (t.session_id && t.session_id !== this.host.sessionId()) return !0;
326
+ const e = R(t.payload.interaction_cursor), s = b(t.payload);
327
+ return !s || s.interaction_status === "preparing" || e === null || k(e, this._cursor) <= 0 ? !0 : this.hasMissingOutcome(s) || !v(s) && this.operations.has(s.interaction_id) && !y(t.payload.interaction_response_message) ? (this.refreshMissingOutcome(e), !0) : (this._cursor = e, this.setCursor(e), this.mergeProjection(s, t.payload.interaction_response_message), v(s) ? this.setActive(s) : this._active?.interaction_id === s.interaction_id && this.setActive(null), this.operation && (this.operation.interactionId !== s.interaction_id || !v(s)) && (this.operation = null, this.setSelectionPending(!1)), !0);
328
+ }
329
+ handleWriteResult(t) {
330
+ const e = t, s = [...this.operations.values()].find((n) => n.messageId === e.message_id);
331
+ if (!s) return !1;
332
+ if (e.error || ["refused", "failed", "error", "busy"].includes(String(e.state))) {
333
+ const n = ["interaction_not_pending", "interaction_suspended", "invalid_interaction", "network"].includes(String(e.error)) ? e.error : "invalid_interaction";
334
+ this.reject(s, { code: n, message: String(e.error || e.reason || "The selection was not accepted. Please try again.") });
335
+ } else
336
+ s.acknowledged = !0, this.operation === s && (this.operation = null), this.setSelectionPending(!1), this.setInteractionError(null);
337
+ return !0;
338
+ }
339
+ respond(t, e) {
340
+ const s = this._active;
341
+ if (!this.host.sessionId() || this.host.humanConnected() || this.operation || !s || s.interaction_id !== t || s.interaction_status !== "pending" || !$.some((c) => c.tool_type === s.tool_type && c.schema_version === s.schema_version) || !et(s, e)) return !1;
342
+ const n = s.tool_type === "ui_buttons" && s.schema_version === 1;
343
+ let r = null;
344
+ if (n && e.kind === "selection" && Z(s.presentation))
345
+ r = s.presentation.options.find((c) => c.id === e.value)?.label ?? null;
346
+ else if (!n && e.kind === "text" && s.tool_type === "ui_buttons" && O(s.presentation))
347
+ r = e.value;
348
+ else if (!n && e.kind === "selection" && s.tool_type === "ui_buttons" && O(s.presentation))
349
+ r = s.presentation.options.find((c) => c.id === e.value)?.label ?? null;
350
+ else if (e.kind === "selection" && s.tool_type === "ui_carousel" && tt(s.presentation, void 0, !0))
351
+ r = s.presentation.items.find((c) => c.id === e.value)?.title ?? null;
352
+ else if (e.kind === "date" && s.tool_type === "ui_date_picker" && s.schema_version === 1 && L(s.presentation) && s.presentation.selection_mode === "single")
353
+ (!s.presentation.min_date || e.value >= s.presentation.min_date) && (!s.presentation.max_date || e.value <= s.presentation.max_date) && (r = e.value);
354
+ else if (e.kind === "date_range" && s.tool_type === "ui_date_picker" && s.schema_version === 1 && L(s.presentation) && s.presentation.selection_mode === "range") {
355
+ const { start_date: c, end_date: l } = e.value;
356
+ (!s.presentation.min_date || c >= s.presentation.min_date) && (!s.presentation.max_date || l <= s.presentation.max_date) && (r = `${c} to ${l}`);
357
+ }
358
+ if (!r) return !1;
359
+ const o = this.host.newId(), a = {
360
+ interactionId: t,
361
+ messageId: o,
362
+ original: s,
363
+ acknowledged: !1,
364
+ sent: !1,
365
+ frame: {
366
+ type: "interaction_response",
367
+ interaction_id: t,
368
+ ...n ? { option_id: e.value } : { response: e },
369
+ message_id: o,
370
+ idempotency_key: this.host.newId(),
371
+ supported_interactions: $
372
+ }
373
+ };
374
+ this.operations.set(t, a), this.operation = a, this.setSelectionPending(!0), this.setInteractionError(null);
375
+ const h = {
376
+ ...s,
377
+ interaction_status: "accepted",
378
+ ...n ? { selected_option_id: e.value } : { response_payload: e }
379
+ };
380
+ return this.setActive(h), this.setRows((c) => M(c, [
381
+ y(h),
382
+ { id: o, type: "message", role: "user", content: r, ts: (/* @__PURE__ */ new Date()).toISOString(), local: !0 }
383
+ ])), a.sent = this.host.sendFrame(a.frame), !0;
384
+ }
385
+ onConnectionOpen() {
386
+ const t = this.operation;
387
+ t && !t.acknowledged && !this.host.humanConnected() && (t.sent = this.host.sendFrame(t.frame));
388
+ }
389
+ }
390
+ function St(i) {
391
+ const t = [];
392
+ for (const e of i)
393
+ e.kind === "interaction" ? t.push(y(e.interaction)) : e.kind === "message" && t.push({
394
+ id: e.serverId ?? e.id,
395
+ type: "message",
396
+ role: e.role === "human" ? "operator" : e.role,
397
+ content: e.content,
398
+ ts: e.createdAt
399
+ });
400
+ return t;
401
+ }
402
+ function kt(i, t) {
403
+ const e = /* @__PURE__ */ new Map();
404
+ for (const n of t) n.kind === "message" && (e.set(n.id, n), n.serverId && e.set(n.serverId, n));
405
+ const s = [];
406
+ for (const n of i) {
407
+ if (n.type === "interaction" && n.interaction_id) {
408
+ const o = b(n);
409
+ o && s.push({ kind: "interaction", id: n.interaction_id, interaction: o });
410
+ continue;
411
+ }
412
+ if (n.role === "system") continue;
413
+ const r = e.get(n.id);
414
+ if (r) {
415
+ s.push(r.content === n.content ? r : { ...r, content: n.content });
416
+ continue;
417
+ }
418
+ if (n.local) {
419
+ s.push({ kind: "message", id: n.id, role: "user", content: n.content, createdAt: n.ts, status: "sending" });
420
+ continue;
421
+ }
422
+ s.push({
423
+ kind: "message",
424
+ id: `srv:${n.id}`,
425
+ serverId: n.id,
426
+ role: n.role === "operator" ? "human" : n.role,
427
+ content: n.content,
428
+ createdAt: n.ts,
429
+ status: "sent"
430
+ });
431
+ }
432
+ return s;
433
+ }
434
+ function bt(i) {
435
+ let t = i;
436
+ if (typeof i == "string")
437
+ try {
438
+ t = JSON.parse(i);
439
+ } catch {
440
+ return null;
441
+ }
442
+ if (!t || typeof t != "object" || Array.isArray(t)) return null;
443
+ const e = t;
444
+ if (typeof e.type != "string") return null;
445
+ const s = e.payload && typeof e.payload == "object" && !Array.isArray(e.payload) ? e.payload : {};
446
+ return { ...e, type: e.type, payload: s };
447
+ }
448
+ const It = 25e3, vt = 6e4, Tt = 3e4, z = 6e4, T = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4], x = 1e4, Ct = 4e3, At = 2, q = /* @__PURE__ */ new Set(["invalid_token", "session_not_found", "session_closed", "origin_not_allowed", "agent_archived", "agent_not_found"]);
449
+ function st() {
450
+ return {
451
+ isVisible: () => typeof document > "u" || document.visibilityState !== "hidden",
452
+ onVisible: (i) => {
453
+ const t = () => {
454
+ document.visibilityState !== "hidden" && i();
455
+ };
456
+ return typeof document > "u" ? () => {
457
+ } : (document.addEventListener("visibilitychange", t), () => document.removeEventListener("visibilitychange", t));
458
+ },
459
+ onOnline: (i) => typeof window > "u" ? () => {
460
+ } : (window.addEventListener("online", i), () => window.removeEventListener("online", i))
461
+ };
462
+ }
463
+ function C(i) {
464
+ i && (i.onopen = null, i.onmessage = null, i.onclose = null, i.onerror = null);
465
+ }
466
+ class Pt {
467
+ constructor(t) {
468
+ this.opts = t, this.socket = null, this.next = null, this.stopped = !1, this.started = !1, this.everOpened = !1, this.failures = 0, this.authCloses = 0, this.epoch = 0, this.rotating = !1, this.pingSupported = !0, this.lastInbound = 0, this.lastPingSentAt = 0, this.expiresAt = 0, this.timers = /* @__PURE__ */ new Set(), this.pingTimer = null, this.waitingForPage = /* @__PURE__ */ new Set(), this.page = t.page ?? st(), this.WS = t.WebSocketImpl ?? WebSocket, this.random = t.random ?? Math.random;
469
+ }
470
+ get isOpen() {
471
+ return !this.stopped && this.socket?.readyState === 1;
472
+ }
473
+ start() {
474
+ this.started || this.stopped || (this.started = !0, this.opts.onStatus("connecting"), this.connect());
475
+ }
476
+ send(t) {
477
+ return this.isOpen ? (this.socket.send(JSON.stringify(t)), !0) : !1;
478
+ }
479
+ stop() {
480
+ this.stopped = !0, this.epoch += 1, this.clearTimers(), this.stopPings(), this.waitingForPage.forEach((t) => t()), this.waitingForPage.clear(), this.abandon(this.next), this.next = null, this.abandon(this.socket), this.socket = null;
481
+ }
482
+ abandon(t) {
483
+ C(t);
484
+ try {
485
+ t?.close(1e3, "client-stop");
486
+ } catch {
487
+ }
488
+ }
489
+ recoveringStatus() {
490
+ return this.everOpened ? "recovering" : "connecting";
491
+ }
492
+ urlFor(t) {
493
+ const e = t.wsUrl.includes("?") ? "&" : "?";
494
+ return `${t.wsUrl}${e}token=${encodeURIComponent(t.token)}&sdk=${encodeURIComponent(this.opts.sdkVersion)}`;
495
+ }
496
+ async connect() {
497
+ if (this.stopped) return;
498
+ const t = this.epoch;
499
+ let e;
500
+ try {
501
+ e = await this.opts.mint();
502
+ } catch (s) {
503
+ if (this.stopped || t !== this.epoch) return;
504
+ this.handleMintFailure(s);
505
+ return;
506
+ }
507
+ if (!(this.stopped || t !== this.epoch))
508
+ try {
509
+ this.openSocket(e, !1);
510
+ } catch (s) {
511
+ this.handleMintFailure(s);
512
+ }
513
+ }
514
+ // Handlers are bound to `s`: events from a socket that is no longer current are ignored.
515
+ openSocket(t, e) {
516
+ const s = new this.WS(this.urlFor(t));
517
+ e ? this.next = s : (this.socket = s, this.expiresAt = t.expiresAt), s.onopen = () => {
518
+ this.stopped || (e ? this.next === s && this.swapIn(s, t.expiresAt) : this.socket === s && this.handleOpen());
519
+ }, s.onmessage = (n) => {
520
+ this.socket === s && this.handleMessage(n.data);
521
+ }, s.onclose = (n) => {
522
+ if (!this.stopped) {
523
+ if (this.next === s) {
524
+ C(s), this.next = null, this.later(x, () => this.whenVisible(() => {
525
+ this.rotate();
526
+ }));
527
+ return;
528
+ }
529
+ this.socket === s && this.handleClose(n.code, n.reason);
530
+ }
531
+ };
532
+ }
533
+ handleOpen() {
534
+ const t = this.everOpened;
535
+ this.everOpened = !0, this.failures = 0, this.authCloses = 0, this.pingSupported = !0, this.lastInbound = Date.now(), this.opts.onStatus("open"), !this.stopped && (this.startPings(), this.scheduleRotation(), !this.stopped && (this.opts.onOpen(), t && !this.stopped && this.opts.onReconnected()));
536
+ }
537
+ swapIn(t, e) {
538
+ const s = this.socket;
539
+ this.next = null, this.socket = t, this.expiresAt = e, this.failures = 0, this.authCloses = 0, this.pingSupported = !0, C(s);
540
+ try {
541
+ s?.close(Ct, "token-refresh");
542
+ } catch {
543
+ }
544
+ this.clearTimers(), this.lastInbound = Date.now(), this.startPings(), this.scheduleRotation(), this.opts.onOpen(), this.stopped || this.opts.onReconnected();
545
+ }
546
+ handleMessage(t) {
547
+ if (this.stopped) return;
548
+ this.lastInbound = Date.now();
549
+ const e = bt(t);
550
+ if (e) {
551
+ if (e.type === "ws_write_result" && e.payload.error === "invalid_input_type" && !e.payload.message_id) {
552
+ this.pingSupported = !1, this.stopPings();
553
+ return;
554
+ }
555
+ this.opts.onFrame(e);
556
+ }
557
+ }
558
+ handleClose(t, e) {
559
+ if (!this.stopped) {
560
+ if (this.epoch += 1, C(this.socket), this.socket = null, this.abandon(this.next), this.next = null, this.rotating = !1, this.stopPings(), this.clearTimers(), this.clearPageListeners(), t === 4401) {
561
+ if (this.authCloses += 1, this.authCloses > At) {
562
+ this.opts.onError(f("invalid_token")), this.scheduleBackoff();
563
+ return;
564
+ }
565
+ this.opts.onStatus(this.recoveringStatus()), this.whenVisible(() => this.reconnectNow());
566
+ return;
567
+ }
568
+ if (t === 1008 && e === "agent_inactive") {
569
+ this.opts.onError(f("agent_inactive")), this.stopped || this.opts.onStatus(this.recoveringStatus()), this.later(z, () => this.reconnectNow());
570
+ return;
571
+ }
572
+ if (t === 1008) {
573
+ this.terminate(e || "policy");
574
+ return;
575
+ }
576
+ this.scheduleBackoff();
577
+ }
578
+ }
579
+ handleMintFailure(t) {
580
+ const e = t instanceof m ? t.error : f("network");
581
+ if (e.code === "agent_inactive") {
582
+ this.opts.onError(e), this.stopped || this.opts.onStatus(this.recoveringStatus()), this.later(z, () => this.reconnectNow());
583
+ return;
584
+ }
585
+ if (q.has(e.code)) {
586
+ this.terminate(e.code);
587
+ return;
588
+ }
589
+ if (e.code === "rate_limited" && e.retryAfterSeconds) {
590
+ this.opts.onError(e), this.stopped || this.opts.onStatus(this.recoveringStatus()), this.later(e.retryAfterSeconds * 1e3, () => this.reconnectNow());
591
+ return;
592
+ }
593
+ this.scheduleBackoff();
594
+ }
595
+ reconnectNow() {
596
+ this.stopped || (this.opts.onStatus(this.recoveringStatus()), this.connect());
597
+ }
598
+ scheduleBackoff() {
599
+ if (this.stopped) return;
600
+ const t = Math.min(this.failures, T.length - 1);
601
+ if (this.failures += 1, this.failures > T.length) {
602
+ this.opts.onStatus("offline"), this.retryWhenReachable();
603
+ return;
604
+ }
605
+ this.opts.onStatus(this.recoveringStatus());
606
+ const e = Math.round(T[t] * (0.8 + 0.4 * this.random()));
607
+ this.later(e, () => {
608
+ this.connect();
609
+ });
610
+ }
611
+ // First of online / visible / 30 s timer wins and cancels the other two.
612
+ retryWhenReachable() {
613
+ if (this.stopped) return;
614
+ let t = !1;
615
+ const e = () => {
616
+ clearTimeout(o), this.timers.delete(o), n(), r(), this.waitingForPage.delete(e);
617
+ }, s = () => {
618
+ t || this.stopped || (t = !0, e(), this.reconnectNow());
619
+ }, n = this.page.onVisible(s), r = this.page.onOnline(s), o = setTimeout(() => {
620
+ this.stopped || s();
621
+ }, T[T.length - 1]);
622
+ this.timers.add(o), this.waitingForPage.add(e);
623
+ }
624
+ whenVisible(t) {
625
+ if (this.stopped) return;
626
+ if (this.page.isVisible()) {
627
+ t();
628
+ return;
629
+ }
630
+ let e = !1;
631
+ const s = this.page.onVisible(() => {
632
+ e || this.stopped || !this.page.isVisible() || (e = !0, s(), this.waitingForPage.delete(s), t());
633
+ });
634
+ this.waitingForPage.add(s);
635
+ }
636
+ startPings() {
637
+ this.stopPings(), this.lastPingSentAt = 0, this.pingTimer = setInterval(() => {
638
+ if (this.stopped || !this.isOpen || !this.pingSupported) return;
639
+ const t = Date.now(), e = this.lastPingSentAt > this.lastInbound;
640
+ if (this.page.isVisible() && e && t - this.lastInbound >= vt) {
641
+ this.declareDead();
642
+ return;
643
+ }
644
+ this.send({ type: "ping" }) && (this.lastPingSentAt = t);
645
+ }, It);
646
+ }
647
+ declareDead() {
648
+ const t = this.socket;
649
+ if (t) {
650
+ C(t);
651
+ try {
652
+ t.close(4001, "silent");
653
+ } catch {
654
+ }
655
+ this.handleClose(4001, "silent");
656
+ }
657
+ }
658
+ stopPings() {
659
+ this.pingTimer !== null && clearInterval(this.pingTimer), this.pingTimer = null;
660
+ }
661
+ scheduleRotation() {
662
+ const t = Math.max(5e3, this.expiresAt - Date.now() - Tt);
663
+ this.later(t, () => this.whenVisible(() => {
664
+ this.rotate();
665
+ }));
666
+ }
667
+ // Mint first, open the new socket, close the old one only once the new one is open.
668
+ async rotate() {
669
+ if (this.stopped || this.rotating || !this.isOpen || this.next) return;
670
+ this.rotating = !0;
671
+ const t = this.epoch;
672
+ let e;
673
+ try {
674
+ e = await this.opts.mint();
675
+ } catch (s) {
676
+ if (this.stopped || t !== this.epoch) return;
677
+ this.rotating = !1;
678
+ const n = s instanceof m ? s.error : f("network");
679
+ if (q.has(n.code)) {
680
+ this.terminate(n.code);
681
+ return;
682
+ }
683
+ const r = n.retryAfterSeconds ? n.retryAfterSeconds * 1e3 : x;
684
+ this.later(r, () => this.whenVisible(() => {
685
+ this.rotate();
686
+ }));
687
+ return;
688
+ }
689
+ if (!(this.stopped || t !== this.epoch)) {
690
+ this.rotating = !1;
691
+ try {
692
+ this.openSocket(e, !0);
693
+ } catch {
694
+ this.later(x, () => this.whenVisible(() => {
695
+ this.rotate();
696
+ }));
697
+ }
698
+ }
699
+ }
700
+ terminate(t) {
701
+ this.stop(), this.opts.onClosed(t);
702
+ }
703
+ later(t, e) {
704
+ if (this.stopped) return;
705
+ const s = setTimeout(() => {
706
+ this.timers.delete(s), this.stopped || e();
707
+ }, t);
708
+ this.timers.add(s);
709
+ }
710
+ clearPageListeners() {
711
+ this.waitingForPage.forEach((t) => t()), this.waitingForPage.clear();
712
+ }
713
+ clearTimers() {
714
+ this.timers.forEach(clearTimeout), this.timers.clear();
715
+ }
716
+ }
717
+ const U = "osvi.chat.visitor", Et = /^web:[0-9a-f]{32}$/;
718
+ function Ot() {
719
+ const i = /* @__PURE__ */ new Map();
720
+ return {
721
+ get: (t) => i.get(t) ?? null,
722
+ set: (t, e) => {
723
+ i.set(t, e);
724
+ },
725
+ remove: (t) => {
726
+ i.delete(t);
727
+ }
728
+ };
729
+ }
730
+ function Rt() {
731
+ const i = Ot();
732
+ let t = !1;
733
+ const e = (s, n) => {
734
+ if (t) return n();
735
+ try {
736
+ return s();
737
+ } catch {
738
+ return t = !0, n();
739
+ }
740
+ };
741
+ return {
742
+ get: (s) => e(() => window.localStorage.getItem(s), () => i.get(s)),
743
+ set: (s, n) => e(() => window.localStorage.setItem(s, n), () => i.set(s, n)),
744
+ remove: (s) => e(() => window.localStorage.removeItem(s), () => i.remove(s))
745
+ };
746
+ }
747
+ const Y = (i) => `web:${Array.from(i, (t) => t.toString(16).padStart(2, "0")).join("")}`;
748
+ let F = null;
749
+ function A(i, t) {
750
+ const e = i.get(U);
751
+ if (e && Et.test(e)) return e;
752
+ e !== null && i.remove(U);
753
+ let s;
754
+ try {
755
+ s = globalThis.crypto?.getRandomValues?.(new Uint8Array(16));
756
+ } catch {
757
+ }
758
+ if (s) {
759
+ const n = Y(s);
760
+ return i.set(U, n), n;
761
+ }
762
+ if (!F) {
763
+ const n = new Uint8Array(16);
764
+ for (let r = 0; r < n.length; r += 1)
765
+ n[r] = Math.floor(Math.random() * 256);
766
+ F = Y(n);
767
+ }
768
+ return F;
769
+ }
770
+ function D(i) {
771
+ return `osvi.chat.session.${i}`;
772
+ }
773
+ const Mt = "https://api.osvi.ai", Nt = 12e4, xt = 15e3, K = [1e3, 2e3, 4e3, 8e3, 16e3], Ut = 2048, Ft = /* @__PURE__ */ new Set(["session_closed", "session_dormant", "new_session"]);
774
+ function E() {
775
+ const i = globalThis.crypto;
776
+ if (i?.randomUUID) return i.randomUUID();
777
+ if (i?.getRandomValues) {
778
+ const t = i.getRandomValues(new Uint8Array(16));
779
+ t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128;
780
+ const e = Array.from(t, (s) => s.toString(16).padStart(2, "0")).join("");
781
+ return `${e.slice(0, 8)}-${e.slice(8, 12)}-${e.slice(12, 16)}-${e.slice(16, 20)}-${e.slice(20)}`;
782
+ }
783
+ return `${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`;
784
+ }
785
+ const H = () => ({
786
+ status: "idle",
787
+ mode: "ai",
788
+ awaitingReply: !1,
789
+ items: [],
790
+ activeInteraction: null,
791
+ interactionPending: !1,
792
+ agent: null,
793
+ error: null
794
+ }), J = {
795
+ user: "user",
796
+ ai: "assistant",
797
+ assistant: "assistant",
798
+ operator: "human",
799
+ support: "human"
800
+ };
801
+ class Dt {
802
+ // server mode: rotation returned a different session
803
+ constructor(t) {
804
+ this.opts = t, this.state = H(), this.listeners = /* @__PURE__ */ new Set(), this.conn = null, this.sessionId = null, this.latestToken = null, this.chain = Promise.resolve(), this.startP = null, this.ensureP = null, this.pending = /* @__PURE__ */ new Map(), this.openGen = 0, this.sessionGeneration = 0, this.seen = [], this.seenSet = /* @__PURE__ */ new Set(), this.timers = /* @__PURE__ */ new Set(), this.awaitingTimer = null, this.destroyed = !1, this.wantNewServerSession = !1, this.switchTo = null, this.http = new ct(t.baseUrl ?? Mt, t.fetch), this.store = t.store ?? Rt(), this.page = t.page ?? st(), this.interactions = new wt({
805
+ sessionId: () => this.sessionId,
806
+ humanConnected: () => this.state.mode === "human",
807
+ sendFrame: (e) => this.conn?.send(e) ?? !1,
808
+ updateItems: (e) => this.patch({ items: e(this.state.items) }),
809
+ refreshSnapshot: () => this.fetchSnapshot(),
810
+ onChange: () => this.patch({}),
811
+ newId: E
812
+ });
813
+ }
814
+ get serverMode() {
815
+ return this.opts.auth?.mode === "server";
816
+ }
817
+ serialize(t) {
818
+ const e = this.chain.then(t);
819
+ return this.chain = e.catch(() => {
820
+ }), e;
821
+ }
822
+ // ---------- public API ----------
823
+ start() {
824
+ return this.destroyed ? Promise.resolve() : (this.startP || (this.startP = this.serialize(() => this.doStart()).finally(() => {
825
+ this.startP = null;
826
+ })), this.startP);
827
+ }
828
+ async doStart() {
829
+ if (!(this.destroyed || this.sessionId && this.conn)) {
830
+ if (this.serverMode) {
831
+ await this.openServerSession();
832
+ return;
833
+ }
834
+ try {
835
+ const t = await this.http.bootstrap(this.opts.agentId, A(this.store));
836
+ if (this.destroyed) return;
837
+ this.patch({ agent: { agentId: this.opts.agentId, name: t.agent?.name ?? "" } }), t.session?.id && t.session.status === "active" ? this.adopt(t.session.id, t, this.pending.size ? "append" : "replace") : this.store.remove(D(this.opts.agentId));
838
+ } catch (t) {
839
+ this.fail(t, !1);
840
+ }
841
+ }
842
+ }
843
+ async send(t) {
844
+ if (this.destroyed) return { ok: !1, reason: "destroyed" };
845
+ const e = t.trim();
846
+ if (!e) return { ok: !1, reason: "empty" };
847
+ if (this.state.mode === "ai" && (this.interactions.pending || this.interactions.active?.interaction_status === "pending"))
848
+ return { ok: !1, reason: "awaiting_interaction" };
849
+ const s = E(), n = E(), r = {
850
+ kind: "message",
851
+ id: s,
852
+ role: "user",
853
+ content: e,
854
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
855
+ status: "sending",
856
+ idempotencyKey: n
857
+ };
858
+ return this.patch({ items: [...this.state.items, r] }), this.pending.set(s, { frame: this.frameFor(r), attempts: 0, gen: -1, ackTimer: null }), await this.ensureSession() ? (this.transmit(s), { ok: !0, messageId: s }) : (this.dropPending(s), this.setMessage(s, { status: "failed" }), { ok: !1, reason: "unavailable" });
859
+ }
860
+ async respond(t, e) {
861
+ return this.destroyed ? !1 : this.interactions.respond(t, e);
862
+ }
863
+ async retry(t) {
864
+ const e = this.state.items.find((s) => s.kind === "message" && s.id === t);
865
+ return !e || e.status !== "failed" || !e.idempotencyKey || this.destroyed ? !1 : (this.dropPending(t), this.pending.set(t, { frame: this.frameFor(e), attempts: 0, gen: -1, ackTimer: null }), this.setMessage(t, { status: "sending" }), await this.ensureSession() ? (this.transmit(t), !0) : (this.dropPending(t), this.setMessage(t, { status: "failed" }), !1));
866
+ }
867
+ newSession() {
868
+ return this.destroyed ? Promise.resolve(!1) : !this.sessionId && this.ensureP ? this.ensureP.then((t) => t !== null) : this.serialize(async () => {
869
+ if (this.destroyed) return !1;
870
+ if (this.sessionId && this.endSession("new_session"), this.serverMode)
871
+ return this.wantNewServerSession = !0, await this.openServerSession() !== null;
872
+ try {
873
+ const t = await this.http.createSession(this.opts.agentId, A(this.store));
874
+ return this.destroyed ? !1 : (this.adopt(t.id, null, "keep"), !0);
875
+ } catch (t) {
876
+ return this.fail(t, !1), !1;
877
+ }
878
+ });
879
+ }
880
+ subscribe(t) {
881
+ return this.listeners.add(t), () => this.listeners.delete(t);
882
+ }
883
+ getState() {
884
+ return this.state;
885
+ }
886
+ resolveUrl(t) {
887
+ return this.http.resolveUrl(t);
888
+ }
889
+ destroy() {
890
+ this.destroyed || (this.destroyed = !0, this.sessionGeneration += 1, this.conn?.stop(), this.conn = null, this.timers.forEach(clearTimeout), this.timers.clear(), this.pending.forEach((t) => {
891
+ t.ackTimer && clearTimeout(t.ackTimer);
892
+ }), this.pending.clear(), this.awaitingTimer && clearTimeout(this.awaitingTimer), this.interactions.reset(), this.sessionId = null, this.latestToken = null, this.switchTo = null, this.state = H(), this.listeners.clear());
893
+ }
894
+ // ---------- sessions ----------
895
+ ensureSession() {
896
+ return this.ensureP ? this.ensureP : (this.ensureP = this.serialize(async () => this.destroyed ? null : this.sessionId ? this.sessionId : this.serverMode ? this.openServerSession() : this.openAnonymousSession()).finally(() => {
897
+ this.ensureP = null;
898
+ }), this.ensureP);
899
+ }
900
+ async openAnonymousSession() {
901
+ try {
902
+ const t = A(this.store), e = await this.http.bootstrap(this.opts.agentId, t);
903
+ if (this.destroyed) return null;
904
+ if (this.patch({ agent: { agentId: this.opts.agentId, name: e.agent?.name ?? "" } }), e.session?.id && e.session.status === "active")
905
+ return this.adopt(e.session.id, e, "append"), this.sessionId;
906
+ const s = await this.http.createSession(this.opts.agentId, t);
907
+ return this.destroyed ? null : (this.adopt(s.id, null, "keep"), this.sessionId);
908
+ } catch (t) {
909
+ return this.fail(t, !1), null;
910
+ }
911
+ }
912
+ async openServerSession(t) {
913
+ const e = this.sessionGeneration;
914
+ try {
915
+ let s = t ? this.accept(t) : await this.serverToken(e);
916
+ this.assertCurrent(e), this.latestToken = s.token;
917
+ let n;
918
+ try {
919
+ n = await this.http.snapshot(s.sessionId, s.token);
920
+ } catch (r) {
921
+ if (this.assertCurrent(e), !(r instanceof m) || r.error.code !== "invalid_token") throw r;
922
+ s = await this.serverToken(e), this.assertCurrent(e), this.latestToken = s.token, n = await this.http.snapshot(s.sessionId, s.token);
923
+ }
924
+ return this.assertCurrent(e), this.adopt(s.sessionId, n, this.state.items.length ? "append" : "replace", s), this.sessionId;
925
+ } catch (s) {
926
+ return this.isCurrent(e) && this.fail(s, !0), null;
927
+ }
928
+ }
929
+ async serverToken(t = this.sessionGeneration) {
930
+ if (this.assertCurrent(t), this.opts.auth?.mode !== "server") throw new Error("not server mode");
931
+ let e;
932
+ const s = this.wantNewServerSession;
933
+ this.wantNewServerSession = !1;
934
+ try {
935
+ e = await (s ? this.opts.auth.getToken({ newSession: !0 }) : this.opts.auth.getToken());
936
+ } catch {
937
+ throw new m(f("token_failed", "getToken failed"), 0);
938
+ }
939
+ this.assertCurrent(t);
940
+ try {
941
+ return this.accept(e);
942
+ } catch (n) {
943
+ throw this.isCurrent(t) && this.fail(n, !1), n;
944
+ }
945
+ }
946
+ accept(t) {
947
+ return this.checkWsUrl(t.wsUrl), { ...t, expiresAt: X(t.expiresAt) };
948
+ }
949
+ // wss: only (ws: for localhost during development); anything else is a token failure.
950
+ checkWsUrl(t) {
951
+ let e = null;
952
+ try {
953
+ e = new URL(t);
954
+ } catch {
955
+ }
956
+ const s = e?.hostname === "localhost" || e?.hostname === "127.0.0.1";
957
+ if (e && (e.protocol === "wss:" || e.protocol === "ws:" && s)) return;
958
+ const n = f("token_failed", "The chat stream URL must use wss://");
959
+ throw new m(n, 0);
960
+ }
961
+ isCurrent(t, e) {
962
+ return !this.destroyed && this.sessionGeneration === t && (e === void 0 || this.sessionId === e);
963
+ }
964
+ assertCurrent(t, e) {
965
+ if (!this.isCurrent(t, e)) throw new m(f("session_closed"), 0);
966
+ }
967
+ /** Bind to a session; `firstToken` lets server mode reuse the token it just fetched. */
968
+ adopt(t, e, s, n, r = !0) {
969
+ if (this.sessionId === t && this.conn) return;
970
+ this.conn?.stop(), this.conn = null, this.sessionId = t;
971
+ const o = ++this.sessionGeneration;
972
+ this.serverMode || this.store.set(D(this.opts.agentId), t), e && this.applySnapshot(e, s);
973
+ let a = n ?? null;
974
+ const h = this.serverMode ? null : A(this.store);
975
+ let c = !0, l = !1;
976
+ const _ = async () => {
977
+ if (this.assertCurrent(o, t), a) {
978
+ const d = a;
979
+ return a = null, this.latestToken = d.token, d;
980
+ }
981
+ if (this.serverMode) {
982
+ const d = await this.serverToken(o);
983
+ if (this.assertCurrent(o, t), d.sessionId !== t)
984
+ throw this.switchTo = d, new m(f("session_closed"), 0);
985
+ return this.latestToken = d.token, d;
986
+ }
987
+ const u = c;
988
+ c = !1;
989
+ let p;
990
+ try {
991
+ p = await this.http.mintPublicToken(t);
992
+ } catch (d) {
993
+ throw l = u && r && this.isCurrent(o, t) && d instanceof m && d.status === 404 && d.error.code === "session_not_found" && [...this.pending.values()].every((I) => I.gen === -1), d;
994
+ }
995
+ this.assertCurrent(o, t);
996
+ try {
997
+ this.checkWsUrl(p.wsUrl);
998
+ } catch (d) {
999
+ throw this.fail(d, !1), d;
1000
+ }
1001
+ return this.latestToken = p.token, p;
1002
+ };
1003
+ this.conn = new Pt({
1004
+ mint: _,
1005
+ sdkVersion: nt,
1006
+ page: this.page,
1007
+ random: this.opts.random,
1008
+ WebSocketImpl: this.opts.WebSocketImpl,
1009
+ onFrame: (u) => this.onFrame(u),
1010
+ onStatus: (u) => this.patch({ status: u, ...u === "open" ? { error: null } : {} }),
1011
+ onOpen: () => this.onOpen(),
1012
+ onReconnected: () => {
1013
+ this.recover();
1014
+ },
1015
+ onError: (u) => this.patch({ error: u }),
1016
+ onClosed: (u) => {
1017
+ if (!this.isCurrent(o, t)) return;
1018
+ if (l && h && u === "session_not_found") {
1019
+ l = !1, this.serialize(() => this.replaceBeforeFirstWrite(o, t, h));
1020
+ return;
1021
+ }
1022
+ const p = this.switchTo;
1023
+ this.switchTo = null, this.endSession(u), p && this.serialize(() => this.openServerSession(p));
1024
+ }
1025
+ }), this.conn.start();
1026
+ }
1027
+ /** An initial mint can lose to a sibling tab before this tab has written anything. */
1028
+ async replaceBeforeFirstWrite(t, e, s) {
1029
+ if (this.isCurrent(t, e))
1030
+ try {
1031
+ const n = await this.http.bootstrap(this.opts.agentId, s);
1032
+ if (!this.isCurrent(t, e)) return;
1033
+ const r = n?.session, o = r, a = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1034
+ if (n?.agent?.agent_uuid !== this.opts.agentId || !Array.isArray(n.messages) || !r || typeof r.id != "string" || !a.test(r.id) || r.id === e || r.status !== "active" || r.mode !== "ai" && r.mode !== "support" || o && "customer_id" in o && o.customer_id !== s || o && "agent_uuid" in o && o.agent_uuid !== this.opts.agentId || [...this.pending.values()].some((h) => h.gen !== -1)) {
1035
+ this.endSession("session_not_found");
1036
+ return;
1037
+ }
1038
+ this.adopt(r.id, n, "append", void 0, !1);
1039
+ } catch {
1040
+ this.isCurrent(t, e) && this.endSession("session_not_found");
1041
+ }
1042
+ }
1043
+ // Every socket that becomes current (first open, reconnect, rotation): resend what is unacked.
1044
+ onOpen() {
1045
+ this.openGen += 1, this.seen = [], this.seenSet.clear();
1046
+ for (const t of [...this.pending.keys()]) this.write(t);
1047
+ this.interactions.onConnectionOpen();
1048
+ }
1049
+ async recover() {
1050
+ const t = this.sessionId, e = this.sessionGeneration, s = await this.fetchSnapshot();
1051
+ s && t && this.isCurrent(e, t) && this.applySnapshot(s, "reconcile");
1052
+ }
1053
+ async fetchSnapshot() {
1054
+ if (this.destroyed) return null;
1055
+ const t = this.sessionId, e = this.sessionGeneration;
1056
+ if (!t) return null;
1057
+ try {
1058
+ try {
1059
+ const s = await this.http.snapshot(t, this.latestToken ?? await this.mintFresh(t));
1060
+ return this.isCurrent(e, t) ? s : null;
1061
+ } catch (s) {
1062
+ if (this.assertCurrent(e, t), !(s instanceof m) || s.error.code !== "invalid_token") throw s;
1063
+ const n = await this.http.snapshot(t, await this.mintFresh(t));
1064
+ return this.isCurrent(e, t) ? n : null;
1065
+ }
1066
+ } catch (s) {
1067
+ if (s instanceof m && s.error.code === "session_not_found") {
1068
+ if (!this.isCurrent(e, t)) return null;
1069
+ this.endSession("session_closed"), this.serverMode || this.readoptAfterReplacement();
1070
+ }
1071
+ return null;
1072
+ }
1073
+ }
1074
+ async mintFresh(t) {
1075
+ const e = this.sessionGeneration;
1076
+ if (this.assertCurrent(e, t), this.serverMode) {
1077
+ const n = await this.serverToken(e);
1078
+ return this.assertCurrent(e, t), this.latestToken = n.token, n.token;
1079
+ }
1080
+ const s = await this.http.mintPublicToken(t);
1081
+ return this.assertCurrent(e, t), this.checkWsUrl(s.wsUrl), this.latestToken = s.token, s.token;
1082
+ }
1083
+ async readoptAfterReplacement() {
1084
+ try {
1085
+ const t = await this.http.bootstrap(this.opts.agentId, A(this.store));
1086
+ !this.destroyed && !this.sessionId && t.session?.id && t.session.status === "active" && this.adopt(t.session.id, t, "append");
1087
+ } catch {
1088
+ }
1089
+ }
1090
+ endSession(t) {
1091
+ if (this.destroyed) return;
1092
+ this.sessionGeneration += 1, this.conn?.stop(), this.conn = null, this.sessionId = null, this.latestToken = null, this.serverMode || this.store.remove(D(this.opts.agentId)), this.interactions.reset(), this.pending.forEach((r) => {
1093
+ r.ackTimer && clearTimeout(r.ackTimer);
1094
+ }), this.pending.clear();
1095
+ const e = this.state.items.map((r) => r.kind === "message" && r.status === "sending" ? { ...r, status: "failed" } : r), s = e[e.length - 1], n = { kind: "divider", id: E(), reason: "session_ended" };
1096
+ this.setAwaiting(!1), this.patch({
1097
+ status: "closed",
1098
+ mode: "ai",
1099
+ items: e.length && s?.kind !== "divider" ? [...e, n] : e,
1100
+ ...Ft.has(t) ? {} : { error: f(t) }
1101
+ });
1102
+ }
1103
+ // ---------- frames ----------
1104
+ onFrame(t) {
1105
+ if (this.destroyed) return;
1106
+ if (t.event_id !== void 0) {
1107
+ const s = String(t.event_id);
1108
+ if (this.seenSet.has(s)) return;
1109
+ this.seenSet.add(s), this.seen.push(s), this.seen.length > Ut && this.seenSet.delete(this.seen.shift());
1110
+ }
1111
+ const e = t.payload;
1112
+ switch (t.type) {
1113
+ case "ws_write_result":
1114
+ this.interactions.handleWriteResult(e) || this.onWriteResult(e);
1115
+ return;
1116
+ case "message_received": {
1117
+ if (e.type === "interaction") return;
1118
+ const s = N(e);
1119
+ if (!s) return;
1120
+ s.role === "user" ? this.onUserEcho(s.id, s.content, s.created_at, typeof e.message_id == "string" ? e.message_id : void 0) : this.appendRemote(s.id, s.role, s.content, s.created_at);
1121
+ return;
1122
+ }
1123
+ case "operator_message": {
1124
+ const s = N({ ...e, role: "operator" });
1125
+ s && this.appendRemote(s.id, "operator", s.content, s.created_at);
1126
+ return;
1127
+ }
1128
+ case "mode_changed":
1129
+ e.to === "support" ? this.setMode("human") : e.to === "ai" && this.setMode("ai");
1130
+ return;
1131
+ case "takeover_started":
1132
+ this.setMode("human");
1133
+ return;
1134
+ case "takeover_ended":
1135
+ this.setMode("ai");
1136
+ return;
1137
+ case "interaction_published":
1138
+ case "interaction_updated":
1139
+ case "interaction_closed":
1140
+ this.interactions.applyEvent(t) && t.type === "interaction_published" && this.setAwaiting(!1), this.patch({});
1141
+ return;
1142
+ case "turn_result":
1143
+ (e.state === "failed" || e.state === "error") && (this.setAwaiting(!1), this.patch({ error: { code: "unknown", message: "The assistant could not reply", retryable: !0 } }));
1144
+ return;
1145
+ case "session_closed":
1146
+ case "session_dormant":
1147
+ this.endSession(t.type);
1148
+ return;
1149
+ default:
1150
+ return;
1151
+ }
1152
+ }
1153
+ onWriteResult(t) {
1154
+ const e = t.message_id;
1155
+ if (!e) return;
1156
+ const s = this.pending.get(e);
1157
+ if (s) {
1158
+ if (s.ackTimer && (clearTimeout(s.ackTimer), s.ackTimer = null), t.state === "accepted" || t.state === "merged" || t.state === "done") {
1159
+ this.pending.delete(e), this.setMessage(e, { status: "sent" }), this.setAwaiting(!0);
1160
+ return;
1161
+ }
1162
+ if (t.state === "busy" && s.attempts < K.length) {
1163
+ const n = K[s.attempts];
1164
+ s.attempts += 1, this.later(n, () => {
1165
+ this.pending.get(e) === s && (s.gen = -1, this.transmit(e));
1166
+ });
1167
+ return;
1168
+ }
1169
+ this.pending.delete(e), this.setMessage(e, { status: "failed" }), this.patch({ error: f(t.error, t.error) });
1170
+ }
1171
+ }
1172
+ /** Our own message comes back as a user echo: adopt it (by client message_id, else by content on an older engine). */
1173
+ onUserEcho(t, e, s, n) {
1174
+ const r = this.state.items;
1175
+ if (r.some((a) => a.kind === "message" && a.serverId === t)) return;
1176
+ const o = n ? r.findIndex((a) => a.kind === "message" && a.role === "user" && a.id === n) : r.findIndex((a) => a.kind === "message" && a.role === "user" && !a.serverId && a.status !== "failed" && a.content === e);
1177
+ if (o >= 0) {
1178
+ const a = r.slice(), h = a[o];
1179
+ a[o] = { ...h, serverId: t, status: "sent" }, this.dropPending(h.id), this.patch({ items: a });
1180
+ return;
1181
+ }
1182
+ this.appendRemote(t, "user", e, s);
1183
+ }
1184
+ appendRemote(t, e, s, n) {
1185
+ const r = J[e];
1186
+ if (!r || this.state.items.some((a) => a.kind === "message" && a.serverId === t)) return;
1187
+ const o = {
1188
+ kind: "message",
1189
+ id: `srv:${t}`,
1190
+ serverId: t,
1191
+ role: r,
1192
+ content: s,
1193
+ createdAt: n ?? (/* @__PURE__ */ new Date()).toISOString(),
1194
+ status: "sent"
1195
+ };
1196
+ this.patch({ items: [...this.state.items, o] }), r !== "user" && this.setAwaiting(!1);
1197
+ }
1198
+ // ---------- snapshot → items ----------
1199
+ applySnapshot(t, e) {
1200
+ if (this.destroyed) return;
1201
+ const s = [], n = /* @__PURE__ */ new Map();
1202
+ for (const h of t.messages ?? []) {
1203
+ const c = b(h);
1204
+ if (c) {
1205
+ s.push({ kind: "interaction", id: c.interaction_id, interaction: c });
1206
+ continue;
1207
+ }
1208
+ const l = N(h), _ = l ? J[l.role] : void 0;
1209
+ if (l && _) {
1210
+ s.push({
1211
+ kind: "message",
1212
+ id: `srv:${l.id}`,
1213
+ serverId: l.id,
1214
+ role: _,
1215
+ content: l.content,
1216
+ createdAt: l.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
1217
+ status: "sent"
1218
+ });
1219
+ const u = h.message_id;
1220
+ typeof u == "string" && n.set(l.id, u);
1221
+ }
1222
+ }
1223
+ let r = this.state.items;
1224
+ if (e === "replace") r = s;
1225
+ else if (e === "append") {
1226
+ let h = r.length;
1227
+ for (; h > 0; ) {
1228
+ const c = r[h - 1];
1229
+ if (c.kind === "message" && c.role === "user" && c.status === "sending" && !c.serverId) h -= 1;
1230
+ else break;
1231
+ }
1232
+ r = [...r.slice(0, h), ...s, ...r.slice(h)];
1233
+ } else if (e === "reconcile") {
1234
+ const h = new Set(r.flatMap((c) => c.kind === "message" ? [c.serverId] : c.kind === "interaction" ? [c.id] : []));
1235
+ for (const c of s) {
1236
+ const l = c.kind === "message" ? c.serverId : c.id;
1237
+ if (c.kind === "message" && c.role === "user" && !h.has(l)) {
1238
+ const _ = n.get(c.serverId), u = r.findIndex((p) => p.kind === "message" && p.role === "user" && !p.serverId && (_ ? p.id === _ : p.content === c.content));
1239
+ if (u >= 0) {
1240
+ const p = r[u];
1241
+ r = r.slice(), r[u] = { ...p, serverId: c.serverId, status: "sent" }, this.dropPending(p.id), h.add(l);
1242
+ continue;
1243
+ }
1244
+ }
1245
+ h.has(l) || (r = [...r, c], h.add(l));
1246
+ }
1247
+ }
1248
+ const o = t.session;
1249
+ this.patch({ items: r, ...o ? { mode: o.mode === "support" ? "human" : "ai" } : {} }), this.interactions.applySnapshot(t);
1250
+ const a = r.filter((h) => h.kind !== "divider").at(-1);
1251
+ a && !(a.kind === "message" && a.role === "user") && this.setAwaiting(!1), this.patch({});
1252
+ }
1253
+ // ---------- sends ----------
1254
+ frameFor(t) {
1255
+ return {
1256
+ type: "message",
1257
+ content: t.content,
1258
+ message_id: t.id,
1259
+ idempotency_key: t.idempotencyKey,
1260
+ supported_interactions: $
1261
+ };
1262
+ }
1263
+ transmit(t) {
1264
+ this.write(t);
1265
+ }
1266
+ // Write once per socket generation; an ack timer starts with every write.
1267
+ write(t) {
1268
+ const e = this.pending.get(t);
1269
+ !e || !this.conn?.isOpen || e.gen === this.openGen || this.conn.send(e.frame) && (e.gen = this.openGen, e.ackTimer && clearTimeout(e.ackTimer), e.ackTimer = setTimeout(() => {
1270
+ this.onAckTimeout(t);
1271
+ }, xt));
1272
+ }
1273
+ // No ack within 15 s: reconcile with the server; if the message is still unconfirmed, it failed (retry reuses the key).
1274
+ async onAckTimeout(t) {
1275
+ const e = this.pending.get(t);
1276
+ if (!e || this.destroyed || (e.ackTimer = null, !this.conn?.isOpen)) return;
1277
+ const s = this.openGen;
1278
+ await this.recover(), !(this.destroyed || this.pending.get(t) !== e || !this.conn?.isOpen || s !== this.openGen) && (this.dropPending(t), this.setMessage(t, { status: "failed" }), this.patch({ error: f("network", "The message could not be confirmed") }));
1279
+ }
1280
+ dropPending(t) {
1281
+ const e = this.pending.get(t);
1282
+ e?.ackTimer && clearTimeout(e.ackTimer), this.pending.delete(t);
1283
+ }
1284
+ // ---------- helpers ----------
1285
+ setMode(t) {
1286
+ this.setAwaiting(!1), this.patch({ mode: t });
1287
+ }
1288
+ setAwaiting(t) {
1289
+ this.awaitingTimer && (clearTimeout(this.awaitingTimer), this.awaitingTimer = null), t && (this.awaitingTimer = setTimeout(() => {
1290
+ this.awaitingTimer = null, this.patch({ awaitingReply: !1 });
1291
+ }, Nt)), this.state.awaitingReply !== t && this.patch({ awaitingReply: t });
1292
+ }
1293
+ setMessage(t, e) {
1294
+ this.patch({ items: this.state.items.map((s) => s.kind === "message" && s.id === t ? { ...s, ...e } : s) });
1295
+ }
1296
+ fail(t, e) {
1297
+ const s = t instanceof m ? t.error : f("network", "Network error");
1298
+ this.patch({ error: s, ...e || !s.retryable ? { status: "closed" } : {} });
1299
+ }
1300
+ later(t, e) {
1301
+ const s = setTimeout(() => {
1302
+ this.timers.delete(s), this.destroyed || e();
1303
+ }, t);
1304
+ this.timers.add(s);
1305
+ }
1306
+ patch(t) {
1307
+ if (this.destroyed) return;
1308
+ const e = {
1309
+ ...this.state,
1310
+ ...t,
1311
+ activeInteraction: this.interactions.active,
1312
+ interactionPending: this.interactions.pending
1313
+ };
1314
+ Object.keys(e).some((n) => e[n] !== this.state[n]) && (this.state = e, this.listeners.forEach((n) => n(e)));
1315
+ }
1316
+ }
1317
+ function Vt(i) {
1318
+ return new Dt(i);
1319
+ }
1320
+ export {
1321
+ Nt as A,
1322
+ Mt as D,
1323
+ nt as S,
1324
+ gt as a,
1325
+ P as b,
1326
+ Vt as c,
1327
+ xt as d,
1328
+ $ as e,
1329
+ $t as i
1330
+ };
1331
+ //# sourceMappingURL=index-BsRyQwUM.js.map