@anam-ai/agent-widget 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3891 @@
1
+ var Fe, k, hi, fi, Ee, Ht, pi, _i, Ei, At, gt, vt, Me = {}, mi = [], ln = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, ot = Array.isArray;
2
+ function ie(t, e) {
3
+ for (var n in e) t[n] = e[n];
4
+ return t;
5
+ }
6
+ function Tt(t) {
7
+ t && t.parentNode && t.parentNode.removeChild(t);
8
+ }
9
+ function Ce(t, e, n) {
10
+ var o, c, a, u = {};
11
+ for (a in e) a == "key" ? o = e[a] : a == "ref" ? c = e[a] : u[a] = e[a];
12
+ if (arguments.length > 2 && (u.children = arguments.length > 3 ? Fe.call(arguments, 2) : n), typeof t == "function" && t.defaultProps != null) for (a in t.defaultProps) u[a] === void 0 && (u[a] = t.defaultProps[a]);
13
+ return Ne(t, u, o, c, null);
14
+ }
15
+ function Ne(t, e, n, o, c) {
16
+ var a = { type: t, props: e, key: n, ref: o, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: c ?? ++hi, __i: -1, __u: 0 };
17
+ return c == null && k.vnode != null && k.vnode(a), a;
18
+ }
19
+ function oe(t) {
20
+ return t.children;
21
+ }
22
+ function Oe(t, e) {
23
+ this.props = t, this.context = e;
24
+ }
25
+ function be(t, e) {
26
+ if (e == null) return t.__ ? be(t.__, t.__i + 1) : null;
27
+ for (var n; e < t.__k.length; e++) if ((n = t.__k[e]) != null && n.__e != null) return n.__e;
28
+ return typeof t.type == "function" ? be(t) : null;
29
+ }
30
+ function gi(t) {
31
+ var e, n;
32
+ if ((t = t.__) != null && t.__c != null) {
33
+ for (t.__e = t.__c.base = null, e = 0; e < t.__k.length; e++) if ((n = t.__k[e]) != null && n.__e != null) {
34
+ t.__e = t.__c.base = n.__e;
35
+ break;
36
+ }
37
+ return gi(t);
38
+ }
39
+ }
40
+ function Wt(t) {
41
+ (!t.__d && (t.__d = !0) && Ee.push(t) && !Xe.__r++ || Ht != k.debounceRendering) && ((Ht = k.debounceRendering) || pi)(Xe);
42
+ }
43
+ function Xe() {
44
+ for (var t, e, n, o, c, a, u, l = 1; Ee.length; ) Ee.length > l && Ee.sort(_i), t = Ee.shift(), l = Ee.length, t.__d && (n = void 0, o = void 0, c = (o = (e = t).__v).__e, a = [], u = [], e.__P && ((n = ie({}, o)).__v = o.__v + 1, k.vnode && k.vnode(n), Rt(e.__P, n, o, e.__n, e.__P.namespaceURI, 32 & o.__u ? [c] : null, a, c ?? be(o), !!(32 & o.__u), u), n.__v = o.__v, n.__.__k[n.__i] = n, Si(a, n, u), o.__e = o.__ = null, n.__e != c && gi(n)));
45
+ Xe.__r = 0;
46
+ }
47
+ function vi(t, e, n, o, c, a, u, l, g, p, _) {
48
+ var d, S, m, y, A, w, I, b = o && o.__k || mi, x = e.length;
49
+ for (g = cn(n, e, b, g, x), d = 0; d < x; d++) (m = n.__k[d]) != null && (S = m.__i == -1 ? Me : b[m.__i] || Me, m.__i = d, w = Rt(t, m, S, c, a, u, l, g, p, _), y = m.__e, m.ref && S.ref != m.ref && (S.ref && xt(S.ref, null, m), _.push(m.ref, m.__c || y, m)), A == null && y != null && (A = y), (I = !!(4 & m.__u)) || S.__k === m.__k ? g = yi(m, g, t, I) : typeof m.type == "function" && w !== void 0 ? g = w : y && (g = y.nextSibling), m.__u &= -7);
50
+ return n.__e = A, g;
51
+ }
52
+ function cn(t, e, n, o, c) {
53
+ var a, u, l, g, p, _ = n.length, d = _, S = 0;
54
+ for (t.__k = new Array(c), a = 0; a < c; a++) (u = e[a]) != null && typeof u != "boolean" && typeof u != "function" ? (typeof u == "string" || typeof u == "number" || typeof u == "bigint" || u.constructor == String ? u = t.__k[a] = Ne(null, u, null, null, null) : ot(u) ? u = t.__k[a] = Ne(oe, { children: u }, null, null, null) : u.constructor === void 0 && u.__b > 0 ? u = t.__k[a] = Ne(u.type, u.props, u.key, u.ref ? u.ref : null, u.__v) : t.__k[a] = u, g = a + S, u.__ = t, u.__b = t.__b + 1, l = null, (p = u.__i = un(u, n, g, d)) != -1 && (d--, (l = n[p]) && (l.__u |= 2)), l == null || l.__v == null ? (p == -1 && (c > _ ? S-- : c < _ && S++), typeof u.type != "function" && (u.__u |= 4)) : p != g && (p == g - 1 ? S-- : p == g + 1 ? S++ : (p > g ? S-- : S++, u.__u |= 4))) : t.__k[a] = null;
55
+ if (d) for (a = 0; a < _; a++) (l = n[a]) != null && (2 & l.__u) == 0 && (l.__e == o && (o = be(l)), Ci(l, l));
56
+ return o;
57
+ }
58
+ function yi(t, e, n, o) {
59
+ var c, a;
60
+ if (typeof t.type == "function") {
61
+ for (c = t.__k, a = 0; c && a < c.length; a++) c[a] && (c[a].__ = t, e = yi(c[a], e, n, o));
62
+ return e;
63
+ }
64
+ t.__e != e && (o && (e && t.type && !e.parentNode && (e = be(t)), n.insertBefore(t.__e, e || null)), e = t.__e);
65
+ do
66
+ e = e && e.nextSibling;
67
+ while (e != null && e.nodeType == 8);
68
+ return e;
69
+ }
70
+ function un(t, e, n, o) {
71
+ var c, a, u, l = t.key, g = t.type, p = e[n], _ = p != null && (2 & p.__u) == 0;
72
+ if (p === null && l == null || _ && l == p.key && g == p.type) return n;
73
+ if (o > (_ ? 1 : 0)) {
74
+ for (c = n - 1, a = n + 1; c >= 0 || a < e.length; ) if ((p = e[u = c >= 0 ? c-- : a++]) != null && (2 & p.__u) == 0 && l == p.key && g == p.type) return u;
75
+ }
76
+ return -1;
77
+ }
78
+ function zt(t, e, n) {
79
+ e[0] == "-" ? t.setProperty(e, n ?? "") : t[e] = n == null ? "" : typeof n != "number" || ln.test(e) ? n : n + "px";
80
+ }
81
+ function Ve(t, e, n, o, c) {
82
+ var a, u;
83
+ e: if (e == "style") if (typeof n == "string") t.style.cssText = n;
84
+ else {
85
+ if (typeof o == "string" && (t.style.cssText = o = ""), o) for (e in o) n && e in n || zt(t.style, e, "");
86
+ if (n) for (e in n) o && n[e] == o[e] || zt(t.style, e, n[e]);
87
+ }
88
+ else if (e[0] == "o" && e[1] == "n") a = e != (e = e.replace(Ei, "$1")), u = e.toLowerCase(), e = u in t || e == "onFocusOut" || e == "onFocusIn" ? u.slice(2) : e.slice(2), t.l || (t.l = {}), t.l[e + a] = n, n ? o ? n.u = o.u : (n.u = At, t.addEventListener(e, a ? vt : gt, a)) : t.removeEventListener(e, a ? vt : gt, a);
89
+ else {
90
+ if (c == "http://www.w3.org/2000/svg") e = e.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
91
+ else if (e != "width" && e != "height" && e != "href" && e != "list" && e != "form" && e != "tabIndex" && e != "download" && e != "rowSpan" && e != "colSpan" && e != "role" && e != "popover" && e in t) try {
92
+ t[e] = n ?? "";
93
+ break e;
94
+ } catch {
95
+ }
96
+ typeof n == "function" || (n == null || n === !1 && e[4] != "-" ? t.removeAttribute(e) : t.setAttribute(e, e == "popover" && n == 1 ? "" : n));
97
+ }
98
+ }
99
+ function qt(t) {
100
+ return function(e) {
101
+ if (this.l) {
102
+ var n = this.l[e.type + t];
103
+ if (e.t == null) e.t = At++;
104
+ else if (e.t < n.u) return;
105
+ return n(k.event ? k.event(e) : e);
106
+ }
107
+ };
108
+ }
109
+ function Rt(t, e, n, o, c, a, u, l, g, p) {
110
+ var _, d, S, m, y, A, w, I, b, x, M, N, Z, H, ae, ne, re, Q = e.type;
111
+ if (e.constructor !== void 0) return null;
112
+ 128 & n.__u && (g = !!(32 & n.__u), a = [l = e.__e = n.__e]), (_ = k.__b) && _(e);
113
+ e: if (typeof Q == "function") try {
114
+ if (I = e.props, b = "prototype" in Q && Q.prototype.render, x = (_ = Q.contextType) && o[_.__c], M = _ ? x ? x.props.value : _.__ : o, n.__c ? w = (d = e.__c = n.__c).__ = d.__E : (b ? e.__c = d = new Q(I, M) : (e.__c = d = new Oe(I, M), d.constructor = Q, d.render = hn), x && x.sub(d), d.state || (d.state = {}), d.__n = o, S = d.__d = !0, d.__h = [], d._sb = []), b && d.__s == null && (d.__s = d.state), b && Q.getDerivedStateFromProps != null && (d.__s == d.state && (d.__s = ie({}, d.__s)), ie(d.__s, Q.getDerivedStateFromProps(I, d.__s))), m = d.props, y = d.state, d.__v = e, S) b && Q.getDerivedStateFromProps == null && d.componentWillMount != null && d.componentWillMount(), b && d.componentDidMount != null && d.__h.push(d.componentDidMount);
115
+ else {
116
+ if (b && Q.getDerivedStateFromProps == null && I !== m && d.componentWillReceiveProps != null && d.componentWillReceiveProps(I, M), e.__v == n.__v || !d.__e && d.shouldComponentUpdate != null && d.shouldComponentUpdate(I, d.__s, M) === !1) {
117
+ for (e.__v != n.__v && (d.props = I, d.state = d.__s, d.__d = !1), e.__e = n.__e, e.__k = n.__k, e.__k.some(function(le) {
118
+ le && (le.__ = e);
119
+ }), N = 0; N < d._sb.length; N++) d.__h.push(d._sb[N]);
120
+ d._sb = [], d.__h.length && u.push(d);
121
+ break e;
122
+ }
123
+ d.componentWillUpdate != null && d.componentWillUpdate(I, d.__s, M), b && d.componentDidUpdate != null && d.__h.push(function() {
124
+ d.componentDidUpdate(m, y, A);
125
+ });
126
+ }
127
+ if (d.context = M, d.props = I, d.__P = t, d.__e = !1, Z = k.__r, H = 0, b) {
128
+ for (d.state = d.__s, d.__d = !1, Z && Z(e), _ = d.render(d.props, d.state, d.context), ae = 0; ae < d._sb.length; ae++) d.__h.push(d._sb[ae]);
129
+ d._sb = [];
130
+ } else do
131
+ d.__d = !1, Z && Z(e), _ = d.render(d.props, d.state, d.context), d.state = d.__s;
132
+ while (d.__d && ++H < 25);
133
+ d.state = d.__s, d.getChildContext != null && (o = ie(ie({}, o), d.getChildContext())), b && !S && d.getSnapshotBeforeUpdate != null && (A = d.getSnapshotBeforeUpdate(m, y)), ne = _, _ != null && _.type === oe && _.key == null && (ne = wi(_.props.children)), l = vi(t, ot(ne) ? ne : [ne], e, n, o, c, a, u, l, g, p), d.base = e.__e, e.__u &= -161, d.__h.length && u.push(d), w && (d.__E = d.__ = null);
134
+ } catch (le) {
135
+ if (e.__v = null, g || a != null) if (le.then) {
136
+ for (e.__u |= g ? 160 : 128; l && l.nodeType == 8 && l.nextSibling; ) l = l.nextSibling;
137
+ a[a.indexOf(l)] = null, e.__e = l;
138
+ } else {
139
+ for (re = a.length; re--; ) Tt(a[re]);
140
+ yt(e);
141
+ }
142
+ else e.__e = n.__e, e.__k = n.__k, le.then || yt(e);
143
+ k.__e(le, e, n);
144
+ }
145
+ else a == null && e.__v == n.__v ? (e.__k = n.__k, e.__e = n.__e) : l = e.__e = dn(n.__e, e, n, o, c, a, u, g, p);
146
+ return (_ = k.diffed) && _(e), 128 & e.__u ? void 0 : l;
147
+ }
148
+ function yt(t) {
149
+ t && t.__c && (t.__c.__e = !0), t && t.__k && t.__k.forEach(yt);
150
+ }
151
+ function Si(t, e, n) {
152
+ for (var o = 0; o < n.length; o++) xt(n[o], n[++o], n[++o]);
153
+ k.__c && k.__c(e, t), t.some(function(c) {
154
+ try {
155
+ t = c.__h, c.__h = [], t.some(function(a) {
156
+ a.call(c);
157
+ });
158
+ } catch (a) {
159
+ k.__e(a, c.__v);
160
+ }
161
+ });
162
+ }
163
+ function wi(t) {
164
+ return typeof t != "object" || t == null || t.__b && t.__b > 0 ? t : ot(t) ? t.map(wi) : ie({}, t);
165
+ }
166
+ function dn(t, e, n, o, c, a, u, l, g) {
167
+ var p, _, d, S, m, y, A, w = n.props || Me, I = e.props, b = e.type;
168
+ if (b == "svg" ? c = "http://www.w3.org/2000/svg" : b == "math" ? c = "http://www.w3.org/1998/Math/MathML" : c || (c = "http://www.w3.org/1999/xhtml"), a != null) {
169
+ for (p = 0; p < a.length; p++) if ((m = a[p]) && "setAttribute" in m == !!b && (b ? m.localName == b : m.nodeType == 3)) {
170
+ t = m, a[p] = null;
171
+ break;
172
+ }
173
+ }
174
+ if (t == null) {
175
+ if (b == null) return document.createTextNode(I);
176
+ t = document.createElementNS(c, b, I.is && I), l && (k.__m && k.__m(e, a), l = !1), a = null;
177
+ }
178
+ if (b == null) w === I || l && t.data == I || (t.data = I);
179
+ else {
180
+ if (a = a && Fe.call(t.childNodes), !l && a != null) for (w = {}, p = 0; p < t.attributes.length; p++) w[(m = t.attributes[p]).name] = m.value;
181
+ for (p in w) if (m = w[p], p != "children") {
182
+ if (p == "dangerouslySetInnerHTML") d = m;
183
+ else if (!(p in I)) {
184
+ if (p == "value" && "defaultValue" in I || p == "checked" && "defaultChecked" in I) continue;
185
+ Ve(t, p, null, m, c);
186
+ }
187
+ }
188
+ for (p in I) m = I[p], p == "children" ? S = m : p == "dangerouslySetInnerHTML" ? _ = m : p == "value" ? y = m : p == "checked" ? A = m : l && typeof m != "function" || w[p] === m || Ve(t, p, m, w[p], c);
189
+ if (_) l || d && (_.__html == d.__html || _.__html == t.innerHTML) || (t.innerHTML = _.__html), e.__k = [];
190
+ else if (d && (t.innerHTML = ""), vi(e.type == "template" ? t.content : t, ot(S) ? S : [S], e, n, o, b == "foreignObject" ? "http://www.w3.org/1999/xhtml" : c, a, u, a ? a[0] : n.__k && be(n, 0), l, g), a != null) for (p = a.length; p--; ) Tt(a[p]);
191
+ l || (p = "value", b == "progress" && y == null ? t.removeAttribute("value") : y != null && (y !== t[p] || b == "progress" && !y || b == "option" && y != w[p]) && Ve(t, p, y, w[p], c), p = "checked", A != null && A != t[p] && Ve(t, p, A, w[p], c));
192
+ }
193
+ return t;
194
+ }
195
+ function xt(t, e, n) {
196
+ try {
197
+ if (typeof t == "function") {
198
+ var o = typeof t.__u == "function";
199
+ o && t.__u(), o && e == null || (t.__u = t(e));
200
+ } else t.current = e;
201
+ } catch (c) {
202
+ k.__e(c, n);
203
+ }
204
+ }
205
+ function Ci(t, e, n) {
206
+ var o, c;
207
+ if (k.unmount && k.unmount(t), (o = t.ref) && (o.current && o.current != t.__e || xt(o, null, e)), (o = t.__c) != null) {
208
+ if (o.componentWillUnmount) try {
209
+ o.componentWillUnmount();
210
+ } catch (a) {
211
+ k.__e(a, e);
212
+ }
213
+ o.base = o.__P = null;
214
+ }
215
+ if (o = t.__k) for (c = 0; c < o.length; c++) o[c] && Ci(o[c], e, n || typeof t.type != "function");
216
+ n || Tt(t.__e), t.__c = t.__ = t.__e = void 0;
217
+ }
218
+ function hn(t, e, n) {
219
+ return this.constructor(t, n);
220
+ }
221
+ function st(t, e, n) {
222
+ var o, c, a, u;
223
+ e == document && (e = document.documentElement), k.__ && k.__(t, e), c = (o = typeof n == "function") ? null : n && n.__k || e.__k, a = [], u = [], Rt(e, t = (!o && n || e).__k = Ce(oe, null, [t]), c || Me, Me, e.namespaceURI, !o && n ? [n] : c ? null : e.firstChild ? Fe.call(e.childNodes) : null, a, !o && n ? n : c ? c.__e : e.firstChild, o, u), Si(a, t, u);
224
+ }
225
+ function Ii(t, e) {
226
+ st(t, e, Ii);
227
+ }
228
+ function bi(t, e, n) {
229
+ var o, c, a, u, l = ie({}, t.props);
230
+ for (a in t.type && t.type.defaultProps && (u = t.type.defaultProps), e) a == "key" ? o = e[a] : a == "ref" ? c = e[a] : l[a] = e[a] === void 0 && u != null ? u[a] : e[a];
231
+ return arguments.length > 2 && (l.children = arguments.length > 3 ? Fe.call(arguments, 2) : n), Ne(t.type, l, o || t.key, c || t.ref, null);
232
+ }
233
+ Fe = mi.slice, k = { __e: function(t, e, n, o) {
234
+ for (var c, a, u; e = e.__; ) if ((c = e.__c) && !c.__) try {
235
+ if ((a = c.constructor) && a.getDerivedStateFromError != null && (c.setState(a.getDerivedStateFromError(t)), u = c.__d), c.componentDidCatch != null && (c.componentDidCatch(t, o || {}), u = c.__d), u) return c.__E = c;
236
+ } catch (l) {
237
+ t = l;
238
+ }
239
+ throw t;
240
+ } }, hi = 0, fi = function(t) {
241
+ return t != null && t.constructor === void 0;
242
+ }, Oe.prototype.setState = function(t, e) {
243
+ var n;
244
+ n = this.__s != null && this.__s != this.state ? this.__s : this.__s = ie({}, this.state), typeof t == "function" && (t = t(ie({}, n), this.props)), t && ie(n, t), t != null && this.__v && (e && this._sb.push(e), Wt(this));
245
+ }, Oe.prototype.forceUpdate = function(t) {
246
+ this.__v && (this.__e = !0, t && this.__h.push(t), Wt(this));
247
+ }, Oe.prototype.render = oe, Ee = [], pi = typeof Promise == "function" ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, _i = function(t, e) {
248
+ return t.__v.__b - e.__v.__b;
249
+ }, Xe.__r = 0, Ei = /(PointerCapture)$|Capture$/i, At = 0, gt = qt(!1), vt = qt(!0);
250
+ function Ze() {
251
+ return Ze = Object.assign ? Object.assign.bind() : function(t) {
252
+ for (var e = 1; e < arguments.length; e++) {
253
+ var n = arguments[e];
254
+ for (var o in n) Object.prototype.hasOwnProperty.call(n, o) && (t[o] = n[o]);
255
+ }
256
+ return t;
257
+ }, Ze.apply(this, arguments);
258
+ }
259
+ function Ai(t, e) {
260
+ if (t == null) return {};
261
+ var n, o, c = {}, a = Object.keys(t);
262
+ for (o = 0; o < a.length; o++) e.indexOf(n = a[o]) >= 0 || (c[n] = t[n]);
263
+ return c;
264
+ }
265
+ var fn = ["context", "children"], pn = ["useFragment"];
266
+ function _n(t, e, n, o) {
267
+ function c() {
268
+ var a, u = Reflect.construct(HTMLElement, [], c);
269
+ return u._vdomComponent = t, o && o.shadow ? (u._root = u.attachShadow({ mode: o.mode || "open", serializable: (a = o.serializable) != null && a }), o.adoptedStyleSheets && (u._root.adoptedStyleSheets = o.adoptedStyleSheets)) : u._root = u, u;
270
+ }
271
+ return (c.prototype = Object.create(HTMLElement.prototype)).constructor = c, c.prototype.connectedCallback = function() {
272
+ mn.call(this, o);
273
+ }, c.prototype.attributeChangedCallback = gn, c.prototype.disconnectedCallback = vn, n = n || t.observedAttributes || Object.keys(t.propTypes || {}), c.observedAttributes = n, t.formAssociated && (c.formAssociated = !0), n.forEach(function(a) {
274
+ Object.defineProperty(c.prototype, a, { get: function() {
275
+ return this._vdom ? this._vdom.props[a] : this._props[a];
276
+ }, set: function(u) {
277
+ this._vdom ? this.attributeChangedCallback(a, null, u) : (this._props || (this._props = {}), this._props[a] = u);
278
+ var l = typeof u;
279
+ u != null && l !== "string" && l !== "boolean" && l !== "number" || this.setAttribute(a, u);
280
+ } });
281
+ }), customElements.define(e || t.tagName || t.displayName || t.name, c), c;
282
+ }
283
+ function En(t) {
284
+ this.getChildContext = function() {
285
+ return t.context;
286
+ };
287
+ var e = t.children, n = Ai(t, fn);
288
+ return bi(e, n);
289
+ }
290
+ function mn(t) {
291
+ var e = new CustomEvent("_preact", { detail: {}, bubbles: !0, cancelable: !0 });
292
+ this.dispatchEvent(e), this._vdom = Ce(En, Ze({}, this._props, { context: e.detail.context }), Ri(this, this._vdomComponent, t)), (this.hasAttribute("hydrate") ? Ii : st)(this._vdom, this._root);
293
+ }
294
+ function Ti(t) {
295
+ return t.replace(/-(\w)/g, function(e, n) {
296
+ return n ? n.toUpperCase() : "";
297
+ });
298
+ }
299
+ function gn(t, e, n) {
300
+ if (this._vdom) {
301
+ var o = {};
302
+ o[t] = n = n ?? void 0, o[Ti(t)] = n, this._vdom = bi(this._vdom, o), st(this._vdom, this._root);
303
+ }
304
+ }
305
+ function vn() {
306
+ st(this._vdom = null, this._root);
307
+ }
308
+ function Yt(t, e) {
309
+ var n = this, o = t.useFragment, c = Ai(t, pn);
310
+ return Ce(o ? oe : "slot", Ze({}, c, { ref: function(a) {
311
+ a ? (n.ref = a, n._listener || (n._listener = function(u) {
312
+ u.stopPropagation(), u.detail.context = e;
313
+ }, a.addEventListener("_preact", n._listener))) : n.ref.removeEventListener("_preact", n._listener);
314
+ } }));
315
+ }
316
+ function Ri(t, e, n) {
317
+ if (t.nodeType === 3) return t.data;
318
+ if (t.nodeType !== 1) return null;
319
+ var o = [], c = {}, a = 0, u = t.attributes, l = t.childNodes;
320
+ for (a = u.length; a--; ) u[a].name !== "slot" && (c[u[a].name] = u[a].value, c[Ti(u[a].name)] = u[a].value);
321
+ for (a = l.length; a--; ) {
322
+ var g = Ri(l[a], null, n), p = l[a].slot;
323
+ p ? c[p] = Ce(Yt, { name: p }, g) : o[a] = g;
324
+ }
325
+ var _ = !(!n || !n.shadow), d = e ? Ce(Yt, { useFragment: !_ }, o) : o;
326
+ return !_ && e && (t.innerHTML = ""), Ce(e || t.nodeName.toLowerCase(), c, d);
327
+ }
328
+ var yn = 0;
329
+ function C(t, e, n, o, c, a) {
330
+ e || (e = {});
331
+ var u, l, g = e;
332
+ if ("ref" in g) for (l in g = {}, e) l == "ref" ? u = e[l] : g[l] = e[l];
333
+ var p = { type: t, props: g, key: n, ref: u, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: void 0, __v: --yn, __i: -1, __u: 0, __source: c, __self: a };
334
+ if (typeof t == "function" && (u = t.defaultProps)) for (l in u) g[l] === void 0 && (g[l] = u[l]);
335
+ return k.vnode && k.vnode(p), p;
336
+ }
337
+ var Ue, P, pt, Kt, Be = 0, xi = [], F = k, Jt = F.__b, Xt = F.__r, Zt = F.diffed, Qt = F.__c, ei = F.unmount, ti = F.__;
338
+ function Nt(t, e) {
339
+ F.__h && F.__h(P, t, Be || e), Be = 0;
340
+ var n = P.__H || (P.__H = { __: [], __h: [] });
341
+ return t >= n.__.length && n.__.push({}), n.__[t];
342
+ }
343
+ function Ye(t) {
344
+ return Be = 1, Sn(Oi, t);
345
+ }
346
+ function Sn(t, e, n) {
347
+ var o = Nt(Ue++, 2);
348
+ if (o.t = t, !o.__c && (o.__ = [Oi(void 0, e), function(l) {
349
+ var g = o.__N ? o.__N[0] : o.__[0], p = o.t(g, l);
350
+ g !== p && (o.__N = [p, o.__[1]], o.__c.setState({}));
351
+ }], o.__c = P, !P.__f)) {
352
+ var c = function(l, g, p) {
353
+ if (!o.__c.__H) return !0;
354
+ var _ = o.__c.__H.__.filter(function(S) {
355
+ return !!S.__c;
356
+ });
357
+ if (_.every(function(S) {
358
+ return !S.__N;
359
+ })) return !a || a.call(this, l, g, p);
360
+ var d = o.__c.props !== l;
361
+ return _.forEach(function(S) {
362
+ if (S.__N) {
363
+ var m = S.__[0];
364
+ S.__ = S.__N, S.__N = void 0, m !== S.__[0] && (d = !0);
365
+ }
366
+ }), a && a.call(this, l, g, p) || d;
367
+ };
368
+ P.__f = !0;
369
+ var a = P.shouldComponentUpdate, u = P.componentWillUpdate;
370
+ P.componentWillUpdate = function(l, g, p) {
371
+ if (this.__e) {
372
+ var _ = a;
373
+ a = void 0, c(l, g, p), a = _;
374
+ }
375
+ u && u.call(this, l, g, p);
376
+ }, P.shouldComponentUpdate = c;
377
+ }
378
+ return o.__N || o.__;
379
+ }
380
+ function St(t, e) {
381
+ var n = Nt(Ue++, 3);
382
+ !F.__s && Ni(n.__H, e) && (n.__ = t, n.u = e, P.__H.__h.push(n));
383
+ }
384
+ function Qe(t) {
385
+ return Be = 5, Ie(function() {
386
+ return { current: t };
387
+ }, []);
388
+ }
389
+ function Ie(t, e) {
390
+ var n = Nt(Ue++, 7);
391
+ return Ni(n.__H, e) && (n.__ = t(), n.__H = e, n.__h = t), n.__;
392
+ }
393
+ function je(t, e) {
394
+ return Be = 8, Ie(function() {
395
+ return t;
396
+ }, e);
397
+ }
398
+ function wn() {
399
+ for (var t; t = xi.shift(); ) if (t.__P && t.__H) try {
400
+ t.__H.__h.forEach(Ke), t.__H.__h.forEach(wt), t.__H.__h = [];
401
+ } catch (e) {
402
+ t.__H.__h = [], F.__e(e, t.__v);
403
+ }
404
+ }
405
+ F.__b = function(t) {
406
+ P = null, Jt && Jt(t);
407
+ }, F.__ = function(t, e) {
408
+ t && e.__k && e.__k.__m && (t.__m = e.__k.__m), ti && ti(t, e);
409
+ }, F.__r = function(t) {
410
+ Xt && Xt(t), Ue = 0;
411
+ var e = (P = t.__c).__H;
412
+ e && (pt === P ? (e.__h = [], P.__h = [], e.__.forEach(function(n) {
413
+ n.__N && (n.__ = n.__N), n.u = n.__N = void 0;
414
+ })) : (e.__h.forEach(Ke), e.__h.forEach(wt), e.__h = [], Ue = 0)), pt = P;
415
+ }, F.diffed = function(t) {
416
+ Zt && Zt(t);
417
+ var e = t.__c;
418
+ e && e.__H && (e.__H.__h.length && (xi.push(e) !== 1 && Kt === F.requestAnimationFrame || ((Kt = F.requestAnimationFrame) || Cn)(wn)), e.__H.__.forEach(function(n) {
419
+ n.u && (n.__H = n.u), n.u = void 0;
420
+ })), pt = P = null;
421
+ }, F.__c = function(t, e) {
422
+ e.some(function(n) {
423
+ try {
424
+ n.__h.forEach(Ke), n.__h = n.__h.filter(function(o) {
425
+ return !o.__ || wt(o);
426
+ });
427
+ } catch (o) {
428
+ e.some(function(c) {
429
+ c.__h && (c.__h = []);
430
+ }), e = [], F.__e(o, n.__v);
431
+ }
432
+ }), Qt && Qt(t, e);
433
+ }, F.unmount = function(t) {
434
+ ei && ei(t);
435
+ var e, n = t.__c;
436
+ n && n.__H && (n.__H.__.forEach(function(o) {
437
+ try {
438
+ Ke(o);
439
+ } catch (c) {
440
+ e = c;
441
+ }
442
+ }), n.__H = void 0, e && F.__e(e, n.__v));
443
+ };
444
+ var ii = typeof requestAnimationFrame == "function";
445
+ function Cn(t) {
446
+ var e, n = function() {
447
+ clearTimeout(o), ii && cancelAnimationFrame(e), setTimeout(t);
448
+ }, o = setTimeout(n, 35);
449
+ ii && (e = requestAnimationFrame(n));
450
+ }
451
+ function Ke(t) {
452
+ var e = P, n = t.__c;
453
+ typeof n == "function" && (t.__c = void 0, n()), P = e;
454
+ }
455
+ function wt(t) {
456
+ var e = P;
457
+ t.__c = t.__(), P = e;
458
+ }
459
+ function Ni(t, e) {
460
+ return !t || t.length !== e.length || e.some(function(n, o) {
461
+ return n !== t[o];
462
+ });
463
+ }
464
+ function Oi(t, e) {
465
+ return typeof e == "function" ? e(t) : e;
466
+ }
467
+ var In = /* @__PURE__ */ Symbol.for("preact-signals");
468
+ function at() {
469
+ if (pe > 1)
470
+ pe--;
471
+ else {
472
+ for (var t, e = !1; ke !== void 0; ) {
473
+ var n = ke;
474
+ for (ke = void 0, Ct++; n !== void 0; ) {
475
+ var o = n.o;
476
+ if (n.o = void 0, n.f &= -3, !(8 & n.f) && Mi(n)) try {
477
+ n.c();
478
+ } catch (c) {
479
+ e || (t = c, e = !0);
480
+ }
481
+ n = o;
482
+ }
483
+ }
484
+ if (Ct = 0, pe--, e) throw t;
485
+ }
486
+ }
487
+ function bn(t) {
488
+ if (pe > 0) return t();
489
+ pe++;
490
+ try {
491
+ return t();
492
+ } finally {
493
+ at();
494
+ }
495
+ }
496
+ var O = void 0;
497
+ function ki(t) {
498
+ var e = O;
499
+ O = void 0;
500
+ try {
501
+ return t();
502
+ } finally {
503
+ O = e;
504
+ }
505
+ }
506
+ var ke = void 0, pe = 0, Ct = 0, et = 0;
507
+ function Di(t) {
508
+ if (O !== void 0) {
509
+ var e = t.n;
510
+ if (e === void 0 || e.t !== O)
511
+ return e = { i: 0, S: t, p: O.s, n: void 0, t: O, e: void 0, x: void 0, r: e }, O.s !== void 0 && (O.s.n = e), O.s = e, t.n = e, 32 & O.f && t.S(e), e;
512
+ if (e.i === -1)
513
+ return e.i = 0, e.n !== void 0 && (e.n.p = e.p, e.p !== void 0 && (e.p.n = e.n), e.p = O.s, e.n = void 0, O.s.n = e, O.s = e), e;
514
+ }
515
+ }
516
+ function j(t, e) {
517
+ this.v = t, this.i = 0, this.n = void 0, this.t = void 0, this.W = e?.watched, this.Z = e?.unwatched, this.name = e?.name;
518
+ }
519
+ j.prototype.brand = In;
520
+ j.prototype.h = function() {
521
+ return !0;
522
+ };
523
+ j.prototype.S = function(t) {
524
+ var e = this, n = this.t;
525
+ n !== t && t.e === void 0 && (t.x = n, this.t = t, n !== void 0 ? n.e = t : ki(function() {
526
+ var o;
527
+ (o = e.W) == null || o.call(e);
528
+ }));
529
+ };
530
+ j.prototype.U = function(t) {
531
+ var e = this;
532
+ if (this.t !== void 0) {
533
+ var n = t.e, o = t.x;
534
+ n !== void 0 && (n.x = o, t.e = void 0), o !== void 0 && (o.e = n, t.x = void 0), t === this.t && (this.t = o, o === void 0 && ki(function() {
535
+ var c;
536
+ (c = e.Z) == null || c.call(e);
537
+ }));
538
+ }
539
+ };
540
+ j.prototype.subscribe = function(t) {
541
+ var e = this;
542
+ return $e(function() {
543
+ var n = e.value, o = O;
544
+ O = void 0;
545
+ try {
546
+ t(n);
547
+ } finally {
548
+ O = o;
549
+ }
550
+ }, { name: "sub" });
551
+ };
552
+ j.prototype.valueOf = function() {
553
+ return this.value;
554
+ };
555
+ j.prototype.toString = function() {
556
+ return this.value + "";
557
+ };
558
+ j.prototype.toJSON = function() {
559
+ return this.value;
560
+ };
561
+ j.prototype.peek = function() {
562
+ var t = O;
563
+ O = void 0;
564
+ try {
565
+ return this.value;
566
+ } finally {
567
+ O = t;
568
+ }
569
+ };
570
+ Object.defineProperty(j.prototype, "value", { get: function() {
571
+ var t = Di(this);
572
+ return t !== void 0 && (t.i = this.i), this.v;
573
+ }, set: function(t) {
574
+ if (t !== this.v) {
575
+ if (Ct > 100) throw new Error("Cycle detected");
576
+ this.v = t, this.i++, et++, pe++;
577
+ try {
578
+ for (var e = this.t; e !== void 0; e = e.x) e.t.N();
579
+ } finally {
580
+ at();
581
+ }
582
+ }
583
+ } });
584
+ function Y(t, e) {
585
+ return new j(t, e);
586
+ }
587
+ function Mi(t) {
588
+ for (var e = t.s; e !== void 0; e = e.n) if (e.S.i !== e.i || !e.S.h() || e.S.i !== e.i) return !0;
589
+ return !1;
590
+ }
591
+ function Ui(t) {
592
+ for (var e = t.s; e !== void 0; e = e.n) {
593
+ var n = e.S.n;
594
+ if (n !== void 0 && (e.r = n), e.S.n = e, e.i = -1, e.n === void 0) {
595
+ t.s = e;
596
+ break;
597
+ }
598
+ }
599
+ }
600
+ function Bi(t) {
601
+ for (var e = t.s, n = void 0; e !== void 0; ) {
602
+ var o = e.p;
603
+ e.i === -1 ? (e.S.U(e), o !== void 0 && (o.n = e.n), e.n !== void 0 && (e.n.p = o)) : n = e, e.S.n = e.r, e.r !== void 0 && (e.r = void 0), e = o;
604
+ }
605
+ t.s = n;
606
+ }
607
+ function ge(t, e) {
608
+ j.call(this, void 0), this.x = t, this.s = void 0, this.g = et - 1, this.f = 4, this.W = e?.watched, this.Z = e?.unwatched, this.name = e?.name;
609
+ }
610
+ ge.prototype = new j();
611
+ ge.prototype.h = function() {
612
+ if (this.f &= -3, 1 & this.f) return !1;
613
+ if ((36 & this.f) == 32 || (this.f &= -5, this.g === et)) return !0;
614
+ if (this.g = et, this.f |= 1, this.i > 0 && !Mi(this))
615
+ return this.f &= -2, !0;
616
+ var t = O;
617
+ try {
618
+ Ui(this), O = this;
619
+ var e = this.x();
620
+ (16 & this.f || this.v !== e || this.i === 0) && (this.v = e, this.f &= -17, this.i++);
621
+ } catch (n) {
622
+ this.v = n, this.f |= 16, this.i++;
623
+ }
624
+ return O = t, Bi(this), this.f &= -2, !0;
625
+ };
626
+ ge.prototype.S = function(t) {
627
+ if (this.t === void 0) {
628
+ this.f |= 36;
629
+ for (var e = this.s; e !== void 0; e = e.n) e.S.S(e);
630
+ }
631
+ j.prototype.S.call(this, t);
632
+ };
633
+ ge.prototype.U = function(t) {
634
+ if (this.t !== void 0 && (j.prototype.U.call(this, t), this.t === void 0)) {
635
+ this.f &= -33;
636
+ for (var e = this.s; e !== void 0; e = e.n) e.S.U(e);
637
+ }
638
+ };
639
+ ge.prototype.N = function() {
640
+ if (!(2 & this.f)) {
641
+ this.f |= 6;
642
+ for (var t = this.t; t !== void 0; t = t.x) t.t.N();
643
+ }
644
+ };
645
+ Object.defineProperty(ge.prototype, "value", { get: function() {
646
+ if (1 & this.f) throw new Error("Cycle detected");
647
+ var t = Di(this);
648
+ if (this.h(), t !== void 0 && (t.i = this.i), 16 & this.f) throw this.v;
649
+ return this.v;
650
+ } });
651
+ function ni(t, e) {
652
+ return new ge(t, e);
653
+ }
654
+ function Li(t) {
655
+ var e = t.u;
656
+ if (t.u = void 0, typeof e == "function") {
657
+ pe++;
658
+ var n = O;
659
+ O = void 0;
660
+ try {
661
+ e();
662
+ } catch (o) {
663
+ throw t.f &= -2, t.f |= 8, Ot(t), o;
664
+ } finally {
665
+ O = n, at();
666
+ }
667
+ }
668
+ }
669
+ function Ot(t) {
670
+ for (var e = t.s; e !== void 0; e = e.n) e.S.U(e);
671
+ t.x = void 0, t.s = void 0, Li(t);
672
+ }
673
+ function An(t) {
674
+ if (O !== this) throw new Error("Out-of-order effect");
675
+ Bi(this), O = t, this.f &= -2, 8 & this.f && Ot(this), at();
676
+ }
677
+ function Ae(t, e) {
678
+ this.x = t, this.u = void 0, this.s = void 0, this.o = void 0, this.f = 32, this.name = e?.name;
679
+ }
680
+ Ae.prototype.c = function() {
681
+ var t = this.S();
682
+ try {
683
+ if (8 & this.f || this.x === void 0) return;
684
+ var e = this.x();
685
+ typeof e == "function" && (this.u = e);
686
+ } finally {
687
+ t();
688
+ }
689
+ };
690
+ Ae.prototype.S = function() {
691
+ if (1 & this.f) throw new Error("Cycle detected");
692
+ this.f |= 1, this.f &= -9, Li(this), Ui(this), pe++;
693
+ var t = O;
694
+ return O = this, An.bind(this, t);
695
+ };
696
+ Ae.prototype.N = function() {
697
+ 2 & this.f || (this.f |= 2, this.o = ke, ke = this);
698
+ };
699
+ Ae.prototype.d = function() {
700
+ this.f |= 8, 1 & this.f || Ot(this);
701
+ };
702
+ Ae.prototype.dispose = function() {
703
+ this.d();
704
+ };
705
+ function $e(t, e) {
706
+ var n = new Ae(t, e);
707
+ try {
708
+ n.c();
709
+ } catch (c) {
710
+ throw n.d(), c;
711
+ }
712
+ var o = n.d.bind(n);
713
+ return o[Symbol.dispose] = o, o;
714
+ }
715
+ var Pi, _t, Tn = typeof window < "u" && !!window.__PREACT_SIGNALS_DEVTOOLS__, Fi = [];
716
+ $e(function() {
717
+ Pi = this.N;
718
+ })();
719
+ function Te(t, e) {
720
+ k[t] = e.bind(null, k[t] || function() {
721
+ });
722
+ }
723
+ function tt(t) {
724
+ _t && _t(), _t = t && t.S();
725
+ }
726
+ function $i(t) {
727
+ var e = this, n = t.data, o = Gi(n);
728
+ o.value = n;
729
+ var c = Ie(function() {
730
+ for (var l = e, g = e.__v; g = g.__; ) if (g.__c) {
731
+ g.__c.__$f |= 4;
732
+ break;
733
+ }
734
+ var p = ni(function() {
735
+ var m = o.value.value;
736
+ return m === 0 ? 0 : m === !0 ? "" : m || "";
737
+ }), _ = ni(function() {
738
+ return !Array.isArray(p.value) && !fi(p.value);
739
+ }), d = $e(function() {
740
+ if (this.N = Vi, _.value) {
741
+ var m = p.value;
742
+ l.__v && l.__v.__e && l.__v.__e.nodeType === 3 && (l.__v.__e.data = m);
743
+ }
744
+ }), S = e.__$u.d;
745
+ return e.__$u.d = function() {
746
+ d(), S.call(this);
747
+ }, [_, p];
748
+ }, []), a = c[0], u = c[1];
749
+ return a.value ? u.peek() : u.value;
750
+ }
751
+ $i.displayName = "ReactiveTextNode";
752
+ Object.defineProperties(j.prototype, { constructor: { configurable: !0, value: void 0 }, type: { configurable: !0, value: $i }, props: { configurable: !0, get: function() {
753
+ return { data: this };
754
+ } }, __b: { configurable: !0, value: 1 } });
755
+ Te("__b", function(t, e) {
756
+ if (typeof e.type == "string") {
757
+ var n, o = e.props;
758
+ for (var c in o) if (c !== "children") {
759
+ var a = o[c];
760
+ a instanceof j && (n || (e.__np = n = {}), n[c] = a, o[c] = a.peek());
761
+ }
762
+ }
763
+ t(e);
764
+ });
765
+ Te("__r", function(t, e) {
766
+ if (e.type !== oe) {
767
+ tt();
768
+ var n, o = e.__c;
769
+ o && (o.__$f &= -2, (n = o.__$u) === void 0 && (o.__$u = n = (function(c, a) {
770
+ var u;
771
+ return $e(function() {
772
+ u = this;
773
+ }, { name: a }), u.c = c, u;
774
+ })(function() {
775
+ var c;
776
+ Tn && ((c = n.y) == null || c.call(n)), o.__$f |= 1, o.setState({});
777
+ }, typeof e.type == "function" ? e.type.displayName || e.type.name : ""))), tt(n);
778
+ }
779
+ t(e);
780
+ });
781
+ Te("__e", function(t, e, n, o) {
782
+ tt(), t(e, n, o);
783
+ });
784
+ Te("diffed", function(t, e) {
785
+ tt();
786
+ var n;
787
+ if (typeof e.type == "string" && (n = e.__e)) {
788
+ var o = e.__np, c = e.props;
789
+ if (o) {
790
+ var a = n.U;
791
+ if (a) for (var u in a) {
792
+ var l = a[u];
793
+ l !== void 0 && !(u in o) && (l.d(), a[u] = void 0);
794
+ }
795
+ else
796
+ a = {}, n.U = a;
797
+ for (var g in o) {
798
+ var p = a[g], _ = o[g];
799
+ p === void 0 ? (p = Rn(n, g, _, c), a[g] = p) : p.o(_, c);
800
+ }
801
+ }
802
+ }
803
+ t(e);
804
+ });
805
+ function Rn(t, e, n, o) {
806
+ var c = e in t && t.ownerSVGElement === void 0, a = Y(n);
807
+ return { o: function(u, l) {
808
+ a.value = u, o = l;
809
+ }, d: $e(function() {
810
+ this.N = Vi;
811
+ var u = a.value.value;
812
+ o[e] !== u && (o[e] = u, c ? t[e] = u : u != null && (u !== !1 || e[4] === "-") ? t.setAttribute(e, u) : t.removeAttribute(e));
813
+ }) };
814
+ }
815
+ Te("unmount", function(t, e) {
816
+ if (typeof e.type == "string") {
817
+ var n = e.__e;
818
+ if (n) {
819
+ var o = n.U;
820
+ if (o) {
821
+ n.U = void 0;
822
+ for (var c in o) {
823
+ var a = o[c];
824
+ a && a.d();
825
+ }
826
+ }
827
+ }
828
+ } else {
829
+ var u = e.__c;
830
+ if (u) {
831
+ var l = u.__$u;
832
+ l && (u.__$u = void 0, l.d());
833
+ }
834
+ }
835
+ t(e);
836
+ });
837
+ Te("__h", function(t, e, n, o) {
838
+ (o < 3 || o === 9) && (e.__$f |= 2), t(e, n, o);
839
+ });
840
+ Oe.prototype.shouldComponentUpdate = function(t, e) {
841
+ if (this.__R) return !0;
842
+ var n = this.__$u, o = n && n.s !== void 0;
843
+ for (var c in e) return !0;
844
+ if (this.__f || typeof this.u == "boolean" && this.u === !0) {
845
+ var a = 2 & this.__$f;
846
+ if (!(o || a || 4 & this.__$f) || 1 & this.__$f) return !0;
847
+ } else if (!(o || 4 & this.__$f) || 3 & this.__$f) return !0;
848
+ for (var u in t) if (u !== "__source" && t[u] !== this.props[u]) return !0;
849
+ for (var l in this.props) if (!(l in t)) return !0;
850
+ return !1;
851
+ };
852
+ function Gi(t, e) {
853
+ return Ye(function() {
854
+ return Y(t, e);
855
+ })[0];
856
+ }
857
+ var xn = function(t) {
858
+ queueMicrotask(function() {
859
+ queueMicrotask(t);
860
+ });
861
+ };
862
+ function Nn() {
863
+ bn(function() {
864
+ for (var t; t = Fi.shift(); ) Pi.call(t);
865
+ });
866
+ }
867
+ function Vi() {
868
+ Fi.push(this) === 1 && (k.requestAnimationFrame || xn)(Nn);
869
+ }
870
+ const He = {
871
+ mode: "orb",
872
+ layout: "fixed",
873
+ position: "bottom-right",
874
+ styles: {
875
+ backgroundColor: "#ffffff",
876
+ textColor: "#1f2937"
877
+ },
878
+ showTranscript: !0,
879
+ showTextInput: !0,
880
+ showMuteButton: !0,
881
+ interactionMode: "both",
882
+ startExpanded: !1,
883
+ textContents: {
884
+ callToAction: "Talk to our assistant",
885
+ connecting: "Connecting...",
886
+ listening: "Listening...",
887
+ speaking: "Speaking...",
888
+ endCall: "End",
889
+ sendMessage: "Send",
890
+ placeholder: "Type a message..."
891
+ }
892
+ }, We = {
893
+ "bottom-right": { bottom: "24px", right: "24px" },
894
+ "bottom-left": { bottom: "24px", left: "24px" },
895
+ "top-right": { top: "24px", right: "24px" },
896
+ "top-left": { top: "24px", left: "24px" }
897
+ };
898
+ function On(t) {
899
+ if (We[t])
900
+ return We[t];
901
+ const e = t.match(/^\[(.+)\]$/);
902
+ if (!e) return We["bottom-right"];
903
+ const n = {};
904
+ for (const o of e[1].split(",")) {
905
+ const c = o.trim(), a = c.lastIndexOf("-");
906
+ if (a <= 0) continue;
907
+ const u = c.slice(0, a), l = c.slice(a + 1);
908
+ n[u] = /^\d+$/.test(l) ? `${l}px` : l;
909
+ }
910
+ return Object.keys(n).length > 0 ? n : We["bottom-right"];
911
+ }
912
+ const kn = [
913
+ // Authentication
914
+ "agent-id",
915
+ "api-base-url",
916
+ // Default: https://api.anam.ai
917
+ // Layout
918
+ "mode",
919
+ // 'orb' | 'expanded'
920
+ "layout",
921
+ // 'inline' | 'fixed'
922
+ "position",
923
+ // 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left' | '[top-20,right-0]'
924
+ // Backward compat (mapped to mode/layout)
925
+ "variant",
926
+ // deprecated → maps to mode
927
+ "placement",
928
+ // deprecated → maps to position
929
+ // Theming
930
+ "background-color",
931
+ "text-color",
932
+ // Features
933
+ "show-transcript",
934
+ // 'true' | 'false'
935
+ "show-text-input",
936
+ // 'true' | 'false'
937
+ "show-mute-button",
938
+ // 'true' | 'false'
939
+ "interaction-mode",
940
+ // 'voice' | 'text' | 'both'
941
+ "start-expanded",
942
+ // 'true' | 'false'
943
+ // Text customization
944
+ "text-call-to-action",
945
+ "text-connecting",
946
+ "text-listening",
947
+ "text-speaking",
948
+ "text-end-call",
949
+ // Advanced
950
+ "override-config"
951
+ // JSON string for full config override
952
+ ];
953
+ function ze(t) {
954
+ return t === void 0 ? !1 : t === "true" || t === "";
955
+ }
956
+ var Et = {}, xe = {}, ri;
957
+ function Dn() {
958
+ if (ri) return xe;
959
+ ri = 1, xe.byteLength = l, xe.toByteArray = p, xe.fromByteArray = S;
960
+ for (var t = [], e = [], n = typeof Uint8Array < "u" ? Uint8Array : Array, o = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", c = 0, a = o.length; c < a; ++c)
961
+ t[c] = o[c], e[o.charCodeAt(c)] = c;
962
+ e[45] = 62, e[95] = 63;
963
+ function u(m) {
964
+ var y = m.length;
965
+ if (y % 4 > 0)
966
+ throw new Error("Invalid string. Length must be a multiple of 4");
967
+ var A = m.indexOf("=");
968
+ A === -1 && (A = y);
969
+ var w = A === y ? 0 : 4 - A % 4;
970
+ return [A, w];
971
+ }
972
+ function l(m) {
973
+ var y = u(m), A = y[0], w = y[1];
974
+ return (A + w) * 3 / 4 - w;
975
+ }
976
+ function g(m, y, A) {
977
+ return (y + A) * 3 / 4 - A;
978
+ }
979
+ function p(m) {
980
+ var y, A = u(m), w = A[0], I = A[1], b = new n(g(m, w, I)), x = 0, M = I > 0 ? w - 4 : w, N;
981
+ for (N = 0; N < M; N += 4)
982
+ y = e[m.charCodeAt(N)] << 18 | e[m.charCodeAt(N + 1)] << 12 | e[m.charCodeAt(N + 2)] << 6 | e[m.charCodeAt(N + 3)], b[x++] = y >> 16 & 255, b[x++] = y >> 8 & 255, b[x++] = y & 255;
983
+ return I === 2 && (y = e[m.charCodeAt(N)] << 2 | e[m.charCodeAt(N + 1)] >> 4, b[x++] = y & 255), I === 1 && (y = e[m.charCodeAt(N)] << 10 | e[m.charCodeAt(N + 1)] << 4 | e[m.charCodeAt(N + 2)] >> 2, b[x++] = y >> 8 & 255, b[x++] = y & 255), b;
984
+ }
985
+ function _(m) {
986
+ return t[m >> 18 & 63] + t[m >> 12 & 63] + t[m >> 6 & 63] + t[m & 63];
987
+ }
988
+ function d(m, y, A) {
989
+ for (var w, I = [], b = y; b < A; b += 3)
990
+ w = (m[b] << 16 & 16711680) + (m[b + 1] << 8 & 65280) + (m[b + 2] & 255), I.push(_(w));
991
+ return I.join("");
992
+ }
993
+ function S(m) {
994
+ for (var y, A = m.length, w = A % 3, I = [], b = 16383, x = 0, M = A - w; x < M; x += b)
995
+ I.push(d(m, x, x + b > M ? M : x + b));
996
+ return w === 1 ? (y = m[A - 1], I.push(
997
+ t[y >> 2] + t[y << 4 & 63] + "=="
998
+ )) : w === 2 && (y = (m[A - 2] << 8) + m[A - 1], I.push(
999
+ t[y >> 10] + t[y >> 4 & 63] + t[y << 2 & 63] + "="
1000
+ )), I.join("");
1001
+ }
1002
+ return xe;
1003
+ }
1004
+ var qe = {};
1005
+ var oi;
1006
+ function Mn() {
1007
+ return oi || (oi = 1, qe.read = function(t, e, n, o, c) {
1008
+ var a, u, l = c * 8 - o - 1, g = (1 << l) - 1, p = g >> 1, _ = -7, d = n ? c - 1 : 0, S = n ? -1 : 1, m = t[e + d];
1009
+ for (d += S, a = m & (1 << -_) - 1, m >>= -_, _ += l; _ > 0; a = a * 256 + t[e + d], d += S, _ -= 8)
1010
+ ;
1011
+ for (u = a & (1 << -_) - 1, a >>= -_, _ += o; _ > 0; u = u * 256 + t[e + d], d += S, _ -= 8)
1012
+ ;
1013
+ if (a === 0)
1014
+ a = 1 - p;
1015
+ else {
1016
+ if (a === g)
1017
+ return u ? NaN : (m ? -1 : 1) * (1 / 0);
1018
+ u = u + Math.pow(2, o), a = a - p;
1019
+ }
1020
+ return (m ? -1 : 1) * u * Math.pow(2, a - o);
1021
+ }, qe.write = function(t, e, n, o, c, a) {
1022
+ var u, l, g, p = a * 8 - c - 1, _ = (1 << p) - 1, d = _ >> 1, S = c === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, m = o ? 0 : a - 1, y = o ? 1 : -1, A = e < 0 || e === 0 && 1 / e < 0 ? 1 : 0;
1023
+ for (e = Math.abs(e), isNaN(e) || e === 1 / 0 ? (l = isNaN(e) ? 1 : 0, u = _) : (u = Math.floor(Math.log(e) / Math.LN2), e * (g = Math.pow(2, -u)) < 1 && (u--, g *= 2), u + d >= 1 ? e += S / g : e += S * Math.pow(2, 1 - d), e * g >= 2 && (u++, g /= 2), u + d >= _ ? (l = 0, u = _) : u + d >= 1 ? (l = (e * g - 1) * Math.pow(2, c), u = u + d) : (l = e * Math.pow(2, d - 1) * Math.pow(2, c), u = 0)); c >= 8; t[n + m] = l & 255, m += y, l /= 256, c -= 8)
1024
+ ;
1025
+ for (u = u << c | l, p += c; p > 0; t[n + m] = u & 255, m += y, u /= 256, p -= 8)
1026
+ ;
1027
+ t[n + m - y] |= A * 128;
1028
+ }), qe;
1029
+ }
1030
+ var si;
1031
+ function Un() {
1032
+ return si || (si = 1, (function(t) {
1033
+ const e = Dn(), n = Mn(), o = typeof Symbol == "function" && typeof Symbol.for == "function" ? /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom") : null;
1034
+ t.Buffer = l, t.SlowBuffer = b, t.INSPECT_MAX_BYTES = 50;
1035
+ const c = 2147483647;
1036
+ t.kMaxLength = c, l.TYPED_ARRAY_SUPPORT = a(), !l.TYPED_ARRAY_SUPPORT && typeof console < "u" && typeof console.error == "function" && console.error(
1037
+ "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
1038
+ );
1039
+ function a() {
1040
+ try {
1041
+ const s = new Uint8Array(1), i = { foo: function() {
1042
+ return 42;
1043
+ } };
1044
+ return Object.setPrototypeOf(i, Uint8Array.prototype), Object.setPrototypeOf(s, i), s.foo() === 42;
1045
+ } catch {
1046
+ return !1;
1047
+ }
1048
+ }
1049
+ Object.defineProperty(l.prototype, "parent", {
1050
+ enumerable: !0,
1051
+ get: function() {
1052
+ if (l.isBuffer(this))
1053
+ return this.buffer;
1054
+ }
1055
+ }), Object.defineProperty(l.prototype, "offset", {
1056
+ enumerable: !0,
1057
+ get: function() {
1058
+ if (l.isBuffer(this))
1059
+ return this.byteOffset;
1060
+ }
1061
+ });
1062
+ function u(s) {
1063
+ if (s > c)
1064
+ throw new RangeError('The value "' + s + '" is invalid for option "size"');
1065
+ const i = new Uint8Array(s);
1066
+ return Object.setPrototypeOf(i, l.prototype), i;
1067
+ }
1068
+ function l(s, i, r) {
1069
+ if (typeof s == "number") {
1070
+ if (typeof i == "string")
1071
+ throw new TypeError(
1072
+ 'The "string" argument must be of type string. Received type number'
1073
+ );
1074
+ return d(s);
1075
+ }
1076
+ return g(s, i, r);
1077
+ }
1078
+ l.poolSize = 8192;
1079
+ function g(s, i, r) {
1080
+ if (typeof s == "string")
1081
+ return S(s, i);
1082
+ if (ArrayBuffer.isView(s))
1083
+ return y(s);
1084
+ if (s == null)
1085
+ throw new TypeError(
1086
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof s
1087
+ );
1088
+ if (ee(s, ArrayBuffer) || s && ee(s.buffer, ArrayBuffer) || typeof SharedArrayBuffer < "u" && (ee(s, SharedArrayBuffer) || s && ee(s.buffer, SharedArrayBuffer)))
1089
+ return A(s, i, r);
1090
+ if (typeof s == "number")
1091
+ throw new TypeError(
1092
+ 'The "value" argument must not be of type number. Received type number'
1093
+ );
1094
+ const h = s.valueOf && s.valueOf();
1095
+ if (h != null && h !== s)
1096
+ return l.from(h, i, r);
1097
+ const f = w(s);
1098
+ if (f) return f;
1099
+ if (typeof Symbol < "u" && Symbol.toPrimitive != null && typeof s[Symbol.toPrimitive] == "function")
1100
+ return l.from(s[Symbol.toPrimitive]("string"), i, r);
1101
+ throw new TypeError(
1102
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof s
1103
+ );
1104
+ }
1105
+ l.from = function(s, i, r) {
1106
+ return g(s, i, r);
1107
+ }, Object.setPrototypeOf(l.prototype, Uint8Array.prototype), Object.setPrototypeOf(l, Uint8Array);
1108
+ function p(s) {
1109
+ if (typeof s != "number")
1110
+ throw new TypeError('"size" argument must be of type number');
1111
+ if (s < 0)
1112
+ throw new RangeError('The value "' + s + '" is invalid for option "size"');
1113
+ }
1114
+ function _(s, i, r) {
1115
+ return p(s), s <= 0 ? u(s) : i !== void 0 ? typeof r == "string" ? u(s).fill(i, r) : u(s).fill(i) : u(s);
1116
+ }
1117
+ l.alloc = function(s, i, r) {
1118
+ return _(s, i, r);
1119
+ };
1120
+ function d(s) {
1121
+ return p(s), u(s < 0 ? 0 : I(s) | 0);
1122
+ }
1123
+ l.allocUnsafe = function(s) {
1124
+ return d(s);
1125
+ }, l.allocUnsafeSlow = function(s) {
1126
+ return d(s);
1127
+ };
1128
+ function S(s, i) {
1129
+ if ((typeof i != "string" || i === "") && (i = "utf8"), !l.isEncoding(i))
1130
+ throw new TypeError("Unknown encoding: " + i);
1131
+ const r = x(s, i) | 0;
1132
+ let h = u(r);
1133
+ const f = h.write(s, i);
1134
+ return f !== r && (h = h.slice(0, f)), h;
1135
+ }
1136
+ function m(s) {
1137
+ const i = s.length < 0 ? 0 : I(s.length) | 0, r = u(i);
1138
+ for (let h = 0; h < i; h += 1)
1139
+ r[h] = s[h] & 255;
1140
+ return r;
1141
+ }
1142
+ function y(s) {
1143
+ if (ee(s, Uint8Array)) {
1144
+ const i = new Uint8Array(s);
1145
+ return A(i.buffer, i.byteOffset, i.byteLength);
1146
+ }
1147
+ return m(s);
1148
+ }
1149
+ function A(s, i, r) {
1150
+ if (i < 0 || s.byteLength < i)
1151
+ throw new RangeError('"offset" is outside of buffer bounds');
1152
+ if (s.byteLength < i + (r || 0))
1153
+ throw new RangeError('"length" is outside of buffer bounds');
1154
+ let h;
1155
+ return i === void 0 && r === void 0 ? h = new Uint8Array(s) : r === void 0 ? h = new Uint8Array(s, i) : h = new Uint8Array(s, i, r), Object.setPrototypeOf(h, l.prototype), h;
1156
+ }
1157
+ function w(s) {
1158
+ if (l.isBuffer(s)) {
1159
+ const i = I(s.length) | 0, r = u(i);
1160
+ return r.length === 0 || s.copy(r, 0, 0, i), r;
1161
+ }
1162
+ if (s.length !== void 0)
1163
+ return typeof s.length != "number" || ft(s.length) ? u(0) : m(s);
1164
+ if (s.type === "Buffer" && Array.isArray(s.data))
1165
+ return m(s.data);
1166
+ }
1167
+ function I(s) {
1168
+ if (s >= c)
1169
+ throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + c.toString(16) + " bytes");
1170
+ return s | 0;
1171
+ }
1172
+ function b(s) {
1173
+ return +s != s && (s = 0), l.alloc(+s);
1174
+ }
1175
+ l.isBuffer = function(i) {
1176
+ return i != null && i._isBuffer === !0 && i !== l.prototype;
1177
+ }, l.compare = function(i, r) {
1178
+ if (ee(i, Uint8Array) && (i = l.from(i, i.offset, i.byteLength)), ee(r, Uint8Array) && (r = l.from(r, r.offset, r.byteLength)), !l.isBuffer(i) || !l.isBuffer(r))
1179
+ throw new TypeError(
1180
+ 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
1181
+ );
1182
+ if (i === r) return 0;
1183
+ let h = i.length, f = r.length;
1184
+ for (let E = 0, v = Math.min(h, f); E < v; ++E)
1185
+ if (i[E] !== r[E]) {
1186
+ h = i[E], f = r[E];
1187
+ break;
1188
+ }
1189
+ return h < f ? -1 : f < h ? 1 : 0;
1190
+ }, l.isEncoding = function(i) {
1191
+ switch (String(i).toLowerCase()) {
1192
+ case "hex":
1193
+ case "utf8":
1194
+ case "utf-8":
1195
+ case "ascii":
1196
+ case "latin1":
1197
+ case "binary":
1198
+ case "base64":
1199
+ case "ucs2":
1200
+ case "ucs-2":
1201
+ case "utf16le":
1202
+ case "utf-16le":
1203
+ return !0;
1204
+ default:
1205
+ return !1;
1206
+ }
1207
+ }, l.concat = function(i, r) {
1208
+ if (!Array.isArray(i))
1209
+ throw new TypeError('"list" argument must be an Array of Buffers');
1210
+ if (i.length === 0)
1211
+ return l.alloc(0);
1212
+ let h;
1213
+ if (r === void 0)
1214
+ for (r = 0, h = 0; h < i.length; ++h)
1215
+ r += i[h].length;
1216
+ const f = l.allocUnsafe(r);
1217
+ let E = 0;
1218
+ for (h = 0; h < i.length; ++h) {
1219
+ let v = i[h];
1220
+ if (ee(v, Uint8Array))
1221
+ E + v.length > f.length ? (l.isBuffer(v) || (v = l.from(v)), v.copy(f, E)) : Uint8Array.prototype.set.call(
1222
+ f,
1223
+ v,
1224
+ E
1225
+ );
1226
+ else if (l.isBuffer(v))
1227
+ v.copy(f, E);
1228
+ else
1229
+ throw new TypeError('"list" argument must be an Array of Buffers');
1230
+ E += v.length;
1231
+ }
1232
+ return f;
1233
+ };
1234
+ function x(s, i) {
1235
+ if (l.isBuffer(s))
1236
+ return s.length;
1237
+ if (ArrayBuffer.isView(s) || ee(s, ArrayBuffer))
1238
+ return s.byteLength;
1239
+ if (typeof s != "string")
1240
+ throw new TypeError(
1241
+ 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof s
1242
+ );
1243
+ const r = s.length, h = arguments.length > 2 && arguments[2] === !0;
1244
+ if (!h && r === 0) return 0;
1245
+ let f = !1;
1246
+ for (; ; )
1247
+ switch (i) {
1248
+ case "ascii":
1249
+ case "latin1":
1250
+ case "binary":
1251
+ return r;
1252
+ case "utf8":
1253
+ case "utf-8":
1254
+ return ht(s).length;
1255
+ case "ucs2":
1256
+ case "ucs-2":
1257
+ case "utf16le":
1258
+ case "utf-16le":
1259
+ return r * 2;
1260
+ case "hex":
1261
+ return r >>> 1;
1262
+ case "base64":
1263
+ return jt(s).length;
1264
+ default:
1265
+ if (f)
1266
+ return h ? -1 : ht(s).length;
1267
+ i = ("" + i).toLowerCase(), f = !0;
1268
+ }
1269
+ }
1270
+ l.byteLength = x;
1271
+ function M(s, i, r) {
1272
+ let h = !1;
1273
+ if ((i === void 0 || i < 0) && (i = 0), i > this.length || ((r === void 0 || r > this.length) && (r = this.length), r <= 0) || (r >>>= 0, i >>>= 0, r <= i))
1274
+ return "";
1275
+ for (s || (s = "utf8"); ; )
1276
+ switch (s) {
1277
+ case "hex":
1278
+ return Zi(this, i, r);
1279
+ case "utf8":
1280
+ case "utf-8":
1281
+ return Mt(this, i, r);
1282
+ case "ascii":
1283
+ return Ji(this, i, r);
1284
+ case "latin1":
1285
+ case "binary":
1286
+ return Xi(this, i, r);
1287
+ case "base64":
1288
+ return Yi(this, i, r);
1289
+ case "ucs2":
1290
+ case "ucs-2":
1291
+ case "utf16le":
1292
+ case "utf-16le":
1293
+ return Qi(this, i, r);
1294
+ default:
1295
+ if (h) throw new TypeError("Unknown encoding: " + s);
1296
+ s = (s + "").toLowerCase(), h = !0;
1297
+ }
1298
+ }
1299
+ l.prototype._isBuffer = !0;
1300
+ function N(s, i, r) {
1301
+ const h = s[i];
1302
+ s[i] = s[r], s[r] = h;
1303
+ }
1304
+ l.prototype.swap16 = function() {
1305
+ const i = this.length;
1306
+ if (i % 2 !== 0)
1307
+ throw new RangeError("Buffer size must be a multiple of 16-bits");
1308
+ for (let r = 0; r < i; r += 2)
1309
+ N(this, r, r + 1);
1310
+ return this;
1311
+ }, l.prototype.swap32 = function() {
1312
+ const i = this.length;
1313
+ if (i % 4 !== 0)
1314
+ throw new RangeError("Buffer size must be a multiple of 32-bits");
1315
+ for (let r = 0; r < i; r += 4)
1316
+ N(this, r, r + 3), N(this, r + 1, r + 2);
1317
+ return this;
1318
+ }, l.prototype.swap64 = function() {
1319
+ const i = this.length;
1320
+ if (i % 8 !== 0)
1321
+ throw new RangeError("Buffer size must be a multiple of 64-bits");
1322
+ for (let r = 0; r < i; r += 8)
1323
+ N(this, r, r + 7), N(this, r + 1, r + 6), N(this, r + 2, r + 5), N(this, r + 3, r + 4);
1324
+ return this;
1325
+ }, l.prototype.toString = function() {
1326
+ const i = this.length;
1327
+ return i === 0 ? "" : arguments.length === 0 ? Mt(this, 0, i) : M.apply(this, arguments);
1328
+ }, l.prototype.toLocaleString = l.prototype.toString, l.prototype.equals = function(i) {
1329
+ if (!l.isBuffer(i)) throw new TypeError("Argument must be a Buffer");
1330
+ return this === i ? !0 : l.compare(this, i) === 0;
1331
+ }, l.prototype.inspect = function() {
1332
+ let i = "";
1333
+ const r = t.INSPECT_MAX_BYTES;
1334
+ return i = this.toString("hex", 0, r).replace(/(.{2})/g, "$1 ").trim(), this.length > r && (i += " ... "), "<Buffer " + i + ">";
1335
+ }, o && (l.prototype[o] = l.prototype.inspect), l.prototype.compare = function(i, r, h, f, E) {
1336
+ if (ee(i, Uint8Array) && (i = l.from(i, i.offset, i.byteLength)), !l.isBuffer(i))
1337
+ throw new TypeError(
1338
+ 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof i
1339
+ );
1340
+ if (r === void 0 && (r = 0), h === void 0 && (h = i ? i.length : 0), f === void 0 && (f = 0), E === void 0 && (E = this.length), r < 0 || h > i.length || f < 0 || E > this.length)
1341
+ throw new RangeError("out of range index");
1342
+ if (f >= E && r >= h)
1343
+ return 0;
1344
+ if (f >= E)
1345
+ return -1;
1346
+ if (r >= h)
1347
+ return 1;
1348
+ if (r >>>= 0, h >>>= 0, f >>>= 0, E >>>= 0, this === i) return 0;
1349
+ let v = E - f, T = h - r;
1350
+ const B = Math.min(v, T), U = this.slice(f, E), L = i.slice(r, h);
1351
+ for (let D = 0; D < B; ++D)
1352
+ if (U[D] !== L[D]) {
1353
+ v = U[D], T = L[D];
1354
+ break;
1355
+ }
1356
+ return v < T ? -1 : T < v ? 1 : 0;
1357
+ };
1358
+ function Z(s, i, r, h, f) {
1359
+ if (s.length === 0) return -1;
1360
+ if (typeof r == "string" ? (h = r, r = 0) : r > 2147483647 ? r = 2147483647 : r < -2147483648 && (r = -2147483648), r = +r, ft(r) && (r = f ? 0 : s.length - 1), r < 0 && (r = s.length + r), r >= s.length) {
1361
+ if (f) return -1;
1362
+ r = s.length - 1;
1363
+ } else if (r < 0)
1364
+ if (f) r = 0;
1365
+ else return -1;
1366
+ if (typeof i == "string" && (i = l.from(i, h)), l.isBuffer(i))
1367
+ return i.length === 0 ? -1 : H(s, i, r, h, f);
1368
+ if (typeof i == "number")
1369
+ return i = i & 255, typeof Uint8Array.prototype.indexOf == "function" ? f ? Uint8Array.prototype.indexOf.call(s, i, r) : Uint8Array.prototype.lastIndexOf.call(s, i, r) : H(s, [i], r, h, f);
1370
+ throw new TypeError("val must be string, number or Buffer");
1371
+ }
1372
+ function H(s, i, r, h, f) {
1373
+ let E = 1, v = s.length, T = i.length;
1374
+ if (h !== void 0 && (h = String(h).toLowerCase(), h === "ucs2" || h === "ucs-2" || h === "utf16le" || h === "utf-16le")) {
1375
+ if (s.length < 2 || i.length < 2)
1376
+ return -1;
1377
+ E = 2, v /= 2, T /= 2, r /= 2;
1378
+ }
1379
+ function B(L, D) {
1380
+ return E === 1 ? L[D] : L.readUInt16BE(D * E);
1381
+ }
1382
+ let U;
1383
+ if (f) {
1384
+ let L = -1;
1385
+ for (U = r; U < v; U++)
1386
+ if (B(s, U) === B(i, L === -1 ? 0 : U - L)) {
1387
+ if (L === -1 && (L = U), U - L + 1 === T) return L * E;
1388
+ } else
1389
+ L !== -1 && (U -= U - L), L = -1;
1390
+ } else
1391
+ for (r + T > v && (r = v - T), U = r; U >= 0; U--) {
1392
+ let L = !0;
1393
+ for (let D = 0; D < T; D++)
1394
+ if (B(s, U + D) !== B(i, D)) {
1395
+ L = !1;
1396
+ break;
1397
+ }
1398
+ if (L) return U;
1399
+ }
1400
+ return -1;
1401
+ }
1402
+ l.prototype.includes = function(i, r, h) {
1403
+ return this.indexOf(i, r, h) !== -1;
1404
+ }, l.prototype.indexOf = function(i, r, h) {
1405
+ return Z(this, i, r, h, !0);
1406
+ }, l.prototype.lastIndexOf = function(i, r, h) {
1407
+ return Z(this, i, r, h, !1);
1408
+ };
1409
+ function ae(s, i, r, h) {
1410
+ r = Number(r) || 0;
1411
+ const f = s.length - r;
1412
+ h ? (h = Number(h), h > f && (h = f)) : h = f;
1413
+ const E = i.length;
1414
+ h > E / 2 && (h = E / 2);
1415
+ let v;
1416
+ for (v = 0; v < h; ++v) {
1417
+ const T = parseInt(i.substr(v * 2, 2), 16);
1418
+ if (ft(T)) return v;
1419
+ s[r + v] = T;
1420
+ }
1421
+ return v;
1422
+ }
1423
+ function ne(s, i, r, h) {
1424
+ return Ge(ht(i, s.length - r), s, r, h);
1425
+ }
1426
+ function re(s, i, r, h) {
1427
+ return Ge(rn(i), s, r, h);
1428
+ }
1429
+ function Q(s, i, r, h) {
1430
+ return Ge(jt(i), s, r, h);
1431
+ }
1432
+ function le(s, i, r, h) {
1433
+ return Ge(on(i, s.length - r), s, r, h);
1434
+ }
1435
+ l.prototype.write = function(i, r, h, f) {
1436
+ if (r === void 0)
1437
+ f = "utf8", h = this.length, r = 0;
1438
+ else if (h === void 0 && typeof r == "string")
1439
+ f = r, h = this.length, r = 0;
1440
+ else if (isFinite(r))
1441
+ r = r >>> 0, isFinite(h) ? (h = h >>> 0, f === void 0 && (f = "utf8")) : (f = h, h = void 0);
1442
+ else
1443
+ throw new Error(
1444
+ "Buffer.write(string, encoding, offset[, length]) is no longer supported"
1445
+ );
1446
+ const E = this.length - r;
1447
+ if ((h === void 0 || h > E) && (h = E), i.length > 0 && (h < 0 || r < 0) || r > this.length)
1448
+ throw new RangeError("Attempt to write outside buffer bounds");
1449
+ f || (f = "utf8");
1450
+ let v = !1;
1451
+ for (; ; )
1452
+ switch (f) {
1453
+ case "hex":
1454
+ return ae(this, i, r, h);
1455
+ case "utf8":
1456
+ case "utf-8":
1457
+ return ne(this, i, r, h);
1458
+ case "ascii":
1459
+ case "latin1":
1460
+ case "binary":
1461
+ return re(this, i, r, h);
1462
+ case "base64":
1463
+ return Q(this, i, r, h);
1464
+ case "ucs2":
1465
+ case "ucs-2":
1466
+ case "utf16le":
1467
+ case "utf-16le":
1468
+ return le(this, i, r, h);
1469
+ default:
1470
+ if (v) throw new TypeError("Unknown encoding: " + f);
1471
+ f = ("" + f).toLowerCase(), v = !0;
1472
+ }
1473
+ }, l.prototype.toJSON = function() {
1474
+ return {
1475
+ type: "Buffer",
1476
+ data: Array.prototype.slice.call(this._arr || this, 0)
1477
+ };
1478
+ };
1479
+ function Yi(s, i, r) {
1480
+ return i === 0 && r === s.length ? e.fromByteArray(s) : e.fromByteArray(s.slice(i, r));
1481
+ }
1482
+ function Mt(s, i, r) {
1483
+ r = Math.min(s.length, r);
1484
+ const h = [];
1485
+ let f = i;
1486
+ for (; f < r; ) {
1487
+ const E = s[f];
1488
+ let v = null, T = E > 239 ? 4 : E > 223 ? 3 : E > 191 ? 2 : 1;
1489
+ if (f + T <= r) {
1490
+ let B, U, L, D;
1491
+ switch (T) {
1492
+ case 1:
1493
+ E < 128 && (v = E);
1494
+ break;
1495
+ case 2:
1496
+ B = s[f + 1], (B & 192) === 128 && (D = (E & 31) << 6 | B & 63, D > 127 && (v = D));
1497
+ break;
1498
+ case 3:
1499
+ B = s[f + 1], U = s[f + 2], (B & 192) === 128 && (U & 192) === 128 && (D = (E & 15) << 12 | (B & 63) << 6 | U & 63, D > 2047 && (D < 55296 || D > 57343) && (v = D));
1500
+ break;
1501
+ case 4:
1502
+ B = s[f + 1], U = s[f + 2], L = s[f + 3], (B & 192) === 128 && (U & 192) === 128 && (L & 192) === 128 && (D = (E & 15) << 18 | (B & 63) << 12 | (U & 63) << 6 | L & 63, D > 65535 && D < 1114112 && (v = D));
1503
+ }
1504
+ }
1505
+ v === null ? (v = 65533, T = 1) : v > 65535 && (v -= 65536, h.push(v >>> 10 & 1023 | 55296), v = 56320 | v & 1023), h.push(v), f += T;
1506
+ }
1507
+ return Ki(h);
1508
+ }
1509
+ const Ut = 4096;
1510
+ function Ki(s) {
1511
+ const i = s.length;
1512
+ if (i <= Ut)
1513
+ return String.fromCharCode.apply(String, s);
1514
+ let r = "", h = 0;
1515
+ for (; h < i; )
1516
+ r += String.fromCharCode.apply(
1517
+ String,
1518
+ s.slice(h, h += Ut)
1519
+ );
1520
+ return r;
1521
+ }
1522
+ function Ji(s, i, r) {
1523
+ let h = "";
1524
+ r = Math.min(s.length, r);
1525
+ for (let f = i; f < r; ++f)
1526
+ h += String.fromCharCode(s[f] & 127);
1527
+ return h;
1528
+ }
1529
+ function Xi(s, i, r) {
1530
+ let h = "";
1531
+ r = Math.min(s.length, r);
1532
+ for (let f = i; f < r; ++f)
1533
+ h += String.fromCharCode(s[f]);
1534
+ return h;
1535
+ }
1536
+ function Zi(s, i, r) {
1537
+ const h = s.length;
1538
+ (!i || i < 0) && (i = 0), (!r || r < 0 || r > h) && (r = h);
1539
+ let f = "";
1540
+ for (let E = i; E < r; ++E)
1541
+ f += sn[s[E]];
1542
+ return f;
1543
+ }
1544
+ function Qi(s, i, r) {
1545
+ const h = s.slice(i, r);
1546
+ let f = "";
1547
+ for (let E = 0; E < h.length - 1; E += 2)
1548
+ f += String.fromCharCode(h[E] + h[E + 1] * 256);
1549
+ return f;
1550
+ }
1551
+ l.prototype.slice = function(i, r) {
1552
+ const h = this.length;
1553
+ i = ~~i, r = r === void 0 ? h : ~~r, i < 0 ? (i += h, i < 0 && (i = 0)) : i > h && (i = h), r < 0 ? (r += h, r < 0 && (r = 0)) : r > h && (r = h), r < i && (r = i);
1554
+ const f = this.subarray(i, r);
1555
+ return Object.setPrototypeOf(f, l.prototype), f;
1556
+ };
1557
+ function G(s, i, r) {
1558
+ if (s % 1 !== 0 || s < 0) throw new RangeError("offset is not uint");
1559
+ if (s + i > r) throw new RangeError("Trying to access beyond buffer length");
1560
+ }
1561
+ l.prototype.readUintLE = l.prototype.readUIntLE = function(i, r, h) {
1562
+ i = i >>> 0, r = r >>> 0, h || G(i, r, this.length);
1563
+ let f = this[i], E = 1, v = 0;
1564
+ for (; ++v < r && (E *= 256); )
1565
+ f += this[i + v] * E;
1566
+ return f;
1567
+ }, l.prototype.readUintBE = l.prototype.readUIntBE = function(i, r, h) {
1568
+ i = i >>> 0, r = r >>> 0, h || G(i, r, this.length);
1569
+ let f = this[i + --r], E = 1;
1570
+ for (; r > 0 && (E *= 256); )
1571
+ f += this[i + --r] * E;
1572
+ return f;
1573
+ }, l.prototype.readUint8 = l.prototype.readUInt8 = function(i, r) {
1574
+ return i = i >>> 0, r || G(i, 1, this.length), this[i];
1575
+ }, l.prototype.readUint16LE = l.prototype.readUInt16LE = function(i, r) {
1576
+ return i = i >>> 0, r || G(i, 2, this.length), this[i] | this[i + 1] << 8;
1577
+ }, l.prototype.readUint16BE = l.prototype.readUInt16BE = function(i, r) {
1578
+ return i = i >>> 0, r || G(i, 2, this.length), this[i] << 8 | this[i + 1];
1579
+ }, l.prototype.readUint32LE = l.prototype.readUInt32LE = function(i, r) {
1580
+ return i = i >>> 0, r || G(i, 4, this.length), (this[i] | this[i + 1] << 8 | this[i + 2] << 16) + this[i + 3] * 16777216;
1581
+ }, l.prototype.readUint32BE = l.prototype.readUInt32BE = function(i, r) {
1582
+ return i = i >>> 0, r || G(i, 4, this.length), this[i] * 16777216 + (this[i + 1] << 16 | this[i + 2] << 8 | this[i + 3]);
1583
+ }, l.prototype.readBigUInt64LE = ce(function(i) {
1584
+ i = i >>> 0, ye(i, "offset");
1585
+ const r = this[i], h = this[i + 7];
1586
+ (r === void 0 || h === void 0) && Re(i, this.length - 8);
1587
+ const f = r + this[++i] * 2 ** 8 + this[++i] * 2 ** 16 + this[++i] * 2 ** 24, E = this[++i] + this[++i] * 2 ** 8 + this[++i] * 2 ** 16 + h * 2 ** 24;
1588
+ return BigInt(f) + (BigInt(E) << BigInt(32));
1589
+ }), l.prototype.readBigUInt64BE = ce(function(i) {
1590
+ i = i >>> 0, ye(i, "offset");
1591
+ const r = this[i], h = this[i + 7];
1592
+ (r === void 0 || h === void 0) && Re(i, this.length - 8);
1593
+ const f = r * 2 ** 24 + this[++i] * 2 ** 16 + this[++i] * 2 ** 8 + this[++i], E = this[++i] * 2 ** 24 + this[++i] * 2 ** 16 + this[++i] * 2 ** 8 + h;
1594
+ return (BigInt(f) << BigInt(32)) + BigInt(E);
1595
+ }), l.prototype.readIntLE = function(i, r, h) {
1596
+ i = i >>> 0, r = r >>> 0, h || G(i, r, this.length);
1597
+ let f = this[i], E = 1, v = 0;
1598
+ for (; ++v < r && (E *= 256); )
1599
+ f += this[i + v] * E;
1600
+ return E *= 128, f >= E && (f -= Math.pow(2, 8 * r)), f;
1601
+ }, l.prototype.readIntBE = function(i, r, h) {
1602
+ i = i >>> 0, r = r >>> 0, h || G(i, r, this.length);
1603
+ let f = r, E = 1, v = this[i + --f];
1604
+ for (; f > 0 && (E *= 256); )
1605
+ v += this[i + --f] * E;
1606
+ return E *= 128, v >= E && (v -= Math.pow(2, 8 * r)), v;
1607
+ }, l.prototype.readInt8 = function(i, r) {
1608
+ return i = i >>> 0, r || G(i, 1, this.length), this[i] & 128 ? (255 - this[i] + 1) * -1 : this[i];
1609
+ }, l.prototype.readInt16LE = function(i, r) {
1610
+ i = i >>> 0, r || G(i, 2, this.length);
1611
+ const h = this[i] | this[i + 1] << 8;
1612
+ return h & 32768 ? h | 4294901760 : h;
1613
+ }, l.prototype.readInt16BE = function(i, r) {
1614
+ i = i >>> 0, r || G(i, 2, this.length);
1615
+ const h = this[i + 1] | this[i] << 8;
1616
+ return h & 32768 ? h | 4294901760 : h;
1617
+ }, l.prototype.readInt32LE = function(i, r) {
1618
+ return i = i >>> 0, r || G(i, 4, this.length), this[i] | this[i + 1] << 8 | this[i + 2] << 16 | this[i + 3] << 24;
1619
+ }, l.prototype.readInt32BE = function(i, r) {
1620
+ return i = i >>> 0, r || G(i, 4, this.length), this[i] << 24 | this[i + 1] << 16 | this[i + 2] << 8 | this[i + 3];
1621
+ }, l.prototype.readBigInt64LE = ce(function(i) {
1622
+ i = i >>> 0, ye(i, "offset");
1623
+ const r = this[i], h = this[i + 7];
1624
+ (r === void 0 || h === void 0) && Re(i, this.length - 8);
1625
+ const f = this[i + 4] + this[i + 5] * 2 ** 8 + this[i + 6] * 2 ** 16 + (h << 24);
1626
+ return (BigInt(f) << BigInt(32)) + BigInt(r + this[++i] * 2 ** 8 + this[++i] * 2 ** 16 + this[++i] * 2 ** 24);
1627
+ }), l.prototype.readBigInt64BE = ce(function(i) {
1628
+ i = i >>> 0, ye(i, "offset");
1629
+ const r = this[i], h = this[i + 7];
1630
+ (r === void 0 || h === void 0) && Re(i, this.length - 8);
1631
+ const f = (r << 24) + // Overflow
1632
+ this[++i] * 2 ** 16 + this[++i] * 2 ** 8 + this[++i];
1633
+ return (BigInt(f) << BigInt(32)) + BigInt(this[++i] * 2 ** 24 + this[++i] * 2 ** 16 + this[++i] * 2 ** 8 + h);
1634
+ }), l.prototype.readFloatLE = function(i, r) {
1635
+ return i = i >>> 0, r || G(i, 4, this.length), n.read(this, i, !0, 23, 4);
1636
+ }, l.prototype.readFloatBE = function(i, r) {
1637
+ return i = i >>> 0, r || G(i, 4, this.length), n.read(this, i, !1, 23, 4);
1638
+ }, l.prototype.readDoubleLE = function(i, r) {
1639
+ return i = i >>> 0, r || G(i, 8, this.length), n.read(this, i, !0, 52, 8);
1640
+ }, l.prototype.readDoubleBE = function(i, r) {
1641
+ return i = i >>> 0, r || G(i, 8, this.length), n.read(this, i, !1, 52, 8);
1642
+ };
1643
+ function q(s, i, r, h, f, E) {
1644
+ if (!l.isBuffer(s)) throw new TypeError('"buffer" argument must be a Buffer instance');
1645
+ if (i > f || i < E) throw new RangeError('"value" argument is out of bounds');
1646
+ if (r + h > s.length) throw new RangeError("Index out of range");
1647
+ }
1648
+ l.prototype.writeUintLE = l.prototype.writeUIntLE = function(i, r, h, f) {
1649
+ if (i = +i, r = r >>> 0, h = h >>> 0, !f) {
1650
+ const T = Math.pow(2, 8 * h) - 1;
1651
+ q(this, i, r, h, T, 0);
1652
+ }
1653
+ let E = 1, v = 0;
1654
+ for (this[r] = i & 255; ++v < h && (E *= 256); )
1655
+ this[r + v] = i / E & 255;
1656
+ return r + h;
1657
+ }, l.prototype.writeUintBE = l.prototype.writeUIntBE = function(i, r, h, f) {
1658
+ if (i = +i, r = r >>> 0, h = h >>> 0, !f) {
1659
+ const T = Math.pow(2, 8 * h) - 1;
1660
+ q(this, i, r, h, T, 0);
1661
+ }
1662
+ let E = h - 1, v = 1;
1663
+ for (this[r + E] = i & 255; --E >= 0 && (v *= 256); )
1664
+ this[r + E] = i / v & 255;
1665
+ return r + h;
1666
+ }, l.prototype.writeUint8 = l.prototype.writeUInt8 = function(i, r, h) {
1667
+ return i = +i, r = r >>> 0, h || q(this, i, r, 1, 255, 0), this[r] = i & 255, r + 1;
1668
+ }, l.prototype.writeUint16LE = l.prototype.writeUInt16LE = function(i, r, h) {
1669
+ return i = +i, r = r >>> 0, h || q(this, i, r, 2, 65535, 0), this[r] = i & 255, this[r + 1] = i >>> 8, r + 2;
1670
+ }, l.prototype.writeUint16BE = l.prototype.writeUInt16BE = function(i, r, h) {
1671
+ return i = +i, r = r >>> 0, h || q(this, i, r, 2, 65535, 0), this[r] = i >>> 8, this[r + 1] = i & 255, r + 2;
1672
+ }, l.prototype.writeUint32LE = l.prototype.writeUInt32LE = function(i, r, h) {
1673
+ return i = +i, r = r >>> 0, h || q(this, i, r, 4, 4294967295, 0), this[r + 3] = i >>> 24, this[r + 2] = i >>> 16, this[r + 1] = i >>> 8, this[r] = i & 255, r + 4;
1674
+ }, l.prototype.writeUint32BE = l.prototype.writeUInt32BE = function(i, r, h) {
1675
+ return i = +i, r = r >>> 0, h || q(this, i, r, 4, 4294967295, 0), this[r] = i >>> 24, this[r + 1] = i >>> 16, this[r + 2] = i >>> 8, this[r + 3] = i & 255, r + 4;
1676
+ };
1677
+ function Bt(s, i, r, h, f) {
1678
+ Vt(i, h, f, s, r, 7);
1679
+ let E = Number(i & BigInt(4294967295));
1680
+ s[r++] = E, E = E >> 8, s[r++] = E, E = E >> 8, s[r++] = E, E = E >> 8, s[r++] = E;
1681
+ let v = Number(i >> BigInt(32) & BigInt(4294967295));
1682
+ return s[r++] = v, v = v >> 8, s[r++] = v, v = v >> 8, s[r++] = v, v = v >> 8, s[r++] = v, r;
1683
+ }
1684
+ function Lt(s, i, r, h, f) {
1685
+ Vt(i, h, f, s, r, 7);
1686
+ let E = Number(i & BigInt(4294967295));
1687
+ s[r + 7] = E, E = E >> 8, s[r + 6] = E, E = E >> 8, s[r + 5] = E, E = E >> 8, s[r + 4] = E;
1688
+ let v = Number(i >> BigInt(32) & BigInt(4294967295));
1689
+ return s[r + 3] = v, v = v >> 8, s[r + 2] = v, v = v >> 8, s[r + 1] = v, v = v >> 8, s[r] = v, r + 8;
1690
+ }
1691
+ l.prototype.writeBigUInt64LE = ce(function(i, r = 0) {
1692
+ return Bt(this, i, r, BigInt(0), BigInt("0xffffffffffffffff"));
1693
+ }), l.prototype.writeBigUInt64BE = ce(function(i, r = 0) {
1694
+ return Lt(this, i, r, BigInt(0), BigInt("0xffffffffffffffff"));
1695
+ }), l.prototype.writeIntLE = function(i, r, h, f) {
1696
+ if (i = +i, r = r >>> 0, !f) {
1697
+ const B = Math.pow(2, 8 * h - 1);
1698
+ q(this, i, r, h, B - 1, -B);
1699
+ }
1700
+ let E = 0, v = 1, T = 0;
1701
+ for (this[r] = i & 255; ++E < h && (v *= 256); )
1702
+ i < 0 && T === 0 && this[r + E - 1] !== 0 && (T = 1), this[r + E] = (i / v >> 0) - T & 255;
1703
+ return r + h;
1704
+ }, l.prototype.writeIntBE = function(i, r, h, f) {
1705
+ if (i = +i, r = r >>> 0, !f) {
1706
+ const B = Math.pow(2, 8 * h - 1);
1707
+ q(this, i, r, h, B - 1, -B);
1708
+ }
1709
+ let E = h - 1, v = 1, T = 0;
1710
+ for (this[r + E] = i & 255; --E >= 0 && (v *= 256); )
1711
+ i < 0 && T === 0 && this[r + E + 1] !== 0 && (T = 1), this[r + E] = (i / v >> 0) - T & 255;
1712
+ return r + h;
1713
+ }, l.prototype.writeInt8 = function(i, r, h) {
1714
+ return i = +i, r = r >>> 0, h || q(this, i, r, 1, 127, -128), i < 0 && (i = 255 + i + 1), this[r] = i & 255, r + 1;
1715
+ }, l.prototype.writeInt16LE = function(i, r, h) {
1716
+ return i = +i, r = r >>> 0, h || q(this, i, r, 2, 32767, -32768), this[r] = i & 255, this[r + 1] = i >>> 8, r + 2;
1717
+ }, l.prototype.writeInt16BE = function(i, r, h) {
1718
+ return i = +i, r = r >>> 0, h || q(this, i, r, 2, 32767, -32768), this[r] = i >>> 8, this[r + 1] = i & 255, r + 2;
1719
+ }, l.prototype.writeInt32LE = function(i, r, h) {
1720
+ return i = +i, r = r >>> 0, h || q(this, i, r, 4, 2147483647, -2147483648), this[r] = i & 255, this[r + 1] = i >>> 8, this[r + 2] = i >>> 16, this[r + 3] = i >>> 24, r + 4;
1721
+ }, l.prototype.writeInt32BE = function(i, r, h) {
1722
+ return i = +i, r = r >>> 0, h || q(this, i, r, 4, 2147483647, -2147483648), i < 0 && (i = 4294967295 + i + 1), this[r] = i >>> 24, this[r + 1] = i >>> 16, this[r + 2] = i >>> 8, this[r + 3] = i & 255, r + 4;
1723
+ }, l.prototype.writeBigInt64LE = ce(function(i, r = 0) {
1724
+ return Bt(this, i, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1725
+ }), l.prototype.writeBigInt64BE = ce(function(i, r = 0) {
1726
+ return Lt(this, i, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1727
+ });
1728
+ function Pt(s, i, r, h, f, E) {
1729
+ if (r + h > s.length) throw new RangeError("Index out of range");
1730
+ if (r < 0) throw new RangeError("Index out of range");
1731
+ }
1732
+ function Ft(s, i, r, h, f) {
1733
+ return i = +i, r = r >>> 0, f || Pt(s, i, r, 4), n.write(s, i, r, h, 23, 4), r + 4;
1734
+ }
1735
+ l.prototype.writeFloatLE = function(i, r, h) {
1736
+ return Ft(this, i, r, !0, h);
1737
+ }, l.prototype.writeFloatBE = function(i, r, h) {
1738
+ return Ft(this, i, r, !1, h);
1739
+ };
1740
+ function $t(s, i, r, h, f) {
1741
+ return i = +i, r = r >>> 0, f || Pt(s, i, r, 8), n.write(s, i, r, h, 52, 8), r + 8;
1742
+ }
1743
+ l.prototype.writeDoubleLE = function(i, r, h) {
1744
+ return $t(this, i, r, !0, h);
1745
+ }, l.prototype.writeDoubleBE = function(i, r, h) {
1746
+ return $t(this, i, r, !1, h);
1747
+ }, l.prototype.copy = function(i, r, h, f) {
1748
+ if (!l.isBuffer(i)) throw new TypeError("argument should be a Buffer");
1749
+ if (h || (h = 0), !f && f !== 0 && (f = this.length), r >= i.length && (r = i.length), r || (r = 0), f > 0 && f < h && (f = h), f === h || i.length === 0 || this.length === 0) return 0;
1750
+ if (r < 0)
1751
+ throw new RangeError("targetStart out of bounds");
1752
+ if (h < 0 || h >= this.length) throw new RangeError("Index out of range");
1753
+ if (f < 0) throw new RangeError("sourceEnd out of bounds");
1754
+ f > this.length && (f = this.length), i.length - r < f - h && (f = i.length - r + h);
1755
+ const E = f - h;
1756
+ return this === i && typeof Uint8Array.prototype.copyWithin == "function" ? this.copyWithin(r, h, f) : Uint8Array.prototype.set.call(
1757
+ i,
1758
+ this.subarray(h, f),
1759
+ r
1760
+ ), E;
1761
+ }, l.prototype.fill = function(i, r, h, f) {
1762
+ if (typeof i == "string") {
1763
+ if (typeof r == "string" ? (f = r, r = 0, h = this.length) : typeof h == "string" && (f = h, h = this.length), f !== void 0 && typeof f != "string")
1764
+ throw new TypeError("encoding must be a string");
1765
+ if (typeof f == "string" && !l.isEncoding(f))
1766
+ throw new TypeError("Unknown encoding: " + f);
1767
+ if (i.length === 1) {
1768
+ const v = i.charCodeAt(0);
1769
+ (f === "utf8" && v < 128 || f === "latin1") && (i = v);
1770
+ }
1771
+ } else typeof i == "number" ? i = i & 255 : typeof i == "boolean" && (i = Number(i));
1772
+ if (r < 0 || this.length < r || this.length < h)
1773
+ throw new RangeError("Out of range index");
1774
+ if (h <= r)
1775
+ return this;
1776
+ r = r >>> 0, h = h === void 0 ? this.length : h >>> 0, i || (i = 0);
1777
+ let E;
1778
+ if (typeof i == "number")
1779
+ for (E = r; E < h; ++E)
1780
+ this[E] = i;
1781
+ else {
1782
+ const v = l.isBuffer(i) ? i : l.from(i, f), T = v.length;
1783
+ if (T === 0)
1784
+ throw new TypeError('The value "' + i + '" is invalid for argument "value"');
1785
+ for (E = 0; E < h - r; ++E)
1786
+ this[E + r] = v[E % T];
1787
+ }
1788
+ return this;
1789
+ };
1790
+ const ve = {};
1791
+ function dt(s, i, r) {
1792
+ ve[s] = class extends r {
1793
+ constructor() {
1794
+ super(), Object.defineProperty(this, "message", {
1795
+ value: i.apply(this, arguments),
1796
+ writable: !0,
1797
+ configurable: !0
1798
+ }), this.name = `${this.name} [${s}]`, this.stack, delete this.name;
1799
+ }
1800
+ get code() {
1801
+ return s;
1802
+ }
1803
+ set code(f) {
1804
+ Object.defineProperty(this, "code", {
1805
+ configurable: !0,
1806
+ enumerable: !0,
1807
+ value: f,
1808
+ writable: !0
1809
+ });
1810
+ }
1811
+ toString() {
1812
+ return `${this.name} [${s}]: ${this.message}`;
1813
+ }
1814
+ };
1815
+ }
1816
+ dt(
1817
+ "ERR_BUFFER_OUT_OF_BOUNDS",
1818
+ function(s) {
1819
+ return s ? `${s} is outside of buffer bounds` : "Attempt to access memory outside buffer bounds";
1820
+ },
1821
+ RangeError
1822
+ ), dt(
1823
+ "ERR_INVALID_ARG_TYPE",
1824
+ function(s, i) {
1825
+ return `The "${s}" argument must be of type number. Received type ${typeof i}`;
1826
+ },
1827
+ TypeError
1828
+ ), dt(
1829
+ "ERR_OUT_OF_RANGE",
1830
+ function(s, i, r) {
1831
+ let h = `The value of "${s}" is out of range.`, f = r;
1832
+ return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? f = Gt(String(r)) : typeof r == "bigint" && (f = String(r), (r > BigInt(2) ** BigInt(32) || r < -(BigInt(2) ** BigInt(32))) && (f = Gt(f)), f += "n"), h += ` It must be ${i}. Received ${f}`, h;
1833
+ },
1834
+ RangeError
1835
+ );
1836
+ function Gt(s) {
1837
+ let i = "", r = s.length;
1838
+ const h = s[0] === "-" ? 1 : 0;
1839
+ for (; r >= h + 4; r -= 3)
1840
+ i = `_${s.slice(r - 3, r)}${i}`;
1841
+ return `${s.slice(0, r)}${i}`;
1842
+ }
1843
+ function en(s, i, r) {
1844
+ ye(i, "offset"), (s[i] === void 0 || s[i + r] === void 0) && Re(i, s.length - (r + 1));
1845
+ }
1846
+ function Vt(s, i, r, h, f, E) {
1847
+ if (s > r || s < i) {
1848
+ const v = typeof i == "bigint" ? "n" : "";
1849
+ let T;
1850
+ throw i === 0 || i === BigInt(0) ? T = `>= 0${v} and < 2${v} ** ${(E + 1) * 8}${v}` : T = `>= -(2${v} ** ${(E + 1) * 8 - 1}${v}) and < 2 ** ${(E + 1) * 8 - 1}${v}`, new ve.ERR_OUT_OF_RANGE("value", T, s);
1851
+ }
1852
+ en(h, f, E);
1853
+ }
1854
+ function ye(s, i) {
1855
+ if (typeof s != "number")
1856
+ throw new ve.ERR_INVALID_ARG_TYPE(i, "number", s);
1857
+ }
1858
+ function Re(s, i, r) {
1859
+ throw Math.floor(s) !== s ? (ye(s, r), new ve.ERR_OUT_OF_RANGE("offset", "an integer", s)) : i < 0 ? new ve.ERR_BUFFER_OUT_OF_BOUNDS() : new ve.ERR_OUT_OF_RANGE(
1860
+ "offset",
1861
+ `>= 0 and <= ${i}`,
1862
+ s
1863
+ );
1864
+ }
1865
+ const tn = /[^+/0-9A-Za-z-_]/g;
1866
+ function nn(s) {
1867
+ if (s = s.split("=")[0], s = s.trim().replace(tn, ""), s.length < 2) return "";
1868
+ for (; s.length % 4 !== 0; )
1869
+ s = s + "=";
1870
+ return s;
1871
+ }
1872
+ function ht(s, i) {
1873
+ i = i || 1 / 0;
1874
+ let r;
1875
+ const h = s.length;
1876
+ let f = null;
1877
+ const E = [];
1878
+ for (let v = 0; v < h; ++v) {
1879
+ if (r = s.charCodeAt(v), r > 55295 && r < 57344) {
1880
+ if (!f) {
1881
+ if (r > 56319) {
1882
+ (i -= 3) > -1 && E.push(239, 191, 189);
1883
+ continue;
1884
+ } else if (v + 1 === h) {
1885
+ (i -= 3) > -1 && E.push(239, 191, 189);
1886
+ continue;
1887
+ }
1888
+ f = r;
1889
+ continue;
1890
+ }
1891
+ if (r < 56320) {
1892
+ (i -= 3) > -1 && E.push(239, 191, 189), f = r;
1893
+ continue;
1894
+ }
1895
+ r = (f - 55296 << 10 | r - 56320) + 65536;
1896
+ } else f && (i -= 3) > -1 && E.push(239, 191, 189);
1897
+ if (f = null, r < 128) {
1898
+ if ((i -= 1) < 0) break;
1899
+ E.push(r);
1900
+ } else if (r < 2048) {
1901
+ if ((i -= 2) < 0) break;
1902
+ E.push(
1903
+ r >> 6 | 192,
1904
+ r & 63 | 128
1905
+ );
1906
+ } else if (r < 65536) {
1907
+ if ((i -= 3) < 0) break;
1908
+ E.push(
1909
+ r >> 12 | 224,
1910
+ r >> 6 & 63 | 128,
1911
+ r & 63 | 128
1912
+ );
1913
+ } else if (r < 1114112) {
1914
+ if ((i -= 4) < 0) break;
1915
+ E.push(
1916
+ r >> 18 | 240,
1917
+ r >> 12 & 63 | 128,
1918
+ r >> 6 & 63 | 128,
1919
+ r & 63 | 128
1920
+ );
1921
+ } else
1922
+ throw new Error("Invalid code point");
1923
+ }
1924
+ return E;
1925
+ }
1926
+ function rn(s) {
1927
+ const i = [];
1928
+ for (let r = 0; r < s.length; ++r)
1929
+ i.push(s.charCodeAt(r) & 255);
1930
+ return i;
1931
+ }
1932
+ function on(s, i) {
1933
+ let r, h, f;
1934
+ const E = [];
1935
+ for (let v = 0; v < s.length && !((i -= 2) < 0); ++v)
1936
+ r = s.charCodeAt(v), h = r >> 8, f = r % 256, E.push(f), E.push(h);
1937
+ return E;
1938
+ }
1939
+ function jt(s) {
1940
+ return e.toByteArray(nn(s));
1941
+ }
1942
+ function Ge(s, i, r, h) {
1943
+ let f;
1944
+ for (f = 0; f < h && !(f + r >= i.length || f >= s.length); ++f)
1945
+ i[f + r] = s[f];
1946
+ return f;
1947
+ }
1948
+ function ee(s, i) {
1949
+ return s instanceof i || s != null && s.constructor != null && s.constructor.name != null && s.constructor.name === i.name;
1950
+ }
1951
+ function ft(s) {
1952
+ return s !== s;
1953
+ }
1954
+ const sn = (function() {
1955
+ const s = "0123456789abcdef", i = new Array(256);
1956
+ for (let r = 0; r < 16; ++r) {
1957
+ const h = r * 16;
1958
+ for (let f = 0; f < 16; ++f)
1959
+ i[h + f] = s[r] + s[f];
1960
+ }
1961
+ return i;
1962
+ })();
1963
+ function ce(s) {
1964
+ return typeof BigInt > "u" ? an : s;
1965
+ }
1966
+ function an() {
1967
+ throw new Error("BigInt not supported");
1968
+ }
1969
+ })(Et)), Et;
1970
+ }
1971
+ var Bn = Un();
1972
+ const Ln = "https://api.anam.ai", Pn = "/v1", ji = {
1973
+ client: "js-sdk",
1974
+ version: "4.8.0"
1975
+ };
1976
+ var Fn = function(t, e, n, o) {
1977
+ function c(a) {
1978
+ return a instanceof n ? a : new n(function(u) {
1979
+ u(a);
1980
+ });
1981
+ }
1982
+ return new (n || (n = Promise))(function(a, u) {
1983
+ function l(_) {
1984
+ try {
1985
+ p(o.next(_));
1986
+ } catch (d) {
1987
+ u(d);
1988
+ }
1989
+ }
1990
+ function g(_) {
1991
+ try {
1992
+ p(o.throw(_));
1993
+ } catch (d) {
1994
+ u(d);
1995
+ }
1996
+ }
1997
+ function p(_) {
1998
+ _.done ? a(_.value) : c(_.value).then(l, g);
1999
+ }
2000
+ p((o = o.apply(t, e || [])).next());
2001
+ });
2002
+ };
2003
+ const Hi = "https://api.anam.ai", kt = "/v1";
2004
+ var se;
2005
+ (function(t) {
2006
+ t.CLIENT_METRIC_MEASUREMENT_ERROR = "client_error", t.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED = "client_connection_closed", t.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED = "client_connection_established", t.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT = "client_session_attempt", t.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS = "client_session_success";
2007
+ })(se || (se = {}));
2008
+ let It = Hi, Wi = kt, de, zi = !1;
2009
+ const $n = (t, e = kt) => {
2010
+ It = t, Wi = e;
2011
+ }, Gn = (t) => {
2012
+ de = t;
2013
+ }, Vn = (t) => {
2014
+ zi = t;
2015
+ };
2016
+ let he = {
2017
+ sessionId: null,
2018
+ organizationId: null,
2019
+ attemptCorrelationId: null
2020
+ };
2021
+ const Se = (t) => {
2022
+ he = Object.assign(Object.assign({}, he), t);
2023
+ }, me = (t, e, n) => Fn(void 0, void 0, void 0, function* () {
2024
+ if (!zi)
2025
+ try {
2026
+ const o = Object.assign(Object.assign({}, ji), n);
2027
+ he.sessionId && (o.sessionId = he.sessionId), he.organizationId && (o.organizationId = he.organizationId), he.attemptCorrelationId && (o.attemptCorrelationId = he.attemptCorrelationId);
2028
+ const c = `${Wi}/metrics/client`;
2029
+ let a, u = {
2030
+ "Content-Type": "application/json"
2031
+ };
2032
+ de?.enabled && de?.baseUrl ? (a = `${de.baseUrl}${c}`, u["X-Anam-Target-Url"] = `${It}${c}`) : a = `${It}${c}`, yield fetch(a, {
2033
+ method: "POST",
2034
+ headers: u,
2035
+ body: JSON.stringify({
2036
+ name: t,
2037
+ value: e,
2038
+ tags: o
2039
+ })
2040
+ });
2041
+ } catch (o) {
2042
+ console.error("Failed to send error metric:", o);
2043
+ }
2044
+ }), jn = (t, e = "console") => {
2045
+ var n, o, c;
2046
+ const a = {};
2047
+ t.forEach((d) => {
2048
+ a[d.type] || (a[d.type] = []), a[d.type].push(d);
2049
+ });
2050
+ const u = {
2051
+ issues: []
2052
+ }, l = ((n = a["inbound-rtp"]) === null || n === void 0 ? void 0 : n.filter((d) => d.kind === "video")) || [];
2053
+ l.length > 0 && (u.personaVideoStream = [], l.forEach((d) => {
2054
+ var S, m, y, A, w;
2055
+ const I = {
2056
+ framesReceived: (S = d.framesReceived) !== null && S !== void 0 ? S : "unknown",
2057
+ framesDropped: (m = d.framesDropped) !== null && m !== void 0 ? m : "unknown",
2058
+ framesPerSecond: (y = d.framesPerSecond) !== null && y !== void 0 ? y : "unknown",
2059
+ packetsReceived: (A = d.packetsReceived) !== null && A !== void 0 ? A : "unknown",
2060
+ packetsLost: (w = d.packetsLost) !== null && w !== void 0 ? w : "unknown",
2061
+ resolution: d.frameWidth && d.frameHeight ? `${d.frameWidth}x${d.frameHeight}` : void 0,
2062
+ jitter: d.jitter !== void 0 ? d.jitter : void 0
2063
+ };
2064
+ u.personaVideoStream.push(I);
2065
+ }));
2066
+ const g = ((o = a["inbound-rtp"]) === null || o === void 0 ? void 0 : o.filter((d) => d.kind === "audio")) || [];
2067
+ g.length > 0 && (u.personaAudioStream = [], g.forEach((d) => {
2068
+ var S, m, y;
2069
+ const A = {
2070
+ packetsReceived: (S = d.packetsReceived) !== null && S !== void 0 ? S : "unknown",
2071
+ packetsLost: (m = d.packetsLost) !== null && m !== void 0 ? m : "unknown",
2072
+ audioLevel: (y = d.audioLevel) !== null && y !== void 0 ? y : "unknown",
2073
+ jitter: d.jitter !== void 0 ? d.jitter : void 0,
2074
+ totalAudioEnergy: d.totalAudioEnergy !== void 0 ? d.totalAudioEnergy : void 0
2075
+ };
2076
+ u.personaAudioStream.push(A);
2077
+ }));
2078
+ const p = ((c = a["outbound-rtp"]) === null || c === void 0 ? void 0 : c.filter((d) => d.kind === "audio")) || [];
2079
+ p.length > 0 && (u.userAudioInput = [], p.forEach((d) => {
2080
+ var S, m;
2081
+ const y = {
2082
+ packetsSent: (S = d.packetsSent) !== null && S !== void 0 ? S : "unknown",
2083
+ retransmittedPackets: (m = d.retransmittedPacketsSent) !== null && m !== void 0 ? m : void 0,
2084
+ avgPacketSendDelay: d.totalPacketSendDelay !== void 0 ? d.totalPacketSendDelay / (d.packetsSent || 1) * 1e3 : void 0
2085
+ };
2086
+ u.userAudioInput.push(y);
2087
+ })), a.codec && (u.codecs = [], a.codec.forEach((d) => {
2088
+ const S = {
2089
+ status: d.payloadType ? "Active" : "Available",
2090
+ mimeType: d.mimeType || "Unknown",
2091
+ payloadType: d.payloadType || "N/A",
2092
+ clockRate: d.clockRate || void 0,
2093
+ channels: d.channels || void 0
2094
+ };
2095
+ u.codecs.push(S);
2096
+ })), a.transport && (u.transportLayer = [], a.transport.forEach((d) => {
2097
+ const S = {
2098
+ dtlsState: d.dtlsState || "unknown",
2099
+ iceState: d.iceState || "unknown",
2100
+ bytesSent: d.bytesSent || void 0,
2101
+ bytesReceived: d.bytesReceived || void 0
2102
+ };
2103
+ u.transportLayer.push(S);
2104
+ }));
2105
+ const _ = [];
2106
+ if (l.forEach((d) => {
2107
+ typeof d.framesDropped == "number" && d.framesDropped > 0 && _.push(`Video: ${d.framesDropped} frames dropped`), typeof d.packetsLost == "number" && d.packetsLost > 0 && _.push(`Video: ${d.packetsLost} packets lost`), typeof d.framesPerSecond == "number" && d.framesPerSecond < 23 && _.push(`Video: Low frame rate (${d.framesPerSecond} fps)`);
2108
+ }), g.forEach((d) => {
2109
+ typeof d.packetsLost == "number" && d.packetsLost > 0 && _.push(`Audio: ${d.packetsLost} packets lost`), typeof d.jitter == "number" && d.jitter > 0.1 && _.push(`Audio: High jitter (${(d.jitter * 1e3).toFixed(1)}ms)`);
2110
+ }), u.issues = _, e === "json")
2111
+ return u;
2112
+ console.group("📊 WebRTC Session Statistics Report"), u.personaVideoStream && u.personaVideoStream.length > 0 && (console.group("📹 Persona Video Stream (Inbound)"), u.personaVideoStream.forEach((d) => {
2113
+ console.log(`Frames Received: ${d.framesReceived}`), console.log(`Frames Dropped: ${d.framesDropped}`), console.log(`Frames Per Second: ${d.framesPerSecond}`), console.log(`Packets Received: ${typeof d.packetsReceived == "number" ? d.packetsReceived.toLocaleString() : d.packetsReceived}`), console.log(`Packets Lost: ${d.packetsLost}`), d.resolution && console.log(`Resolution: ${d.resolution}`), d.jitter !== void 0 && console.log(`Jitter: ${d.jitter.toFixed(5)}ms`);
2114
+ }), console.groupEnd()), u.personaAudioStream && u.personaAudioStream.length > 0 && (console.group("🔊 Persona Audio Stream (Inbound)"), u.personaAudioStream.forEach((d) => {
2115
+ console.log(`Packets Received: ${typeof d.packetsReceived == "number" ? d.packetsReceived.toLocaleString() : d.packetsReceived}`), console.log(`Packets Lost: ${d.packetsLost}`), console.log(`Audio Level: ${d.audioLevel}`), d.jitter !== void 0 && console.log(`Jitter: ${d.jitter.toFixed(5)}ms`), d.totalAudioEnergy !== void 0 && console.log(`Total Audio Energy: ${d.totalAudioEnergy.toFixed(6)}`);
2116
+ }), console.groupEnd()), u.userAudioInput && u.userAudioInput.length > 0 && (console.group("🎤 User Audio Input (Outbound)"), u.userAudioInput.forEach((d) => {
2117
+ console.log(`Packets Sent: ${typeof d.packetsSent == "number" ? d.packetsSent.toLocaleString() : d.packetsSent}`), d.retransmittedPackets && console.log(`Retransmitted Packets: ${d.retransmittedPackets}`), d.avgPacketSendDelay !== void 0 && console.log(`Avg Packet Send Delay: ${d.avgPacketSendDelay.toFixed(5)}ms`);
2118
+ }), console.groupEnd()), u.codecs && u.codecs.length > 0 && (console.group("🔧 Codecs Used"), u.codecs.forEach((d) => {
2119
+ console.log(`${d.status} ${d.mimeType} - Payload Type: ${d.payloadType}`), d.clockRate && console.log(` Clock Rate: ${d.clockRate}Hz`), d.channels && console.log(` Channels: ${d.channels}`);
2120
+ }), console.groupEnd()), u.transportLayer && u.transportLayer.length > 0 && (console.group("🚚 Transport Layer"), u.transportLayer.forEach((d) => {
2121
+ console.log(`DTLS State: ${d.dtlsState}`), console.log(`ICE State: ${d.iceState}`), (d.bytesReceived || d.bytesSent) && console.log(`Data Transfer (bytes) - Sent: ${(d.bytesSent || 0).toLocaleString()}, Received: ${(d.bytesReceived || 0).toLocaleString()}`);
2122
+ }), console.groupEnd()), u.issues.length > 0 ? (console.group("⚠️ Potential Issues Detected"), u.issues.forEach((d) => console.warn(d)), console.groupEnd()) : console.log("✅ No significant issues detected"), console.groupEnd();
2123
+ };
2124
+ var V;
2125
+ (function(t) {
2126
+ t.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED = "CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED", t.CLIENT_ERROR_CODE_SPEND_CAP_REACHED = "CLIENT_ERROR_CODE_SPEND_CAP_REACHED", t.CLIENT_ERROR_CODE_VALIDATION_ERROR = "CLIENT_ERROR_CODE_VALIDATION_ERROR", t.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR = "CLIENT_ERROR_CODE_AUTHENTICATION_ERROR", t.CLIENT_ERROR_CODE_SERVER_ERROR = "CLIENT_ERROR_CODE_SERVER_ERROR", t.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED = "CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED", t.CLIENT_ERROR_CODE_SERVICE_BUSY = "CLIENT_ERROR_CODE_SERVICE_BUSY", t.CLIENT_ERROR_CODE_NO_PLAN_FOUND = "CLIENT_ERROR_CODE_NO_PLAN_FOUND", t.CLIENT_ERROR_CODE_UNKNOWN_ERROR = "CLIENT_ERROR_CODE_UNKNOWN_ERROR", t.CLIENT_ERROR_CODE_CONFIGURATION_ERROR = "CLIENT_ERROR_CODE_CONFIGURATION_ERROR";
2127
+ })(V || (V = {}));
2128
+ class $ extends Error {
2129
+ constructor(e, n, o = 500, c) {
2130
+ super(e), this.name = "ClientError", this.code = n, this.statusCode = o, this.details = c, Object.setPrototypeOf(this, $.prototype), me(se.CLIENT_METRIC_MEASUREMENT_ERROR, n, {
2131
+ details: c,
2132
+ statusCode: o
2133
+ });
2134
+ }
2135
+ }
2136
+ function ai() {
2137
+ return typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : Date.now().toString(36) + Math.random().toString(36).substr(2, 9);
2138
+ }
2139
+ function Hn(t) {
2140
+ if (!(!t || !t.enabled)) {
2141
+ if (!t.baseUrl)
2142
+ return "API Gateway baseUrl is required when enabled";
2143
+ try {
2144
+ const e = new URL(t.baseUrl);
2145
+ if (!["http:", "https:", "ws:", "wss:"].includes(e.protocol))
2146
+ return `Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`;
2147
+ } catch {
2148
+ return `Invalid API Gateway baseUrl: ${t.baseUrl}`;
2149
+ }
2150
+ if (t.wsPath && !t.wsPath.startsWith("/"))
2151
+ return "API Gateway wsPath must start with /";
2152
+ }
2153
+ }
2154
+ var W;
2155
+ (function(t) {
2156
+ t.OFFER = "offer", t.ANSWER = "answer", t.ICE_CANDIDATE = "icecandidate", t.END_SESSION = "endsession", t.HEARTBEAT = "heartbeat", t.WARNING = "warning", t.TALK_STREAM_INTERRUPTED = "talkinputstreaminterrupted", t.TALK_STREAM_INPUT = "talkstream", t.SESSION_READY = "sessionready", t.AGENT_AUDIO_INPUT = "agentaudioinput", t.AGENT_AUDIO_INPUT_END = "agentaudioinputend";
2157
+ })(W || (W = {}));
2158
+ var De;
2159
+ (function(t) {
2160
+ t.SPEECH_TEXT = "speechText", t.CLIENT_TOOL_EVENT = "clientToolEvent", t.REASONING_TEXT = "reasoningText";
2161
+ })(De || (De = {}));
2162
+ var fe;
2163
+ (function(t) {
2164
+ t.PENDING = "pending", t.GRANTED = "granted", t.DENIED = "denied", t.NOT_REQUESTED = "not_requested";
2165
+ })(fe || (fe = {}));
2166
+ var it;
2167
+ (function(t) {
2168
+ t.USER = "user", t.PERSONA = "persona";
2169
+ })(it || (it = {}));
2170
+ var R;
2171
+ (function(t) {
2172
+ t.MESSAGE_HISTORY_UPDATED = "MESSAGE_HISTORY_UPDATED", t.MESSAGE_STREAM_EVENT_RECEIVED = "MESSAGE_STREAM_EVENT_RECEIVED", t.CONNECTION_ESTABLISHED = "CONNECTION_ESTABLISHED", t.CONNECTION_CLOSED = "CONNECTION_CLOSED", t.INPUT_AUDIO_STREAM_STARTED = "INPUT_AUDIO_STREAM_STARTED", t.VIDEO_STREAM_STARTED = "VIDEO_STREAM_STARTED", t.VIDEO_PLAY_STARTED = "VIDEO_PLAY_STARTED", t.AUDIO_STREAM_STARTED = "AUDIO_STREAM_STARTED", t.TALK_STREAM_INTERRUPTED = "TALK_STREAM_INTERRUPTED", t.SESSION_READY = "SESSION_READY", t.SERVER_WARNING = "SERVER_WARNING", t.MIC_PERMISSION_PENDING = "MIC_PERMISSION_PENDING", t.MIC_PERMISSION_GRANTED = "MIC_PERMISSION_GRANTED", t.MIC_PERMISSION_DENIED = "MIC_PERMISSION_DENIED", t.INPUT_AUDIO_DEVICE_CHANGED = "INPUT_AUDIO_DEVICE_CHANGED", t.CLIENT_TOOL_EVENT_RECEIVED = "CLIENT_TOOL_EVENT_RECEIVED", t.REASONING_HISTORY_UPDATED = "REASONING_HISTORY_UPDATED", t.REASONING_STREAM_EVENT_RECEIVED = "REASONING_STREAM_EVENT_RECEIVED";
2173
+ })(R || (R = {}));
2174
+ var J;
2175
+ (function(t) {
2176
+ t.WEB_SOCKET_OPEN = "WEB_SOCKET_OPEN", t.SIGNAL_MESSAGE_RECEIVED = "SIGNAL_MESSAGE_RECEIVED", t.WEBRTC_CHAT_MESSAGE_RECEIVED = "WEBRTC_CHAT_MESSAGE_RECEIVED", t.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED = "WEBRTC_CLIENT_TOOL_EVENT_RECEIVED", t.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED = "WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED";
2177
+ })(J || (J = {}));
2178
+ var _e;
2179
+ (function(t) {
2180
+ t.NORMAL = "CONNECTION_CLOSED_CODE_NORMAL", t.MICROPHONE_PERMISSION_DENIED = "CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED", t.SIGNALLING_CLIENT_CONNECTION_FAILURE = "CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE", t.WEBRTC_FAILURE = "CONNECTION_CLOSED_CODE_WEBRTC_FAILURE", t.SERVER_CLOSED_CONNECTION = "CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION";
2181
+ })(_e || (_e = {}));
2182
+ class Wn {
2183
+ constructor(e, n) {
2184
+ this.sequenceNumber = 0, this.config = e, this.signallingClient = n;
2185
+ }
2186
+ /**
2187
+ * Send PCM audio chunk to server.
2188
+ * @param audioData - Raw PCM audio bytes (ArrayBuffer/Uint8Array) or base64-encoded string
2189
+ */
2190
+ sendAudioChunk(e) {
2191
+ const o = {
2192
+ audioData: typeof e == "string" ? e : this.arrayBufferToBase64(e),
2193
+ encoding: this.config.encoding,
2194
+ sampleRate: this.config.sampleRate,
2195
+ channels: this.config.channels,
2196
+ sequenceNumber: this.sequenceNumber++
2197
+ };
2198
+ this.signallingClient.sendAgentAudioInput(o);
2199
+ }
2200
+ /**
2201
+ * Signal end of the current audio sequence/turn.
2202
+ * Sends AGENT_AUDIO_INPUT_END signal message and resets sequence number.
2203
+ */
2204
+ endSequence() {
2205
+ this.signallingClient.sendAgentAudioInputEnd(), this.sequenceNumber = 0;
2206
+ }
2207
+ /**
2208
+ * Get the current sequence number (number of chunks sent in current sequence).
2209
+ */
2210
+ getSequenceNumber() {
2211
+ return this.sequenceNumber;
2212
+ }
2213
+ /**
2214
+ * Get the audio format configuration for this stream.
2215
+ */
2216
+ getConfig() {
2217
+ return this.config;
2218
+ }
2219
+ arrayBufferToBase64(e) {
2220
+ const n = e instanceof Uint8Array ? e : new Uint8Array(e), o = Array.from(n, (c) => String.fromCharCode(c)).join("");
2221
+ return btoa(o);
2222
+ }
2223
+ }
2224
+ var we = function(t, e, n, o) {
2225
+ function c(a) {
2226
+ return a instanceof n ? a : new n(function(u) {
2227
+ u(a);
2228
+ });
2229
+ }
2230
+ return new (n || (n = Promise))(function(a, u) {
2231
+ function l(_) {
2232
+ try {
2233
+ p(o.next(_));
2234
+ } catch (d) {
2235
+ u(d);
2236
+ }
2237
+ }
2238
+ function g(_) {
2239
+ try {
2240
+ p(o.throw(_));
2241
+ } catch (d) {
2242
+ u(d);
2243
+ }
2244
+ }
2245
+ function p(_) {
2246
+ _.done ? a(_.value) : c(_.value).then(l, g);
2247
+ }
2248
+ p((o = o.apply(t, e || [])).next());
2249
+ });
2250
+ };
2251
+ const zn = 5, qn = 5;
2252
+ class Yn {
2253
+ constructor(e, n, o, c, a) {
2254
+ var u, l, g, p, _;
2255
+ if (this.stopSignal = !1, this.sendingBuffer = [], this.wsConnectionAttempts = 0, this.socket = null, this.heartBeatIntervalRef = null, this.publicEventEmitter = o, this.internalEventEmitter = c, this.apiGatewayConfig = a, !e)
2256
+ throw new Error("Signalling Client: sessionId is required");
2257
+ this.sessionId = e;
2258
+ const { heartbeatIntervalSeconds: d, maxWsReconnectionAttempts: S, url: m } = n;
2259
+ if (this.heartbeatIntervalSeconds = d || zn, this.maxWsReconnectionAttempts = S || qn, !m.baseUrl)
2260
+ throw new Error("Signalling Client: baseUrl is required");
2261
+ if (!((u = this.apiGatewayConfig) === null || u === void 0) && u.enabled && (!((l = this.apiGatewayConfig) === null || l === void 0) && l.baseUrl)) {
2262
+ const y = new URL(this.apiGatewayConfig.baseUrl), A = (g = this.apiGatewayConfig.wsPath) !== null && g !== void 0 ? g : "/ws";
2263
+ y.protocol = y.protocol.replace("http", "ws"), y.pathname = A, this.url = y;
2264
+ const w = m.protocol || "https", I = w === "http" ? "ws" : "wss", b = `${w}://${m.baseUrl}`, x = (p = m.signallingPath) !== null && p !== void 0 ? p : "/ws", M = new URL(b);
2265
+ M.protocol = I === "ws" ? "ws:" : "wss:", m.port && (M.port = m.port), M.pathname = x, M.searchParams.append("session_id", e), this.url.searchParams.append("target_url", M.href);
2266
+ } else {
2267
+ const A = `${m.protocol || "https"}://${m.baseUrl}`;
2268
+ this.url = new URL(A), this.url.protocol = m.protocol === "http" ? "ws:" : "wss:", m.port && (this.url.port = m.port), this.url.pathname = (_ = m.signallingPath) !== null && _ !== void 0 ? _ : "/ws", this.url.searchParams.append("session_id", e);
2269
+ }
2270
+ }
2271
+ stop() {
2272
+ this.stopSignal = !0, this.closeSocket();
2273
+ }
2274
+ connect() {
2275
+ return this.socket = new WebSocket(this.url.href), this.socket.onopen = this.onOpen.bind(this), this.socket.onclose = this.onClose.bind(this), this.socket.onerror = this.onError.bind(this), this.socket;
2276
+ }
2277
+ sendOffer(e) {
2278
+ return we(this, void 0, void 0, function* () {
2279
+ const n = {
2280
+ connectionDescription: e,
2281
+ userUid: this.sessionId
2282
+ // TODO: this should be renamed to session Id on the server
2283
+ }, o = {
2284
+ actionType: W.OFFER,
2285
+ sessionId: this.sessionId,
2286
+ payload: n
2287
+ };
2288
+ this.sendSignalMessage(o);
2289
+ });
2290
+ }
2291
+ sendIceCandidate(e) {
2292
+ return we(this, void 0, void 0, function* () {
2293
+ const n = {
2294
+ actionType: W.ICE_CANDIDATE,
2295
+ sessionId: this.sessionId,
2296
+ payload: e.toJSON()
2297
+ };
2298
+ this.sendSignalMessage(n);
2299
+ });
2300
+ }
2301
+ sendSignalMessage(e) {
2302
+ var n;
2303
+ if (((n = this.socket) === null || n === void 0 ? void 0 : n.readyState) === WebSocket.OPEN)
2304
+ try {
2305
+ this.socket.send(JSON.stringify(e));
2306
+ } catch (o) {
2307
+ console.error("SignallingClient - sendSignalMessage: error sending message", o);
2308
+ }
2309
+ else
2310
+ this.sendingBuffer.push(e);
2311
+ }
2312
+ sendTalkMessage(e) {
2313
+ return we(this, void 0, void 0, function* () {
2314
+ const n = {
2315
+ actionType: W.TALK_STREAM_INPUT,
2316
+ sessionId: this.sessionId,
2317
+ payload: e
2318
+ };
2319
+ this.sendSignalMessage(n);
2320
+ });
2321
+ }
2322
+ sendAgentAudioInput(e) {
2323
+ const n = {
2324
+ actionType: W.AGENT_AUDIO_INPUT,
2325
+ sessionId: this.sessionId,
2326
+ payload: e
2327
+ };
2328
+ this.sendSignalMessage(n);
2329
+ }
2330
+ sendAgentAudioInputEnd() {
2331
+ const e = {
2332
+ actionType: W.AGENT_AUDIO_INPUT_END,
2333
+ sessionId: this.sessionId,
2334
+ payload: {}
2335
+ };
2336
+ this.sendSignalMessage(e);
2337
+ }
2338
+ closeSocket() {
2339
+ this.socket && (this.socket.close(), this.socket = null), this.heartBeatIntervalRef && (clearInterval(this.heartBeatIntervalRef), this.heartBeatIntervalRef = null);
2340
+ }
2341
+ onOpen() {
2342
+ return we(this, void 0, void 0, function* () {
2343
+ if (!this.socket)
2344
+ throw new Error("SignallingClient - onOpen: socket is null");
2345
+ try {
2346
+ this.wsConnectionAttempts = 0, this.flushSendingBuffer(), this.socket.onmessage = this.onMessage.bind(this), this.startSendingHeartBeats(), this.internalEventEmitter.emit(J.WEB_SOCKET_OPEN);
2347
+ } catch (e) {
2348
+ console.error("SignallingClient - onOpen: error in onOpen", e), this.publicEventEmitter.emit(R.CONNECTION_CLOSED, _e.SIGNALLING_CLIENT_CONNECTION_FAILURE);
2349
+ }
2350
+ });
2351
+ }
2352
+ onClose() {
2353
+ return we(this, void 0, void 0, function* () {
2354
+ this.wsConnectionAttempts += 1, !this.stopSignal && (this.wsConnectionAttempts <= this.maxWsReconnectionAttempts ? (this.socket = null, setTimeout(() => {
2355
+ this.connect();
2356
+ }, 100 * this.wsConnectionAttempts)) : (this.heartBeatIntervalRef && (clearInterval(this.heartBeatIntervalRef), this.heartBeatIntervalRef = null), this.publicEventEmitter.emit(R.CONNECTION_CLOSED, _e.SIGNALLING_CLIENT_CONNECTION_FAILURE)));
2357
+ });
2358
+ }
2359
+ onError(e) {
2360
+ this.stopSignal || console.error("SignallingClient - onError: ", e);
2361
+ }
2362
+ flushSendingBuffer() {
2363
+ const e = [];
2364
+ this.sendingBuffer.length > 0 && this.sendingBuffer.forEach((n) => {
2365
+ var o;
2366
+ ((o = this.socket) === null || o === void 0 ? void 0 : o.readyState) === WebSocket.OPEN ? this.socket.send(JSON.stringify(n)) : e.push(n);
2367
+ }), this.sendingBuffer = e;
2368
+ }
2369
+ onMessage(e) {
2370
+ return we(this, void 0, void 0, function* () {
2371
+ const n = JSON.parse(e.data);
2372
+ this.internalEventEmitter.emit(J.SIGNAL_MESSAGE_RECEIVED, n);
2373
+ });
2374
+ }
2375
+ startSendingHeartBeats() {
2376
+ if (!this.socket)
2377
+ throw new Error("SignallingClient - startSendingHeartBeats: socket is null");
2378
+ this.heartBeatIntervalRef && console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");
2379
+ const e = this.heartbeatIntervalSeconds * 1e3, n = {
2380
+ actionType: W.HEARTBEAT,
2381
+ sessionId: this.sessionId,
2382
+ payload: ""
2383
+ }, o = JSON.stringify(n);
2384
+ this.heartBeatIntervalRef = setInterval(() => {
2385
+ var c;
2386
+ this.stopSignal || ((c = this.socket) === null || c === void 0 ? void 0 : c.readyState) === WebSocket.OPEN && this.socket.send(o);
2387
+ }, e);
2388
+ }
2389
+ }
2390
+ function Kn(t) {
2391
+ return "brainType" in t || "llmId" in t;
2392
+ }
2393
+ var li = function(t, e, n, o) {
2394
+ function c(a) {
2395
+ return a instanceof n ? a : new n(function(u) {
2396
+ u(a);
2397
+ });
2398
+ }
2399
+ return new (n || (n = Promise))(function(a, u) {
2400
+ function l(_) {
2401
+ try {
2402
+ p(o.next(_));
2403
+ } catch (d) {
2404
+ u(d);
2405
+ }
2406
+ }
2407
+ function g(_) {
2408
+ try {
2409
+ p(o.throw(_));
2410
+ } catch (d) {
2411
+ u(d);
2412
+ }
2413
+ }
2414
+ function p(_) {
2415
+ _.done ? a(_.value) : c(_.value).then(l, g);
2416
+ }
2417
+ p((o = o.apply(t, e || [])).next());
2418
+ });
2419
+ };
2420
+ class Jn {
2421
+ constructor(e, n, o) {
2422
+ if (!e && !n)
2423
+ throw new Error("Either sessionToken or apiKey must be provided");
2424
+ this.sessionToken = e || null, this.apiKey = n || null, this.baseUrl = o?.baseUrl || Ln, this.apiVersion = o?.apiVersion || Pn, this.apiGatewayConfig = o?.apiGateway || void 0;
2425
+ }
2426
+ /**
2427
+ * Builds URL and headers for a request, applying API Gateway configuration if enabled
2428
+ */
2429
+ buildGatewayUrlAndHeaders(e, n) {
2430
+ var o, c;
2431
+ if (!((o = this.apiGatewayConfig) === null || o === void 0) && o.enabled && (!((c = this.apiGatewayConfig) === null || c === void 0) && c.baseUrl)) {
2432
+ const a = `${this.apiGatewayConfig.baseUrl}${e}`, u = new URL(`${this.baseUrl}${e}`), l = Object.assign(Object.assign({}, n), { "X-Anam-Target-Url": u.href });
2433
+ return { url: a, headers: l };
2434
+ } else
2435
+ return {
2436
+ url: `${this.baseUrl}${e}`,
2437
+ headers: n
2438
+ };
2439
+ }
2440
+ startSession(e, n) {
2441
+ return li(this, void 0, void 0, function* () {
2442
+ if (!this.sessionToken) {
2443
+ if (!e)
2444
+ throw new $("Persona configuration must be provided when using apiKey", V.CLIENT_ERROR_CODE_VALIDATION_ERROR, 400);
2445
+ this.sessionToken = yield this.unsafe_getSessionToken(e);
2446
+ }
2447
+ e && "brainType" in e && console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");
2448
+ try {
2449
+ const o = `${this.apiVersion}/engine/session`, { url: c, headers: a } = this.buildGatewayUrlAndHeaders(o, {
2450
+ "Content-Type": "application/json",
2451
+ Authorization: `Bearer ${this.sessionToken}`
2452
+ }), u = yield fetch(c, {
2453
+ method: "POST",
2454
+ headers: a,
2455
+ body: JSON.stringify({
2456
+ personaConfig: e,
2457
+ sessionOptions: n,
2458
+ clientMetadata: ji
2459
+ })
2460
+ }), l = yield u.json(), g = l.error;
2461
+ switch (u.status) {
2462
+ case 200:
2463
+ case 201:
2464
+ return l;
2465
+ case 400:
2466
+ throw new $("Invalid request to start session", V.CLIENT_ERROR_CODE_VALIDATION_ERROR, 400, { cause: l.message });
2467
+ case 401:
2468
+ throw new $("Authentication failed when starting session", V.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR, 401, { cause: l.message });
2469
+ case 402:
2470
+ throw new $("Please sign up for a plan to start a session", V.CLIENT_ERROR_CODE_NO_PLAN_FOUND, 402, { cause: l.message });
2471
+ case 403:
2472
+ throw new $("Authentication failed when starting session", V.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR, 403, { cause: l.message });
2473
+ case 429:
2474
+ throw g === "Concurrent session limit reached" ? new $("Concurrency limit reached, please upgrade your plan", V.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED, 429, { cause: l.message }) : g === "Spend cap reached" ? new $("Spend cap reached, please upgrade your plan", V.CLIENT_ERROR_CODE_SPEND_CAP_REACHED, 429, { cause: l.message }) : new $("Usage limit reached, please upgrade your plan", V.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED, 429, { cause: l.message });
2475
+ case 503:
2476
+ throw new $("There are no available personas, please try again later", V.CLIENT_ERROR_CODE_SERVICE_BUSY, 503, { cause: l.message });
2477
+ default:
2478
+ throw new $("Unknown error when starting session", V.CLIENT_ERROR_CODE_SERVER_ERROR, 500, { cause: l.message });
2479
+ }
2480
+ } catch (o) {
2481
+ throw o instanceof $ ? o : new $("Failed to start session", V.CLIENT_ERROR_CODE_SERVER_ERROR, 500, { cause: o instanceof Error ? o.message : String(o) });
2482
+ }
2483
+ });
2484
+ }
2485
+ unsafe_getSessionToken(e) {
2486
+ return li(this, void 0, void 0, function* () {
2487
+ if (console.warn("Using unsecure method. This method should not be used in production."), !this.apiKey)
2488
+ throw new Error("No apiKey provided");
2489
+ e && "brainType" in e && console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");
2490
+ let n = {
2491
+ clientLabel: "js-sdk-api-key"
2492
+ };
2493
+ Kn(e) && (n = Object.assign(Object.assign({}, n), { personaConfig: e }));
2494
+ try {
2495
+ const o = `${this.apiVersion}/auth/session-token`, { url: c, headers: a } = this.buildGatewayUrlAndHeaders(o, {
2496
+ "Content-Type": "application/json",
2497
+ Authorization: `Bearer ${this.apiKey}`
2498
+ });
2499
+ return (yield (yield fetch(c, {
2500
+ method: "POST",
2501
+ headers: a,
2502
+ body: JSON.stringify(n)
2503
+ })).json()).sessionToken;
2504
+ } catch {
2505
+ throw new Error("Failed to get session token");
2506
+ }
2507
+ });
2508
+ }
2509
+ getApiUrl() {
2510
+ return `${this.baseUrl}${this.apiVersion}`;
2511
+ }
2512
+ }
2513
+ var Xn = function(t, e, n, o) {
2514
+ function c(a) {
2515
+ return a instanceof n ? a : new n(function(u) {
2516
+ u(a);
2517
+ });
2518
+ }
2519
+ return new (n || (n = Promise))(function(a, u) {
2520
+ function l(_) {
2521
+ try {
2522
+ p(o.next(_));
2523
+ } catch (d) {
2524
+ u(d);
2525
+ }
2526
+ }
2527
+ function g(_) {
2528
+ try {
2529
+ p(o.throw(_));
2530
+ } catch (d) {
2531
+ u(d);
2532
+ }
2533
+ }
2534
+ function p(_) {
2535
+ _.done ? a(_.value) : c(_.value).then(l, g);
2536
+ }
2537
+ p((o = o.apply(t, e || [])).next());
2538
+ });
2539
+ };
2540
+ class Zn {
2541
+ constructor(e, n, o) {
2542
+ this.baseUrl = e, this.sessionId = n, this.apiGatewayConfig = o;
2543
+ }
2544
+ sendTalkCommand(e) {
2545
+ return Xn(this, void 0, void 0, function* () {
2546
+ var n, o;
2547
+ try {
2548
+ let c, a = {
2549
+ "Content-Type": "application/json"
2550
+ };
2551
+ const u = "/talk", l = `?session_id=${this.sessionId}`;
2552
+ if (!((n = this.apiGatewayConfig) === null || n === void 0) && n.enabled && (!((o = this.apiGatewayConfig) === null || o === void 0) && o.baseUrl)) {
2553
+ c = `${this.apiGatewayConfig.baseUrl}${u}${l}`;
2554
+ const p = new URL(`${this.baseUrl}${u}${l}`);
2555
+ a["X-Anam-Target-Url"] = p.href;
2556
+ } else
2557
+ c = `${this.baseUrl}${u}${l}`;
2558
+ const g = yield fetch(c, {
2559
+ method: "POST",
2560
+ headers: a,
2561
+ body: JSON.stringify({
2562
+ content: e
2563
+ })
2564
+ });
2565
+ if (!g.ok)
2566
+ throw new Error(`Failed to send talk command: ${g.status} ${g.statusText}`);
2567
+ } catch (c) {
2568
+ throw console.error(c), new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command");
2569
+ }
2570
+ });
2571
+ }
2572
+ }
2573
+ class Qn {
2574
+ constructor() {
2575
+ this.listeners = {};
2576
+ }
2577
+ addListener(e, n) {
2578
+ this.listeners[e] || (this.listeners[e] = /* @__PURE__ */ new Set()), this.listeners[e].add(n);
2579
+ }
2580
+ removeListener(e, n) {
2581
+ this.listeners[e] && this.listeners[e].delete(n);
2582
+ }
2583
+ emit(e, ...n) {
2584
+ this.listeners[e] && this.listeners[e].forEach((o) => {
2585
+ o(...n);
2586
+ });
2587
+ }
2588
+ }
2589
+ class er {
2590
+ constructor(e, n) {
2591
+ this.messages = [], this.publicEventEmitter = e, this.internalEventEmitter = n, this.internalEventEmitter.addListener(J.WEBRTC_CHAT_MESSAGE_RECEIVED, this.processWebRtcTextMessageEvent.bind(this));
2592
+ }
2593
+ webRtcTextMessageEventToMessageStreamEvent(e) {
2594
+ return {
2595
+ id: `${e.role}::${e.message_id}`,
2596
+ // id is the same for persona and user for a single question response, so we need to differentiate them
2597
+ content: e.content,
2598
+ role: e.role,
2599
+ endOfSpeech: e.end_of_speech,
2600
+ interrupted: e.interrupted
2601
+ };
2602
+ }
2603
+ processUserMessage(e) {
2604
+ const n = {
2605
+ id: e.id,
2606
+ content: e.content,
2607
+ role: e.role
2608
+ };
2609
+ this.messages.push(n);
2610
+ }
2611
+ processPersonaMessage(e) {
2612
+ const n = {
2613
+ id: e.id,
2614
+ content: e.content,
2615
+ role: e.role,
2616
+ interrupted: e.interrupted
2617
+ }, o = this.messages.findIndex((c) => c.id === n.id);
2618
+ if (o !== -1) {
2619
+ const c = this.messages[o];
2620
+ this.messages[o] = Object.assign(Object.assign({}, c), { content: c.content + n.content, interrupted: c.interrupted || n.interrupted });
2621
+ } else
2622
+ this.messages.push(n);
2623
+ }
2624
+ processWebRtcTextMessageEvent(e) {
2625
+ const n = this.webRtcTextMessageEventToMessageStreamEvent(e);
2626
+ switch (this.publicEventEmitter.emit(R.MESSAGE_STREAM_EVENT_RECEIVED, n), n.role) {
2627
+ case it.USER:
2628
+ this.processUserMessage(n);
2629
+ break;
2630
+ case it.PERSONA:
2631
+ this.processPersonaMessage(n);
2632
+ break;
2633
+ }
2634
+ n.endOfSpeech && this.publicEventEmitter.emit(R.MESSAGE_HISTORY_UPDATED, this.messages);
2635
+ }
2636
+ }
2637
+ class tr {
2638
+ constructor() {
2639
+ this.listeners = {};
2640
+ }
2641
+ addListener(e, n) {
2642
+ this.listeners[e] || (this.listeners[e] = /* @__PURE__ */ new Set()), this.listeners[e].add(n);
2643
+ }
2644
+ removeListener(e, n) {
2645
+ this.listeners[e] && this.listeners[e].delete(n);
2646
+ }
2647
+ emit(e, ...n) {
2648
+ if (e === R.CONNECTION_ESTABLISHED && me(se.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED, "1"), e === R.CONNECTION_CLOSED) {
2649
+ const [o, c] = n;
2650
+ me(se.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED, o, c ? { details: c } : void 0);
2651
+ }
2652
+ this.listeners[e] && this.listeners[e].forEach((o) => {
2653
+ o(...n);
2654
+ });
2655
+ }
2656
+ }
2657
+ var z;
2658
+ (function(t) {
2659
+ t[t.UNSTARTED = 0] = "UNSTARTED", t[t.STREAMING = 1] = "STREAMING", t[t.INTERRUPTED = 2] = "INTERRUPTED", t[t.ENDED = 3] = "ENDED";
2660
+ })(z || (z = {}));
2661
+ var mt = function(t, e, n, o) {
2662
+ function c(a) {
2663
+ return a instanceof n ? a : new n(function(u) {
2664
+ u(a);
2665
+ });
2666
+ }
2667
+ return new (n || (n = Promise))(function(a, u) {
2668
+ function l(_) {
2669
+ try {
2670
+ p(o.next(_));
2671
+ } catch (d) {
2672
+ u(d);
2673
+ }
2674
+ }
2675
+ function g(_) {
2676
+ try {
2677
+ p(o.throw(_));
2678
+ } catch (d) {
2679
+ u(d);
2680
+ }
2681
+ }
2682
+ function p(_) {
2683
+ _.done ? a(_.value) : c(_.value).then(l, g);
2684
+ }
2685
+ p((o = o.apply(t, e || [])).next());
2686
+ });
2687
+ };
2688
+ class ir {
2689
+ constructor(e, n, o) {
2690
+ this.state = z.UNSTARTED, this.correlationId = e, this.internalEventEmitter = n, this.signallingClient = o, this.internalEventEmitter.addListener(J.SIGNAL_MESSAGE_RECEIVED, this.onSignalMessage.bind(this));
2691
+ }
2692
+ onDeactivate() {
2693
+ this.internalEventEmitter.removeListener(J.SIGNAL_MESSAGE_RECEIVED, this.onSignalMessage.bind(this));
2694
+ }
2695
+ onSignalMessage(e) {
2696
+ return mt(this, void 0, void 0, function* () {
2697
+ e.actionType === W.TALK_STREAM_INTERRUPTED && e.payload.correlationId === this.correlationId && (this.state = z.INTERRUPTED, this.onDeactivate());
2698
+ });
2699
+ }
2700
+ endMessage() {
2701
+ return mt(this, void 0, void 0, function* () {
2702
+ if (this.state === z.ENDED) {
2703
+ console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");
2704
+ return;
2705
+ }
2706
+ if (this.state !== z.STREAMING) {
2707
+ console.warn("Talk stream is not active state: " + this.state);
2708
+ return;
2709
+ }
2710
+ const e = {
2711
+ content: "",
2712
+ startOfSpeech: !1,
2713
+ endOfSpeech: !0,
2714
+ correlationId: this.correlationId
2715
+ };
2716
+ yield this.signallingClient.sendTalkMessage(e), this.state = z.ENDED, this.onDeactivate();
2717
+ });
2718
+ }
2719
+ streamMessageChunk(e, n) {
2720
+ return mt(this, void 0, void 0, function* () {
2721
+ if (this.state !== z.STREAMING && this.state !== z.UNSTARTED)
2722
+ throw new Error("Talk stream is not in an active state: " + this.state);
2723
+ const o = {
2724
+ content: e,
2725
+ startOfSpeech: this.state === z.UNSTARTED,
2726
+ endOfSpeech: n,
2727
+ correlationId: this.correlationId
2728
+ };
2729
+ this.state = n ? z.ENDED : z.STREAMING, this.state === z.ENDED && this.onDeactivate(), yield this.signallingClient.sendTalkMessage(o);
2730
+ });
2731
+ }
2732
+ getCorrelationId() {
2733
+ return this.correlationId;
2734
+ }
2735
+ isActive() {
2736
+ return this.state === z.STREAMING || this.state === z.UNSTARTED;
2737
+ }
2738
+ getState() {
2739
+ return this.state;
2740
+ }
2741
+ }
2742
+ var K = function(t, e, n, o) {
2743
+ function c(a) {
2744
+ return a instanceof n ? a : new n(function(u) {
2745
+ u(a);
2746
+ });
2747
+ }
2748
+ return new (n || (n = Promise))(function(a, u) {
2749
+ function l(_) {
2750
+ try {
2751
+ p(o.next(_));
2752
+ } catch (d) {
2753
+ u(d);
2754
+ }
2755
+ }
2756
+ function g(_) {
2757
+ try {
2758
+ p(o.throw(_));
2759
+ } catch (d) {
2760
+ u(d);
2761
+ }
2762
+ }
2763
+ function p(_) {
2764
+ _.done ? a(_.value) : c(_.value).then(l, g);
2765
+ }
2766
+ p((o = o.apply(t, e || [])).next());
2767
+ });
2768
+ };
2769
+ const nr = 15e3, rr = 5e3, or = 2;
2770
+ class sr {
2771
+ constructor(e, n, o, c) {
2772
+ var a, u, l, g;
2773
+ this.peerConnection = null, this.connectionReceivedAnswer = !1, this.remoteIceCandidateBuffer = [], this.inputAudioStream = null, this.dataChannel = null, this.videoElement = null, this.videoStream = null, this.audioStream = null, this.inputAudioState = {
2774
+ isMuted: !1,
2775
+ permissionState: fe.NOT_REQUESTED
2776
+ }, this.successMetricPoller = null, this.successMetricFired = !1, this.showPeerConnectionStatsReport = !1, this.peerConnectionStatsReportOutputFormat = "console", this.statsCollectionInterval = null, this.agentAudioInputStream = null, this.publicEventEmitter = o, this.internalEventEmitter = c, this.apiGatewayConfig = n.apiGateway;
2777
+ const { inputAudio: p } = n;
2778
+ this.inputAudioState = p.inputAudioState, n.inputAudio.userProvidedMediaStream && (this.inputAudioStream = n.inputAudio.userProvidedMediaStream), this.disableInputAudio = n.inputAudio.disableInputAudio === !0, this.internalEventEmitter.addListener(J.WEB_SOCKET_OPEN, this.onSignallingClientConnected.bind(this)), this.internalEventEmitter.addListener(J.SIGNAL_MESSAGE_RECEIVED, this.onSignalMessage.bind(this)), this.iceServers = n.iceServers, this.signallingClient = new Yn(e, n.signalling, this.publicEventEmitter, this.internalEventEmitter, this.apiGatewayConfig), this.engineApiRestClient = new Zn(n.engine.baseUrl, e, this.apiGatewayConfig), this.audioDeviceId = n.inputAudio.audioDeviceId, this.showPeerConnectionStatsReport = (u = (a = n.metrics) === null || a === void 0 ? void 0 : a.showPeerConnectionStatsReport) !== null && u !== void 0 ? u : !1, this.peerConnectionStatsReportOutputFormat = (g = (l = n.metrics) === null || l === void 0 ? void 0 : l.peerConnectionStatsReportOutputFormat) !== null && g !== void 0 ? g : "console";
2779
+ }
2780
+ onInputAudioStateChange(e, n) {
2781
+ e.isMuted !== n.isMuted && (n.isMuted ? this.muteAllAudioTracks() : this.unmuteAllAudioTracks());
2782
+ }
2783
+ muteAllAudioTracks() {
2784
+ var e;
2785
+ (e = this.inputAudioStream) === null || e === void 0 || e.getAudioTracks().forEach((n) => {
2786
+ n.enabled = !1;
2787
+ });
2788
+ }
2789
+ unmuteAllAudioTracks() {
2790
+ var e;
2791
+ (e = this.inputAudioStream) === null || e === void 0 || e.getAudioTracks().forEach((n) => {
2792
+ n.enabled = !0;
2793
+ });
2794
+ }
2795
+ startStatsCollection() {
2796
+ this.statsCollectionInterval || (this.statsCollectionInterval = setInterval(() => K(this, void 0, void 0, function* () {
2797
+ if (!(!this.peerConnection || !this.dataChannel || this.dataChannel.readyState !== "open"))
2798
+ try {
2799
+ const e = yield this.peerConnection.getStats();
2800
+ this.sendClientSideMetrics(e);
2801
+ } catch (e) {
2802
+ console.error("Failed to collect and send stats:", e);
2803
+ }
2804
+ }), rr));
2805
+ }
2806
+ sendClientSideMetrics(e) {
2807
+ e.forEach((n) => {
2808
+ if (n.type === "inbound-rtp") {
2809
+ const o = {
2810
+ message_type: "remote_rtp_stats",
2811
+ data: n
2812
+ };
2813
+ this.dataChannel && this.dataChannel.readyState === "open" && this.dataChannel.send(JSON.stringify(o));
2814
+ }
2815
+ });
2816
+ }
2817
+ startSuccessMetricPolling() {
2818
+ if (this.successMetricPoller || this.successMetricFired)
2819
+ return;
2820
+ const e = setTimeout(() => {
2821
+ this.successMetricPoller && (console.warn("No video frames received, there is a problem with the connection."), clearInterval(this.successMetricPoller), this.successMetricPoller = null);
2822
+ }, nr);
2823
+ this.successMetricPoller = setInterval(() => K(this, void 0, void 0, function* () {
2824
+ if (!this.peerConnection || this.successMetricFired) {
2825
+ this.successMetricPoller && clearInterval(this.successMetricPoller), clearTimeout(e);
2826
+ return;
2827
+ }
2828
+ try {
2829
+ const n = yield this.peerConnection.getStats();
2830
+ let o = !1, c = null;
2831
+ n.forEach((a) => {
2832
+ a.type === "inbound-rtp" && a.kind === "video" && (a.framesDecoded !== void 0 && a.framesDecoded > 0 ? (o = !0, c = "framesDecoded") : a.framesReceived !== void 0 && a.framesReceived > 0 ? (o = !0, c = "framesReceived") : a.bytesReceived > 0 && a.packetsReceived > 0 && // Additional check: ensure we've received enough data for actual video
2833
+ a.bytesReceived > 1e5 && (o = !0, c = "bytesReceived"));
2834
+ }), o && !this.successMetricFired && (this.successMetricFired = !0, me(se.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS, "1", c ? { detectionMethod: c } : void 0), this.successMetricPoller && clearInterval(this.successMetricPoller), clearTimeout(e), this.successMetricPoller = null);
2835
+ } catch {
2836
+ }
2837
+ }), 500);
2838
+ }
2839
+ muteInputAudio() {
2840
+ const e = this.inputAudioState, n = Object.assign(Object.assign({}, this.inputAudioState), { isMuted: !0 });
2841
+ return this.inputAudioState = n, this.onInputAudioStateChange(e, n), this.inputAudioState;
2842
+ }
2843
+ unmuteInputAudio() {
2844
+ const e = this.inputAudioState, n = Object.assign(Object.assign({}, this.inputAudioState), { isMuted: !1 });
2845
+ return this.inputAudioState = n, this.onInputAudioStateChange(e, n), this.inputAudioState;
2846
+ }
2847
+ getInputAudioState() {
2848
+ return this.inputAudioState;
2849
+ }
2850
+ getPeerConnection() {
2851
+ return this.peerConnection;
2852
+ }
2853
+ changeAudioInputDevice(e) {
2854
+ return K(this, void 0, void 0, function* () {
2855
+ if (!this.peerConnection)
2856
+ throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");
2857
+ if (e == null)
2858
+ throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");
2859
+ const n = this.inputAudioState.isMuted;
2860
+ try {
2861
+ this.inputAudioStream && this.inputAudioStream.getAudioTracks().forEach((c) => {
2862
+ c.stop();
2863
+ });
2864
+ const o = {
2865
+ echoCancellation: !0,
2866
+ deviceId: {
2867
+ exact: e
2868
+ }
2869
+ };
2870
+ this.inputAudioStream = yield navigator.mediaDevices.getUserMedia({
2871
+ audio: o
2872
+ }), this.audioDeviceId = e, yield this.setupAudioTrack(), n && this.muteAllAudioTracks(), this.publicEventEmitter.emit(R.INPUT_AUDIO_DEVICE_CHANGED, e);
2873
+ } catch (o) {
2874
+ throw console.error("Failed to change audio input device:", o), new Error(`StreamingClient - changeAudioInputDevice: ${o instanceof Error ? o.message : String(o)}`);
2875
+ }
2876
+ });
2877
+ }
2878
+ getInputAudioStream() {
2879
+ return this.inputAudioStream;
2880
+ }
2881
+ getVideoStream() {
2882
+ return this.videoStream;
2883
+ }
2884
+ getAudioStream() {
2885
+ return this.audioStream;
2886
+ }
2887
+ sendDataMessage(e) {
2888
+ this.dataChannel && this.dataChannel.readyState === "open" && this.dataChannel.send(e);
2889
+ }
2890
+ setMediaStreamTargetById(e) {
2891
+ if (e) {
2892
+ const n = document.getElementById(e);
2893
+ if (!n)
2894
+ throw new Error(`StreamingClient: video element with id ${e} not found`);
2895
+ this.videoElement = n;
2896
+ }
2897
+ }
2898
+ startConnection() {
2899
+ try {
2900
+ if (this.peerConnection) {
2901
+ console.error("StreamingClient - startConnection: peer connection already exists");
2902
+ return;
2903
+ }
2904
+ this.signallingClient.connect();
2905
+ } catch (e) {
2906
+ console.error("StreamingClient - startConnection: error", e), this.handleWebrtcFailure(e);
2907
+ }
2908
+ }
2909
+ stopConnection() {
2910
+ return K(this, void 0, void 0, function* () {
2911
+ yield this.shutdown();
2912
+ });
2913
+ }
2914
+ sendTalkCommand(e) {
2915
+ return K(this, void 0, void 0, function* () {
2916
+ if (!this.peerConnection)
2917
+ throw new Error("StreamingClient - sendTalkCommand: peer connection is null");
2918
+ yield this.engineApiRestClient.sendTalkCommand(e);
2919
+ });
2920
+ }
2921
+ startTalkMessageStream(e) {
2922
+ return e || (e = Math.random().toString(36).substring(2, 15)), new ir(e, this.internalEventEmitter, this.signallingClient);
2923
+ }
2924
+ createAgentAudioInputStream(e) {
2925
+ return this.agentAudioInputStream = new Wn(e, this.signallingClient), this.agentAudioInputStream;
2926
+ }
2927
+ getAgentAudioInputStream() {
2928
+ return this.agentAudioInputStream;
2929
+ }
2930
+ initPeerConnection() {
2931
+ return K(this, void 0, void 0, function* () {
2932
+ this.peerConnection = new RTCPeerConnection({
2933
+ iceServers: this.iceServers,
2934
+ iceCandidatePoolSize: or
2935
+ }), this.peerConnection.onicecandidate = this.onIceCandidate.bind(this), this.peerConnection.oniceconnectionstatechange = this.onIceConnectionStateChange.bind(this), this.peerConnection.onconnectionstatechange = this.onConnectionStateChange.bind(this), this.peerConnection.addEventListener("track", this.onTrackEventHandler.bind(this)), yield this.setupDataChannels(), this.peerConnection.addTransceiver("video", { direction: "recvonly" }), this.disableInputAudio ? this.peerConnection.addTransceiver("audio", { direction: "recvonly" }) : (this.peerConnection.addTransceiver("audio", { direction: "sendrecv" }), this.inputAudioStream ? yield this.setupAudioTrack() : this.requestMicrophonePermissionAsync().catch((e) => {
2936
+ console.error("Async microphone permission request failed:", e);
2937
+ }));
2938
+ });
2939
+ }
2940
+ onSignalMessage(e) {
2941
+ return K(this, void 0, void 0, function* () {
2942
+ if (!this.peerConnection) {
2943
+ console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");
2944
+ return;
2945
+ }
2946
+ switch (e.actionType) {
2947
+ case W.ANSWER:
2948
+ const n = e.payload;
2949
+ yield this.peerConnection.setRemoteDescription(n), this.connectionReceivedAnswer = !0, this.flushRemoteIceCandidateBuffer();
2950
+ break;
2951
+ case W.ICE_CANDIDATE:
2952
+ const o = e.payload, c = new RTCIceCandidate(o);
2953
+ this.connectionReceivedAnswer ? yield this.peerConnection.addIceCandidate(c) : this.remoteIceCandidateBuffer.push(c);
2954
+ break;
2955
+ case W.END_SESSION:
2956
+ const a = e.payload;
2957
+ this.publicEventEmitter.emit(R.CONNECTION_CLOSED, _e.SERVER_CLOSED_CONNECTION, a), this.shutdown();
2958
+ break;
2959
+ case W.WARNING:
2960
+ const u = e.payload;
2961
+ console.warn("Warning received from server: " + u), this.publicEventEmitter.emit(R.SERVER_WARNING, u);
2962
+ break;
2963
+ case W.TALK_STREAM_INTERRUPTED:
2964
+ const l = e.payload;
2965
+ this.publicEventEmitter.emit(R.TALK_STREAM_INTERRUPTED, l.correlationId);
2966
+ break;
2967
+ case W.SESSION_READY:
2968
+ const g = e.sessionId;
2969
+ this.publicEventEmitter.emit(R.SESSION_READY, g);
2970
+ break;
2971
+ case W.HEARTBEAT:
2972
+ break;
2973
+ default:
2974
+ console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?", e);
2975
+ }
2976
+ });
2977
+ }
2978
+ onSignallingClientConnected() {
2979
+ return K(this, void 0, void 0, function* () {
2980
+ if (!this.peerConnection)
2981
+ try {
2982
+ yield this.initPeerConnectionAndSendOffer();
2983
+ } catch (e) {
2984
+ console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection", e), this.handleWebrtcFailure(e);
2985
+ }
2986
+ });
2987
+ }
2988
+ flushRemoteIceCandidateBuffer() {
2989
+ this.remoteIceCandidateBuffer.forEach((e) => {
2990
+ var n;
2991
+ (n = this.peerConnection) === null || n === void 0 || n.addIceCandidate(e);
2992
+ }), this.remoteIceCandidateBuffer = [];
2993
+ }
2994
+ /**
2995
+ * ICE Candidate Trickle
2996
+ * As each ICE candidate is gathered from the STUN server it is sent to the
2997
+ * webRTC server immediately in an effort to reduce time to connection.
2998
+ */
2999
+ onIceCandidate(e) {
3000
+ e.candidate && this.signallingClient.sendIceCandidate(e.candidate);
3001
+ }
3002
+ onIceConnectionStateChange() {
3003
+ var e, n;
3004
+ (((e = this.peerConnection) === null || e === void 0 ? void 0 : e.iceConnectionState) === "connected" || ((n = this.peerConnection) === null || n === void 0 ? void 0 : n.iceConnectionState) === "completed") && (this.publicEventEmitter.emit(R.CONNECTION_ESTABLISHED), this.startStatsCollection());
3005
+ }
3006
+ onConnectionStateChange() {
3007
+ var e;
3008
+ ((e = this.peerConnection) === null || e === void 0 ? void 0 : e.connectionState) === "closed" && (console.error("StreamingClient - onConnectionStateChange: Connection closed"), this.handleWebrtcFailure("The connection to our servers was lost. Please try again."));
3009
+ }
3010
+ handleWebrtcFailure(e) {
3011
+ console.error({ message: "StreamingClient - handleWebrtcFailure: ", err: e }), e.name === "NotAllowedError" && e.message === "Permission denied" ? this.publicEventEmitter.emit(R.CONNECTION_CLOSED, _e.MICROPHONE_PERMISSION_DENIED) : this.publicEventEmitter.emit(R.CONNECTION_CLOSED, _e.WEBRTC_FAILURE);
3012
+ try {
3013
+ this.stopConnection();
3014
+ } catch (n) {
3015
+ console.error("StreamingClient - handleWebrtcFailure: error stopping connection", n);
3016
+ }
3017
+ }
3018
+ onTrackEventHandler(e) {
3019
+ if (e.track.kind === "video") {
3020
+ if (this.startSuccessMetricPolling(), this.videoStream = e.streams[0], this.publicEventEmitter.emit(R.VIDEO_STREAM_STARTED, this.videoStream), this.videoElement) {
3021
+ this.videoElement.srcObject = this.videoStream;
3022
+ const n = this.videoElement.requestVideoFrameCallback(() => {
3023
+ var o;
3024
+ (o = this.videoElement) === null || o === void 0 || o.cancelVideoFrameCallback(n), this.publicEventEmitter.emit(R.VIDEO_PLAY_STARTED), this.successMetricFired || (this.successMetricFired = !0, me(se.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS, "1", { detectionMethod: "videoElement" }));
3025
+ });
3026
+ }
3027
+ } else e.track.kind === "audio" && (this.audioStream = e.streams[0], this.publicEventEmitter.emit(R.AUDIO_STREAM_STARTED, this.audioStream));
3028
+ }
3029
+ /**
3030
+ * Set up the data channels for sending and receiving messages
3031
+ */
3032
+ setupDataChannels() {
3033
+ return K(this, void 0, void 0, function* () {
3034
+ if (!this.peerConnection) {
3035
+ console.error("StreamingClient - setupDataChannels: peer connection is not initialized");
3036
+ return;
3037
+ }
3038
+ if (!this.disableInputAudio && this.inputAudioStream && !this.inputAudioStream.getAudioTracks().length)
3039
+ throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");
3040
+ const e = this.peerConnection.createDataChannel("session", {
3041
+ ordered: !0
3042
+ });
3043
+ e.onopen = () => {
3044
+ this.dataChannel = e ?? null;
3045
+ }, e.onclose = () => {
3046
+ }, e.onmessage = (n) => {
3047
+ try {
3048
+ const o = JSON.parse(n.data);
3049
+ switch (o.messageType) {
3050
+ case De.SPEECH_TEXT:
3051
+ this.internalEventEmitter.emit(J.WEBRTC_CHAT_MESSAGE_RECEIVED, o.data);
3052
+ break;
3053
+ case De.CLIENT_TOOL_EVENT:
3054
+ const c = o.data;
3055
+ this.internalEventEmitter.emit(J.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED, c);
3056
+ const a = ar.WebRTCClientToolEventToClientToolEvent(c);
3057
+ this.publicEventEmitter.emit(R.CLIENT_TOOL_EVENT_RECEIVED, a);
3058
+ break;
3059
+ case De.REASONING_TEXT:
3060
+ this.internalEventEmitter.emit(J.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED, o.data);
3061
+ break;
3062
+ // Unknown message types are silently ignored to maintain forward compatibility
3063
+ default:
3064
+ break;
3065
+ }
3066
+ } catch (o) {
3067
+ console.error("Failed to parse data channel message:", o);
3068
+ }
3069
+ };
3070
+ });
3071
+ }
3072
+ /**
3073
+ * Request microphone permission asynchronously without blocking connection
3074
+ */
3075
+ requestMicrophonePermissionAsync() {
3076
+ return K(this, void 0, void 0, function* () {
3077
+ if (this.inputAudioState.permissionState !== fe.PENDING) {
3078
+ this.inputAudioState = Object.assign(Object.assign({}, this.inputAudioState), { permissionState: fe.PENDING }), this.publicEventEmitter.emit(R.MIC_PERMISSION_PENDING);
3079
+ try {
3080
+ const e = {
3081
+ echoCancellation: !0
3082
+ };
3083
+ this.audioDeviceId && (e.deviceId = {
3084
+ exact: this.audioDeviceId
3085
+ }), this.inputAudioStream = yield navigator.mediaDevices.getUserMedia({
3086
+ audio: e
3087
+ }), this.inputAudioState = Object.assign(Object.assign({}, this.inputAudioState), { permissionState: fe.GRANTED }), this.publicEventEmitter.emit(R.MIC_PERMISSION_GRANTED), yield this.setupAudioTrack();
3088
+ } catch (e) {
3089
+ console.error("Failed to get microphone permission:", e), this.inputAudioState = Object.assign(Object.assign({}, this.inputAudioState), { permissionState: fe.DENIED });
3090
+ const n = e instanceof Error ? e.message : String(e);
3091
+ this.publicEventEmitter.emit(R.MIC_PERMISSION_DENIED, n);
3092
+ }
3093
+ }
3094
+ });
3095
+ }
3096
+ /**
3097
+ * Set up audio track and add it to the peer connection using replaceTrack
3098
+ */
3099
+ setupAudioTrack() {
3100
+ return K(this, void 0, void 0, function* () {
3101
+ if (!this.peerConnection || !this.inputAudioStream)
3102
+ return;
3103
+ if (!this.inputAudioStream.getAudioTracks().length) {
3104
+ console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");
3105
+ return;
3106
+ }
3107
+ this.inputAudioState.isMuted && this.muteAllAudioTracks();
3108
+ const e = this.inputAudioStream.getAudioTracks()[0], o = this.peerConnection.getSenders().find((c) => {
3109
+ var a;
3110
+ return ((a = c.track) === null || a === void 0 ? void 0 : a.kind) === "audio" || c.track === null && c.dtmf !== null;
3111
+ });
3112
+ if (o)
3113
+ try {
3114
+ yield o.replaceTrack(e);
3115
+ } catch (c) {
3116
+ console.error("Failed to replace audio track:", c), this.peerConnection.addTrack(e, this.inputAudioStream);
3117
+ }
3118
+ else
3119
+ this.peerConnection.addTrack(e, this.inputAudioStream);
3120
+ this.publicEventEmitter.emit(R.INPUT_AUDIO_STREAM_STARTED, this.inputAudioStream);
3121
+ });
3122
+ }
3123
+ initPeerConnectionAndSendOffer() {
3124
+ return K(this, void 0, void 0, function* () {
3125
+ if (yield this.initPeerConnection(), !this.peerConnection) {
3126
+ console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");
3127
+ return;
3128
+ }
3129
+ try {
3130
+ const e = yield this.peerConnection.createOffer();
3131
+ yield this.peerConnection.setLocalDescription(e);
3132
+ } catch (e) {
3133
+ console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer", e);
3134
+ }
3135
+ if (!this.peerConnection.localDescription)
3136
+ throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");
3137
+ yield this.signallingClient.sendOffer(this.peerConnection.localDescription);
3138
+ });
3139
+ }
3140
+ shutdown() {
3141
+ return K(this, void 0, void 0, function* () {
3142
+ var e;
3143
+ if (this.showPeerConnectionStatsReport) {
3144
+ const n = yield (e = this.peerConnection) === null || e === void 0 ? void 0 : e.getStats();
3145
+ if (n) {
3146
+ const o = jn(n, this.peerConnectionStatsReportOutputFormat);
3147
+ o && console.log(o, void 0, 2);
3148
+ }
3149
+ }
3150
+ this.statsCollectionInterval && (clearInterval(this.statsCollectionInterval), this.statsCollectionInterval = null), this.successMetricPoller && (clearInterval(this.successMetricPoller), this.successMetricPoller = null), this.successMetricFired = !1;
3151
+ try {
3152
+ this.inputAudioStream && this.inputAudioStream.getTracks().forEach((n) => {
3153
+ n.stop();
3154
+ }), this.inputAudioStream = null;
3155
+ } catch (n) {
3156
+ console.error("StreamingClient - shutdown: error stopping input audio stream", n);
3157
+ }
3158
+ try {
3159
+ this.signallingClient.stop();
3160
+ } catch (n) {
3161
+ console.error("StreamingClient - shutdown: error stopping signallilng", n);
3162
+ }
3163
+ try {
3164
+ this.peerConnection && this.peerConnection.connectionState !== "closed" && (this.peerConnection.onconnectionstatechange = null, this.peerConnection.close(), this.peerConnection = null);
3165
+ } catch (n) {
3166
+ console.error("StreamingClient - shutdown: error closing peer connection", n);
3167
+ }
3168
+ });
3169
+ }
3170
+ }
3171
+ class ar {
3172
+ /**
3173
+ * Converts a WebRtcClientToolEvent to a ClientToolEvent
3174
+ */
3175
+ static WebRTCClientToolEventToClientToolEvent(e) {
3176
+ return {
3177
+ eventUid: e.event_uid,
3178
+ sessionId: e.session_id,
3179
+ eventName: e.event_name,
3180
+ eventData: e.event_data,
3181
+ timestamp: e.timestamp,
3182
+ timestampUserAction: e.timestamp_user_action,
3183
+ userActionCorrelationId: e.user_action_correlation_id
3184
+ };
3185
+ }
3186
+ }
3187
+ class lr {
3188
+ constructor(e, n) {
3189
+ this.reasoning_messages = [], this.publicEventEmitter = e, this.internalEventEmitter = n, this.internalEventEmitter.addListener(J.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED, this.processWebRtcReasoningTextMessageEvent.bind(this));
3190
+ }
3191
+ webRtcTextMessageEventToReasoningStreamEvent(e) {
3192
+ return {
3193
+ id: `${e.role}::${e.message_id}`,
3194
+ content: e.content,
3195
+ endOfThought: e.end_of_thought,
3196
+ role: e.role
3197
+ };
3198
+ }
3199
+ processWebRtcReasoningTextMessageEvent(e) {
3200
+ const n = this.webRtcTextMessageEventToReasoningStreamEvent(e);
3201
+ this.publicEventEmitter.emit(R.REASONING_STREAM_EVENT_RECEIVED, n);
3202
+ const o = {
3203
+ id: n.id,
3204
+ content: n.content,
3205
+ role: n.role
3206
+ }, c = this.reasoning_messages.findIndex((a) => a.id === o.id);
3207
+ if (c !== -1) {
3208
+ const a = this.reasoning_messages[c];
3209
+ a.content += o.content, this.reasoning_messages[c] = a;
3210
+ } else
3211
+ this.reasoning_messages.push(o);
3212
+ n.endOfThought && this.publicEventEmitter.emit(R.REASONING_HISTORY_UPDATED, this.reasoning_messages);
3213
+ }
3214
+ }
3215
+ var ue = function(t, e, n, o) {
3216
+ function c(a) {
3217
+ return a instanceof n ? a : new n(function(u) {
3218
+ u(a);
3219
+ });
3220
+ }
3221
+ return new (n || (n = Promise))(function(a, u) {
3222
+ function l(_) {
3223
+ try {
3224
+ p(o.next(_));
3225
+ } catch (d) {
3226
+ u(d);
3227
+ }
3228
+ }
3229
+ function g(_) {
3230
+ try {
3231
+ p(o.throw(_));
3232
+ } catch (d) {
3233
+ u(d);
3234
+ }
3235
+ }
3236
+ function p(_) {
3237
+ _.done ? a(_.value) : c(_.value).then(l, g);
3238
+ }
3239
+ p((o = o.apply(t, e || [])).next());
3240
+ });
3241
+ };
3242
+ class cr {
3243
+ constructor(e, n, o) {
3244
+ var c, a, u, l, g;
3245
+ this.inputAudioState = {
3246
+ isMuted: !1,
3247
+ permissionState: fe.NOT_REQUESTED
3248
+ }, this.sessionId = null, this.organizationId = null, this.streamingClient = null, this._isStreaming = !1;
3249
+ const p = this.validateClientConfig(e, n, o);
3250
+ if (p)
3251
+ throw new $(p, V.CLIENT_ERROR_CODE_CONFIGURATION_ERROR, 400);
3252
+ this.personaConfig = n, this.clientOptions = o, (!((c = o?.api) === null || c === void 0) && c.baseUrl || !((a = o?.api) === null || a === void 0) && a.apiVersion) && $n(o.api.baseUrl || Hi, o.api.apiVersion || kt), !((l = (u = o?.api) === null || u === void 0 ? void 0 : u.apiGateway) === null || l === void 0) && l.enabled && Gn(o.api.apiGateway), !((g = o?.metrics) === null || g === void 0) && g.disableClientMetrics && Vn(!0), this.publicEventEmitter = new tr(), this.internalEventEmitter = new Qn(), this.apiClient = new Jn(e, o?.apiKey, o?.api), this.messageHistoryClient = new er(this.publicEventEmitter, this.internalEventEmitter), this.reasoningHistoryClient = new lr(this.publicEventEmitter, this.internalEventEmitter);
3253
+ }
3254
+ decodeJwt(e) {
3255
+ try {
3256
+ const n = e.split(".")[1], o = Bn.Buffer.from(n, "base64").toString("utf8");
3257
+ return JSON.parse(o);
3258
+ } catch {
3259
+ throw new Error("Invalid session token format");
3260
+ }
3261
+ }
3262
+ validateClientConfig(e, n, o) {
3263
+ var c, a;
3264
+ if (!e && !o?.apiKey)
3265
+ return "Either sessionToken or apiKey must be provided";
3266
+ if (o?.apiKey && e)
3267
+ return "Only one of sessionToken or apiKey should be used";
3268
+ const u = Hn((c = o?.api) === null || c === void 0 ? void 0 : c.apiGateway);
3269
+ if (u)
3270
+ return u;
3271
+ if (e) {
3272
+ const l = this.decodeJwt(e);
3273
+ this.organizationId = l.accountId, Se({
3274
+ organizationId: this.organizationId
3275
+ });
3276
+ const g = (a = l.type) === null || a === void 0 ? void 0 : a.toLowerCase();
3277
+ if (g === "legacy")
3278
+ return "Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";
3279
+ if ((g === "ephemeral" || g === "stateful") && n)
3280
+ return "This session token already contains a persona configuration. Please remove the personaConfig parameter.";
3281
+ } else if (!n)
3282
+ return "Missing persona config. Persona configuration must be provided when using apiKey";
3283
+ if (o?.voiceDetection) {
3284
+ if (o.disableInputAudio)
3285
+ return "Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";
3286
+ if (o.voiceDetection.endOfSpeechSensitivity !== void 0) {
3287
+ if (typeof o.voiceDetection.endOfSpeechSensitivity != "number")
3288
+ return "End of speech sensitivity must be a number";
3289
+ if (o.voiceDetection.endOfSpeechSensitivity < 0 || o.voiceDetection.endOfSpeechSensitivity > 1)
3290
+ return "End of speech sensitivity must be between 0 and 1";
3291
+ }
3292
+ }
3293
+ }
3294
+ buildStartSessionOptionsForClient() {
3295
+ var e;
3296
+ const n = {};
3297
+ if (!((e = this.clientOptions) === null || e === void 0) && e.voiceDetection && (n.voiceDetection = this.clientOptions.voiceDetection), Object.keys(n).length !== 0)
3298
+ return n;
3299
+ }
3300
+ startSession(e) {
3301
+ return ue(this, void 0, void 0, function* () {
3302
+ var n, o, c, a, u, l, g, p, _, d, S, m;
3303
+ const y = this.personaConfig, A = this.buildStartSessionOptionsForClient(), w = yield this.apiClient.startSession(y, A), { sessionId: I, clientConfig: b, engineHost: x, engineProtocol: M, signallingEndpoint: N } = w, { heartbeatIntervalSeconds: Z, maxWsReconnectionAttempts: H, iceServers: ae } = b;
3304
+ this.sessionId = I, Se({
3305
+ sessionId: this.sessionId
3306
+ });
3307
+ const ne = !((n = this.clientOptions) === null || n === void 0) && n.iceServers ? this.clientOptions.iceServers : ae;
3308
+ try {
3309
+ this.streamingClient = new sr(I, {
3310
+ engine: {
3311
+ baseUrl: `${M}://${x}`
3312
+ },
3313
+ signalling: {
3314
+ heartbeatIntervalSeconds: Z,
3315
+ maxWsReconnectionAttempts: H,
3316
+ url: {
3317
+ baseUrl: x,
3318
+ protocol: M,
3319
+ signallingPath: N
3320
+ }
3321
+ },
3322
+ iceServers: ne,
3323
+ inputAudio: {
3324
+ inputAudioState: this.inputAudioState,
3325
+ userProvidedMediaStream: !((o = this.clientOptions) === null || o === void 0) && o.disableInputAudio ? void 0 : e,
3326
+ audioDeviceId: (c = this.clientOptions) === null || c === void 0 ? void 0 : c.audioDeviceId,
3327
+ disableInputAudio: (a = this.clientOptions) === null || a === void 0 ? void 0 : a.disableInputAudio
3328
+ },
3329
+ apiGateway: (l = (u = this.clientOptions) === null || u === void 0 ? void 0 : u.api) === null || l === void 0 ? void 0 : l.apiGateway,
3330
+ metrics: {
3331
+ showPeerConnectionStatsReport: (_ = (p = (g = this.clientOptions) === null || g === void 0 ? void 0 : g.metrics) === null || p === void 0 ? void 0 : p.showPeerConnectionStatsReport) !== null && _ !== void 0 ? _ : !1,
3332
+ peerConnectionStatsReportOutputFormat: (m = (S = (d = this.clientOptions) === null || d === void 0 ? void 0 : d.metrics) === null || S === void 0 ? void 0 : S.peerConnectionStatsReportOutputFormat) !== null && m !== void 0 ? m : "console"
3333
+ }
3334
+ }, this.publicEventEmitter, this.internalEventEmitter);
3335
+ } catch (re) {
3336
+ throw Se({
3337
+ sessionId: null
3338
+ }), new $("Failed to initialize streaming client", V.CLIENT_ERROR_CODE_SERVER_ERROR, 500, {
3339
+ cause: re instanceof Error ? re.message : String(re),
3340
+ sessionId: I
3341
+ });
3342
+ }
3343
+ return I;
3344
+ });
3345
+ }
3346
+ startSessionIfNeeded(e) {
3347
+ return ue(this, void 0, void 0, function* () {
3348
+ if ((!this.sessionId || !this.streamingClient) && (yield this.startSession(e), !this.sessionId || !this.streamingClient))
3349
+ throw new $("Session ID or streaming client is not available after starting session", V.CLIENT_ERROR_CODE_SERVER_ERROR, 500, {
3350
+ cause: "Failed to initialize session properly"
3351
+ });
3352
+ });
3353
+ }
3354
+ stream(e) {
3355
+ return ue(this, void 0, void 0, function* () {
3356
+ var n;
3357
+ if (this._isStreaming)
3358
+ throw new Error("Already streaming");
3359
+ const o = ai();
3360
+ return Se({
3361
+ attemptCorrelationId: o,
3362
+ sessionId: null
3363
+ // reset sessionId
3364
+ }), me(se.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT, "1"), !((n = this.clientOptions) === null || n === void 0) && n.disableInputAudio && e && console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."), yield this.startSessionIfNeeded(e), this._isStreaming = !0, new Promise((c) => {
3365
+ var a;
3366
+ const u = [];
3367
+ let l = !1, g = !1;
3368
+ this.publicEventEmitter.addListener(R.VIDEO_STREAM_STARTED, (p) => {
3369
+ u.push(p), l = !0, g && c(u);
3370
+ }), this.publicEventEmitter.addListener(R.AUDIO_STREAM_STARTED, (p) => {
3371
+ u.push(p), g = !0, l && c(u);
3372
+ }), (a = this.streamingClient) === null || a === void 0 || a.startConnection();
3373
+ });
3374
+ });
3375
+ }
3376
+ /**
3377
+ * @deprecated This method is deprecated. Please use streamToVideoElement instead.
3378
+ */
3379
+ streamToVideoAndAudioElements(e, n, o) {
3380
+ return ue(this, void 0, void 0, function* () {
3381
+ console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."), yield this.streamToVideoElement(e, o);
3382
+ });
3383
+ }
3384
+ streamToVideoElement(e, n) {
3385
+ return ue(this, void 0, void 0, function* () {
3386
+ var o;
3387
+ const c = ai();
3388
+ Se({
3389
+ attemptCorrelationId: c,
3390
+ sessionId: null
3391
+ // reset sessionId
3392
+ }), me(se.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT, "1"), !((o = this.clientOptions) === null || o === void 0) && o.disableInputAudio && n && console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");
3393
+ try {
3394
+ yield this.startSessionIfNeeded(n);
3395
+ } catch (a) {
3396
+ throw a instanceof $ ? a : new $("Failed to start session", V.CLIENT_ERROR_CODE_SERVER_ERROR, 500, {
3397
+ cause: a instanceof Error ? a.message : String(a),
3398
+ sessionId: this.sessionId
3399
+ });
3400
+ }
3401
+ if (this._isStreaming)
3402
+ throw new Error("Already streaming");
3403
+ if (this._isStreaming = !0, !this.streamingClient)
3404
+ throw new Error("Failed to stream: streaming client is not available");
3405
+ this.streamingClient.setMediaStreamTargetById(e), this.streamingClient.startConnection();
3406
+ });
3407
+ }
3408
+ /**
3409
+ * Send a talk command to make the persona speak the provided content.
3410
+ * @param content - The text content for the persona to speak
3411
+ * @throws Error if session is not started or not currently streaming
3412
+ */
3413
+ talk(e) {
3414
+ return ue(this, void 0, void 0, function* () {
3415
+ if (!this.streamingClient)
3416
+ throw new Error("Failed to send talk command: session is not started. Have you called startSession?");
3417
+ if (!this._isStreaming)
3418
+ throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");
3419
+ yield this.streamingClient.sendTalkCommand(e);
3420
+ });
3421
+ }
3422
+ /**
3423
+ * Send a raw data message through the WebRTC data channel.
3424
+ * @param message - The message string to send through the data channel
3425
+ * @throws Error if session is not started
3426
+ */
3427
+ sendDataMessage(e) {
3428
+ if (this.streamingClient)
3429
+ this.streamingClient.sendDataMessage(e);
3430
+ else
3431
+ throw new Error("Failed to send message: session is not started.");
3432
+ }
3433
+ /**
3434
+ * Send a user text message in the active streaming session.
3435
+ * @param content - The text message content to send
3436
+ * @throws Error if not currently streaming or session is not started
3437
+ */
3438
+ sendUserMessage(e) {
3439
+ if (!this._isStreaming)
3440
+ throw console.warn("AnamClient: Not currently streaming. User message will not be sent."), new Error("Failed to send user message: not currently streaming");
3441
+ const n = this.getActiveSessionId();
3442
+ if (!n)
3443
+ throw new Error("Failed to send user message: no active session");
3444
+ const o = (/* @__PURE__ */ new Date()).toISOString().replace("Z", ""), c = JSON.stringify({
3445
+ content: e,
3446
+ timestamp: o,
3447
+ session_id: n,
3448
+ message_type: "speech"
3449
+ });
3450
+ this.sendDataMessage(c);
3451
+ }
3452
+ interruptPersona() {
3453
+ if (!this._isStreaming)
3454
+ throw new Error("Failed to send interrupt command: not currently streaming");
3455
+ const e = this.getActiveSessionId();
3456
+ if (!e)
3457
+ throw new Error("Failed to send interrupt command: no active session");
3458
+ const n = JSON.stringify({
3459
+ message_type: "interrupt",
3460
+ session_id: e,
3461
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
3462
+ // removing Z not needed
3463
+ });
3464
+ this.sendDataMessage(n);
3465
+ }
3466
+ stopStreaming() {
3467
+ return ue(this, void 0, void 0, function* () {
3468
+ this.streamingClient && (this.publicEventEmitter.emit(R.CONNECTION_CLOSED, _e.NORMAL), yield this.streamingClient.stopConnection(), this.streamingClient = null, this.sessionId = null, Se({
3469
+ attemptCorrelationId: null,
3470
+ sessionId: null,
3471
+ organizationId: this.organizationId
3472
+ }), this._isStreaming = !1);
3473
+ });
3474
+ }
3475
+ isStreaming() {
3476
+ return this._isStreaming;
3477
+ }
3478
+ setPersonaConfig(e) {
3479
+ this.personaConfig = e;
3480
+ }
3481
+ getPersonaConfig() {
3482
+ return this.personaConfig;
3483
+ }
3484
+ getInputAudioState() {
3485
+ var e;
3486
+ return !((e = this.clientOptions) === null || e === void 0) && e.disableInputAudio && console.warn("AnamClient: Audio state will not be used because input audio is disabled."), this.streamingClient && (this.inputAudioState = this.streamingClient.getInputAudioState()), this.inputAudioState;
3487
+ }
3488
+ muteInputAudio() {
3489
+ var e, n;
3490
+ return !((e = this.clientOptions) === null || e === void 0) && e.disableInputAudio && console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."), this.streamingClient && !(!((n = this.clientOptions) === null || n === void 0) && n.disableInputAudio) ? this.inputAudioState = this.streamingClient.muteInputAudio() : this.inputAudioState = Object.assign(Object.assign({}, this.inputAudioState), { isMuted: !0 }), this.inputAudioState;
3491
+ }
3492
+ unmuteInputAudio() {
3493
+ var e, n;
3494
+ return !((e = this.clientOptions) === null || e === void 0) && e.disableInputAudio && console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."), this.streamingClient && !(!((n = this.clientOptions) === null || n === void 0) && n.disableInputAudio) ? this.inputAudioState = this.streamingClient.unmuteInputAudio() : this.inputAudioState = Object.assign(Object.assign({}, this.inputAudioState), { isMuted: !1 }), this.inputAudioState;
3495
+ }
3496
+ changeAudioInputDevice(e) {
3497
+ return ue(this, void 0, void 0, function* () {
3498
+ var n;
3499
+ if (!((n = this.clientOptions) === null || n === void 0) && n.disableInputAudio)
3500
+ throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");
3501
+ if (!this._isStreaming)
3502
+ throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");
3503
+ if (!this.streamingClient)
3504
+ throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");
3505
+ yield this.streamingClient.changeAudioInputDevice(e);
3506
+ });
3507
+ }
3508
+ createTalkMessageStream(e) {
3509
+ if (!this.streamingClient)
3510
+ throw new Error("Failed to start talk message stream: session is not started.");
3511
+ if (e && e.trim() === "")
3512
+ throw new Error("Failed to start talk message stream: correlationId is empty");
3513
+ return this.streamingClient.startTalkMessageStream(e);
3514
+ }
3515
+ createAgentAudioInputStream(e) {
3516
+ if (!this.streamingClient)
3517
+ throw new Error("Failed to create agent audio input stream: session is not started.");
3518
+ return this.streamingClient.createAgentAudioInputStream(e);
3519
+ }
3520
+ /**
3521
+ * Event handling
3522
+ */
3523
+ addListener(e, n) {
3524
+ this.publicEventEmitter.addListener(e, n);
3525
+ }
3526
+ removeListener(e, n) {
3527
+ this.publicEventEmitter.removeListener(e, n);
3528
+ }
3529
+ getActiveSessionId() {
3530
+ return this.sessionId;
3531
+ }
3532
+ }
3533
+ const ur = (t, e) => new cr(t, void 0, e), dr = "https://api.anam.ai", X = Y(null), te = Y("idle"), Le = Y(!1), Je = Y(!1), lt = Y([]), Pe = Y(null), nt = Y(null), ct = Y(null), ut = Y(null), Dt = Y(null), ci = Y(!1), rt = Y(!1);
3534
+ function hr(t, e) {
3535
+ return e === 401 || e === 403 ? "This agent is not authorized. Check your agent ID." : e === 404 ? "Agent not found. Check your agent ID." : e === 429 ? "Too many requests. Please wait a moment." : e && e >= 500 ? "Server error. Please try again later." : t instanceof TypeError && t.message === "Failed to fetch" ? "Unable to connect. Check your network connection." : t instanceof Error && t.message.length < 80 ? t.message : "Something went wrong. Please try again.";
3536
+ }
3537
+ async function fr(t, e) {
3538
+ rt.value = !1;
3539
+ try {
3540
+ const n = await fetch(`${e}/v1/personas/${t}/widget`);
3541
+ if (!n.ok) return;
3542
+ const o = await n.json();
3543
+ ct.value = o.persona?.avatarImageUrl || null, ut.value = o.persona?.name || null, Dt.value = o.widgetConfig || null;
3544
+ } catch {
3545
+ } finally {
3546
+ rt.value = !0;
3547
+ }
3548
+ }
3549
+ async function pr(t, e, n) {
3550
+ if (te.value === "connecting" || te.value === "connected")
3551
+ return;
3552
+ te.value = "connecting", Pe.value = null;
3553
+ let o;
3554
+ try {
3555
+ console.log("[AnamWidget] Fetching session for agent:", t);
3556
+ const c = await fetch(`${e}/v1/auth/widget`, {
3557
+ method: "POST",
3558
+ headers: { "Content-Type": "application/json" },
3559
+ body: JSON.stringify({ agentId: t })
3560
+ });
3561
+ if (o = c.status, !c.ok) {
3562
+ const g = await c.json().catch(() => ({}));
3563
+ throw new Error(g.error || `HTTP ${c.status}`);
3564
+ }
3565
+ const a = await c.json();
3566
+ console.log("[AnamWidget] Got session from agent-id:", {
3567
+ persona: a.persona?.name,
3568
+ hasToken: !!a.sessionToken
3569
+ }), ct.value = a.persona?.avatarImageUrl || null, ut.value = a.persona?.name || null;
3570
+ const u = ur(a.sessionToken, {
3571
+ api: e ? { baseUrl: e } : void 0,
3572
+ metrics: { disableClientMetrics: !0 }
3573
+ });
3574
+ u.addListener(R.CONNECTION_ESTABLISHED, () => {
3575
+ console.log("[AnamWidget] Connection established"), te.value = "connected";
3576
+ }), u.addListener(R.VIDEO_STREAM_STARTED, () => {
3577
+ console.log("[AnamWidget] Video stream started"), Le.value = !0;
3578
+ }), u.addListener(R.AUDIO_STREAM_STARTED, () => {
3579
+ console.log("[AnamWidget] Audio stream started");
3580
+ }), u.addListener(R.MESSAGE_HISTORY_UPDATED, (g) => {
3581
+ lt.value = [...g];
3582
+ }), u.addListener(R.CONNECTION_CLOSED, (g, p) => {
3583
+ console.log("[AnamWidget] Connection closed:", g, p), te.value = "idle", Le.value = !1, nt.value = null;
3584
+ }), u.addListener(R.SESSION_READY, (g) => {
3585
+ console.log("[AnamWidget] Session ready:", g), nt.value = g;
3586
+ }), X.value = u;
3587
+ const l = await u.stream();
3588
+ if (n && l.length > 0) {
3589
+ const g = l.find((p) => p.getVideoTracks().length > 0);
3590
+ g && (n.srcObject = g);
3591
+ }
3592
+ } catch (c) {
3593
+ console.error("[AnamWidget] Failed to start session:", c), Pe.value = hr(c, o), te.value = "error", X.value = null;
3594
+ }
3595
+ }
3596
+ async function _r() {
3597
+ if (X.value)
3598
+ try {
3599
+ await X.value.stopStreaming();
3600
+ } catch (t) {
3601
+ console.error("[AnamWidget] Failed to stop session:", t);
3602
+ }
3603
+ X.value = null, te.value = "idle", Le.value = !1, lt.value = [];
3604
+ }
3605
+ function Er(t) {
3606
+ !X.value || te.value !== "connected" || X.value.sendUserMessage(t);
3607
+ }
3608
+ function mr() {
3609
+ X.value && (Je.value ? (X.value.unmuteInputAudio(), Je.value = !1) : (X.value.muteInputAudio(), Je.value = !0));
3610
+ }
3611
+ function gr() {
3612
+ X.value?.isStreaming() && X.value.stopStreaming(), X.value = null, te.value = "idle", Le.value = !1, lt.value = [], Pe.value = null, nt.value = null, ct.value = null, ut.value = null, Dt.value = null;
3613
+ }
3614
+ function vr(t, e) {
3615
+ ci.value = !!t;
3616
+ const n = e || dr;
3617
+ return {
3618
+ connectionStatus: te,
3619
+ isStreaming: Le,
3620
+ isMuted: Je,
3621
+ messages: lt,
3622
+ error: Pe,
3623
+ sessionId: nt,
3624
+ hasAgentId: ci,
3625
+ isReady: rt,
3626
+ avatarThumbnailUrl: ct,
3627
+ personaName: ut,
3628
+ serverConfig: Dt,
3629
+ fetchWidgetConfig: () => {
3630
+ if (!t) {
3631
+ rt.value = !0;
3632
+ return;
3633
+ }
3634
+ fr(t, n);
3635
+ },
3636
+ startSession: (a) => t ? pr(t, n, a) : (Pe.value = "No agent ID configured", Promise.resolve()),
3637
+ stopSession: _r,
3638
+ sendMessage: Er,
3639
+ toggleMute: mr,
3640
+ cleanup: gr
3641
+ };
3642
+ }
3643
+ const ui = '@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-outline-style:solid}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.visible{visibility:visible}.fixed{position:fixed}.block{display:block}.flex{display:flex}.inline{display:inline}.flex-shrink{flex-shrink:1}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}}:host{--anam-background:#fff;--anam-text:#18181b;--anam-trigger-size:80px;--anam-sheet-width:400px;--anam-sheet-height:640px;all:initial;color:var(--anam-text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:DM Sans,system-ui,-apple-system,sans-serif;font-size:15px;line-height:1.5}@media(max-width:640px){:host{--anam-trigger-size:72px;--anam-sheet-width: calc(100vw - 24px) ;--anam-sheet-height: calc(100dvh - 100px) }}.anam-widget{z-index:9999;font-family:inherit}.anam-widget[data-layout=fixed]{position:fixed}.anam-widget[data-layout=inline]{position:relative}.anam-trigger{width:var(--anam-trigger-size);height:var(--anam-trigger-size);cursor:pointer;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;padding:0;transition:all .25s cubic-bezier(.4,0,.2,1);display:flex;overflow:hidden;box-shadow:0 2px 8px #00000014,0 8px 24px -4px #0000002e}.anam-trigger:hover{transform:scale(1.06);box-shadow:0 4px 12px #0000001a,0 12px 32px -4px #00000040}.anam-trigger:active{transform:scale(.97)}.anam-trigger img{object-fit:cover;width:100%;height:100%;display:block}.anam-sheet{width:var(--anam-sheet-width);aspect-ratio:16/10;max-height:var(--anam-sheet-height);border-radius:16px;animation:.25s cubic-bezier(.16,1,.3,1) sheetIn;position:relative;overflow:hidden;box-shadow:0 32px 64px -16px #00000040,0 0 0 1px #00000014}.anam-widget[data-mode=expanded][data-layout=inline] .anam-sheet{border-radius:16px;width:100%;max-height:none;animation:none}@keyframes sheetIn{0%{opacity:0;transform:translateY(8px)scale(.97)}to{opacity:1;transform:translateY(0)scale(1)}}.anam-video{object-fit:cover;background:#000;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-video[data-hidden=true]{visibility:hidden}.anam-overlay-idle{z-index:2;position:absolute;inset:0}.anam-overlay-idle img{object-fit:cover;width:100%;height:100%;display:block}.anam-cta-pill{-webkit-backdrop-filter:blur(16px);color:#fff;letter-spacing:-.01em;cursor:pointer;white-space:nowrap;background:#00000080;border:1px solid #ffffff1a;border-radius:999px;align-items:center;gap:10px;padding:12px 28px;font-family:inherit;font-size:15px;font-weight:500;transition:all .2s;display:flex;position:absolute;bottom:40px;left:50%;transform:translate(-50%)}.anam-cta-pill:hover{background:#000000a6;transform:translate(-50%)scale(1.03)}.anam-cta-pill:active{transform:translate(-50%)scale(.98)}.anam-cta-pill svg{flex-shrink:0}.anam-overlay-unconfigured{z-index:2;background:#111;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-unconfigured span{color:#ffffff59;letter-spacing:-.01em;font-size:14px;font-weight:400}.anam-overlay-loading{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:20px;display:flex;position:absolute;inset:0}.anam-overlay-loading span{color:#fffc;letter-spacing:-.01em;font-size:15px;font-weight:400}.anam-overlay-error{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-error-text{color:#fff9;text-align:center;max-width:260px;font-size:14px;line-height:1.5}.anam-overlay-error .anam-retry-btn{-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#ffffff1f;border:1px solid #ffffff1a;border-radius:999px;padding:10px 24px;font-family:inherit;font-size:14px;font-weight:500;transition:background .15s}.anam-overlay-error .anam-retry-btn:hover{background:#fff3}.anam-spinner{border:2.5px solid #ffffff1f;border-top-color:#fff;border-radius:50%;width:32px;height:32px;animation:.75s linear infinite spin}@keyframes spin{to{transform:rotate(360deg)}}.anam-close-btn{z-index:10;-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#00000073;border:1px solid #ffffff14;border-radius:50%;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:background .15s;display:flex;position:absolute;top:12px;right:12px}.anam-close-btn:hover{background:#0009}.anam-toast{z-index:10;-webkit-backdrop-filter:blur(16px);color:#fff;letter-spacing:-.01em;white-space:nowrap;text-overflow:ellipsis;pointer-events:none;background:#0009;border:1px solid #ffffff0f;border-radius:999px;max-width:85%;padding:10px 22px;font-size:14px;font-weight:400;animation:.25s cubic-bezier(.16,1,.3,1) toastIn;position:absolute;bottom:80px;left:50%;overflow:hidden;transform:translate(-50%)}.anam-toast-out{animation:.4s forwards toastOut}@keyframes toastIn{0%{opacity:0;transform:translate(-50%)translateY(6px)}to{opacity:1;transform:translate(-50%)translateY(0)}}@keyframes toastOut{0%{opacity:1}to{opacity:0}}.anam-control-bar{z-index:10;background:linear-gradient(#0000,#00000040 40%,#0000008c);align-items:center;gap:8px;padding:48px 16px 16px;display:flex;position:absolute;bottom:0;left:0;right:0}.anam-ctl-btn{-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#ffffff24;border:1px solid #ffffff0f;border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;width:44px;height:44px;padding:0;transition:background .15s;display:flex}.anam-ctl-btn:hover{background:#ffffff38}.anam-ctl-btn:disabled{opacity:.35;cursor:not-allowed}.anam-ctl-btn-muted{background:#dc26268c;border-color:#dc262633}.anam-ctl-btn-muted:hover{background:#dc2626b3}.anam-ctl-end{background:#dc262699;border-color:#dc262626}.anam-ctl-end:hover{background:#dc2626cc}.anam-ctl-input{-webkit-backdrop-filter:blur(8px);color:#fff;background:#ffffff1a;border:1px solid #ffffff14;border-radius:999px;outline:none;flex:1;min-width:0;padding:11px 18px;font-family:inherit;font-size:14px;transition:background .15s,border-color .15s}.anam-ctl-input::placeholder{color:#fff6}.anam-ctl-input:focus{background:#ffffff26;border-color:#ffffff2e}.anam-ctl-input:disabled{opacity:.35;cursor:not-allowed}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}';
3644
+ function qi(t, e) {
3645
+ const n = { ...t };
3646
+ for (const o of Object.keys(e)) {
3647
+ const c = e[o];
3648
+ c !== void 0 && (c !== null && typeof c == "object" && !Array.isArray(c) && typeof n[o] == "object" && n[o] !== null && !Array.isArray(n[o]) ? n[o] = qi(n[o], c) : n[o] = c);
3649
+ }
3650
+ return n;
3651
+ }
3652
+ const yr = () => /* @__PURE__ */ C("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2.5", "stroke-linecap": "round", children: /* @__PURE__ */ C("path", { d: "M18 6L6 18M6 6l12 12" }) }), Sr = () => /* @__PURE__ */ C("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "currentColor", children: /* @__PURE__ */ C("path", { d: "M8 5.14v13.72a1 1 0 0 0 1.5.86l11.04-6.86a1 1 0 0 0 0-1.72L9.5 4.28A1 1 0 0 0 8 5.14Z" }) }), wr = () => /* @__PURE__ */ C("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", children: [
3653
+ /* @__PURE__ */ C("path", { d: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" }),
3654
+ /* @__PURE__ */ C("path", { d: "M19 10v2a7 7 0 0 1-14 0v-2" }),
3655
+ /* @__PURE__ */ C("line", { x1: "12", y1: "19", x2: "12", y2: "22" })
3656
+ ] }), Cr = () => /* @__PURE__ */ C("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", children: [
3657
+ /* @__PURE__ */ C("line", { x1: "1", y1: "1", x2: "23", y2: "23" }),
3658
+ /* @__PURE__ */ C("path", { d: "M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6" }),
3659
+ /* @__PURE__ */ C("path", { d: "M17 16.95A7 7 0 0 1 5 12v-2m14 0v2c0 .87-.16 1.71-.46 2.49" }),
3660
+ /* @__PURE__ */ C("line", { x1: "12", y1: "19", x2: "12", y2: "22" })
3661
+ ] }), Ir = () => /* @__PURE__ */ C("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", children: [
3662
+ /* @__PURE__ */ C("line", { x1: "22", y1: "2", x2: "11", y2: "13" }),
3663
+ /* @__PURE__ */ C("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
3664
+ ] }), br = () => /* @__PURE__ */ C("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", children: [
3665
+ /* @__PURE__ */ C("path", { d: "M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 2.59 3.4z" }),
3666
+ /* @__PURE__ */ C("line", { x1: "1", y1: "1", x2: "23", y2: "23" })
3667
+ ] }), bt = () => /* @__PURE__ */ C("svg", { width: "48", height: "48", viewBox: "0 0 48 48", fill: "none", style: { opacity: 0.3 }, children: [
3668
+ /* @__PURE__ */ C("circle", { cx: "24", cy: "18", r: "8", stroke: "white", "stroke-width": "2", fill: "none" }),
3669
+ /* @__PURE__ */ C("path", { d: "M8 42c0-8.837 7.163-16 16-16s16 7.163 16 16", stroke: "white", "stroke-width": "2", fill: "none" })
3670
+ ] });
3671
+ function Ar({
3672
+ config: t,
3673
+ session: e,
3674
+ videoRef: n,
3675
+ avatarSrc: o,
3676
+ displayCta: c,
3677
+ onCollapse: a
3678
+ }) {
3679
+ const u = Qe(null), [l, g] = Ye(""), [p, _] = Ye(null), [d, S] = Ye(!1), m = Qe(null), y = e.connectionStatus.value === "connected", A = e.connectionStatus.value === "connecting", w = e.connectionStatus.value === "error", I = e.isStreaming.value, b = !A && !y && !w, x = je(async () => {
3680
+ n.current && await e.startSession(n.current);
3681
+ }, []), M = je(async () => {
3682
+ await e.stopSession();
3683
+ }, []), N = je(() => {
3684
+ if (!l.trim()) return;
3685
+ const H = l.trim();
3686
+ e.sendMessage(H), g(""), u.current?.focus(), m.current && clearTimeout(m.current), S(!1), _(H), m.current = window.setTimeout(() => {
3687
+ S(!0), m.current = window.setTimeout(() => {
3688
+ _(null), S(!1);
3689
+ }, 400);
3690
+ }, 2600);
3691
+ }, [l]), Z = je((H) => {
3692
+ H.key === "Enter" && !H.shiftKey && (H.preventDefault(), N());
3693
+ }, [N]);
3694
+ return St(() => () => {
3695
+ m.current && clearTimeout(m.current);
3696
+ }, []), /* @__PURE__ */ C("div", { class: "anam-sheet", children: [
3697
+ /* @__PURE__ */ C(
3698
+ "video",
3699
+ {
3700
+ ref: n,
3701
+ class: "anam-video",
3702
+ autoplay: !0,
3703
+ playsinline: !0,
3704
+ "data-hidden": I ? void 0 : "true"
3705
+ }
3706
+ ),
3707
+ b && (e.hasAgentId.value ? (
3708
+ /* Has agent-id: show avatar or placeholder + CTA pill */
3709
+ /* @__PURE__ */ C("div", { class: "anam-overlay-idle", children: [
3710
+ o ? /* @__PURE__ */ C("img", { src: o, alt: "Avatar" }) : /* @__PURE__ */ C(bt, {}),
3711
+ /* @__PURE__ */ C("button", { class: "anam-cta-pill", onClick: x, children: [
3712
+ /* @__PURE__ */ C(Sr, {}),
3713
+ c
3714
+ ] })
3715
+ ] })
3716
+ ) : (
3717
+ /* No agent-id: unconfigured overlay */
3718
+ /* @__PURE__ */ C("div", { class: "anam-overlay-unconfigured", children: [
3719
+ /* @__PURE__ */ C(bt, {}),
3720
+ /* @__PURE__ */ C("span", { children: "Agent not configured" })
3721
+ ] })
3722
+ )),
3723
+ A && /* @__PURE__ */ C("div", { class: "anam-overlay-loading", children: [
3724
+ /* @__PURE__ */ C("span", { class: "anam-spinner" }),
3725
+ /* @__PURE__ */ C("span", { children: "Starting your conversation..." })
3726
+ ] }),
3727
+ w && /* @__PURE__ */ C("div", { class: "anam-overlay-error", children: [
3728
+ /* @__PURE__ */ C("div", { class: "anam-overlay-error-text", children: e.error.value || "Something went wrong" }),
3729
+ /* @__PURE__ */ C("button", { class: "anam-retry-btn", onClick: x, children: "Try Again" })
3730
+ ] }),
3731
+ (y || I) && /* @__PURE__ */ C(oe, { children: [
3732
+ a && /* @__PURE__ */ C("button", { class: "anam-close-btn", onClick: a, "aria-label": "Close", children: /* @__PURE__ */ C(yr, {}) }),
3733
+ p && /* @__PURE__ */ C("div", { class: `anam-toast ${d ? "anam-toast-out" : ""}`, children: p }),
3734
+ /* @__PURE__ */ C("div", { class: "anam-control-bar", children: [
3735
+ t.showMuteButton && /* @__PURE__ */ C(
3736
+ "button",
3737
+ {
3738
+ class: `anam-ctl-btn ${e.isMuted.value ? "anam-ctl-btn-muted" : ""}`,
3739
+ onClick: () => e.toggleMute(),
3740
+ "aria-label": e.isMuted.value ? "Unmute" : "Mute",
3741
+ children: e.isMuted.value ? /* @__PURE__ */ C(Cr, {}) : /* @__PURE__ */ C(wr, {})
3742
+ }
3743
+ ),
3744
+ t.showTextInput && /* @__PURE__ */ C(oe, { children: [
3745
+ /* @__PURE__ */ C(
3746
+ "input",
3747
+ {
3748
+ ref: u,
3749
+ type: "text",
3750
+ class: "anam-ctl-input",
3751
+ placeholder: t.textContents.placeholder,
3752
+ value: l,
3753
+ onInput: (H) => g(H.target.value),
3754
+ onKeyDown: Z,
3755
+ disabled: !y
3756
+ }
3757
+ ),
3758
+ /* @__PURE__ */ C(
3759
+ "button",
3760
+ {
3761
+ class: "anam-ctl-btn",
3762
+ onClick: N,
3763
+ disabled: !y || !l.trim(),
3764
+ "aria-label": "Send message",
3765
+ children: /* @__PURE__ */ C(Ir, {})
3766
+ }
3767
+ )
3768
+ ] }),
3769
+ /* @__PURE__ */ C(
3770
+ "button",
3771
+ {
3772
+ class: "anam-ctl-btn anam-ctl-end",
3773
+ onClick: M,
3774
+ "aria-label": "End call",
3775
+ children: /* @__PURE__ */ C(br, {})
3776
+ }
3777
+ )
3778
+ ] })
3779
+ ] })
3780
+ ] });
3781
+ }
3782
+ function Tr(t) {
3783
+ const e = Qe(null), n = Gi(!1), o = vr(t["agent-id"], t["api-base-url"]), c = Ie(() => {
3784
+ const w = {
3785
+ ...He,
3786
+ styles: { ...He.styles },
3787
+ textContents: { ...He.textContents }
3788
+ };
3789
+ if (t.mode ? w.mode = t.mode : t.variant && (w.mode = t.variant), t.layout ? w.layout = t.layout : w.layout = w.mode === "orb" ? "fixed" : "inline", t.position ? w.position = t.position : t.placement && (w.position = t.placement), t["background-color"] && (w.styles.backgroundColor = t["background-color"]), t["text-color"] && (w.styles.textColor = t["text-color"]), t["show-transcript"] !== void 0 && (w.showTranscript = ze(t["show-transcript"])), t["show-text-input"] !== void 0 && (w.showTextInput = ze(t["show-text-input"])), t["show-mute-button"] !== void 0 && (w.showMuteButton = ze(t["show-mute-button"])), t["interaction-mode"] && (w.interactionMode = t["interaction-mode"]), t["start-expanded"] !== void 0 && (w.startExpanded = ze(t["start-expanded"])), t["text-call-to-action"] && (w.textContents.callToAction = t["text-call-to-action"]), t["override-config"])
3790
+ try {
3791
+ Object.assign(w, JSON.parse(t["override-config"]));
3792
+ } catch (x) {
3793
+ console.warn("[AnamWidget] Invalid override-config JSON:", x);
3794
+ }
3795
+ const I = o.serverConfig.value, b = I ? qi(w, I) : w;
3796
+ return b.mode === "orb" && (b.layout = "fixed"), b;
3797
+ }, [
3798
+ t.mode,
3799
+ t.variant,
3800
+ t.layout,
3801
+ t.position,
3802
+ t.placement,
3803
+ t["background-color"],
3804
+ t["text-color"],
3805
+ t["show-transcript"],
3806
+ t["show-text-input"],
3807
+ t["show-mute-button"],
3808
+ t["interaction-mode"],
3809
+ t["start-expanded"],
3810
+ t["text-call-to-action"],
3811
+ t["override-config"],
3812
+ o.serverConfig.value
3813
+ ]);
3814
+ St(() => {
3815
+ o.fetchWidgetConfig();
3816
+ }, [t["agent-id"], t["api-base-url"]]);
3817
+ const a = o.avatarThumbnailUrl.value || null, u = c.textContents.callToAction === He.textContents.callToAction && o.personaName.value ? `Talk to ${o.personaName.value}` : c.textContents.callToAction, l = Ie(
3818
+ () => `--anam-background: ${c.styles.backgroundColor}; --anam-text: ${c.styles.textColor};`,
3819
+ [c.styles.backgroundColor, c.styles.textColor]
3820
+ ), g = Ie(() => {
3821
+ if (c.layout !== "fixed") return "";
3822
+ const w = On(c.position);
3823
+ return Object.entries(w).map(([I, b]) => `${I}: ${b}`).join("; ");
3824
+ }, [c.layout, c.position]), p = [l, g].filter(Boolean).join("; "), _ = Qe(!1), d = () => {
3825
+ n.value = !0, _.current = !1, setTimeout(() => {
3826
+ e.current && o.startSession(e.current);
3827
+ }, 50);
3828
+ }, S = async () => {
3829
+ o.connectionStatus.value !== "idle" && await o.stopSession(), _.current = !1, n.value = !1;
3830
+ }, m = c.mode === "orb", y = o.connectionStatus.value;
3831
+ (y === "connecting" || y === "connected") && (_.current = !0), St(() => {
3832
+ m && n.value && y === "idle" && _.current && (_.current = !1, n.value = !1);
3833
+ }, [y]);
3834
+ const A = m ? n.value : !0;
3835
+ return o.isReady.value ? /* @__PURE__ */ C(oe, { children: [
3836
+ /* @__PURE__ */ C("style", { children: ui }),
3837
+ /* @__PURE__ */ C(
3838
+ "div",
3839
+ {
3840
+ class: "anam-widget",
3841
+ "data-mode": c.mode,
3842
+ "data-layout": c.layout,
3843
+ style: p,
3844
+ children: [
3845
+ m && !n.value && /* @__PURE__ */ C(
3846
+ "button",
3847
+ {
3848
+ class: "anam-trigger",
3849
+ onClick: d,
3850
+ "aria-label": u,
3851
+ children: a ? /* @__PURE__ */ C("img", { src: a, alt: "Avatar" }) : /* @__PURE__ */ C(bt, {})
3852
+ }
3853
+ ),
3854
+ A && /* @__PURE__ */ C(
3855
+ Ar,
3856
+ {
3857
+ config: c,
3858
+ session: o,
3859
+ videoRef: e,
3860
+ avatarSrc: a,
3861
+ displayCta: u,
3862
+ onCollapse: m ? S : null
3863
+ }
3864
+ )
3865
+ ]
3866
+ }
3867
+ )
3868
+ ] }) : /* @__PURE__ */ C("style", { children: ui });
3869
+ }
3870
+ const xr = {
3871
+ SESSION_STARTED: "anam-agent:session-started",
3872
+ SESSION_ENDED: "anam-agent:session-ended",
3873
+ MESSAGE_RECEIVED: "anam-agent:message-received",
3874
+ MESSAGE_SENT: "anam-agent:message-sent",
3875
+ EXPANDED: "anam-agent:expanded",
3876
+ COLLAPSED: "anam-agent:collapsed",
3877
+ ERROR: "anam-agent:error",
3878
+ MIC_MUTED: "anam-agent:mic-muted",
3879
+ MIC_UNMUTED: "anam-agent:mic-unmuted"
3880
+ };
3881
+ function di(t = "anam-agent") {
3882
+ _n(Tr, t, [...kn], {
3883
+ shadow: !0
3884
+ });
3885
+ }
3886
+ typeof window < "u" && typeof document < "u" && (document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", () => di()) : di());
3887
+ export {
3888
+ He as DefaultConfig,
3889
+ xr as WidgetEventNames,
3890
+ di as registerWidget
3891
+ };