@telnyx/ai-agent-lib 0.2.8 → 0.2.11

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,4131 @@
1
+ import ut, { useReducer as En, useEffect as pe, useDebugValue as Tn, useCallback as An, useContext as Vt, createContext as Gt, useState as Rn } from "react";
2
+ function Wt(t, e) {
3
+ var n = {};
4
+ for (var i in t) Object.prototype.hasOwnProperty.call(t, i) && e.indexOf(i) < 0 && (n[i] = t[i]);
5
+ if (t != null && typeof Object.getOwnPropertySymbols == "function") {
6
+ var s = 0;
7
+ for (i = Object.getOwnPropertySymbols(t); s < i.length; s++) e.indexOf(i[s]) < 0 && Object.prototype.propertyIsEnumerable.call(t, i[s]) && (n[i[s]] = t[i[s]]);
8
+ }
9
+ return n;
10
+ }
11
+ function O(t, e, n, i) {
12
+ return new (n || (n = Promise))((function(s, a) {
13
+ function o(h) {
14
+ try {
15
+ d(i.next(h));
16
+ } catch (f) {
17
+ a(f);
18
+ }
19
+ }
20
+ function l(h) {
21
+ try {
22
+ d(i.throw(h));
23
+ } catch (f) {
24
+ a(f);
25
+ }
26
+ }
27
+ function d(h) {
28
+ var f;
29
+ h.done ? s(h.value) : (f = h.value, f instanceof n ? f : new n((function(m) {
30
+ m(f);
31
+ }))).then(o, l);
32
+ }
33
+ d((i = i.apply(t, [])).next());
34
+ }));
35
+ }
36
+ var gt = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto < "u" && typeof msCrypto.getRandomValues == "function" && msCrypto.getRandomValues.bind(msCrypto), xn = new Uint8Array(16);
37
+ function Ln() {
38
+ if (!gt) throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
39
+ return gt(xn);
40
+ }
41
+ for (var Ht = [], xe = 0; xe < 256; ++xe) Ht[xe] = (xe + 256).toString(16).substr(1);
42
+ function ve(t, e, n) {
43
+ var i = e && n || 0;
44
+ typeof t == "string" && (e = t === "binary" ? new Array(16) : null, t = null);
45
+ var s = (t = t || {}).random || (t.rng || Ln)();
46
+ if (s[6] = 15 & s[6] | 64, s[8] = 63 & s[8] | 128, e) for (var a = 0; a < 16; ++a) e[i + a] = s[a];
47
+ return e || (function(o, l) {
48
+ var d = 0, h = Ht;
49
+ return [h[o[d++]], h[o[d++]], h[o[d++]], h[o[d++]], "-", h[o[d++]], h[o[d++]], "-", h[o[d++]], h[o[d++]], "-", h[o[d++]], h[o[d++]], "-", h[o[d++]], h[o[d++]], h[o[d++]], h[o[d++]], h[o[d++]], h[o[d++]]].join("");
50
+ })(s);
51
+ }
52
+ const mt = "wss://rtc.telnyx.com", qt = { urls: "stun:stun.l.google.com:19302" }, On = [{ urls: "stun:stun.telnyx.com:3478" }, qt, { urls: "turn:turn.telnyx.com:3478?transport=tcp", username: "testuser", credential: "testpassword" }], Mn = [{ urls: "stun:stundev.telnyx.com:3478" }, qt, { urls: "turn:turndev.telnyx.com:3478?transport=tcp", username: "testuser", credential: "testpassword" }];
53
+ var L;
54
+ (function(t) {
55
+ t.SocketOpen = "telnyx.socket.open", t.SocketClose = "telnyx.socket.close", t.SocketError = "telnyx.socket.error", t.SocketMessage = "telnyx.socket.message", t.SpeedTest = "telnyx.internal.speedtest", t.Ready = "telnyx.ready", t.Error = "telnyx.error", t.Notification = "telnyx.notification", t.StatsFrame = "telnyx.stats.frame", t.StatsReport = "telnyx.stats.report", t.Messages = "telnyx.messages", t.Calls = "telnyx.calls", t.MediaError = "telnyx.rtc.mediaError", t.PeerConnectionFailureError = "telnyx.rtc.peerConnectionFailureError";
56
+ })(L || (L = {}));
57
+ var Pn = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
58
+ function Jt(t, e) {
59
+ return t(e = { exports: {} }, e.exports), e.exports;
60
+ }
61
+ var Dn = Jt((function(t) {
62
+ var e, n;
63
+ e = Pn, n = function() {
64
+ var i = function() {
65
+ }, s = "undefined", a = typeof window !== s && typeof window.navigator !== s && /Trident\/|MSIE /.test(window.navigator.userAgent), o = ["trace", "debug", "info", "warn", "error"];
66
+ function l(p, _) {
67
+ var A = p[_];
68
+ if (typeof A.bind == "function") return A.bind(p);
69
+ try {
70
+ return Function.prototype.bind.call(A, p);
71
+ } catch {
72
+ return function() {
73
+ return Function.prototype.apply.apply(A, [p, arguments]);
74
+ };
75
+ }
76
+ }
77
+ function d() {
78
+ console.log && (console.log.apply ? console.log.apply(console, arguments) : Function.prototype.apply.apply(console.log, [console, arguments])), console.trace && console.trace();
79
+ }
80
+ function h(p, _) {
81
+ for (var A = 0; A < o.length; A++) {
82
+ var E = o[A];
83
+ this[E] = A < p ? i : this.methodFactory(E, p, _);
84
+ }
85
+ this.log = this.debug;
86
+ }
87
+ function f(p, _, A) {
88
+ return function() {
89
+ typeof console !== s && (h.call(this, _, A), this[p].apply(this, arguments));
90
+ };
91
+ }
92
+ function m(p, _, A) {
93
+ return (function(E) {
94
+ return E === "debug" && (E = "log"), typeof console !== s && (E === "trace" && a ? d : console[E] !== void 0 ? l(console, E) : console.log !== void 0 ? l(console, "log") : i);
95
+ })(p) || f.apply(this, arguments);
96
+ }
97
+ function S(p, _, A) {
98
+ var E, P = this;
99
+ _ = _ ?? "WARN";
100
+ var D = "loglevel";
101
+ function q() {
102
+ var x;
103
+ if (typeof window !== s && D) {
104
+ try {
105
+ x = window.localStorage[D];
106
+ } catch {
107
+ }
108
+ if (typeof x === s) try {
109
+ var r = window.document.cookie, c = r.indexOf(encodeURIComponent(D) + "=");
110
+ c !== -1 && (x = /^([^;]+)/.exec(r.slice(c))[1]);
111
+ } catch {
112
+ }
113
+ return P.levels[x] === void 0 && (x = void 0), x;
114
+ }
115
+ }
116
+ typeof p == "string" ? D += ":" + p : typeof p == "symbol" && (D = void 0), P.name = p, P.levels = { TRACE: 0, DEBUG: 1, INFO: 2, WARN: 3, ERROR: 4, SILENT: 5 }, P.methodFactory = A || m, P.getLevel = function() {
117
+ return E;
118
+ }, P.setLevel = function(x, r) {
119
+ if (typeof x == "string" && P.levels[x.toUpperCase()] !== void 0 && (x = P.levels[x.toUpperCase()]), !(typeof x == "number" && x >= 0 && x <= P.levels.SILENT)) throw "log.setLevel() called with invalid level: " + x;
120
+ if (E = x, r !== !1 && (function(c) {
121
+ var u = (o[c] || "silent").toUpperCase();
122
+ if (typeof window !== s && D) {
123
+ try {
124
+ return void (window.localStorage[D] = u);
125
+ } catch {
126
+ }
127
+ try {
128
+ window.document.cookie = encodeURIComponent(D) + "=" + u + ";";
129
+ } catch {
130
+ }
131
+ }
132
+ })(x), h.call(P, x, p), typeof console === s && x < P.levels.SILENT) return "No console available for logging";
133
+ }, P.setDefaultLevel = function(x) {
134
+ _ = x, q() || P.setLevel(x, !1);
135
+ }, P.resetLevel = function() {
136
+ P.setLevel(_, !1), (function() {
137
+ if (typeof window !== s && D) {
138
+ try {
139
+ return void window.localStorage.removeItem(D);
140
+ } catch {
141
+ }
142
+ try {
143
+ window.document.cookie = encodeURIComponent(D) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
144
+ } catch {
145
+ }
146
+ }
147
+ })();
148
+ }, P.enableAll = function(x) {
149
+ P.setLevel(P.levels.TRACE, x);
150
+ }, P.disableAll = function(x) {
151
+ P.setLevel(P.levels.SILENT, x);
152
+ };
153
+ var B = q();
154
+ B == null && (B = _), P.setLevel(B, !1);
155
+ }
156
+ var w = new S(), C = {};
157
+ w.getLogger = function(p) {
158
+ if (typeof p != "symbol" && typeof p != "string" || p === "") throw new TypeError("You must supply a name when creating a logger.");
159
+ var _ = C[p];
160
+ return _ || (_ = C[p] = new S(p, w.getLevel(), w.methodFactory)), _;
161
+ };
162
+ var k = typeof window !== s ? window.log : void 0;
163
+ return w.noConflict = function() {
164
+ return typeof window !== s && window.log === w && (window.log = k), w;
165
+ }, w.getLoggers = function() {
166
+ return C;
167
+ }, w.default = w, w;
168
+ }, t.exports ? t.exports = n() : e.log = n();
169
+ }));
170
+ const y = Dn.getLogger("telnyx"), Nn = y.methodFactory;
171
+ y.methodFactory = (t, e, n) => {
172
+ const i = Nn(t, e, n);
173
+ return function() {
174
+ const s = [(/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", ""), "-"];
175
+ for (let a = 0; a < arguments.length; a++) s.push(arguments[a]);
176
+ i.apply(void 0, s);
177
+ };
178
+ }, y.setLevel("info");
179
+ const Le = (t) => {
180
+ const [e, n, i, s, a, o] = t;
181
+ let l = {};
182
+ try {
183
+ l = JSON.parse(a.replace(/ID"/g, 'Id"'));
184
+ } catch {
185
+ y.warn("Verto LA invalid media JSON string:", a);
186
+ }
187
+ return { participantId: Number(e), participantNumber: n, participantName: i, codec: s, media: l, participantData: o };
188
+ }, Yt = (t) => {
189
+ if (typeof t != "string") return t;
190
+ try {
191
+ return JSON.parse(t);
192
+ } catch {
193
+ return t;
194
+ }
195
+ }, ye = (t) => t instanceof Function || typeof t == "function", De = (t) => typeof document == "object" && "getElementById" in document ? typeof t == "string" ? document.getElementById(t) || null : typeof t == "function" ? t() : t instanceof HTMLMediaElement ? t : null : null, Un = /^(ws|wss):\/\//, zt = (t, e = null) => {
196
+ const { result: n = {}, error: i } = t;
197
+ if (i) return { error: i };
198
+ const { result: s = null } = n;
199
+ if (s === null) return e !== null && (n.node_id = e), { result: n };
200
+ const { code: a = null, node_id: o = null, result: l = null } = s;
201
+ return a && a !== "200" ? { error: s } : l ? zt(l, o) : { result: s };
202
+ }, Kt = (t, e) => Math.floor(Math.random() * (e - t + 1) + t), Ne = ({ login: t, passwd: e, password: n, login_token: i }) => !!(t && (e || n) || i), Ie = ({ anonymous_login: t }) => !!t && !!t.target_id && !!t.target_type, ht = (t) => {
203
+ var e, n, i, s, a, o;
204
+ let l = "", d = "";
205
+ return !((n = (e = t?.result) === null || e === void 0 ? void 0 : e.params) === null || n === void 0) && n.state && (l = (s = (i = t?.result) === null || i === void 0 ? void 0 : i.params) === null || s === void 0 ? void 0 : s.state), !((a = t?.params) === null || a === void 0) && a.state && (d = (o = t?.params) === null || o === void 0 ? void 0 : o.state), l || d;
206
+ };
207
+ function vt({ debounceTime: t }) {
208
+ let e, n;
209
+ return { promise: new Promise(((i, s) => {
210
+ e = t ? jn(i, t) : i, n = s;
211
+ })), resolve: e, reject: n };
212
+ }
213
+ const jn = (t, e) => {
214
+ let n;
215
+ return (...i) => {
216
+ clearTimeout(n), n = window.setTimeout((() => {
217
+ t(...i);
218
+ }), e);
219
+ };
220
+ }, pt = "telnyx-voice-sdk-id";
221
+ function fe() {
222
+ return sessionStorage.getItem(pt);
223
+ }
224
+ var K, le, $;
225
+ typeof window < "u" && window.addEventListener("beforeunload", (() => {
226
+ sessionStorage.removeItem(pt);
227
+ })), (function(t) {
228
+ t.Offer = "offer", t.Answer = "answer";
229
+ })(K || (K = {})), (function(t) {
230
+ t.Inbound = "inbound", t.Outbound = "outbound";
231
+ })(le || (le = {})), (function(t) {
232
+ t.Invite = "telnyx_rtc.invite", t.Attach = "telnyx_rtc.attach", t.Answer = "telnyx_rtc.answer", t.Info = "telnyx_rtc.info", t.Candidate = "telnyx_rtc.candidate", t.EndOfCandidates = "telnyx_rtc.endOfCandidates", t.Display = "telnyx_rtc.display", t.Media = "telnyx_rtc.media", t.Event = "telnyx_rtc.event", t.Bye = "telnyx_rtc.bye", t.Punt = "telnyx_rtc.punt", t.Broadcast = "telnyx_rtc.broadcast", t.Subscribe = "telnyx_rtc.subscribe", t.Unsubscribe = "telnyx_rtc.unsubscribe", t.ClientReady = "telnyx_rtc.clientReady", t.Modify = "telnyx_rtc.modify", t.Ringing = "telnyx_rtc.ringing", t.GatewayState = "telnyx_rtc.gatewayState", t.Ping = "telnyx_rtc.ping", t.Pong = "telnyx_rtc.pong";
233
+ })($ || ($ = {}));
234
+ const oe = { generic: "event", [$.Display]: "participantData", [$.Attach]: "participantData", conferenceUpdate: "conferenceUpdate", callUpdate: "callUpdate", vertoClientReady: "vertoClientReady", userMediaError: "userMediaError", peerConnectionFailureError: "peerConnectionFailureError" }, Fn = { destinationNumber: "", remoteCallerName: "Outbound Call", remoteCallerNumber: "", callerName: "", callerNumber: "", audio: !0, useStereo: !1, debug: !1, debugOutput: "socket", attach: !1, screenShare: !1, userVariables: {}, mediaSettings: { useSdpASBandwidthKbps: !1, sdpASBandwidthKbps: 0 }, mutedMicOnStart: !1 };
235
+ var N, et, se, ae, te;
236
+ (function(t) {
237
+ t[t.New = 0] = "New", t[t.Requesting = 1] = "Requesting", t[t.Trying = 2] = "Trying", t[t.Recovering = 3] = "Recovering", t[t.Ringing = 4] = "Ringing", t[t.Answering = 5] = "Answering", t[t.Early = 6] = "Early", t[t.Active = 7] = "Active", t[t.Held = 8] = "Held", t[t.Hangup = 9] = "Hangup", t[t.Destroy = 10] = "Destroy", t[t.Purge = 11] = "Purge";
238
+ })(N || (N = {})), (function(t) {
239
+ t.Participant = "participant", t.Moderator = "moderator";
240
+ })(et || (et = {})), (function(t) {
241
+ t.Join = "join", t.Leave = "leave", t.Bootstrap = "bootstrap", t.Add = "add", t.Modify = "modify", t.Delete = "delete", t.Clear = "clear", t.ChatMessage = "chatMessage", t.LayerInfo = "layerInfo", t.LogoInfo = "logoInfo", t.LayoutInfo = "layoutInfo", t.LayoutList = "layoutList", t.ModCmdResponse = "modCommandResponse";
242
+ })(se || (se = {})), (function(t) {
243
+ t.Video = "videoinput", t.AudioIn = "audioinput", t.AudioOut = "audiooutput";
244
+ })(ae || (ae = {})), (function(t) {
245
+ t.REGED = "REGED", t.UNREGED = "UNREGED", t.NOREG = "NOREG", t.FAILED = "FAILED", t.FAIL_WAIT = "FAIL_WAIT", t.REGISTER = "REGISTER", t.TRYING = "TRYING", t.EXPIRED = "EXPIRED", t.UNREGISTER = "UNREGISTER";
246
+ })(te || (te = {}));
247
+ const be = "GLOBAL", ie = {}, Ae = (t, e) => `${t}|${e}`, Qt = (t, e = be) => Ae(t, e) in ie, de = (t, e, n = be) => {
248
+ const i = Ae(t, n);
249
+ i in ie || (ie[i] = []), ie[i].push(e);
250
+ }, Xt = (t, e, n = be) => {
251
+ const i = function(s) {
252
+ ue(t, i, n), e(s);
253
+ };
254
+ return i.prototype.targetRef = e, de(t, i, n);
255
+ }, ue = (t, e, n = be) => {
256
+ if (!Qt(t, n)) return !1;
257
+ const i = Ae(t, n);
258
+ if (ye(e))
259
+ for (let s = ie[i].length - 1; s >= 0; s--) {
260
+ const a = ie[i][s];
261
+ (e === a || a.prototype && e === a.prototype.targetRef) && ie[i].splice(s, 1);
262
+ }
263
+ else ie[i] = [];
264
+ return ie[i].length === 0 && delete ie[i], !0;
265
+ }, F = (t, e, n = be, i = !0) => {
266
+ const s = i && n !== be;
267
+ if (!Qt(t, n)) return s && F(t, e), !1;
268
+ const a = Ae(t, n), o = ie[a].length;
269
+ if (!o) return s && F(t, e), !1;
270
+ for (let l = o - 1; l >= 0; l--) ie[a][l](e);
271
+ return s && F(t, e), !0;
272
+ }, Ke = (t) => {
273
+ const e = Ae(t, "");
274
+ Object.keys(ie).filter(((n) => n.indexOf(e) === 0)).forEach(((n) => delete ie[n]));
275
+ };
276
+ let $n = typeof WebSocket < "u" ? WebSocket : null;
277
+ const Bn = 0, Vn = 1, Gn = 2, Wn = 3;
278
+ class yt {
279
+ constructor(e) {
280
+ this.session = e, this.previousGatewayState = "", this._wsClient = null, this._host = mt, this._timers = {}, this._useCanaryRtcServer = !1, this._hasCanaryBeenUsed = !1, this.upDur = null, this.downDur = null;
281
+ const { host: n, env: i, region: s, trickleIce: a, useCanaryRtcServer: o } = e.options;
282
+ i && (this._host = i === "development" ? "wss://rtcdev.telnyx.com" : mt), n && (this._host = ((l) => `${Un.test(l) ? "" : "wss://"}${l}`)(n)), s && (this._host = this._host.replace(/rtc(dev)?/, `${s}.rtc$1`)), (a || o) && (this._useCanaryRtcServer = !0);
283
+ }
284
+ get connected() {
285
+ return this._wsClient && this._wsClient.readyState === Vn;
286
+ }
287
+ get connecting() {
288
+ return this._wsClient && this._wsClient.readyState === Bn;
289
+ }
290
+ get closing() {
291
+ return this._wsClient && this._wsClient.readyState === Gn;
292
+ }
293
+ get closed() {
294
+ return this._wsClient && this._wsClient.readyState === Wn;
295
+ }
296
+ get isAlive() {
297
+ return this.connecting || this.connected;
298
+ }
299
+ get isDead() {
300
+ return this.closing || this.closed;
301
+ }
302
+ connect() {
303
+ const e = new URL(this._host);
304
+ let n = fe();
305
+ this.session.options.rtcIp && this.session.options.rtcPort && (n = null, this._useCanaryRtcServer = !1, e.searchParams.set("rtc_ip", this.session.options.rtcIp), e.searchParams.set("rtc_port", this.session.options.rtcPort.toString())), n && e.searchParams.set("voice_sdk_id", n), this._useCanaryRtcServer && (e.searchParams.set("canary", "true"), n && !this._hasCanaryBeenUsed && (e.searchParams.delete("voice_sdk_id"), y.debug("first canary connection. Refreshing voice_sdk_id")), this._hasCanaryBeenUsed = !0), this._wsClient = new $n(e.toString()), this._wsClient.onopen = (i) => F(L.SocketOpen, i, this.session.uuid), this._wsClient.onclose = (i) => F(L.SocketClose, i, this.session.uuid), this._wsClient.onerror = (i) => F(L.SocketError, { error: i, sessionId: this.session.sessionid }, this.session.uuid), this._wsClient.onmessage = (i) => {
306
+ var s, a;
307
+ const o = Yt(i.data);
308
+ var l;
309
+ if (typeof o != "string") {
310
+ if (o.voice_sdk_id && (l = o.voice_sdk_id, sessionStorage.setItem(pt, l)), this._unsetTimer(o.id), y.debug(`RECV:
311
+ `, JSON.stringify(o, null, 2), `
312
+ `), te[`${(a = (s = o?.result) === null || s === void 0 ? void 0 : s.params) === null || a === void 0 ? void 0 : a.state}`] || !F(o.id, o)) {
313
+ const d = ht(o);
314
+ F(L.SocketMessage, o, this.session.uuid), d && (this.previousGatewayState = d);
315
+ }
316
+ } else this._handleStringResponse(o);
317
+ };
318
+ }
319
+ sendRawText(e) {
320
+ this._wsClient.send(e);
321
+ }
322
+ send(e) {
323
+ const { request: n } = e, i = new Promise(((s, a) => {
324
+ if (n.hasOwnProperty("result")) return s();
325
+ Xt(n.id, ((o) => {
326
+ const { result: l, error: d } = zt(o);
327
+ return d ? a(d) : s(l);
328
+ }));
329
+ }));
330
+ return y.debug(`SEND:
331
+ `, JSON.stringify(n, null, 2), `
332
+ `), this._wsClient.send(JSON.stringify(n)), i;
333
+ }
334
+ close() {
335
+ this._wsClient && (ye(this._wsClient._beginClose) ? this._wsClient._beginClose() : this._wsClient.close()), this._wsClient = null;
336
+ }
337
+ _unsetTimer(e) {
338
+ clearTimeout(this._timers[e]), delete this._timers[e];
339
+ }
340
+ _handleStringResponse(e) {
341
+ if (/^#SP/.test(e)) switch (e[3]) {
342
+ case "U":
343
+ this.upDur = parseInt(e.substring(4));
344
+ break;
345
+ case "D":
346
+ this.downDur = parseInt(e.substring(4)), F(L.SpeedTest, { upDur: this.upDur, downDur: this.downDur }, this.session.uuid);
347
+ }
348
+ else y.warn("Unknown message from socket", e);
349
+ }
350
+ }
351
+ class Re {
352
+ buildRequest(e) {
353
+ this.request = Object.assign({ jsonrpc: "2.0", id: ve() }, e);
354
+ }
355
+ }
356
+ const bt = { id: "callID", destinationNumber: "destination_number", remoteCallerName: "remote_caller_id_name", remoteCallerNumber: "remote_caller_id_number", callerName: "caller_id_name", callerNumber: "caller_id_number", customHeaders: "custom_headers" };
357
+ class Z extends Re {
358
+ constructor(e = {}) {
359
+ if (super(), e.hasOwnProperty("dialogParams")) {
360
+ const n = Wt(e.dialogParams, ["remoteSdp", "localStream", "remoteStream", "onNotification", "camId", "micId", "speakerId"]);
361
+ for (const i in bt) i && n.hasOwnProperty(i) && (n[bt[i]] = n[i], delete n[i]);
362
+ e.dialogParams = n;
363
+ }
364
+ this.buildRequest({ method: this.toString(), params: e });
365
+ }
366
+ }
367
+ class Zt extends Z {
368
+ constructor(e) {
369
+ super(), this.method = $.GatewayState, this.buildRequest({ method: this.method, voice_sdk_id: e, params: {} });
370
+ }
371
+ }
372
+ class Hn {
373
+ constructor(e) {
374
+ this.pendingRequestId = null, this.onSocketMessage = (n) => O(this, void 0, void 0, (function* () {
375
+ n.id === this.pendingRequestId && this.gatewayStateTask.resolve(ht(n));
376
+ })), this.getIsRegistered = () => O(this, void 0, void 0, (function* () {
377
+ const n = new Zt(fe());
378
+ this.pendingRequestId = n.request.id, this.gatewayStateTask = vt({}), this.session.execute(n);
379
+ const i = yield this.gatewayStateTask.promise;
380
+ return !!i && [te.REGISTER, te.REGED].includes(i);
381
+ })), this.session = e, this.gatewayStateTask = vt({}), this.session.on("telnyx.socket.message", this.onSocketMessage);
382
+ }
383
+ }
384
+ class en extends Z {
385
+ constructor(e) {
386
+ super(), this.method = $.Ping, this.buildRequest({ method: this.method, voice_sdk_id: e, params: {} });
387
+ }
388
+ }
389
+ class qn {
390
+ constructor(e) {
391
+ if (this.options = e, this.uuid = ve(), this.sessionid = "", this.subscriptions = {}, this.signature = null, this.relayProtocol = null, this.contexts = [], this.timeoutErrorCode = -32e3, this.invalidMethodErrorCode = -32601, this.authenticationRequiredErrorCode = -32e3, this.connection = null, this._jwtAuth = !1, this._autoReconnect = !0, this._idle = !1, this._executeQueue = [], !this.validateOptions()) throw new Error("Invalid init options");
392
+ y.setLevel(e.debug ? "debug" : "info"), this._onSocketOpen = this._onSocketOpen.bind(this), this.onNetworkClose = this.onNetworkClose.bind(this), this._onSocketMessage = this._onSocketMessage.bind(this), this._handleLoginError = this._handleLoginError.bind(this), this._attachListeners(), this.connection = new yt(this), this.registerAgent = new Hn(this);
393
+ }
394
+ get __logger() {
395
+ return y;
396
+ }
397
+ get connected() {
398
+ return this.connection && this.connection.connected;
399
+ }
400
+ getIsRegistered() {
401
+ return O(this, void 0, void 0, (function* () {
402
+ return this.registerAgent.getIsRegistered();
403
+ }));
404
+ }
405
+ get reconnectDelay() {
406
+ return 1e3 * Kt(2, 6);
407
+ }
408
+ execute(e) {
409
+ return this._idle ? new Promise(((n) => this._executeQueue.push({ resolve: n, msg: e }))) : this.connected ? this.connection.send(e) : new Promise(((n) => {
410
+ this._executeQueue.push({ resolve: n, msg: e }), this.connect();
411
+ }));
412
+ }
413
+ executeRaw(e) {
414
+ this._idle ? this._executeQueue.push({ msg: e }) : this.connection.sendRawText(e);
415
+ }
416
+ validateOptions() {
417
+ return Ne(this.options) || Ie(this.options);
418
+ }
419
+ broadcast(e) {
420
+ }
421
+ disconnect() {
422
+ return O(this, void 0, void 0, (function* () {
423
+ clearTimeout(this._reconnectTimeout), this.subscriptions = {}, this._autoReconnect = !1, this.relayProtocol = null, this._closeConnection(), yield sessionStorage.removeItem(this.signature), this._executeQueue = [], this._detachListeners();
424
+ }));
425
+ }
426
+ on(e, n) {
427
+ return de(e, n, this.uuid), this;
428
+ }
429
+ off(e, n) {
430
+ return ue(e, n, this.uuid), this;
431
+ }
432
+ connect() {
433
+ return O(this, void 0, void 0, (function* () {
434
+ this.connection || (this.connection = new yt(this)), this._attachListeners(), this.connection.isAlive || this.connection.connect();
435
+ }));
436
+ }
437
+ _handleLoginError(e) {
438
+ F(L.Error, { error: e, sessionId: this.sessionid }, this.uuid);
439
+ }
440
+ _onSocketOpen() {
441
+ return O(this, void 0, void 0, (function* () {
442
+ }));
443
+ }
444
+ onNetworkClose() {
445
+ this.relayProtocol && Ke(this.relayProtocol);
446
+ for (const e in this.subscriptions) Ke(e);
447
+ this.subscriptions = {}, this.contexts = [], clearTimeout(this._keepAliveTimeout), this._autoReconnect && (this._reconnectTimeout = setTimeout((() => this.connect()), this.reconnectDelay));
448
+ }
449
+ _onSocketMessage(e) {
450
+ }
451
+ _removeSubscription(e, n) {
452
+ this._existsSubscription(e, n) && (n ? (delete this.subscriptions[e][n], ue(e, null, n)) : (delete this.subscriptions[e], Ke(e)));
453
+ }
454
+ _addSubscription(e, n = null, i) {
455
+ this._existsSubscription(e, i) || (this._existsSubscription(e) || (this.subscriptions[e] = {}), this.subscriptions[e][i] = {}, ye(n) && de(e, n, i));
456
+ }
457
+ _existsSubscription(e, n) {
458
+ return !(!this.subscriptions.hasOwnProperty(e) || !(!n || n && this.subscriptions[e].hasOwnProperty(n)));
459
+ }
460
+ _attachListeners() {
461
+ this._detachListeners(), this.on(L.SocketOpen, this._onSocketOpen), this.on(L.SocketClose, this.onNetworkClose), this.on(L.SocketError, this.onNetworkClose), this.on(L.SocketMessage, this._onSocketMessage);
462
+ }
463
+ _detachListeners() {
464
+ this.off(L.SocketOpen, this._onSocketOpen), this.off(L.SocketClose, this.onNetworkClose), this.off(L.SocketError, this.onNetworkClose), this.off(L.SocketMessage, this._onSocketMessage);
465
+ }
466
+ _emptyExecuteQueues() {
467
+ this._executeQueue.forEach((({ resolve: e, msg: n }) => {
468
+ typeof n == "string" ? this.executeRaw(n) : e(this.execute(n));
469
+ }));
470
+ }
471
+ _closeConnection() {
472
+ this._idle = !0, clearTimeout(this._keepAliveTimeout), this.connection && this.connection.close();
473
+ }
474
+ _resetKeepAlive() {
475
+ this._pong === !1 && (y.warn("No ping/pong received, forcing PING ACK to keep alive"), this.execute(new en(fe()))), clearTimeout(this._keepAliveTimeout), this._triggerKeepAliveTimeoutCheck();
476
+ }
477
+ _triggerKeepAliveTimeoutCheck() {
478
+ this._pong = !1, this._keepAliveTimeout = setTimeout((() => this._resetKeepAlive()), 35e3);
479
+ }
480
+ setPingReceived() {
481
+ y.debug("Ping received"), this._pong = !0;
482
+ }
483
+ static on(e, n) {
484
+ de(e, n);
485
+ }
486
+ static off(e) {
487
+ ue(e);
488
+ }
489
+ static uuid() {
490
+ return ve();
491
+ }
492
+ clearConnection() {
493
+ this.connection = null;
494
+ }
495
+ hasAutoReconnect() {
496
+ return this._autoReconnect;
497
+ }
498
+ }
499
+ const tt = (t) => navigator.mediaDevices.getUserMedia(t), ge = (t) => t && t instanceof MediaStream, Ee = (t, e) => {
500
+ const n = De(t);
501
+ n !== null && (n.getAttribute("autoplay") || n.setAttribute("autoplay", "autoplay"), n.getAttribute("playsinline") || n.setAttribute("playsinline", "playsinline"), n.srcObject = e);
502
+ }, tn = (t, e) => O(void 0, void 0, void 0, (function* () {
503
+ const n = De(t);
504
+ if (n === null) return y.info("No HTMLMediaElement to attach the speakerId"), !1;
505
+ if (typeof e != "string") return y.info(`Invalid speaker deviceId: '${e}'`), !1;
506
+ try {
507
+ return yield n.setSinkId(e), !0;
508
+ } catch {
509
+ return !1;
510
+ }
511
+ })), Jn = (t) => {
512
+ t && t.readyState === "live" && t.stop();
513
+ }, Te = (t) => {
514
+ ge(t) && t.getTracks().forEach(Jn), t = null;
515
+ }, Ue = (t) => O(void 0, void 0, void 0, (function* () {
516
+ y.info("RTCService.getUserMedia", t);
517
+ const { audio: e, video: n } = t;
518
+ if (!e && !n) return null;
519
+ try {
520
+ return yield tt(t);
521
+ } catch (i) {
522
+ throw y.error("getUserMedia error: ", i), i;
523
+ }
524
+ })), ke = (t = null, e = !1) => O(void 0, void 0, void 0, (function* () {
525
+ let n = [];
526
+ const i = yield navigator.mediaDevices.getUserMedia(((s = null) => ({ audio: !s || s === ae.AudioIn || s === ae.AudioOut, video: !s || s === ae.Video }))(t)).catch(((s) => (y.error(s), null)));
527
+ if (i) {
528
+ if (Te(i), n = yield navigator.mediaDevices.enumerateDevices(), t && (n = n.filter(((a) => a.kind === t))), e === !0) return n;
529
+ const s = [];
530
+ n = n.filter(((a) => {
531
+ if (!a.groupId) return !0;
532
+ const o = `${a.kind}-${a.groupId}`;
533
+ return !s.includes(o) && (s.push(o), !0);
534
+ }));
535
+ }
536
+ return n;
537
+ })), St = [[320, 240], [640, 360], [640, 480], [1280, 720], [1920, 1080]], je = (t, e, n) => O(void 0, void 0, void 0, (function* () {
538
+ const i = yield ke(n, !0);
539
+ for (let s = 0; s < i.length; s++) {
540
+ const { deviceId: a, label: o } = i[s];
541
+ if (t === a || e === o) return a;
542
+ }
543
+ return null;
544
+ })), Yn = (t) => {
545
+ const e = navigator.mediaDevices.getSupportedConstraints();
546
+ Object.keys(t).map(((n) => {
547
+ e.hasOwnProperty(n) && t[n] !== null && t[n] !== void 0 || delete t[n];
548
+ }));
549
+ }, nt = (t, e) => {
550
+ if (!t) return !1;
551
+ const { subscribed: n, alreadySubscribed: i } = it(t);
552
+ return n.includes(e) || i.includes(e);
553
+ }, it = (t) => {
554
+ const e = { subscribed: [], alreadySubscribed: [], unauthorized: [], unsubscribed: [], notSubscribed: [] };
555
+ return Object.keys(e).forEach(((n) => {
556
+ e[n] = t[`${n}Channels`] || [];
557
+ })), e;
558
+ }, me = (t, e = null, n = null) => {
559
+ if (!ge(t)) return null;
560
+ let i = [];
561
+ switch (e) {
562
+ case "audio":
563
+ i = t.getAudioTracks();
564
+ break;
565
+ case "video":
566
+ i = t.getVideoTracks();
567
+ break;
568
+ default:
569
+ i = t.getTracks();
570
+ }
571
+ i.forEach(((s) => {
572
+ switch (n) {
573
+ case "on":
574
+ case !0:
575
+ s.enabled = !0;
576
+ break;
577
+ case "off":
578
+ case !1:
579
+ s.enabled = !1;
580
+ break;
581
+ default:
582
+ s.enabled = !s.enabled;
583
+ }
584
+ }));
585
+ }, _t = (t) => {
586
+ me(t, "audio", !0);
587
+ }, st = (t) => {
588
+ me(t, "audio", !1);
589
+ }, wt = (t) => {
590
+ me(t, "audio", null);
591
+ }, zn = (t) => ((e, n = null) => {
592
+ if (!ge(e)) return null;
593
+ let i = [];
594
+ switch (n) {
595
+ case "audio":
596
+ i = e.getAudioTracks();
597
+ break;
598
+ case "video":
599
+ i = e.getVideoTracks();
600
+ break;
601
+ default:
602
+ i = e.getTracks();
603
+ }
604
+ return i.some(((s) => s.enabled));
605
+ })(t, "audio");
606
+ function Kn() {
607
+ try {
608
+ const { browserInfo: t, name: e, version: n, supportAudio: i, supportVideo: s } = (function() {
609
+ if (!window || !window.navigator || !window.navigator.userAgent) throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");
610
+ if (navigator.userAgent.match(/chrom(e|ium)/gim) && !navigator.userAgent.match(/OPR\/[0-9]{2}/gi) && !navigator.userAgent.match(/edg/gim)) {
611
+ const f = navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"), m = f[0], S = parseInt(f[1], 10);
612
+ return { browserInfo: navigator.userAgent, name: m, version: S, supportAudio: !0, supportVideo: !0 };
613
+ }
614
+ if (navigator.userAgent.match(/firefox/gim) && !navigator.userAgent.match(/OPR\/[0-9]{2}/gi) && !navigator.userAgent.match(/edg/gim)) {
615
+ const f = navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"), m = f[0], S = parseInt(f[1], 10);
616
+ return { browserInfo: navigator.userAgent, name: m, version: S, supportAudio: !0, supportVideo: !1 };
617
+ }
618
+ if (navigator.userAgent.match(/safari/gim) && !navigator.userAgent.match(/OPR\/[0-9]{2}/gi) && !navigator.userAgent.match(/edg/gim)) {
619
+ const f = navigator.userAgent.match(/safari/gim)[0], m = navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"), S = parseInt(m[1], 10);
620
+ return { browserInfo: navigator.userAgent, name: f, version: S, supportAudio: !0, supportVideo: !0 };
621
+ }
622
+ if (navigator.userAgent.match(/edg/gim) && !navigator.userAgent.match(/OPR\/[0-9]{2}/gi)) {
623
+ const f = navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"), m = f[0], S = parseInt(f[1], 10);
624
+ return { browserInfo: navigator.userAgent, name: m, version: S, supportAudio: !0, supportVideo: !0 };
625
+ }
626
+ throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`");
627
+ })(), a = window.RTCPeerConnection, o = window.RTCSessionDescription, l = window.RTCIceCandidate, d = window.navigator && window.navigator.mediaDevices, h = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia || navigator.mozGetUserMedia;
628
+ return { browserInfo: t, browserName: e, browserVersion: n, supportWebRTC: !!(a && o && l && d && h), supportWebRTCAudio: i, supportWebRTCVideo: s, supportRTCPeerConnection: !!a, supportSessionDescription: !!o, supportIceCandidate: !!l, supportMediaDevices: !!d, supportGetUserMedia: !!Ue };
629
+ } catch (t) {
630
+ return t.message;
631
+ }
632
+ }
633
+ var H;
634
+ function Ct(t, e) {
635
+ const n = document.getElementById(e);
636
+ if (n) return n;
637
+ if (t && e) {
638
+ const i = document.createElement("audio");
639
+ return i.id = e, i.loop = !0, i.src = t, i.preload = "auto", i.load(), document.body.appendChild(i), i;
640
+ }
641
+ return null;
642
+ }
643
+ function kt(t) {
644
+ t && (t._playFulfilled = !1, t._promise = t.play(), t._promise.then((() => {
645
+ t._playFulfilled = !0;
646
+ })).catch(((e) => {
647
+ y.error("playAudio", e), t._playFulfilled = !0;
648
+ })));
649
+ }
650
+ function It(t) {
651
+ t && (t._playFulfilled ? (t.pause(), t.currentTime = 0) : t._promise && t._promise.then ? t._promise.then((() => {
652
+ t.pause(), t.currentTime = 0;
653
+ })) : setTimeout((() => {
654
+ t.pause(), t.currentTime = 0;
655
+ }), 1e3));
656
+ }
657
+ (function(t) {
658
+ t.not_supported = "not supported", t.full = "full", t.partial = "partial";
659
+ })(H || (H = {}));
660
+ var nn = "2.25.14", We = nn;
661
+ class sn extends Z {
662
+ constructor(e, n, i, s, a = {}, o) {
663
+ super(), this.method = "login";
664
+ const l = { login: e, passwd: n, login_token: i, userVariables: a, reconnection: o, loginParams: {}, "User-Agent": { sdkVersion: We, data: navigator.userAgent } };
665
+ s && (l.sessid = s), this.buildRequest({ method: this.method, params: l });
666
+ }
667
+ }
668
+ class Qn extends Z {
669
+ constructor(e, n) {
670
+ super(), this.buildRequest({ id: e, result: { method: n } });
671
+ }
672
+ }
673
+ class Et extends Z {
674
+ toString() {
675
+ return $.Invite;
676
+ }
677
+ }
678
+ class Tt extends Z {
679
+ toString() {
680
+ return $.Answer;
681
+ }
682
+ }
683
+ class ot extends Z {
684
+ toString() {
685
+ return $.Attach;
686
+ }
687
+ }
688
+ class Xn extends Z {
689
+ toString() {
690
+ return $.Bye;
691
+ }
692
+ }
693
+ class on extends Z {
694
+ toString() {
695
+ return $.Candidate;
696
+ }
697
+ }
698
+ class Zn extends Z {
699
+ toString() {
700
+ return $.EndOfCandidates;
701
+ }
702
+ }
703
+ class Qe extends Z {
704
+ toString() {
705
+ return $.Modify;
706
+ }
707
+ }
708
+ class At extends Z {
709
+ toString() {
710
+ return $.Info;
711
+ }
712
+ }
713
+ class ei extends Z {
714
+ toString() {
715
+ return $.Broadcast;
716
+ }
717
+ }
718
+ class ti extends Z {
719
+ toString() {
720
+ return $.Subscribe;
721
+ }
722
+ }
723
+ class ni extends Z {
724
+ toString() {
725
+ return $.Unsubscribe;
726
+ }
727
+ }
728
+ class ii extends Re {
729
+ constructor(e, n) {
730
+ super(), this.method = "ai_conversation", this.buildRequest({ method: this.method, params: { type: "conversation.item.create", previous_item_id: null, item: { id: ve(), type: "message", role: "user", content: [{ type: "input_text", text: e }, ...n?.map(((i) => ({ type: "image_url", image_url: { url: i } })))] } } });
731
+ }
732
+ }
733
+ var Oe, rn = Jt((function(t, e) {
734
+ var n;
735
+ function i() {
736
+ }
737
+ function s() {
738
+ s.init.call(this);
739
+ }
740
+ function a(r) {
741
+ return r._maxListeners === void 0 ? s.defaultMaxListeners : r._maxListeners;
742
+ }
743
+ function o(r, c, u, g) {
744
+ var b, T, I;
745
+ if (typeof u != "function") throw new TypeError('"listener" argument must be a function');
746
+ if ((T = r._events) ? (T.newListener && (r.emit("newListener", c, u.listener ? u.listener : u), T = r._events), I = T[c]) : (T = r._events = new i(), r._eventsCount = 0), I) {
747
+ if (typeof I == "function" ? I = T[c] = g ? [u, I] : [I, u] : g ? I.unshift(u) : I.push(u), !I.warned && (b = a(r)) && 0 < b && I.length > b) {
748
+ I.warned = !0;
749
+ var R = new Error("Possible EventEmitter memory leak detected. " + I.length + " " + c + " listeners added. Use emitter.setMaxListeners() to increase limit");
750
+ R.name = "MaxListenersExceededWarning", R.emitter = r, R.type = c, R.count = I.length, (function(j) {
751
+ typeof console.warn == "function" ? console.warn(j) : console.log(j);
752
+ })(R);
753
+ }
754
+ } else I = T[c] = u, ++r._eventsCount;
755
+ return r;
756
+ }
757
+ function l(r, c, u) {
758
+ function g() {
759
+ r.removeListener(c, g), b || (b = !0, u.apply(r, arguments));
760
+ }
761
+ var b = !1;
762
+ return g.listener = u, g;
763
+ }
764
+ function d(r) {
765
+ var c = this._events;
766
+ if (c) {
767
+ var u = c[r];
768
+ if (typeof u == "function") return 1;
769
+ if (u) return u.length;
770
+ }
771
+ return 0;
772
+ }
773
+ function h(r, c) {
774
+ for (var u = Array(c); c--; ) u[c] = r[c];
775
+ return u;
776
+ }
777
+ Object.defineProperty(e, "__esModule", { value: !0 }), i.prototype = /* @__PURE__ */ Object.create(null), s.EventEmitter = s, s.usingDomains = !1, s.prototype.domain = void 0, s.prototype._events = void 0, s.prototype._maxListeners = void 0, s.defaultMaxListeners = 10, s.init = function() {
778
+ this.domain = null, s.usingDomains && n.active && !(this instanceof n.Domain) && (this.domain = n.active), this._events && this._events !== Object.getPrototypeOf(this)._events || (this._events = new i(), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
779
+ }, s.prototype.setMaxListeners = function(r) {
780
+ if (typeof r != "number" || 0 > r || isNaN(r)) throw new TypeError('"n" argument must be a positive number');
781
+ return this._maxListeners = r, this;
782
+ }, s.prototype.getMaxListeners = function() {
783
+ return a(this);
784
+ }, s.prototype.emit = function(r) {
785
+ var c, u, g, b, T, I, R, j = r === "error";
786
+ if (I = this._events) j = j && I.error == null;
787
+ else if (!j) return !1;
788
+ if (R = this.domain, j) {
789
+ if (c = arguments[1], !R) {
790
+ if (c instanceof Error) throw c;
791
+ var ee = new Error('Uncaught, unspecified "error" event. (' + c + ")");
792
+ throw ee.context = c, ee;
793
+ }
794
+ return c || (c = new Error('Uncaught, unspecified "error" event')), c.domainEmitter = this, c.domain = R, c.domainThrown = !1, R.emit("error", c), !1;
795
+ }
796
+ if (!(u = I[r])) return !1;
797
+ var ne = typeof u == "function";
798
+ switch (g = arguments.length) {
799
+ case 1:
800
+ (function(G, v, M) {
801
+ if (v) G.call(M);
802
+ else for (var U = G.length, V = h(G, U), Y = 0; Y < U; ++Y) V[Y].call(M);
803
+ })(u, ne, this);
804
+ break;
805
+ case 2:
806
+ (function(G, v, M, U) {
807
+ if (v) G.call(M, U);
808
+ else for (var V = G.length, Y = h(G, V), Q = 0; Q < V; ++Q) Y[Q].call(M, U);
809
+ })(u, ne, this, arguments[1]);
810
+ break;
811
+ case 3:
812
+ (function(G, v, M, U, V) {
813
+ if (v) G.call(M, U, V);
814
+ else for (var Y = G.length, Q = h(G, Y), W = 0; W < Y; ++W) Q[W].call(M, U, V);
815
+ })(u, ne, this, arguments[1], arguments[2]);
816
+ break;
817
+ case 4:
818
+ (function(G, v, M, U, V, Y) {
819
+ if (v) G.call(M, U, V, Y);
820
+ else for (var Q = G.length, W = h(G, Q), re = 0; re < Q; ++re) W[re].call(M, U, V, Y);
821
+ })(u, ne, this, arguments[1], arguments[2], arguments[3]);
822
+ break;
823
+ default:
824
+ for (b = Array(g - 1), T = 1; T < g; T++) b[T - 1] = arguments[T];
825
+ (function(G, v, M, U) {
826
+ if (v) G.apply(M, U);
827
+ else for (var V = G.length, Y = h(G, V), Q = 0; Q < V; ++Q) Y[Q].apply(M, U);
828
+ })(u, ne, this, b);
829
+ }
830
+ return !0;
831
+ }, s.prototype.addListener = function(r, c) {
832
+ return o(this, r, c, !1);
833
+ }, s.prototype.on = s.prototype.addListener, s.prototype.prependListener = function(r, c) {
834
+ return o(this, r, c, !0);
835
+ }, s.prototype.once = function(r, c) {
836
+ if (typeof c != "function") throw new TypeError('"listener" argument must be a function');
837
+ return this.on(r, l(this, r, c)), this;
838
+ }, s.prototype.prependOnceListener = function(r, c) {
839
+ if (typeof c != "function") throw new TypeError('"listener" argument must be a function');
840
+ return this.prependListener(r, l(this, r, c)), this;
841
+ }, s.prototype.removeListener = function(r, c) {
842
+ var u, g, b, T, I;
843
+ if (typeof c != "function") throw new TypeError('"listener" argument must be a function');
844
+ if (!(g = this._events)) return this;
845
+ if (!(u = g[r])) return this;
846
+ if (u === c || u.listener && u.listener === c) --this._eventsCount == 0 ? this._events = new i() : (delete g[r], g.removeListener && this.emit("removeListener", r, u.listener || c));
847
+ else if (typeof u != "function") {
848
+ for (b = -1, T = u.length; 0 < T--; ) if (u[T] === c || u[T].listener && u[T].listener === c) {
849
+ I = u[T].listener, b = T;
850
+ break;
851
+ }
852
+ if (0 > b) return this;
853
+ if (u.length === 1) {
854
+ if (u[0] = void 0, --this._eventsCount == 0) return this._events = new i(), this;
855
+ delete g[r];
856
+ } else (function(R, j) {
857
+ for (var ee = j, ne = ee + 1, G = R.length; ne < G; ee += 1, ne += 1) R[ee] = R[ne];
858
+ R.pop();
859
+ })(u, b);
860
+ g.removeListener && this.emit("removeListener", r, I || c);
861
+ }
862
+ return this;
863
+ }, s.prototype.removeAllListeners = function(r) {
864
+ var c, u;
865
+ if (!(u = this._events)) return this;
866
+ if (!u.removeListener) return arguments.length === 0 ? (this._events = new i(), this._eventsCount = 0) : u[r] && (--this._eventsCount == 0 ? this._events = new i() : delete u[r]), this;
867
+ if (arguments.length === 0) {
868
+ for (var g, b = Object.keys(u), T = 0; T < b.length; ++T) (g = b[T]) !== "removeListener" && this.removeAllListeners(g);
869
+ return this.removeAllListeners("removeListener"), this._events = new i(), this._eventsCount = 0, this;
870
+ }
871
+ if (typeof (c = u[r]) == "function") this.removeListener(r, c);
872
+ else if (c) do
873
+ this.removeListener(r, c[c.length - 1]);
874
+ while (c[0]);
875
+ return this;
876
+ }, s.prototype.listeners = function(r) {
877
+ var c, u, g = this._events;
878
+ return g ? u = (c = g[r]) ? typeof c == "function" ? [c.listener || c] : (function(b) {
879
+ for (var T = Array(b.length), I = 0; I < T.length; ++I) T[I] = b[I].listener || b[I];
880
+ return T;
881
+ })(c) : [] : u = [], u;
882
+ }, s.listenerCount = function(r, c) {
883
+ return typeof r.listenerCount == "function" ? r.listenerCount(c) : d.call(r, c);
884
+ }, s.prototype.listenerCount = d, s.prototype.eventNames = function() {
885
+ return 0 < this._eventsCount ? Reflect.ownKeys(this._events) : [];
886
+ };
887
+ var f, m = new Uint8Array(16);
888
+ function S() {
889
+ if (!f && !(f = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto < "u" && typeof msCrypto.getRandomValues == "function" && msCrypto.getRandomValues.bind(msCrypto))) throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
890
+ return f(m);
891
+ }
892
+ for (var w = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i, C = [], k = 0; 256 > k; ++k) C.push((k + 256).toString(16).substr(1));
893
+ function p(r) {
894
+ var c = 1 < arguments.length && arguments[1] !== void 0 ? arguments[1] : 0, u = (C[r[c + 0]] + C[r[c + 1]] + C[r[c + 2]] + C[r[c + 3]] + "-" + C[r[c + 4]] + C[r[c + 5]] + "-" + C[r[c + 6]] + C[r[c + 7]] + "-" + C[r[c + 8]] + C[r[c + 9]] + "-" + C[r[c + 10]] + C[r[c + 11]] + C[r[c + 12]] + C[r[c + 13]] + C[r[c + 14]] + C[r[c + 15]]).toLowerCase();
895
+ if (!(function(g) {
896
+ return typeof g == "string" && w.test(g);
897
+ })(u)) throw TypeError("Stringified UUID is invalid");
898
+ return u;
899
+ }
900
+ function _(r, c, u) {
901
+ var g = (r = r || {}).random || (r.rng || S)();
902
+ return g[6] = 64 | 15 & g[6], g[8] = 128 | 63 & g[8], p(g);
903
+ }
904
+ function A(r, c) {
905
+ if (!r || !c) return {};
906
+ const u = { ...r };
907
+ if (u.localCandidateId) {
908
+ const g = c.get(u.localCandidateId);
909
+ u.local = { ...g };
910
+ }
911
+ if (u.remoteCandidateId) {
912
+ const g = c.get(u.remoteCandidateId);
913
+ u.remote = { ...g };
914
+ }
915
+ return u;
916
+ }
917
+ function E(r, c, u) {
918
+ return 8 * (function(g, b, T) {
919
+ const I = g[T], R = b ? b[T] : null;
920
+ return I === null || R === null ? null : (I - R) / (g.timestamp - b.timestamp) * 1e3;
921
+ })(r, c, u);
922
+ }
923
+ function P(r) {
924
+ if (!r.entries) return r;
925
+ const c = {};
926
+ return r.forEach((function(u, g) {
927
+ c[g] = u;
928
+ })), c;
929
+ }
930
+ function D(r, c, u = {}) {
931
+ if (!r) return null;
932
+ let g = { audio: { inbound: [], outbound: [] }, video: { inbound: [], outbound: [] }, connection: { inbound: [], outbound: [] } };
933
+ u.remote && (g.remote = { audio: { inbound: [], outbound: [] }, video: { inbound: [], outbound: [] } });
934
+ for (const b of r.values()) switch (b.type) {
935
+ case "outbound-rtp": {
936
+ const T = b.mediaType || b.kind, I = {};
937
+ let R = {};
938
+ if (!["audio", "video"].includes(T)) continue;
939
+ if (b.codecId) {
940
+ const j = r.get(b.codecId);
941
+ j && (I.clockRate = j.clockRate, I.mimeType = j.mimeType, I.payloadType = j.payloadType);
942
+ }
943
+ R = r.get(b.mediaSourceId) || r.get(b.trackId) || {}, g[T].outbound.push({ ...b, ...I, track: { ...R } });
944
+ break;
945
+ }
946
+ case "inbound-rtp": {
947
+ let T = b.mediaType || b.kind, I = {};
948
+ const R = {};
949
+ if (!["audio", "video"].includes(T)) if (b.id.includes("Video")) T = "video";
950
+ else {
951
+ if (!b.id.includes("Audio")) continue;
952
+ T = "audio";
953
+ }
954
+ if (b.codecId) {
955
+ const j = r.get(b.codecId);
956
+ j && (R.clockRate = j.clockRate, R.mimeType = j.mimeType, R.payloadType = j.payloadType);
957
+ }
958
+ if (!g.connection.id && b.transportId) {
959
+ const j = r.get(b.transportId);
960
+ if (j && j.selectedCandidatePairId) {
961
+ const ee = r.get(j.selectedCandidatePairId);
962
+ g.connection = A(ee, r);
963
+ }
964
+ }
965
+ I = r.get(b.mediaSourceId) || r.get(b.trackId) || {}, g[T].inbound.push({ ...b, ...R, track: { ...I } });
966
+ break;
967
+ }
968
+ case "peer-connection":
969
+ g.connection.dataChannelsClosed = b.dataChannelsClosed, g.connection.dataChannelsOpened = b.dataChannelsOpened;
970
+ break;
971
+ case "remote-inbound-rtp": {
972
+ if (!u.remote) break;
973
+ let T = b.mediaType || b.kind;
974
+ const I = {};
975
+ if (!["audio", "video"].includes(T)) if (b.id.includes("Video")) T = "video";
976
+ else {
977
+ if (!b.id.includes("Audio")) continue;
978
+ T = "audio";
979
+ }
980
+ if (b.codecId) {
981
+ const R = r.get(b.codecId);
982
+ R && (I.clockRate = R.clockRate, I.mimeType = R.mimeType, I.payloadType = R.payloadType);
983
+ }
984
+ if (!g.connection.id && b.transportId) {
985
+ const R = r.get(b.transportId);
986
+ if (R && R.selectedCandidatePairId) {
987
+ const j = r.get(R.selectedCandidatePairId);
988
+ g.connection = A(j, r);
989
+ }
990
+ }
991
+ g.remote[T].inbound.push({ ...b, ...I });
992
+ break;
993
+ }
994
+ case "remote-outbound-rtp": {
995
+ if (!u.remote) break;
996
+ const T = b.mediaType || b.kind, I = {};
997
+ if (!["audio", "video"].includes(T)) continue;
998
+ if (b.codecId) {
999
+ const R = r.get(b.codecId);
1000
+ R && (I.clockRate = R.clockRate, I.mimeType = R.mimeType, I.payloadType = R.payloadType);
1001
+ }
1002
+ g.remote[T].outbound.push({ ...b, ...I });
1003
+ break;
1004
+ }
1005
+ }
1006
+ if (!g.connection.id) for (const b of r.values()) b.type === "candidate-pair" && b.nominated && b.state === "succeeded" && (g.connection = A(b, r));
1007
+ return g = (function(b, T) {
1008
+ return T && (b.audio.inbound.map(((I) => {
1009
+ let R = T.audio.inbound.find(((j) => j.id === I.id));
1010
+ I.bitrate = E(I, R, "bytesReceived"), I.packetRate = E(I, R, "packetsReceived");
1011
+ })), b.audio.outbound.map(((I) => {
1012
+ let R = T.audio.outbound.find(((j) => j.id === I.id));
1013
+ I.bitrate = E(I, R, "bytesSent"), I.packetRate = E(I, R, "packetsSent");
1014
+ })), b.video.inbound.map(((I) => {
1015
+ let R = T.video.inbound.find(((j) => j.id === I.id));
1016
+ I.bitrate = E(I, R, "bytesReceived"), I.packetRate = E(I, R, "packetsReceived");
1017
+ })), b.video.outbound.map(((I) => {
1018
+ let R = T.video.outbound.find(((j) => j.id === I.id));
1019
+ I.bitrate = E(I, R, "bytesSent"), I.packetRate = E(I, R, "packetsSent");
1020
+ }))), b;
1021
+ })(g, c), g;
1022
+ }
1023
+ let q, B = {}, x = [];
1024
+ e.WebRTCStats = class extends s {
1025
+ constructor(r) {
1026
+ if (super(), this.monitoringSetInterval = 0, this.connectionMonitoringSetInterval = 0, this.connectionMonitoringInterval = 1e3, this.remote = !0, this.peersToMonitor = {}, this.timeline = [], this.statsToMonitor = ["inbound-rtp", "outbound-rtp", "remote-inbound-rtp", "remote-outbound-rtp", "peer-connection", "data-channel", "stream", "track", "sender", "receiver", "transport", "candidate-pair", "local-candidate", "remote-candidate"], typeof window > "u") throw new Error("WebRTCStats only works in browser");
1027
+ const c = { ...r };
1028
+ this.isEdge = !!window.RTCIceGatherer, this.getStatsInterval = c.getStatsInterval || 1e3, this.rawStats = !!c.rawStats, this.statsObject = !!c.statsObject, this.filteredStats = !!c.filteredStats, this.shouldWrapGetUserMedia = !!c.wrapGetUserMedia, typeof c.remote == "boolean" && (this.remote = c.remote), this.debug = !!c.debug, this.logLevel = c.logLevel || "none", this.shouldWrapGetUserMedia && this.wrapGetUserMedia();
1029
+ }
1030
+ async addPeer(r, c) {
1031
+ return console.warn("The addPeer() method has been deprecated, please use addConnection()"), this.addConnection({ peerId: r, pc: c });
1032
+ }
1033
+ async addConnection(r) {
1034
+ const { pc: c, peerId: u } = r;
1035
+ let { connectionId: g, remote: b } = r;
1036
+ if (b = typeof b == "boolean" ? b : this.remote, !(c && c instanceof RTCPeerConnection)) throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");
1037
+ if (!u) throw new Error("Missing argument peerId");
1038
+ if (this.isEdge) throw new Error("Can't monitor peers in Edge at this time.");
1039
+ if (this.peersToMonitor[u]) {
1040
+ if (g && g in this.peersToMonitor[u]) throw new Error(`We are already monitoring connection with id ${g}.`);
1041
+ for (let I in this.peersToMonitor[u]) {
1042
+ const R = this.peersToMonitor[u][I];
1043
+ if (R.pc === c) throw new Error(`We are already monitoring peer with id ${u}.`);
1044
+ R.pc.connectionState === "closed" && this.removeConnection({ pc: R.pc });
1045
+ }
1046
+ }
1047
+ const T = c.getConfiguration();
1048
+ return T.iceServers && T.iceServers.forEach((function(I) {
1049
+ delete I.credential;
1050
+ })), g || (g = _()), this.emitEvent({ event: "addConnection", tag: "peer", peerId: u, connectionId: g, data: { options: r, peerConfiguration: T } }), this.monitorPeer({ peerId: u, connectionId: g, pc: c, remote: b }), { connectionId: g };
1051
+ }
1052
+ getTimeline(r) {
1053
+ return this.timeline = this.timeline.sort(((c, u) => c.timestamp.getTime() - u.timestamp.getTime())), r ? this.timeline.filter(((c) => c.tag === r)) : this.timeline;
1054
+ }
1055
+ get logger() {
1056
+ const r = (c) => {
1057
+ const u = ["none", "error", "warn", "info", "debug"];
1058
+ return u.slice(0, u.indexOf(this.logLevel) + 1).indexOf(c) > -1;
1059
+ };
1060
+ return { error(...c) {
1061
+ this.debug && r("error") && console.error("[webrtc-stats][error] ", ...c);
1062
+ }, warn(...c) {
1063
+ this.debug && r("warn") && console.warn("[webrtc-stats][warn] ", ...c);
1064
+ }, info(...c) {
1065
+ this.debug && r("info") && console.log("[webrtc-stats][info] ", ...c);
1066
+ }, debug(...c) {
1067
+ this.debug && r("debug") && console.debug("[webrtc-stats][debug] ", ...c);
1068
+ } };
1069
+ }
1070
+ removeConnection(r) {
1071
+ let c, { connectionId: u, pc: g } = r;
1072
+ if (!g && !u) throw new Error("Missing arguments. You need to either send pc or a connectionId.");
1073
+ if (u) {
1074
+ if (typeof u != "string") throw new Error("connectionId must be a string.");
1075
+ for (let b in this.peersToMonitor) u in this.peersToMonitor[b] && (g = this.peersToMonitor[b][u].pc, c = b);
1076
+ } else if (g) {
1077
+ if (!(g instanceof RTCPeerConnection)) throw new Error("pc must be an instance of RTCPeerConnection.");
1078
+ for (let b in this.peersToMonitor) for (let T in this.peersToMonitor[b]) this.peersToMonitor[b][T].pc === g && (u = T, c = b);
1079
+ }
1080
+ if (!g || !u) throw new Error("Could not find the desired connection.");
1081
+ return this.removePeerConnectionEventListeners(u, g), delete this.peersToMonitor[c][u], Object.values(this.peersToMonitor[c]).length === 0 && delete this.peersToMonitor[c], { connectionId: u };
1082
+ }
1083
+ removeAllPeers() {
1084
+ for (let r in this.peersToMonitor) this.removePeer(r);
1085
+ }
1086
+ removePeer(r) {
1087
+ if (this.logger.info(`Removing PeerConnection with id ${r}.`), this.peersToMonitor[r]) {
1088
+ for (let c in this.peersToMonitor[r]) {
1089
+ let u = this.peersToMonitor[r][c].pc;
1090
+ this.removePeerConnectionEventListeners(c, u);
1091
+ }
1092
+ delete this.peersToMonitor[r];
1093
+ }
1094
+ }
1095
+ destroy() {
1096
+ this.removeAllPeers(), x.forEach(((r) => {
1097
+ this.removeTrackEventListeners(r);
1098
+ })), x = [], this.shouldWrapGetUserMedia && q && (navigator.mediaDevices.getUserMedia = q);
1099
+ }
1100
+ monitorPeer(r) {
1101
+ let { peerId: c, connectionId: u, pc: g, remote: b } = r;
1102
+ if (!g) return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");
1103
+ const T = { pc: g, connectionId: u, stream: null, stats: { parsed: null, raw: null }, options: { remote: b } };
1104
+ if (this.peersToMonitor[c]) {
1105
+ if (u in this.peersToMonitor[c]) return void this.logger.warn(`Already watching connection with ID ${u}`);
1106
+ this.peersToMonitor[c][u] = T;
1107
+ } else this.peersToMonitor[c] = { [u]: T };
1108
+ this.addPeerConnectionEventListeners(c, u, g), this.numberOfMonitoredPeers === 1 && (this.startStatsMonitoring(), this.startConnectionStateMonitoring());
1109
+ }
1110
+ startStatsMonitoring() {
1111
+ this.monitoringSetInterval || (this.monitoringSetInterval = window.setInterval((() => {
1112
+ this.numberOfMonitoredPeers || this.stopStatsMonitoring(), this.getStats().then(((r) => {
1113
+ r.forEach(((c) => {
1114
+ this.emitEvent(c);
1115
+ }));
1116
+ }));
1117
+ }), this._getStatsInterval));
1118
+ }
1119
+ stopStatsMonitoring() {
1120
+ this.monitoringSetInterval && (window.clearInterval(this.monitoringSetInterval), this.monitoringSetInterval = 0);
1121
+ }
1122
+ async getStats(r = null) {
1123
+ this.logger.info(r ? `Getting stats from peer ${r}` : "Getting stats from all peers");
1124
+ let c = {};
1125
+ if (r) {
1126
+ if (!this.peersToMonitor[r]) throw new Error(`Cannot get stats. Peer with id ${r} does not exist`);
1127
+ c[r] = this.peersToMonitor[r];
1128
+ } else c = this.peersToMonitor;
1129
+ let u = [];
1130
+ for (const g in c) for (const b in c[g]) {
1131
+ const T = c[g][b], I = T.pc;
1132
+ if (I && !this.checkIfConnectionIsClosed(g, b, I)) try {
1133
+ const R = this.getTimestamp(), j = I.getStats(null);
1134
+ if (j) {
1135
+ const ee = await j, ne = this.getTimestamp(), G = P(ee), v = { remote: T.options.remote }, M = D(ee, T.stats.parsed, v), U = { event: "stats", tag: "stats", peerId: g, connectionId: b, timeTaken: ne - R, data: M };
1136
+ this.rawStats === !0 && (U.rawStats = ee), this.statsObject === !0 && (U.statsObject = G), this.filteredStats === !0 && (U.filteredStats = this.filteroutStats(G)), u.push(U), T.stats.parsed = M;
1137
+ } else this.logger.error(`PeerConnection from peer ${g} did not return any stats data`);
1138
+ } catch (R) {
1139
+ this.logger.error(R);
1140
+ }
1141
+ }
1142
+ return u;
1143
+ }
1144
+ startConnectionStateMonitoring() {
1145
+ this.connectionMonitoringSetInterval = window.setInterval((() => {
1146
+ this.numberOfMonitoredPeers || this.stopConnectionStateMonitoring();
1147
+ for (const r in this.peersToMonitor) for (const c in this.peersToMonitor[r]) {
1148
+ const u = this.peersToMonitor[r][c].pc;
1149
+ this.checkIfConnectionIsClosed(r, c, u);
1150
+ }
1151
+ }), this.connectionMonitoringInterval);
1152
+ }
1153
+ checkIfConnectionIsClosed(r, c, u) {
1154
+ const g = this.isConnectionClosed(u);
1155
+ if (g) {
1156
+ this.removeConnection({ pc: u });
1157
+ let b = u.connectionState === "closed" ? "onconnectionstatechange" : "oniceconnectionstatechange";
1158
+ this.emitEvent({ event: b, peerId: r, connectionId: c, tag: "connection", data: "closed" });
1159
+ }
1160
+ return g;
1161
+ }
1162
+ isConnectionClosed(r) {
1163
+ return r.connectionState === "closed" || r.iceConnectionState === "closed";
1164
+ }
1165
+ stopConnectionStateMonitoring() {
1166
+ this.connectionMonitoringSetInterval && (window.clearInterval(this.connectionMonitoringSetInterval), this.connectionMonitoringSetInterval = 0);
1167
+ }
1168
+ wrapGetUserMedia() {
1169
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");
1170
+ this.logger.info("Wrapping getUsermedia functions."), q = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
1171
+ const r = this.parseGetUserMedia.bind(this);
1172
+ navigator.mediaDevices.getUserMedia = (function() {
1173
+ return r({ constraints: arguments[0] }), q.apply(navigator.mediaDevices, arguments).then(((c) => (r({ stream: c }), c)), ((c) => (r({ error: c }), Promise.reject(c))));
1174
+ }).bind(navigator.mediaDevices);
1175
+ }
1176
+ filteroutStats(r = {}) {
1177
+ const c = { ...r };
1178
+ for (const g in c) {
1179
+ var u = c[g];
1180
+ this.statsToMonitor.includes(u.type) || delete c[g];
1181
+ }
1182
+ return c;
1183
+ }
1184
+ get peerConnectionListeners() {
1185
+ return { icecandidate: (r, c, u, g) => {
1186
+ this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}", g), this.emitEvent({ event: "onicecandidate", tag: "connection", peerId: r, connectionId: c, data: g.candidate });
1187
+ }, track: (r, c, u, g) => {
1188
+ this.logger.debug(`[pc-event] track | peerId: ${r}`, g);
1189
+ const b = g.track, T = g.streams[0];
1190
+ r in this.peersToMonitor && c in this.peersToMonitor[r] && (this.peersToMonitor[r][c].stream = T), this.addTrackEventListeners(b, c), this.emitEvent({ event: "ontrack", tag: "track", peerId: r, connectionId: c, data: { stream: T ? this.getStreamDetails(T) : null, track: b ? this.getMediaTrackDetails(b) : null, title: g.track.kind + ":" + g.track.id + " " + g.streams.map((function(I) {
1191
+ return "stream:" + I.id;
1192
+ })) } });
1193
+ }, signalingstatechange: (r, c, u) => {
1194
+ this.logger.debug(`[pc-event] signalingstatechange | peerId: ${r}`), this.emitEvent({ event: "onsignalingstatechange", tag: "connection", peerId: r, connectionId: c, data: { signalingState: u.signalingState, localDescription: u.localDescription, remoteDescription: u.remoteDescription } });
1195
+ }, iceconnectionstatechange: (r, c, u) => {
1196
+ this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${r}`), this.emitEvent({ event: "oniceconnectionstatechange", tag: "connection", peerId: r, connectionId: c, data: u.iceConnectionState });
1197
+ }, icegatheringstatechange: (r, c, u) => {
1198
+ this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${r}`), this.emitEvent({ event: "onicegatheringstatechange", tag: "connection", peerId: r, connectionId: c, data: u.iceGatheringState });
1199
+ }, icecandidateerror: (r, c, u, g) => {
1200
+ this.logger.debug(`[pc-event] icecandidateerror | peerId: ${r}`), this.emitEvent({ event: "onicecandidateerror", tag: "connection", peerId: r, connectionId: c, error: { errorCode: g.errorCode } });
1201
+ }, connectionstatechange: (r, c, u) => {
1202
+ this.logger.debug(`[pc-event] connectionstatechange | peerId: ${r}`), this.emitEvent({ event: "onconnectionstatechange", tag: "connection", peerId: r, connectionId: c, data: u.connectionState });
1203
+ }, negotiationneeded: (r, c, u) => {
1204
+ this.logger.debug(`[pc-event] negotiationneeded | peerId: ${r}`), this.emitEvent({ event: "onnegotiationneeded", tag: "connection", peerId: r, connectionId: c });
1205
+ }, datachannel: (r, c, u, g) => {
1206
+ this.logger.debug(`[pc-event] datachannel | peerId: ${r}`, g), this.emitEvent({ event: "ondatachannel", tag: "datachannel", peerId: r, connectionId: c, data: g.channel });
1207
+ } };
1208
+ }
1209
+ addPeerConnectionEventListeners(r, c, u) {
1210
+ this.logger.debug(`Adding event listeners for peer ${r} and connection ${c}.`), B[c] = {}, Object.keys(this.peerConnectionListeners).forEach(((g) => {
1211
+ B[c][g] = this.peerConnectionListeners[g].bind(this, r, c, u), u.addEventListener(g, B[c][g], !1);
1212
+ }));
1213
+ }
1214
+ parseGetUserMedia(r) {
1215
+ try {
1216
+ const c = { event: "getUserMedia", tag: "getUserMedia", data: { ...r } };
1217
+ r.stream && (c.data.details = this.parseStream(r.stream), r.stream.getTracks().map(((u) => {
1218
+ this.addTrackEventListeners(u), x.push(u);
1219
+ }))), this.emitEvent(c);
1220
+ } catch {
1221
+ }
1222
+ }
1223
+ parseStream(r) {
1224
+ const c = { audio: [], video: [] };
1225
+ return r.getTracks().forEach(((u) => {
1226
+ c[u.kind].push(this.getMediaTrackDetails(u));
1227
+ })), c;
1228
+ }
1229
+ getMediaTrackDetails(r) {
1230
+ return { enabled: r.enabled, id: r.id, contentHint: r.contentHint, kind: r.kind, label: r.label, muted: r.muted, readyState: r.readyState, constructorName: r.constructor.name, capabilities: r.getCapabilities ? r.getCapabilities() : {}, constraints: r.getConstraints ? r.getConstraints() : {}, settings: r.getSettings ? r.getSettings() : {}, _track: r };
1231
+ }
1232
+ getStreamDetails(r) {
1233
+ return { active: r.active, id: r.id, _stream: r };
1234
+ }
1235
+ getTrackEventObject(r) {
1236
+ return { mute: (c) => {
1237
+ this.emitEvent({ event: "mute", tag: "track", connectionId: r, data: { event: c } });
1238
+ }, unmute: (c) => {
1239
+ this.emitEvent({ event: "unmute", tag: "track", connectionId: r, data: { event: c } });
1240
+ }, overconstrained: (c) => {
1241
+ this.emitEvent({ event: "overconstrained", tag: "track", connectionId: r, data: { event: c } });
1242
+ }, ended: (c) => {
1243
+ this.emitEvent({ event: "ended", tag: "track", connectionId: r, data: { event: c } }), this.removeTrackEventListeners(c.target);
1244
+ } };
1245
+ }
1246
+ addTrackEventListeners(r, c) {
1247
+ B[r.id] = {};
1248
+ const u = this.getTrackEventObject(c);
1249
+ Object.keys(u).forEach(((g) => {
1250
+ B[r.id][g] = u[g].bind(this), r.addEventListener(g, B[r.id][g]);
1251
+ })), B[r.id].readyState = setInterval((() => {
1252
+ if (r.readyState === "ended") {
1253
+ let g = new CustomEvent("ended", { detail: { check: "readyState" } });
1254
+ r.dispatchEvent(g);
1255
+ }
1256
+ }), 1e3);
1257
+ }
1258
+ removeTrackEventListeners(r) {
1259
+ if (r.id in B) {
1260
+ const c = this.getTrackEventObject();
1261
+ Object.keys(c).forEach(((u) => {
1262
+ r.removeEventListener(u, B[r.id][u]);
1263
+ })), clearInterval(B[r.id].readyState), delete B[r.id];
1264
+ }
1265
+ }
1266
+ addToTimeline(r) {
1267
+ this.timeline.push(r), this.emit("timeline", r);
1268
+ }
1269
+ emitEvent(r) {
1270
+ const c = { ...r, timestamp: /* @__PURE__ */ new Date() };
1271
+ this.addToTimeline(c), c.tag && this.emit(c.tag, c);
1272
+ }
1273
+ set getStatsInterval(r) {
1274
+ if (!Number.isInteger(r)) throw new Error(`getStatsInterval should be an integer, got: ${r}`);
1275
+ this._getStatsInterval = r, this.monitoringSetInterval && (this.stopStatsMonitoring(), this.startStatsMonitoring());
1276
+ }
1277
+ get numberOfMonitoredPeers() {
1278
+ return Object.keys(this.peersToMonitor).length;
1279
+ }
1280
+ removePeerConnectionEventListeners(r, c) {
1281
+ r in B && (Object.keys(this.peerConnectionListeners).forEach(((u) => {
1282
+ c.removeEventListener(u, B[r][u], !1);
1283
+ })), delete B[r]), c.getSenders().forEach(((u) => {
1284
+ u.track && this.removeTrackEventListeners(u.track);
1285
+ })), c.getReceivers().forEach(((u) => {
1286
+ u.track && this.removeTrackEventListeners(u.track);
1287
+ }));
1288
+ }
1289
+ getTimestamp() {
1290
+ return Date.now();
1291
+ }
1292
+ wrapGetDisplayMedia() {
1293
+ const r = this;
1294
+ if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
1295
+ const c = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices), u = function() {
1296
+ return r.debug("navigator.mediaDevices.getDisplayMedia", null, arguments[0]), c.apply(navigator.mediaDevices, arguments).then((function(g) {
1297
+ return g;
1298
+ }), (function(g) {
1299
+ return r.debug("navigator.mediaDevices.getDisplayMediaOnFailure", null, g.name), Promise.reject(g);
1300
+ }));
1301
+ };
1302
+ navigator.mediaDevices.getDisplayMedia = u.bind(navigator.mediaDevices);
1303
+ }
1304
+ }
1305
+ };
1306
+ }));
1307
+ (Oe = rn) && Oe.__esModule && Object.prototype.hasOwnProperty.call(Oe, "default") && Oe.default;
1308
+ var si = rn.WebRTCStats;
1309
+ function oi(t) {
1310
+ const { packetsLost: e, packetsReceived: n, jitter: i, rtt: s } = t, a = (function(h) {
1311
+ const { jitter: f, rtt: m } = h, S = f + m / 2;
1312
+ return 0.024 * S + 0.11 * (S - 177.3) * (S > 177.3 ? 1 : 0);
1313
+ })({ rtt: s, jitter: i }), o = (function(h) {
1314
+ const { packetsLost: f, packetsReceived: m } = h, S = f / (m + f) * 100;
1315
+ return 20 * Math.log(1 + S);
1316
+ })({ packetsLost: e, packetsReceived: n }), l = 93.2 - a - o + 0, d = 1 + 0.035 * l + 7e-6 * l * (l - 60) * (100 - l);
1317
+ return Math.min(Math.max(d, 1), 5);
1318
+ }
1319
+ function ri(t) {
1320
+ return isNaN(t) ? null : t > 4.2 ? "excellent" : t >= 4.1 && t <= 4.2 ? "good" : t >= 3.7 && t <= 4 ? "fair" : t >= 3.1 && t <= 3.6 ? "poor" : "bad";
1321
+ }
1322
+ class ai extends Re {
1323
+ constructor(e, n) {
1324
+ super(), this.buildRequest({ type: "debug_report_start", debug_report_id: e, debug_report_version: 1, call_id: n });
1325
+ }
1326
+ }
1327
+ class ci extends Re {
1328
+ constructor(e, n) {
1329
+ super(), this.buildRequest({ type: "debug_report_stop", debug_report_id: e, debug_report_version: 1, call_id: n });
1330
+ }
1331
+ }
1332
+ class li extends Re {
1333
+ constructor(e, n) {
1334
+ super(), this.buildRequest({ type: "debug_report_data", debug_report_id: e, debug_report_version: 1, debug_report_data: n });
1335
+ }
1336
+ }
1337
+ function Rt(t, e) {
1338
+ var n, i;
1339
+ return { errorCode: t.errorCode, errorText: t.errorText, url: t.url, address: t.address, port: t.port, connectionState: e.connectionState, iceConnectionState: e.iceConnectionState, iceGatheringState: e.iceGatheringState, signalingState: e.signalingState, localDescriptionType: (n = e.localDescription) === null || n === void 0 ? void 0 : n.type, remoteDescriptionType: (i = e.remoteDescription) === null || i === void 0 ? void 0 : i.type };
1340
+ }
1341
+ function di(t, e) {
1342
+ const n = ve(), i = new si({ getStatsInterval: 1e3, rawStats: !1, statsObject: !0, filteredStats: !1, remote: !0, debug: !1, logLevel: "warn" }), s = (a) => O(this, void 0, void 0, (function* () {
1343
+ a.event === "stats" && F(L.StatsFrame, (function({ data: o }) {
1344
+ var l, d, h, f, m, S, w, C;
1345
+ const { audio: k, remote: p } = o, { audio: _ } = p, A = (d = (l = _.inbound[0]) === null || l === void 0 ? void 0 : l.jitter) !== null && d !== void 0 ? d : 1 / 0, E = (f = (h = _.inbound[0]) === null || h === void 0 ? void 0 : h.roundTripTime) !== null && f !== void 0 ? f : 1 / 0, P = (S = (m = k.inbound[0]) === null || m === void 0 ? void 0 : m.packetsReceived) !== null && S !== void 0 ? S : -1, D = (C = (w = k.inbound[0]) === null || w === void 0 ? void 0 : w.packetsLost) !== null && C !== void 0 ? C : -1, q = oi({ jitter: 1e3 * A, rtt: 1e3 * E, packetsLost: D, packetsReceived: P });
1346
+ return { jitter: A, rtt: E, mos: q, quality: ri(q), inboundAudio: k.inbound[0], outboundAudio: k.outbound[0], remoteInboundAudio: _.inbound[0], remoteOutboundAudio: _.outbound[0] };
1347
+ })(a), t.uuid), yield t.execute(new li(n, a));
1348
+ }));
1349
+ return { start: (a, o, l) => O(this, void 0, void 0, (function* () {
1350
+ yield t.execute(new ai(n, e)), i.on("timeline", s), yield new Promise(((d) => setTimeout(d, 500))), i.addConnection({ pc: a, peerId: o, connectionId: l });
1351
+ })), stop: (a) => O(this, void 0, void 0, (function* () {
1352
+ const o = i.getTimeline();
1353
+ F(L.StatsReport, o, t.uuid), a === "file" && (function(l, d) {
1354
+ const h = new Blob([JSON.stringify(l)], { type: "application/json" }), f = URL.createObjectURL(h), m = document.createElement("a");
1355
+ m.href = f, m.download = `${d}.json`, m.click(), URL.revokeObjectURL(f);
1356
+ })(o, `webrtc-stats-${n}-${Date.now()}`), yield t.execute(new ci(n, e)), i.removeAllPeers(), i.destroy();
1357
+ })), reportConnectionStateChange: (a) => {
1358
+ const o = { event: "connectionstatechange-detailed", tag: "connection", timestamp: (/* @__PURE__ */ new Date()).toISOString(), data: a };
1359
+ s(o);
1360
+ }, reportIceCandidateError: (a) => {
1361
+ const o = { event: "icecandidateerror-detailed", tag: "connection", timestamp: (/* @__PURE__ */ new Date()).toISOString(), data: a };
1362
+ s(o);
1363
+ } };
1364
+ }
1365
+ const an = (t, e) => {
1366
+ const { contentType: n, canvasType: i, callID: s, canvasInfo: a = null, currentLayerIdx: o = -1 } = e;
1367
+ a && i !== "mcu-personal-canvas" && delete a.memberID;
1368
+ const l = { type: oe.conferenceUpdate, call: t.calls[s], canvasInfo: ui(a), currentLayerIdx: o };
1369
+ switch (n) {
1370
+ case "layer-info": {
1371
+ const d = Object.assign({ action: se.LayerInfo }, l);
1372
+ F(L.Notification, d, t.uuid);
1373
+ break;
1374
+ }
1375
+ case "layout-info": {
1376
+ const d = Object.assign({ action: se.LayoutInfo }, l);
1377
+ F(L.Notification, d, t.uuid);
1378
+ break;
1379
+ }
1380
+ }
1381
+ }, ui = (t) => {
1382
+ const e = JSON.stringify(t).replace(/memberID/g, "participantId").replace(/ID"/g, 'Id"').replace(/POS"/g, 'Pos"');
1383
+ return Yt(e);
1384
+ };
1385
+ class xt {
1386
+ constructor(e, n, i, s, a) {
1387
+ this.type = e, this.options = n, this.onSdpReadyTwice = null, this.statsReporter = null, this._negotiating = !1, this._prevConnectionState = null, this._restartedIceOnConnectionStateFailed = !1, this._sleepWakeupIntervalId = null, this.handleConnectionStateChange = (o) => O(this, void 0, void 0, (function* () {
1388
+ const { connectionState: l } = this.instance;
1389
+ if (y.info(`[${(/* @__PURE__ */ new Date()).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`), l === "failed" || l === "disconnected") {
1390
+ const d = () => O(this, void 0, void 0, (function* () {
1391
+ if (this.isDebugEnabled && this.statsReporter) {
1392
+ const h = yield (function(f, m) {
1393
+ return O(this, void 0, void 0, (function* () {
1394
+ const S = { connectionState: f.connectionState, previousConnectionState: m, iceConnectionState: f.iceConnectionState, iceGatheringState: f.iceGatheringState, signalingState: f.signalingState }, w = f.getTransceivers();
1395
+ if (w.length > 0) {
1396
+ const C = w[0].sender, k = C?.transport;
1397
+ k && (S.dtlsState = k.state);
1398
+ }
1399
+ f.sctp && (S.sctpState = f.sctp.state);
1400
+ try {
1401
+ const C = yield f.getStats();
1402
+ C.forEach(((k) => {
1403
+ k.type === "candidate-pair" && k.state === "succeeded" && (S.candidatePairState = k.state, C.forEach(((p) => {
1404
+ p.type === "local-candidate" && p.id === k.localCandidateId && (S.localCandidateType = p.candidateType, S.selectedCandidatePair = S.selectedCandidatePair || { local: {}, remote: {} }, S.selectedCandidatePair.local = { address: p.address, port: p.port, protocol: p.protocol, candidateType: p.candidateType }), p.type === "remote-candidate" && p.id === k.remoteCandidateId && (S.remoteCandidateType = p.candidateType, S.selectedCandidatePair = S.selectedCandidatePair || { local: {}, remote: {} }, S.selectedCandidatePair.remote = { address: p.address, port: p.port, protocol: p.protocol, candidateType: p.candidateType });
1405
+ }))), k.type === "transport" && (S.dtlsCipher = k.dtlsCipher, S.srtpCipher = k.srtpCipher, S.tlsVersion = k.tlsVersion, k.dtlsState && (S.dtlsState = k.dtlsState));
1406
+ }));
1407
+ } catch (C) {
1408
+ y.error("Error gathering connection state details:", C);
1409
+ }
1410
+ return S;
1411
+ }));
1412
+ })(this.instance, this._prevConnectionState);
1413
+ this.statsReporter.reportConnectionStateChange(h);
1414
+ }
1415
+ this._restartedIceOnConnectionStateFailed ? (y.debug("Peer Connection failed again after ICE restart. Recovering call via peer reconnection through error handling."), F(L.PeerConnectionFailureError, { error: new Error(`Peer Connection failed twice. previous state: ${this._prevConnectionState}, current state: ${l}`), sessionId: this._session.sessionid }, this.options.id)) : (this.instance.restartIce(), l === "failed" && (this._restartedIceOnConnectionStateFailed = !0, y.debug("ICE has been restarted on connection state failed.")), this._isTrickleIce() ? yield this.startTrickleIceNegotiation() : this.startNegotiation()), window.removeEventListener("online", d);
1416
+ }));
1417
+ navigator.onLine ? d() : window.addEventListener("online", d);
1418
+ }
1419
+ this._prevConnectionState === "connected" && l === "disconnected" && (yield this._resetJitterBuffer()), this._prevConnectionState === "disconnected" && l === "connected" && (yield this._resetJitterBuffer()), this._prevConnectionState = l, this._isTrickleIce() && (l === "connecting" && performance.mark("peer-connection-connecting"), l === "connected" && (performance.mark("peer-connection-connected"), console.group("Performance Metrics"), console.table(this.trickleIcePerformanceMetrics), console.groupEnd(), performance.clearMarks())), this._restartNegotiationOnDeviceSleepWakeup();
1420
+ })), this._handleIceConnectionStateChange = (o) => {
1421
+ y.debug(`[${(/* @__PURE__ */ new Date()).toISOString()}] ICE Connection State`, this.instance.iceConnectionState);
1422
+ }, this._handleIceGatheringStateChange = (o) => {
1423
+ y.debug(`[${(/* @__PURE__ */ new Date()).toISOString()}] ICE Gathering State`, this.instance.iceGatheringState);
1424
+ }, this._setCodecs = (o, l) => {
1425
+ if (o.setCodecPreferences) return o.setCodecPreferences(l);
1426
+ }, y.info("New Peer with type:", this.type, "Options:", this.options), this._constraints = { offerToReceiveAudio: !0, offerToReceiveVideo: !!n.video }, this._sdpReady = this._sdpReady.bind(this), this.handleSignalingStateChangeEvent = this.handleSignalingStateChangeEvent.bind(this), this.handleNegotiationNeededEvent = this.handleNegotiationNeededEvent.bind(this), this.handleTrackEvent = this.handleTrackEvent.bind(this), this.createPeerConnection = this.createPeerConnection.bind(this), this._session = i, this._trickleIceSdpFn = s, this._registerPeerEvents = a;
1427
+ }
1428
+ get isOffer() {
1429
+ return this.type === K.Offer;
1430
+ }
1431
+ get isAnswer() {
1432
+ return this.type === K.Answer;
1433
+ }
1434
+ get isDebugEnabled() {
1435
+ return this.options.debug || this._session.options.debug;
1436
+ }
1437
+ get debugOutput() {
1438
+ return this.options.debugOutput || this._session.options.debugOutput;
1439
+ }
1440
+ get keepConnectionAliveOnSocketClose() {
1441
+ return this.options.keepConnectionAliveOnSocketClose || this._session.options.keepConnectionAliveOnSocketClose;
1442
+ }
1443
+ startNegotiation() {
1444
+ performance.mark("ice-gathering-start"), this._negotiating = !0, this._isOffer() ? this._createOffer() : this._createAnswer();
1445
+ }
1446
+ startTrickleIceNegotiation() {
1447
+ return O(this, void 0, void 0, (function* () {
1448
+ performance.mark("ice-gathering-start"), this._negotiating = !0, this._isOffer() ? yield this._createOffer().then(this._trickleIceSdpFn.bind(this)) : yield this._createAnswer().then(this._trickleIceSdpFn.bind(this));
1449
+ }));
1450
+ }
1451
+ _logTransceivers() {
1452
+ y.info("Number of transceivers:", this.instance.getTransceivers().length), this.instance.getTransceivers().forEach(((e, n) => {
1453
+ y.info(`>> Transceiver [${n}]:`, e.mid, e.direction, e.stopped), y.info(`>> Sender Params [${n}]:`, JSON.stringify(e.sender.getParameters(), null, 2));
1454
+ }));
1455
+ }
1456
+ get trickleIcePerformanceMetrics() {
1457
+ const e = performance.measure("new-call", "new-call-start", "new-call-end"), n = performance.measure("peer-creation", "peer-creation-start", "peer-creation-end"), i = performance.measure("ice-gathering", "ice-gathering-start", "ice-gathering-end"), s = performance.measure("sdp-send", "sdp-send-start", "sdp-send-end"), a = performance.measure("invite-send", "new-call-start", "sdp-send-start"), o = performance.measure("total-duration", "peer-creation-start", "sdp-send-end"), l = (d) => `${d.toFixed(2)}ms`;
1458
+ return { "New Call": { duration: l(e.duration) }, "Peer Creation": { duration: l(n.duration) }, "ICE Gathering": { duration: l(i.duration) }, [this._isOffer() ? "Invite Send" : "Answer Send"]: { duration: l(a.duration) }, "SDP Send": { duration: l(s.duration) }, "Total Duration": { duration: l(o.duration) } };
1459
+ }
1460
+ handleSignalingStateChangeEvent(e) {
1461
+ switch (y.info("signalingState:", this.instance.signalingState), this.instance.signalingState) {
1462
+ case "stable":
1463
+ this._negotiating = !1;
1464
+ break;
1465
+ case "closed":
1466
+ if (this.keepConnectionAliveOnSocketClose) return void y.debug("Keeping peer connection alive due to keepConnectionAliveOnSocketClose option");
1467
+ this.instance = null;
1468
+ break;
1469
+ default:
1470
+ this._negotiating = !0;
1471
+ }
1472
+ }
1473
+ handleNegotiationNeededEvent() {
1474
+ y.info("Negotiation needed event"), this.instance.signalingState !== "stable" || this._negotiating ? y.debug("Skipping negotiation, state:", this.instance.signalingState, "negotiating:", this._negotiating) : this._isTrickleIce() ? this.startTrickleIceNegotiation() : this.startNegotiation();
1475
+ }
1476
+ handleTrackEvent(e) {
1477
+ const { streams: [n] } = e, { remoteElement: i, screenShare: s } = this.options;
1478
+ let { remoteStream: a } = this.options;
1479
+ a = n, s === !1 && Ee(i, a);
1480
+ }
1481
+ createPeerConnection() {
1482
+ return O(this, void 0, void 0, (function* () {
1483
+ var e;
1484
+ this.instance = (e = this._config(), new window.RTCPeerConnection(e)), this.instance.onsignalingstatechange = this.handleSignalingStateChangeEvent, this.instance.onnegotiationneeded = this.handleNegotiationNeededEvent, this.instance.ontrack = this.handleTrackEvent, this.instance.addEventListener("connectionstatechange", this.handleConnectionStateChange), this.instance.addEventListener("iceconnectionstatechange", this._handleIceConnectionStateChange), this.instance.addEventListener("icegatheringstatechange", this._handleIceGatheringStateChange), this.instance.addEventListener("addstream", ((n) => {
1485
+ this.options.remoteStream = n.stream;
1486
+ })), this._registerPeerEvents(this.instance), this._prevConnectionState = this.instance.connectionState, this.isAnswer && (yield this._setRemoteDescription({ sdp: this.options.remoteSdp, type: K.Offer })), this.options.localStream = yield this._retrieveLocalStream().catch(((n) => (F(L.MediaError, n, this.options.id), null))), this.options.mutedMicOnStart && ge(this.options.localStream) && (y.info("Muting local audio tracks on start"), st(this.options.localStream)), performance.mark("peer-creation-end");
1487
+ }));
1488
+ }
1489
+ init() {
1490
+ var e;
1491
+ return O(this, void 0, void 0, (function* () {
1492
+ yield this.createPeerConnection(), this.isDebugEnabled && (this.statsReporter = di(this._session, this.options.id), yield (e = this.statsReporter) === null || e === void 0 ? void 0 : e.start(this.instance, this._session.sessionid, this._session.sessionid));
1493
+ const { localElement: n, localStream: i = null, screenShare: s = !1 } = this.options;
1494
+ if (ge(i)) {
1495
+ const a = i.getAudioTracks();
1496
+ let o = [...a];
1497
+ if (y.info("Local audio tracks: ", a), typeof this.options.audio == "object" && a.forEach(((h) => {
1498
+ y.info("Local audio tracks constraints: ", h.getConstraints());
1499
+ })), this.options.video) {
1500
+ const h = i.getVideoTracks();
1501
+ o = [...a, ...h], y.info("Local video tracks: ", h), typeof this.options.video == "object" && h.forEach(((f) => {
1502
+ y.info("Local video tracks constraints: ", f.getConstraints());
1503
+ }));
1504
+ }
1505
+ const { audioCodecs: l, videoCodecs: d } = ((h) => {
1506
+ const f = [], m = [];
1507
+ return h && h.length !== 0 ? (h.forEach(((S) => {
1508
+ const w = S.mimeType.toLocaleLowerCase();
1509
+ w.startsWith("audio/") ? f.push(S) : w.startsWith("video/") && m.push(S);
1510
+ })), { audioCodecs: f, videoCodecs: m }) : { audioCodecs: f, videoCodecs: m };
1511
+ })(this.options.preferred_codecs);
1512
+ if (this.isOffer && typeof this.instance.addTransceiver == "function") {
1513
+ const h = { direction: "sendrecv", streams: [i] };
1514
+ o.forEach(((f) => {
1515
+ f.kind === "audio" && (this.options.userVariables.microphoneLabel = f.label), f.kind === "video" && (this.options.userVariables.cameraLabel = f.label);
1516
+ const m = this.instance.addTransceiver(f, h);
1517
+ f.kind === "audio" && l.length > 0 && this._setCodecs(m, l), f.kind === "video" && d.length > 0 && this._setCodecs(m, d);
1518
+ }));
1519
+ } else typeof this.instance.addTrack == "function" ? (o.forEach(((h) => {
1520
+ h.kind === "audio" && (this.options.userVariables.microphoneLabel = h.label), h.kind === "video" && (this.options.userVariables.cameraLabel = h.label), this.instance.addTrack(h, i);
1521
+ })), this.instance.getTransceivers().forEach(((h) => {
1522
+ h.receiver.track.kind === "audio" && l.length > 0 && this._setCodecs(h, l), h.receiver.track.kind === "video" && d.length > 0 && this._setCodecs(h, d);
1523
+ }))) : this.instance.addStream(i);
1524
+ s === !1 && Ee(n, i);
1525
+ }
1526
+ this.isOffer ? (this.options.negotiateAudio && this._checkMediaToNegotiate("audio"), this.options.negotiateVideo && this._checkMediaToNegotiate("video")) : this._isTrickleIce() || this.startNegotiation(), this._isTrickleIce() && this.startTrickleIceNegotiation(), this._logTransceivers();
1527
+ }));
1528
+ }
1529
+ _getSenderByKind(e) {
1530
+ return this.instance.getSenders().find((({ track: n }) => n && n.kind === e));
1531
+ }
1532
+ _checkMediaToNegotiate(e) {
1533
+ if (!this._getSenderByKind(e)) {
1534
+ const n = this.instance.addTransceiver(e);
1535
+ y.info("Add transceiver", e, n);
1536
+ }
1537
+ }
1538
+ _createOffer() {
1539
+ return O(this, void 0, void 0, (function* () {
1540
+ if (this._isOffer()) {
1541
+ this._constraints.offerToReceiveAudio = this.options.audio !== !1, this._constraints.offerToReceiveVideo = !!this.options.video, y.info("_createOffer - this._constraints", this._constraints);
1542
+ try {
1543
+ const e = yield this.instance.createOffer(this._constraints);
1544
+ return yield this._setLocalDescription(e), this._isTrickleIce() || this._sdpReady(), e;
1545
+ } catch (e) {
1546
+ y.error("Peer _createOffer error:", e);
1547
+ }
1548
+ }
1549
+ }));
1550
+ }
1551
+ _setRemoteDescription(e) {
1552
+ return O(this, void 0, void 0, (function* () {
1553
+ y.debug("Setting remote description", e), yield this.instance.setRemoteDescription(e);
1554
+ }));
1555
+ }
1556
+ _createAnswer() {
1557
+ return O(this, void 0, void 0, (function* () {
1558
+ if (this._isAnswer()) {
1559
+ if (this.instance.signalingState !== "stable" && this.instance.signalingState !== "have-remote-offer") return y.debug("Skipping negotiation, state:", this.instance.signalingState), y.debug(" - But the signaling state isn't stable, so triggering rollback"), void (yield Promise.all([this.instance.setLocalDescription({ type: "rollback" }), this.instance.setRemoteDescription({ sdp: this.options.remoteSdp, type: K.Offer })]));
1560
+ this._logTransceivers();
1561
+ try {
1562
+ const e = yield this.instance.createAnswer();
1563
+ return yield this._setLocalDescription(e), e;
1564
+ } catch (e) {
1565
+ y.error("Peer _createAnswer error:", e);
1566
+ }
1567
+ }
1568
+ }));
1569
+ }
1570
+ _setLocalDescription(e) {
1571
+ return O(this, void 0, void 0, (function* () {
1572
+ yield this.instance.setLocalDescription(e);
1573
+ }));
1574
+ }
1575
+ _sdpReady() {
1576
+ ye(this.onSdpReadyTwice) && this.onSdpReadyTwice(this.instance.localDescription);
1577
+ }
1578
+ _retrieveLocalStream() {
1579
+ return O(this, void 0, void 0, (function* () {
1580
+ if (ge(this.options.localStream)) return this.options.localStream;
1581
+ const e = yield (n = this.options, O(void 0, void 0, void 0, (function* () {
1582
+ let { audio: i = !0, micId: s, video: a = !1, camId: o } = n;
1583
+ const { micLabel: l = "", camLabel: d = "" } = n;
1584
+ return s && (s = yield je(s, l, ae.AudioIn).catch(((h) => null)), s && (typeof i == "boolean" && (i = {}), i.deviceId = { exact: s })), o && (o = yield je(o, d, ae.Video).catch(((h) => null)), o && (typeof a == "boolean" && (a = {}), a.deviceId = { exact: o })), { audio: i, video: a };
1585
+ })));
1586
+ var n;
1587
+ return Ue(e);
1588
+ }));
1589
+ }
1590
+ _resetJitterBuffer() {
1591
+ return O(this, void 0, void 0, (function* () {
1592
+ try {
1593
+ const n = this.instance.getReceivers().find(((s) => s.track && s.track.kind === "audio")), i = this.instance.getReceivers().find(((s) => s.track && s.track.kind === "video"));
1594
+ n && "jitterBufferTarget" in n && (n.jitterBufferTarget = 20, y.debug("audio [jitter] target set to", n.jitterBufferTarget, "ms")), i && "jitterBufferTarget" in i && (i.jitterBufferTarget = 20, y.debug("video [jitter] target set to", i.jitterBufferTarget, "ms"));
1595
+ } catch (e) {
1596
+ y.error("Peer _resetJitterBuffer error:", e);
1597
+ }
1598
+ }));
1599
+ }
1600
+ _restartNegotiationOnDeviceSleepWakeup() {
1601
+ return O(this, void 0, void 0, (function* () {
1602
+ this._sleepWakeupIntervalId !== null && (clearInterval(this._sleepWakeupIntervalId), this._sleepWakeupIntervalId = null);
1603
+ let e = Date.now();
1604
+ this._sleepWakeupIntervalId = setInterval((() => O(this, void 0, void 0, (function* () {
1605
+ var n;
1606
+ const i = Date.now();
1607
+ if (i - e > 5e3) {
1608
+ if (y.warn(`Device sleep/wake detected. Time jump: ${i - e}ms, connectionState: ${(n = this.instance) === null || n === void 0 ? void 0 : n.connectionState}`), !this.instance) return void y.debug("Peer connection closed, skipping ICE restart");
1609
+ y.info("Restarting ICE and renegotiating due to device wakeup"), this.instance.restartIce(), this._isTrickleIce() ? yield this.startTrickleIceNegotiation() : this.startNegotiation();
1610
+ }
1611
+ e = i;
1612
+ }))), 1e3);
1613
+ }));
1614
+ }
1615
+ _isOffer() {
1616
+ return this.type === K.Offer;
1617
+ }
1618
+ _isAnswer() {
1619
+ return this.type === K.Answer;
1620
+ }
1621
+ _isTrickleIce() {
1622
+ return this.options.trickleIce === !0;
1623
+ }
1624
+ _config() {
1625
+ const { prefetchIceCandidates: e, forceRelayCandidate: n, iceServers: i } = this.options, s = { bundlePolicy: "balanced", iceCandidatePoolSize: e ? 10 : 0, iceServers: i, iceTransportPolicy: n ? "relay" : "all" };
1626
+ return y.info("RTC config", s), s;
1627
+ }
1628
+ close() {
1629
+ var e;
1630
+ return O(this, void 0, void 0, (function* () {
1631
+ this._sleepWakeupIntervalId !== null && (clearInterval(this._sleepWakeupIntervalId), this._sleepWakeupIntervalId = null), yield (e = this.statsReporter) === null || e === void 0 ? void 0 : e.stop(this.debugOutput), this.instance && (this.instance.close(), this.instance = null);
1632
+ }));
1633
+ }
1634
+ }
1635
+ const Lt = We;
1636
+ class cn {
1637
+ constructor(e, n) {
1638
+ this.session = e, this.id = "", this.state = N[N.New], this.prevState = "", this.channels = [], this.role = et.Participant, this.extension = null, this._state = N.New, this._prevState = N.New, this.gotAnswer = !1, this.gotEarly = !1, this._lastSerno = 0, this._targetNodeId = null, this._iceTimeout = null, this._iceDone = !1, this._statsBindings = [], this._statsIntervalId = null, this._pendingIceCandidates = [], this._isRemoteDescriptionSet = !1, this._checkConferenceSerno = (p) => {
1639
+ const _ = p < 0 || !this._lastSerno || this._lastSerno && p === this._lastSerno + 1;
1640
+ return _ && p >= 0 && (this._lastSerno = p), _;
1641
+ }, this._doStats = () => {
1642
+ this.peer && this.peer.instance && this._statsBindings.length !== 0 && this.peer.instance.getStats().then(((p) => {
1643
+ p.forEach(((_) => {
1644
+ this._statsBindings.forEach(((A) => {
1645
+ if (A.callback) {
1646
+ if (A.constraints) {
1647
+ for (var E in A.constraints) if (A.constraints.hasOwnProperty(E) && A.constraints[E] !== _[E]) return;
1648
+ }
1649
+ A.callback(_);
1650
+ }
1651
+ }));
1652
+ }));
1653
+ }));
1654
+ };
1655
+ const { iceServers: i, speaker: s, micId: a, micLabel: o, camId: l, camLabel: d, localElement: h, remoteElement: f, options: m, mediaConstraints: { audio: S, video: w }, ringtoneFile: C, ringbackFile: k } = e;
1656
+ this.options = Object.assign({}, Fn, { audio: S, video: w, iceServers: n?.iceServers && Array.isArray(n.iceServers) ? n.iceServers : i, localElement: h, remoteElement: f, micId: a, micLabel: o, camId: l, camLabel: d, speakerId: s, ringtoneFile: C, ringbackFile: k, debug: m.debug, debugOutput: m.debugOutput, trickleIce: m.trickleIce, prefetchIceCandidates: m.prefetchIceCandidates, keepConnectionAliveOnSocketClose: m.keepConnectionAliveOnSocketClose, mutedMicOnStart: m.mutedMicOnStart }, n), this._onMediaError = this._onMediaError.bind(this), this._onPeerConnectionFailureError = this._onPeerConnectionFailureError.bind(this), this._onTrickleIceSdp = this._onTrickleIceSdp.bind(this), this._registerPeerEvents = this._registerPeerEvents.bind(this), this._registerTrickleIcePeerEvents = this._registerTrickleIcePeerEvents.bind(this), this._init(), this.options && (this._ringtone = Ct(this.options.ringtoneFile, "_ringtone"), this._ringback = Ct(this.options.ringbackFile, "_ringback"));
1657
+ }
1658
+ get performanceMetrics() {
1659
+ const e = performance.measure("peer-creation", "peer-creation-start", "peer-creation-end"), n = performance.measure("ice-gathering", "ice-gathering-start", "ice-gathering-end"), i = performance.measure("sdp-send", "sdp-send-start", "sdp-send-end"), s = performance.measure("total-duration", "peer-creation-start", "sdp-send-end"), a = (o) => `${o.toFixed(2)}ms`;
1660
+ return { "Peer Creation": { duration: a(e.duration) }, "ICE Gathering": { duration: a(n.duration) }, "SDP Send": { duration: a(i.duration) }, "Total Duration": { duration: a(s.duration) } };
1661
+ }
1662
+ get nodeId() {
1663
+ return this._targetNodeId;
1664
+ }
1665
+ set nodeId(e) {
1666
+ this._targetNodeId = e;
1667
+ }
1668
+ get isVideoCall() {
1669
+ return !!this.options.video;
1670
+ }
1671
+ get telnyxIDs() {
1672
+ return { telnyxCallControlId: this.options.telnyxCallControlId, telnyxSessionId: this.options.telnyxSessionId, telnyxLegId: this.options.telnyxLegId };
1673
+ }
1674
+ get localStream() {
1675
+ return this.options.localStream;
1676
+ }
1677
+ get remoteStream() {
1678
+ return this.options.remoteStream;
1679
+ }
1680
+ get memberChannel() {
1681
+ return `conference-member.${this.id}`;
1682
+ }
1683
+ get isAudioMuted() {
1684
+ return !zn(this.options.localStream);
1685
+ }
1686
+ invite() {
1687
+ return O(this, void 0, void 0, (function* () {
1688
+ this.direction = le.Outbound, this.options.trickleIce && this._resetTrickleIceCandidateState(), performance.mark("peer-creation-start"), this.peer = new xt(K.Offer, this.options, this.session, this._onTrickleIceSdp, this.options.trickleIce ? this._registerTrickleIcePeerEvents : this._registerPeerEvents), yield this.peer.init();
1689
+ }));
1690
+ }
1691
+ answer(e = {}) {
1692
+ var n;
1693
+ return O(this, void 0, void 0, (function* () {
1694
+ performance.mark("new-call-start"), this.stopRingtone(), this.direction = le.Inbound, ((n = e?.customHeaders) === null || n === void 0 ? void 0 : n.length) > 0 && (this.options = Object.assign(Object.assign({}, this.options), { customHeaders: e.customHeaders })), this.options.trickleIce && this._resetTrickleIceCandidateState(), performance.mark("peer-creation-start"), this.peer = new xt(K.Answer, this.options, this.session, this._onTrickleIceSdp, this.options.trickleIce ? this._registerTrickleIcePeerEvents : this._registerPeerEvents), yield this.peer.init(), performance.mark("new-call-end");
1695
+ }));
1696
+ }
1697
+ playRingtone() {
1698
+ kt(this._ringtone);
1699
+ }
1700
+ stopRingtone() {
1701
+ It(this._ringtone);
1702
+ }
1703
+ playRingback() {
1704
+ kt(this._ringback);
1705
+ }
1706
+ stopRingback() {
1707
+ It(this._ringback);
1708
+ }
1709
+ hangup(e, n) {
1710
+ var i, s, a;
1711
+ let o = e || {}, l = n !== !1;
1712
+ this.cause = o.cause || "NORMAL_CLEARING", this.causeCode = o.causeCode || 16, this.sipCode = o.sipCode || null, this.sipReason = o.sipReason || null, this.sipCallId = o.sip_call_id || null, this.options.customHeaders = [...(i = this.options.customHeaders) !== null && i !== void 0 ? i : [], ...(a = (s = o?.dialogParams) === null || s === void 0 ? void 0 : s.customHeaders) !== null && a !== void 0 ? a : []], this.setState(N.Hangup);
1713
+ const d = () => {
1714
+ var h;
1715
+ return (h = this.peer) === null || h === void 0 || h.close(), this.setState(N.Destroy);
1716
+ };
1717
+ if (this.stopRingtone(), this.stopRingback(), l) {
1718
+ const h = new Xn({ sipCode: this.sipCode, sip_call_id: this.sipCallId, sessid: this.session.sessionid, dialogParams: this.options, cause: "USER_BUSY", causeCode: 17 });
1719
+ this._execute(h).catch(((f) => {
1720
+ y.error("telnyx_rtc.bye failed!", f), F(L.Error, { error: f, sessionId: this.session.sessionid }, this.session.uuid);
1721
+ })).then(d.bind(this));
1722
+ } else d();
1723
+ }
1724
+ hold() {
1725
+ const e = new Qe({ sessid: this.session.sessionid, action: "hold", dialogParams: this.options });
1726
+ return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this));
1727
+ }
1728
+ unhold() {
1729
+ const e = new Qe({ sessid: this.session.sessionid, action: "unhold", dialogParams: this.options });
1730
+ return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this));
1731
+ }
1732
+ toggleHold() {
1733
+ const e = new Qe({ sessid: this.session.sessionid, action: "toggleHold", dialogParams: this.options });
1734
+ return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this));
1735
+ }
1736
+ dtmf(e) {
1737
+ const n = new At({ sessid: this.session.sessionid, dtmf: e, dialogParams: this.options });
1738
+ this._execute(n);
1739
+ }
1740
+ message(e, n) {
1741
+ const i = { from: this.session.options.login, to: e, body: n }, s = new At({ sessid: this.session.sessionid, msg: i, dialogParams: this.options });
1742
+ this._execute(s);
1743
+ }
1744
+ muteAudio() {
1745
+ st(this.options.localStream);
1746
+ }
1747
+ unmuteAudio() {
1748
+ _t(this.options.localStream);
1749
+ }
1750
+ toggleAudioMute() {
1751
+ wt(this.options.localStream);
1752
+ }
1753
+ setAudioInDevice(e, n = this.options.mutedMicOnStart) {
1754
+ return O(this, void 0, void 0, (function* () {
1755
+ const { instance: i } = this.peer, s = i.getSenders().find((({ track: { kind: a } }) => a === "audio"));
1756
+ if (s) {
1757
+ const a = yield tt({ audio: { deviceId: { exact: e } } }), o = a.getAudioTracks()[0];
1758
+ o.enabled = !n, s.replaceTrack(o), this.options.micId = e;
1759
+ const { localStream: l } = this.options;
1760
+ l.getAudioTracks().forEach(((d) => d.stop())), l.getVideoTracks().forEach(((d) => a.addTrack(d))), this.options.localStream = a;
1761
+ }
1762
+ }));
1763
+ }
1764
+ muteVideo() {
1765
+ var e;
1766
+ e = this.options.localStream, me(e, "video", !1);
1767
+ }
1768
+ unmuteVideo() {
1769
+ var e;
1770
+ e = this.options.localStream, me(e, "video", !0);
1771
+ }
1772
+ toggleVideoMute() {
1773
+ var e;
1774
+ e = this.options.localStream, me(e, "video", null);
1775
+ }
1776
+ setVideoDevice(e) {
1777
+ return O(this, void 0, void 0, (function* () {
1778
+ const { instance: n } = this.peer, i = n.getSenders().find((({ track: { kind: s } }) => s === "video"));
1779
+ if (i) {
1780
+ const s = yield tt({ video: { deviceId: { exact: e } } }), a = s.getVideoTracks()[0];
1781
+ i.replaceTrack(a);
1782
+ const { localElement: o, localStream: l } = this.options;
1783
+ Ee(o, s), this.options.camId = e, l.getAudioTracks().forEach(((d) => s.addTrack(d))), l.getVideoTracks().forEach(((d) => d.stop())), this.options.localStream = s;
1784
+ }
1785
+ }));
1786
+ }
1787
+ deaf() {
1788
+ st(this.options.remoteStream);
1789
+ }
1790
+ undeaf() {
1791
+ _t(this.options.remoteStream);
1792
+ }
1793
+ toggleDeaf() {
1794
+ wt(this.options.remoteStream);
1795
+ }
1796
+ setBandwidthEncodingsMaxBps(e, n) {
1797
+ return O(this, void 0, void 0, (function* () {
1798
+ if (!this || !this.peer) return void y.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");
1799
+ const { instance: i } = this.peer, s = i.getSenders();
1800
+ if (!s) return void y.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");
1801
+ const a = s.find((({ track: { kind: o } }) => o === n));
1802
+ if (a) {
1803
+ const o = a.getParameters();
1804
+ o.encodings || (o.encodings = [{ rid: "h" }]), y.info("Parameters: ", o), y.info("Setting max ", n === "audio" ? "audio" : "video", " bandwidth to: ", e, " [bps]"), o.encodings[0].maxBitrate = e, yield a.setParameters(o).then((() => {
1805
+ y.info(n === "audio" ? "New audio" : "New video", " bandwidth settings in use: ", a.getParameters());
1806
+ })).catch(((l) => y.error(l)));
1807
+ } else y.error("Could not set bandwidth (reason: no " + n + " sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");
1808
+ }));
1809
+ }
1810
+ setAudioBandwidthEncodingsMaxBps(e) {
1811
+ this.setBandwidthEncodingsMaxBps(e, "audio");
1812
+ }
1813
+ setVideoBandwidthEncodingsMaxBps(e) {
1814
+ this.setBandwidthEncodingsMaxBps(e, "video");
1815
+ }
1816
+ getStats(e, n) {
1817
+ if (!e) return;
1818
+ const i = { callback: e, constraints: n };
1819
+ this._statsBindings.push(i), !this._statsIntervalId && this._startStats(2e3);
1820
+ }
1821
+ setState(e) {
1822
+ switch (this._prevState = this._state, this._state = e, this.state = N[this._state].toLowerCase(), this.prevState = N[this._prevState].toLowerCase(), y.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`), this._dispatchNotification({ type: oe.callUpdate, call: this }), e) {
1823
+ case N.Purge:
1824
+ y.debug(`Call ${this.id} hangup call due to purge state`), this.hangup({ cause: "PURGE", causeCode: "01" }, !1);
1825
+ break;
1826
+ case N.Active:
1827
+ setTimeout((() => {
1828
+ const { remoteElement: n, speakerId: i } = this.options;
1829
+ n && i && tn(n, i);
1830
+ }), 0);
1831
+ break;
1832
+ case N.Destroy:
1833
+ this._finalize();
1834
+ }
1835
+ }
1836
+ handleMessage(e) {
1837
+ const { method: n, params: i } = e;
1838
+ switch (n) {
1839
+ case $.Answer:
1840
+ if (this.gotAnswer = !0, this._state >= N.Active) return;
1841
+ this._state >= N.Early && this.setState(N.Active), this.gotEarly || this._onRemoteSdp(i.sdp), this.stopRingback(), this.stopRingtone();
1842
+ break;
1843
+ case $.Media:
1844
+ if (this._state >= N.Early) return;
1845
+ this.gotEarly = !0, this._onRemoteSdp(i.sdp);
1846
+ break;
1847
+ case $.Display:
1848
+ case $.Attach: {
1849
+ const { display_name: a, display_number: o, display_direction: l } = i;
1850
+ this.extension = o;
1851
+ const d = l === le.Inbound ? le.Outbound : le.Inbound, h = { type: oe[n], call: this, displayName: a, displayNumber: o, displayDirection: d };
1852
+ F(L.Notification, h, this.id) || F(L.Notification, h, this.session.uuid);
1853
+ break;
1854
+ }
1855
+ case $.Candidate:
1856
+ this._addIceCandidate(i);
1857
+ break;
1858
+ case $.Info:
1859
+ case $.Event: {
1860
+ const a = Object.assign(Object.assign({}, i), { type: oe.generic, call: this });
1861
+ F(L.Notification, a, this.id) || F(L.Notification, a, this.session.uuid);
1862
+ break;
1863
+ }
1864
+ case $.Ringing:
1865
+ this.playRingback(), i.telnyx_call_control_id && (this.options.telnyxCallControlId = i.telnyx_call_control_id), i.telnyx_session_id && (this.options.telnyxSessionId = i.telnyx_session_id), i.telnyx_leg_id && (this.options.telnyxLegId = i.telnyx_leg_id);
1866
+ break;
1867
+ case $.Bye:
1868
+ const s = i.client_state || i.clientState;
1869
+ s && (this.options.clientState = s), this.stopRingback(), this.stopRingtone(), this.hangup(i, !1);
1870
+ }
1871
+ }
1872
+ handleConferenceUpdate(e, n) {
1873
+ return O(this, void 0, void 0, (function* () {
1874
+ if (!this._checkConferenceSerno(e.wireSerno) && e.name !== n.laName) return y.error("ConferenceUpdate invalid wireSerno or packet name:", e), "INVALID_PACKET";
1875
+ const { action: i, data: s, hashKey: a = String(this._lastSerno), arrIndex: o } = e;
1876
+ switch (i) {
1877
+ case "bootObj": {
1878
+ this._lastSerno = 0;
1879
+ const { chatChannel: l, infoChannel: d, modChannel: h, laName: f, conferenceMemberID: m, role: S } = n;
1880
+ this._dispatchConferenceUpdate({ action: se.Join, conferenceName: f, participantId: Number(m), role: S }), l && (yield this._subscribeConferenceChat(l)), d && (yield this._subscribeConferenceInfo(d));
1881
+ const w = [];
1882
+ for (const C in s) w.push(Object.assign({ callId: s[C][0], index: Number(C) }, Le(s[C][1])));
1883
+ this._dispatchConferenceUpdate({ action: se.Bootstrap, participants: w });
1884
+ break;
1885
+ }
1886
+ case "add":
1887
+ this._dispatchConferenceUpdate(Object.assign({ action: se.Add, callId: a, index: o }, Le(s)));
1888
+ break;
1889
+ case "modify":
1890
+ this._dispatchConferenceUpdate(Object.assign({ action: se.Modify, callId: a, index: o }, Le(s)));
1891
+ break;
1892
+ case "del":
1893
+ this._dispatchConferenceUpdate(Object.assign({ action: se.Delete, callId: a, index: o }, Le(s)));
1894
+ break;
1895
+ case "clear":
1896
+ this._dispatchConferenceUpdate({ action: se.Clear });
1897
+ break;
1898
+ default:
1899
+ this._dispatchConferenceUpdate({ action: i, data: s, callId: a, index: o });
1900
+ }
1901
+ }));
1902
+ }
1903
+ _addChannel(e) {
1904
+ this.channels.includes(e) || this.channels.push(e);
1905
+ const n = this.session.relayProtocol;
1906
+ this.session._existsSubscription(n, e) && (this.session.subscriptions[n][e] = Object.assign(Object.assign({}, this.session.subscriptions[n][e]), { callId: this.id }));
1907
+ }
1908
+ _subscribeConferenceChat(e) {
1909
+ return O(this, void 0, void 0, (function* () {
1910
+ const n = { nodeId: this.nodeId, channels: [e], handler: (s) => {
1911
+ const { direction: a, from: o, fromDisplay: l, message: d, type: h } = s.data;
1912
+ this._dispatchConferenceUpdate({ action: se.ChatMessage, direction: a, participantNumber: o, participantName: l, messageText: d, messageType: h, messageId: s.eventSerno });
1913
+ } }, i = yield this.session.vertoSubscribe(n).catch(((s) => {
1914
+ y.error("ConfChat subscription error:", s);
1915
+ }));
1916
+ nt(i, e) && (this._addChannel(e), Object.defineProperties(this, { sendChatMessage: { configurable: !0, value: (s, a) => {
1917
+ this.session.vertoBroadcast({ nodeId: this.nodeId, channel: e, data: { action: "send", message: s, type: a } });
1918
+ } } }));
1919
+ }));
1920
+ }
1921
+ _subscribeConferenceInfo(e) {
1922
+ return O(this, void 0, void 0, (function* () {
1923
+ const n = { nodeId: this.nodeId, channels: [e], handler: (s) => {
1924
+ const { eventData: a } = s;
1925
+ a.contentType === "layout-info" ? (a.callID = this.id, an(this.session, a)) : y.error("Conference-Info unknown contentType", s);
1926
+ } }, i = yield this.session.vertoSubscribe(n).catch(((s) => {
1927
+ y.error("ConfInfo subscription error:", s);
1928
+ }));
1929
+ nt(i, e) && this._addChannel(e);
1930
+ }));
1931
+ }
1932
+ _confControl(e, n = {}) {
1933
+ const i = Object.assign({ application: "conf-control", callID: this.id, value: null }, n);
1934
+ this.session.vertoBroadcast({ nodeId: this.nodeId, channel: e, data: i });
1935
+ }
1936
+ _handleChangeHoldStateSuccess(e) {
1937
+ return e.holdState === "active" ? this.setState(N.Active) : this.setState(N.Held), !0;
1938
+ }
1939
+ _handleChangeHoldStateError(e) {
1940
+ return y.error(`Failed to ${e.action} on call ${this.id}`), !1;
1941
+ }
1942
+ _onRemoteSdp(e) {
1943
+ return O(this, void 0, void 0, (function* () {
1944
+ const n = new RTCSessionDescription({ sdp: e, type: K.Answer });
1945
+ yield this.peer.instance.setRemoteDescription(n).then((() => {
1946
+ this.options.trickleIce && (this._isRemoteDescriptionSet = !0, this._flushPendingTrickleIceCandidates()), this.gotEarly && this.setState(N.Early), this.gotAnswer && this.setState(N.Active);
1947
+ })).catch(((i) => {
1948
+ y.error("Call setRemoteDescription Error: ", i), this.hangup();
1949
+ }));
1950
+ }));
1951
+ }
1952
+ _requestAnotherLocalDescription() {
1953
+ ye(this.peer.onSdpReadyTwice) ? F(L.Error, { error: new Error("SDP without candidates for the second time!"), sessionId: this.session.sessionid }, this.session.uuid) : (Object.defineProperty(this.peer, "onSdpReadyTwice", { value: this._onIceSdp.bind(this) }), this._iceDone = !1, this.peer.startNegotiation());
1954
+ }
1955
+ _onIceSdp(e) {
1956
+ var n, i;
1957
+ this._iceTimeout && clearTimeout(this._iceTimeout), this._iceTimeout = null, this._iceDone = !0;
1958
+ const { sdp: s, type: a } = e;
1959
+ if (s.indexOf("candidate") === -1) return y.info(`No candidate - retry
1960
+ `), void this._requestAnotherLocalDescription();
1961
+ (i = (n = this.peer) === null || n === void 0 ? void 0 : n.instance) === null || i === void 0 || i.removeEventListener("icecandidate", this._onIce), performance.mark("ice-gathering-end");
1962
+ let o = null;
1963
+ const l = { sessid: this.session.sessionid, sdp: s, dialogParams: this.options, "User-Agent": `Web-${Lt}` };
1964
+ switch (a) {
1965
+ case K.Offer:
1966
+ this.setState(N.Requesting), o = new Et(l);
1967
+ break;
1968
+ case K.Answer:
1969
+ this.setState(N.Answering), o = this.options.attach === !0 ? new ot(l) : new Tt(l);
1970
+ break;
1971
+ default:
1972
+ return y.error(`${this.id} - Unknown local SDP type:`, e), this.hangup({}, !1);
1973
+ }
1974
+ performance.mark("sdp-send-start"), this._execute(o).then(((d) => {
1975
+ const { node_id: h = null } = d;
1976
+ this._targetNodeId = h, a === K.Offer ? this.setState(N.Trying) : this.setState(N.Active);
1977
+ })).catch(((d) => {
1978
+ y.error(`${this.id} - Sending ${a} error:`, d), this.hangup();
1979
+ })).finally((() => {
1980
+ performance.mark("sdp-send-end"), console.group("Performance Metrics"), console.table(this.performanceMetrics), console.groupEnd(), performance.clearMarks();
1981
+ }));
1982
+ }
1983
+ _onTrickleIceSdp(e) {
1984
+ if (!e) return y.error("No SDP data provided"), this.hangup({}, !1);
1985
+ const { sdp: n, type: i } = e;
1986
+ let s = null;
1987
+ const a = { sessid: this.session.sessionid, sdp: n, dialogParams: this.options, trickle: !0, "User-Agent": `Web-${Lt}` };
1988
+ switch (i) {
1989
+ case K.Offer:
1990
+ this.setState(N.Requesting), s = new Et(a);
1991
+ break;
1992
+ case K.Answer:
1993
+ this.setState(N.Answering), s = this.options.attach === !0 ? new ot(a) : new Tt(a);
1994
+ break;
1995
+ default:
1996
+ return y.error(`${this.id} - Unknown local SDP type:`, e), this.hangup({}, !1);
1997
+ }
1998
+ performance.mark("sdp-send-start"), this._execute(s).then(((o) => {
1999
+ const { node_id: l = null } = o;
2000
+ this._targetNodeId = l, i === K.Offer ? this.setState(N.Trying) : this.setState(N.Active);
2001
+ })).catch(((o) => {
2002
+ y.error(`${this.id} - Sending ${i} error:`, o), this.hangup();
2003
+ })).finally((() => {
2004
+ performance.mark("sdp-send-end");
2005
+ }));
2006
+ }
2007
+ _onIce(e) {
2008
+ const { instance: n } = this.peer;
2009
+ this._iceTimeout === null && (this._iceTimeout = setTimeout((() => this._onIceSdp(n.localDescription)), 1e3)), e.candidate ? y.debug("RTCPeer Candidate:", e.candidate) : this._onIceSdp(n.localDescription);
2010
+ }
2011
+ _onTrickleIce(e) {
2012
+ e.candidate && e.candidate.candidate ? (y.debug("RTCPeer Candidate:", e.candidate), this._sendIceCandidate(e.candidate)) : this._sendEndOfCandidates();
2013
+ }
2014
+ _sendIceCandidate(e) {
2015
+ const n = new on({ sessid: this.session.sessionid, candidate: e.candidate, sdpMLineIndex: e.sdpMLineIndex, sdpMid: e.sdpMid, dialogParams: this.options });
2016
+ this._execute(n);
2017
+ }
2018
+ _addIceCandidate(e) {
2019
+ if (!this._isRemoteDescriptionSet) return y.debug("Remote description not set. Queued ICE candidate.", e), void this._pendingIceCandidates.push(e);
2020
+ this._addIceCandidateToPeer(e);
2021
+ }
2022
+ _addIceCandidateToPeer(e) {
2023
+ const n = this.peer.instance.addIceCandidate(e);
2024
+ Promise.resolve(n).then((() => {
2025
+ y.debug("Successfully added ICE candidate:", e);
2026
+ })).catch(((i) => {
2027
+ y.error("Failed to add ICE candidate:", i, e);
2028
+ }));
2029
+ }
2030
+ _sendEndOfCandidates() {
2031
+ const e = new Zn({ sessid: this.session.sessionid, endOfCandidates: !0, dialogParams: this.options });
2032
+ this._execute(e), performance.mark("ice-gathering-end");
2033
+ }
2034
+ _resetTrickleIceCandidateState() {
2035
+ this._pendingIceCandidates = [], this._isRemoteDescriptionSet = !1;
2036
+ }
2037
+ _flushPendingTrickleIceCandidates() {
2038
+ if (!this._pendingIceCandidates.length) return;
2039
+ const e = [...this._pendingIceCandidates];
2040
+ this._pendingIceCandidates = [], e.forEach(((n) => {
2041
+ this._addIceCandidateToPeer(n);
2042
+ }));
2043
+ }
2044
+ _registerPeerEvents(e) {
2045
+ this._iceDone = !1, e.onicecandidate = (n) => {
2046
+ this._iceDone || this._onIce(n);
2047
+ }, e.onicecandidateerror = (n) => {
2048
+ var i;
2049
+ if (y.debug("ICE candidate error:", n), (i = this.peer) === null || i === void 0 ? void 0 : i.statsReporter) {
2050
+ const s = Rt(n, e);
2051
+ this.peer.statsReporter.reportIceCandidateError(s);
2052
+ }
2053
+ }, e.addEventListener("addstream", ((n) => {
2054
+ this.options.remoteStream = n.stream;
2055
+ })), e.addEventListener("track", ((n) => {
2056
+ this.options.remoteStream = n.streams[0];
2057
+ const { remoteElement: i, remoteStream: s, screenShare: a } = this.options;
2058
+ a === !1 && Ee(i, s);
2059
+ }));
2060
+ }
2061
+ _registerTrickleIcePeerEvents(e) {
2062
+ e.onicecandidate = (n) => {
2063
+ this._onTrickleIce(n);
2064
+ }, e.onicegatheringstatechange = (n) => {
2065
+ y.debug("ICE gathering state changed:", e.iceGatheringState), e.iceGatheringState === "complete" && y.debug("Finished gathering candidates");
2066
+ }, e.onicecandidateerror = (n) => {
2067
+ var i;
2068
+ if (y.debug("ICE candidate error:", n), (i = this.peer) === null || i === void 0 ? void 0 : i.statsReporter) {
2069
+ const s = Rt(n, e);
2070
+ this.peer.statsReporter.reportIceCandidateError(s);
2071
+ }
2072
+ }, e.addEventListener("addstream", ((n) => {
2073
+ this.options.remoteStream = n.stream;
2074
+ })), e.addEventListener("track", ((n) => {
2075
+ this.options.remoteStream = n.streams[0];
2076
+ const { remoteElement: i, remoteStream: s, screenShare: a } = this.options;
2077
+ a === !1 && Ee(i, s);
2078
+ }));
2079
+ }
2080
+ _onMediaError(e) {
2081
+ this._dispatchNotification({ type: oe.userMediaError, error: e }), y.error("Media error, hanging up call", e), this.hangup({}, !1);
2082
+ }
2083
+ _onPeerConnectionFailureError(e) {
2084
+ this._dispatchNotification({ type: oe.peerConnectionFailureError, error: e }), y.error("Peer connection failure error, hanging up call", e), this.hangup({}, !1);
2085
+ }
2086
+ _dispatchConferenceUpdate(e) {
2087
+ this._dispatchNotification(Object.assign({ type: oe.conferenceUpdate, call: this }, e));
2088
+ }
2089
+ _dispatchNotification(e) {
2090
+ this.options.screenShare !== !0 && (F(L.Notification, e, this.id, !1) || F(L.Notification, e, this.session.uuid));
2091
+ }
2092
+ _execute(e) {
2093
+ return this.nodeId && (e.targetNodeId = this.nodeId), this.session.execute(e);
2094
+ }
2095
+ _init() {
2096
+ const { id: e, userVariables: n, remoteCallerNumber: i, onNotification: s } = this.options;
2097
+ var a;
2098
+ this.options.id = e ? e.toString() : ve(), this.id = this.options.id, n && (a = n, Object.keys(a).length !== 0) || (this.options.userVariables = this.session.options.userVariables || {}), i || (this.options.remoteCallerNumber = this.options.destinationNumber), this.session.calls[this.id] = this, de(L.MediaError, this._onMediaError, this.id), de(L.PeerConnectionFailureError, this._onPeerConnectionFailureError, this.id), ye(s) && de(L.Notification, s.bind(this), this.id), this.setState(N.New), y.info("New Call with Options:", this.options);
2099
+ }
2100
+ _finalize() {
2101
+ var e;
2102
+ this._stopStats(), (e = this.peer) === null || e === void 0 || e.close();
2103
+ const { remoteStream: n, localStream: i } = this.options;
2104
+ Te(n), Te(i), ue(L.MediaError, null, this.id), ue(L.PeerConnectionFailureError, null, this.id), this.session.calls[this.id] = null, delete this.session.calls[this.id];
2105
+ }
2106
+ _startStats(e) {
2107
+ this._statsIntervalId = setInterval(this._doStats, e), y.info("Stats started");
2108
+ }
2109
+ _stopStats() {
2110
+ this._statsIntervalId && (clearInterval(this._statsIntervalId), this._statsIntervalId = null), y.debug("Stats stopped");
2111
+ }
2112
+ }
2113
+ cn.setStateTelnyx = (t) => {
2114
+ if (t) {
2115
+ switch (t._state) {
2116
+ case N.Requesting:
2117
+ case N.Recovering:
2118
+ case N.Trying:
2119
+ case N.Early:
2120
+ t.state = "connecting";
2121
+ break;
2122
+ case N.Active:
2123
+ t.state = "active";
2124
+ break;
2125
+ case N.Held:
2126
+ t.state = "held";
2127
+ break;
2128
+ case N.Hangup:
2129
+ case N.Destroy:
2130
+ t.state = "done";
2131
+ break;
2132
+ case N.Answering:
2133
+ t.state = "ringing";
2134
+ break;
2135
+ case N.New:
2136
+ t.state = "new";
2137
+ }
2138
+ return t;
2139
+ }
2140
+ };
2141
+ class he extends cn {
2142
+ constructor() {
2143
+ super(...arguments), this._statsInterval = null, this.sendConversationMessage = (e, n) => this.session.execute(new ii(e, n));
2144
+ }
2145
+ hangup(e = {}, n = !0) {
2146
+ this.screenShare instanceof he && this.screenShare.hangup(e, n), super.hangup(e, n);
2147
+ }
2148
+ startScreenShare(e) {
2149
+ return O(this, void 0, void 0, (function* () {
2150
+ const n = yield (i = { video: !0 }, navigator.mediaDevices.getDisplayMedia(i));
2151
+ var i;
2152
+ n.getTracks().forEach(((h) => {
2153
+ h.addEventListener("ended", (() => {
2154
+ this.screenShare && this.screenShare.hangup();
2155
+ }));
2156
+ }));
2157
+ const { remoteCallerName: s, remoteCallerNumber: a, callerName: o, callerNumber: l } = this.options, d = Object.assign({ screenShare: !0, localStream: n, destinationNumber: `${this.extension}-screen`, remoteCallerName: s, remoteCallerNumber: `${a}-screen`, callerName: `${o} (Screen)`, callerNumber: `${l} (Screen)` }, e);
2158
+ return this.screenShare = new he(this.session, d), this.screenShare.invite(), this.screenShare;
2159
+ }));
2160
+ }
2161
+ stopScreenShare() {
2162
+ this.screenShare instanceof he && this.screenShare.hangup();
2163
+ }
2164
+ setAudioOutDevice(e) {
2165
+ return O(this, void 0, void 0, (function* () {
2166
+ this.options.speakerId = e;
2167
+ const { remoteElement: n, speakerId: i } = this.options;
2168
+ return !(!n || !i) && tn(n, i);
2169
+ }));
2170
+ }
2171
+ _finalize() {
2172
+ this._stats(!1), super._finalize();
2173
+ }
2174
+ _stats(e = !0) {
2175
+ if (e === !1) return clearInterval(this._statsInterval);
2176
+ y.setLevel(2), this._statsInterval = window.setInterval((() => O(this, void 0, void 0, (function* () {
2177
+ const n = yield this.peer.instance.getStats(null);
2178
+ let i = "";
2179
+ const s = ["certificate", "codec", "peer-connection", "stream", "local-candidate", "remote-candidate"], a = ["id", "type", "timestamp"];
2180
+ n.forEach(((o) => {
2181
+ s.includes(o.type) || (i += `
2182
+ ${o.type}
2183
+ `, Object.keys(o).forEach(((l) => {
2184
+ a.includes(l) || (i += ` ${l}: ${o[l]}
2185
+ `);
2186
+ })));
2187
+ })), y.info(i);
2188
+ }))), 2e3);
2189
+ }
2190
+ }
2191
+ class hi extends qn {
2192
+ constructor(e) {
2193
+ super(e), this.calls = {}, this.autoRecoverCalls = !0, this._iceServers = [], this._localElement = null, this._remoteElement = null, this._jwtAuth = !0, this._audioConstraints = !0, this._previousAudioConstraints = !0, this._videoConstraints = !1, this._speaker = null, this._onlineHandler = null, this._offlineHandler = null, this._wasOffline = !1, this._videoConstraints = e.video || !1, this.iceServers = e.iceServers, this.ringtoneFile = e.ringtoneFile, this.ringbackFile = e.ringbackFile, this._setupNetworkListeners();
2194
+ }
2195
+ get reconnectDelay() {
2196
+ return 1e3;
2197
+ }
2198
+ getIsRegistered() {
2199
+ const e = Object.create(null, { getIsRegistered: { get: () => super.getIsRegistered } });
2200
+ return O(this, void 0, void 0, (function* () {
2201
+ return e.getIsRegistered.call(this);
2202
+ }));
2203
+ }
2204
+ connect() {
2205
+ const e = Object.create(null, { connect: { get: () => super.connect } });
2206
+ return O(this, void 0, void 0, (function* () {
2207
+ e.connect.call(this);
2208
+ }));
2209
+ }
2210
+ checkPermissions(e = !0, n = !0) {
2211
+ return O(this, void 0, void 0, (function* () {
2212
+ try {
2213
+ const i = yield Ue({ audio: e, video: n });
2214
+ return Te(i), !0;
2215
+ } catch {
2216
+ return !1;
2217
+ }
2218
+ }));
2219
+ }
2220
+ logout() {
2221
+ this.disconnect();
2222
+ }
2223
+ disconnect() {
2224
+ const e = Object.create(null, { disconnect: { get: () => super.disconnect } });
2225
+ return O(this, void 0, void 0, (function* () {
2226
+ Object.keys(this.calls).forEach(((n) => this.calls[n].setState(N.Purge))), this.calls = {}, this._cleanupNetworkListeners(), yield e.disconnect.call(this);
2227
+ }));
2228
+ }
2229
+ socketDisconnect() {
2230
+ this._closeConnection();
2231
+ }
2232
+ handleLoginError(e) {
2233
+ super._handleLoginError(e);
2234
+ }
2235
+ speedTest(e) {
2236
+ return new Promise(((n, i) => {
2237
+ if (Xt(L.SpeedTest, ((o) => {
2238
+ const { upDur: l, downDur: d } = o, h = d ? 8 * e / (d / 1e3) / 1024 : 0;
2239
+ n({ upDur: l, downDur: d, upKps: (l ? 8 * e / (l / 1e3) / 1024 : 0).toFixed(0), downKps: h.toFixed(0) });
2240
+ }), this.uuid), !(e = Number(e))) return i(`Invalid parameter 'bytes': ${e}`);
2241
+ this.executeRaw(`#SPU ${e}`);
2242
+ let s = e / 1024;
2243
+ e % 1024 && s++;
2244
+ const a = ".".repeat(1024);
2245
+ for (let o = 0; o < s; o++) this.executeRaw(`#SPB ${a}`);
2246
+ this.executeRaw("#SPE");
2247
+ }));
2248
+ }
2249
+ getDevices() {
2250
+ return ke().catch(((e) => (F(L.MediaError, e, this.uuid), [])));
2251
+ }
2252
+ getVideoDevices() {
2253
+ return ke(ae.Video).catch(((e) => (F(L.MediaError, e, this.uuid), [])));
2254
+ }
2255
+ getAudioInDevices() {
2256
+ return ke(ae.AudioIn).catch(((e) => (F(L.MediaError, e, this.uuid), [])));
2257
+ }
2258
+ getAudioOutDevices() {
2259
+ return ke(ae.AudioOut).catch(((e) => (y.error("getAudioOutDevices", e), F(L.MediaError, e, this.uuid), [])));
2260
+ }
2261
+ validateDeviceId(e, n, i) {
2262
+ return je(e, n, i);
2263
+ }
2264
+ getDeviceResolutions(e) {
2265
+ return O(this, void 0, void 0, (function* () {
2266
+ try {
2267
+ return yield ((n) => O(void 0, void 0, void 0, (function* () {
2268
+ const i = [], s = yield Ue({ video: { deviceId: { exact: n } } }), a = s.getVideoTracks()[0];
2269
+ for (let o = 0; o < St.length; o++) {
2270
+ const [l, d] = St[o];
2271
+ (yield a.applyConstraints({ width: { exact: l }, height: { exact: d } }).then((() => !0)).catch((() => !1))) && i.push({ resolution: `${l}x${d}`, width: l, height: d });
2272
+ }
2273
+ return Te(s), i;
2274
+ })))(e);
2275
+ } catch (n) {
2276
+ throw n;
2277
+ }
2278
+ }));
2279
+ }
2280
+ get mediaConstraints() {
2281
+ return { audio: this._audioConstraints, video: this._videoConstraints };
2282
+ }
2283
+ setAudioSettings(e) {
2284
+ return O(this, void 0, void 0, (function* () {
2285
+ if (!e) throw new Error("You need to provide the settings object");
2286
+ const { micId: n, micLabel: i } = e, s = Wt(e, ["micId", "micLabel"]);
2287
+ return Yn(s), this._audioConstraints = yield ((a, o, l, d) => O(void 0, void 0, void 0, (function* () {
2288
+ const { deviceId: h } = d;
2289
+ if (h === void 0 && (a || o)) {
2290
+ const f = yield je(a, o, l).catch(((m) => null));
2291
+ f && (d.deviceId = { exact: f });
2292
+ }
2293
+ return d;
2294
+ })))(n, i, "audioinput", s), this.micId = n, this.micLabel = i, this._audioConstraints;
2295
+ }));
2296
+ }
2297
+ disableMicrophone() {
2298
+ this._previousAudioConstraints = this._audioConstraints, this._audioConstraints = !1;
2299
+ }
2300
+ enableMicrophone() {
2301
+ this._audioConstraints = this._previousAudioConstraints || !0;
2302
+ }
2303
+ set iceServers(e) {
2304
+ if (e && Array.isArray(e)) this._iceServers = e;
2305
+ else {
2306
+ const n = this.options.env === "development";
2307
+ this._iceServers = n ? Mn : On;
2308
+ }
2309
+ }
2310
+ get iceServers() {
2311
+ return this._iceServers;
2312
+ }
2313
+ set speaker(e) {
2314
+ this._speaker = e;
2315
+ }
2316
+ get speaker() {
2317
+ return this._speaker;
2318
+ }
2319
+ set localElement(e) {
2320
+ this._localElement = De(e);
2321
+ }
2322
+ get localElement() {
2323
+ return this._localElement;
2324
+ }
2325
+ set remoteElement(e) {
2326
+ this._remoteElement = De(e);
2327
+ }
2328
+ get remoteElement() {
2329
+ return this._remoteElement;
2330
+ }
2331
+ vertoBroadcast({ nodeId: e, channel: n = "", data: i }) {
2332
+ if (!n) throw new Error(`Invalid channel for broadcast: ${n}`);
2333
+ const s = new ei({ sessid: this.sessionid, eventChannel: n, data: i });
2334
+ e && (s.targetNodeId = e), this.execute(s).catch(((a) => a));
2335
+ }
2336
+ vertoSubscribe({ nodeId: e, channels: n = [], handler: i }) {
2337
+ return O(this, void 0, void 0, (function* () {
2338
+ if (!(n = n.filter(((d) => d && !this._existsSubscription(this.relayProtocol, d)))).length) return {};
2339
+ const s = new ti({ sessid: this.sessionid, eventChannel: n });
2340
+ e && (s.targetNodeId = e);
2341
+ const a = yield this.execute(s), { unauthorized: o = [], subscribed: l = [] } = it(a);
2342
+ return o.length && o.forEach(((d) => this._removeSubscription(this.relayProtocol, d))), l.forEach(((d) => this._addSubscription(this.relayProtocol, i, d))), a;
2343
+ }));
2344
+ }
2345
+ vertoUnsubscribe({ nodeId: e, channels: n = [] }) {
2346
+ return O(this, void 0, void 0, (function* () {
2347
+ if (!(n = n.filter(((l) => l && this._existsSubscription(this.relayProtocol, l)))).length) return {};
2348
+ const i = new ni({ sessid: this.sessionid, eventChannel: n });
2349
+ e && (i.targetNodeId = e);
2350
+ const s = yield this.execute(i), { unsubscribed: a = [], notSubscribed: o = [] } = it(s);
2351
+ return a.forEach(((l) => this._removeSubscription(this.relayProtocol, l))), o.forEach(((l) => this._removeSubscription(this.relayProtocol, l))), s;
2352
+ }));
2353
+ }
2354
+ _setupNetworkListeners() {
2355
+ typeof window < "u" && (this._onlineHandler = () => {
2356
+ this._wasOffline && (y.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`), this.socketDisconnect(), this.connect()), this._wasOffline = !1;
2357
+ }, this._offlineHandler = () => {
2358
+ this._wasOffline = !0, y.debug(`Network connectivity lost for session ${this.sessionid}`);
2359
+ }, window.addEventListener("online", this._onlineHandler), window.addEventListener("offline", this._offlineHandler));
2360
+ }
2361
+ _cleanupNetworkListeners() {
2362
+ typeof window < "u" && this._onlineHandler && this._offlineHandler && (window.removeEventListener("online", this._onlineHandler), window.removeEventListener("offline", this._offlineHandler), this._onlineHandler = null, this._offlineHandler = null);
2363
+ }
2364
+ static telnyxStateCall(e) {
2365
+ return he.setStateTelnyx(e);
2366
+ }
2367
+ }
2368
+ class Ot {
2369
+ constructor(e, n) {
2370
+ this.code = n, this.message = e;
2371
+ }
2372
+ }
2373
+ class ln extends Z {
2374
+ constructor(e) {
2375
+ super(), this.method = "anonymous_login";
2376
+ const { target_type: n, target_id: i, target_version_id: s, userVariables: a, sessionId: o, reconnection: l } = e, d = { target_type: n, target_id: i, userVariables: a, reconnection: l, "User-Agent": { sdkVersion: We, data: navigator.userAgent } };
2377
+ o && (d.sessid = o), s && (d.target_version_id = s), this.buildRequest({ method: this.method, params: d });
2378
+ }
2379
+ }
2380
+ const pi = We;
2381
+ class J {
2382
+ constructor(e) {
2383
+ this.session = e, this.handleLogin = () => O(this, void 0, void 0, (function* () {
2384
+ const { login: n, password: i, passwd: s, login_token: a, userVariables: o } = this.session.options, l = new sn(n, i || s, a, this.session.sessionid, o, !!fe()), d = yield this.session.execute(l).catch(this.session.handleLoginError);
2385
+ d && (this.session.sessionid = d.sessid);
2386
+ })), this.handleAnonymousLogin = () => O(this, void 0, void 0, (function* () {
2387
+ const { anonymous_login: n } = this.session.options, i = new ln({ target_id: n.target_id, target_type: n.target_type, target_version_id: n.target_version_id, sessionId: this.session.sessionid, userVariables: this.session.options.userVariables, reconnection: !!fe() }), s = yield this.session.execute(i).catch(this.session.handleLoginError);
2388
+ s && (this.session.sessionid = s.sessid);
2389
+ }));
2390
+ }
2391
+ _ack(e, n) {
2392
+ const i = new Qn(e, n);
2393
+ this.nodeId && (i.targetNodeId = this.nodeId), this.session.execute(i);
2394
+ }
2395
+ reconnectDelay() {
2396
+ return 1e3 * Kt(2, 6);
2397
+ }
2398
+ handleMessage(e) {
2399
+ var n;
2400
+ const { session: i } = this, { id: s, method: a, params: o = {}, voice_sdk_id: l } = e, d = o?.callID, h = o?.eventChannel, f = o?.eventType, m = a === $.Attach, S = a === $.Punt;
2401
+ let w = !1;
2402
+ if (f === "channelPvtData") return this._handlePvtEvent(o.pvtData);
2403
+ if (d && i.calls.hasOwnProperty(d)) {
2404
+ if (!m) return i.calls[d].handleMessage(e), void this._ack(s, a);
2405
+ w = (i.options.keepConnectionAliveOnSocketClose || i.calls[d].options.keepConnectionAliveOnSocketClose) && !!(!((n = this.session.calls[d].peer) === null || n === void 0) && n.instance), w ? y.info(`[${(/* @__PURE__ */ new Date()).toISOString()}][${d}] re-attaching call due to ATTACH and keepConnectionAliveOnSocketClose`) : (y.info(`[${(/* @__PURE__ */ new Date()).toISOString()}][${d}] Hanging up the call due to ATTACH`), i.calls[d].hangup({}, !1));
2406
+ }
2407
+ if (S && i.options.keepConnectionAliveOnSocketClose) return y.info(`[${(/* @__PURE__ */ new Date()).toISOString()}][${d}] keeping call alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`), this.session.socketDisconnect(), void this._ack(s, a);
2408
+ const C = () => {
2409
+ var _, A, E, P, D, q;
2410
+ const B = { id: d, audio: !0, video: i.options.video, remoteSdp: o.sdp, destinationNumber: o.callee_id_number, remoteCallerName: o.caller_id_name, remoteCallerNumber: o.caller_id_number, callerName: o.callee_id_name, callerNumber: o.callee_id_number, attach: m, mediaSettings: o.mediaSettings, debug: (_ = i.options.debug) !== null && _ !== void 0 && _, debugOutput: (A = i.options.debugOutput) !== null && A !== void 0 ? A : "socket", trickleIce: (E = i.options.trickleIce) !== null && E !== void 0 && E, prefetchIceCandidates: (P = i.options.prefetchIceCandidates) !== null && P !== void 0 && P, forceRelayCandidate: (D = i.options.forceRelayCandidate) !== null && D !== void 0 && D, keepConnectionAliveOnSocketClose: (q = i.options.keepConnectionAliveOnSocketClose) !== null && q !== void 0 && q };
2411
+ o.telnyx_call_control_id && (B.telnyxCallControlId = o.telnyx_call_control_id), o.telnyx_session_id && (B.telnyxSessionId = o.telnyx_session_id), o.telnyx_leg_id && (B.telnyxLegId = o.telnyx_leg_id), o.client_state && (B.clientState = o.client_state), o.dialogParams && o.dialogParams.custom_headers && o.dialogParams.custom_headers.length && (B.customHeaders = o.dialogParams.custom_headers);
2412
+ const x = new he(i, B);
2413
+ return x.nodeId = this.nodeId, x;
2414
+ }, k = new Zt(l), p = new en(l);
2415
+ switch (a) {
2416
+ case $.Ping:
2417
+ this.session.setPingReceived(), this.session.execute(p).then((() => {
2418
+ J.receivedAuthenticationRequired = 0;
2419
+ })).catch(((E) => O(this, void 0, void 0, (function* () {
2420
+ E.code === this.session.authenticationRequiredErrorCode && J.receivedAuthenticationRequired >= 0 && (J.receivedAuthenticationRequired += 1, J.receivedAuthenticationRequired > 1 && this.session.hasAutoReconnect() && (y.warn("Ping failed twice with Authentication Required. Re-logging in..."), Ne(this.session.options) ? this.handleLogin() : Ie(this.session.options) && this.handleAnonymousLogin(), J.receivedAuthenticationRequired = -1));
2421
+ }))));
2422
+ break;
2423
+ case $.Punt:
2424
+ i.disconnect();
2425
+ break;
2426
+ case $.Invite: {
2427
+ const E = C();
2428
+ E.playRingtone(), E.setState(N.Ringing), E.direction = le.Inbound, this._ack(s, a);
2429
+ break;
2430
+ }
2431
+ case $.Attach: {
2432
+ if (w) return void this.session.execute(new ot({ sessid: this.session.sessionid, sdp: this.session.calls[d].peer.instance.localDescription.sdp, dialogParams: this.session.calls[d].options, "User-Agent": `Web-${pi}` }));
2433
+ y.info(`[${(/* @__PURE__ */ new Date()).toISOString()}][${d}] Re-creating call instance.`);
2434
+ const E = C();
2435
+ this.session.autoRecoverCalls ? E.answer() : E.setState(N.Recovering), E.handleMessage(e);
2436
+ break;
2437
+ }
2438
+ case $.Event:
2439
+ case "webrtc.event":
2440
+ if (!h) return void y.error("Verto received an unknown event:", o);
2441
+ const _ = i.relayProtocol, A = h.split(".")[0];
2442
+ i._existsSubscription(_, h) ? F(_, o, h) : h === i.sessionid ? this._handleSessionEvent(o.eventData) : i._existsSubscription(_, A) ? F(_, o, A) : i.calls.hasOwnProperty(h) ? i.calls[h].handleMessage(e) : F(L.Notification, o, i.uuid);
2443
+ break;
2444
+ case $.Info:
2445
+ o.type = oe.generic, F(L.Notification, o, i.uuid);
2446
+ break;
2447
+ case $.ClientReady:
2448
+ this.session.execute(k);
2449
+ break;
2450
+ default: {
2451
+ const E = ht(e);
2452
+ if (E) {
2453
+ switch (E) {
2454
+ case te.REGISTER:
2455
+ case te.REGED:
2456
+ i.connection.previousGatewayState !== te.REGED && i.connection.previousGatewayState !== te.REGISTER && (this.session._triggerKeepAliveTimeoutCheck(), J.retriedRegister = 0, o.type = oe.vertoClientReady, F(L.Ready, o, i.uuid), i.options.trickleIce && (y.debug("Trickle ICE is enabled. Checking Gateway support"), this.session.execute(new on({ candidate: "" })).catch(((P) => {
2457
+ P.code === this.session.invalidMethodErrorCode ? (y.warn("Trickle ICE is not supported by the server, disabling it."), y.debug("Trickle ICE check error:", JSON.stringify(P, null, 2)), i.options.trickleIce = !1) : y.debug("Trickle ICE check:", JSON.stringify(P, null, 2));
2458
+ }))));
2459
+ break;
2460
+ case te.UNREGED:
2461
+ case te.NOREG:
2462
+ if (J.retriedRegister += 1, J.retriedRegister === 5) {
2463
+ J.retriedRegister = 0, F(L.Error, { error: new Ot("Fail to register the user, the server tried 5 times", "UNREGED|NOREG"), sessionId: i.sessionid }, i.uuid);
2464
+ break;
2465
+ }
2466
+ setTimeout((() => {
2467
+ this.session.execute(k);
2468
+ }), this.reconnectDelay());
2469
+ break;
2470
+ case te.FAILED:
2471
+ case te.FAIL_WAIT:
2472
+ if (i.connection.previousGatewayState !== te.FAILED && i.connection.previousGatewayState !== te.FAIL_WAIT) {
2473
+ if (!this.session.hasAutoReconnect()) {
2474
+ J.retriedConnect = 0, F(L.Error, { error: new Ot("Fail to connect the server, the server tried 5 times", "FAILED|FAIL_WAIT"), sessionId: i.sessionid }, i.uuid);
2475
+ break;
2476
+ }
2477
+ if (J.retriedConnect += 1, J.retriedConnect === 5) {
2478
+ J.retriedConnect = 0, F(L.Error, { error: new Error("Connection Retry Failed"), sessionId: i.sessionid }, i.uuid);
2479
+ break;
2480
+ }
2481
+ setTimeout((() => {
2482
+ if (y.debug(`Reconnecting... Retry ${J.retriedConnect} of 5`), this.session.options.keepConnectionAliveOnSocketClose) return y.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."), this.session.socketDisconnect(), void this.session.connect();
2483
+ this.session.disconnect().then((() => {
2484
+ this.session.clearConnection(), this.session.connect();
2485
+ }));
2486
+ }), this.reconnectDelay());
2487
+ }
2488
+ break;
2489
+ default:
2490
+ y.warn("GatewayState message unknown method:", e);
2491
+ }
2492
+ break;
2493
+ }
2494
+ y.debug("Verto message unknown method:", e);
2495
+ break;
2496
+ }
2497
+ }
2498
+ }
2499
+ _retrieveCallId(e, n) {
2500
+ const i = Object.keys(this.session.calls);
2501
+ if (e.action !== "bootObj") return i.find(((s) => this.session.calls[s].channels.includes(n)));
2502
+ {
2503
+ const s = e.data.find(((a) => i.includes(a[0])));
2504
+ if (s instanceof Array) return s[0];
2505
+ }
2506
+ }
2507
+ _handlePvtEvent(e) {
2508
+ return O(this, void 0, void 0, (function* () {
2509
+ const { session: n } = this, i = n.relayProtocol, { action: s, laChannel: a, laName: o, chatChannel: l, infoChannel: d, modChannel: h, conferenceMemberID: f, role: m, callID: S } = e;
2510
+ switch (s) {
2511
+ case "conference-liveArray-join": {
2512
+ const w = () => {
2513
+ n.vertoBroadcast({ nodeId: this.nodeId, channel: a, data: { liveArray: { command: "bootstrap", context: a, name: o } } });
2514
+ }, C = { nodeId: this.nodeId, channels: [a], handler: ({ data: p }) => {
2515
+ const _ = S || this._retrieveCallId(p, a);
2516
+ if (_ && n.calls.hasOwnProperty(_)) {
2517
+ const A = n.calls[_];
2518
+ A._addChannel(a), A.extension = o, A.handleConferenceUpdate(p, e).then(((E) => {
2519
+ E === "INVALID_PACKET" && w();
2520
+ }));
2521
+ }
2522
+ } }, k = yield n.vertoSubscribe(C).catch(((p) => {
2523
+ y.error("liveArray subscription error:", p);
2524
+ }));
2525
+ nt(k, a) && w();
2526
+ break;
2527
+ }
2528
+ case "conference-liveArray-part": {
2529
+ let w = null;
2530
+ if (a && n._existsSubscription(i, a)) {
2531
+ const { callId: k = null } = n.subscriptions[i][a];
2532
+ if (w = n.calls[k] || null, k !== null) {
2533
+ const p = { type: oe.conferenceUpdate, action: se.Leave, conferenceName: o, participantId: Number(f), role: m };
2534
+ F(L.Notification, p, k, !1) || F(L.Notification, p, n.uuid), w === null && ue(L.Notification, null, k);
2535
+ }
2536
+ }
2537
+ const C = [a, l, d, h];
2538
+ n.vertoUnsubscribe({ nodeId: this.nodeId, channels: C }).then((({ unsubscribedChannels: k = [] }) => {
2539
+ w && (w.channels = w.channels.filter(((p) => !k.includes(p))));
2540
+ })).catch(((k) => {
2541
+ y.error("liveArray unsubscribe error:", k);
2542
+ }));
2543
+ break;
2544
+ }
2545
+ }
2546
+ }));
2547
+ }
2548
+ _handleSessionEvent(e) {
2549
+ switch (e.contentType) {
2550
+ case "layout-info":
2551
+ case "layer-info":
2552
+ an(this.session, e);
2553
+ break;
2554
+ case "logo-info": {
2555
+ const n = { type: oe.conferenceUpdate, action: se.LogoInfo, logo: e.logoURL };
2556
+ F(L.Notification, n, this.session.uuid);
2557
+ break;
2558
+ }
2559
+ }
2560
+ }
2561
+ }
2562
+ J.retriedConnect = 0, J.retriedRegister = 0, J.receivedAuthenticationRequired = 0;
2563
+ class fi extends hi {
2564
+ constructor(e) {
2565
+ super(e), this.relayProtocol = "verto-protocol", this.timeoutErrorCode = -329990, this.handleLoginOnSocketOpen = () => O(this, void 0, void 0, (function* () {
2566
+ this._idle = !1;
2567
+ const { login: n, password: i, passwd: s, login_token: a, userVariables: o, autoReconnect: l = !0 } = this.options, d = new sn(n, i || s, a, this.sessionid, o, !!fe()), h = yield this.execute(d).catch(this._handleLoginError);
2568
+ h && (this._autoReconnect = l, this.sessionid = h.sessid);
2569
+ })), this.handleAnonymousLoginOnSocketOpen = () => O(this, void 0, void 0, (function* () {
2570
+ this._idle = !1;
2571
+ const { anonymous_login: n } = this.options, i = new ln({ target_id: n.target_id, target_type: n.target_type, target_version_id: n.target_version_id, sessionId: this.sessionid, userVariables: this.options.userVariables, reconnection: !!fe() }), s = yield this.execute(i).catch(this._handleLoginError);
2572
+ s && (this.sessionid = s.sessid);
2573
+ })), window.addEventListener("beforeunload", ((n) => {
2574
+ this.calls && Object.keys(this.calls).forEach(((i) => {
2575
+ this.calls[i] && (y.info(`Hanging up call due to window unload: ${i}`), this.calls[i].hangup({}, !0));
2576
+ }));
2577
+ }));
2578
+ }
2579
+ validateOptions() {
2580
+ return Ne(this.options) || Ie(this.options);
2581
+ }
2582
+ newCall(e) {
2583
+ if (!this.validateCallOptions(e)) throw new Error("Verto.newCall() error: destinationNumber is required.");
2584
+ performance.mark("new-call-start");
2585
+ const n = new he(this, e);
2586
+ return n.invite(), performance.mark("new-call-end"), n;
2587
+ }
2588
+ broadcast(e) {
2589
+ return this.vertoBroadcast(e);
2590
+ }
2591
+ subscribe(e) {
2592
+ return this.vertoSubscribe(e);
2593
+ }
2594
+ unsubscribe(e) {
2595
+ return this.vertoUnsubscribe(e);
2596
+ }
2597
+ validateCallOptions(e) {
2598
+ return !!Ie(this.options) || !!e.destinationNumber;
2599
+ }
2600
+ _onSocketOpen() {
2601
+ return O(this, void 0, void 0, (function* () {
2602
+ return Ne(this.options) ? this.handleLoginOnSocketOpen() : Ie(this.options) ? this.handleAnonymousLoginOnSocketOpen() : void 0;
2603
+ }));
2604
+ }
2605
+ _onSocketMessage(e) {
2606
+ new J(this).handleMessage(e);
2607
+ }
2608
+ }
2609
+ class gi extends fi {
2610
+ constructor(e) {
2611
+ super(e), y.info(`SDK version: ${nn}`);
2612
+ }
2613
+ newCall(e) {
2614
+ return super.newCall(e);
2615
+ }
2616
+ static webRTCInfo() {
2617
+ return Kn();
2618
+ }
2619
+ static webRTCSupportedBrowserList() {
2620
+ return [{ operationSystem: "Android", supported: [{ browserName: "Chrome", features: ["audio"], supported: H.full }, { browserName: "Firefox", features: ["audio"], supported: H.partial }, { browserName: "Safari", supported: H.not_supported }, { browserName: "Edge", supported: H.not_supported }] }, { operationSystem: "iOS", supported: [{ browserName: "Chrome", supported: H.not_supported }, { browserName: "Firefox", supported: H.not_supported }, { browserName: "Safari", features: ["video", "audio"], supported: H.full }, { browserName: "Edge", supported: H.not_supported }] }, { operationSystem: "Linux", supported: [{ browserName: "Chrome", features: ["video", "audio"], supported: H.full }, { browserName: "Firefox", features: ["audio"], supported: H.partial }, { browserName: "Safari", supported: H.not_supported }, { browserName: "Edge", supported: H.not_supported }] }, { operationSystem: "MacOS", supported: [{ browserName: "Chrome", features: ["video", "audio"], supported: H.full }, { browserName: "Firefox", features: ["audio"], supported: H.partial }, { browserName: "Safari", features: ["video", "audio"], supported: H.full }, { browserName: "Edge", features: ["audio"], supported: H.partial }] }, { operationSystem: "Windows", supported: [{ browserName: "Chrome", features: ["video", "audio"], supported: H.full }, { browserName: "Firefox", features: ["audio"], supported: H.partial }, { browserName: "Safari", supported: H.not_supported }, { browserName: "Edge", features: ["audio"], supported: H.partial }] }];
2621
+ }
2622
+ }
2623
+ function dn(t) {
2624
+ return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
2625
+ }
2626
+ var Xe = { exports: {} }, Mt;
2627
+ function mi() {
2628
+ return Mt || (Mt = 1, (function(t) {
2629
+ var e = Object.prototype.hasOwnProperty, n = "~";
2630
+ function i() {
2631
+ }
2632
+ Object.create && (i.prototype = /* @__PURE__ */ Object.create(null), new i().__proto__ || (n = !1));
2633
+ function s(d, h, f) {
2634
+ this.fn = d, this.context = h, this.once = f || !1;
2635
+ }
2636
+ function a(d, h, f, m, S) {
2637
+ if (typeof f != "function")
2638
+ throw new TypeError("The listener must be a function");
2639
+ var w = new s(f, m || d, S), C = n ? n + h : h;
2640
+ return d._events[C] ? d._events[C].fn ? d._events[C] = [d._events[C], w] : d._events[C].push(w) : (d._events[C] = w, d._eventsCount++), d;
2641
+ }
2642
+ function o(d, h) {
2643
+ --d._eventsCount === 0 ? d._events = new i() : delete d._events[h];
2644
+ }
2645
+ function l() {
2646
+ this._events = new i(), this._eventsCount = 0;
2647
+ }
2648
+ l.prototype.eventNames = function() {
2649
+ var h = [], f, m;
2650
+ if (this._eventsCount === 0) return h;
2651
+ for (m in f = this._events)
2652
+ e.call(f, m) && h.push(n ? m.slice(1) : m);
2653
+ return Object.getOwnPropertySymbols ? h.concat(Object.getOwnPropertySymbols(f)) : h;
2654
+ }, l.prototype.listeners = function(h) {
2655
+ var f = n ? n + h : h, m = this._events[f];
2656
+ if (!m) return [];
2657
+ if (m.fn) return [m.fn];
2658
+ for (var S = 0, w = m.length, C = new Array(w); S < w; S++)
2659
+ C[S] = m[S].fn;
2660
+ return C;
2661
+ }, l.prototype.listenerCount = function(h) {
2662
+ var f = n ? n + h : h, m = this._events[f];
2663
+ return m ? m.fn ? 1 : m.length : 0;
2664
+ }, l.prototype.emit = function(h, f, m, S, w, C) {
2665
+ var k = n ? n + h : h;
2666
+ if (!this._events[k]) return !1;
2667
+ var p = this._events[k], _ = arguments.length, A, E;
2668
+ if (p.fn) {
2669
+ switch (p.once && this.removeListener(h, p.fn, void 0, !0), _) {
2670
+ case 1:
2671
+ return p.fn.call(p.context), !0;
2672
+ case 2:
2673
+ return p.fn.call(p.context, f), !0;
2674
+ case 3:
2675
+ return p.fn.call(p.context, f, m), !0;
2676
+ case 4:
2677
+ return p.fn.call(p.context, f, m, S), !0;
2678
+ case 5:
2679
+ return p.fn.call(p.context, f, m, S, w), !0;
2680
+ case 6:
2681
+ return p.fn.call(p.context, f, m, S, w, C), !0;
2682
+ }
2683
+ for (E = 1, A = new Array(_ - 1); E < _; E++)
2684
+ A[E - 1] = arguments[E];
2685
+ p.fn.apply(p.context, A);
2686
+ } else {
2687
+ var P = p.length, D;
2688
+ for (E = 0; E < P; E++)
2689
+ switch (p[E].once && this.removeListener(h, p[E].fn, void 0, !0), _) {
2690
+ case 1:
2691
+ p[E].fn.call(p[E].context);
2692
+ break;
2693
+ case 2:
2694
+ p[E].fn.call(p[E].context, f);
2695
+ break;
2696
+ case 3:
2697
+ p[E].fn.call(p[E].context, f, m);
2698
+ break;
2699
+ case 4:
2700
+ p[E].fn.call(p[E].context, f, m, S);
2701
+ break;
2702
+ default:
2703
+ if (!A) for (D = 1, A = new Array(_ - 1); D < _; D++)
2704
+ A[D - 1] = arguments[D];
2705
+ p[E].fn.apply(p[E].context, A);
2706
+ }
2707
+ }
2708
+ return !0;
2709
+ }, l.prototype.on = function(h, f, m) {
2710
+ return a(this, h, f, m, !1);
2711
+ }, l.prototype.once = function(h, f, m) {
2712
+ return a(this, h, f, m, !0);
2713
+ }, l.prototype.removeListener = function(h, f, m, S) {
2714
+ var w = n ? n + h : h;
2715
+ if (!this._events[w]) return this;
2716
+ if (!f)
2717
+ return o(this, w), this;
2718
+ var C = this._events[w];
2719
+ if (C.fn)
2720
+ C.fn === f && (!S || C.once) && (!m || C.context === m) && o(this, w);
2721
+ else {
2722
+ for (var k = 0, p = [], _ = C.length; k < _; k++)
2723
+ (C[k].fn !== f || S && !C[k].once || m && C[k].context !== m) && p.push(C[k]);
2724
+ p.length ? this._events[w] = p.length === 1 ? p[0] : p : o(this, w);
2725
+ }
2726
+ return this;
2727
+ }, l.prototype.removeAllListeners = function(h) {
2728
+ var f;
2729
+ return h ? (f = n ? n + h : h, this._events[f] && o(this, f)) : (this._events = new i(), this._eventsCount = 0), this;
2730
+ }, l.prototype.off = l.prototype.removeListener, l.prototype.addListener = l.prototype.on, l.prefixed = n, l.EventEmitter = l, t.exports = l;
2731
+ })(Xe)), Xe.exports;
2732
+ }
2733
+ var vi = mi();
2734
+ const ft = /* @__PURE__ */ dn(vi), Fe = new ft();
2735
+ var Pe = { exports: {} }, yi = Pe.exports, Pt;
2736
+ function bi() {
2737
+ return Pt || (Pt = 1, (function(t) {
2738
+ (function(e, n) {
2739
+ t.exports ? t.exports = n() : e.log = n();
2740
+ })(yi, function() {
2741
+ var e = function() {
2742
+ }, n = "undefined", i = typeof window !== n && typeof window.navigator !== n && /Trident\/|MSIE /.test(window.navigator.userAgent), s = [
2743
+ "trace",
2744
+ "debug",
2745
+ "info",
2746
+ "warn",
2747
+ "error"
2748
+ ], a = {}, o = null;
2749
+ function l(k, p) {
2750
+ var _ = k[p];
2751
+ if (typeof _.bind == "function")
2752
+ return _.bind(k);
2753
+ try {
2754
+ return Function.prototype.bind.call(_, k);
2755
+ } catch {
2756
+ return function() {
2757
+ return Function.prototype.apply.apply(_, [k, arguments]);
2758
+ };
2759
+ }
2760
+ }
2761
+ function d() {
2762
+ console.log && (console.log.apply ? console.log.apply(console, arguments) : Function.prototype.apply.apply(console.log, [console, arguments])), console.trace && console.trace();
2763
+ }
2764
+ function h(k) {
2765
+ return k === "debug" && (k = "log"), typeof console === n ? !1 : k === "trace" && i ? d : console[k] !== void 0 ? l(console, k) : console.log !== void 0 ? l(console, "log") : e;
2766
+ }
2767
+ function f() {
2768
+ for (var k = this.getLevel(), p = 0; p < s.length; p++) {
2769
+ var _ = s[p];
2770
+ this[_] = p < k ? e : this.methodFactory(_, k, this.name);
2771
+ }
2772
+ if (this.log = this.debug, typeof console === n && k < this.levels.SILENT)
2773
+ return "No console available for logging";
2774
+ }
2775
+ function m(k) {
2776
+ return function() {
2777
+ typeof console !== n && (f.call(this), this[k].apply(this, arguments));
2778
+ };
2779
+ }
2780
+ function S(k, p, _) {
2781
+ return h(k) || m.apply(this, arguments);
2782
+ }
2783
+ function w(k, p) {
2784
+ var _ = this, A, E, P, D = "loglevel";
2785
+ typeof k == "string" ? D += ":" + k : typeof k == "symbol" && (D = void 0);
2786
+ function q(u) {
2787
+ var g = (s[u] || "silent").toUpperCase();
2788
+ if (!(typeof window === n || !D)) {
2789
+ try {
2790
+ window.localStorage[D] = g;
2791
+ return;
2792
+ } catch {
2793
+ }
2794
+ try {
2795
+ window.document.cookie = encodeURIComponent(D) + "=" + g + ";";
2796
+ } catch {
2797
+ }
2798
+ }
2799
+ }
2800
+ function B() {
2801
+ var u;
2802
+ if (!(typeof window === n || !D)) {
2803
+ try {
2804
+ u = window.localStorage[D];
2805
+ } catch {
2806
+ }
2807
+ if (typeof u === n)
2808
+ try {
2809
+ var g = window.document.cookie, b = encodeURIComponent(D), T = g.indexOf(b + "=");
2810
+ T !== -1 && (u = /^([^;]+)/.exec(
2811
+ g.slice(T + b.length + 1)
2812
+ )[1]);
2813
+ } catch {
2814
+ }
2815
+ return _.levels[u] === void 0 && (u = void 0), u;
2816
+ }
2817
+ }
2818
+ function x() {
2819
+ if (!(typeof window === n || !D)) {
2820
+ try {
2821
+ window.localStorage.removeItem(D);
2822
+ } catch {
2823
+ }
2824
+ try {
2825
+ window.document.cookie = encodeURIComponent(D) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
2826
+ } catch {
2827
+ }
2828
+ }
2829
+ }
2830
+ function r(u) {
2831
+ var g = u;
2832
+ if (typeof g == "string" && _.levels[g.toUpperCase()] !== void 0 && (g = _.levels[g.toUpperCase()]), typeof g == "number" && g >= 0 && g <= _.levels.SILENT)
2833
+ return g;
2834
+ throw new TypeError("log.setLevel() called with invalid level: " + u);
2835
+ }
2836
+ _.name = k, _.levels = {
2837
+ TRACE: 0,
2838
+ DEBUG: 1,
2839
+ INFO: 2,
2840
+ WARN: 3,
2841
+ ERROR: 4,
2842
+ SILENT: 5
2843
+ }, _.methodFactory = p || S, _.getLevel = function() {
2844
+ return P ?? E ?? A;
2845
+ }, _.setLevel = function(u, g) {
2846
+ return P = r(u), g !== !1 && q(P), f.call(_);
2847
+ }, _.setDefaultLevel = function(u) {
2848
+ E = r(u), B() || _.setLevel(u, !1);
2849
+ }, _.resetLevel = function() {
2850
+ P = null, x(), f.call(_);
2851
+ }, _.enableAll = function(u) {
2852
+ _.setLevel(_.levels.TRACE, u);
2853
+ }, _.disableAll = function(u) {
2854
+ _.setLevel(_.levels.SILENT, u);
2855
+ }, _.rebuild = function() {
2856
+ if (o !== _ && (A = r(o.getLevel())), f.call(_), o === _)
2857
+ for (var u in a)
2858
+ a[u].rebuild();
2859
+ }, A = r(
2860
+ o ? o.getLevel() : "WARN"
2861
+ );
2862
+ var c = B();
2863
+ c != null && (P = r(c)), f.call(_);
2864
+ }
2865
+ o = new w(), o.getLogger = function(p) {
2866
+ if (typeof p != "symbol" && typeof p != "string" || p === "")
2867
+ throw new TypeError("You must supply a name when creating a logger.");
2868
+ var _ = a[p];
2869
+ return _ || (_ = a[p] = new w(
2870
+ p,
2871
+ o.methodFactory
2872
+ )), _;
2873
+ };
2874
+ var C = typeof window !== n ? window.log : void 0;
2875
+ return o.noConflict = function() {
2876
+ return typeof window !== n && window.log === o && (window.log = C), o;
2877
+ }, o.getLoggers = function() {
2878
+ return a;
2879
+ }, o.default = o, o;
2880
+ });
2881
+ })(Pe)), Pe.exports;
2882
+ }
2883
+ var Si = bi();
2884
+ const _i = /* @__PURE__ */ dn(Si), wi = () => (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", ""), z = _i.getLogger("telnyx-ai-agent"), Ci = z.methodFactory;
2885
+ z.methodFactory = (t, e, n) => {
2886
+ const i = Ci(t, e, n);
2887
+ return function(...s) {
2888
+ i(wi(), "-", ...s);
2889
+ };
2890
+ };
2891
+ z.setLevel("info");
2892
+ function ki(t, e) {
2893
+ let n = 0;
2894
+ return (...i) => {
2895
+ const s = Date.now();
2896
+ s - n >= e && (n = s, t(...i));
2897
+ };
2898
+ }
2899
+ const Ii = 10, Ei = 500, Ti = 100, Dt = 20;
2900
+ class Ai {
2901
+ remoteIntervalId = null;
2902
+ localIntervalId = null;
2903
+ remoteStream = null;
2904
+ localStream = null;
2905
+ remoteAudioContext = null;
2906
+ remoteSource = null;
2907
+ remoteAnalyser = null;
2908
+ localAudioContext = null;
2909
+ localSource = null;
2910
+ localAnalyser = null;
2911
+ thinkingStartTime = null;
2912
+ lastState = null;
2913
+ // Local stream (user) state tracking
2914
+ userIsSpeaking = !1;
2915
+ lastUserAudioTime = null;
2916
+ userSpeechStartTime = null;
2917
+ // Latency measurement tracking
2918
+ userSilenceStartTime = null;
2919
+ isFirstAgentSpeech = !0;
2920
+ monitorStartTime = null;
2921
+ // Configurable VAD options
2922
+ volumeThreshold;
2923
+ silenceDurationMs;
2924
+ minSpeechDurationMs;
2925
+ maxLatencyMs;
2926
+ constructor(e) {
2927
+ this.volumeThreshold = e?.volumeThreshold ?? Ii, this.silenceDurationMs = e?.silenceDurationMs ?? Ei, this.minSpeechDurationMs = e?.minSpeechDurationMs ?? Ti, this.maxLatencyMs = e?.maxLatencyMs;
2928
+ }
2929
+ updateAgentState = ki((e) => {
2930
+ z.debug("AudioStreamMonitor updateAgentState", e), z.debug("Previous state:", this.lastState), e.state !== this.lastState && (this.lastState = e.state, Fe.emit("conversation.agent.state", e));
2931
+ }, 100);
2932
+ /**
2933
+ * Set the remote audio stream (agent's voice) to monitor for speech detection
2934
+ */
2935
+ setRemoteStream(e) {
2936
+ this.remoteStream && this.stopRemoteMonitor(), this.remoteStream = e, this.startRemoteMonitor();
2937
+ }
2938
+ /**
2939
+ * Set the local audio stream (user's microphone) to monitor for VAD
2940
+ */
2941
+ setLocalStream(e) {
2942
+ this.localStream && this.stopLocalMonitor(), this.localStream = e, this.startLocalMonitor();
2943
+ }
2944
+ // Legacy method for backwards compatibility
2945
+ setMonitoredAudioStream(e) {
2946
+ this.setRemoteStream(e);
2947
+ }
2948
+ stopRemoteMonitor() {
2949
+ this.remoteIntervalId && (clearInterval(this.remoteIntervalId), this.remoteIntervalId = null), this.remoteSource?.disconnect(), this.remoteAudioContext?.close(), this.remoteAudioContext = null, this.remoteSource = null, this.remoteAnalyser = null;
2950
+ }
2951
+ stopLocalMonitor() {
2952
+ this.localIntervalId && (clearInterval(this.localIntervalId), this.localIntervalId = null), this.localSource?.disconnect(), this.localAudioContext?.close(), this.localAudioContext = null, this.localSource = null, this.localAnalyser = null;
2953
+ }
2954
+ /**
2955
+ * Reset all latency tracking state for a fresh call.
2956
+ * Should be called when a call ends to prevent stale data affecting the next call.
2957
+ */
2958
+ resetLatencyState() {
2959
+ this.thinkingStartTime = null, this.lastState = null, this.userIsSpeaking = !1, this.lastUserAudioTime = null, this.userSpeechStartTime = null, this.userSilenceStartTime = null, this.isFirstAgentSpeech = !0, this.monitorStartTime = null;
2960
+ }
2961
+ stopAudioStreamMonitor() {
2962
+ this.stopRemoteMonitor(), this.stopLocalMonitor(), this.resetLatencyState();
2963
+ }
2964
+ /**
2965
+ * Monitor remote stream (agent's audio) for speech detection
2966
+ * Detects when agent starts speaking to calculate latency
2967
+ */
2968
+ startRemoteMonitor() {
2969
+ if (!this.remoteStream) {
2970
+ z.debug("Remote monitor: no stream, skipping");
2971
+ return;
2972
+ }
2973
+ this.monitorStartTime = performance.now(), this.remoteAudioContext = new AudioContext(), z.debug("Remote AudioContext state:", this.remoteAudioContext.state), this.remoteAudioContext.state === "suspended" && (z.debug("Resuming suspended AudioContext..."), this.remoteAudioContext.resume().then(() => {
2974
+ z.debug("AudioContext resumed, state:", this.remoteAudioContext?.state);
2975
+ })), this.remoteSource = this.remoteAudioContext.createMediaStreamSource(
2976
+ this.remoteStream
2977
+ ), this.remoteAnalyser = this.remoteAudioContext.createAnalyser(), this.remoteSource.connect(this.remoteAnalyser);
2978
+ const e = this.remoteAudioContext.createGain();
2979
+ e.gain.value = 0, this.remoteAnalyser.connect(e), e.connect(this.remoteAudioContext.destination), this.remoteAnalyser.fftSize = 512;
2980
+ const n = new Uint8Array(this.remoteAnalyser.frequencyBinCount);
2981
+ let i = !1;
2982
+ const s = () => {
2983
+ this.remoteAnalyser?.getByteFrequencyData(n);
2984
+ const a = n.reduce((l, d) => l + d, 0) / n.length, o = a >= this.volumeThreshold;
2985
+ if (Math.random() < 0.01 && z.debug("Remote audio volume:", a, "threshold:", this.volumeThreshold, "above:", o), o)
2986
+ if (i)
2987
+ this.updateAgentState({ state: "speaking" });
2988
+ else if (this.isFirstAgentSpeech && this.monitorStartTime !== null) {
2989
+ const l = Math.round(performance.now() - this.monitorStartTime);
2990
+ this.isFirstAgentSpeech = !1, this.thinkingStartTime = null, this.userSilenceStartTime = null, this.userSpeechStartTime = null, this.updateAgentState({ state: "speaking", greetingLatencyMs: l });
2991
+ } else if (this.userSilenceStartTime !== null) {
2992
+ const l = Math.round(performance.now() - this.userSilenceStartTime);
2993
+ this.thinkingStartTime = null, this.userSilenceStartTime = null, this.maxLatencyMs === void 0 || l < this.maxLatencyMs ? this.updateAgentState({ state: "speaking", userPerceivedLatencyMs: l }) : this.updateAgentState({ state: "speaking" });
2994
+ } else
2995
+ this.updateAgentState({ state: "speaking" });
2996
+ else
2997
+ this.thinkingStartTime === null && this.updateAgentState({ state: "listening" });
2998
+ i = o;
2999
+ };
3000
+ this.remoteIntervalId = window.setInterval(s, Dt);
3001
+ }
3002
+ /**
3003
+ * Monitor local stream (user's microphone) for VAD
3004
+ * Detects when user stops speaking (1000ms of silence) to start latency measurement
3005
+ */
3006
+ startLocalMonitor() {
3007
+ if (!this.localStream) {
3008
+ z.debug("Local monitor: no stream, skipping");
3009
+ return;
3010
+ }
3011
+ this.localAudioContext = new AudioContext(), z.debug("Local AudioContext state:", this.localAudioContext.state), this.localAudioContext.state === "suspended" && (z.debug("Resuming suspended local AudioContext..."), this.localAudioContext.resume()), this.localSource = this.localAudioContext.createMediaStreamSource(
3012
+ this.localStream
3013
+ ), this.localAnalyser = this.localAudioContext.createAnalyser(), this.localSource.connect(this.localAnalyser), this.localAnalyser.fftSize = 512;
3014
+ const e = new Uint8Array(this.localAnalyser.frequencyBinCount), n = () => {
3015
+ this.localAnalyser?.getByteFrequencyData(e);
3016
+ const i = e.reduce((a, o) => a + o, 0) / e.length;
3017
+ if (Math.random() < 0.02 && z.debug("Local audio volume:", i), i >= this.volumeThreshold)
3018
+ this.userIsSpeaking || (this.userIsSpeaking = !0, this.userSpeechStartTime = performance.now(), this.userSilenceStartTime = null), this.lastUserAudioTime = performance.now();
3019
+ else if (this.userIsSpeaking && this.lastUserAudioTime !== null && (this.lastUserAudioTime - (this.userSpeechStartTime || this.lastUserAudioTime) >= this.minSpeechDurationMs && this.userSilenceStartTime === null && (this.userSilenceStartTime = this.lastUserAudioTime), performance.now() - this.lastUserAudioTime > this.silenceDurationMs)) {
3020
+ this.userIsSpeaking = !1, this.userSpeechStartTime = null, this.thinkingStartTime = performance.now();
3021
+ const l = (/* @__PURE__ */ new Date()).toISOString();
3022
+ this.updateAgentState({ state: "thinking", thinkingStartedAt: l });
3023
+ }
3024
+ };
3025
+ this.localIntervalId = window.setInterval(n, Dt);
3026
+ }
3027
+ destroy() {
3028
+ this.stopAudioStreamMonitor();
3029
+ }
3030
+ }
3031
+ function Ri(t) {
3032
+ if (!t || typeof t != "object")
3033
+ return !1;
3034
+ const e = t;
3035
+ return e.method === "ai_conversation" && typeof e.params == "object";
3036
+ }
3037
+ function xi(t) {
3038
+ if (!t || typeof t != "object")
3039
+ return !1;
3040
+ const e = t;
3041
+ return e.params.type !== "response.text.delta" ? !1 : !!e.params.delta;
3042
+ }
3043
+ function Li(t) {
3044
+ if (!t || typeof t != "object")
3045
+ return !1;
3046
+ const e = t;
3047
+ return e.params.type !== "conversation.item.created" ? !1 : !!e.params.item.content;
3048
+ }
3049
+ function Oi(t) {
3050
+ if (!t || typeof t != "object")
3051
+ return !1;
3052
+ const e = t;
3053
+ return e.params?.type !== "conversation.item.deleted" ? !1 : !!e.params.item_id;
3054
+ }
3055
+ function Mi(t) {
3056
+ return xi(t) ? {
3057
+ id: `${t.params.item_id}-${Date.now()}`,
3058
+ role: "assistant",
3059
+ content: t.params.delta,
3060
+ timestamp: /* @__PURE__ */ new Date()
3061
+ } : null;
3062
+ }
3063
+ function Pi(t) {
3064
+ if (!Li(t) || t.params.item.role !== "user" || t.params.item.status !== "completed")
3065
+ return null;
3066
+ let e = "", n = [];
3067
+ return Array.isArray(t.params.item.content) ? (e = t.params.item.content.reduce((i, s) => (s.type === "text" && (i += s.text), i), ""), n = t.params.item.content.reduce((i, s) => (s.type === "image_url" && s.image_url.url && i.push({ type: "image", url: s.image_url.url }), i), [])) : e = t.params.item.content, {
3068
+ id: t.params.item.id,
3069
+ role: t.params.item.role,
3070
+ timestamp: /* @__PURE__ */ new Date(),
3071
+ content: e,
3072
+ attachments: n
3073
+ };
3074
+ }
3075
+ class Di extends ft {
3076
+ telnyxRTC;
3077
+ transcript = [];
3078
+ constructor(e) {
3079
+ super(), this.telnyxRTC = e, this.telnyxRTC.on(L.SocketMessage, this.onSocketMessage);
3080
+ }
3081
+ onSocketMessage = (e) => {
3082
+ if (Ri(e))
3083
+ switch (e.params.type) {
3084
+ case "response.text.delta": {
3085
+ const n = Mi(e);
3086
+ n && (this.transcript.push(n), this.emit("transcript.item", n), Fe.emit("conversation.agent.state", { state: "listening" }));
3087
+ return;
3088
+ }
3089
+ case "conversation.item.deleted": {
3090
+ if (Oi(e)) {
3091
+ const n = e.params.item_id, i = this.transcript.findIndex((s) => s.id === n);
3092
+ i !== -1 && this.transcript.splice(i, 1);
3093
+ }
3094
+ return;
3095
+ }
3096
+ case "conversation.item.created": {
3097
+ const n = Pi(e);
3098
+ if (n) {
3099
+ const i = this.transcript.findIndex(
3100
+ (s) => s.id === n.id
3101
+ );
3102
+ i !== -1 ? this.transcript[i] = n : this.transcript.push(n), this.emit("transcript.item", n);
3103
+ }
3104
+ return;
3105
+ }
3106
+ }
3107
+ };
3108
+ }
3109
+ class Nt extends ft {
3110
+ telnyxRTC;
3111
+ transcription;
3112
+ agentId;
3113
+ versionId;
3114
+ debug;
3115
+ audioStreamMonitor;
3116
+ activeCall;
3117
+ constructor(e) {
3118
+ super(), this.agentId = e.agentId, this.versionId = e.versionId || "main", this.debug = e.debug || !1, this.activeCall = null, z.setLevel(this.debug ? "debug" : "info"), this.telnyxRTC = new gi({
3119
+ // @ts-expect-error hidden argument
3120
+ environment: e.environment || "production",
3121
+ anonymous_login: {
3122
+ target_id: e.agentId,
3123
+ target_type: "ai_assistant",
3124
+ target_version_id: e.versionId
3125
+ },
3126
+ debug: e.debug || !1,
3127
+ trickleIce: e.trickleIce
3128
+ }), this.telnyxRTC.on(L.Ready, this.onClientReady), this.telnyxRTC.on(L.Error, this.onClientOrSocketError), this.telnyxRTC.on(L.SocketError, this.onClientOrSocketError), this.telnyxRTC.on(L.Notification, this.onNotification), this.transcription = new Di(this.telnyxRTC), this.transcription.addListener("transcript.item", this.onTranscriptItem), Fe.addListener(
3129
+ "conversation.agent.state",
3130
+ this.onAgentStateChange
3131
+ ), this.audioStreamMonitor = new Ai(e.vad);
3132
+ }
3133
+ /**
3134
+ * Connects to the Telnyx WebRTC service and establishes a session with the AI agent.
3135
+ *
3136
+ * @returns Promise that resolves when the connection is established
3137
+ */
3138
+ async connect() {
3139
+ return this.telnyxRTC.connect();
3140
+ }
3141
+ /**
3142
+ * Disconnects from the Telnyx WebRTC service and cleans up all event listeners.
3143
+ * Emits an 'agent.disconnected' event before completing cleanup.
3144
+ */
3145
+ async disconnect() {
3146
+ this.audioStreamMonitor.destroy(), this.telnyxRTC.disconnect(), this.telnyxRTC.off(L.Ready, this.onClientReady), this.telnyxRTC.off(L.Error, this.onClientOrSocketError), this.telnyxRTC.off(L.SocketError, this.onClientOrSocketError), this.telnyxRTC.off(L.Notification, this.onNotification), this.emit("agent.disconnected"), this.transcription.removeAllListeners(), Fe.removeAllListeners(), this.removeAllListeners();
3147
+ }
3148
+ /**
3149
+ * Sends a text message to the AI agent during an active conversation.
3150
+ * Requires an active conversation to be in progress.
3151
+ *
3152
+ * @param message - The text message to send to the AI agent
3153
+ * @param attachments - Optional array of base64 encoded file attachments (defaults to empty array)
3154
+ *
3155
+ * @example
3156
+ * client.sendConversationMessage('Hello, I need help with my account');
3157
+ *
3158
+ * @example
3159
+ * // With attachments
3160
+ * client.sendConversationMessage('Please review this document', ['base64EncodedData...']);
3161
+ */
3162
+ sendConversationMessage(e, n = []) {
3163
+ if (!this.activeCall) {
3164
+ z.error("No active call to send message.");
3165
+ return;
3166
+ }
3167
+ this.activeCall.sendConversationMessage(e, n);
3168
+ }
3169
+ /**
3170
+ * Gets the current conversation transcript.
3171
+ *
3172
+ * @returns Array of transcript items containing all messages exchanged during the conversation
3173
+ */
3174
+ get transcript() {
3175
+ return this.transcription.transcript;
3176
+ }
3177
+ /**
3178
+ * Initiates a conversation with the AI agent.
3179
+ *
3180
+ * @param options - Optional configuration for the call.
3181
+ * Note: This method will ALWAYS call the AI agent, the optional parameters are primarily used for log referencing or passing parameters to the agent via the custom headers.
3182
+ * @param options.destinationNumber - The destination phone number (defaults to "xxx"). Note, regardless of the destination number, the call will be made to the AI agent.
3183
+ * @param options.callerNumber - The caller's phone number
3184
+ * @param options.callerName - The caller's display name
3185
+ * @param options.customHeaders - Custom SIP headers to pass to the AI agent. Headers with the `X-` prefix
3186
+ * will be mapped to dynamic variables in the AI assistant (e.g., `X-Account-Number` becomes `{{account_number}}`).
3187
+ * Note: Hyphens in header names are converted to underscores in variable names.
3188
+ *
3189
+ * @example
3190
+ * // Start conversation with custom headers for dynamic variables
3191
+ * client.startConversation({
3192
+ * callerName: 'John Doe',
3193
+ * customHeaders: [
3194
+ * { name: 'X-User-Name', value: 'user-name' },
3195
+ * { name: 'X-Agent-Session', value: 'session-abc' }
3196
+ * ]
3197
+ * });
3198
+ * // These headers will be available in your AI assistant as {{user_name}} and {{agent_session}}
3199
+ * @param options.audio - Audio constraints for the call (boolean or MediaTrackConstraints)
3200
+ */
3201
+ async startConversation(e) {
3202
+ if (!this.telnyxRTC) {
3203
+ z.error("Client is not initialized.");
3204
+ return;
3205
+ }
3206
+ const i = RTCRtpReceiver.getCapabilities("audio")?.codecs?.find(
3207
+ (h) => h.mimeType.toLowerCase().includes("opus")
3208
+ ), {
3209
+ customHeaders: s,
3210
+ audio: a,
3211
+ ...o
3212
+ } = e || {}, l = s ? [...s] : [];
3213
+ this.versionId && l.push({
3214
+ name: "X-AI-Assistant-Version-ID",
3215
+ value: this.versionId
3216
+ });
3217
+ const d = this.telnyxRTC.newCall({
3218
+ destinationNumber: "xxx",
3219
+ ...o,
3220
+ audio: a ?? !0,
3221
+ preferred_codecs: [i],
3222
+ customHeaders: l.length > 0 ? l : void 0
3223
+ });
3224
+ this.emit("conversation.update", { call: d, type: "callUpdate" });
3225
+ }
3226
+ /**
3227
+ * Ends the current active conversation with the AI agent.
3228
+ *
3229
+ * @returns Promise that resolves when the call is hung up, or undefined if there is no active call
3230
+ */
3231
+ endConversation() {
3232
+ return this.activeCall?.hangup();
3233
+ }
3234
+ /**
3235
+ * Sets the remote audio stream for monitoring agent speech.
3236
+ * Use this when call.remoteStream is not available and you need to provide
3237
+ * the stream from the peer connection receiver.
3238
+ *
3239
+ * @param stream - The MediaStream containing the remote (agent) audio
3240
+ */
3241
+ setRemoteStream(e) {
3242
+ this.audioStreamMonitor.setRemoteStream(e);
3243
+ }
3244
+ onClientReady = () => {
3245
+ this.emit("agent.connected");
3246
+ };
3247
+ onClientOrSocketError = (e) => {
3248
+ this.emit("agent.error", e);
3249
+ };
3250
+ onNotification = (e) => {
3251
+ e.type !== "callUpdate" || !e.call || (this.emit("conversation.update", e), e.call.state === "active" ? (this.activeCall = e.call, e.call.remoteStream && this.audioStreamMonitor.setRemoteStream(e.call.remoteStream), e.call.localStream && this.audioStreamMonitor.setLocalStream(e.call.localStream)) : (this.activeCall = null, this.audioStreamMonitor.stopAudioStreamMonitor()));
3252
+ };
3253
+ onTranscriptItem = (e) => {
3254
+ this.emit("transcript.item", e);
3255
+ };
3256
+ onAgentStateChange = (e) => {
3257
+ this.emit("conversation.agent.state", e);
3258
+ };
3259
+ }
3260
+ var Me = { exports: {} }, Se = {};
3261
+ var Ut;
3262
+ function Ni() {
3263
+ if (Ut) return Se;
3264
+ Ut = 1;
3265
+ var t = Symbol.for("react.transitional.element"), e = Symbol.for("react.fragment");
3266
+ function n(i, s, a) {
3267
+ var o = null;
3268
+ if (a !== void 0 && (o = "" + a), s.key !== void 0 && (o = "" + s.key), "key" in s) {
3269
+ a = {};
3270
+ for (var l in s)
3271
+ l !== "key" && (a[l] = s[l]);
3272
+ } else a = s;
3273
+ return s = a.ref, {
3274
+ $$typeof: t,
3275
+ type: i,
3276
+ key: o,
3277
+ ref: s !== void 0 ? s : null,
3278
+ props: a
3279
+ };
3280
+ }
3281
+ return Se.Fragment = e, Se.jsx = n, Se.jsxs = n, Se;
3282
+ }
3283
+ var _e = {};
3284
+ var jt;
3285
+ function Ui() {
3286
+ return jt || (jt = 1, process.env.NODE_ENV !== "production" && (function() {
3287
+ function t(v) {
3288
+ if (v == null) return null;
3289
+ if (typeof v == "function")
3290
+ return v.$$typeof === u ? null : v.displayName || v.name || null;
3291
+ if (typeof v == "string") return v;
3292
+ switch (v) {
3293
+ case p:
3294
+ return "Fragment";
3295
+ case A:
3296
+ return "Profiler";
3297
+ case _:
3298
+ return "StrictMode";
3299
+ case q:
3300
+ return "Suspense";
3301
+ case B:
3302
+ return "SuspenseList";
3303
+ case c:
3304
+ return "Activity";
3305
+ }
3306
+ if (typeof v == "object")
3307
+ switch (typeof v.tag == "number" && console.error(
3308
+ "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
3309
+ ), v.$$typeof) {
3310
+ case k:
3311
+ return "Portal";
3312
+ case P:
3313
+ return v.displayName || "Context";
3314
+ case E:
3315
+ return (v._context.displayName || "Context") + ".Consumer";
3316
+ case D:
3317
+ var M = v.render;
3318
+ return v = v.displayName, v || (v = M.displayName || M.name || "", v = v !== "" ? "ForwardRef(" + v + ")" : "ForwardRef"), v;
3319
+ case x:
3320
+ return M = v.displayName || null, M !== null ? M : t(v.type) || "Memo";
3321
+ case r:
3322
+ M = v._payload, v = v._init;
3323
+ try {
3324
+ return t(v(M));
3325
+ } catch {
3326
+ }
3327
+ }
3328
+ return null;
3329
+ }
3330
+ function e(v) {
3331
+ return "" + v;
3332
+ }
3333
+ function n(v) {
3334
+ try {
3335
+ e(v);
3336
+ var M = !1;
3337
+ } catch {
3338
+ M = !0;
3339
+ }
3340
+ if (M) {
3341
+ M = console;
3342
+ var U = M.error, V = typeof Symbol == "function" && Symbol.toStringTag && v[Symbol.toStringTag] || v.constructor.name || "Object";
3343
+ return U.call(
3344
+ M,
3345
+ "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
3346
+ V
3347
+ ), e(v);
3348
+ }
3349
+ }
3350
+ function i(v) {
3351
+ if (v === p) return "<>";
3352
+ if (typeof v == "object" && v !== null && v.$$typeof === r)
3353
+ return "<...>";
3354
+ try {
3355
+ var M = t(v);
3356
+ return M ? "<" + M + ">" : "<...>";
3357
+ } catch {
3358
+ return "<...>";
3359
+ }
3360
+ }
3361
+ function s() {
3362
+ var v = g.A;
3363
+ return v === null ? null : v.getOwner();
3364
+ }
3365
+ function a() {
3366
+ return Error("react-stack-top-frame");
3367
+ }
3368
+ function o(v) {
3369
+ if (b.call(v, "key")) {
3370
+ var M = Object.getOwnPropertyDescriptor(v, "key").get;
3371
+ if (M && M.isReactWarning) return !1;
3372
+ }
3373
+ return v.key !== void 0;
3374
+ }
3375
+ function l(v, M) {
3376
+ function U() {
3377
+ R || (R = !0, console.error(
3378
+ "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
3379
+ M
3380
+ ));
3381
+ }
3382
+ U.isReactWarning = !0, Object.defineProperty(v, "key", {
3383
+ get: U,
3384
+ configurable: !0
3385
+ });
3386
+ }
3387
+ function d() {
3388
+ var v = t(this.type);
3389
+ return j[v] || (j[v] = !0, console.error(
3390
+ "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
3391
+ )), v = this.props.ref, v !== void 0 ? v : null;
3392
+ }
3393
+ function h(v, M, U, V, Y, Q) {
3394
+ var W = U.ref;
3395
+ return v = {
3396
+ $$typeof: C,
3397
+ type: v,
3398
+ key: M,
3399
+ props: U,
3400
+ _owner: V
3401
+ }, (W !== void 0 ? W : null) !== null ? Object.defineProperty(v, "ref", {
3402
+ enumerable: !1,
3403
+ get: d
3404
+ }) : Object.defineProperty(v, "ref", { enumerable: !1, value: null }), v._store = {}, Object.defineProperty(v._store, "validated", {
3405
+ configurable: !1,
3406
+ enumerable: !1,
3407
+ writable: !0,
3408
+ value: 0
3409
+ }), Object.defineProperty(v, "_debugInfo", {
3410
+ configurable: !1,
3411
+ enumerable: !1,
3412
+ writable: !0,
3413
+ value: null
3414
+ }), Object.defineProperty(v, "_debugStack", {
3415
+ configurable: !1,
3416
+ enumerable: !1,
3417
+ writable: !0,
3418
+ value: Y
3419
+ }), Object.defineProperty(v, "_debugTask", {
3420
+ configurable: !1,
3421
+ enumerable: !1,
3422
+ writable: !0,
3423
+ value: Q
3424
+ }), Object.freeze && (Object.freeze(v.props), Object.freeze(v)), v;
3425
+ }
3426
+ function f(v, M, U, V, Y, Q) {
3427
+ var W = M.children;
3428
+ if (W !== void 0)
3429
+ if (V)
3430
+ if (T(W)) {
3431
+ for (V = 0; V < W.length; V++)
3432
+ m(W[V]);
3433
+ Object.freeze && Object.freeze(W);
3434
+ } else
3435
+ console.error(
3436
+ "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
3437
+ );
3438
+ else m(W);
3439
+ if (b.call(M, "key")) {
3440
+ W = t(v);
3441
+ var re = Object.keys(M).filter(function(In) {
3442
+ return In !== "key";
3443
+ });
3444
+ V = 0 < re.length ? "{key: someKey, " + re.join(": ..., ") + ": ...}" : "{key: someKey}", G[W + V] || (re = 0 < re.length ? "{" + re.join(": ..., ") + ": ...}" : "{}", console.error(
3445
+ `A props object containing a "key" prop is being spread into JSX:
3446
+ let props = %s;
3447
+ <%s {...props} />
3448
+ React keys must be passed directly to JSX without using spread:
3449
+ let props = %s;
3450
+ <%s key={someKey} {...props} />`,
3451
+ V,
3452
+ W,
3453
+ re,
3454
+ W
3455
+ ), G[W + V] = !0);
3456
+ }
3457
+ if (W = null, U !== void 0 && (n(U), W = "" + U), o(M) && (n(M.key), W = "" + M.key), "key" in M) {
3458
+ U = {};
3459
+ for (var ze in M)
3460
+ ze !== "key" && (U[ze] = M[ze]);
3461
+ } else U = M;
3462
+ return W && l(
3463
+ U,
3464
+ typeof v == "function" ? v.displayName || v.name || "Unknown" : v
3465
+ ), h(
3466
+ v,
3467
+ W,
3468
+ U,
3469
+ s(),
3470
+ Y,
3471
+ Q
3472
+ );
3473
+ }
3474
+ function m(v) {
3475
+ S(v) ? v._store && (v._store.validated = 1) : typeof v == "object" && v !== null && v.$$typeof === r && (v._payload.status === "fulfilled" ? S(v._payload.value) && v._payload.value._store && (v._payload.value._store.validated = 1) : v._store && (v._store.validated = 1));
3476
+ }
3477
+ function S(v) {
3478
+ return typeof v == "object" && v !== null && v.$$typeof === C;
3479
+ }
3480
+ var w = ut, C = Symbol.for("react.transitional.element"), k = Symbol.for("react.portal"), p = Symbol.for("react.fragment"), _ = Symbol.for("react.strict_mode"), A = Symbol.for("react.profiler"), E = Symbol.for("react.consumer"), P = Symbol.for("react.context"), D = Symbol.for("react.forward_ref"), q = Symbol.for("react.suspense"), B = Symbol.for("react.suspense_list"), x = Symbol.for("react.memo"), r = Symbol.for("react.lazy"), c = Symbol.for("react.activity"), u = Symbol.for("react.client.reference"), g = w.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, b = Object.prototype.hasOwnProperty, T = Array.isArray, I = console.createTask ? console.createTask : function() {
3481
+ return null;
3482
+ };
3483
+ w = {
3484
+ react_stack_bottom_frame: function(v) {
3485
+ return v();
3486
+ }
3487
+ };
3488
+ var R, j = {}, ee = w.react_stack_bottom_frame.bind(
3489
+ w,
3490
+ a
3491
+ )(), ne = I(i(a)), G = {};
3492
+ _e.Fragment = p, _e.jsx = function(v, M, U) {
3493
+ var V = 1e4 > g.recentlyCreatedOwnerStacks++;
3494
+ return f(
3495
+ v,
3496
+ M,
3497
+ U,
3498
+ !1,
3499
+ V ? Error("react-stack-top-frame") : ee,
3500
+ V ? I(i(v)) : ne
3501
+ );
3502
+ }, _e.jsxs = function(v, M, U) {
3503
+ var V = 1e4 > g.recentlyCreatedOwnerStacks++;
3504
+ return f(
3505
+ v,
3506
+ M,
3507
+ U,
3508
+ !0,
3509
+ V ? Error("react-stack-top-frame") : ee,
3510
+ V ? I(i(v)) : ne
3511
+ );
3512
+ };
3513
+ })()), _e;
3514
+ }
3515
+ var Ft;
3516
+ function ji() {
3517
+ return Ft || (Ft = 1, process.env.NODE_ENV === "production" ? Me.exports = Ni() : Me.exports = Ui()), Me.exports;
3518
+ }
3519
+ var we = ji();
3520
+ const ce = { BASE_URL: "/", DEV: !1, MODE: "production", PROD: !0, SSR: !1 };
3521
+ function un(t) {
3522
+ return "init" in t;
3523
+ }
3524
+ function rt(t) {
3525
+ return !!t.write;
3526
+ }
3527
+ function $t(t) {
3528
+ return "v" in t || "e" in t;
3529
+ }
3530
+ function $e(t) {
3531
+ if ("e" in t)
3532
+ throw t.e;
3533
+ if ((ce ? "production" : void 0) !== "production" && !("v" in t))
3534
+ throw new Error("[Bug] atom state is not initialized");
3535
+ return t.v;
3536
+ }
3537
+ const Be = /* @__PURE__ */ new WeakMap();
3538
+ function hn(t) {
3539
+ var e;
3540
+ return Ve(t) && !!((e = Be.get(t)) != null && e[0]);
3541
+ }
3542
+ function Fi(t) {
3543
+ const e = Be.get(t);
3544
+ e?.[0] && (e[0] = !1, e[1].forEach((n) => n()));
3545
+ }
3546
+ function at(t, e) {
3547
+ let n = Be.get(t);
3548
+ if (!n) {
3549
+ n = [!0, /* @__PURE__ */ new Set()], Be.set(t, n);
3550
+ const i = () => {
3551
+ n[0] = !1;
3552
+ };
3553
+ t.then(i, i);
3554
+ }
3555
+ n[1].add(e);
3556
+ }
3557
+ function Ve(t) {
3558
+ return typeof t?.then == "function";
3559
+ }
3560
+ function pn(t, e, n) {
3561
+ if (!n.p.has(t)) {
3562
+ n.p.add(t);
3563
+ const i = () => n.p.delete(t);
3564
+ e.then(i, i);
3565
+ }
3566
+ }
3567
+ function fn(t, e, n) {
3568
+ var i;
3569
+ const s = /* @__PURE__ */ new Set();
3570
+ for (const a of ((i = n.get(t)) == null ? void 0 : i.t) || [])
3571
+ s.add(a);
3572
+ for (const a of e.p)
3573
+ s.add(a);
3574
+ return s;
3575
+ }
3576
+ const $i = (t, e, ...n) => e.read(...n), Bi = (t, e, ...n) => e.write(...n), Vi = (t, e) => {
3577
+ if (e.INTERNAL_onInit)
3578
+ return e.INTERNAL_onInit(t);
3579
+ if (e.unstable_onInit)
3580
+ return console.warn(
3581
+ "[DEPRECATED] atom.unstable_onInit is renamed to atom.INTERNAL_onInit."
3582
+ ), e.unstable_onInit(t);
3583
+ }, Gi = (t, e, n) => {
3584
+ var i;
3585
+ return (i = e.onMount) == null ? void 0 : i.call(e, n);
3586
+ }, Wi = (t, e) => {
3587
+ var n;
3588
+ const i = X(t), s = i[0], a = i[6], o = i[9];
3589
+ if ((ce ? "production" : void 0) !== "production" && !e)
3590
+ throw new Error("Atom is undefined or null");
3591
+ let l = s.get(e);
3592
+ return l || (l = { d: /* @__PURE__ */ new Map(), p: /* @__PURE__ */ new Set(), n: 0 }, s.set(e, l), (n = a.i) == null || n.call(a, e), o?.(t, e)), l;
3593
+ }, Hi = (t) => {
3594
+ const e = X(t), n = e[1], i = e[3], s = e[4], a = e[5], o = e[6], l = e[13], d = [], h = (f) => {
3595
+ try {
3596
+ f();
3597
+ } catch (m) {
3598
+ d.push(m);
3599
+ }
3600
+ };
3601
+ do {
3602
+ o.f && h(o.f);
3603
+ const f = /* @__PURE__ */ new Set(), m = f.add.bind(f);
3604
+ i.forEach((S) => {
3605
+ var w;
3606
+ return (w = n.get(S)) == null ? void 0 : w.l.forEach(m);
3607
+ }), i.clear(), a.forEach(m), a.clear(), s.forEach(m), s.clear(), f.forEach(h), i.size && l(t);
3608
+ } while (i.size || a.size || s.size);
3609
+ if (d.length)
3610
+ throw new AggregateError(d);
3611
+ }, qi = (t) => {
3612
+ const e = X(t), n = e[1], i = e[2], s = e[3], a = e[11], o = e[14], l = e[17], d = [], h = /* @__PURE__ */ new WeakSet(), f = /* @__PURE__ */ new WeakSet(), m = Array.from(s);
3613
+ for (; m.length; ) {
3614
+ const S = m[m.length - 1], w = a(t, S);
3615
+ if (f.has(S)) {
3616
+ m.pop();
3617
+ continue;
3618
+ }
3619
+ if (h.has(S)) {
3620
+ if (i.get(S) === w.n)
3621
+ d.push([S, w]);
3622
+ else if ((ce ? "production" : void 0) !== "production" && i.has(S))
3623
+ throw new Error("[Bug] invalidated atom exists");
3624
+ f.add(S), m.pop();
3625
+ continue;
3626
+ }
3627
+ h.add(S);
3628
+ for (const C of fn(S, w, n))
3629
+ h.has(C) || m.push(C);
3630
+ }
3631
+ for (let S = d.length - 1; S >= 0; --S) {
3632
+ const [w, C] = d[S];
3633
+ let k = !1;
3634
+ for (const p of C.d.keys())
3635
+ if (p !== w && s.has(p)) {
3636
+ k = !0;
3637
+ break;
3638
+ }
3639
+ k && (o(t, w), l(t, w)), i.delete(w);
3640
+ }
3641
+ }, ct = /* @__PURE__ */ new WeakSet(), Ji = (t, e) => {
3642
+ var n, i;
3643
+ const s = X(t), a = s[1], o = s[2], l = s[3], d = s[6], h = s[7], f = s[11], m = s[12], S = s[13], w = s[14], C = s[16], k = s[17], p = f(t, e);
3644
+ if ($t(p)) {
3645
+ if (a.has(e) && o.get(e) !== p.n)
3646
+ return p;
3647
+ let x = !1;
3648
+ for (const [r, c] of p.d)
3649
+ if (w(t, r).n !== c) {
3650
+ x = !0;
3651
+ break;
3652
+ }
3653
+ if (!x)
3654
+ return p;
3655
+ }
3656
+ p.d.clear();
3657
+ let _ = !0;
3658
+ function A() {
3659
+ a.has(e) && (k(t, e), S(t), m(t));
3660
+ }
3661
+ function E(x) {
3662
+ var r;
3663
+ if (x === e) {
3664
+ const u = f(t, x);
3665
+ if (!$t(u))
3666
+ if (un(x))
3667
+ Ge(t, x, x.init);
3668
+ else
3669
+ throw new Error("no atom init");
3670
+ return $e(u);
3671
+ }
3672
+ const c = w(t, x);
3673
+ try {
3674
+ return $e(c);
3675
+ } finally {
3676
+ p.d.set(x, c.n), hn(p.v) && pn(e, p.v, c), a.has(e) && ((r = a.get(x)) == null || r.t.add(e)), _ || A();
3677
+ }
3678
+ }
3679
+ let P, D;
3680
+ const q = {
3681
+ get signal() {
3682
+ return P || (P = new AbortController()), P.signal;
3683
+ },
3684
+ get setSelf() {
3685
+ return (ce ? "production" : void 0) !== "production" && !rt(e) && console.warn("setSelf function cannot be used with read-only atom"), !D && rt(e) && (D = (...x) => {
3686
+ if ((ce ? "production" : void 0) !== "production" && _ && console.warn("setSelf function cannot be called in sync"), !_)
3687
+ try {
3688
+ return C(t, e, ...x);
3689
+ } finally {
3690
+ S(t), m(t);
3691
+ }
3692
+ }), D;
3693
+ }
3694
+ }, B = p.n;
3695
+ try {
3696
+ (ce ? "production" : void 0) !== "production" && ct.delete(t);
3697
+ const x = h(t, e, E, q);
3698
+ return (ce ? "production" : void 0) !== "production" && ct.has(t) && console.warn(
3699
+ "Detected store mutation during atom read. This is not supported."
3700
+ ), Ge(t, e, x), Ve(x) && (at(x, () => P?.abort()), x.then(A, A)), (n = d.r) == null || n.call(d, e), p;
3701
+ } catch (x) {
3702
+ return delete p.v, p.e = x, ++p.n, p;
3703
+ } finally {
3704
+ _ = !1, B !== p.n && o.get(e) === B && (o.set(e, p.n), l.add(e), (i = d.c) == null || i.call(d, e));
3705
+ }
3706
+ }, Yi = (t, e) => {
3707
+ const n = X(t), i = n[1], s = n[2], a = n[11], o = [e];
3708
+ for (; o.length; ) {
3709
+ const l = o.pop(), d = a(t, l);
3710
+ for (const h of fn(l, d, i)) {
3711
+ const f = a(t, h);
3712
+ s.set(h, f.n), o.push(h);
3713
+ }
3714
+ }
3715
+ }, gn = (t, e, ...n) => {
3716
+ const i = X(t), s = i[3], a = i[6], o = i[8], l = i[11], d = i[12], h = i[13], f = i[14], m = i[15], S = i[17];
3717
+ let w = !0;
3718
+ const C = (p) => $e(f(t, p)), k = (p, ..._) => {
3719
+ var A;
3720
+ const E = l(t, p);
3721
+ try {
3722
+ if (p === e) {
3723
+ if (!un(p))
3724
+ throw new Error("atom not writable");
3725
+ (ce ? "production" : void 0) !== "production" && ct.add(t);
3726
+ const P = E.n, D = _[0];
3727
+ Ge(t, p, D), S(t, p), P !== E.n && (s.add(p), m(t, p), (A = a.c) == null || A.call(a, p));
3728
+ return;
3729
+ } else
3730
+ return gn(t, p, ..._);
3731
+ } finally {
3732
+ w || (h(t), d(t));
3733
+ }
3734
+ };
3735
+ try {
3736
+ return o(t, e, C, k, ...n);
3737
+ } finally {
3738
+ w = !1;
3739
+ }
3740
+ }, zi = (t, e) => {
3741
+ var n;
3742
+ const i = X(t), s = i[1], a = i[3], o = i[6], l = i[11], d = i[15], h = i[18], f = i[19], m = l(t, e), S = s.get(e);
3743
+ if (S && !hn(m.v)) {
3744
+ for (const [w, C] of m.d)
3745
+ if (!S.d.has(w)) {
3746
+ const k = l(t, w);
3747
+ h(t, w).t.add(e), S.d.add(w), C !== k.n && (a.add(w), d(t, w), (n = o.c) == null || n.call(o, w));
3748
+ }
3749
+ for (const w of S.d)
3750
+ if (!m.d.has(w)) {
3751
+ S.d.delete(w);
3752
+ const C = f(t, w);
3753
+ C?.t.delete(e);
3754
+ }
3755
+ }
3756
+ }, mn = (t, e) => {
3757
+ var n;
3758
+ const i = X(t), s = i[1], a = i[4], o = i[6], l = i[10], d = i[11], h = i[12], f = i[13], m = i[14], S = i[16], w = d(t, e);
3759
+ let C = s.get(e);
3760
+ if (!C) {
3761
+ m(t, e);
3762
+ for (const k of w.d.keys())
3763
+ mn(t, k).t.add(e);
3764
+ if (C = {
3765
+ l: /* @__PURE__ */ new Set(),
3766
+ d: new Set(w.d.keys()),
3767
+ t: /* @__PURE__ */ new Set()
3768
+ }, s.set(e, C), rt(e)) {
3769
+ const k = () => {
3770
+ let p = !0;
3771
+ const _ = (...A) => {
3772
+ try {
3773
+ return S(t, e, ...A);
3774
+ } finally {
3775
+ p || (f(t), h(t));
3776
+ }
3777
+ };
3778
+ try {
3779
+ const A = l(t, e, _);
3780
+ A && (C.u = () => {
3781
+ p = !0;
3782
+ try {
3783
+ A();
3784
+ } finally {
3785
+ p = !1;
3786
+ }
3787
+ });
3788
+ } finally {
3789
+ p = !1;
3790
+ }
3791
+ };
3792
+ a.add(k);
3793
+ }
3794
+ (n = o.m) == null || n.call(o, e);
3795
+ }
3796
+ return C;
3797
+ }, Ki = (t, e) => {
3798
+ var n, i;
3799
+ const s = X(t), a = s[1], o = s[5], l = s[6], d = s[11], h = s[19], f = d(t, e);
3800
+ let m = a.get(e);
3801
+ if (!m || m.l.size)
3802
+ return m;
3803
+ let S = !1;
3804
+ for (const w of m.t)
3805
+ if ((n = a.get(w)) != null && n.d.has(e)) {
3806
+ S = !0;
3807
+ break;
3808
+ }
3809
+ if (!S) {
3810
+ m.u && o.add(m.u), m = void 0, a.delete(e);
3811
+ for (const w of f.d.keys()) {
3812
+ const C = h(t, w);
3813
+ C?.t.delete(e);
3814
+ }
3815
+ (i = l.u) == null || i.call(l, e);
3816
+ return;
3817
+ }
3818
+ return m;
3819
+ }, Ge = (t, e, n) => {
3820
+ const i = X(t)[11], s = i(t, e), a = "v" in s, o = s.v;
3821
+ if (Ve(n))
3822
+ for (const l of s.d.keys())
3823
+ pn(
3824
+ e,
3825
+ n,
3826
+ i(t, l)
3827
+ );
3828
+ s.v = n, delete s.e, (!a || !Object.is(o, s.v)) && (++s.n, Ve(o) && Fi(o));
3829
+ }, Qi = (t, e) => {
3830
+ const n = X(t)[14];
3831
+ return $e(n(t, e));
3832
+ }, Xi = (t, e, ...n) => {
3833
+ const i = X(t), s = i[12], a = i[13], o = i[16];
3834
+ try {
3835
+ return o(t, e, ...n);
3836
+ } finally {
3837
+ a(t), s(t);
3838
+ }
3839
+ }, Zi = (t, e, n) => {
3840
+ const i = X(t), s = i[12], a = i[18], o = i[19], d = a(t, e).l;
3841
+ return d.add(n), s(t), () => {
3842
+ d.delete(n), o(t, e), s(t);
3843
+ };
3844
+ }, vn = /* @__PURE__ */ new WeakMap(), X = (t) => {
3845
+ const e = vn.get(t);
3846
+ if ((ce ? "production" : void 0) !== "production" && !e)
3847
+ throw new Error(
3848
+ "Store must be created by buildStore to read its building blocks"
3849
+ );
3850
+ return e;
3851
+ };
3852
+ function es(...t) {
3853
+ const e = {
3854
+ get(i) {
3855
+ const s = X(e)[21];
3856
+ return s(e, i);
3857
+ },
3858
+ set(i, ...s) {
3859
+ const a = X(e)[22];
3860
+ return a(e, i, ...s);
3861
+ },
3862
+ sub(i, s) {
3863
+ const a = X(e)[23];
3864
+ return a(e, i, s);
3865
+ }
3866
+ }, n = [
3867
+ // store state
3868
+ /* @__PURE__ */ new WeakMap(),
3869
+ // atomStateMap
3870
+ /* @__PURE__ */ new WeakMap(),
3871
+ // mountedMap
3872
+ /* @__PURE__ */ new WeakMap(),
3873
+ // invalidatedAtoms
3874
+ /* @__PURE__ */ new Set(),
3875
+ // changedAtoms
3876
+ /* @__PURE__ */ new Set(),
3877
+ // mountCallbacks
3878
+ /* @__PURE__ */ new Set(),
3879
+ // unmountCallbacks
3880
+ {},
3881
+ // storeHooks
3882
+ // atom interceptors
3883
+ $i,
3884
+ Bi,
3885
+ Vi,
3886
+ Gi,
3887
+ // building-block functions
3888
+ Wi,
3889
+ Hi,
3890
+ qi,
3891
+ Ji,
3892
+ Yi,
3893
+ gn,
3894
+ zi,
3895
+ mn,
3896
+ Ki,
3897
+ Ge,
3898
+ Qi,
3899
+ Xi,
3900
+ Zi,
3901
+ void 0
3902
+ ].map((i, s) => t[s] || i);
3903
+ return vn.set(e, Object.freeze(n)), e;
3904
+ }
3905
+ const yn = {};
3906
+ let ts = 0;
3907
+ function He(t, e) {
3908
+ const n = `atom${++ts}`, i = {
3909
+ toString() {
3910
+ return (yn ? "production" : void 0) !== "production" && this.debugLabel ? n + ":" + this.debugLabel : n;
3911
+ }
3912
+ };
3913
+ return typeof t == "function" ? i.read = t : (i.init = t, i.read = ns, i.write = is), i;
3914
+ }
3915
+ function ns(t) {
3916
+ return t(this);
3917
+ }
3918
+ function is(t, e, n) {
3919
+ return e(
3920
+ this,
3921
+ typeof n == "function" ? n(t(this)) : n
3922
+ );
3923
+ }
3924
+ function ss() {
3925
+ return es();
3926
+ }
3927
+ let Ce;
3928
+ function os() {
3929
+ return Ce || (Ce = ss(), (yn ? "production" : void 0) !== "production" && (globalThis.__JOTAI_DEFAULT_STORE__ || (globalThis.__JOTAI_DEFAULT_STORE__ = Ce), globalThis.__JOTAI_DEFAULT_STORE__ !== Ce && console.warn(
3930
+ "Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"
3931
+ ))), Ce;
3932
+ }
3933
+ const rs = {}, as = Gt(
3934
+ void 0
3935
+ );
3936
+ function bn(t) {
3937
+ return Vt(as) || os();
3938
+ }
3939
+ const lt = (t) => typeof t?.then == "function", dt = (t) => {
3940
+ t.status || (t.status = "pending", t.then(
3941
+ (e) => {
3942
+ t.status = "fulfilled", t.value = e;
3943
+ },
3944
+ (e) => {
3945
+ t.status = "rejected", t.reason = e;
3946
+ }
3947
+ ));
3948
+ }, cs = ut.use || // A shim for older React versions
3949
+ ((t) => {
3950
+ if (t.status === "pending")
3951
+ throw t;
3952
+ if (t.status === "fulfilled")
3953
+ return t.value;
3954
+ throw t.status === "rejected" ? t.reason : (dt(t), t);
3955
+ }), Ze = /* @__PURE__ */ new WeakMap(), Bt = (t, e) => {
3956
+ let n = Ze.get(t);
3957
+ return n || (n = new Promise((i, s) => {
3958
+ let a = t;
3959
+ const o = (h) => (f) => {
3960
+ a === h && i(f);
3961
+ }, l = (h) => (f) => {
3962
+ a === h && s(f);
3963
+ }, d = () => {
3964
+ try {
3965
+ const h = e();
3966
+ lt(h) ? (Ze.set(h, n), a = h, h.then(o(h), l(h)), at(h, d)) : i(h);
3967
+ } catch (h) {
3968
+ s(h);
3969
+ }
3970
+ };
3971
+ t.then(o(t), l(t)), at(t, d);
3972
+ }), Ze.set(t, n)), n;
3973
+ };
3974
+ function qe(t, e) {
3975
+ const { delay: n, unstable_promiseStatus: i = !ut.use } = {}, s = bn(), [[a, o, l], d] = En(
3976
+ (f) => {
3977
+ const m = s.get(t);
3978
+ return Object.is(f[0], m) && f[1] === s && f[2] === t ? f : [m, s, t];
3979
+ },
3980
+ void 0,
3981
+ () => [s.get(t), s, t]
3982
+ );
3983
+ let h = a;
3984
+ if ((o !== s || l !== t) && (d(), h = s.get(t)), pe(() => {
3985
+ const f = s.sub(t, () => {
3986
+ if (i)
3987
+ try {
3988
+ const m = s.get(t);
3989
+ lt(m) && dt(
3990
+ Bt(m, () => s.get(t))
3991
+ );
3992
+ } catch {
3993
+ }
3994
+ if (typeof n == "number") {
3995
+ setTimeout(d, n);
3996
+ return;
3997
+ }
3998
+ d();
3999
+ });
4000
+ return d(), f;
4001
+ }, [s, t, n, i]), Tn(h), lt(h)) {
4002
+ const f = Bt(h, () => s.get(t));
4003
+ return i && dt(f), cs(f);
4004
+ }
4005
+ return h;
4006
+ }
4007
+ function Je(t, e) {
4008
+ const n = bn();
4009
+ return An(
4010
+ (...s) => {
4011
+ if ((rs ? "production" : void 0) !== "production" && !("write" in t))
4012
+ throw new Error("not writable atom");
4013
+ return n.set(t, ...s);
4014
+ },
4015
+ [n, t]
4016
+ );
4017
+ }
4018
+ const Sn = He([]);
4019
+ function ys() {
4020
+ return qe(Sn);
4021
+ }
4022
+ function ls() {
4023
+ return Je(Sn);
4024
+ }
4025
+ const Ye = () => {
4026
+ const t = Vt(kn);
4027
+ if (!t)
4028
+ throw new Error("useClient must be used within a TelnyxAIAgentProvider");
4029
+ return t;
4030
+ };
4031
+ function ds() {
4032
+ const t = Ye(), e = ls();
4033
+ return pe(() => {
4034
+ const n = (i) => e((s) => [...s, i]);
4035
+ return t.addListener("transcript.item", n), () => {
4036
+ t.removeListener("transcript.item", n);
4037
+ };
4038
+ }, [t, e]), null;
4039
+ }
4040
+ const _n = He("connecting");
4041
+ function bs() {
4042
+ return qe(_n);
4043
+ }
4044
+ function us() {
4045
+ return Je(_n);
4046
+ }
4047
+ function hs() {
4048
+ const t = Ye(), e = us();
4049
+ return pe(() => {
4050
+ const n = () => e("connected"), i = () => e("disconnected"), s = () => e("error");
4051
+ return t.addListener("agent.connected", n), t.addListener("agent.disconnected", i), t.addListener("agent.error", s), () => {
4052
+ t.removeListener("agent.connected", n), t.removeListener("agent.disconnected", i), t.removeListener("agent.error", s);
4053
+ };
4054
+ }, [t, e]), null;
4055
+ }
4056
+ const wn = He(null);
4057
+ function Ss() {
4058
+ return qe(wn);
4059
+ }
4060
+ function ps() {
4061
+ return Je(wn);
4062
+ }
4063
+ const fs = () => {
4064
+ const t = Ye(), e = ps();
4065
+ return pe(() => {
4066
+ const n = (i) => {
4067
+ e(i);
4068
+ };
4069
+ return t.addListener("conversation.update", n), () => {
4070
+ t.removeListener("conversation.update", n);
4071
+ };
4072
+ }, [t, e]), null;
4073
+ }, Cn = He({ state: "listening" });
4074
+ function _s() {
4075
+ return qe(Cn);
4076
+ }
4077
+ function gs() {
4078
+ return Je(Cn);
4079
+ }
4080
+ function ms() {
4081
+ const t = Ye(), e = gs();
4082
+ return pe(() => {
4083
+ const n = (i) => {
4084
+ e(i);
4085
+ };
4086
+ return t.addListener("conversation.agent.state", n), () => {
4087
+ t.removeListener("conversation.agent.state", n);
4088
+ };
4089
+ }, [t, e]), null;
4090
+ }
4091
+ const kn = Gt(null), ws = ({
4092
+ children: t,
4093
+ agentId: e,
4094
+ environment: n,
4095
+ versionId: i,
4096
+ debug: s,
4097
+ vad: a
4098
+ }) => {
4099
+ const [o, l] = Rn(() => new Nt({ agentId: e, environment: n, versionId: i, debug: s, vad: a }));
4100
+ return pe(() => {
4101
+ if (!o) {
4102
+ const d = new Nt({ agentId: e, environment: n, versionId: i, vad: a });
4103
+ return l(d), () => {
4104
+ d.disconnect();
4105
+ };
4106
+ }
4107
+ }, [e, o, n, i, a]), pe(() => {
4108
+ o?.connect();
4109
+ }, [o]), /* @__PURE__ */ we.jsxs(kn.Provider, { value: o, children: [
4110
+ /* @__PURE__ */ we.jsx(ds, {}),
4111
+ /* @__PURE__ */ we.jsx(hs, {}),
4112
+ /* @__PURE__ */ we.jsx(fs, {}),
4113
+ /* @__PURE__ */ we.jsx(ms, {}),
4114
+ t
4115
+ ] });
4116
+ };
4117
+ export {
4118
+ kn as ClientContext,
4119
+ L as SwEvent,
4120
+ Nt as TelnyxAIAgent,
4121
+ ws as TelnyxAIAgentProvider,
4122
+ _s as useAgentState,
4123
+ Ye as useClient,
4124
+ bs as useConnectionState,
4125
+ Ss as useConversation,
4126
+ gs as useSetAgentState,
4127
+ us as useSetConnectionState,
4128
+ ps as useSetConversation,
4129
+ ls as useSetTranscript,
4130
+ ys as useTranscript
4131
+ };