@nainudhin/video-meeting-sdk 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/meet-sdk.d.ts +5 -0
- package/dist/meet-sdk.mjs +63 -44
- package/dist/meet-sdk.umd.js +6 -6
- package/package.json +1 -1
package/dist/meet-sdk.d.ts
CHANGED
|
@@ -66,6 +66,11 @@ export interface MeetSDKConfig {
|
|
|
66
66
|
compositeHeight?: number;
|
|
67
67
|
compositeFps?: number;
|
|
68
68
|
|
|
69
|
+
/** MediaRecorder video bitrate (bits/sec). Default 1_000_000 (1 Mbps). */
|
|
70
|
+
recordingVideoBps?: number;
|
|
71
|
+
/** MediaRecorder audio bitrate (bits/sec). Default 64_000 (64 kbps Opus). */
|
|
72
|
+
recordingAudioBps?: number;
|
|
73
|
+
|
|
69
74
|
/**
|
|
70
75
|
* Which side-panel tabs to show. Chat is always rendered even if omitted.
|
|
71
76
|
* Default: ['chat'].
|
package/dist/meet-sdk.mjs
CHANGED
|
@@ -1295,7 +1295,7 @@ const nt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
|
1295
1295
|
function Pn(r) {
|
|
1296
1296
|
return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r;
|
|
1297
1297
|
}
|
|
1298
|
-
var
|
|
1298
|
+
var Vt = { exports: {} };
|
|
1299
1299
|
(function(r) {
|
|
1300
1300
|
const e = {};
|
|
1301
1301
|
e.generateIdentifier = function() {
|
|
@@ -1682,12 +1682,12 @@ t=0 0\r
|
|
|
1682
1682
|
return !1;
|
|
1683
1683
|
return !0;
|
|
1684
1684
|
}, r.exports = e;
|
|
1685
|
-
})(
|
|
1686
|
-
var
|
|
1687
|
-
const L = /* @__PURE__ */ Pn(
|
|
1685
|
+
})(Vt);
|
|
1686
|
+
var Ht = Vt.exports;
|
|
1687
|
+
const L = /* @__PURE__ */ Pn(Ht), wn = /* @__PURE__ */ _n({
|
|
1688
1688
|
__proto__: null,
|
|
1689
1689
|
default: L
|
|
1690
|
-
}, [
|
|
1690
|
+
}, [Ht]);
|
|
1691
1691
|
function J(r) {
|
|
1692
1692
|
if (!r.RTCIceCandidate || r.RTCIceCandidate && "foundation" in r.RTCIceCandidate.prototype)
|
|
1693
1693
|
return;
|
|
@@ -2145,9 +2145,9 @@ class $n {
|
|
|
2145
2145
|
}
|
|
2146
2146
|
}
|
|
2147
2147
|
var f = new $n(), De = {}, Bn = Object.prototype.hasOwnProperty, C = "~";
|
|
2148
|
-
function
|
|
2148
|
+
function V() {
|
|
2149
2149
|
}
|
|
2150
|
-
Object.create && (
|
|
2150
|
+
Object.create && (V.prototype = /* @__PURE__ */ Object.create(null), new V().__proto__ || (C = !1));
|
|
2151
2151
|
function Un(r, e, t) {
|
|
2152
2152
|
this.fn = r, this.context = e, this.once = t || !1;
|
|
2153
2153
|
}
|
|
@@ -2160,10 +2160,10 @@ function Wt(r, e, t, n, s) {
|
|
|
2160
2160
|
] : r._events[o].push(i) : (r._events[o] = i, r._eventsCount++), r;
|
|
2161
2161
|
}
|
|
2162
2162
|
function X(r, e) {
|
|
2163
|
-
--r._eventsCount === 0 ? r._events = new
|
|
2163
|
+
--r._eventsCount === 0 ? r._events = new V() : delete r._events[e];
|
|
2164
2164
|
}
|
|
2165
2165
|
function S() {
|
|
2166
|
-
this._events = new
|
|
2166
|
+
this._events = new V(), this._eventsCount = 0;
|
|
2167
2167
|
}
|
|
2168
2168
|
S.prototype.eventNames = function() {
|
|
2169
2169
|
var e = [], t, n;
|
|
@@ -2250,7 +2250,7 @@ S.prototype.removeListener = function(e, t, n, s) {
|
|
|
2250
2250
|
};
|
|
2251
2251
|
S.prototype.removeAllListeners = function(e) {
|
|
2252
2252
|
var t;
|
|
2253
|
-
return e ? (t = C ? C + e : e, this._events[t] && X(this, t)) : (this._events = new
|
|
2253
|
+
return e ? (t = C ? C + e : e, this._events[t] && X(this, t)) : (this._events = new V(), this._eventsCount = 0), this;
|
|
2254
2254
|
};
|
|
2255
2255
|
S.prototype.off = S.prototype.removeListener;
|
|
2256
2256
|
S.prototype.addListener = S.prototype.on;
|
|
@@ -3169,8 +3169,8 @@ const q = class q extends Qt {
|
|
|
3169
3169
|
};
|
|
3170
3170
|
Ae = new WeakMap(), B(q, Ae, q.DEFAULT_KEY = "peerjs");
|
|
3171
3171
|
let Se = q;
|
|
3172
|
-
var
|
|
3173
|
-
class
|
|
3172
|
+
var Vn = Se;
|
|
3173
|
+
class Hn {
|
|
3174
3174
|
constructor(e) {
|
|
3175
3175
|
this.config = e, this.peer = null, this.localStream = null, this.connections = {}, this.callbacks = {
|
|
3176
3176
|
onStream: null,
|
|
@@ -3188,7 +3188,7 @@ class Vn {
|
|
|
3188
3188
|
async initialize(e, t = 0) {
|
|
3189
3189
|
return new Promise((n, s) => {
|
|
3190
3190
|
const i = t === 0 ? e : `${e}-r${Math.random().toString(36).slice(2, 6)}`;
|
|
3191
|
-
this.peer = new
|
|
3191
|
+
this.peer = new Vn(i, {
|
|
3192
3192
|
host: this.config.peerServer.host,
|
|
3193
3193
|
port: this.config.peerServer.port,
|
|
3194
3194
|
path: this.config.peerServer.path || "/peerjs",
|
|
@@ -3457,7 +3457,7 @@ function Xn() {
|
|
|
3457
3457
|
});
|
|
3458
3458
|
}
|
|
3459
3459
|
let ue;
|
|
3460
|
-
function
|
|
3460
|
+
function H(r) {
|
|
3461
3461
|
return r.reduce((e, t) => e + t.length, 0);
|
|
3462
3462
|
}
|
|
3463
3463
|
function K(r, e) {
|
|
@@ -3477,17 +3477,17 @@ function Zn(r, e) {
|
|
|
3477
3477
|
transform(o, a) {
|
|
3478
3478
|
for (t.push(o); ; ) {
|
|
3479
3479
|
if (n === 0) {
|
|
3480
|
-
if (
|
|
3480
|
+
if (H(t) < 1)
|
|
3481
3481
|
break;
|
|
3482
3482
|
const c = K(t, 1);
|
|
3483
3483
|
i = (c[0] & 128) === 128, s = c[0] & 127, s < 126 ? n = 3 : s === 126 ? n = 1 : n = 2;
|
|
3484
3484
|
} else if (n === 1) {
|
|
3485
|
-
if (
|
|
3485
|
+
if (H(t) < 2)
|
|
3486
3486
|
break;
|
|
3487
3487
|
const c = K(t, 2);
|
|
3488
3488
|
s = new DataView(c.buffer, c.byteOffset, c.length).getUint16(0), n = 3;
|
|
3489
3489
|
} else if (n === 2) {
|
|
3490
|
-
if (
|
|
3490
|
+
if (H(t) < 8)
|
|
3491
3491
|
break;
|
|
3492
3492
|
const c = K(t, 8), h = new DataView(c.buffer, c.byteOffset, c.length), l = h.getUint32(0);
|
|
3493
3493
|
if (l > Math.pow(2, 21) - 1) {
|
|
@@ -3496,7 +3496,7 @@ function Zn(r, e) {
|
|
|
3496
3496
|
}
|
|
3497
3497
|
s = l * Math.pow(2, 32) + h.getUint32(4), n = 3;
|
|
3498
3498
|
} else {
|
|
3499
|
-
if (
|
|
3499
|
+
if (H(t) < s)
|
|
3500
3500
|
break;
|
|
3501
3501
|
const c = K(t, s);
|
|
3502
3502
|
a.enqueue(Ue(i ? c : ue.decode(c), e)), n = 0;
|
|
@@ -5829,26 +5829,29 @@ class je {
|
|
|
5829
5829
|
e === "stateChange" ? this.callbacks.onStateChange = t : e === "chunk" && (this.callbacks.onChunk = t);
|
|
5830
5830
|
}
|
|
5831
5831
|
// opts:
|
|
5832
|
-
// timesliceMs
|
|
5833
|
-
//
|
|
5832
|
+
// timesliceMs default 15000 — chunk emission cadence
|
|
5833
|
+
// videoBitsPerSecond default 1_000_000 — capped to keep per-chunk size
|
|
5834
|
+
// below Apache/multer body limits (~2 MB per 15 s)
|
|
5835
|
+
// audioBitsPerSecond default 64_000 — Opus is efficient at this rate
|
|
5836
|
+
// onChunk async (blob, seq)
|
|
5834
5837
|
start(e, t = {}) {
|
|
5835
5838
|
if (!je.isSupported())
|
|
5836
5839
|
throw new Error("MediaRecorder API not supported in this browser");
|
|
5837
5840
|
if (this.state === "recording") return;
|
|
5838
5841
|
if (!e) throw new Error("stream is required to start recording");
|
|
5839
|
-
const n = t.timesliceMs || 15e3;
|
|
5842
|
+
const n = t.timesliceMs || 15e3, s = Number.isFinite(t.videoBitsPerSecond) ? t.videoBitsPerSecond : 1e6, i = Number.isFinite(t.audioBitsPerSecond) ? t.audioBitsPerSecond : 64e3;
|
|
5840
5843
|
t.onChunk && (this.callbacks.onChunk = t.onChunk), this.stream = e, this.seq = typeof t.startSeq == "number" ? t.startSeq : 0, this.pendingUploads = [];
|
|
5841
|
-
const
|
|
5842
|
-
this.recorder = new window.MediaRecorder(e,
|
|
5843
|
-
if (!
|
|
5844
|
-
const
|
|
5845
|
-
if (!
|
|
5846
|
-
const
|
|
5847
|
-
console.warn(`Recording chunk seq=${
|
|
5844
|
+
const o = this.pickMimeType(), a = { videoBitsPerSecond: s, audioBitsPerSecond: i };
|
|
5845
|
+
o && (a.mimeType = o), this.recorder = new window.MediaRecorder(e, a), this.mimeType = this.recorder.mimeType || o || "video/webm", this.recorder.ondataavailable = (c) => {
|
|
5846
|
+
if (!c.data || c.data.size === 0) return;
|
|
5847
|
+
const h = this.seq++, l = c.data, d = this.callbacks.onChunk;
|
|
5848
|
+
if (!d) return;
|
|
5849
|
+
const u = Promise.resolve().then(() => d(l, h)).catch((p) => {
|
|
5850
|
+
console.warn(`Recording chunk seq=${h} upload failed:`, p && p.message);
|
|
5848
5851
|
});
|
|
5849
|
-
this.pendingUploads.push(
|
|
5850
|
-
}, this.recorder.onerror = (
|
|
5851
|
-
console.error("MediaRecorder error:",
|
|
5852
|
+
this.pendingUploads.push(u);
|
|
5853
|
+
}, this.recorder.onerror = (c) => {
|
|
5854
|
+
console.error("MediaRecorder error:", c);
|
|
5852
5855
|
}, this.startedAt = /* @__PURE__ */ new Date(), this.recorder.start(n), this.setState("recording");
|
|
5853
5856
|
}
|
|
5854
5857
|
// Stops recording and returns { startedAt, endedAt, mimeType }.
|
|
@@ -5923,7 +5926,7 @@ class qe {
|
|
|
5923
5926
|
this.ctx.fillStyle = "#0d0d0d", this.ctx.fillRect(0, 0, this.width, this.height);
|
|
5924
5927
|
const e = Array.from(this.videos.values());
|
|
5925
5928
|
if (e.length === 0) return;
|
|
5926
|
-
const { cols: t, rows: n } =
|
|
5929
|
+
const { cols: t, rows: n } = Vr(e.length), s = this.width / t, i = this.height / n;
|
|
5927
5930
|
e.forEach((o, a) => {
|
|
5928
5931
|
const c = a % t, h = Math.floor(a / t), l = c * s, d = h * i;
|
|
5929
5932
|
this.ctx.fillStyle = "#1a1a1a", this.ctx.fillRect(l, d, s, i);
|
|
@@ -5936,10 +5939,10 @@ class qe {
|
|
|
5936
5939
|
}
|
|
5937
5940
|
} else
|
|
5938
5941
|
qr(this.ctx, o.label || "Peer", l, d, s, i);
|
|
5939
|
-
const
|
|
5942
|
+
const Ve = o.label || "Peer";
|
|
5940
5943
|
this.ctx.font = "bold 16px system-ui, sans-serif";
|
|
5941
|
-
const fn = this.ctx.measureText(
|
|
5942
|
-
this.ctx.fillStyle = "rgba(0,0,0,0.65)", this.ctx.fillRect(Ke, Je, gn, ce), this.ctx.fillStyle = "#fff", this.ctx.fillText(
|
|
5944
|
+
const fn = this.ctx.measureText(Ve), He = 10, pn = 6, gn = fn.width + He * 2, ce = 24, Ke = l + 12, Je = d + i - ce - 12;
|
|
5945
|
+
this.ctx.fillStyle = "rgba(0,0,0,0.65)", this.ctx.fillRect(Ke, Je, gn, ce), this.ctx.fillStyle = "#fff", this.ctx.fillText(Ve, Ke + He, Je + ce - pn - 2);
|
|
5943
5946
|
});
|
|
5944
5947
|
}
|
|
5945
5948
|
addStream(e, t, n = {}) {
|
|
@@ -6010,7 +6013,7 @@ function qr(r, e, t, n, s, i) {
|
|
|
6010
6013
|
const o = t + s / 2, a = n + i / 2, c = Math.min(s, i) * 0.22;
|
|
6011
6014
|
r.fillStyle = jr(e), r.beginPath(), r.arc(o, a, c, 0, Math.PI * 2), r.fill(), r.fillStyle = "#fff", r.font = `600 ${Math.floor(c)}px system-ui, sans-serif`, r.textAlign = "center", r.textBaseline = "middle", r.fillText(Fr(e), o, a + 1), r.textAlign = "start", r.textBaseline = "alphabetic";
|
|
6012
6015
|
}
|
|
6013
|
-
function
|
|
6016
|
+
function Vr(r) {
|
|
6014
6017
|
if (r <= 1) return { cols: 1, rows: 1 };
|
|
6015
6018
|
if (r === 2) return { cols: 2, rows: 1 };
|
|
6016
6019
|
if (r <= 4) return { cols: 2, rows: 2 };
|
|
@@ -6019,7 +6022,7 @@ function Hr(r) {
|
|
|
6019
6022
|
const e = 4;
|
|
6020
6023
|
return { cols: e, rows: Math.ceil(r / e) };
|
|
6021
6024
|
}
|
|
6022
|
-
function
|
|
6025
|
+
function Hr(r, e) {
|
|
6023
6026
|
return r.includes("pdf") || /\.pdf$/i.test(e) ? "📕" : r.includes("word") || /\.docx?$/i.test(e) ? "📘" : r.includes("sheet") || r.includes("excel") || /\.(xlsx?|csv)$/i.test(e) ? "📗" : r.startsWith("text/") ? "📄" : "📎";
|
|
6024
6027
|
}
|
|
6025
6028
|
class Kr {
|
|
@@ -6174,7 +6177,7 @@ class Kr {
|
|
|
6174
6177
|
<img src="${i}" alt="${s}" style="max-width:100%; border-radius:6px; display:block;" />
|
|
6175
6178
|
<div style="font-size:11px; color:#888; margin-top:2px;">${s} · ${n} KB</div>
|
|
6176
6179
|
</a>`;
|
|
6177
|
-
const o =
|
|
6180
|
+
const o = Hr(e.contentType || "", e.fileName || "");
|
|
6178
6181
|
return `<a href="${i}" target="_blank" rel="noreferrer" style="display:flex; align-items:center; gap:8px; padding:8px 10px; background:#333; border-radius:6px; text-decoration:none; color:#ddd; font-size:13px;">
|
|
6179
6182
|
<span style="font-size:22px;">${o}</span>
|
|
6180
6183
|
<div style="min-width:0; flex:1; overflow:hidden;">
|
|
@@ -6562,8 +6565,8 @@ class Zr {
|
|
|
6562
6565
|
init(e) {
|
|
6563
6566
|
if (!e || !e.workspace || !e.roomId || !e.user)
|
|
6564
6567
|
throw new Error("workspace, roomId, and user are required");
|
|
6565
|
-
const t = e.host || Qr, n = Yr.has(e.recording) ? e.recording : "off", s = n !== "off" && !!e.transcribe, i = s && !!e.summarize, o = e.recordOnlyIfHost !== !1, a = Gr.has(e.recordingMode) ? e.recordingMode : "local", c = Number.isFinite(e.compositeWidth) ? e.compositeWidth : 1280, h = Number.isFinite(e.compositeHeight) ? e.compositeHeight : 720, l = Number.isFinite(e.compositeFps) ? e.compositeFps : 30, d = ["chat", "code", "whiteboard"],
|
|
6566
|
-
|
|
6568
|
+
const t = e.host || Qr, n = Yr.has(e.recording) ? e.recording : "off", s = n !== "off" && !!e.transcribe, i = s && !!e.summarize, o = e.recordOnlyIfHost !== !1, a = Gr.has(e.recordingMode) ? e.recordingMode : "local", c = Number.isFinite(e.compositeWidth) ? e.compositeWidth : 1280, h = Number.isFinite(e.compositeHeight) ? e.compositeHeight : 720, l = Number.isFinite(e.compositeFps) ? e.compositeFps : 30, d = Number.isFinite(e.recordingVideoBps) ? e.recordingVideoBps : 1e6, u = Number.isFinite(e.recordingAudioBps) ? e.recordingAudioBps : 64e3, p = ["chat", "code", "whiteboard"], m = Array.isArray(e.panels) && e.panels.length ? e.panels.filter((_) => p.includes(_)) : ["chat"];
|
|
6569
|
+
m.includes("chat") || m.unshift("chat"), this.config = {
|
|
6567
6570
|
...e,
|
|
6568
6571
|
host: t,
|
|
6569
6572
|
apiUrl: e.apiUrl || `${t}/api`,
|
|
@@ -6578,11 +6581,13 @@ class Zr {
|
|
|
6578
6581
|
compositeWidth: c,
|
|
6579
6582
|
compositeHeight: h,
|
|
6580
6583
|
compositeFps: l,
|
|
6581
|
-
|
|
6582
|
-
|
|
6584
|
+
recordingVideoBps: d,
|
|
6585
|
+
recordingAudioBps: u,
|
|
6586
|
+
panels: m
|
|
6587
|
+
}, this.myRole = null, this.roleResolvers = [], this.currentRoom = this.config.roomId, this.currentUser = this.config.user, this.peerManager = new Hn(this.config), this.socketManager = new Nr(this.config), this.mediaManager = new zr(), this.uiManager = new Kr({
|
|
6583
6588
|
recording: n,
|
|
6584
6589
|
screenShare: e.screenShare !== !1,
|
|
6585
|
-
panels:
|
|
6590
|
+
panels: m
|
|
6586
6591
|
}), this.recorder = n === "off" ? null : new je(), this.compositor = null, this.setupEventHandlers(), this.isInitialized = !0, console.log("MeetSDK initialized");
|
|
6587
6592
|
}
|
|
6588
6593
|
setupEventHandlers() {
|
|
@@ -6625,6 +6630,18 @@ class Zr {
|
|
|
6625
6630
|
this.refreshParticipantsPanel();
|
|
6626
6631
|
});
|
|
6627
6632
|
}
|
|
6633
|
+
async hydrateIceServers() {
|
|
6634
|
+
try {
|
|
6635
|
+
const e = await fetch(`${this.config.apiUrl}/rt-config`, { headers: this.buildHeaders() });
|
|
6636
|
+
if (!e.ok) return;
|
|
6637
|
+
const t = await e.json();
|
|
6638
|
+
if (!t || !Array.isArray(t.iceServers) || t.iceServers.length === 0) return;
|
|
6639
|
+
const n = Array.isArray(this.config.iceServers) ? this.config.iceServers : [];
|
|
6640
|
+
this.config.iceServers = [...n, ...t.iceServers];
|
|
6641
|
+
} catch (e) {
|
|
6642
|
+
console.warn("rt-config fetch failed, using STUN defaults:", e && e.message);
|
|
6643
|
+
}
|
|
6644
|
+
}
|
|
6628
6645
|
labelForPeer(e, t) {
|
|
6629
6646
|
return t ? this.currentUser && this.currentUser.name ? this.currentUser.name : "You" : this.peerLabels && this.peerLabels.has(e) ? this.peerLabels.get(e) : e;
|
|
6630
6647
|
}
|
|
@@ -6660,7 +6677,7 @@ class Zr {
|
|
|
6660
6677
|
async mount(e) {
|
|
6661
6678
|
if (!this.isInitialized)
|
|
6662
6679
|
throw new Error("SDK not initialized. Call init() first.");
|
|
6663
|
-
this.uiManager.mount(e);
|
|
6680
|
+
this.uiManager.mount(e), await this.hydrateIceServers();
|
|
6664
6681
|
const t = `${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;
|
|
6665
6682
|
await this.peerManager.initialize(t);
|
|
6666
6683
|
const n = await this.peerManager.getLocalStream();
|
|
@@ -6809,6 +6826,8 @@ class Zr {
|
|
|
6809
6826
|
n || (n = await this.startRecordingSession(), this.persistStoredSession(n)), this.recordingSession = n, this.chunkQueue = [], this.chunkDrainerRunning = !1, this.recorder.start(e, {
|
|
6810
6827
|
timesliceMs: 15e3,
|
|
6811
6828
|
startSeq: s,
|
|
6829
|
+
videoBitsPerSecond: this.config.recordingVideoBps,
|
|
6830
|
+
audioBitsPerSecond: this.config.recordingAudioBps,
|
|
6812
6831
|
onChunk: (i, o) => (this.enqueueChunk(n.sessionId, i, o), Promise.resolve())
|
|
6813
6832
|
});
|
|
6814
6833
|
}
|
package/dist/meet-sdk.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(x,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(x=typeof globalThis<"u"?globalThis:x||self,E(x.MeetSDK={}))})(this,function(x){"use strict";var es=x=>{throw TypeError(x)};var K=(x,E,le)=>E.has(x)?es("Cannot add the same private member more than once"):E instanceof WeakSet?E.add(x):E.set(x,le);var je,qe,He,Ve;function E(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const s in n)if(s!=="default"&&!(s in r)){const i=Object.getOwnPropertyDescriptor(n,s);i&&Object.defineProperty(r,s,i.get?i:{enumerable:!0,get:()=>n[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}class le{constructor(){this.encoder=new TextEncoder,this._pieces=[],this._parts=[]}append_buffer(e){this.flush(),this._parts.push(e)}append(e){this._pieces.push(e)}flush(){if(this._pieces.length>0){const e=new Uint8Array(this._pieces);this._parts.push(e),this._pieces=[]}}toArrayBuffer(){const e=[];for(const t of this._parts)e.push(t);return yn(e).buffer}}function yn(r){let e=0;for(const s of r)e+=s.byteLength;const t=new Uint8Array(e);let n=0;for(const s of r){const i=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);t.set(i,n),n+=s.byteLength}return t}function Je(r){return new bn(r).unpack()}function We(r){const e=new _n,t=e.pack(r);return t instanceof Promise?t.then(()=>e.getBuffer()):e.getBuffer()}class bn{constructor(e){this.index=0,this.dataBuffer=e,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}unpack(){const e=this.unpack_uint8();if(e<128)return e;if((e^224)<32)return(e^224)-32;let t;if((t=e^160)<=15)return this.unpack_raw(t);if((t=e^176)<=15)return this.unpack_string(t);if((t=e^144)<=15)return this.unpack_array(t);if((t=e^128)<=15)return this.unpack_map(t);switch(e){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return;case 213:return;case 214:return;case 215:return;case 216:return t=this.unpack_uint16(),this.unpack_string(t);case 217:return t=this.unpack_uint32(),this.unpack_string(t);case 218:return t=this.unpack_uint16(),this.unpack_raw(t);case 219:return t=this.unpack_uint32(),this.unpack_raw(t);case 220:return t=this.unpack_uint16(),this.unpack_array(t);case 221:return t=this.unpack_uint32(),this.unpack_array(t);case 222:return t=this.unpack_uint16(),this.unpack_map(t);case 223:return t=this.unpack_uint32(),this.unpack_map(t)}}unpack_uint8(){const e=this.dataView[this.index]&255;return this.index++,e}unpack_uint16(){const e=this.read(2),t=(e[0]&255)*256+(e[1]&255);return this.index+=2,t}unpack_uint32(){const e=this.read(4),t=((e[0]*256+e[1])*256+e[2])*256+e[3];return this.index+=4,t}unpack_uint64(){const e=this.read(8),t=((((((e[0]*256+e[1])*256+e[2])*256+e[3])*256+e[4])*256+e[5])*256+e[6])*256+e[7];return this.index+=8,t}unpack_int8(){const e=this.unpack_uint8();return e<128?e:e-256}unpack_int16(){const e=this.unpack_uint16();return e<32768?e:e-65536}unpack_int32(){const e=this.unpack_uint32();return e<2**31?e:e-2**32}unpack_int64(){const e=this.unpack_uint64();return e<2**63?e:e-2**64}unpack_raw(e){if(this.length<this.index+e)throw new Error(`BinaryPackFailure: index is out of range ${this.index} ${e} ${this.length}`);const t=this.dataBuffer.slice(this.index,this.index+e);return this.index+=e,t}unpack_string(e){const t=this.read(e);let n=0,s="",i,o;for(;n<e;)i=t[n],i<160?(o=i,n++):(i^192)<32?(o=(i&31)<<6|t[n+1]&63,n+=2):(i^224)<16?(o=(i&15)<<12|(t[n+1]&63)<<6|t[n+2]&63,n+=3):(o=(i&7)<<18|(t[n+1]&63)<<12|(t[n+2]&63)<<6|t[n+3]&63,n+=4),s+=String.fromCodePoint(o);return this.index+=e,s}unpack_array(e){const t=new Array(e);for(let n=0;n<e;n++)t[n]=this.unpack();return t}unpack_map(e){const t={};for(let n=0;n<e;n++){const s=this.unpack();t[s]=this.unpack()}return t}unpack_float(){const e=this.unpack_uint32(),t=e>>31,n=(e>>23&255)-127,s=e&8388607|8388608;return(t===0?1:-1)*s*2**(n-23)}unpack_double(){const e=this.unpack_uint32(),t=this.unpack_uint32(),n=e>>31,s=(e>>20&2047)-1023,o=(e&1048575|1048576)*2**(s-20)+t*2**(s-52);return(n===0?1:-1)*o}read(e){const t=this.index;if(t+e<=this.length)return this.dataView.subarray(t,t+e);throw new Error("BinaryPackFailure: read index out of range")}}class _n{getBuffer(){return this._bufferBuilder.toArrayBuffer()}pack(e){if(typeof e=="string")this.pack_string(e);else if(typeof e=="number")Math.floor(e)===e?this.pack_integer(e):this.pack_double(e);else if(typeof e=="boolean")e===!0?this._bufferBuilder.append(195):e===!1&&this._bufferBuilder.append(194);else if(e===void 0)this._bufferBuilder.append(192);else if(typeof e=="object")if(e===null)this._bufferBuilder.append(192);else{const t=e.constructor;if(e instanceof Array){const n=this.pack_array(e);if(n instanceof Promise)return n.then(()=>this._bufferBuilder.flush())}else if(e instanceof ArrayBuffer)this.pack_bin(new Uint8Array(e));else if("BYTES_PER_ELEMENT"in e){const n=e;this.pack_bin(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}else if(e instanceof Date)this.pack_string(e.toString());else{if(e instanceof Blob)return e.arrayBuffer().then(n=>{this.pack_bin(new Uint8Array(n)),this._bufferBuilder.flush()});if(t==Object||t.toString().startsWith("class")){const n=this.pack_object(e);if(n instanceof Promise)return n.then(()=>this._bufferBuilder.flush())}else throw new Error(`Type "${t.toString()}" not yet supported`)}}else throw new Error(`Type "${typeof e}" not yet supported`);this._bufferBuilder.flush()}pack_bin(e){const t=e.length;if(t<=15)this.pack_uint8(160+t);else if(t<=65535)this._bufferBuilder.append(218),this.pack_uint16(t);else if(t<=4294967295)this._bufferBuilder.append(219),this.pack_uint32(t);else throw new Error("Invalid length");this._bufferBuilder.append_buffer(e)}pack_string(e){const t=this._textEncoder.encode(e),n=t.length;if(n<=15)this.pack_uint8(176+n);else if(n<=65535)this._bufferBuilder.append(216),this.pack_uint16(n);else if(n<=4294967295)this._bufferBuilder.append(217),this.pack_uint32(n);else throw new Error("Invalid length");this._bufferBuilder.append_buffer(t)}pack_array(e){const t=e.length;if(t<=15)this.pack_uint8(144+t);else if(t<=65535)this._bufferBuilder.append(220),this.pack_uint16(t);else if(t<=4294967295)this._bufferBuilder.append(221),this.pack_uint32(t);else throw new Error("Invalid length");const n=s=>{if(s<t){const i=this.pack(e[s]);return i instanceof Promise?i.then(()=>n(s+1)):n(s+1)}};return n(0)}pack_integer(e){if(e>=-32&&e<=127)this._bufferBuilder.append(e&255);else if(e>=0&&e<=255)this._bufferBuilder.append(204),this.pack_uint8(e);else if(e>=-128&&e<=127)this._bufferBuilder.append(208),this.pack_int8(e);else if(e>=0&&e<=65535)this._bufferBuilder.append(205),this.pack_uint16(e);else if(e>=-32768&&e<=32767)this._bufferBuilder.append(209),this.pack_int16(e);else if(e>=0&&e<=4294967295)this._bufferBuilder.append(206),this.pack_uint32(e);else if(e>=-2147483648&&e<=2147483647)this._bufferBuilder.append(210),this.pack_int32(e);else if(e>=-9223372036854776e3&&e<=9223372036854776e3)this._bufferBuilder.append(211),this.pack_int64(e);else if(e>=0&&e<=18446744073709552e3)this._bufferBuilder.append(207),this.pack_uint64(e);else throw new Error("Invalid integer")}pack_double(e){let t=0;e<0&&(t=1,e=-e);const n=Math.floor(Math.log(e)/Math.LN2),s=e/2**n-1,i=Math.floor(s*2**52),o=2**32,a=t<<31|n+1023<<20|i/o&1048575,c=i%o;this._bufferBuilder.append(203),this.pack_int32(a),this.pack_int32(c)}pack_object(e){const t=Object.keys(e),n=t.length;if(n<=15)this.pack_uint8(128+n);else if(n<=65535)this._bufferBuilder.append(222),this.pack_uint16(n);else if(n<=4294967295)this._bufferBuilder.append(223),this.pack_uint32(n);else throw new Error("Invalid length");const s=i=>{if(i<t.length){const o=t[i];if(e.hasOwnProperty(o)){this.pack(o);const a=this.pack(e[o]);if(a instanceof Promise)return a.then(()=>s(i+1))}return s(i+1)}};return s(0)}pack_uint8(e){this._bufferBuilder.append(e)}pack_uint16(e){this._bufferBuilder.append(e>>8),this._bufferBuilder.append(e&255)}pack_uint32(e){const t=e&4294967295;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255)}pack_uint64(e){const t=e/4294967296,n=e%2**32;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255),this._bufferBuilder.append((n&4278190080)>>>24),this._bufferBuilder.append((n&16711680)>>>16),this._bufferBuilder.append((n&65280)>>>8),this._bufferBuilder.append(n&255)}pack_int8(e){this._bufferBuilder.append(e&255)}pack_int16(e){this._bufferBuilder.append((e&65280)>>8),this._bufferBuilder.append(e&255)}pack_int32(e){this._bufferBuilder.append(e>>>24&255),this._bufferBuilder.append((e&16711680)>>>16),this._bufferBuilder.append((e&65280)>>>8),this._bufferBuilder.append(e&255)}pack_int64(e){const t=Math.floor(e/4294967296),n=e%2**32;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255),this._bufferBuilder.append((n&4278190080)>>>24),this._bufferBuilder.append((n&16711680)>>>16),this._bufferBuilder.append((n&65280)>>>8),this._bufferBuilder.append(n&255)}constructor(){this._bufferBuilder=new le,this._textEncoder=new TextEncoder}}let Ye=!0,Ge=!0;function N(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function I(r,e,t){if(!r.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){de("Unable to polyfill events");return}const s=r.RTCPeerConnection.prototype,i=s.addEventListener;s.addEventListener=function(a,c){if(a!==e)return i.apply(this,arguments);const h=l=>{const d=t(l);d&&(c.handleEvent?c.handleEvent(d):c(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(c,h),i.apply(this,[a,h])};const o=s.removeEventListener;s.removeEventListener=function(a,c){if(a!==e||!this._eventMap||!this._eventMap[e])return o.apply(this,arguments);if(!this._eventMap[e].has(c))return o.apply(this,arguments);const h=this._eventMap[e].get(c);return this._eventMap[e].delete(c),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,o.apply(this,[a,h])},Object.defineProperty(s,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function vn(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ye=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function Sn(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ge=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function de(){if(typeof window=="object"){if(Ye)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function ue(r,e){Ge&&console.warn(r+" is deprecated, please use "+e+" instead.")}function Cn(r){const e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n){const s=parseInt(n.version,10);if(s>=90)return{browser:"chrome",version:s}}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(N(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(N(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(N(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype,e._safariVersion=N(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Qe(r){return Object.prototype.toString.call(r)==="[object Object]"}function Xe(r){return Qe(r)?Object.keys(r).reduce(function(e,t){const n=Qe(r[t]),s=n?Xe(r[t]):r[t],i=n&&!Object.keys(s).length;return s===void 0||i?e:Object.assign(e,{[t]:s})},{}):r}function fe(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?fe(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{fe(r,r.get(s),t)})}))}function Ze(r,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const i=[];return r.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&i.push(o)}),i.forEach(o=>{r.forEach(a=>{a.type===n&&a.trackId===o.id&&fe(r,a,s)})}),s}const et=de;function tt(r,e){if(e.version>=64)return;const t=r&&r.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(h=>{if(h==="require"||h==="advanced"||h==="mediaSource")return;const l=typeof a[h]=="object"?a[h]:{ideal:a[h]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const d=function(u,p){return u?u+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){c.optional=c.optional||[];let u={};typeof l.ideal=="number"?(u[d("min",h)]=l.ideal,c.optional.push(u),u={},u[d("max",h)]=l.ideal,c.optional.push(u)):(u[d("",h)]=l.ideal,c.optional.push(u))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[d("",h)]=l.exact):["min","max"].forEach(u=>{l[u]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[d(u,h)]=l[u])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const h=function(l,d,u){d in l&&!(u in l)&&(l[u]=l[d],delete l[d])};a=JSON.parse(JSON.stringify(a)),h(a.audio,"autoGainControl","googAutoGainControl"),h(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let h=a.video.facingMode;h=h&&(typeof h=="object"?h:{ideal:h});const l=e.version<66;if(h&&(h.exact==="user"||h.exact==="environment"||h.ideal==="user"||h.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete a.video.facingMode;let d;if(h.exact==="environment"||h.ideal==="environment"?d=["back","rear"]:(h.exact==="user"||h.ideal==="user")&&(d=["front"]),d)return t.mediaDevices.enumerateDevices().then(u=>{u=u.filter(m=>m.kind==="videoinput");let p=u.find(m=>d.some(_=>m.label.toLowerCase().includes(_)));return!p&&u.length&&d.includes("back")&&(p=u[u.length-1]),p&&(a.video.deviceId=h.exact?{exact:p.deviceId}:{ideal:p.deviceId}),a.video=n(a.video),et("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return et("chrome: "+JSON.stringify(a)),c(a)},i=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,h){s(a,l=>{t.webkitGetUserMedia(l,c,d=>{h&&h(i(d))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,h=>a(h).then(l=>{if(h.audio&&!l.getAudioTracks().length||h.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(i(l))))}}}function nt(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function rt(r,e){if(!(e.version>102))if(typeof r=="object"&&r.RTCPeerConnection&&!("ontrack"in r.RTCPeerConnection.prototype)){Object.defineProperty(r.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});const t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=s=>{s.stream.addEventListener("addtrack",i=>{let o;r.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(c=>c.track&&c.track.id===i.track.id):o={track:i.track};const a=new Event("track");a.track=i.track,a.receiver=o,a.transceiver={receiver:o},a.streams=[s.stream],this.dispatchEvent(a)}),s.stream.getTracks().forEach(i=>{let o;r.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(c=>c.track&&c.track.id===i.id):o={track:i};const a=new Event("track");a.track=i,a.receiver=o,a.transceiver={receiver:o},a.streams=[s.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else I(r,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function st(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(s,i){return{track:i,get dtmf(){return this._dtmf===void 0&&(i.kind==="audio"?this._dtmf=s.createDTMFSender(i):this._dtmf=null),this._dtmf},_pc:s}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,c){let h=s.apply(this,arguments);return h||(h=e(this,a),this._senders.push(h)),h};const i=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){i.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(i){this._senders=this._senders||[],t.apply(this,[i]),i.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(i){this._senders=this._senders||[],n.apply(this,[i]),i.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof r=="object"&&r.RTCPeerConnection&&"getSenders"in r.RTCPeerConnection.prototype&&"createDTMFSender"in r.RTCPeerConnection.prototype&&r.RTCRtpSender&&!("dtmf"in r.RTCRtpSender.prototype)){const e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(r.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function it(r,e){if(e.version>=67||!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){const n=r.RTCPeerConnection.prototype.getSenders;n&&(r.RTCPeerConnection.prototype.getSenders=function(){const o=n.apply(this,[]);return o.forEach(a=>a._pc=this),o});const s=r.RTCPeerConnection.prototype.addTrack;s&&(r.RTCPeerConnection.prototype.addTrack=function(){const o=s.apply(this,arguments);return o._pc=this,o}),r.RTCRtpSender.prototype.getStats=function(){const o=this;return this._pc.getStats().then(a=>Ze(a,o.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const n=r.RTCPeerConnection.prototype.getReceivers;n&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=n.apply(this,[]);return i.forEach(o=>o._pc=this),i}),I(r,"track",s=>(s.receiver._pc=s.srcElement,s)),r.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(o=>Ze(o,i.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;const t=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){const s=arguments[0];let i,o,a;return this.getSenders().forEach(c=>{c.track===s&&(i?a=!0:i=c)}),this.getReceivers().forEach(c=>(c.track===s&&(o?a=!0:o=c),c.track===s)),a||i&&o?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():o?o.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ot(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(h=>{if(this.getSenders().find(d=>d.track===h))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(h=>a.indexOf(h)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function at(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ot(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(d=>this._reverseStreams[d.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(d=>{if(this.getSenders().find(p=>p.track===d))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const d=new r.MediaStream(l.getTracks());this._streams[l.id]=d,this._reverseStreams[d.id]=l,l=d}n.apply(this,[l])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},r.RTCPeerConnection.prototype.addTrack=function(l,d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const u=[].slice.call(arguments,1);if(u.length!==1||!u[0].getTracks().find(_=>_===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(_=>_.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const m=this._streams[d.id];if(m)m.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const _=new r.MediaStream([l]);this._streams[d.id]=_,this._reverseStreams[_.id]=d,this.addStream(_)}return this.getSenders().find(_=>_.track===l)};function i(h,l){let d=l.sdp;return Object.keys(h._reverseStreams||[]).forEach(u=>{const p=h._reverseStreams[u],m=h._streams[p.id];d=d.replace(new RegExp(m.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:d})}function o(h,l){let d=l.sdp;return Object.keys(h._reverseStreams||[]).forEach(u=>{const p=h._reverseStreams[u],m=h._streams[p.id];d=d.replace(new RegExp(p.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:d})}["createOffer","createAnswer"].forEach(function(h){const l=r.RTCPeerConnection.prototype[h],d={[h](){const u=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[m=>{const _=i(this,m);u[0].apply(null,[_])},m=>{u[1]&&u[1].apply(null,m)},arguments[2]]):l.apply(this,arguments).then(m=>i(this,m))}};r.RTCPeerConnection.prototype[h]=d[h]});const a=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const h=c.get.apply(this);return h.type===""?h:i(this,h)}}),r.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let u;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(_=>l.track===_)&&(u=this._streams[p])}),u&&(u.getTracks().length===1?this.removeStream(this._reverseStreams[u.id]):u.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function pe(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]})}function ct(r,e){e.version>102||I(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const ht=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:ct,shimAddTrackRemoveTrack:at,shimAddTrackRemoveTrackWithNative:ot,shimGetSendersWithDtmf:st,shimGetUserMedia:tt,shimMediaStream:nt,shimOnTrack:rt,shimPeerConnection:pe,shimSenderReceiverGetStats:it},Symbol.toStringTag,{value:"Module"}));function lt(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(s,i,o){ue("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(i,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},i=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),i(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function kn(r,e){r.navigator.mediaDevices&&(r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)}))}function dt(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ge(r,e){typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection)||(!r.RTCPeerConnection&&r.mozRTCPeerConnection&&(r.RTCPeerConnection=r.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]}))}function ut(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection)||e.version>=151)return;const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[i,o,a]=arguments;return this.signalingState==="closed"?Promise.resolve(new Map):n.apply(this,[i||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(h=>{h.type=t[h.type]||h.type})}catch(h){if(h.name!=="TypeError")throw h;c.forEach((l,d)=>{c.set(d,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(o,a)}}function ft(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;const e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(i=>i._pc=this),s});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function pt(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;const e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),I(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function gt(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){ue("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function mt(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function yt(r,e){if(!(typeof r=="object"&&r.RTCPeerConnection)||e.version>=110)return;const t=r.RTCPeerConnection.prototype.addTransceiver;t&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let s=arguments[1]&&arguments[1].sendEncodings;s===void 0&&(s=[]),s=[...s];const i=s.length>0;i&&s.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const o=t.apply(this,arguments);if(i){const{sender:a}=o,c=a.getParameters();(!("encodings"in c)||c.encodings.length===1&&Object.keys(c.encodings[0]).length===0)&&(c.encodings=s,a.sendEncodings=s,this.setParametersPromises.push(a.setParameters(c).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return o})}function bt(r,e){if(!(typeof r=="object"&&r.RTCRtpSender)||e.version>=110)return;const t=r.RTCRtpSender.prototype.getParameters;t&&(r.RTCRtpSender.prototype.getParameters=function(){const s=t.apply(this,arguments);return"encodings"in s||(s.encodings=[].concat(this.sendEncodings||[{}])),s})}function _t(r,e){if(!(typeof r=="object"&&r.RTCPeerConnection)||e.version>=110)return;const t=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function vt(r,e){if(!(typeof r=="object"&&r.RTCPeerConnection)||e.version>=110)return;const t=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}const St=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:yt,shimCreateAnswer:vt,shimCreateOffer:_t,shimGetDisplayMedia:kn,shimGetParameters:bt,shimGetStats:ut,shimGetUserMedia:lt,shimOnTrack:dt,shimPeerConnection:ge,shimRTCDataChannel:mt,shimReceiverGetStats:pt,shimRemoveStream:gt,shimSenderGetStats:ft},Symbol.toStringTag,{value:"Module"}));function Ct(r){if(!(typeof r!="object"||!r.RTCPeerConnection)){if("getLocalStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in r.RTCPeerConnection.prototype)){const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...s){return s&&s.forEach(i=>{this._localStreams?this._localStreams.includes(i)||this._localStreams.push(i):this._localStreams=[i]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(i=>{s.includes(i.track)&&this.removeTrack(i)})})}}function kt(r){if(!(typeof r!="object"||!r.RTCPeerConnection)&&("getRemoteStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in r.RTCPeerConnection.prototype))){Object.defineProperty(r.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const i=new Event("addstream");i.stream=s,this.dispatchEvent(i)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(i=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(i)>=0)return;n._remoteStreams.push(i);const o=new Event("addstream");o.stream=i,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function xt(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,i=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(h,l){const d=arguments.length>=2?arguments[2]:arguments[0],u=t.apply(this,[d]);return l?(u.then(h,l),Promise.resolve()):u},e.createAnswer=function(h,l){const d=arguments.length>=2?arguments[2]:arguments[0],u=n.apply(this,[d]);return l?(u.then(h,l),Promise.resolve()):u};let a=function(c,h,l){const d=s.apply(this,[c]);return l?(d.then(h,l),Promise.resolve()):d};e.setLocalDescription=a,a=function(c,h,l){const d=i.apply(this,[c]);return l?(d.then(h,l),Promise.resolve()):d},e.setRemoteDescription=a,a=function(c,h,l){const d=o.apply(this,[c]);return l?(d.then(h,l),Promise.resolve()):d},e.addIceCandidate=a}function Tt(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(Rt(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,i){e.mediaDevices.getUserMedia(n).then(s,i)}).bind(e))}function Rt(r){return r&&r.video!==void 0?Object.assign({},r,{video:Xe(r.video)}):r}function Et(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const i=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(ue("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,i.push(a)):i.push(n.iceServers[o])}n.iceServers=i}return new e(n,s)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Pt(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function wt(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const i=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveVideo===!0&&!i&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Mt(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const At=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Mt,shimCallbacksAPI:xt,shimConstraints:Rt,shimCreateOfferLegacy:wt,shimGetUserMedia:Tt,shimLocalStreamsAPI:Ct,shimRTCIceServerUrls:Et,shimRemoteStreamsAPI:kt,shimTrackEventTransceiver:Pt},Symbol.toStringTag,{value:"Module"}));function xn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ot={exports:{}};(function(r){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
|
|
1
|
+
(function(x,P){typeof exports=="object"&&typeof module<"u"?P(exports):typeof define=="function"&&define.amd?define(["exports"],P):(x=typeof globalThis<"u"?globalThis:x||self,P(x.MeetSDK={}))})(this,function(x){"use strict";var es=x=>{throw TypeError(x)};var K=(x,P,le)=>P.has(x)?es("Cannot add the same private member more than once"):P instanceof WeakSet?P.add(x):P.set(x,le);var je,qe,Ve,He;function P(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const s in n)if(s!=="default"&&!(s in r)){const i=Object.getOwnPropertyDescriptor(n,s);i&&Object.defineProperty(r,s,i.get?i:{enumerable:!0,get:()=>n[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}class le{constructor(){this.encoder=new TextEncoder,this._pieces=[],this._parts=[]}append_buffer(e){this.flush(),this._parts.push(e)}append(e){this._pieces.push(e)}flush(){if(this._pieces.length>0){const e=new Uint8Array(this._pieces);this._parts.push(e),this._pieces=[]}}toArrayBuffer(){const e=[];for(const t of this._parts)e.push(t);return yn(e).buffer}}function yn(r){let e=0;for(const s of r)e+=s.byteLength;const t=new Uint8Array(e);let n=0;for(const s of r){const i=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);t.set(i,n),n+=s.byteLength}return t}function Je(r){return new bn(r).unpack()}function We(r){const e=new _n,t=e.pack(r);return t instanceof Promise?t.then(()=>e.getBuffer()):e.getBuffer()}class bn{constructor(e){this.index=0,this.dataBuffer=e,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}unpack(){const e=this.unpack_uint8();if(e<128)return e;if((e^224)<32)return(e^224)-32;let t;if((t=e^160)<=15)return this.unpack_raw(t);if((t=e^176)<=15)return this.unpack_string(t);if((t=e^144)<=15)return this.unpack_array(t);if((t=e^128)<=15)return this.unpack_map(t);switch(e){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return;case 213:return;case 214:return;case 215:return;case 216:return t=this.unpack_uint16(),this.unpack_string(t);case 217:return t=this.unpack_uint32(),this.unpack_string(t);case 218:return t=this.unpack_uint16(),this.unpack_raw(t);case 219:return t=this.unpack_uint32(),this.unpack_raw(t);case 220:return t=this.unpack_uint16(),this.unpack_array(t);case 221:return t=this.unpack_uint32(),this.unpack_array(t);case 222:return t=this.unpack_uint16(),this.unpack_map(t);case 223:return t=this.unpack_uint32(),this.unpack_map(t)}}unpack_uint8(){const e=this.dataView[this.index]&255;return this.index++,e}unpack_uint16(){const e=this.read(2),t=(e[0]&255)*256+(e[1]&255);return this.index+=2,t}unpack_uint32(){const e=this.read(4),t=((e[0]*256+e[1])*256+e[2])*256+e[3];return this.index+=4,t}unpack_uint64(){const e=this.read(8),t=((((((e[0]*256+e[1])*256+e[2])*256+e[3])*256+e[4])*256+e[5])*256+e[6])*256+e[7];return this.index+=8,t}unpack_int8(){const e=this.unpack_uint8();return e<128?e:e-256}unpack_int16(){const e=this.unpack_uint16();return e<32768?e:e-65536}unpack_int32(){const e=this.unpack_uint32();return e<2**31?e:e-2**32}unpack_int64(){const e=this.unpack_uint64();return e<2**63?e:e-2**64}unpack_raw(e){if(this.length<this.index+e)throw new Error(`BinaryPackFailure: index is out of range ${this.index} ${e} ${this.length}`);const t=this.dataBuffer.slice(this.index,this.index+e);return this.index+=e,t}unpack_string(e){const t=this.read(e);let n=0,s="",i,o;for(;n<e;)i=t[n],i<160?(o=i,n++):(i^192)<32?(o=(i&31)<<6|t[n+1]&63,n+=2):(i^224)<16?(o=(i&15)<<12|(t[n+1]&63)<<6|t[n+2]&63,n+=3):(o=(i&7)<<18|(t[n+1]&63)<<12|(t[n+2]&63)<<6|t[n+3]&63,n+=4),s+=String.fromCodePoint(o);return this.index+=e,s}unpack_array(e){const t=new Array(e);for(let n=0;n<e;n++)t[n]=this.unpack();return t}unpack_map(e){const t={};for(let n=0;n<e;n++){const s=this.unpack();t[s]=this.unpack()}return t}unpack_float(){const e=this.unpack_uint32(),t=e>>31,n=(e>>23&255)-127,s=e&8388607|8388608;return(t===0?1:-1)*s*2**(n-23)}unpack_double(){const e=this.unpack_uint32(),t=this.unpack_uint32(),n=e>>31,s=(e>>20&2047)-1023,o=(e&1048575|1048576)*2**(s-20)+t*2**(s-52);return(n===0?1:-1)*o}read(e){const t=this.index;if(t+e<=this.length)return this.dataView.subarray(t,t+e);throw new Error("BinaryPackFailure: read index out of range")}}class _n{getBuffer(){return this._bufferBuilder.toArrayBuffer()}pack(e){if(typeof e=="string")this.pack_string(e);else if(typeof e=="number")Math.floor(e)===e?this.pack_integer(e):this.pack_double(e);else if(typeof e=="boolean")e===!0?this._bufferBuilder.append(195):e===!1&&this._bufferBuilder.append(194);else if(e===void 0)this._bufferBuilder.append(192);else if(typeof e=="object")if(e===null)this._bufferBuilder.append(192);else{const t=e.constructor;if(e instanceof Array){const n=this.pack_array(e);if(n instanceof Promise)return n.then(()=>this._bufferBuilder.flush())}else if(e instanceof ArrayBuffer)this.pack_bin(new Uint8Array(e));else if("BYTES_PER_ELEMENT"in e){const n=e;this.pack_bin(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}else if(e instanceof Date)this.pack_string(e.toString());else{if(e instanceof Blob)return e.arrayBuffer().then(n=>{this.pack_bin(new Uint8Array(n)),this._bufferBuilder.flush()});if(t==Object||t.toString().startsWith("class")){const n=this.pack_object(e);if(n instanceof Promise)return n.then(()=>this._bufferBuilder.flush())}else throw new Error(`Type "${t.toString()}" not yet supported`)}}else throw new Error(`Type "${typeof e}" not yet supported`);this._bufferBuilder.flush()}pack_bin(e){const t=e.length;if(t<=15)this.pack_uint8(160+t);else if(t<=65535)this._bufferBuilder.append(218),this.pack_uint16(t);else if(t<=4294967295)this._bufferBuilder.append(219),this.pack_uint32(t);else throw new Error("Invalid length");this._bufferBuilder.append_buffer(e)}pack_string(e){const t=this._textEncoder.encode(e),n=t.length;if(n<=15)this.pack_uint8(176+n);else if(n<=65535)this._bufferBuilder.append(216),this.pack_uint16(n);else if(n<=4294967295)this._bufferBuilder.append(217),this.pack_uint32(n);else throw new Error("Invalid length");this._bufferBuilder.append_buffer(t)}pack_array(e){const t=e.length;if(t<=15)this.pack_uint8(144+t);else if(t<=65535)this._bufferBuilder.append(220),this.pack_uint16(t);else if(t<=4294967295)this._bufferBuilder.append(221),this.pack_uint32(t);else throw new Error("Invalid length");const n=s=>{if(s<t){const i=this.pack(e[s]);return i instanceof Promise?i.then(()=>n(s+1)):n(s+1)}};return n(0)}pack_integer(e){if(e>=-32&&e<=127)this._bufferBuilder.append(e&255);else if(e>=0&&e<=255)this._bufferBuilder.append(204),this.pack_uint8(e);else if(e>=-128&&e<=127)this._bufferBuilder.append(208),this.pack_int8(e);else if(e>=0&&e<=65535)this._bufferBuilder.append(205),this.pack_uint16(e);else if(e>=-32768&&e<=32767)this._bufferBuilder.append(209),this.pack_int16(e);else if(e>=0&&e<=4294967295)this._bufferBuilder.append(206),this.pack_uint32(e);else if(e>=-2147483648&&e<=2147483647)this._bufferBuilder.append(210),this.pack_int32(e);else if(e>=-9223372036854776e3&&e<=9223372036854776e3)this._bufferBuilder.append(211),this.pack_int64(e);else if(e>=0&&e<=18446744073709552e3)this._bufferBuilder.append(207),this.pack_uint64(e);else throw new Error("Invalid integer")}pack_double(e){let t=0;e<0&&(t=1,e=-e);const n=Math.floor(Math.log(e)/Math.LN2),s=e/2**n-1,i=Math.floor(s*2**52),o=2**32,a=t<<31|n+1023<<20|i/o&1048575,c=i%o;this._bufferBuilder.append(203),this.pack_int32(a),this.pack_int32(c)}pack_object(e){const t=Object.keys(e),n=t.length;if(n<=15)this.pack_uint8(128+n);else if(n<=65535)this._bufferBuilder.append(222),this.pack_uint16(n);else if(n<=4294967295)this._bufferBuilder.append(223),this.pack_uint32(n);else throw new Error("Invalid length");const s=i=>{if(i<t.length){const o=t[i];if(e.hasOwnProperty(o)){this.pack(o);const a=this.pack(e[o]);if(a instanceof Promise)return a.then(()=>s(i+1))}return s(i+1)}};return s(0)}pack_uint8(e){this._bufferBuilder.append(e)}pack_uint16(e){this._bufferBuilder.append(e>>8),this._bufferBuilder.append(e&255)}pack_uint32(e){const t=e&4294967295;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255)}pack_uint64(e){const t=e/4294967296,n=e%2**32;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255),this._bufferBuilder.append((n&4278190080)>>>24),this._bufferBuilder.append((n&16711680)>>>16),this._bufferBuilder.append((n&65280)>>>8),this._bufferBuilder.append(n&255)}pack_int8(e){this._bufferBuilder.append(e&255)}pack_int16(e){this._bufferBuilder.append((e&65280)>>8),this._bufferBuilder.append(e&255)}pack_int32(e){this._bufferBuilder.append(e>>>24&255),this._bufferBuilder.append((e&16711680)>>>16),this._bufferBuilder.append((e&65280)>>>8),this._bufferBuilder.append(e&255)}pack_int64(e){const t=Math.floor(e/4294967296),n=e%2**32;this._bufferBuilder.append((t&4278190080)>>>24),this._bufferBuilder.append((t&16711680)>>>16),this._bufferBuilder.append((t&65280)>>>8),this._bufferBuilder.append(t&255),this._bufferBuilder.append((n&4278190080)>>>24),this._bufferBuilder.append((n&16711680)>>>16),this._bufferBuilder.append((n&65280)>>>8),this._bufferBuilder.append(n&255)}constructor(){this._bufferBuilder=new le,this._textEncoder=new TextEncoder}}let Ye=!0,Ge=!0;function N(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function I(r,e,t){if(!r.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){de("Unable to polyfill events");return}const s=r.RTCPeerConnection.prototype,i=s.addEventListener;s.addEventListener=function(a,c){if(a!==e)return i.apply(this,arguments);const h=l=>{const d=t(l);d&&(c.handleEvent?c.handleEvent(d):c(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(c,h),i.apply(this,[a,h])};const o=s.removeEventListener;s.removeEventListener=function(a,c){if(a!==e||!this._eventMap||!this._eventMap[e])return o.apply(this,arguments);if(!this._eventMap[e].has(c))return o.apply(this,arguments);const h=this._eventMap[e].get(c);return this._eventMap[e].delete(c),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,o.apply(this,[a,h])},Object.defineProperty(s,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function vn(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ye=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function Sn(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ge=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function de(){if(typeof window=="object"){if(Ye)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function ue(r,e){Ge&&console.warn(r+" is deprecated, please use "+e+" instead.")}function Cn(r){const e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n){const s=parseInt(n.version,10);if(s>=90)return{browser:"chrome",version:s}}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(N(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(N(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(N(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype,e._safariVersion=N(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Qe(r){return Object.prototype.toString.call(r)==="[object Object]"}function Xe(r){return Qe(r)?Object.keys(r).reduce(function(e,t){const n=Qe(r[t]),s=n?Xe(r[t]):r[t],i=n&&!Object.keys(s).length;return s===void 0||i?e:Object.assign(e,{[t]:s})},{}):r}function fe(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?fe(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{fe(r,r.get(s),t)})}))}function Ze(r,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const i=[];return r.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&i.push(o)}),i.forEach(o=>{r.forEach(a=>{a.type===n&&a.trackId===o.id&&fe(r,a,s)})}),s}const et=de;function tt(r,e){if(e.version>=64)return;const t=r&&r.navigator;if(!t.mediaDevices)return;const n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(h=>{if(h==="require"||h==="advanced"||h==="mediaSource")return;const l=typeof a[h]=="object"?a[h]:{ideal:a[h]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const d=function(u,p){return u?u+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){c.optional=c.optional||[];let u={};typeof l.ideal=="number"?(u[d("min",h)]=l.ideal,c.optional.push(u),u={},u[d("max",h)]=l.ideal,c.optional.push(u)):(u[d("",h)]=l.ideal,c.optional.push(u))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[d("",h)]=l.exact):["min","max"].forEach(u=>{l[u]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[d(u,h)]=l[u])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},s=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const h=function(l,d,u){d in l&&!(u in l)&&(l[u]=l[d],delete l[d])};a=JSON.parse(JSON.stringify(a)),h(a.audio,"autoGainControl","googAutoGainControl"),h(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let h=a.video.facingMode;h=h&&(typeof h=="object"?h:{ideal:h});const l=e.version<66;if(h&&(h.exact==="user"||h.exact==="environment"||h.ideal==="user"||h.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete a.video.facingMode;let d;if(h.exact==="environment"||h.ideal==="environment"?d=["back","rear"]:(h.exact==="user"||h.ideal==="user")&&(d=["front"]),d)return t.mediaDevices.enumerateDevices().then(u=>{u=u.filter(m=>m.kind==="videoinput");let p=u.find(m=>d.some(_=>m.label.toLowerCase().includes(_)));return!p&&u.length&&d.includes("back")&&(p=u[u.length-1]),p&&(a.video.deviceId=h.exact?{exact:p.deviceId}:{ideal:p.deviceId}),a.video=n(a.video),et("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return et("chrome: "+JSON.stringify(a)),c(a)},i=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,h){s(a,l=>{t.webkitGetUserMedia(l,c,d=>{h&&h(i(d))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,h=>a(h).then(l=>{if(h.audio&&!l.getAudioTracks().length||h.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(i(l))))}}}function nt(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function rt(r,e){if(!(e.version>102))if(typeof r=="object"&&r.RTCPeerConnection&&!("ontrack"in r.RTCPeerConnection.prototype)){Object.defineProperty(r.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});const t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=s=>{s.stream.addEventListener("addtrack",i=>{let o;r.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(c=>c.track&&c.track.id===i.track.id):o={track:i.track};const a=new Event("track");a.track=i.track,a.receiver=o,a.transceiver={receiver:o},a.streams=[s.stream],this.dispatchEvent(a)}),s.stream.getTracks().forEach(i=>{let o;r.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(c=>c.track&&c.track.id===i.id):o={track:i};const a=new Event("track");a.track=i,a.receiver=o,a.transceiver={receiver:o},a.streams=[s.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else I(r,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function st(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(s,i){return{track:i,get dtmf(){return this._dtmf===void 0&&(i.kind==="audio"?this._dtmf=s.createDTMFSender(i):this._dtmf=null),this._dtmf},_pc:s}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,c){let h=s.apply(this,arguments);return h||(h=e(this,a),this._senders.push(h)),h};const i=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){i.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(i){this._senders=this._senders||[],t.apply(this,[i]),i.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(i){this._senders=this._senders||[],n.apply(this,[i]),i.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof r=="object"&&r.RTCPeerConnection&&"getSenders"in r.RTCPeerConnection.prototype&&"createDTMFSender"in r.RTCPeerConnection.prototype&&r.RTCRtpSender&&!("dtmf"in r.RTCRtpSender.prototype)){const e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n},Object.defineProperty(r.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function it(r,e){if(e.version>=67||!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){const n=r.RTCPeerConnection.prototype.getSenders;n&&(r.RTCPeerConnection.prototype.getSenders=function(){const o=n.apply(this,[]);return o.forEach(a=>a._pc=this),o});const s=r.RTCPeerConnection.prototype.addTrack;s&&(r.RTCPeerConnection.prototype.addTrack=function(){const o=s.apply(this,arguments);return o._pc=this,o}),r.RTCRtpSender.prototype.getStats=function(){const o=this;return this._pc.getStats().then(a=>Ze(a,o.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const n=r.RTCPeerConnection.prototype.getReceivers;n&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=n.apply(this,[]);return i.forEach(o=>o._pc=this),i}),I(r,"track",s=>(s.receiver._pc=s.srcElement,s)),r.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(o=>Ze(o,i.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;const t=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){const s=arguments[0];let i,o,a;return this.getSenders().forEach(c=>{c.track===s&&(i?a=!0:i=c)}),this.getReceivers().forEach(c=>(c.track===s&&(o?a=!0:o=c),c.track===s)),a||i&&o?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():o?o.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ot(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(h=>{if(this.getSenders().find(d=>d.track===h))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(h=>a.indexOf(h)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const s=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),s.apply(this,arguments)}}function at(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ot(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(d=>this._reverseStreams[d.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(d=>{if(this.getSenders().find(p=>p.track===d))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const d=new r.MediaStream(l.getTracks());this._streams[l.id]=d,this._reverseStreams[d.id]=l,l=d}n.apply(this,[l])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},r.RTCPeerConnection.prototype.addTrack=function(l,d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const u=[].slice.call(arguments,1);if(u.length!==1||!u[0].getTracks().find(_=>_===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(_=>_.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const m=this._streams[d.id];if(m)m.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const _=new r.MediaStream([l]);this._streams[d.id]=_,this._reverseStreams[_.id]=d,this.addStream(_)}return this.getSenders().find(_=>_.track===l)};function i(h,l){let d=l.sdp;return Object.keys(h._reverseStreams||[]).forEach(u=>{const p=h._reverseStreams[u],m=h._streams[p.id];d=d.replace(new RegExp(m.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:d})}function o(h,l){let d=l.sdp;return Object.keys(h._reverseStreams||[]).forEach(u=>{const p=h._reverseStreams[u],m=h._streams[p.id];d=d.replace(new RegExp(p.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:d})}["createOffer","createAnswer"].forEach(function(h){const l=r.RTCPeerConnection.prototype[h],d={[h](){const u=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[m=>{const _=i(this,m);u[0].apply(null,[_])},m=>{u[1]&&u[1].apply(null,m)},arguments[2]]):l.apply(this,arguments).then(m=>i(this,m))}};r.RTCPeerConnection.prototype[h]=d[h]});const a=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const h=c.get.apply(this);return h.type===""?h:i(this,h)}}),r.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let u;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(_=>l.track===_)&&(u=this._streams[p])}),u&&(u.getTracks().length===1?this.removeStream(this._reverseStreams[u.id]):u.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function pe(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]})}function ct(r,e){e.version>102||I(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const ht=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:ct,shimAddTrackRemoveTrack:at,shimAddTrackRemoveTrackWithNative:ot,shimGetSendersWithDtmf:st,shimGetUserMedia:tt,shimMediaStream:nt,shimOnTrack:rt,shimPeerConnection:pe,shimSenderReceiverGetStats:it},Symbol.toStringTag,{value:"Module"}));function lt(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(s,i,o){ue("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(i,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},i=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o.audio,"autoGainControl","mozAutoGainControl"),s(o.audio,"noiseSuppression","mozNoiseSuppression")),i(o)},n&&n.prototype.getSettings){const o=n.prototype.getSettings;n.prototype.getSettings=function(){const a=o.apply(this,arguments);return s(a,"mozAutoGainControl","autoGainControl"),s(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const o=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a,"autoGainControl","mozAutoGainControl"),s(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function kn(r,e){r.navigator.mediaDevices&&(r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)}))}function dt(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ge(r,e){typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection)||(!r.RTCPeerConnection&&r.mozRTCPeerConnection&&(r.RTCPeerConnection=r.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]}))}function ut(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection)||e.version>=151)return;const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[i,o,a]=arguments;return this.signalingState==="closed"?Promise.resolve(new Map):n.apply(this,[i||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(h=>{h.type=t[h.type]||h.type})}catch(h){if(h.name!=="TypeError")throw h;c.forEach((l,d)=>{c.set(d,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(o,a)}}function ft(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;const e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(i=>i._pc=this),s});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function pt(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;const e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),I(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function gt(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){ue("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function mt(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function yt(r,e){if(!(typeof r=="object"&&r.RTCPeerConnection)||e.version>=110)return;const t=r.RTCPeerConnection.prototype.addTransceiver;t&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let s=arguments[1]&&arguments[1].sendEncodings;s===void 0&&(s=[]),s=[...s];const i=s.length>0;i&&s.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const o=t.apply(this,arguments);if(i){const{sender:a}=o,c=a.getParameters();(!("encodings"in c)||c.encodings.length===1&&Object.keys(c.encodings[0]).length===0)&&(c.encodings=s,a.sendEncodings=s,this.setParametersPromises.push(a.setParameters(c).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return o})}function bt(r,e){if(!(typeof r=="object"&&r.RTCRtpSender)||e.version>=110)return;const t=r.RTCRtpSender.prototype.getParameters;t&&(r.RTCRtpSender.prototype.getParameters=function(){const s=t.apply(this,arguments);return"encodings"in s||(s.encodings=[].concat(this.sendEncodings||[{}])),s})}function _t(r,e){if(!(typeof r=="object"&&r.RTCPeerConnection)||e.version>=110)return;const t=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function vt(r,e){if(!(typeof r=="object"&&r.RTCPeerConnection)||e.version>=110)return;const t=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}const St=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:yt,shimCreateAnswer:vt,shimCreateOffer:_t,shimGetDisplayMedia:kn,shimGetParameters:bt,shimGetStats:ut,shimGetUserMedia:lt,shimOnTrack:dt,shimPeerConnection:ge,shimRTCDataChannel:mt,shimReceiverGetStats:pt,shimRemoveStream:gt,shimSenderGetStats:ft},Symbol.toStringTag,{value:"Module"}));function Ct(r){if(!(typeof r!="object"||!r.RTCPeerConnection)){if("getLocalStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in r.RTCPeerConnection.prototype)){const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...s){return s&&s.forEach(i=>{this._localStreams?this._localStreams.includes(i)||this._localStreams.push(i):this._localStreams=[i]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(i=>{s.includes(i.track)&&this.removeTrack(i)})})}}function kt(r){if(!(typeof r!="object"||!r.RTCPeerConnection)&&("getRemoteStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in r.RTCPeerConnection.prototype))){Object.defineProperty(r.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const i=new Event("addstream");i.stream=s,this.dispatchEvent(i)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(i=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(i)>=0)return;n._remoteStreams.push(i);const o=new Event("addstream");o.stream=i,n.dispatchEvent(o)})}),e.apply(n,arguments)}}}function xt(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,i=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(h,l){const d=arguments.length>=2?arguments[2]:arguments[0],u=t.apply(this,[d]);return l?(u.then(h,l),Promise.resolve()):u},e.createAnswer=function(h,l){const d=arguments.length>=2?arguments[2]:arguments[0],u=n.apply(this,[d]);return l?(u.then(h,l),Promise.resolve()):u};let a=function(c,h,l){const d=s.apply(this,[c]);return l?(d.then(h,l),Promise.resolve()):d};e.setLocalDescription=a,a=function(c,h,l){const d=i.apply(this,[c]);return l?(d.then(h,l),Promise.resolve()):d},e.setRemoteDescription=a,a=function(c,h,l){const d=o.apply(this,[c]);return l?(d.then(h,l),Promise.resolve()):d},e.addIceCandidate=a}function Tt(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(Rt(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,i){e.mediaDevices.getUserMedia(n).then(s,i)}).bind(e))}function Rt(r){return r&&r.video!==void 0?Object.assign({},r,{video:Xe(r.video)}):r}function Pt(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const i=[];for(let o=0;o<n.iceServers.length;o++){let a=n.iceServers[o];a.urls===void 0&&a.url?(ue("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,i.push(a)):i.push(n.iceServers[o])}n.iceServers=i}return new e(n,s)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Et(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function wt(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const i=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveVideo===!0&&!i&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Mt(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const At=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Mt,shimCallbacksAPI:xt,shimConstraints:Rt,shimCreateOfferLegacy:wt,shimGetUserMedia:Tt,shimLocalStreamsAPI:Ct,shimRTCIceServerUrls:Pt,shimRemoteStreamsAPI:kt,shimTrackEventTransceiver:Et},Symbol.toStringTag,{value:"Module"}));function xn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ot={exports:{}};(function(r){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
|
|
2
2
|
`).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
|
|
3
3
|
m=`).map((s,i)=>(i>0?"m="+s:s).trim()+`\r
|
|
4
4
|
`)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(s=>s.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const s={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let i=8;i<n.length;i+=2)switch(n[i]){case"raddr":s.relatedAddress=n[i+1];break;case"rport":s.relatedPort=parseInt(n[i+1],10);break;case"tcptype":s.tcpType=n[i+1];break;case"ufrag":s.ufrag=n[i+1],s.usernameFragment=n[i+1];break;default:s[n[i]]===void 0&&(s[n[i]]=n[i+1]);break}return s},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const s=t.component;s==="rtp"?n.push(1):s==="rtcp"?n.push(2):n.push(s),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const i=t.type;return n.push("typ"),n.push(i),i!=="host"&&t.relatedAddress&&t.relatedPort!==void 0&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const s={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),s.name=n[0],s.clockRate=parseInt(n[1],10),s.channels=n.length===3?parseInt(n[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
|
|
@@ -29,16 +29,16 @@ a=ice-pwd:`+t.password+`\r
|
|
|
29
29
|
o=`+(s||"thisisadapterortc")+" "+i+" "+o+` IN IP4 127.0.0.1\r
|
|
30
30
|
s=-\r
|
|
31
31
|
t=0 0\r
|
|
32
|
-
`},e.getDirection=function(t,n){const s=e.splitLines(t);for(let i=0;i<s.length;i++)switch(s[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[i].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},r.exports=e})(Ot);var It=Ot.exports;const B=xn(It),Tn=
|
|
32
|
+
`},e.getDirection=function(t,n){const s=e.splitLines(t);for(let i=0;i<s.length;i++)switch(s[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[i].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},r.exports=e})(Ot);var It=Ot.exports;const B=xn(It),Tn=P({__proto__:null,default:B},[It]);function J(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;const e=r.RTCIceCandidate;r.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const s=new e(n),i=B.parseCandidate(n.candidate);for(const o in i)o in s||Object.defineProperty(s,o,{value:i[o]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(n)},r.RTCIceCandidate.prototype=e.prototype,I(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function me(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||I(r,"icecandidate",e=>{if(e.candidate){const t=B.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function W(r,e){if(!r.RTCPeerConnection||e.browser==="chrome"&&e.version>102||e.browser==="firefox"&&e.version>=113)return;"sctp"in r.RTCPeerConnection.prototype||Object.defineProperty(r.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(a){if(!a||!a.sdp)return!1;const c=B.splitSections(a.sdp);return c.shift(),c.some(h=>{const l=B.parseMLine(h);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},n=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const h=parseInt(c[1],10);return h!==h?-1:h},s=function(a){let c=65536;return e.browser==="firefox"&&(e.version<57?a===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},i=function(a,c){let h=65536;e.browser==="firefox"&&e.version===57&&(h=65535);const l=B.matchPrefix(a.sdp,"a=max-message-size:");return l.length>0?h=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(h=2147483637),h},o=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),h=s(c),l=i(arguments[0],c);let d;h===0&&l===0?d=Number.POSITIVE_INFINITY:h===0||l===0?d=Math.max(h,l):d=Math.min(h,l);const u={};Object.defineProperty(u,"maxMessageSize",{get(){return d}}),this._sctp=u}return o.apply(this,arguments)}}function Y(r,e){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype)||e.browser==="chrome"&&e.version>=149||e.browser==="firefox"&&e.version>60)return;function t(s,i){const o=s.send;s.send=function(){const c=arguments[0],h=c.length||c.size||c.byteLength;if(s.readyState==="open"&&i.sctp&&h>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return o.apply(s,arguments)}}const n=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const i=n.apply(this,arguments);return t(i,this),i},I(r,"datachannel",s=>(t(s.channel,s.target),s))}function ye(r){if(!r.RTCPeerConnection||"connectionState"in r.RTCPeerConnection.prototype)return;const e=r.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const i=s.target;if(i._lastConnectionState!==i.connectionState){i._lastConnectionState=i.connectionState;const o=new Event("connectionstatechange",s);i.dispatchEvent(o)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function be(r,e){if(!r.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
|
|
33
33
|
a=extmap-allow-mixed`)!==-1){const i=s.sdp.split(`
|
|
34
34
|
`).filter(o=>o.trim()!=="a=extmap-allow-mixed").join(`
|
|
35
|
-
`);r.RTCSessionDescription&&s instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:s.type,sdp:i}):s.sdp=i}return t.apply(this,arguments)}}function G(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(r.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Q(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}const Rn=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:be,shimAddIceCandidateNullOrEmpty:G,shimConnectionState:ye,shimMaxMessageSize:W,shimParameterlessSetLocalDescription:Q,shimRTCIceCandidate:J,shimRTCIceCandidateRelayProtocol:me,shimSendThrowTypeError:Y},Symbol.toStringTag,{value:"Module"}));function
|
|
35
|
+
`);r.RTCSessionDescription&&s instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:s.type,sdp:i}):s.sdp=i}return t.apply(this,arguments)}}function G(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(r.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Q(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(o=>t.apply(this,[o]))})}const Rn=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:be,shimAddIceCandidateNullOrEmpty:G,shimConnectionState:ye,shimMaxMessageSize:W,shimParameterlessSetLocalDescription:Q,shimRTCIceCandidate:J,shimRTCIceCandidateRelayProtocol:me,shimSendThrowTypeError:Y},Symbol.toStringTag,{value:"Module"}));function Pn({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=de,n=Cn(r),s={browserDetails:n,commonShim:Rn,extractVersion:N,disableLog:vn,disableWarnings:Sn,sdp:Tn};switch(n.browser){case"chrome":if(!ht||!pe||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=ht,G(r,n),Q(r),tt(r,n),nt(r),pe(r,n),rt(r,n),at(r,n),st(r),it(r,n),ct(r,n),J(r),me(r),ye(r),W(r,n),Y(r,n),be(r,n);break;case"firefox":if(!St||!ge||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=St,G(r,n),Q(r),lt(r,n),ge(r,n),ut(r,n),dt(r),gt(r),ft(r),pt(r),mt(r),yt(r,n),bt(r,n),_t(r,n),vt(r,n),J(r),ye(r),W(r,n),Y(r,n);break;case"safari":if(!At||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=At,G(r,n),Q(r),Pt(r),wt(r),xt(r),Ct(r),kt(r),Et(r),Tt(r),Mt(r),J(r),me(r),W(r,n),Y(r,n),be(r,n);break;default:t("Unsupported browser!");break}return s}const Dt=Pn({window:typeof window>"u"?void 0:window});function D(r,e,t,n){Object.defineProperty(r,e,{get:t,set:n,enumerable:!0,configurable:!0})}class Lt{constructor(){this.chunkedMTU=16300,this._dataCount=1,this.chunk=e=>{const t=[],n=e.byteLength,s=Math.ceil(n/this.chunkedMTU);let i=0,o=0;for(;o<n;){const a=Math.min(n,o+this.chunkedMTU),c=e.slice(o,a),h={__peerData:this._dataCount,n:i,data:c,total:s};t.push(h),o=a,i++}return this._dataCount++,t}}}function En(r){let e=0;for(const s of r)e+=s.byteLength;const t=new Uint8Array(e);let n=0;for(const s of r)t.set(s,n),n+=s.byteLength;return t}const _e=Dt.default||Dt,z=new class{isWebRTCSupported(){return typeof RTCPeerConnection<"u"}isBrowserSupported(){const r=this.getBrowser(),e=this.getVersion();return this.supportedBrowsers.includes(r)?r==="chrome"?e>=this.minChromeVersion:r==="firefox"?e>=this.minFirefoxVersion:r==="safari"?!this.isIOS&&e>=this.minSafariVersion:!1:!1}getBrowser(){return _e.browserDetails.browser}getVersion(){return _e.browserDetails.version||0}isUnifiedPlanSupported(){const r=this.getBrowser(),e=_e.browserDetails.version||0;if(r==="chrome"&&e<this.minChromeVersion)return!1;if(r==="firefox"&&e>=this.minFirefoxVersion)return!0;if(!window.RTCRtpTransceiver||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let t,n=!1;try{t=new RTCPeerConnection,t.addTransceiver("audio"),n=!0}catch{}finally{t&&t.close()}return n}toString(){return`Supports:
|
|
36
36
|
browser:${this.getBrowser()}
|
|
37
37
|
version:${this.getVersion()}
|
|
38
38
|
isIOS:${this.isIOS}
|
|
39
39
|
isWebRTCSupported:${this.isWebRTCSupported()}
|
|
40
40
|
isBrowserSupported:${this.isBrowserSupported()}
|
|
41
|
-
isUnifiedPlanSupported:${this.isUnifiedPlanSupported()}`}constructor(){this.isIOS=typeof navigator<"u"?["iPad","iPhone","iPod"].includes(navigator.platform):!1,this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}},wn=r=>!r||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(r),$t=()=>Math.random().toString(36).slice(2),Bt={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};class Mn extends Lt{noop(){}blobToArrayBuffer(e,t){const n=new FileReader;return n.onload=function(s){s.target&&t(s.target.result)},n.readAsArrayBuffer(e),n}binaryStringToArrayBuffer(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t.buffer}isSecure(){return location.protocol==="https:"}constructor(...e){super(...e),this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.defaultConfig=Bt,this.browser=z.getBrowser(),this.browserVersion=z.getVersion(),this.pack=We,this.unpack=Je,this.supports=function(){const t={browser:z.isBrowserSupported(),webRTC:z.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!t.webRTC)return t;let n;try{n=new RTCPeerConnection(Bt),t.audioVideo=!0;let s;try{s=n.createDataChannel("_PEERJSTEST",{ordered:!0}),t.data=!0,t.reliable=!!s.ordered;try{s.binaryType="blob",t.binaryBlob=!z.isIOS}catch{}}catch{}finally{s&&s.close()}}catch{}finally{n&&n.close()}return t}(),this.validateId=wn,this.randomToken=$t}}const k=new Mn,An="PeerJS: ";class On{get logLevel(){return this._logLevel}set logLevel(e){this._logLevel=e}log(...e){this._logLevel>=3&&this._print(3,...e)}warn(...e){this._logLevel>=2&&this._print(2,...e)}error(...e){this._logLevel>=1&&this._print(1,...e)}setLogFunction(e){this._print=e}_print(e,...t){const n=[An,...t];for(const s in n)n[s]instanceof Error&&(n[s]="("+n[s].name+") "+n[s].message);e>=3?console.log(...n):e>=2?console.warn("WARNING",...n):e>=1&&console.error("ERROR",...n)}constructor(){this._logLevel=0}}var f=new On,ve={},In=Object.prototype.hasOwnProperty,C="~";function F(){}Object.create&&(F.prototype=Object.create(null),new F().__proto__||(C=!1));function Dn(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ut(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new Dn(t,n||r,s),o=C?C+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],i]:r._events[o].push(i):(r._events[o]=i,r._eventsCount++),r}function X(r,e){--r._eventsCount===0?r._events=new F:delete r._events[e]}function v(){this._events=new F,this._eventsCount=0}v.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)In.call(t,n)&&e.push(C?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},v.prototype.listeners=function(e){var t=C?C+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o},v.prototype.listenerCount=function(e){var t=C?C+e:e,n=this._events[t];return n?n.fn?1:n.length:0},v.prototype.emit=function(e,t,n,s,i,o){var a=C?C+e:e;if(!this._events[a])return!1;var c=this._events[a],h=arguments.length,l,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),h){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,i),!0;case 6:return c.fn.call(c.context,t,n,s,i,o),!0}for(d=1,l=new Array(h-1);d<h;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var u=c.length,p;for(d=0;d<u;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),h){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,s);break;default:if(!l)for(p=1,l=new Array(h-1);p<h;p++)l[p-1]=arguments[p];c[d].fn.apply(c[d].context,l)}}return!0},v.prototype.on=function(e,t,n){return Ut(this,e,t,n,!1)},v.prototype.once=function(e,t,n){return Ut(this,e,t,n,!0)},v.prototype.removeListener=function(e,t,n,s){var i=C?C+e:e;if(!this._events[i])return this;if(!t)return X(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!s||o.once)&&(!n||o.context===n)&&X(this,i);else{for(var a=0,c=[],h=o.length;a<h;a++)(o[a].fn!==t||s&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:X(this,i)}return this},v.prototype.removeAllListeners=function(e){var t;return e?(t=C?C+e:e,this._events[t]&&X(this,t)):(this._events=new F,this._eventsCount=0),this},v.prototype.off=v.prototype.removeListener,v.prototype.addListener=v.prototype.on,v.prefixed=C,v.EventEmitter=v,ve=v;var L={};D(L,"ConnectionType",()=>M),D(L,"PeerErrorType",()=>y),D(L,"BaseConnectionErrorType",()=>Se),D(L,"DataConnectionErrorType",()=>Ce),D(L,"SerializationType",()=>Z),D(L,"SocketEventType",()=>A),D(L,"ServerMessageType",()=>S);var M=function(r){return r.Data="data",r.Media="media",r}({}),y=function(r){return r.BrowserIncompatible="browser-incompatible",r.Disconnected="disconnected",r.InvalidID="invalid-id",r.InvalidKey="invalid-key",r.Network="network",r.PeerUnavailable="peer-unavailable",r.SslUnavailable="ssl-unavailable",r.ServerError="server-error",r.SocketError="socket-error",r.SocketClosed="socket-closed",r.UnavailableID="unavailable-id",r.WebRTC="webrtc",r}({}),Se=function(r){return r.NegotiationFailed="negotiation-failed",r.ConnectionClosed="connection-closed",r}({}),Ce=function(r){return r.NotOpenYet="not-open-yet",r.MessageToBig="message-too-big",r}({}),Z=function(r){return r.Binary="binary",r.BinaryUTF8="binary-utf8",r.JSON="json",r.None="raw",r}({}),A=function(r){return r.Message="message",r.Disconnected="disconnected",r.Error="error",r.Close="close",r}({}),S=function(r){return r.Heartbeat="HEARTBEAT",r.Candidate="CANDIDATE",r.Offer="OFFER",r.Answer="ANSWER",r.Open="OPEN",r.Error="ERROR",r.IdTaken="ID-TAKEN",r.InvalidKey="INVALID-KEY",r.Leave="LEAVE",r.Expire="EXPIRE",r}({});const Nt="1.5.5";class Ln extends ve.EventEmitter{constructor(e,t,n,s,i,o=5e3){super(),this.pingInterval=o,this._disconnected=!0,this._messagesQueue=[];const a=e?"wss://":"ws://";this._baseUrl=a+t+":"+n+s+"peerjs?key="+i}start(e,t){this._id=e;const n=`${this._baseUrl}&id=${e}&token=${t}`;this._socket||!this._disconnected||(this._socket=new WebSocket(n+"&version="+Nt),this._disconnected=!1,this._socket.onmessage=s=>{let i;try{i=JSON.parse(s.data),f.log("Server message received:",i)}catch{f.log("Invalid server message",s.data);return}this.emit(A.Message,i)},this._socket.onclose=s=>{this._disconnected||(f.log("Socket closed.",s),this._cleanup(),this._disconnected=!0,this.emit(A.Disconnected))},this._socket.onopen=()=>{this._disconnected||(this._sendQueuedMessages(),f.log("Socket open"),this._scheduleHeartbeat())})}_scheduleHeartbeat(){this._wsPingTimer=setTimeout(()=>{this._sendHeartbeat()},this.pingInterval)}_sendHeartbeat(){if(!this._wsOpen()){f.log("Cannot send heartbeat, because socket closed");return}const e=JSON.stringify({type:S.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()}_wsOpen(){return!!this._socket&&this._socket.readyState===1}_sendQueuedMessages(){const e=[...this._messagesQueue];this._messagesQueue=[];for(const t of e)this.send(t)}send(e){if(this._disconnected)return;if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(A.Error,"Invalid message");return}if(!this._wsOpen())return;const t=JSON.stringify(e);this._socket.send(t)}close(){this._disconnected||(this._cleanup(),this._disconnected=!0)}_cleanup(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)}}class zt{constructor(e){this.connection=e}startConnection(e){const t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===M.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){const n=this.connection,s={ordered:!!e.reliable},i=t.createDataChannel(n.label,s);n._initializeDataChannel(i),this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){f.log("Creating RTCPeerConnection.");const e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e}_setupListeners(e){const t=this.connection.peer,n=this.connection.connectionId,s=this.connection.type,i=this.connection.provider;f.log("Listening for ICE candidates."),e.onicecandidate=o=>{!o.candidate||!o.candidate.candidate||(f.log(`Received ICE candidates for ${t}:`,o.candidate),i.socket.send({type:S.Candidate,payload:{candidate:o.candidate,type:s,connectionId:n},dst:t}))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":f.log("iceConnectionState is failed, closing connections to "+t),this.connection.emitError(Se.NegotiationFailed,"Negotiation of connection to "+t+" failed."),this.connection.close();break;case"closed":f.log("iceConnectionState is closed, closing connections to "+t),this.connection.emitError(Se.ConnectionClosed,"Connection to "+t+" closed."),this.connection.close();break;case"disconnected":f.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":e.onicecandidate=()=>{};break}this.connection.emit("iceStateChanged",e.iceConnectionState)},f.log("Listening for data channel"),e.ondatachannel=o=>{f.log("Received data channel");const a=o.channel;i.getConnection(t,n)._initializeDataChannel(a)},f.log("Listening for remote stream"),e.ontrack=o=>{f.log("Received remote stream");const a=o.streams[0],c=i.getConnection(t,n);if(c.type===M.Media){const h=c;this._addStreamToMediaConnection(a,h)}}}cleanup(){f.log("Cleaning up PeerConnection to "+this.connection.peer);const e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=()=>{};const t=e.signalingState!=="closed";let n=!1;const s=this.connection.dataChannel;s&&(n=!!s.readyState&&s.readyState!=="closed"),(t||n)&&e.close()}async _makeOffer(){const e=this.connection.peerConnection,t=this.connection.provider;try{const n=await e.createOffer(this.connection.options.constraints);f.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp);try{await e.setLocalDescription(n),f.log("Set localDescription:",n,`for:${this.connection.peer}`);let s={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type===M.Data){const i=this.connection;s={...s,label:i.label,reliable:i.reliable,serialization:i.serialization}}t.socket.send({type:S.Offer,payload:s,dst:this.connection.peer})}catch(s){s!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(y.WebRTC,s),f.log("Failed to setLocalDescription, ",s))}}catch(n){t.emitError(y.WebRTC,n),f.log("Failed to createOffer, ",n)}}async _makeAnswer(){const e=this.connection.peerConnection,t=this.connection.provider;try{const n=await e.createAnswer();f.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp);try{await e.setLocalDescription(n),f.log("Set localDescription:",n,`for:${this.connection.peer}`),t.socket.send({type:S.Answer,payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(s){t.emitError(y.WebRTC,s),f.log("Failed to setLocalDescription, ",s)}}catch(n){t.emitError(y.WebRTC,n),f.log("Failed to create answer, ",n)}}async handleSDP(e,t){t=new RTCSessionDescription(t);const n=this.connection.peerConnection,s=this.connection.provider;f.log("Setting remote description",t);const i=this;try{await n.setRemoteDescription(t),f.log(`Set remoteDescription:${e} for:${this.connection.peer}`),e==="OFFER"&&await i._makeAnswer()}catch(o){s.emitError(y.WebRTC,o),f.log("Failed to setRemoteDescription, ",o)}}async handleCandidate(e){f.log("handleCandidate:",e);try{await this.connection.peerConnection.addIceCandidate(e),f.log(`Added ICE candidate for:${this.connection.peer}`)}catch(t){this.connection.provider.emitError(y.WebRTC,t),f.log("Failed to handleCandidate, ",t)}}_addTracksToConnection(e,t){if(f.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack)return f.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(n=>{t.addTrack(n,e)})}_addStreamToMediaConnection(e,t){f.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}}class Ft extends ve.EventEmitter{emitError(e,t){f.error("Error:",t),this.emit("error",new $n(`${e}`,t))}}class $n extends Error{constructor(e,t){typeof t=="string"?super(t):(super(),Object.assign(this,t)),this.type=e}}class jt extends Ft{get open(){return this._open}constructor(e,t,n){super(),this.peer=e,this.provider=t,this.options=n,this._open=!1,this.metadata=n.metadata}}const H=class H extends jt{get type(){return M.Media}get localStream(){return this._localStream}get remoteStream(){return this._remoteStream}constructor(e,t,n){super(e,t,n),this._localStream=this.options._stream,this.connectionId=this.options.connectionId||H.ID_PREFIX+k.randomToken(),this._negotiator=new zt(this),this._localStream&&this._negotiator.startConnection({_stream:this._localStream,originator:!0})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{f.log(`DC#${this.connectionId} dc connection success`),this.emit("willCloseOnRemote")},this.dataChannel.onclose=()=>{f.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}addStream(e){f.log("Receiving stream",e),this._remoteStream=e,super.emit("stream",e)}handleMessage(e){const t=e.type,n=e.payload;switch(e.type){case S.Answer:this._negotiator.handleSDP(t,n.sdp),this._open=!0;break;case S.Candidate:this._negotiator.handleCandidate(n.candidate);break;default:f.warn(`Unrecognized message type:${t} from peer:${this.peer}`);break}}answer(e,t={}){if(this._localStream){f.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,t&&t.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection({...this.options._payload,_stream:e});const n=this.provider._getMessages(this.connectionId);for(const s of n)this.handleMessage(s);this._open=!0}close(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,super.emit("close"))}};je=new WeakMap,K(H,je,H.ID_PREFIX="mc_");let ee=H;class Bn{constructor(e){this._options=e}_buildRequest(e){const t=this._options.secure?"https":"http",{host:n,port:s,path:i,key:o}=this._options,a=new URL(`${t}://${n}:${s}${i}${o}/${e}`);return a.searchParams.set("ts",`${Date.now()}${Math.random()}`),a.searchParams.set("version",Nt),fetch(a.href,{referrerPolicy:this._options.referrerPolicy})}async retrieveId(){try{const e=await this._buildRequest("id");if(e.status!==200)throw new Error(`Error. Status:${e.status}`);return e.text()}catch(e){f.error("Error retrieving ID",e);let t="";throw this._options.path==="/"&&this._options.host!==k.CLOUD_HOST&&(t=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+t)}}async listAllPeers(){try{const e=await this._buildRequest("peers");if(e.status!==200){if(e.status===401){let t="";throw this._options.host===k.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)}throw new Error(`Error. Status:${e.status}`)}return e.json()}catch(e){throw f.error("Error retrieving list peers",e),new Error("Could not get list peers from the server."+e)}}}const $=class $ extends jt{get type(){return M.Data}constructor(e,t,n){super(e,t,n),this.connectionId=this.options.connectionId||$.ID_PREFIX+$t(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new zt(this),this._negotiator.startConnection(this.options._payload||{originator:!0,reliable:this.reliable})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{f.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this.emit("open")},this.dataChannel.onmessage=t=>{f.log(`DC#${this.connectionId} dc onmessage:`,t.data)},this.dataChannel.onclose=()=>{f.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}close(e){if(e!=null&&e.flush){this.send({__peerData:{type:"close"}});return}this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this.dataChannel=null),this.open&&(this._open=!1,super.emit("close"))}send(e,t=!1){if(!this.open){this.emitError(Ce.NotOpenYet,"Connection is not open. You should listen for the `open` event before sending messages.");return}return this._send(e,t)}async handleMessage(e){const t=e.payload;switch(e.type){case S.Answer:await this._negotiator.handleSDP(e.type,t.sdp);break;case S.Candidate:await this._negotiator.handleCandidate(t.candidate);break;default:f.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}};qe=new WeakMap,He=new WeakMap,K($,qe,$.ID_PREFIX="dc_"),K($,He,$.MAX_BUFFERED_AMOUNT=8388608);let te=$;class ke extends te{get bufferSize(){return this._bufferSize}_initializeDataChannel(e){super._initializeDataChannel(e),this.dataChannel.binaryType="arraybuffer",this.dataChannel.addEventListener("message",t=>this._handleDataMessage(t))}_bufferedSend(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)}_trySend(e){if(!this.open)return!1;if(this.dataChannel.bufferedAmount>te.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(()=>{this._buffering=!1,this._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(t){return f.error(`DC#:${this.connectionId} Error when sending:`,t),this._buffering=!0,this.close(),!1}return!0}_tryBuffer(){if(!this.open||this._buffer.length===0)return;const e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}close(e){if(e!=null&&e.flush){this.send({__peerData:{type:"close"}});return}this._buffer=[],this._bufferSize=0,super.close()}constructor(...e){super(...e),this._buffer=[],this._bufferSize=0,this._buffering=!1}}class xe extends ke{close(e){super.close(e),this._chunkedData={}}constructor(e,t,n){super(e,t,n),this.chunker=new Lt,this.serialization=Z.Binary,this._chunkedData={}}_handleDataMessage({data:e}){const t=Je(e),n=t.__peerData;if(n){if(n.type==="close"){this.close();return}this._handleChunk(t);return}this.emit("data",t)}_handleChunk(e){const t=e.__peerData,n=this._chunkedData[t]||{data:[],count:0,total:e.total};if(n.data[e.n]=new Uint8Array(e.data),n.count++,this._chunkedData[t]=n,n.total===n.count){delete this._chunkedData[t];const s=Pn(n.data);this._handleDataMessage({data:s})}}_send(e,t){const n=We(e);if(n instanceof Promise)return this._send_blob(n);if(!t&&n.byteLength>this.chunker.chunkedMTU){this._sendChunks(n);return}this._bufferedSend(n)}async _send_blob(e){const t=await e;if(t.byteLength>this.chunker.chunkedMTU){this._sendChunks(t);return}this._bufferedSend(t)}_sendChunks(e){const t=this.chunker.chunk(e);f.log(`DC#${this.connectionId} Try to send ${t.length} chunks...`);for(const n of t)this.send(n,!0)}}class Un extends ke{_handleDataMessage({data:e}){super.emit("data",e)}_send(e,t){this._bufferedSend(e)}constructor(...e){super(...e),this.serialization=Z.None}}class Nn extends ke{_handleDataMessage({data:e}){const t=this.parse(this.decoder.decode(e)),n=t.__peerData;if(n&&n.type==="close"){this.close();return}this.emit("data",t)}_send(e,t){const n=this.encoder.encode(this.stringify(e));if(n.byteLength>=k.chunkedMTU){this.emitError(Ce.MessageToBig,"Message too big for JSON channel");return}this._bufferedSend(n)}constructor(...e){super(...e),this.serialization=Z.JSON,this.encoder=new TextEncoder,this.decoder=new TextDecoder,this.stringify=JSON.stringify,this.parse=JSON.parse}}const V=class V extends Ft{get id(){return this._id}get options(){return this._options}get open(){return this._open}get socket(){return this._socket}get connections(){const e=Object.create(null);for(const[t,n]of this._connections)e[t]=n;return e}get destroyed(){return this._destroyed}get disconnected(){return this._disconnected}constructor(e,t){super(),this._serializers={raw:Un,json:Nn,binary:xe,"binary-utf8":xe,default:xe},this._id=null,this._lastServerId=null,this._destroyed=!1,this._disconnected=!1,this._open=!1,this._connections=new Map,this._lostMessages=new Map;let n;if(e&&e.constructor==Object?t=e:e&&(n=e.toString()),t={debug:0,host:k.CLOUD_HOST,port:k.CLOUD_PORT,path:"/",key:V.DEFAULT_KEY,token:k.randomToken(),config:k.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin",serializers:{},...t},this._options=t,this._serializers={...this._serializers,...this.options.serializers},this._options.host==="/"&&(this._options.host=window.location.hostname),this._options.path&&(this._options.path[0]!=="/"&&(this._options.path="/"+this._options.path),this._options.path[this._options.path.length-1]!=="/"&&(this._options.path+="/")),this._options.secure===void 0&&this._options.host!==k.CLOUD_HOST?this._options.secure=k.isSecure():this._options.host==k.CLOUD_HOST&&(this._options.secure=!0),this._options.logFunction&&f.setLogFunction(this._options.logFunction),f.logLevel=this._options.debug||0,this._api=new Bn(t),this._socket=this._createServerConnection(),!k.supports.audioVideo&&!k.supports.data){this._delayedAbort(y.BrowserIncompatible,"The current browser does not support WebRTC");return}if(n&&!k.validateId(n)){this._delayedAbort(y.InvalidID,`ID "${n}" is invalid`);return}n?this._initialize(n):this._api.retrieveId().then(s=>this._initialize(s)).catch(s=>this._abort(y.ServerError,s))}_createServerConnection(){const e=new Ln(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return e.on(A.Message,t=>{this._handleMessage(t)}),e.on(A.Error,t=>{this._abort(y.SocketError,t)}),e.on(A.Disconnected,()=>{this.disconnected||(this.emitError(y.Network,"Lost connection to server."),this.disconnect())}),e.on(A.Close,()=>{this.disconnected||this._abort(y.SocketClosed,"Underlying socket is already closed.")}),e}_initialize(e){this._id=e,this.socket.start(e,this._options.token)}_handleMessage(e){const t=e.type,n=e.payload,s=e.src;switch(t){case S.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case S.Error:this._abort(y.ServerError,n.msg);break;case S.IdTaken:this._abort(y.UnavailableID,`ID "${this.id}" is taken`);break;case S.InvalidKey:this._abort(y.InvalidKey,`API KEY "${this._options.key}" is invalid`);break;case S.Leave:f.log(`Received leave message from ${s}`),this._cleanupPeer(s),this._connections.delete(s);break;case S.Expire:this.emitError(y.PeerUnavailable,`Could not connect to peer ${s}`);break;case S.Offer:{const i=n.connectionId;let o=this.getConnection(s,i);if(o&&(o.close(),f.warn(`Offer received for existing Connection ID:${i}`)),n.type===M.Media){const c=new ee(s,this,{connectionId:i,_payload:n,metadata:n.metadata});o=c,this._addConnection(s,o),this.emit("call",c)}else if(n.type===M.Data){const c=new this._serializers[n.serialization](s,this,{connectionId:i,_payload:n,metadata:n.metadata,label:n.label,serialization:n.serialization,reliable:n.reliable});o=c,this._addConnection(s,o),this.emit("connection",c)}else{f.warn(`Received malformed connection type:${n.type}`);return}const a=this._getMessages(i);for(const c of a)o.handleMessage(c);break}default:{if(!n){f.warn(`You received a malformed message from ${s} of type ${t}`);return}const i=n.connectionId,o=this.getConnection(s,i);o&&o.peerConnection?o.handleMessage(e):i?this._storeMessage(i,e):f.warn("You received an unrecognized message:",e);break}}}_storeMessage(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(t)}_getMessages(e){const t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),t):[]}connect(e,t={}){if(t={serialization:"default",...t},this.disconnected){f.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(y.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}const n=new this._serializers[t.serialization](e,this,t);return this._addConnection(e,n),n}call(e,t,n={}){if(this.disconnected){f.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(y.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!t){f.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}const s=new ee(e,this,{...n,_stream:t});return this._addConnection(e,s),s}_addConnection(e,t){f.log(`add connection ${t.type}:${t.connectionId} to peerId:${e}`),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(t)}_removeConnection(e){const t=this._connections.get(e.peer);if(t){const n=t.indexOf(e);n!==-1&&t.splice(n,1)}this._lostMessages.delete(e.connectionId)}getConnection(e,t){const n=this._connections.get(e);if(!n)return null;for(const s of n)if(s.connectionId===t)return s;return null}_delayedAbort(e,t){setTimeout(()=>{this._abort(e,t)},0)}_abort(e,t){f.error("Aborting!"),this.emitError(e,t),this._lastServerId?this.disconnect():this.destroy()}destroy(){this.destroyed||(f.log(`Destroy peer with ID:${this.id}`),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))}_cleanup(){for(const e of this._connections.keys())this._cleanupPeer(e),this._connections.delete(e);this.socket.removeAllListeners()}_cleanupPeer(e){const t=this._connections.get(e);if(t)for(const n of t)n.close()}disconnect(){if(this.disconnected)return;const e=this.id;f.log(`Disconnect peer with ID:${e}`),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}reconnect(){if(this.disconnected&&!this.destroyed)f.log(`Attempting reconnection to server with ID ${this._lastServerId}`),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)f.error("In a hurry? We're still trying to make the initial connection!");else throw new Error(`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`)}}listAllPeers(e=t=>{}){this._api.listAllPeers().then(t=>e(t)).catch(t=>this._abort(y.ServerError,t))}};Ve=new WeakMap,K(V,Ve,V.DEFAULT_KEY="peerjs");let Te=V;var zn=Te;class Fn{constructor(e){this.config=e,this.peer=null,this.localStream=null,this.connections={},this.callbacks={onStream:null,onPeerLeft:null,onError:null}}buildIceServers(){const e=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],t=Array.isArray(this.config.iceServers)?this.config.iceServers:[];return[...e,...t]}async initialize(e,t=0){return new Promise((n,s)=>{const i=t===0?e:`${e}-r${Math.random().toString(36).slice(2,6)}`;this.peer=new zn(i,{host:this.config.peerServer.host,port:this.config.peerServer.port,path:this.config.peerServer.path||"/peerjs",secure:this.config.peerServer.secure??!1,config:{iceServers:this.buildIceServers()}});let o=!1;this.peer.on("open",a=>{o=!0,console.log("Peer initialized:",a),this.actualPeerId=a,n(a)}),this.peer.on("error",async a=>{if(!o&&a&&a.type==="unavailable-id"&&t<1){console.warn(`Peer id "${i}" taken — retrying with a suffix`);try{this.peer.destroy()}catch{}this.peer=null;try{const c=await this.initialize(e,t+1);o=!0,n(c)}catch(c){s(c)}return}console.error("Peer error:",a),this.callbacks.onError&&this.callbacks.onError(a),o||s(a)}),this.peer.on("call",a=>{this.handleIncomingCall(a)})})}async getLocalStream(){if(this.localStream)return this.localStream;try{return this.localStream=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0}),this.localStream}catch(e){throw console.error("Failed to get local stream:",e),this.callbacks.onError&&this.callbacks.onError(e),e}}async handleIncomingCall(e){if(this.connections[e.peer]){console.log("Duplicate incoming call from",e.peer,"— closing");try{e.close()}catch{}return}this.connections[e.peer]={call:e,stream:null};const t=await this.getLocalStream();e.answer(t),e.on("stream",n=>{console.log("Received stream from:",e.peer),this.connections[e.peer]={call:e,stream:n},this.callbacks.onStream&&this.callbacks.onStream(e.peer,n,!1)}),e.on("close",()=>{console.log("Call closed:",e.peer),delete this.connections[e.peer],this.callbacks.onPeerLeft&&this.callbacks.onPeerLeft(e.peer)})}async callPeer(e){if(this.connections[e]){console.log("Already connected to:",e);return}if(this.peer&&this.peer.id&&this.peer.id>e){console.log(`Waiting for ${e} to call us (our id ${this.peer.id} > theirs)`);return}this.connections[e]={call:null,stream:null};const t=await this.getLocalStream();if(this.connections[e]&&this.connections[e].call)return;const n=this.peer.call(e,t);this.connections[e]={call:n,stream:null},n.on("stream",s=>{console.log("Received stream from:",e),this.connections[e]={call:n,stream:s},this.callbacks.onStream&&this.callbacks.onStream(e,s,!1)}),n.on("close",()=>{console.log("Call closed:",e),delete this.connections[e],this.callbacks.onPeerLeft&&this.callbacks.onPeerLeft(e)}),n.on("error",s=>{console.error("Call error:",s),delete this.connections[e]})}toggleVideo(){if(this.localStream){const e=this.localStream.getVideoTracks()[0];if(e)return e.enabled=!e.enabled,e.enabled}return!1}toggleAudio(){if(this.localStream){const e=this.localStream.getAudioTracks()[0];if(e)return e.enabled=!e.enabled,e.enabled}return!1}replaceVideoTrackOnAllConnections(e){for(const{call:t}of Object.values(this.connections)){const n=t&&t.peerConnection;if(!n)continue;const s=n.getSenders().find(i=>i.track&&i.track.kind==="video");s&&s.replaceTrack(e).catch(i=>console.warn("replaceTrack failed:",i&&i.message))}}async startScreenShare(){if(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)throw new Error("Screen sharing is not supported in this browser");const t=(await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1})).getVideoTracks()[0];if(!t)throw new Error("Could not obtain display video track");return this.cameraVideoTrack=this.localStream.getVideoTracks()[0]||null,this.replaceVideoTrackOnAllConnections(t),this.cameraVideoTrack&&this.localStream.removeTrack(this.cameraVideoTrack),this.localStream.addTrack(t),this.screenTrack=t,t.addEventListener("ended",()=>this.stopScreenShare().catch(()=>{})),t}async stopScreenShare(){if(!this.screenTrack)return!1;try{this.screenTrack.stop()}catch{}let e=this.cameraVideoTrack;if(!e||e.readyState==="ended")try{e=(await navigator.mediaDevices.getUserMedia({video:!0,audio:!1})).getVideoTracks()[0]}catch(t){console.warn("Could not restore camera after screen share:",t&&t.message),e=null}if(e){this.replaceVideoTrackOnAllConnections(e);try{this.localStream.removeTrack(this.screenTrack)}catch{}this.localStream.addTrack(e),this.cameraVideoTrack=e}return this.screenTrack=null,!0}isScreenSharing(){return!!this.screenTrack}on(e,t){this.callbacks.hasOwnProperty("on"+e.charAt(0).toUpperCase()+e.slice(1))&&(this.callbacks["on"+e.charAt(0).toUpperCase()+e.slice(1)]=t)}disconnect(){Object.values(this.connections).forEach(({call:e})=>{e.close()}),this.connections={},this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null),this.peer&&(this.peer.destroy(),this.peer=null)}}const P=Object.create(null);P.open="0",P.close="1",P.ping="2",P.pong="3",P.message="4",P.upgrade="5",P.noop="6";const ne=Object.create(null);Object.keys(P).forEach(r=>{ne[P[r]]=r});const Re={type:"error",data:"parser error"},qt=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Ht=typeof ArrayBuffer=="function",Vt=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,Ee=({type:r,data:e},t,n)=>qt&&e instanceof Blob?t?n(e):Kt(e,n):Ht&&(e instanceof ArrayBuffer||Vt(e))?t?n(e):Kt(new Blob([e]),n):n(P[r]+(e||"")),Kt=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function Jt(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Pe;function jn(r,e){if(qt&&r.data instanceof Blob)return r.data.arrayBuffer().then(Jt).then(e);if(Ht&&(r.data instanceof ArrayBuffer||Vt(r.data)))return e(Jt(r.data));Ee(r,!1,t=>{Pe||(Pe=new TextEncoder),e(Pe.encode(t))})}const Wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",j=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Wt.length;r++)j[Wt.charCodeAt(r)]=r;const qn=r=>{let e=r.length*.75,t=r.length,n,s=0,i,o,a,c;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const h=new ArrayBuffer(e),l=new Uint8Array(h);for(n=0;n<t;n+=4)i=j[r.charCodeAt(n)],o=j[r.charCodeAt(n+1)],a=j[r.charCodeAt(n+2)],c=j[r.charCodeAt(n+3)],l[s++]=i<<2|o>>4,l[s++]=(o&15)<<4|a>>2,l[s++]=(a&3)<<6|c&63;return h},Hn=typeof ArrayBuffer=="function",we=(r,e)=>{if(typeof r!="string")return{type:"message",data:Yt(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:Vn(r.substring(1),e)}:ne[t]?r.length>1?{type:ne[t],data:r.substring(1)}:{type:ne[t]}:Re},Vn=(r,e)=>{if(Hn){const t=qn(r);return Yt(t,e)}else return{base64:!0,data:r}},Yt=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}},Gt="",Kn=(r,e)=>{const t=r.length,n=new Array(t);let s=0;r.forEach((i,o)=>{Ee(i,!1,a=>{n[o]=a,++s===t&&e(n.join(Gt))})})},Jn=(r,e)=>{const t=r.split(Gt),n=[];for(let s=0;s<t.length;s++){const i=we(t[s],e);if(n.push(i),i.type==="error")break}return n};function Wn(){return new TransformStream({transform(r,e){jn(r,t=>{const n=t.length;let s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);const i=new DataView(s.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{s=new Uint8Array(9);const i=new DataView(s.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}let Me;function re(r){return r.reduce((e,t)=>e+t.length,0)}function se(r,e){if(r[0].length===e)return r.shift();const t=new Uint8Array(e);let n=0;for(let s=0;s<e;s++)t[s]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function Yn(r,e){Me||(Me=new TextDecoder);const t=[];let n=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(n===0){if(re(t)<1)break;const c=se(t,1);i=(c[0]&128)===128,s=c[0]&127,s<126?n=3:s===126?n=1:n=2}else if(n===1){if(re(t)<2)break;const c=se(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),n=3}else if(n===2){if(re(t)<8)break;const c=se(t,8),h=new DataView(c.buffer,c.byteOffset,c.length),l=h.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(Re);break}s=l*Math.pow(2,32)+h.getUint32(4),n=3}else{if(re(t)<s)break;const c=se(t,s);a.enqueue(we(i?c:Me.decode(c),e)),n=0}if(s===0||s>r){a.enqueue(Re);break}}}})}const Qt=4;function b(r){if(r)return Gn(r)}function Gn(r){for(var e in b.prototype)r[e]=b.prototype[e];return r}b.prototype.on=b.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this},b.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this},b.prototype.off=b.prototype.removeListener=b.prototype.removeAllListeners=b.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,s=0;s<t.length;s++)if(n=t[s],n===e||n.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+r],this},b.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,s=t.length;n<s;++n)t[n].apply(this,e)}return this},b.prototype.emitReserved=b.prototype.emit,b.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]},b.prototype.hasListeners=function(r){return!!this.listeners(r).length};const ie=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),T=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Qn="arraybuffer";function ts(){}function Xt(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const Xn=T.setTimeout,Zn=T.clearTimeout;function oe(r,e){e.useNativeTimers?(r.setTimeoutFn=Xn.bind(T),r.clearTimeoutFn=Zn.bind(T)):(r.setTimeoutFn=T.setTimeout.bind(T),r.clearTimeoutFn=T.clearTimeout.bind(T))}const er=1.33;function tr(r){return typeof r=="string"?nr(r):Math.ceil((r.byteLength||r.size)*er)}function nr(r){let e=0,t=0;for(let n=0,s=r.length;n<s;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function Zt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function rr(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function sr(r){let e={},t=r.split("&");for(let n=0,s=t.length;n<s;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class ir extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Ae extends b{constructor(e){super(),this.writable=!1,oe(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new ir(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=we(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=rr(e);return t.length?"?"+t:""}}class or extends Ae{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Jn(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Kn(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=Zt()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let en=!1;try{en=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const ar=en;function cr(){}class hr extends or{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class w extends b{constructor(e,t,n){super(),this.createRequest=e,oe(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=Xt(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&n.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var s;n.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=w.requestsCount++,w.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=cr,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete w.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(w.requestsCount=0,w.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",tn);else if(typeof addEventListener=="function"){const r="onpagehide"in T?"pagehide":"unload";addEventListener(r,tn,!1)}}function tn(){for(let r in w.requests)w.requests.hasOwnProperty(r)&&w.requests[r].abort()}const lr=function(){const r=nn({xdomain:!1});return r&&r.responseType!==null}();class dr extends hr{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=lr&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new w(nn,this.uri(),e)}}function nn(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||ar))return new XMLHttpRequest}catch{}if(!e)try{return new T[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const rn=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ur extends Ae{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=rn?{}:Xt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],s=t===e.length-1;Ee(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}s&&ie(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Zt()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Oe=T.WebSocket||T.MozWebSocket;class fr extends ur{createSocket(e,t,n){return rn?new Oe(e,t,n):t?new Oe(e,t):new Oe(e)}doWrite(e,t){this.ws.send(t)}}class pr extends Ae{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=Yn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),s=Wn();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();const i=()=>{n.read().then(({done:a,value:c})=>{a||(this.onPacket(c),i())}).catch(a=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&ie(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const gr={websocket:fr,webtransport:pr,polling:dr},mr=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,yr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ie(r){if(r.length>8e3)throw"URI too long";const e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let s=mr.exec(r||""),i={},o=14;for(;o--;)i[yr[o]]=s[o]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=br(i,i.path),i.queryKey=_r(i,i.query),i}function br(r,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function _r(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,s,i){s&&(t[s]=i)}),t}const De=typeof addEventListener=="function"&&typeof removeEventListener=="function",ae=[];De&&addEventListener("offline",()=>{ae.forEach(r=>r())},!1);class O extends b{constructor(e,t){if(super(),this.binaryType=Qn,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=Ie(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Ie(t.host).host);oe(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const s=n.prototype.name;this.transports.push(s),this._transportsByName[s]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=sr(this.opts.query)),De&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ae.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=Qt,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&O.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",O.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const s=this.writeBuffer[n].data;if(s&&(t+=tr(s)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,ie(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if(typeof t=="function"&&(s=t,t=void 0),typeof n=="function"&&(s=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(O.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),De&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=ae.indexOf(this._offlineEventListener);n!==-1&&ae.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}O.protocol=Qt;class vr extends O{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;O.priorWebsocketSuccess=!1;const s=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",d=>{if(!n)if(d.type==="pong"&&d.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;O.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const u=new Error("probe error");u.transport=t.name,this.emitReserved("upgradeError",u)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}const o=d=>{const u=new Error("probe error: "+d);u.transport=t.name,i(),this.emitReserved("upgradeError",u)};function a(){o("transport closed")}function c(){o("socket closed")}function h(d){t&&d.name!==t.name&&i()}const l=()=>{t.removeListener("open",s),t.removeListener("error",o),t.removeListener("close",a),this.off("close",c),this.off("upgrading",h)};t.once("open",s),t.once("error",o),t.once("close",a),this.once("close",c),this.once("upgrading",h),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let Sr=class extends vr{constructor(e,t={}){const n=typeof e=="object",s=n?{...e}:{...t};(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>gr[i]).filter(i=>!!i)),super(n?s:e,s)}};function Cr(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),n=Ie(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}const kr=typeof ArrayBuffer=="function",xr=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,sn=Object.prototype.toString,Tr=typeof Blob=="function"||typeof Blob<"u"&&sn.call(Blob)==="[object BlobConstructor]",Rr=typeof File=="function"||typeof File<"u"&&sn.call(File)==="[object FileConstructor]";function Le(r){return kr&&(r instanceof ArrayBuffer||xr(r))||Tr&&r instanceof Blob||Rr&&r instanceof File}function ce(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(ce(r[t]))return!0;return!1}if(Le(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return ce(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&ce(r[t]))return!0;return!1}function Er(r){const e=[],t=r.data,n=r;return n.data=$e(t,e),n.attachments=e.length,{packet:n,buffers:e}}function $e(r,e){if(!r)return r;if(Le(r)){const t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=$e(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){const t={};for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=$e(r[n],e));return t}return r}function Pr(r,e){return r.data=Be(r.data,e),delete r.attachments,r}function Be(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=Be(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Be(r[t],e));return r}const wr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var g;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(g||(g={}));class Mr{constructor(e){this.replacer=e}encode(e){return(e.type===g.EVENT||e.type===g.ACK)&&ce(e)?this.encodeAsBinary({type:e.type===g.EVENT?g.BINARY_EVENT:g.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===g.BINARY_EVENT||e.type===g.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Er(e),n=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(n),s}}class Ue extends b{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===g.BINARY_EVENT;n||t.type===g.BINARY_ACK?(t.type=n?g.EVENT:g.ACK,this.reconstructor=new Ar(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Le(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(g[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===g.BINARY_EVENT||n.type===g.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Or(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";const s=e.charAt(t+1);if(s!==""&&Number(s)==s){const i=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(Ue.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case g.CONNECT:return on(t);case g.DISCONNECT:return t===void 0;case g.CONNECT_ERROR:return typeof t=="string"||on(t);case g.EVENT:case g.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&wr.indexOf(t[0])===-1);case g.ACK:case g.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ar{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=Pr(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Or=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function on(r){return Object.prototype.toString.call(r)==="[object Object]"}const Ir=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ue,Encoder:Mr,get PacketType(){return g}},Symbol.toStringTag,{value:"Module"}));function R(r,e,t){return r.on(e,t),function(){r.off(e,t)}}const Dr=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class an extends b{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[R(e,"open",this.onopen.bind(this)),R(e,"packet",this.onpacket.bind(this)),R(e,"error",this.onerror.bind(this)),R(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,i;if(Dr.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:g.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const l=this.ids++,d=t.pop();this._registerAckCallback(l,d),o.id=l}const a=(s=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||s===void 0?void 0:s.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a||(c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var n;const s=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);t.call(this,new Error("operation has timed out"))},s),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((n,s)=>{const i=(o,a)=>o?s(o):n(a);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>(this._queue[0],s!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(s)):(this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:g.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case g.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case g.EVENT:case g.BINARY_EVENT:this.onevent(e);break;case g.ACK:case g.BINARY_ACK:this.onack(e);break;case g.DISCONNECT:this.ondisconnect();break;case g.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...s){n||(n=!0,t.packet({type:g.ACK,id:e,data:s}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:g.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function U(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}U.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0},U.prototype.reset=function(){this.attempts=0},U.prototype.setMin=function(r){this.ms=r},U.prototype.setMax=function(r){this.max=r},U.prototype.setJitter=function(r){this.jitter=r};class Ne extends b{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,oe(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new U({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const s=t.parser||Ir;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Sr(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const s=R(t,"open",function(){n.onopen(),e&&e()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=R(t,"error",i);if(this._timeout!==!1){const a=this._timeout,c=this.setTimeoutFn(()=>{s(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(s),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(R(e,"ping",this.onping.bind(this)),R(e,"data",this.ondata.bind(this)),R(e,"error",this.onerror.bind(this)),R(e,"close",this.onclose.bind(this)),R(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){ie(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new an(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const q={};function he(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};const t=Cr(r,e.path||"/socket.io"),n=t.source,s=t.id,i=t.path,o=q[s]&&i in q[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let c;return a?c=new Ne(n,e):(q[s]||(q[s]=new Ne(n,e)),c=q[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}Object.assign(he,{Manager:Ne,Socket:an,io:he,connect:he});class Lr{constructor(e){this.config=e,this.socket=null,this.callbacks={onMessage:null,onExistingPeers:null,onYouJoined:null,onUserJoined:null,onUserLeft:null,onPeerMediaStateChange:null,onError:null},this.rawListeners=new Map}connect(e){let t=this.config.socketUrl,n="/socket.io/";try{const i=new URL(this.config.socketUrl);t=`${i.protocol}//${i.host}`;const o=i.pathname.replace(/\/+$/,"");o&&(n=`${o}/socket.io/`)}catch{}this.socket=he(t,{path:n,auth:{workspace:e},transports:["websocket","polling"]}),this.socket.on("connect",()=>{console.log("Socket connected")}),this.socket.on("disconnect",()=>{console.log("Socket disconnected")}),this.socket.on("new-message",i=>{this.callbacks.onMessage&&this.callbacks.onMessage(i)}),this.socket.on("existing-peers",i=>{this.callbacks.onExistingPeers&&this.callbacks.onExistingPeers(i)}),this.socket.on("you-joined",i=>{this.callbacks.onYouJoined&&this.callbacks.onYouJoined(i)}),this.socket.on("user-joined",i=>{this.callbacks.onUserJoined&&this.callbacks.onUserJoined(i)}),this.socket.on("user-left",i=>{this.callbacks.onUserLeft&&this.callbacks.onUserLeft(i)}),this.socket.on("peer-media-state-change",i=>{this.callbacks.onPeerMediaStateChange&&this.callbacks.onPeerMediaStateChange(i)});const s=["code-changed","code-language-changed","code-executing","code-execution-result","code-state-sync","code-permission-changed","code-sandbox-toggled","whiteboard-drawing","whiteboard-cleared","whiteboard-image-uploaded","whiteboard-state-sync","whiteboard-permission-changed","whiteboard-toggled"];for(const i of s)this.socket.on(i,o=>{const a=this.rawListeners&&this.rawListeners.get(i);a&&a.forEach(c=>{try{c(o)}catch(h){console.warn(h)}})});this.socket.on("error",i=>{console.error("Socket error:",i),this.callbacks.onError&&this.callbacks.onError(i)})}joinRoom(e,t,n,s){this.socket&&this.socket.emit("join-room",{roomId:e,userId:t,userName:n,peerId:s})}emitMediaState(e,t,n,s){this.socket&&this.socket.emit("media-state-change",{roomId:e,userId:t,type:n,enabled:s})}emit(e,t){this.socket&&this.socket.emit(e,t)}onRaw(e,t){return this.rawListeners.has(e)||this.rawListeners.set(e,new Set),this.rawListeners.get(e).add(t),()=>{var n;return(n=this.rawListeners.get(e))==null?void 0:n.delete(t)}}sendMessage(e,t,n,s,i){if(this.socket){const o={roomId:e,userId:t,userName:n,message:s||""};Array.isArray(i)&&i.length&&(o.attachmentIds=i),this.socket.emit("send-message",o)}}leaveRoom(){this.socket&&this.socket.emit("leave-room")}on(e,t){this.callbacks.hasOwnProperty("on"+e.charAt(0).toUpperCase()+e.slice(1))&&(this.callbacks["on"+e.charAt(0).toUpperCase()+e.slice(1)]=t)}disconnect(){this.socket&&(this.socket.close(),this.socket=null)}}class $r{constructor(){this.localStream=null,this.remoteStreams={}}async getLocalStream(){if(this.localStream)return this.localStream;try{return this.localStream=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0}),this.localStream}catch(e){throw console.error("Failed to get media devices:",e),e}}addRemoteStream(e,t){this.remoteStreams[e]=t}removeRemoteStream(e){delete this.remoteStreams[e]}toggleVideo(){if(this.localStream){const e=this.localStream.getVideoTracks()[0];if(e)return e.enabled=!e.enabled,e.enabled}return!1}toggleAudio(){if(this.localStream){const e=this.localStream.getAudioTracks()[0];if(e)return e.enabled=!e.enabled,e.enabled}return!1}stopLocalStream(){this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null)}cleanup(){this.stopLocalStream(),this.remoteStreams={}}}class ze{constructor(){this.recorder=null,this.stream=null,this.state="idle",this.startedAt=null,this.seq=0,this.pendingUploads=[],this.callbacks={onStateChange:null,onChunk:null}}static isSupported(){return typeof window<"u"&&typeof window.MediaRecorder<"u"}pickMimeType(){const e=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","video/mp4"];for(const t of e)if(window.MediaRecorder.isTypeSupported(t))return t;return""}setState(e){this.state=e,this.callbacks.onStateChange&&this.callbacks.onStateChange(e)}on(e,t){e==="stateChange"?this.callbacks.onStateChange=t:e==="chunk"&&(this.callbacks.onChunk=t)}start(e,t={}){if(!ze.isSupported())throw new Error("MediaRecorder API not supported in this browser");if(this.state==="recording")return;if(!e)throw new Error("stream is required to start recording");const n=t.timesliceMs||15e3;t.onChunk&&(this.callbacks.onChunk=t.onChunk),this.stream=e,this.seq=typeof t.startSeq=="number"?t.startSeq:0,this.pendingUploads=[];const s=this.pickMimeType();this.recorder=new window.MediaRecorder(e,s?{mimeType:s}:void 0),this.mimeType=this.recorder.mimeType||s||"video/webm",this.recorder.ondataavailable=i=>{if(!i.data||i.data.size===0)return;const o=this.seq++,a=i.data,c=this.callbacks.onChunk;if(!c)return;const h=Promise.resolve().then(()=>c(a,o)).catch(l=>{console.warn(`Recording chunk seq=${o} upload failed:`,l&&l.message)});this.pendingUploads.push(h)},this.recorder.onerror=i=>{console.error("MediaRecorder error:",i)},this.startedAt=new Date,this.recorder.start(n),this.setState("recording")}async stop(){if(this.state!=="recording"||!this.recorder)return null;await new Promise(i=>{this.recorder.onstop=i,this.recorder.stop()});const t=(await Promise.allSettled(this.pendingUploads)).filter(i=>i.status==="rejected").length,n=new Date,s={startedAt:this.startedAt,endedAt:n,mimeType:this.mimeType,totalChunks:this.seq,droppedChunks:t};return this.recorder=null,this.stream=null,this.startedAt=null,this.pendingUploads=[],this.setState("stopped"),s}isRecording(){return this.state==="recording"||this.state==="paused"}isPaused(){return this.state==="paused"}pause(){if(!this.recorder||this.state!=="recording")return!1;try{return this.recorder.pause(),this.setState("paused"),!0}catch{return!1}}resume(){if(!this.recorder||this.state!=="paused")return!1;try{return this.recorder.resume(),this.setState("recording"),!0}catch{return!1}}}class Fe{constructor(e={}){this.width=e.width||1280,this.height=e.height||720,this.fps=e.fps||30,this.canvas=null,this.ctx=null,this.videos=new Map,this.audioContext=null,this.audioDestination=null,this.audioSources=new Map,this.combinedStream=null,this.animationHandle=null,this.running=!1}static isSupported(){return typeof window<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.captureStream=="function"&&typeof(window.AudioContext||window.webkitAudioContext)<"u"}async start(){if(this.running)return this.combinedStream;if(!Fe.isSupported())throw new Error("Composite recording requires canvas.captureStream + AudioContext");this.canvas=document.createElement("canvas"),this.canvas.width=this.width,this.canvas.height=this.height,this.canvas.style.cssText="position:absolute;left:-9999px;top:-9999px;",document.body.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.audioContext.state==="suspended")try{await this.audioContext.resume()}catch{}this.audioDestination=this.audioContext.createMediaStreamDestination();const t=this.canvas.captureStream(this.fps);this.combinedStream=new MediaStream;for(const n of t.getVideoTracks())this.combinedStream.addTrack(n);for(const n of this.audioDestination.stream.getAudioTracks())this.combinedStream.addTrack(n);return this.running=!0,this.tick(),this.combinedStream}tick(){this.running&&(this.draw(),this.animationHandle=requestAnimationFrame(()=>this.tick()))}draw(){if(!this.ctx)return;this.ctx.fillStyle="#0d0d0d",this.ctx.fillRect(0,0,this.width,this.height);const e=Array.from(this.videos.values());if(e.length===0)return;const{cols:t,rows:n}=zr(e.length),s=this.width/t,i=this.height/n;e.forEach((o,a)=>{const c=a%t,h=Math.floor(a/t),l=c*s,d=h*i;this.ctx.fillStyle="#1a1a1a",this.ctx.fillRect(l,d,s,i);const u=o.videoEl.videoWidth||0,p=o.videoEl.videoHeight||0,m=o.videoTrack,_=m&&m.enabled&&m.readyState==="live";if(u>0&&p>0&&_!==!1){const pn=Math.min(s/u,i/p),gn=u*pn,mn=p*pn,Xr=l+(s-gn)/2,Zr=d+(i-mn)/2;try{this.ctx.drawImage(o.videoEl,Xr,Zr,gn,mn)}catch{}}else Nr(this.ctx,o.label||"Peer",l,d,s,i);const ln=o.label||"Peer";this.ctx.font="bold 16px system-ui, sans-serif";const Yr=this.ctx.measureText(ln),dn=10,Gr=6,Qr=Yr.width+dn*2,Ke=24,un=l+12,fn=d+i-Ke-12;this.ctx.fillStyle="rgba(0,0,0,0.65)",this.ctx.fillRect(un,fn,Qr,Ke),this.ctx.fillStyle="#fff",this.ctx.fillText(ln,un+dn,fn+Ke-Gr-2)})}addStream(e,t,n={}){if(!this.running)return;this.videos.has(e)&&this.removeStream(e);const s=document.createElement("video");s.srcObject=t,s.autoplay=!0,s.muted=!0,s.playsInline=!0,s.style.cssText="position:absolute;left:-9999px;top:-9999px;",document.body.appendChild(s),s.play().catch(()=>{});const i=t.getVideoTracks()[0]||null;this.videos.set(e,{videoEl:s,videoTrack:i,label:n.label||(n.isLocal?"You":e)});const o=t.getAudioTracks();if(o.length&&this.audioContext)try{const a=new MediaStream([o[0]]),c=this.audioContext.createMediaStreamSource(a),h=this.audioContext.createGain();h.gain.value=1,c.connect(h).connect(this.audioDestination),this.audioSources.set(e,{source:c,gain:h})}catch(a){console.warn("Compositor audio source failed for",e,a&&a.message)}}removeStream(e){const t=this.videos.get(e);t&&(t.videoEl.pause(),t.videoEl.srcObject=null,t.videoEl.remove(),this.videos.delete(e));const n=this.audioSources.get(e);if(n){try{n.source.disconnect()}catch{}try{n.gain.disconnect()}catch{}this.audioSources.delete(e)}}getStream(){return this.combinedStream}stop(){if(this.running){this.running=!1,this.animationHandle&&cancelAnimationFrame(this.animationHandle),this.animationHandle=null;for(const e of Array.from(this.videos.keys()))this.removeStream(e);this.combinedStream&&(this.combinedStream.getTracks().forEach(e=>{try{e.stop()}catch{}}),this.combinedStream=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null),this.canvas&&(this.canvas.remove(),this.canvas=null,this.ctx=null)}}}function Br(r){const e=String(r).trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[e.length-1][0]).toUpperCase()}function Ur(r){let e=0;const t=String(r);for(let s=0;s<t.length;s++)e=e*31+t.charCodeAt(s)>>>0;return`hsl(${e%360}, 45%, 40%)`}function Nr(r,e,t,n,s,i){const o=t+s/2,a=n+i/2,c=Math.min(s,i)*.22;r.fillStyle=Ur(e),r.beginPath(),r.arc(o,a,c,0,Math.PI*2),r.fill(),r.fillStyle="#fff",r.font=`600 ${Math.floor(c)}px system-ui, sans-serif`,r.textAlign="center",r.textBaseline="middle",r.fillText(Br(e),o,a+1),r.textAlign="start",r.textBaseline="alphabetic"}function zr(r){if(r<=1)return{cols:1,rows:1};if(r===2)return{cols:2,rows:1};if(r<=4)return{cols:2,rows:2};if(r<=6)return{cols:3,rows:2};if(r<=9)return{cols:3,rows:3};const e=4;return{cols:e,rows:Math.ceil(r/e)}}function Fr(r,e){return r.includes("pdf")||/\.pdf$/i.test(e)?"📕":r.includes("word")||/\.docx?$/i.test(e)?"📘":r.includes("sheet")||r.includes("excel")||/\.(xlsx?|csv)$/i.test(e)?"📗":r.startsWith("text/")?"📄":"📎"}class jr{constructor(e={}){this.container=null,this.videoElements={},this.chatMessages=[],this.recording=e.recording||"off",this.screenShare=e.screenShare!==!1,this.enabledPanels=new Set(Array.isArray(e.panels)&&e.panels.length?e.panels:["chat"]),this.enabledPanels.add("chat"),this.activePanel="chat",this.panelSlots={}}mount(e){if(typeof e=="string"?this.container=document.querySelector(e):e instanceof Element&&(this.container=e),!this.container)throw new Error(`Container not found: ${e}`);this.render()}render(){const e=this.recording==="manual"?'<button id="toggle-record" style="padding: 10px 20px; background-color: #7a3a3a; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px;">● Record</button>':"",t=this.recording!=="off"?'<button id="toggle-pause" style="display:none; padding: 10px 20px; background-color: #3a5a7a; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px;">⏸ Pause</button>':"",n=this.screenShare?'<button id="toggle-screenshare" style="padding: 10px 20px; background-color: #3a5a7a; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px;">Share Screen</button>':"",s=this.recording!=="off"?'<span id="recording-indicator" style="display:none; margin-left: 12px; color: #ff5252; font-size: 13px; font-weight: 600;"><span id="rec-dot" style="display:inline-block; width:8px; height:8px; background:#ff5252; border-radius:50%; margin-right:6px; animation: recPulse 1.2s ease-in-out infinite;"></span>REC <span id="rec-elapsed">00:00</span></span>':"",i=this.recording!=="off"?'<span id="queue-indicator" style="display:none; margin-left: 12px; color: #fbbf24; font-size: 12px;">⏳ <span id="queue-count">0</span> uploading</span>':"";this._panelWiredOnRender=!0,this.container.innerHTML=`
|
|
41
|
+
isUnifiedPlanSupported:${this.isUnifiedPlanSupported()}`}constructor(){this.isIOS=typeof navigator<"u"?["iPad","iPhone","iPod"].includes(navigator.platform):!1,this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}},wn=r=>!r||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(r),$t=()=>Math.random().toString(36).slice(2),Bt={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};class Mn extends Lt{noop(){}blobToArrayBuffer(e,t){const n=new FileReader;return n.onload=function(s){s.target&&t(s.target.result)},n.readAsArrayBuffer(e),n}binaryStringToArrayBuffer(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t.buffer}isSecure(){return location.protocol==="https:"}constructor(...e){super(...e),this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.defaultConfig=Bt,this.browser=z.getBrowser(),this.browserVersion=z.getVersion(),this.pack=We,this.unpack=Je,this.supports=function(){const t={browser:z.isBrowserSupported(),webRTC:z.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!t.webRTC)return t;let n;try{n=new RTCPeerConnection(Bt),t.audioVideo=!0;let s;try{s=n.createDataChannel("_PEERJSTEST",{ordered:!0}),t.data=!0,t.reliable=!!s.ordered;try{s.binaryType="blob",t.binaryBlob=!z.isIOS}catch{}}catch{}finally{s&&s.close()}}catch{}finally{n&&n.close()}return t}(),this.validateId=wn,this.randomToken=$t}}const k=new Mn,An="PeerJS: ";class On{get logLevel(){return this._logLevel}set logLevel(e){this._logLevel=e}log(...e){this._logLevel>=3&&this._print(3,...e)}warn(...e){this._logLevel>=2&&this._print(2,...e)}error(...e){this._logLevel>=1&&this._print(1,...e)}setLogFunction(e){this._print=e}_print(e,...t){const n=[An,...t];for(const s in n)n[s]instanceof Error&&(n[s]="("+n[s].name+") "+n[s].message);e>=3?console.log(...n):e>=2?console.warn("WARNING",...n):e>=1&&console.error("ERROR",...n)}constructor(){this._logLevel=0}}var f=new On,ve={},In=Object.prototype.hasOwnProperty,C="~";function F(){}Object.create&&(F.prototype=Object.create(null),new F().__proto__||(C=!1));function Dn(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function Ut(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new Dn(t,n||r,s),o=C?C+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],i]:r._events[o].push(i):(r._events[o]=i,r._eventsCount++),r}function X(r,e){--r._eventsCount===0?r._events=new F:delete r._events[e]}function v(){this._events=new F,this._eventsCount=0}v.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)In.call(t,n)&&e.push(C?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},v.prototype.listeners=function(e){var t=C?C+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o},v.prototype.listenerCount=function(e){var t=C?C+e:e,n=this._events[t];return n?n.fn?1:n.length:0},v.prototype.emit=function(e,t,n,s,i,o){var a=C?C+e:e;if(!this._events[a])return!1;var c=this._events[a],h=arguments.length,l,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),h){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,i),!0;case 6:return c.fn.call(c.context,t,n,s,i,o),!0}for(d=1,l=new Array(h-1);d<h;d++)l[d-1]=arguments[d];c.fn.apply(c.context,l)}else{var u=c.length,p;for(d=0;d<u;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),h){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,s);break;default:if(!l)for(p=1,l=new Array(h-1);p<h;p++)l[p-1]=arguments[p];c[d].fn.apply(c[d].context,l)}}return!0},v.prototype.on=function(e,t,n){return Ut(this,e,t,n,!1)},v.prototype.once=function(e,t,n){return Ut(this,e,t,n,!0)},v.prototype.removeListener=function(e,t,n,s){var i=C?C+e:e;if(!this._events[i])return this;if(!t)return X(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!s||o.once)&&(!n||o.context===n)&&X(this,i);else{for(var a=0,c=[],h=o.length;a<h;a++)(o[a].fn!==t||s&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:X(this,i)}return this},v.prototype.removeAllListeners=function(e){var t;return e?(t=C?C+e:e,this._events[t]&&X(this,t)):(this._events=new F,this._eventsCount=0),this},v.prototype.off=v.prototype.removeListener,v.prototype.addListener=v.prototype.on,v.prefixed=C,v.EventEmitter=v,ve=v;var L={};D(L,"ConnectionType",()=>M),D(L,"PeerErrorType",()=>y),D(L,"BaseConnectionErrorType",()=>Se),D(L,"DataConnectionErrorType",()=>Ce),D(L,"SerializationType",()=>Z),D(L,"SocketEventType",()=>A),D(L,"ServerMessageType",()=>S);var M=function(r){return r.Data="data",r.Media="media",r}({}),y=function(r){return r.BrowserIncompatible="browser-incompatible",r.Disconnected="disconnected",r.InvalidID="invalid-id",r.InvalidKey="invalid-key",r.Network="network",r.PeerUnavailable="peer-unavailable",r.SslUnavailable="ssl-unavailable",r.ServerError="server-error",r.SocketError="socket-error",r.SocketClosed="socket-closed",r.UnavailableID="unavailable-id",r.WebRTC="webrtc",r}({}),Se=function(r){return r.NegotiationFailed="negotiation-failed",r.ConnectionClosed="connection-closed",r}({}),Ce=function(r){return r.NotOpenYet="not-open-yet",r.MessageToBig="message-too-big",r}({}),Z=function(r){return r.Binary="binary",r.BinaryUTF8="binary-utf8",r.JSON="json",r.None="raw",r}({}),A=function(r){return r.Message="message",r.Disconnected="disconnected",r.Error="error",r.Close="close",r}({}),S=function(r){return r.Heartbeat="HEARTBEAT",r.Candidate="CANDIDATE",r.Offer="OFFER",r.Answer="ANSWER",r.Open="OPEN",r.Error="ERROR",r.IdTaken="ID-TAKEN",r.InvalidKey="INVALID-KEY",r.Leave="LEAVE",r.Expire="EXPIRE",r}({});const Nt="1.5.5";class Ln extends ve.EventEmitter{constructor(e,t,n,s,i,o=5e3){super(),this.pingInterval=o,this._disconnected=!0,this._messagesQueue=[];const a=e?"wss://":"ws://";this._baseUrl=a+t+":"+n+s+"peerjs?key="+i}start(e,t){this._id=e;const n=`${this._baseUrl}&id=${e}&token=${t}`;this._socket||!this._disconnected||(this._socket=new WebSocket(n+"&version="+Nt),this._disconnected=!1,this._socket.onmessage=s=>{let i;try{i=JSON.parse(s.data),f.log("Server message received:",i)}catch{f.log("Invalid server message",s.data);return}this.emit(A.Message,i)},this._socket.onclose=s=>{this._disconnected||(f.log("Socket closed.",s),this._cleanup(),this._disconnected=!0,this.emit(A.Disconnected))},this._socket.onopen=()=>{this._disconnected||(this._sendQueuedMessages(),f.log("Socket open"),this._scheduleHeartbeat())})}_scheduleHeartbeat(){this._wsPingTimer=setTimeout(()=>{this._sendHeartbeat()},this.pingInterval)}_sendHeartbeat(){if(!this._wsOpen()){f.log("Cannot send heartbeat, because socket closed");return}const e=JSON.stringify({type:S.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()}_wsOpen(){return!!this._socket&&this._socket.readyState===1}_sendQueuedMessages(){const e=[...this._messagesQueue];this._messagesQueue=[];for(const t of e)this.send(t)}send(e){if(this._disconnected)return;if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(A.Error,"Invalid message");return}if(!this._wsOpen())return;const t=JSON.stringify(e);this._socket.send(t)}close(){this._disconnected||(this._cleanup(),this._disconnected=!0)}_cleanup(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)}}class zt{constructor(e){this.connection=e}startConnection(e){const t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===M.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){const n=this.connection,s={ordered:!!e.reliable},i=t.createDataChannel(n.label,s);n._initializeDataChannel(i),this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){f.log("Creating RTCPeerConnection.");const e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e}_setupListeners(e){const t=this.connection.peer,n=this.connection.connectionId,s=this.connection.type,i=this.connection.provider;f.log("Listening for ICE candidates."),e.onicecandidate=o=>{!o.candidate||!o.candidate.candidate||(f.log(`Received ICE candidates for ${t}:`,o.candidate),i.socket.send({type:S.Candidate,payload:{candidate:o.candidate,type:s,connectionId:n},dst:t}))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":f.log("iceConnectionState is failed, closing connections to "+t),this.connection.emitError(Se.NegotiationFailed,"Negotiation of connection to "+t+" failed."),this.connection.close();break;case"closed":f.log("iceConnectionState is closed, closing connections to "+t),this.connection.emitError(Se.ConnectionClosed,"Connection to "+t+" closed."),this.connection.close();break;case"disconnected":f.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":e.onicecandidate=()=>{};break}this.connection.emit("iceStateChanged",e.iceConnectionState)},f.log("Listening for data channel"),e.ondatachannel=o=>{f.log("Received data channel");const a=o.channel;i.getConnection(t,n)._initializeDataChannel(a)},f.log("Listening for remote stream"),e.ontrack=o=>{f.log("Received remote stream");const a=o.streams[0],c=i.getConnection(t,n);if(c.type===M.Media){const h=c;this._addStreamToMediaConnection(a,h)}}}cleanup(){f.log("Cleaning up PeerConnection to "+this.connection.peer);const e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=()=>{};const t=e.signalingState!=="closed";let n=!1;const s=this.connection.dataChannel;s&&(n=!!s.readyState&&s.readyState!=="closed"),(t||n)&&e.close()}async _makeOffer(){const e=this.connection.peerConnection,t=this.connection.provider;try{const n=await e.createOffer(this.connection.options.constraints);f.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp);try{await e.setLocalDescription(n),f.log("Set localDescription:",n,`for:${this.connection.peer}`);let s={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type===M.Data){const i=this.connection;s={...s,label:i.label,reliable:i.reliable,serialization:i.serialization}}t.socket.send({type:S.Offer,payload:s,dst:this.connection.peer})}catch(s){s!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError(y.WebRTC,s),f.log("Failed to setLocalDescription, ",s))}}catch(n){t.emitError(y.WebRTC,n),f.log("Failed to createOffer, ",n)}}async _makeAnswer(){const e=this.connection.peerConnection,t=this.connection.provider;try{const n=await e.createAnswer();f.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp);try{await e.setLocalDescription(n),f.log("Set localDescription:",n,`for:${this.connection.peer}`),t.socket.send({type:S.Answer,payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(s){t.emitError(y.WebRTC,s),f.log("Failed to setLocalDescription, ",s)}}catch(n){t.emitError(y.WebRTC,n),f.log("Failed to create answer, ",n)}}async handleSDP(e,t){t=new RTCSessionDescription(t);const n=this.connection.peerConnection,s=this.connection.provider;f.log("Setting remote description",t);const i=this;try{await n.setRemoteDescription(t),f.log(`Set remoteDescription:${e} for:${this.connection.peer}`),e==="OFFER"&&await i._makeAnswer()}catch(o){s.emitError(y.WebRTC,o),f.log("Failed to setRemoteDescription, ",o)}}async handleCandidate(e){f.log("handleCandidate:",e);try{await this.connection.peerConnection.addIceCandidate(e),f.log(`Added ICE candidate for:${this.connection.peer}`)}catch(t){this.connection.provider.emitError(y.WebRTC,t),f.log("Failed to handleCandidate, ",t)}}_addTracksToConnection(e,t){if(f.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack)return f.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(n=>{t.addTrack(n,e)})}_addStreamToMediaConnection(e,t){f.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}}class Ft extends ve.EventEmitter{emitError(e,t){f.error("Error:",t),this.emit("error",new $n(`${e}`,t))}}class $n extends Error{constructor(e,t){typeof t=="string"?super(t):(super(),Object.assign(this,t)),this.type=e}}class jt extends Ft{get open(){return this._open}constructor(e,t,n){super(),this.peer=e,this.provider=t,this.options=n,this._open=!1,this.metadata=n.metadata}}const V=class V extends jt{get type(){return M.Media}get localStream(){return this._localStream}get remoteStream(){return this._remoteStream}constructor(e,t,n){super(e,t,n),this._localStream=this.options._stream,this.connectionId=this.options.connectionId||V.ID_PREFIX+k.randomToken(),this._negotiator=new zt(this),this._localStream&&this._negotiator.startConnection({_stream:this._localStream,originator:!0})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{f.log(`DC#${this.connectionId} dc connection success`),this.emit("willCloseOnRemote")},this.dataChannel.onclose=()=>{f.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}addStream(e){f.log("Receiving stream",e),this._remoteStream=e,super.emit("stream",e)}handleMessage(e){const t=e.type,n=e.payload;switch(e.type){case S.Answer:this._negotiator.handleSDP(t,n.sdp),this._open=!0;break;case S.Candidate:this._negotiator.handleCandidate(n.candidate);break;default:f.warn(`Unrecognized message type:${t} from peer:${this.peer}`);break}}answer(e,t={}){if(this._localStream){f.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,t&&t.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection({...this.options._payload,_stream:e});const n=this.provider._getMessages(this.connectionId);for(const s of n)this.handleMessage(s);this._open=!0}close(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,super.emit("close"))}};je=new WeakMap,K(V,je,V.ID_PREFIX="mc_");let ee=V;class Bn{constructor(e){this._options=e}_buildRequest(e){const t=this._options.secure?"https":"http",{host:n,port:s,path:i,key:o}=this._options,a=new URL(`${t}://${n}:${s}${i}${o}/${e}`);return a.searchParams.set("ts",`${Date.now()}${Math.random()}`),a.searchParams.set("version",Nt),fetch(a.href,{referrerPolicy:this._options.referrerPolicy})}async retrieveId(){try{const e=await this._buildRequest("id");if(e.status!==200)throw new Error(`Error. Status:${e.status}`);return e.text()}catch(e){f.error("Error retrieving ID",e);let t="";throw this._options.path==="/"&&this._options.host!==k.CLOUD_HOST&&(t=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+t)}}async listAllPeers(){try{const e=await this._buildRequest("peers");if(e.status!==200){if(e.status===401){let t="";throw this._options.host===k.CLOUD_HOST?t="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":t="You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+t)}throw new Error(`Error. Status:${e.status}`)}return e.json()}catch(e){throw f.error("Error retrieving list peers",e),new Error("Could not get list peers from the server."+e)}}}const $=class $ extends jt{get type(){return M.Data}constructor(e,t,n){super(e,t,n),this.connectionId=this.options.connectionId||$.ID_PREFIX+$t(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new zt(this),this._negotiator.startConnection(this.options._payload||{originator:!0,reliable:this.reliable})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{f.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this.emit("open")},this.dataChannel.onmessage=t=>{f.log(`DC#${this.connectionId} dc onmessage:`,t.data)},this.dataChannel.onclose=()=>{f.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}close(e){if(e!=null&&e.flush){this.send({__peerData:{type:"close"}});return}this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this.dataChannel=null),this.open&&(this._open=!1,super.emit("close"))}send(e,t=!1){if(!this.open){this.emitError(Ce.NotOpenYet,"Connection is not open. You should listen for the `open` event before sending messages.");return}return this._send(e,t)}async handleMessage(e){const t=e.payload;switch(e.type){case S.Answer:await this._negotiator.handleSDP(e.type,t.sdp);break;case S.Candidate:await this._negotiator.handleCandidate(t.candidate);break;default:f.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}};qe=new WeakMap,Ve=new WeakMap,K($,qe,$.ID_PREFIX="dc_"),K($,Ve,$.MAX_BUFFERED_AMOUNT=8388608);let te=$;class ke extends te{get bufferSize(){return this._bufferSize}_initializeDataChannel(e){super._initializeDataChannel(e),this.dataChannel.binaryType="arraybuffer",this.dataChannel.addEventListener("message",t=>this._handleDataMessage(t))}_bufferedSend(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)}_trySend(e){if(!this.open)return!1;if(this.dataChannel.bufferedAmount>te.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(()=>{this._buffering=!1,this._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(t){return f.error(`DC#:${this.connectionId} Error when sending:`,t),this._buffering=!0,this.close(),!1}return!0}_tryBuffer(){if(!this.open||this._buffer.length===0)return;const e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}close(e){if(e!=null&&e.flush){this.send({__peerData:{type:"close"}});return}this._buffer=[],this._bufferSize=0,super.close()}constructor(...e){super(...e),this._buffer=[],this._bufferSize=0,this._buffering=!1}}class xe extends ke{close(e){super.close(e),this._chunkedData={}}constructor(e,t,n){super(e,t,n),this.chunker=new Lt,this.serialization=Z.Binary,this._chunkedData={}}_handleDataMessage({data:e}){const t=Je(e),n=t.__peerData;if(n){if(n.type==="close"){this.close();return}this._handleChunk(t);return}this.emit("data",t)}_handleChunk(e){const t=e.__peerData,n=this._chunkedData[t]||{data:[],count:0,total:e.total};if(n.data[e.n]=new Uint8Array(e.data),n.count++,this._chunkedData[t]=n,n.total===n.count){delete this._chunkedData[t];const s=En(n.data);this._handleDataMessage({data:s})}}_send(e,t){const n=We(e);if(n instanceof Promise)return this._send_blob(n);if(!t&&n.byteLength>this.chunker.chunkedMTU){this._sendChunks(n);return}this._bufferedSend(n)}async _send_blob(e){const t=await e;if(t.byteLength>this.chunker.chunkedMTU){this._sendChunks(t);return}this._bufferedSend(t)}_sendChunks(e){const t=this.chunker.chunk(e);f.log(`DC#${this.connectionId} Try to send ${t.length} chunks...`);for(const n of t)this.send(n,!0)}}class Un extends ke{_handleDataMessage({data:e}){super.emit("data",e)}_send(e,t){this._bufferedSend(e)}constructor(...e){super(...e),this.serialization=Z.None}}class Nn extends ke{_handleDataMessage({data:e}){const t=this.parse(this.decoder.decode(e)),n=t.__peerData;if(n&&n.type==="close"){this.close();return}this.emit("data",t)}_send(e,t){const n=this.encoder.encode(this.stringify(e));if(n.byteLength>=k.chunkedMTU){this.emitError(Ce.MessageToBig,"Message too big for JSON channel");return}this._bufferedSend(n)}constructor(...e){super(...e),this.serialization=Z.JSON,this.encoder=new TextEncoder,this.decoder=new TextDecoder,this.stringify=JSON.stringify,this.parse=JSON.parse}}const H=class H extends Ft{get id(){return this._id}get options(){return this._options}get open(){return this._open}get socket(){return this._socket}get connections(){const e=Object.create(null);for(const[t,n]of this._connections)e[t]=n;return e}get destroyed(){return this._destroyed}get disconnected(){return this._disconnected}constructor(e,t){super(),this._serializers={raw:Un,json:Nn,binary:xe,"binary-utf8":xe,default:xe},this._id=null,this._lastServerId=null,this._destroyed=!1,this._disconnected=!1,this._open=!1,this._connections=new Map,this._lostMessages=new Map;let n;if(e&&e.constructor==Object?t=e:e&&(n=e.toString()),t={debug:0,host:k.CLOUD_HOST,port:k.CLOUD_PORT,path:"/",key:H.DEFAULT_KEY,token:k.randomToken(),config:k.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin",serializers:{},...t},this._options=t,this._serializers={...this._serializers,...this.options.serializers},this._options.host==="/"&&(this._options.host=window.location.hostname),this._options.path&&(this._options.path[0]!=="/"&&(this._options.path="/"+this._options.path),this._options.path[this._options.path.length-1]!=="/"&&(this._options.path+="/")),this._options.secure===void 0&&this._options.host!==k.CLOUD_HOST?this._options.secure=k.isSecure():this._options.host==k.CLOUD_HOST&&(this._options.secure=!0),this._options.logFunction&&f.setLogFunction(this._options.logFunction),f.logLevel=this._options.debug||0,this._api=new Bn(t),this._socket=this._createServerConnection(),!k.supports.audioVideo&&!k.supports.data){this._delayedAbort(y.BrowserIncompatible,"The current browser does not support WebRTC");return}if(n&&!k.validateId(n)){this._delayedAbort(y.InvalidID,`ID "${n}" is invalid`);return}n?this._initialize(n):this._api.retrieveId().then(s=>this._initialize(s)).catch(s=>this._abort(y.ServerError,s))}_createServerConnection(){const e=new Ln(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return e.on(A.Message,t=>{this._handleMessage(t)}),e.on(A.Error,t=>{this._abort(y.SocketError,t)}),e.on(A.Disconnected,()=>{this.disconnected||(this.emitError(y.Network,"Lost connection to server."),this.disconnect())}),e.on(A.Close,()=>{this.disconnected||this._abort(y.SocketClosed,"Underlying socket is already closed.")}),e}_initialize(e){this._id=e,this.socket.start(e,this._options.token)}_handleMessage(e){const t=e.type,n=e.payload,s=e.src;switch(t){case S.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case S.Error:this._abort(y.ServerError,n.msg);break;case S.IdTaken:this._abort(y.UnavailableID,`ID "${this.id}" is taken`);break;case S.InvalidKey:this._abort(y.InvalidKey,`API KEY "${this._options.key}" is invalid`);break;case S.Leave:f.log(`Received leave message from ${s}`),this._cleanupPeer(s),this._connections.delete(s);break;case S.Expire:this.emitError(y.PeerUnavailable,`Could not connect to peer ${s}`);break;case S.Offer:{const i=n.connectionId;let o=this.getConnection(s,i);if(o&&(o.close(),f.warn(`Offer received for existing Connection ID:${i}`)),n.type===M.Media){const c=new ee(s,this,{connectionId:i,_payload:n,metadata:n.metadata});o=c,this._addConnection(s,o),this.emit("call",c)}else if(n.type===M.Data){const c=new this._serializers[n.serialization](s,this,{connectionId:i,_payload:n,metadata:n.metadata,label:n.label,serialization:n.serialization,reliable:n.reliable});o=c,this._addConnection(s,o),this.emit("connection",c)}else{f.warn(`Received malformed connection type:${n.type}`);return}const a=this._getMessages(i);for(const c of a)o.handleMessage(c);break}default:{if(!n){f.warn(`You received a malformed message from ${s} of type ${t}`);return}const i=n.connectionId,o=this.getConnection(s,i);o&&o.peerConnection?o.handleMessage(e):i?this._storeMessage(i,e):f.warn("You received an unrecognized message:",e);break}}}_storeMessage(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(t)}_getMessages(e){const t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),t):[]}connect(e,t={}){if(t={serialization:"default",...t},this.disconnected){f.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError(y.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}const n=new this._serializers[t.serialization](e,this,t);return this._addConnection(e,n),n}call(e,t,n={}){if(this.disconnected){f.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),this.emitError(y.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!t){f.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}const s=new ee(e,this,{...n,_stream:t});return this._addConnection(e,s),s}_addConnection(e,t){f.log(`add connection ${t.type}:${t.connectionId} to peerId:${e}`),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(t)}_removeConnection(e){const t=this._connections.get(e.peer);if(t){const n=t.indexOf(e);n!==-1&&t.splice(n,1)}this._lostMessages.delete(e.connectionId)}getConnection(e,t){const n=this._connections.get(e);if(!n)return null;for(const s of n)if(s.connectionId===t)return s;return null}_delayedAbort(e,t){setTimeout(()=>{this._abort(e,t)},0)}_abort(e,t){f.error("Aborting!"),this.emitError(e,t),this._lastServerId?this.disconnect():this.destroy()}destroy(){this.destroyed||(f.log(`Destroy peer with ID:${this.id}`),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))}_cleanup(){for(const e of this._connections.keys())this._cleanupPeer(e),this._connections.delete(e);this.socket.removeAllListeners()}_cleanupPeer(e){const t=this._connections.get(e);if(t)for(const n of t)n.close()}disconnect(){if(this.disconnected)return;const e=this.id;f.log(`Disconnect peer with ID:${e}`),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}reconnect(){if(this.disconnected&&!this.destroyed)f.log(`Attempting reconnection to server with ID ${this._lastServerId}`),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(!this.disconnected&&!this.open)f.error("In a hurry? We're still trying to make the initial connection!");else throw new Error(`Peer ${this.id} cannot reconnect because it is not disconnected from the server!`)}}listAllPeers(e=t=>{}){this._api.listAllPeers().then(t=>e(t)).catch(t=>this._abort(y.ServerError,t))}};He=new WeakMap,K(H,He,H.DEFAULT_KEY="peerjs");let Te=H;var zn=Te;class Fn{constructor(e){this.config=e,this.peer=null,this.localStream=null,this.connections={},this.callbacks={onStream:null,onPeerLeft:null,onError:null}}buildIceServers(){const e=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}],t=Array.isArray(this.config.iceServers)?this.config.iceServers:[];return[...e,...t]}async initialize(e,t=0){return new Promise((n,s)=>{const i=t===0?e:`${e}-r${Math.random().toString(36).slice(2,6)}`;this.peer=new zn(i,{host:this.config.peerServer.host,port:this.config.peerServer.port,path:this.config.peerServer.path||"/peerjs",secure:this.config.peerServer.secure??!1,config:{iceServers:this.buildIceServers()}});let o=!1;this.peer.on("open",a=>{o=!0,console.log("Peer initialized:",a),this.actualPeerId=a,n(a)}),this.peer.on("error",async a=>{if(!o&&a&&a.type==="unavailable-id"&&t<1){console.warn(`Peer id "${i}" taken — retrying with a suffix`);try{this.peer.destroy()}catch{}this.peer=null;try{const c=await this.initialize(e,t+1);o=!0,n(c)}catch(c){s(c)}return}console.error("Peer error:",a),this.callbacks.onError&&this.callbacks.onError(a),o||s(a)}),this.peer.on("call",a=>{this.handleIncomingCall(a)})})}async getLocalStream(){if(this.localStream)return this.localStream;try{return this.localStream=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0}),this.localStream}catch(e){throw console.error("Failed to get local stream:",e),this.callbacks.onError&&this.callbacks.onError(e),e}}async handleIncomingCall(e){if(this.connections[e.peer]){console.log("Duplicate incoming call from",e.peer,"— closing");try{e.close()}catch{}return}this.connections[e.peer]={call:e,stream:null};const t=await this.getLocalStream();e.answer(t),e.on("stream",n=>{console.log("Received stream from:",e.peer),this.connections[e.peer]={call:e,stream:n},this.callbacks.onStream&&this.callbacks.onStream(e.peer,n,!1)}),e.on("close",()=>{console.log("Call closed:",e.peer),delete this.connections[e.peer],this.callbacks.onPeerLeft&&this.callbacks.onPeerLeft(e.peer)})}async callPeer(e){if(this.connections[e]){console.log("Already connected to:",e);return}if(this.peer&&this.peer.id&&this.peer.id>e){console.log(`Waiting for ${e} to call us (our id ${this.peer.id} > theirs)`);return}this.connections[e]={call:null,stream:null};const t=await this.getLocalStream();if(this.connections[e]&&this.connections[e].call)return;const n=this.peer.call(e,t);this.connections[e]={call:n,stream:null},n.on("stream",s=>{console.log("Received stream from:",e),this.connections[e]={call:n,stream:s},this.callbacks.onStream&&this.callbacks.onStream(e,s,!1)}),n.on("close",()=>{console.log("Call closed:",e),delete this.connections[e],this.callbacks.onPeerLeft&&this.callbacks.onPeerLeft(e)}),n.on("error",s=>{console.error("Call error:",s),delete this.connections[e]})}toggleVideo(){if(this.localStream){const e=this.localStream.getVideoTracks()[0];if(e)return e.enabled=!e.enabled,e.enabled}return!1}toggleAudio(){if(this.localStream){const e=this.localStream.getAudioTracks()[0];if(e)return e.enabled=!e.enabled,e.enabled}return!1}replaceVideoTrackOnAllConnections(e){for(const{call:t}of Object.values(this.connections)){const n=t&&t.peerConnection;if(!n)continue;const s=n.getSenders().find(i=>i.track&&i.track.kind==="video");s&&s.replaceTrack(e).catch(i=>console.warn("replaceTrack failed:",i&&i.message))}}async startScreenShare(){if(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)throw new Error("Screen sharing is not supported in this browser");const t=(await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1})).getVideoTracks()[0];if(!t)throw new Error("Could not obtain display video track");return this.cameraVideoTrack=this.localStream.getVideoTracks()[0]||null,this.replaceVideoTrackOnAllConnections(t),this.cameraVideoTrack&&this.localStream.removeTrack(this.cameraVideoTrack),this.localStream.addTrack(t),this.screenTrack=t,t.addEventListener("ended",()=>this.stopScreenShare().catch(()=>{})),t}async stopScreenShare(){if(!this.screenTrack)return!1;try{this.screenTrack.stop()}catch{}let e=this.cameraVideoTrack;if(!e||e.readyState==="ended")try{e=(await navigator.mediaDevices.getUserMedia({video:!0,audio:!1})).getVideoTracks()[0]}catch(t){console.warn("Could not restore camera after screen share:",t&&t.message),e=null}if(e){this.replaceVideoTrackOnAllConnections(e);try{this.localStream.removeTrack(this.screenTrack)}catch{}this.localStream.addTrack(e),this.cameraVideoTrack=e}return this.screenTrack=null,!0}isScreenSharing(){return!!this.screenTrack}on(e,t){this.callbacks.hasOwnProperty("on"+e.charAt(0).toUpperCase()+e.slice(1))&&(this.callbacks["on"+e.charAt(0).toUpperCase()+e.slice(1)]=t)}disconnect(){Object.values(this.connections).forEach(({call:e})=>{e.close()}),this.connections={},this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null),this.peer&&(this.peer.destroy(),this.peer=null)}}const E=Object.create(null);E.open="0",E.close="1",E.ping="2",E.pong="3",E.message="4",E.upgrade="5",E.noop="6";const ne=Object.create(null);Object.keys(E).forEach(r=>{ne[E[r]]=r});const Re={type:"error",data:"parser error"},qt=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Vt=typeof ArrayBuffer=="function",Ht=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r&&r.buffer instanceof ArrayBuffer,Pe=({type:r,data:e},t,n)=>qt&&e instanceof Blob?t?n(e):Kt(e,n):Vt&&(e instanceof ArrayBuffer||Ht(e))?t?n(e):Kt(new Blob([e]),n):n(E[r]+(e||"")),Kt=(r,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(r)};function Jt(r){return r instanceof Uint8Array?r:r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let Ee;function jn(r,e){if(qt&&r.data instanceof Blob)return r.data.arrayBuffer().then(Jt).then(e);if(Vt&&(r.data instanceof ArrayBuffer||Ht(r.data)))return e(Jt(r.data));Pe(r,!1,t=>{Ee||(Ee=new TextEncoder),e(Ee.encode(t))})}const Wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",j=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let r=0;r<Wt.length;r++)j[Wt.charCodeAt(r)]=r;const qn=r=>{let e=r.length*.75,t=r.length,n,s=0,i,o,a,c;r[r.length-1]==="="&&(e--,r[r.length-2]==="="&&e--);const h=new ArrayBuffer(e),l=new Uint8Array(h);for(n=0;n<t;n+=4)i=j[r.charCodeAt(n)],o=j[r.charCodeAt(n+1)],a=j[r.charCodeAt(n+2)],c=j[r.charCodeAt(n+3)],l[s++]=i<<2|o>>4,l[s++]=(o&15)<<4|a>>2,l[s++]=(a&3)<<6|c&63;return h},Vn=typeof ArrayBuffer=="function",we=(r,e)=>{if(typeof r!="string")return{type:"message",data:Yt(r,e)};const t=r.charAt(0);return t==="b"?{type:"message",data:Hn(r.substring(1),e)}:ne[t]?r.length>1?{type:ne[t],data:r.substring(1)}:{type:ne[t]}:Re},Hn=(r,e)=>{if(Vn){const t=qn(r);return Yt(t,e)}else return{base64:!0,data:r}},Yt=(r,e)=>{switch(e){case"blob":return r instanceof Blob?r:new Blob([r]);case"arraybuffer":default:return r instanceof ArrayBuffer?r:r.buffer}},Gt="",Kn=(r,e)=>{const t=r.length,n=new Array(t);let s=0;r.forEach((i,o)=>{Pe(i,!1,a=>{n[o]=a,++s===t&&e(n.join(Gt))})})},Jn=(r,e)=>{const t=r.split(Gt),n=[];for(let s=0;s<t.length;s++){const i=we(t[s],e);if(n.push(i),i.type==="error")break}return n};function Wn(){return new TransformStream({transform(r,e){jn(r,t=>{const n=t.length;let s;if(n<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,n);else if(n<65536){s=new Uint8Array(3);const i=new DataView(s.buffer);i.setUint8(0,126),i.setUint16(1,n)}else{s=new Uint8Array(9);const i=new DataView(s.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(n))}r.data&&typeof r.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}let Me;function re(r){return r.reduce((e,t)=>e+t.length,0)}function se(r,e){if(r[0].length===e)return r.shift();const t=new Uint8Array(e);let n=0;for(let s=0;s<e;s++)t[s]=r[0][n++],n===r[0].length&&(r.shift(),n=0);return r.length&&n<r[0].length&&(r[0]=r[0].slice(n)),t}function Yn(r,e){Me||(Me=new TextDecoder);const t=[];let n=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(n===0){if(re(t)<1)break;const c=se(t,1);i=(c[0]&128)===128,s=c[0]&127,s<126?n=3:s===126?n=1:n=2}else if(n===1){if(re(t)<2)break;const c=se(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),n=3}else if(n===2){if(re(t)<8)break;const c=se(t,8),h=new DataView(c.buffer,c.byteOffset,c.length),l=h.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(Re);break}s=l*Math.pow(2,32)+h.getUint32(4),n=3}else{if(re(t)<s)break;const c=se(t,s);a.enqueue(we(i?c:Me.decode(c),e)),n=0}if(s===0||s>r){a.enqueue(Re);break}}}})}const Qt=4;function b(r){if(r)return Gn(r)}function Gn(r){for(var e in b.prototype)r[e]=b.prototype[e];return r}b.prototype.on=b.prototype.addEventListener=function(r,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(e),this},b.prototype.once=function(r,e){function t(){this.off(r,t),e.apply(this,arguments)}return t.fn=e,this.on(r,t),this},b.prototype.off=b.prototype.removeListener=b.prototype.removeAllListeners=b.prototype.removeEventListener=function(r,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+r];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var n,s=0;s<t.length;s++)if(n=t[s],n===e||n.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+r],this},b.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+r],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,s=t.length;n<s;++n)t[n].apply(this,e)}return this},b.prototype.emitReserved=b.prototype.emit,b.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]},b.prototype.hasListeners=function(r){return!!this.listeners(r).length};const ie=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),T=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Qn="arraybuffer";function ts(){}function Xt(r,...e){return e.reduce((t,n)=>(r.hasOwnProperty(n)&&(t[n]=r[n]),t),{})}const Xn=T.setTimeout,Zn=T.clearTimeout;function oe(r,e){e.useNativeTimers?(r.setTimeoutFn=Xn.bind(T),r.clearTimeoutFn=Zn.bind(T)):(r.setTimeoutFn=T.setTimeout.bind(T),r.clearTimeoutFn=T.clearTimeout.bind(T))}const er=1.33;function tr(r){return typeof r=="string"?nr(r):Math.ceil((r.byteLength||r.size)*er)}function nr(r){let e=0,t=0;for(let n=0,s=r.length;n<s;n++)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function Zt(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function rr(r){let e="";for(let t in r)r.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(r[t]));return e}function sr(r){let e={},t=r.split("&");for(let n=0,s=t.length;n<s;n++){let i=t[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}class ir extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class Ae extends b{constructor(e){super(),this.writable=!1,oe(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new ir(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=we(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=rr(e);return t.length?"?"+t:""}}class or extends Ae{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Jn(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Kn(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=Zt()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let en=!1;try{en=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const ar=en;function cr(){}class hr extends or{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class w extends b{constructor(e,t,n){super(),this.createRequest=e,oe(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=Xt(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&n.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var s;n.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=w.requestsCount++,w.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=cr,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete w.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(w.requestsCount=0,w.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",tn);else if(typeof addEventListener=="function"){const r="onpagehide"in T?"pagehide":"unload";addEventListener(r,tn,!1)}}function tn(){for(let r in w.requests)w.requests.hasOwnProperty(r)&&w.requests[r].abort()}const lr=function(){const r=nn({xdomain:!1});return r&&r.responseType!==null}();class dr extends hr{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=lr&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new w(nn,this.uri(),e)}}function nn(r){const e=r.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||ar))return new XMLHttpRequest}catch{}if(!e)try{return new T[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const rn=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ur extends Ae{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=rn?{}:Xt(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],s=t===e.length-1;Pe(n,this.supportsBinary,i=>{try{this.doWrite(n,i)}catch{}s&&ie(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Zt()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Oe=T.WebSocket||T.MozWebSocket;class fr extends ur{createSocket(e,t,n){return rn?new Oe(e,t,n):t?new Oe(e,t):new Oe(e)}doWrite(e,t){this.ws.send(t)}}class pr extends Ae{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=Yn(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),s=Wn();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();const i=()=>{n.read().then(({done:a,value:c})=>{a||(this.onPacket(c),i())}).catch(a=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],s=t===e.length-1;this._writer.write(n).then(()=>{s&&ie(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const gr={websocket:fr,webtransport:pr,polling:dr},mr=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,yr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ie(r){if(r.length>8e3)throw"URI too long";const e=r,t=r.indexOf("["),n=r.indexOf("]");t!=-1&&n!=-1&&(r=r.substring(0,t)+r.substring(t,n).replace(/:/g,";")+r.substring(n,r.length));let s=mr.exec(r||""),i={},o=14;for(;o--;)i[yr[o]]=s[o]||"";return t!=-1&&n!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=br(i,i.path),i.queryKey=_r(i,i.query),i}function br(r,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function _r(r,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,s,i){s&&(t[s]=i)}),t}const De=typeof addEventListener=="function"&&typeof removeEventListener=="function",ae=[];De&&addEventListener("offline",()=>{ae.forEach(r=>r())},!1);class O extends b{constructor(e,t){if(super(),this.binaryType=Qn,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=Ie(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Ie(t.host).host);oe(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const s=n.prototype.name;this.transports.push(s),this._transportsByName[s]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=sr(this.opts.query)),De&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},ae.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=Qt,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&O.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",O.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const s=this.writeBuffer[n].data;if(s&&(t+=tr(s)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,ie(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,s){if(typeof t=="function"&&(s=t,t=void 0),typeof n=="function"&&(s=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(O.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),De&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=ae.indexOf(this._offlineEventListener);n!==-1&&ae.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}O.protocol=Qt;class vr extends O{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;O.priorWebsocketSuccess=!1;const s=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",d=>{if(!n)if(d.type==="pong"&&d.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;O.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const u=new Error("probe error");u.transport=t.name,this.emitReserved("upgradeError",u)}}))};function i(){n||(n=!0,l(),t.close(),t=null)}const o=d=>{const u=new Error("probe error: "+d);u.transport=t.name,i(),this.emitReserved("upgradeError",u)};function a(){o("transport closed")}function c(){o("socket closed")}function h(d){t&&d.name!==t.name&&i()}const l=()=>{t.removeListener("open",s),t.removeListener("error",o),t.removeListener("close",a),this.off("close",c),this.off("upgrading",h)};t.once("open",s),t.once("error",o),t.once("close",a),this.once("close",c),this.once("upgrading",h),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let Sr=class extends vr{constructor(e,t={}){const n=typeof e=="object",s=n?{...e}:{...t};(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(i=>gr[i]).filter(i=>!!i)),super(n?s:e,s)}};function Cr(r,e="",t){let n=r;t=t||typeof location<"u"&&location,r==null&&(r=t.protocol+"//"+t.host),typeof r=="string"&&(r.charAt(0)==="/"&&(r.charAt(1)==="/"?r=t.protocol+r:r=t.host+r),/^(https?|wss?):\/\//.test(r)||(typeof t<"u"?r=t.protocol+"//"+r:r="https://"+r),n=Ie(r)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(t&&t.port===n.port?"":":"+n.port),n}const kr=typeof ArrayBuffer=="function",xr=r=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(r):r.buffer instanceof ArrayBuffer,sn=Object.prototype.toString,Tr=typeof Blob=="function"||typeof Blob<"u"&&sn.call(Blob)==="[object BlobConstructor]",Rr=typeof File=="function"||typeof File<"u"&&sn.call(File)==="[object FileConstructor]";function Le(r){return kr&&(r instanceof ArrayBuffer||xr(r))||Tr&&r instanceof Blob||Rr&&r instanceof File}function ce(r,e){if(!r||typeof r!="object")return!1;if(Array.isArray(r)){for(let t=0,n=r.length;t<n;t++)if(ce(r[t]))return!0;return!1}if(Le(r))return!0;if(r.toJSON&&typeof r.toJSON=="function"&&arguments.length===1)return ce(r.toJSON(),!0);for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&ce(r[t]))return!0;return!1}function Pr(r){const e=[],t=r.data,n=r;return n.data=$e(t,e),n.attachments=e.length,{packet:n,buffers:e}}function $e(r,e){if(!r)return r;if(Le(r)){const t={_placeholder:!0,num:e.length};return e.push(r),t}else if(Array.isArray(r)){const t=new Array(r.length);for(let n=0;n<r.length;n++)t[n]=$e(r[n],e);return t}else if(typeof r=="object"&&!(r instanceof Date)){const t={};for(const n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=$e(r[n],e));return t}return r}function Er(r,e){return r.data=Be(r.data,e),delete r.attachments,r}function Be(r,e){if(!r)return r;if(r&&r._placeholder===!0){if(typeof r.num=="number"&&r.num>=0&&r.num<e.length)return e[r.num];throw new Error("illegal attachments")}else if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]=Be(r[t],e);else if(typeof r=="object")for(const t in r)Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=Be(r[t],e));return r}const wr=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var g;(function(r){r[r.CONNECT=0]="CONNECT",r[r.DISCONNECT=1]="DISCONNECT",r[r.EVENT=2]="EVENT",r[r.ACK=3]="ACK",r[r.CONNECT_ERROR=4]="CONNECT_ERROR",r[r.BINARY_EVENT=5]="BINARY_EVENT",r[r.BINARY_ACK=6]="BINARY_ACK"})(g||(g={}));class Mr{constructor(e){this.replacer=e}encode(e){return(e.type===g.EVENT||e.type===g.ACK)&&ce(e)?this.encodeAsBinary({type:e.type===g.EVENT?g.BINARY_EVENT:g.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===g.BINARY_EVENT||e.type===g.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Pr(e),n=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(n),s}}class Ue extends b{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===g.BINARY_EVENT;n||t.type===g.BINARY_ACK?(t.type=n?g.EVENT:g.ACK,this.reconstructor=new Ar(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Le(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(g[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===g.BINARY_EVENT||n.type===g.BINARY_ACK){const i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!Or(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(e.charAt(t+1)==="/"){const i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(i,t)}else n.nsp="/";const s=e.charAt(t+1);if(s!==""&&Number(s)==s){const i=t+1;for(;++t;){const o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}n.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(Ue.isPayloadValid(n.type,i))n.data=i;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case g.CONNECT:return on(t);case g.DISCONNECT:return t===void 0;case g.CONNECT_ERROR:return typeof t=="string"||on(t);case g.EVENT:case g.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&wr.indexOf(t[0])===-1);case g.ACK:case g.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ar{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=Er(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Or=Number.isInteger||function(r){return typeof r=="number"&&isFinite(r)&&Math.floor(r)===r};function on(r){return Object.prototype.toString.call(r)==="[object Object]"}const Ir=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ue,Encoder:Mr,get PacketType(){return g}},Symbol.toStringTag,{value:"Module"}));function R(r,e,t){return r.on(e,t),function(){r.off(e,t)}}const Dr=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class an extends b{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[R(e,"open",this.onopen.bind(this)),R(e,"packet",this.onpacket.bind(this)),R(e,"error",this.onerror.bind(this)),R(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,s,i;if(Dr.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:g.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const l=this.ids++,d=t.pop();this._registerAckCallback(l,d),o.id=l}const a=(s=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||s===void 0?void 0:s.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a||(c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var n;const s=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&this.sendBuffer.splice(a,1);t.call(this,new Error("operation has timed out"))},s),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((n,s)=>{const i=(o,a)=>o?s(o):n(a);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>(this._queue[0],s!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(s)):(this._queue.shift(),t&&t(null,...i)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:g.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case g.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case g.EVENT:case g.BINARY_EVENT:this.onevent(e);break;case g.ACK:case g.BINARY_ACK:this.onack(e);break;case g.DISCONNECT:this.ondisconnect();break;case g.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...s){n||(n=!0,t.packet({type:g.ACK,id:e,data:s}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:g.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function U(r){r=r||{},this.ms=r.min||100,this.max=r.max||1e4,this.factor=r.factor||2,this.jitter=r.jitter>0&&r.jitter<=1?r.jitter:0,this.attempts=0}U.prototype.duration=function(){var r=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*r);r=Math.floor(e*10)&1?r+t:r-t}return Math.min(r,this.max)|0},U.prototype.reset=function(){this.attempts=0},U.prototype.setMin=function(r){this.ms=r},U.prototype.setMax=function(r){this.max=r},U.prototype.setJitter=function(r){this.jitter=r};class Ne extends b{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,oe(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new U({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const s=t.parser||Ir;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Sr(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const s=R(t,"open",function(){n.onopen(),e&&e()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=R(t,"error",i);if(this._timeout!==!1){const a=this._timeout,c=this.setTimeoutFn(()=>{s(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(s),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(R(e,"ping",this.onping.bind(this)),R(e,"data",this.ondata.bind(this)),R(e,"error",this.onerror.bind(this)),R(e,"close",this.onclose.bind(this)),R(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){ie(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new an(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const q={};function he(r,e){typeof r=="object"&&(e=r,r=void 0),e=e||{};const t=Cr(r,e.path||"/socket.io"),n=t.source,s=t.id,i=t.path,o=q[s]&&i in q[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let c;return a?c=new Ne(n,e):(q[s]||(q[s]=new Ne(n,e)),c=q[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}Object.assign(he,{Manager:Ne,Socket:an,io:he,connect:he});class Lr{constructor(e){this.config=e,this.socket=null,this.callbacks={onMessage:null,onExistingPeers:null,onYouJoined:null,onUserJoined:null,onUserLeft:null,onPeerMediaStateChange:null,onError:null},this.rawListeners=new Map}connect(e){let t=this.config.socketUrl,n="/socket.io/";try{const i=new URL(this.config.socketUrl);t=`${i.protocol}//${i.host}`;const o=i.pathname.replace(/\/+$/,"");o&&(n=`${o}/socket.io/`)}catch{}this.socket=he(t,{path:n,auth:{workspace:e},transports:["websocket","polling"]}),this.socket.on("connect",()=>{console.log("Socket connected")}),this.socket.on("disconnect",()=>{console.log("Socket disconnected")}),this.socket.on("new-message",i=>{this.callbacks.onMessage&&this.callbacks.onMessage(i)}),this.socket.on("existing-peers",i=>{this.callbacks.onExistingPeers&&this.callbacks.onExistingPeers(i)}),this.socket.on("you-joined",i=>{this.callbacks.onYouJoined&&this.callbacks.onYouJoined(i)}),this.socket.on("user-joined",i=>{this.callbacks.onUserJoined&&this.callbacks.onUserJoined(i)}),this.socket.on("user-left",i=>{this.callbacks.onUserLeft&&this.callbacks.onUserLeft(i)}),this.socket.on("peer-media-state-change",i=>{this.callbacks.onPeerMediaStateChange&&this.callbacks.onPeerMediaStateChange(i)});const s=["code-changed","code-language-changed","code-executing","code-execution-result","code-state-sync","code-permission-changed","code-sandbox-toggled","whiteboard-drawing","whiteboard-cleared","whiteboard-image-uploaded","whiteboard-state-sync","whiteboard-permission-changed","whiteboard-toggled"];for(const i of s)this.socket.on(i,o=>{const a=this.rawListeners&&this.rawListeners.get(i);a&&a.forEach(c=>{try{c(o)}catch(h){console.warn(h)}})});this.socket.on("error",i=>{console.error("Socket error:",i),this.callbacks.onError&&this.callbacks.onError(i)})}joinRoom(e,t,n,s){this.socket&&this.socket.emit("join-room",{roomId:e,userId:t,userName:n,peerId:s})}emitMediaState(e,t,n,s){this.socket&&this.socket.emit("media-state-change",{roomId:e,userId:t,type:n,enabled:s})}emit(e,t){this.socket&&this.socket.emit(e,t)}onRaw(e,t){return this.rawListeners.has(e)||this.rawListeners.set(e,new Set),this.rawListeners.get(e).add(t),()=>{var n;return(n=this.rawListeners.get(e))==null?void 0:n.delete(t)}}sendMessage(e,t,n,s,i){if(this.socket){const o={roomId:e,userId:t,userName:n,message:s||""};Array.isArray(i)&&i.length&&(o.attachmentIds=i),this.socket.emit("send-message",o)}}leaveRoom(){this.socket&&this.socket.emit("leave-room")}on(e,t){this.callbacks.hasOwnProperty("on"+e.charAt(0).toUpperCase()+e.slice(1))&&(this.callbacks["on"+e.charAt(0).toUpperCase()+e.slice(1)]=t)}disconnect(){this.socket&&(this.socket.close(),this.socket=null)}}class $r{constructor(){this.localStream=null,this.remoteStreams={}}async getLocalStream(){if(this.localStream)return this.localStream;try{return this.localStream=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0}),this.localStream}catch(e){throw console.error("Failed to get media devices:",e),e}}addRemoteStream(e,t){this.remoteStreams[e]=t}removeRemoteStream(e){delete this.remoteStreams[e]}toggleVideo(){if(this.localStream){const e=this.localStream.getVideoTracks()[0];if(e)return e.enabled=!e.enabled,e.enabled}return!1}toggleAudio(){if(this.localStream){const e=this.localStream.getAudioTracks()[0];if(e)return e.enabled=!e.enabled,e.enabled}return!1}stopLocalStream(){this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null)}cleanup(){this.stopLocalStream(),this.remoteStreams={}}}class ze{constructor(){this.recorder=null,this.stream=null,this.state="idle",this.startedAt=null,this.seq=0,this.pendingUploads=[],this.callbacks={onStateChange:null,onChunk:null}}static isSupported(){return typeof window<"u"&&typeof window.MediaRecorder<"u"}pickMimeType(){const e=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm","video/mp4"];for(const t of e)if(window.MediaRecorder.isTypeSupported(t))return t;return""}setState(e){this.state=e,this.callbacks.onStateChange&&this.callbacks.onStateChange(e)}on(e,t){e==="stateChange"?this.callbacks.onStateChange=t:e==="chunk"&&(this.callbacks.onChunk=t)}start(e,t={}){if(!ze.isSupported())throw new Error("MediaRecorder API not supported in this browser");if(this.state==="recording")return;if(!e)throw new Error("stream is required to start recording");const n=t.timesliceMs||15e3,s=Number.isFinite(t.videoBitsPerSecond)?t.videoBitsPerSecond:1e6,i=Number.isFinite(t.audioBitsPerSecond)?t.audioBitsPerSecond:64e3;t.onChunk&&(this.callbacks.onChunk=t.onChunk),this.stream=e,this.seq=typeof t.startSeq=="number"?t.startSeq:0,this.pendingUploads=[];const o=this.pickMimeType(),a={videoBitsPerSecond:s,audioBitsPerSecond:i};o&&(a.mimeType=o),this.recorder=new window.MediaRecorder(e,a),this.mimeType=this.recorder.mimeType||o||"video/webm",this.recorder.ondataavailable=c=>{if(!c.data||c.data.size===0)return;const h=this.seq++,l=c.data,d=this.callbacks.onChunk;if(!d)return;const u=Promise.resolve().then(()=>d(l,h)).catch(p=>{console.warn(`Recording chunk seq=${h} upload failed:`,p&&p.message)});this.pendingUploads.push(u)},this.recorder.onerror=c=>{console.error("MediaRecorder error:",c)},this.startedAt=new Date,this.recorder.start(n),this.setState("recording")}async stop(){if(this.state!=="recording"||!this.recorder)return null;await new Promise(i=>{this.recorder.onstop=i,this.recorder.stop()});const t=(await Promise.allSettled(this.pendingUploads)).filter(i=>i.status==="rejected").length,n=new Date,s={startedAt:this.startedAt,endedAt:n,mimeType:this.mimeType,totalChunks:this.seq,droppedChunks:t};return this.recorder=null,this.stream=null,this.startedAt=null,this.pendingUploads=[],this.setState("stopped"),s}isRecording(){return this.state==="recording"||this.state==="paused"}isPaused(){return this.state==="paused"}pause(){if(!this.recorder||this.state!=="recording")return!1;try{return this.recorder.pause(),this.setState("paused"),!0}catch{return!1}}resume(){if(!this.recorder||this.state!=="paused")return!1;try{return this.recorder.resume(),this.setState("recording"),!0}catch{return!1}}}class Fe{constructor(e={}){this.width=e.width||1280,this.height=e.height||720,this.fps=e.fps||30,this.canvas=null,this.ctx=null,this.videos=new Map,this.audioContext=null,this.audioDestination=null,this.audioSources=new Map,this.combinedStream=null,this.animationHandle=null,this.running=!1}static isSupported(){return typeof window<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLCanvasElement.prototype.captureStream=="function"&&typeof(window.AudioContext||window.webkitAudioContext)<"u"}async start(){if(this.running)return this.combinedStream;if(!Fe.isSupported())throw new Error("Composite recording requires canvas.captureStream + AudioContext");this.canvas=document.createElement("canvas"),this.canvas.width=this.width,this.canvas.height=this.height,this.canvas.style.cssText="position:absolute;left:-9999px;top:-9999px;",document.body.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.audioContext.state==="suspended")try{await this.audioContext.resume()}catch{}this.audioDestination=this.audioContext.createMediaStreamDestination();const t=this.canvas.captureStream(this.fps);this.combinedStream=new MediaStream;for(const n of t.getVideoTracks())this.combinedStream.addTrack(n);for(const n of this.audioDestination.stream.getAudioTracks())this.combinedStream.addTrack(n);return this.running=!0,this.tick(),this.combinedStream}tick(){this.running&&(this.draw(),this.animationHandle=requestAnimationFrame(()=>this.tick()))}draw(){if(!this.ctx)return;this.ctx.fillStyle="#0d0d0d",this.ctx.fillRect(0,0,this.width,this.height);const e=Array.from(this.videos.values());if(e.length===0)return;const{cols:t,rows:n}=zr(e.length),s=this.width/t,i=this.height/n;e.forEach((o,a)=>{const c=a%t,h=Math.floor(a/t),l=c*s,d=h*i;this.ctx.fillStyle="#1a1a1a",this.ctx.fillRect(l,d,s,i);const u=o.videoEl.videoWidth||0,p=o.videoEl.videoHeight||0,m=o.videoTrack,_=m&&m.enabled&&m.readyState==="live";if(u>0&&p>0&&_!==!1){const pn=Math.min(s/u,i/p),gn=u*pn,mn=p*pn,Xr=l+(s-gn)/2,Zr=d+(i-mn)/2;try{this.ctx.drawImage(o.videoEl,Xr,Zr,gn,mn)}catch{}}else Nr(this.ctx,o.label||"Peer",l,d,s,i);const ln=o.label||"Peer";this.ctx.font="bold 16px system-ui, sans-serif";const Yr=this.ctx.measureText(ln),dn=10,Gr=6,Qr=Yr.width+dn*2,Ke=24,un=l+12,fn=d+i-Ke-12;this.ctx.fillStyle="rgba(0,0,0,0.65)",this.ctx.fillRect(un,fn,Qr,Ke),this.ctx.fillStyle="#fff",this.ctx.fillText(ln,un+dn,fn+Ke-Gr-2)})}addStream(e,t,n={}){if(!this.running)return;this.videos.has(e)&&this.removeStream(e);const s=document.createElement("video");s.srcObject=t,s.autoplay=!0,s.muted=!0,s.playsInline=!0,s.style.cssText="position:absolute;left:-9999px;top:-9999px;",document.body.appendChild(s),s.play().catch(()=>{});const i=t.getVideoTracks()[0]||null;this.videos.set(e,{videoEl:s,videoTrack:i,label:n.label||(n.isLocal?"You":e)});const o=t.getAudioTracks();if(o.length&&this.audioContext)try{const a=new MediaStream([o[0]]),c=this.audioContext.createMediaStreamSource(a),h=this.audioContext.createGain();h.gain.value=1,c.connect(h).connect(this.audioDestination),this.audioSources.set(e,{source:c,gain:h})}catch(a){console.warn("Compositor audio source failed for",e,a&&a.message)}}removeStream(e){const t=this.videos.get(e);t&&(t.videoEl.pause(),t.videoEl.srcObject=null,t.videoEl.remove(),this.videos.delete(e));const n=this.audioSources.get(e);if(n){try{n.source.disconnect()}catch{}try{n.gain.disconnect()}catch{}this.audioSources.delete(e)}}getStream(){return this.combinedStream}stop(){if(this.running){this.running=!1,this.animationHandle&&cancelAnimationFrame(this.animationHandle),this.animationHandle=null;for(const e of Array.from(this.videos.keys()))this.removeStream(e);this.combinedStream&&(this.combinedStream.getTracks().forEach(e=>{try{e.stop()}catch{}}),this.combinedStream=null),this.audioContext&&(this.audioContext.close().catch(()=>{}),this.audioContext=null),this.canvas&&(this.canvas.remove(),this.canvas=null,this.ctx=null)}}}function Br(r){const e=String(r).trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[e.length-1][0]).toUpperCase()}function Ur(r){let e=0;const t=String(r);for(let s=0;s<t.length;s++)e=e*31+t.charCodeAt(s)>>>0;return`hsl(${e%360}, 45%, 40%)`}function Nr(r,e,t,n,s,i){const o=t+s/2,a=n+i/2,c=Math.min(s,i)*.22;r.fillStyle=Ur(e),r.beginPath(),r.arc(o,a,c,0,Math.PI*2),r.fill(),r.fillStyle="#fff",r.font=`600 ${Math.floor(c)}px system-ui, sans-serif`,r.textAlign="center",r.textBaseline="middle",r.fillText(Br(e),o,a+1),r.textAlign="start",r.textBaseline="alphabetic"}function zr(r){if(r<=1)return{cols:1,rows:1};if(r===2)return{cols:2,rows:1};if(r<=4)return{cols:2,rows:2};if(r<=6)return{cols:3,rows:2};if(r<=9)return{cols:3,rows:3};const e=4;return{cols:e,rows:Math.ceil(r/e)}}function Fr(r,e){return r.includes("pdf")||/\.pdf$/i.test(e)?"📕":r.includes("word")||/\.docx?$/i.test(e)?"📘":r.includes("sheet")||r.includes("excel")||/\.(xlsx?|csv)$/i.test(e)?"📗":r.startsWith("text/")?"📄":"📎"}class jr{constructor(e={}){this.container=null,this.videoElements={},this.chatMessages=[],this.recording=e.recording||"off",this.screenShare=e.screenShare!==!1,this.enabledPanels=new Set(Array.isArray(e.panels)&&e.panels.length?e.panels:["chat"]),this.enabledPanels.add("chat"),this.activePanel="chat",this.panelSlots={}}mount(e){if(typeof e=="string"?this.container=document.querySelector(e):e instanceof Element&&(this.container=e),!this.container)throw new Error(`Container not found: ${e}`);this.render()}render(){const e=this.recording==="manual"?'<button id="toggle-record" style="padding: 10px 20px; background-color: #7a3a3a; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px;">● Record</button>':"",t=this.recording!=="off"?'<button id="toggle-pause" style="display:none; padding: 10px 20px; background-color: #3a5a7a; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px;">⏸ Pause</button>':"",n=this.screenShare?'<button id="toggle-screenshare" style="padding: 10px 20px; background-color: #3a5a7a; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px;">Share Screen</button>':"",s=this.recording!=="off"?'<span id="recording-indicator" style="display:none; margin-left: 12px; color: #ff5252; font-size: 13px; font-weight: 600;"><span id="rec-dot" style="display:inline-block; width:8px; height:8px; background:#ff5252; border-radius:50%; margin-right:6px; animation: recPulse 1.2s ease-in-out infinite;"></span>REC <span id="rec-elapsed">00:00</span></span>':"",i=this.recording!=="off"?'<span id="queue-indicator" style="display:none; margin-left: 12px; color: #fbbf24; font-size: 12px;">⏳ <span id="queue-count">0</span> uploading</span>':"";this._panelWiredOnRender=!0,this.container.innerHTML=`
|
|
42
42
|
<style>
|
|
43
43
|
@keyframes recPulse { 0%,100%{opacity:1} 50%{opacity:0.3} }
|
|
44
44
|
</style>
|
|
@@ -156,7 +156,7 @@ a=extmap-allow-mixed`)!==-1){const i=s.sdp.split(`
|
|
|
156
156
|
<div id="cs-output" class="cs-output" style="display:none;"></div>
|
|
157
157
|
<div id="cs-status" class="cs-status"></div>
|
|
158
158
|
`,this.langSel=this.container.querySelector("#cs-lang"),this.editor=this.container.querySelector("#cs-editor"),this.runBtn=this.container.querySelector("#cs-run"),this.output=this.container.querySelector("#cs-output"),this.status=this.container.querySelector("#cs-status"),this.permNote=this.container.querySelector("#cs-permission-note"),this.langSel.addEventListener("change",()=>{this.state.language=this.langSel.value,this.emit("code-language-change",{language:this.state.language})}),this.editor.addEventListener("input",()=>{if(!this.canEdit()){this.editor.value=this.state.code;return}this.state.code=this.editor.value,!this._broadcastTimer&&(this._broadcastTimer=setTimeout(()=>{this._broadcastTimer=null,this.emit("code-change",{code:this.state.code})},250))}),this.runBtn.addEventListener("click",()=>{this.canRun()&&(this.setStatus("Running…"),this.emit("code-execute",{code:this.state.code,language:this.state.language}),this.state.running=!0,this.runBtn.disabled=!0)}),this.refreshPermissionUI()}refreshPermissionUI(){const e=this.canEdit();this.editor.readOnly=!e,this.editor.style.opacity=e?"1":"0.7",this.editor.style.cursor=e?"text":"not-allowed",this.runBtn.disabled=!this.canRun()||this.state.running,this.permNote.textContent=e?"":"Read-only — request edit access from the host"}setStatus(e){this.status.textContent=e||""}handleCodeChanged(e){if(!(e.userId&&e.userId===this.userId)&&(this.state.code=e.code||"",this.editor.value!==this.state.code)){const t=this.editor.selectionStart;this.editor.value=this.state.code;try{this.editor.setSelectionRange(t,t)}catch{}}}handleLanguageChanged(e){!e||!e.language||(this.state.language=e.language,this.langSel.value=e.language)}handleExecuting(e){this.state.running=!0,this.runBtn.disabled=!0,this.setStatus(`Running (by ${e.userId||"someone"})…`)}handleExecutionResult(e){this.state.running=!1,this.output.style.display="block";const t=e.stdout||"",n=e.stderr||"",s=[];t&&s.push(`<span style="color:#e5e7eb;">${cn(t)}</span>`),n&&s.push(`<span style="color:#f87171;">${cn(n)}</span>`),!t&&!n&&s.push('<span style="color:#888;">(no output)</span>'),this.output.innerHTML=s.join(`
|
|
159
|
-
`);const i=typeof e.time=="number"||typeof e.time=="string"&&e.time?` · ${e.time}s`:"",o=e.memory?` · ${Math.round(e.memory/1024)} MB`:"";this.setStatus(`Exit ${e.exitCode??0}${i}${o}`),this.refreshPermissionUI()}handleStateSync(e){e&&(typeof e.code=="string"&&e.code!==this.state.code&&(this.state.code=e.code,this.editor.value=e.code),e.language&&(this.state.language=e.language,this.langSel.value=e.language),e.lastExecutionOutput&&this.handleExecutionResult(e.lastExecutionOutput),this.refreshPermissionUI())}}function cn(r){return String(r).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}class
|
|
159
|
+
`);const i=typeof e.time=="number"||typeof e.time=="string"&&e.time?` · ${e.time}s`:"",o=e.memory?` · ${Math.round(e.memory/1024)} MB`:"";this.setStatus(`Exit ${e.exitCode??0}${i}${o}`),this.refreshPermissionUI()}handleStateSync(e){e&&(typeof e.code=="string"&&e.code!==this.state.code&&(this.state.code=e.code,this.editor.value=e.code),e.language&&(this.state.language=e.language,this.langSel.value=e.language),e.lastExecutionOutput&&this.handleExecutionResult(e.lastExecutionOutput),this.refreshPermissionUI())}}function cn(r){return String(r).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}class Vr{constructor(e){this.container=e.container,this.emit=e.emit,this.canDraw=e.canDraw||(()=>!0),this.userId=e.userId,this.tool="pen",this.color="#ffffff",this.size=3,this.imageData=null,this.remoteStrokes=[],this.currentStroke=null,this.render()}render(){this.container.innerHTML=`
|
|
160
160
|
<style>
|
|
161
161
|
.wb-topbar { display:flex; flex-wrap:wrap; gap:6px; padding:8px 10px; border-bottom:1px solid #333; align-items:center; }
|
|
162
162
|
.wb-btn { padding:6px 10px; border-radius:4px; border:1px solid #333; background:#262626; color:#eee; cursor:pointer; font-size:12px; }
|
|
@@ -186,4 +186,4 @@ a=extmap-allow-mixed`)!==-1){const i=s.sdp.split(`
|
|
|
186
186
|
<canvas id="wb-canvas" class="wb-canvas"></canvas>
|
|
187
187
|
</div>
|
|
188
188
|
<div class="wb-note" id="wb-note"></div>
|
|
189
|
-
`,this.canvas=this.container.querySelector("#wb-canvas"),this.wrap=this.container.querySelector("#wb-wrap"),this.ctx=this.canvas.getContext("2d"),this.note=this.container.querySelector("#wb-note"),this._resize=this._resize.bind(this),requestAnimationFrame(()=>{this._resize(),this._replay()}),window.addEventListener("resize",this._resize),this._resizeObserver=null,typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._resize()),this._resizeObserver.observe(this.wrap)),this.container.querySelectorAll(".wb-tool").forEach(e=>{e.addEventListener("click",()=>{this.tool=e.getAttribute("data-tool"),this.container.querySelectorAll(".wb-tool").forEach(t=>t.classList.toggle("active",t===e))})}),this.container.querySelectorAll(".wb-swatch").forEach(e=>{e.addEventListener("click",()=>{this.color=e.getAttribute("data-color"),this.container.querySelectorAll(".wb-swatch").forEach(t=>t.classList.toggle("active",t===e)),this.tool="pen",this.container.querySelectorAll(".wb-tool").forEach(t=>t.classList.toggle("active",t.getAttribute("data-tool")==="pen"))})}),this.container.querySelector("#wb-size").addEventListener("input",e=>{this.size=parseInt(e.target.value,10)||3}),this.container.querySelector("#wb-clear").addEventListener("click",()=>{this.canDraw()&&(this.emit("whiteboard-clear",{}),this._clearLocal())}),this.canvas.addEventListener("pointerdown",e=>this._onDown(e)),this.canvas.addEventListener("pointermove",e=>this._onMove(e)),this.canvas.addEventListener("pointerup",()=>this._onUp()),this.canvas.addEventListener("pointerleave",()=>this._onUp()),this.refreshPermissionUI()}refreshPermissionUI(){const e=this.canDraw();this.canvas.style.pointerEvents=e?"auto":"none",this.note.textContent=e?"":"View-only — request draw access from the host"}_resize(){if(!this.canvas||!this.wrap)return;const e=this.wrap.getBoundingClientRect(),t=window.devicePixelRatio||1;this.canvas.width=Math.max(300,Math.floor(e.width*t)),this.canvas.height=Math.max(200,Math.floor(e.height*t)),this.ctx.setTransform(t,0,0,t,0,0),this._replay()}_pointerCoords(e){const t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width,y:(e.clientY-t.top)/t.height}}_drawSegment(e,t,n,s,i){const o=this.canvas.getBoundingClientRect().width,a=this.canvas.getBoundingClientRect().height;this.ctx.lineWidth=i,this.ctx.lineCap="round",this.ctx.lineJoin="round",this.ctx.globalCompositeOperation=n==="eraser"?"destination-out":"source-over",this.ctx.strokeStyle=n==="eraser"?"rgba(0,0,0,1)":s,this.ctx.beginPath(),this.ctx.moveTo(e.x*o,e.y*a),this.ctx.lineTo(t.x*o,t.y*a),this.ctx.stroke()}_onDown(e){if(!this.canDraw())return;e.preventDefault(),this.canvas.setPointerCapture(e.pointerId);const t=this._pointerCoords(e);this.currentStroke={tool:this.tool,color:this.color,size:this.size,points:[t]}}_onMove(e){if(!this.currentStroke)return;const t=this._pointerCoords(e),n=this.currentStroke.points[this.currentStroke.points.length-1];this._drawSegment(n,t,this.currentStroke.tool,this.currentStroke.color,this.currentStroke.size),this.currentStroke.points.push(t)}_onUp(){if(!this.currentStroke||this.currentStroke.points.length<2){this.currentStroke=null;return}const e=this.currentStroke;this.currentStroke=null,this.remoteStrokes.push(e),this.emit("whiteboard-draw",{drawing:e})}_clearLocal(){this.remoteStrokes=[],this.imageData=null,this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}_replay(){if(this.ctx){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.imageData&&this._drawBackground();for(const e of this.remoteStrokes){const t=e.points||[];for(let n=1;n<t.length;n++)this._drawSegment(t[n-1],t[n],e.tool,e.color,e.size)}}}_drawBackground(){if(!this.imageData)return;const e=new Image;e.onload=()=>{const t=this.canvas.getBoundingClientRect().width,n=this.canvas.getBoundingClientRect().height;this.ctx.globalCompositeOperation="source-over",this.ctx.drawImage(e,0,0,t,n)},e.src=this.imageData}handleDrawing(e){if(e.userId&&e.userId===this.userId||!e.drawing)return;this.remoteStrokes.push(e.drawing);const t=e.drawing.points||[];for(let n=1;n<t.length;n++)this._drawSegment(t[n-1],t[n],e.drawing.tool,e.drawing.color,e.drawing.size)}handleCleared(){this._clearLocal()}handleImageUploaded(e){this.imageData=e.imageData||null,this._replay()}handleStateSync(e){e&&(this.imageData=e.imageData||null,this.remoteStrokes=Array.isArray(e.drawings)?e.drawings.slice():[],this._replay(),this.refreshPermissionUI())}destroy(){window.removeEventListener("resize",this._resize),this._resizeObserver&&this._resizeObserver.disconnect()}}const Vr=new Set(["auto","manual","off"]),Kr=new Set(["local","composite"]),Jr="https://preproduction.tentoro.in/videocall";function Wr(r){const e=new URL(r),t=e.protocol==="https:",n=e.pathname.replace(/\/+$/,"");return{host:e.hostname,port:e.port?parseInt(e.port,10):t?443:80,path:`${n}/peerjs`,secure:t}}class hn{constructor(){this.config=null,this.peerManager=null,this.socketManager=null,this.mediaManager=null,this.uiManager=null,this.isInitialized=!1,this.currentRoom=null,this.currentUser=null}init(e){if(!e||!e.workspace||!e.roomId||!e.user)throw new Error("workspace, roomId, and user are required");const t=e.host||Jr,n=Vr.has(e.recording)?e.recording:"off",s=n!=="off"&&!!e.transcribe,i=s&&!!e.summarize,o=e.recordOnlyIfHost!==!1,a=Kr.has(e.recordingMode)?e.recordingMode:"local",c=Number.isFinite(e.compositeWidth)?e.compositeWidth:1280,h=Number.isFinite(e.compositeHeight)?e.compositeHeight:720,l=Number.isFinite(e.compositeFps)?e.compositeFps:30,d=["chat","code","whiteboard"],u=Array.isArray(e.panels)&&e.panels.length?e.panels.filter(p=>d.includes(p)):["chat"];u.includes("chat")||u.unshift("chat"),this.config={...e,host:t,apiUrl:e.apiUrl||`${t}/api`,socketUrl:e.socketUrl||t,peerServer:e.peerServer||Wr(t),ai:{...e.ai||{}},recording:n,transcribe:s,summarize:i,recordOnlyIfHost:o,recordingMode:a,compositeWidth:c,compositeHeight:h,compositeFps:l,panels:u},this.myRole=null,this.roleResolvers=[],this.currentRoom=this.config.roomId,this.currentUser=this.config.user,this.peerManager=new Fn(this.config),this.socketManager=new Lr(this.config),this.mediaManager=new $r,this.uiManager=new jr({recording:n,screenShare:e.screenShare!==!1,panels:u}),this.recorder=n==="off"?null:new ze,this.compositor=null,this.setupEventHandlers(),this.isInitialized=!0,console.log("MeetSDK initialized")}setupEventHandlers(){this.peerManager.on("stream",(e,t,n)=>{const s=this.labelForPeer(e,n);this.mediaManager.addRemoteStream(e,t),this.uiManager.addVideoStream(e,t,n,s),this.compositor&&this.compositor.addStream(e,t,{isLocal:n,label:s}),this.refreshParticipantsPanel()}),this.peerManager.on("peerLeft",e=>{this.mediaManager.removeRemoteStream(e),this.uiManager.removeVideoStream(e),this.compositor&&this.compositor.removeStream(e),this.refreshParticipantsPanel()}),this.socketManager.on("message",e=>{this.uiManager.addChatMessage(e)}),this.peerLabels=new Map,this.socketManager.on("existingPeers",e=>{e.forEach(t=>{this.peerLabels.set(t.peerId,t.userName||t.userId),this.peerManager.callPeer(t.peerId)})}),this.socketManager.on("userJoined",e=>{this.peerLabels.set(e.peerId,e.userName||e.userId),this.uiManager.updateVideoStreamLabel(e.peerId,e.userName||e.userId),this.peerManager.callPeer(e.peerId),this.refreshParticipantsPanel()}),this.socketManager.on("userLeft",e=>{const t=e.peerId||e.userId;this.mediaManager.removeRemoteStream(t),this.uiManager.removeVideoStream(t),this.compositor&&t&&this.compositor.removeStream(t),e.peerId&&this.peerLabels.delete(e.peerId),this.refreshParticipantsPanel()}),this.socketManager.on("peerMediaStateChange",e=>{if(!e||!e.userId||e.type!=="screen")return;let t=null;for(const[n]of this.peerLabels.entries())if(n.endsWith(`-${e.userId}`)){t=n;break}t&&(e.enabled?this.setPresentingPeer(t):this.presentingPeerId===t&&this.setPresentingPeer(null))}),this.socketManager.on("youJoined",e=>{if(this.myRole=e&&e.role?e.role:"candidate",e&&e.hostId){for(const[n]of this.peerLabels.entries())if(n.endsWith(`-${e.hostId}`)){this.hostPeerId=n;break}}const t=this.roleResolvers;this.roleResolvers=[];for(const n of t)n(this.myRole);this.refreshParticipantsPanel()})}labelForPeer(e,t){return t?this.currentUser&&this.currentUser.name?this.currentUser.name:"You":this.peerLabels&&this.peerLabels.has(e)?this.peerLabels.get(e):e}setPresentingPeer(e){this.presentingPeerId=e||null,this.uiManager&&this.uiManager.setPresentingPeer&&this.uiManager.setPresentingPeer(this.presentingPeerId),this.refreshParticipantsPanel()}refreshParticipantsPanel(){if(!this.uiManager)return;const e=[];if(this.currentUser&&e.push({label:this.currentUser.name||"You",isYou:!0,isHost:this.myRole==="organizer",isSharing:this.peerManager&&this.peerManager.isScreenSharing&&this.peerManager.isScreenSharing()}),this.peerLabels)for(const[t,n]of this.peerLabels.entries())e.push({label:n,isYou:!1,isHost:this.hostPeerId===t,isSharing:this.presentingPeerId===t});this.uiManager.setParticipants(e)}waitForRole(e=3e3){return this.myRole?Promise.resolve(this.myRole):new Promise(t=>{const n=setTimeout(()=>t(this.myRole||"candidate"),e);this.roleResolvers.push(s=>{clearTimeout(n),t(s)})})}async mount(e){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");this.uiManager.mount(e);const t=`${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;await this.peerManager.initialize(t);const n=await this.peerManager.getLocalStream();if(this.uiManager.addVideoStream("local",n,!0),this.config.recordingMode==="composite"&&this.recorder)try{this.compositor=new Fe({width:this.config.compositeWidth,height:this.config.compositeHeight,fps:this.config.compositeFps}),await this.compositor.start(),this.compositor.addStream("local",n,{isLocal:!0,label:this.labelForPeer("local",!0)})}catch(s){console.warn("Composite recording unavailable, falling back to local:",s.message),this.compositor=null}this.socketManager.connect(this.config.workspace),setTimeout(()=>{this.socketManager.joinRoom(this.currentRoom,this.currentUser.id,this.currentUser.name,t)},500),this.setupUIControls(),this.setupRecording(n).catch(s=>console.error("setupRecording failed:",s)),this.setupCollabPanels(),this.fetchChatHistory().then(s=>{s&&s.messages&&this.uiManager.setChatHistory(s.messages)}).catch(s=>console.warn("Chat history fetch failed:",s&&s.message)),console.log("MeetSDK mounted")}setupCollabPanels(){if(this.uiManager&&!this.uiManager._panelWired&&(this.uiManager.wirePanelTabs(),this.uiManager._panelWired=!0),this.config.panels.includes("code")){const e=this.uiManager.getPanelSlot("code");e&&(this.codeSandbox=new qr({container:e,userId:this.currentUser.id,canEdit:()=>this._canEditCode(),canRun:()=>this._canEditCode(),emit:(t,n)=>{this.socketManager.emit(t,{roomId:this.currentRoom,userId:this.currentUser.id,userName:this.currentUser.name,...n})}}),this.socketManager.onRaw("code-changed",t=>this.codeSandbox.handleCodeChanged(t)),this.socketManager.onRaw("code-language-changed",t=>this.codeSandbox.handleLanguageChanged(t)),this.socketManager.onRaw("code-executing",t=>this.codeSandbox.handleExecuting(t)),this.socketManager.onRaw("code-execution-result",t=>this.codeSandbox.handleExecutionResult(t)),this.socketManager.onRaw("code-state-sync",t=>{if(t&&Array.isArray(t.editPermissions)){const n=t.editPermissions.find(s=>s.userId===this.currentUser.id);this._codeEditPermission=!!(n&&n.canEdit)}this.codeSandbox.handleStateSync(t)}),this.socketManager.onRaw("code-permission-changed",t=>{if(t&&t.targetUserId===this.currentUser.id&&(this._codeEditPermission=!!t.canEdit),Array.isArray(t&&t.editPermissions)){const n=t.editPermissions.find(s=>s.userId===this.currentUser.id);n&&(this._codeEditPermission=!!n.canEdit)}this.codeSandbox.refreshPermissionUI()}),this.socketManager.emit("code-state-request",{roomId:this.currentRoom}))}if(this.config.panels.includes("whiteboard")){const e=this.uiManager.getPanelSlot("whiteboard");e&&(this.whiteboard=new Hr({container:e,userId:this.currentUser.id,canDraw:()=>this._canDrawWhiteboard(),emit:(t,n)=>{this.socketManager.emit(t,{roomId:this.currentRoom,userId:this.currentUser.id,userName:this.currentUser.name,...n})}}),this.socketManager.onRaw("whiteboard-drawing",t=>this.whiteboard.handleDrawing(t)),this.socketManager.onRaw("whiteboard-cleared",()=>this.whiteboard.handleCleared()),this.socketManager.onRaw("whiteboard-image-uploaded",t=>this.whiteboard.handleImageUploaded(t)),this.socketManager.onRaw("whiteboard-state-sync",t=>{if(t&&Array.isArray(t.drawPermissions)){const n=t.drawPermissions.find(s=>s.userId===this.currentUser.id);this._whiteboardDrawPermission=!!(n&&n.canDraw)}this.whiteboard.handleStateSync(t)}),this.socketManager.onRaw("whiteboard-permission-changed",t=>{if(t&&t.targetUserId===this.currentUser.id&&(this._whiteboardDrawPermission=!!t.canDraw),Array.isArray(t&&t.drawPermissions)){const n=t.drawPermissions.find(s=>s.userId===this.currentUser.id);n&&(this._whiteboardDrawPermission=!!n.canDraw)}this.whiteboard.refreshPermissionUI()}),this.socketManager.emit("whiteboard-state-request",{roomId:this.currentRoom}))}}_canEditCode(){return this.myRole==="organizer"?!0:!!this._codeEditPermission}_canDrawWhiteboard(){return this.myRole==="organizer"?!0:!!this._whiteboardDrawPermission}async fetchChatHistory(e={}){if(!this.isInitialized)throw new Error("SDK not initialized");const t=new URLSearchParams;e.limit&&t.set("limit",String(e.limit)),e.before&&t.set("before",e.before),e.after&&t.set("after",e.after);const n=t.toString(),s=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/chat/messages${n?"?"+n:""}`,{headers:this.buildHeaders()});if(!s.ok)throw new Error(`chat/messages: HTTP ${s.status}`);return s.json()}async uploadChatAttachment(e){if(!this.isInitialized)throw new Error("SDK not initialized");const t=new FormData;t.append("file",e,e.name),t.append("userId",this.currentUser.id),t.append("userName",this.currentUser.name);const n=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/chat/attachments`,{method:"POST",headers:this.buildHeaders(),body:t});if(!n.ok){const s=await n.json().catch(()=>({}));throw new Error(s.error||`Upload failed: HTTP ${n.status}`)}return n.json()}async setupRecording(e){if(this.recorder){if(this.recorder.on("stateChange",t=>{this.uiManager.updateRecordingIndicator(t),this.uiManager.setPauseButtonVisible(t==="recording"||t==="paused"),this.uiManager.setPauseButtonState(t==="paused")}),this.uiManager.onControlClick("toggle-pause",()=>{this.recorder.isPaused()?this.recorder.resume():this.recorder.pause()}),this.config.recordOnlyIfHost&&await this.waitForRole()!=="organizer"){console.log("MeetSDK: not the host — skipping recording");return}this.config.recording==="auto"&&this.startRecording().catch(t=>console.error("Auto-record failed:",t)),this.config.recording==="manual"&&this.uiManager.onControlClick("toggle-record",async()=>{this.recorder.isRecording()?await this.stopRecording():await this.startRecording()})}}async startRecording(){if(!this.recorder)throw new Error("recording is disabled in SDK config");let e;if(this.config.recordingMode==="composite"&&this.compositor){if(e=this.compositor.getStream(),!e)throw new Error("composite stream not ready")}else if(e=this.peerManager.localStream,!e)throw new Error("local stream not ready");const t=this.readStoredSession();let n=null,s=0;if(t){const i=await this.probeSessionStatus(t.sessionId).catch(()=>null);i&&i.active?(n={sessionId:t.sessionId},s=(i.lastSeq||-1)+1,console.log(`MeetSDK: resuming recording session ${t.sessionId} at seq=${s}`)):this.clearStoredSession()}n||(n=await this.startRecordingSession(),this.persistStoredSession(n)),this.recordingSession=n,this.chunkQueue=[],this.chunkDrainerRunning=!1,this.recorder.start(e,{timesliceMs:15e3,startSeq:s,onChunk:(i,o)=>(this.enqueueChunk(n.sessionId,i,o),Promise.resolve())})}storedSessionKey(){return`meetSdk.session.${this.config.workspace}.${this.currentRoom}`}readStoredSession(){try{const e=window.localStorage.getItem(this.storedSessionKey());if(!e)return null;const t=JSON.parse(e);return Date.now()-(t.at||0)>24*60*60*1e3?null:t}catch{return null}}persistStoredSession(e){try{window.localStorage.setItem(this.storedSessionKey(),JSON.stringify({sessionId:e.sessionId,at:Date.now()}))}catch{}}clearStoredSession(){try{window.localStorage.removeItem(this.storedSessionKey())}catch{}}async probeSessionStatus(e){const t=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/status`,{headers:this.buildHeaders()});return t.ok?t.json():null}enqueueChunk(e,t,n){this.chunkQueue=this.chunkQueue||[],this.chunkQueue.push({sessionId:e,blob:t,seq:n}),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length),this.runChunkDrainer().catch(s=>console.warn("Chunk drainer error:",s&&s.message))}async runChunkDrainer(){if(!this.chunkDrainerRunning){this.chunkDrainerRunning=!0;try{for(;this.chunkQueue&&this.chunkQueue.length>0;){const e=this.chunkQueue[0];try{await this.uploadRecordingChunk(e.sessionId,e.blob,e.seq),this.chunkQueue.shift(),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length)}catch(t){if(/HTTP 404|HTTP 409/.test(String(t&&t.message))){console.warn(`Dropping chunk seq=${e.seq}: ${t.message}`),this.chunkQueue.shift(),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length);continue}const n=Math.min(3e4,1e3*Math.pow(2,this._chunkFailStreak||0));this._chunkFailStreak=(this._chunkFailStreak||0)+1,console.warn(`Chunk seq=${e.seq} failed, retrying in ${n}ms`),await new Promise(s=>setTimeout(s,n))}}this._chunkFailStreak=0}finally{this.chunkDrainerRunning=!1}}}async waitForChunkQueueEmpty(){for(;this.chunkQueue&&this.chunkQueue.length>0||this.chunkDrainerRunning;)await new Promise(e=>setTimeout(e,200))}async stopRecording(){if(!this.recorder)return null;const e=await this.recorder.stop();if(!e||!this.recordingSession)return null;const t=this.recordingSession.sessionId;this.recordingSession=null,await this.waitForChunkQueueEmpty();try{return await this.finalizeRecordingSession(t,e)}catch(n){throw console.error("Recording finalize failed:",n),n}}async startRecordingSession(){const e={recordedBy:this.currentUser.id,contentType:this.recorder.mimeType||"video/webm",transcribe:this.config.transcribe,summarize:this.config.summarize},t=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/start`,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`session/start failed: HTTP ${t.status}`);return t.json()}async uploadRecordingChunk(e,t,n){const s=new FormData;s.append("chunk",t,`chunk-${n}.webm`);const i=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/chunk?seq=${n}`,{method:"POST",headers:this.buildHeaders(),body:s});if(!i.ok)throw new Error(`chunk seq=${n}: HTTP ${i.status}`)}async finalizeRecordingSession(e,t){const n=Math.max(0,Math.round((t.endedAt-t.startedAt)/1e3)),s=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/finalize`,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify({durationSec:n,startedAt:t.startedAt.toISOString(),endedAt:t.endedAt.toISOString()})});if(!s.ok)throw new Error(`session/finalize failed: HTTP ${s.status}`);const i=await s.json();return this.clearStoredSession(),i}async listRecordings(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings`,{headers:this.buildHeaders()})).json()}async getRecording(e){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/${encodeURIComponent(e)}`,{headers:this.buildHeaders()})).json()}setupUIControls(){let e=!0,t=!0;this.uiManager.onControlClick("toggle-video",()=>{e=this.peerManager.toggleVideo(),this.uiManager.updateButtonState("toggle-video",e?"Video On":"Video Off")}),this.uiManager.onControlClick("toggle-audio",()=>{t=this.peerManager.toggleAudio(),this.uiManager.updateButtonState("toggle-audio",t?"Mic On":"Mic Off")}),this.uiManager.onControlClick("leave-meeting",()=>{this.leave()}),this.uiManager.onControlClick("toggle-screenshare",async()=>{try{if(this.peerManager.isScreenSharing())await this.peerManager.stopScreenShare(),this.uiManager.setScreenSharingState(!1),this.socketManager.emitMediaState(this.currentRoom,this.currentUser.id,"screen",!1),this.setPresentingPeer(null);else{await this.peerManager.startScreenShare(),this.uiManager.setScreenSharingState(!0),this.socketManager.emitMediaState(this.currentRoom,this.currentUser.id,"screen",!0);const n=`${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;this.setPresentingPeer(n)}}catch(n){console.warn("Screen share toggle failed:",n&&n.message)}}),this.uiManager.onChatSend((n,s)=>{this.socketManager.sendMessage(this.currentRoom,this.currentUser.id,this.currentUser.name,n,s)}),this.uiManager.onAttachFile(async n=>this.uploadChatAttachment(n))}buildHeaders(e={}){const t=this.config.ai||{},n={workspace:this.config.workspace,...e};return t.whisperKey&&(n["x-whisper-key"]=t.whisperKey),t.whisperUrl&&(n["x-whisper-url"]=t.whisperUrl),t.llmKey&&(n["x-llm-key"]=t.llmKey),t.llmUrl&&(n["x-llm-url"]=t.llmUrl),t.llmModel&&(n["x-llm-model"]=t.llmModel),n}setAiConfig(e={}){if(!this.config)throw new Error("SDK not initialized");this.config.ai={...this.config.ai||{},...e}}async getSummary(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/summary`,{headers:this.buildHeaders()})).json()}async generateSummary(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/summary/generate`,{method:"POST",headers:this.buildHeaders()})).json()}async transcribeAudio(e,t="audio.webm"){if(!this.isInitialized)throw new Error("SDK not initialized");const n=new FormData;return n.append("audio",e,t),(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/transcribe`,{method:"POST",headers:this.buildHeaders(),body:n})).json()}grantCodeEdit(e,t,n=!0){this.socketManager.emit("code-permission-change",{roomId:this.currentRoom,userId:this.currentUser.id,targetUserId:e,targetUserName:t||e,canEdit:!!n})}grantWhiteboardDraw(e,t,n=!0){this.socketManager.emit("whiteboard-permission-change",{roomId:this.currentRoom,userId:this.currentUser.id,targetUserId:e,targetUserName:t||e,canDraw:!!n})}async leave(){if(this.recorder&&this.recorder.isRecording())try{this.uiManager.setUploadingIndicator(!0),await this.stopRecording()}catch(e){console.warn("Recording upload on leave failed:",e)}finally{this.uiManager.setUploadingIndicator(!1)}if(this.socketManager.leaveRoom(),this.socketManager.disconnect(),this.peerManager.disconnect(),this.mediaManager.cleanup(),this.uiManager.destroy(),this.compositor){try{this.compositor.stop()}catch{}this.compositor=null}this.isInitialized=!1,console.log("Left meeting")}}typeof window<"u"&&(window.MeetSDK=new hn),x.default=hn,Object.defineProperties(x,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
189
|
+
`,this.canvas=this.container.querySelector("#wb-canvas"),this.wrap=this.container.querySelector("#wb-wrap"),this.ctx=this.canvas.getContext("2d"),this.note=this.container.querySelector("#wb-note"),this._resize=this._resize.bind(this),requestAnimationFrame(()=>{this._resize(),this._replay()}),window.addEventListener("resize",this._resize),this._resizeObserver=null,typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._resize()),this._resizeObserver.observe(this.wrap)),this.container.querySelectorAll(".wb-tool").forEach(e=>{e.addEventListener("click",()=>{this.tool=e.getAttribute("data-tool"),this.container.querySelectorAll(".wb-tool").forEach(t=>t.classList.toggle("active",t===e))})}),this.container.querySelectorAll(".wb-swatch").forEach(e=>{e.addEventListener("click",()=>{this.color=e.getAttribute("data-color"),this.container.querySelectorAll(".wb-swatch").forEach(t=>t.classList.toggle("active",t===e)),this.tool="pen",this.container.querySelectorAll(".wb-tool").forEach(t=>t.classList.toggle("active",t.getAttribute("data-tool")==="pen"))})}),this.container.querySelector("#wb-size").addEventListener("input",e=>{this.size=parseInt(e.target.value,10)||3}),this.container.querySelector("#wb-clear").addEventListener("click",()=>{this.canDraw()&&(this.emit("whiteboard-clear",{}),this._clearLocal())}),this.canvas.addEventListener("pointerdown",e=>this._onDown(e)),this.canvas.addEventListener("pointermove",e=>this._onMove(e)),this.canvas.addEventListener("pointerup",()=>this._onUp()),this.canvas.addEventListener("pointerleave",()=>this._onUp()),this.refreshPermissionUI()}refreshPermissionUI(){const e=this.canDraw();this.canvas.style.pointerEvents=e?"auto":"none",this.note.textContent=e?"":"View-only — request draw access from the host"}_resize(){if(!this.canvas||!this.wrap)return;const e=this.wrap.getBoundingClientRect(),t=window.devicePixelRatio||1;this.canvas.width=Math.max(300,Math.floor(e.width*t)),this.canvas.height=Math.max(200,Math.floor(e.height*t)),this.ctx.setTransform(t,0,0,t,0,0),this._replay()}_pointerCoords(e){const t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width,y:(e.clientY-t.top)/t.height}}_drawSegment(e,t,n,s,i){const o=this.canvas.getBoundingClientRect().width,a=this.canvas.getBoundingClientRect().height;this.ctx.lineWidth=i,this.ctx.lineCap="round",this.ctx.lineJoin="round",this.ctx.globalCompositeOperation=n==="eraser"?"destination-out":"source-over",this.ctx.strokeStyle=n==="eraser"?"rgba(0,0,0,1)":s,this.ctx.beginPath(),this.ctx.moveTo(e.x*o,e.y*a),this.ctx.lineTo(t.x*o,t.y*a),this.ctx.stroke()}_onDown(e){if(!this.canDraw())return;e.preventDefault(),this.canvas.setPointerCapture(e.pointerId);const t=this._pointerCoords(e);this.currentStroke={tool:this.tool,color:this.color,size:this.size,points:[t]}}_onMove(e){if(!this.currentStroke)return;const t=this._pointerCoords(e),n=this.currentStroke.points[this.currentStroke.points.length-1];this._drawSegment(n,t,this.currentStroke.tool,this.currentStroke.color,this.currentStroke.size),this.currentStroke.points.push(t)}_onUp(){if(!this.currentStroke||this.currentStroke.points.length<2){this.currentStroke=null;return}const e=this.currentStroke;this.currentStroke=null,this.remoteStrokes.push(e),this.emit("whiteboard-draw",{drawing:e})}_clearLocal(){this.remoteStrokes=[],this.imageData=null,this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}_replay(){if(this.ctx){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.imageData&&this._drawBackground();for(const e of this.remoteStrokes){const t=e.points||[];for(let n=1;n<t.length;n++)this._drawSegment(t[n-1],t[n],e.tool,e.color,e.size)}}}_drawBackground(){if(!this.imageData)return;const e=new Image;e.onload=()=>{const t=this.canvas.getBoundingClientRect().width,n=this.canvas.getBoundingClientRect().height;this.ctx.globalCompositeOperation="source-over",this.ctx.drawImage(e,0,0,t,n)},e.src=this.imageData}handleDrawing(e){if(e.userId&&e.userId===this.userId||!e.drawing)return;this.remoteStrokes.push(e.drawing);const t=e.drawing.points||[];for(let n=1;n<t.length;n++)this._drawSegment(t[n-1],t[n],e.drawing.tool,e.drawing.color,e.drawing.size)}handleCleared(){this._clearLocal()}handleImageUploaded(e){this.imageData=e.imageData||null,this._replay()}handleStateSync(e){e&&(this.imageData=e.imageData||null,this.remoteStrokes=Array.isArray(e.drawings)?e.drawings.slice():[],this._replay(),this.refreshPermissionUI())}destroy(){window.removeEventListener("resize",this._resize),this._resizeObserver&&this._resizeObserver.disconnect()}}const Hr=new Set(["auto","manual","off"]),Kr=new Set(["local","composite"]),Jr="https://preproduction.tentoro.in/videocall";function Wr(r){const e=new URL(r),t=e.protocol==="https:",n=e.pathname.replace(/\/+$/,"");return{host:e.hostname,port:e.port?parseInt(e.port,10):t?443:80,path:`${n}/peerjs`,secure:t}}class hn{constructor(){this.config=null,this.peerManager=null,this.socketManager=null,this.mediaManager=null,this.uiManager=null,this.isInitialized=!1,this.currentRoom=null,this.currentUser=null}init(e){if(!e||!e.workspace||!e.roomId||!e.user)throw new Error("workspace, roomId, and user are required");const t=e.host||Jr,n=Hr.has(e.recording)?e.recording:"off",s=n!=="off"&&!!e.transcribe,i=s&&!!e.summarize,o=e.recordOnlyIfHost!==!1,a=Kr.has(e.recordingMode)?e.recordingMode:"local",c=Number.isFinite(e.compositeWidth)?e.compositeWidth:1280,h=Number.isFinite(e.compositeHeight)?e.compositeHeight:720,l=Number.isFinite(e.compositeFps)?e.compositeFps:30,d=Number.isFinite(e.recordingVideoBps)?e.recordingVideoBps:1e6,u=Number.isFinite(e.recordingAudioBps)?e.recordingAudioBps:64e3,p=["chat","code","whiteboard"],m=Array.isArray(e.panels)&&e.panels.length?e.panels.filter(_=>p.includes(_)):["chat"];m.includes("chat")||m.unshift("chat"),this.config={...e,host:t,apiUrl:e.apiUrl||`${t}/api`,socketUrl:e.socketUrl||t,peerServer:e.peerServer||Wr(t),ai:{...e.ai||{}},recording:n,transcribe:s,summarize:i,recordOnlyIfHost:o,recordingMode:a,compositeWidth:c,compositeHeight:h,compositeFps:l,recordingVideoBps:d,recordingAudioBps:u,panels:m},this.myRole=null,this.roleResolvers=[],this.currentRoom=this.config.roomId,this.currentUser=this.config.user,this.peerManager=new Fn(this.config),this.socketManager=new Lr(this.config),this.mediaManager=new $r,this.uiManager=new jr({recording:n,screenShare:e.screenShare!==!1,panels:m}),this.recorder=n==="off"?null:new ze,this.compositor=null,this.setupEventHandlers(),this.isInitialized=!0,console.log("MeetSDK initialized")}setupEventHandlers(){this.peerManager.on("stream",(e,t,n)=>{const s=this.labelForPeer(e,n);this.mediaManager.addRemoteStream(e,t),this.uiManager.addVideoStream(e,t,n,s),this.compositor&&this.compositor.addStream(e,t,{isLocal:n,label:s}),this.refreshParticipantsPanel()}),this.peerManager.on("peerLeft",e=>{this.mediaManager.removeRemoteStream(e),this.uiManager.removeVideoStream(e),this.compositor&&this.compositor.removeStream(e),this.refreshParticipantsPanel()}),this.socketManager.on("message",e=>{this.uiManager.addChatMessage(e)}),this.peerLabels=new Map,this.socketManager.on("existingPeers",e=>{e.forEach(t=>{this.peerLabels.set(t.peerId,t.userName||t.userId),this.peerManager.callPeer(t.peerId)})}),this.socketManager.on("userJoined",e=>{this.peerLabels.set(e.peerId,e.userName||e.userId),this.uiManager.updateVideoStreamLabel(e.peerId,e.userName||e.userId),this.peerManager.callPeer(e.peerId),this.refreshParticipantsPanel()}),this.socketManager.on("userLeft",e=>{const t=e.peerId||e.userId;this.mediaManager.removeRemoteStream(t),this.uiManager.removeVideoStream(t),this.compositor&&t&&this.compositor.removeStream(t),e.peerId&&this.peerLabels.delete(e.peerId),this.refreshParticipantsPanel()}),this.socketManager.on("peerMediaStateChange",e=>{if(!e||!e.userId||e.type!=="screen")return;let t=null;for(const[n]of this.peerLabels.entries())if(n.endsWith(`-${e.userId}`)){t=n;break}t&&(e.enabled?this.setPresentingPeer(t):this.presentingPeerId===t&&this.setPresentingPeer(null))}),this.socketManager.on("youJoined",e=>{if(this.myRole=e&&e.role?e.role:"candidate",e&&e.hostId){for(const[n]of this.peerLabels.entries())if(n.endsWith(`-${e.hostId}`)){this.hostPeerId=n;break}}const t=this.roleResolvers;this.roleResolvers=[];for(const n of t)n(this.myRole);this.refreshParticipantsPanel()})}async hydrateIceServers(){try{const e=await fetch(`${this.config.apiUrl}/rt-config`,{headers:this.buildHeaders()});if(!e.ok)return;const t=await e.json();if(!t||!Array.isArray(t.iceServers)||t.iceServers.length===0)return;const n=Array.isArray(this.config.iceServers)?this.config.iceServers:[];this.config.iceServers=[...n,...t.iceServers]}catch(e){console.warn("rt-config fetch failed, using STUN defaults:",e&&e.message)}}labelForPeer(e,t){return t?this.currentUser&&this.currentUser.name?this.currentUser.name:"You":this.peerLabels&&this.peerLabels.has(e)?this.peerLabels.get(e):e}setPresentingPeer(e){this.presentingPeerId=e||null,this.uiManager&&this.uiManager.setPresentingPeer&&this.uiManager.setPresentingPeer(this.presentingPeerId),this.refreshParticipantsPanel()}refreshParticipantsPanel(){if(!this.uiManager)return;const e=[];if(this.currentUser&&e.push({label:this.currentUser.name||"You",isYou:!0,isHost:this.myRole==="organizer",isSharing:this.peerManager&&this.peerManager.isScreenSharing&&this.peerManager.isScreenSharing()}),this.peerLabels)for(const[t,n]of this.peerLabels.entries())e.push({label:n,isYou:!1,isHost:this.hostPeerId===t,isSharing:this.presentingPeerId===t});this.uiManager.setParticipants(e)}waitForRole(e=3e3){return this.myRole?Promise.resolve(this.myRole):new Promise(t=>{const n=setTimeout(()=>t(this.myRole||"candidate"),e);this.roleResolvers.push(s=>{clearTimeout(n),t(s)})})}async mount(e){if(!this.isInitialized)throw new Error("SDK not initialized. Call init() first.");this.uiManager.mount(e),await this.hydrateIceServers();const t=`${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;await this.peerManager.initialize(t);const n=await this.peerManager.getLocalStream();if(this.uiManager.addVideoStream("local",n,!0),this.config.recordingMode==="composite"&&this.recorder)try{this.compositor=new Fe({width:this.config.compositeWidth,height:this.config.compositeHeight,fps:this.config.compositeFps}),await this.compositor.start(),this.compositor.addStream("local",n,{isLocal:!0,label:this.labelForPeer("local",!0)})}catch(s){console.warn("Composite recording unavailable, falling back to local:",s.message),this.compositor=null}this.socketManager.connect(this.config.workspace),setTimeout(()=>{this.socketManager.joinRoom(this.currentRoom,this.currentUser.id,this.currentUser.name,t)},500),this.setupUIControls(),this.setupRecording(n).catch(s=>console.error("setupRecording failed:",s)),this.setupCollabPanels(),this.fetchChatHistory().then(s=>{s&&s.messages&&this.uiManager.setChatHistory(s.messages)}).catch(s=>console.warn("Chat history fetch failed:",s&&s.message)),console.log("MeetSDK mounted")}setupCollabPanels(){if(this.uiManager&&!this.uiManager._panelWired&&(this.uiManager.wirePanelTabs(),this.uiManager._panelWired=!0),this.config.panels.includes("code")){const e=this.uiManager.getPanelSlot("code");e&&(this.codeSandbox=new qr({container:e,userId:this.currentUser.id,canEdit:()=>this._canEditCode(),canRun:()=>this._canEditCode(),emit:(t,n)=>{this.socketManager.emit(t,{roomId:this.currentRoom,userId:this.currentUser.id,userName:this.currentUser.name,...n})}}),this.socketManager.onRaw("code-changed",t=>this.codeSandbox.handleCodeChanged(t)),this.socketManager.onRaw("code-language-changed",t=>this.codeSandbox.handleLanguageChanged(t)),this.socketManager.onRaw("code-executing",t=>this.codeSandbox.handleExecuting(t)),this.socketManager.onRaw("code-execution-result",t=>this.codeSandbox.handleExecutionResult(t)),this.socketManager.onRaw("code-state-sync",t=>{if(t&&Array.isArray(t.editPermissions)){const n=t.editPermissions.find(s=>s.userId===this.currentUser.id);this._codeEditPermission=!!(n&&n.canEdit)}this.codeSandbox.handleStateSync(t)}),this.socketManager.onRaw("code-permission-changed",t=>{if(t&&t.targetUserId===this.currentUser.id&&(this._codeEditPermission=!!t.canEdit),Array.isArray(t&&t.editPermissions)){const n=t.editPermissions.find(s=>s.userId===this.currentUser.id);n&&(this._codeEditPermission=!!n.canEdit)}this.codeSandbox.refreshPermissionUI()}),this.socketManager.emit("code-state-request",{roomId:this.currentRoom}))}if(this.config.panels.includes("whiteboard")){const e=this.uiManager.getPanelSlot("whiteboard");e&&(this.whiteboard=new Vr({container:e,userId:this.currentUser.id,canDraw:()=>this._canDrawWhiteboard(),emit:(t,n)=>{this.socketManager.emit(t,{roomId:this.currentRoom,userId:this.currentUser.id,userName:this.currentUser.name,...n})}}),this.socketManager.onRaw("whiteboard-drawing",t=>this.whiteboard.handleDrawing(t)),this.socketManager.onRaw("whiteboard-cleared",()=>this.whiteboard.handleCleared()),this.socketManager.onRaw("whiteboard-image-uploaded",t=>this.whiteboard.handleImageUploaded(t)),this.socketManager.onRaw("whiteboard-state-sync",t=>{if(t&&Array.isArray(t.drawPermissions)){const n=t.drawPermissions.find(s=>s.userId===this.currentUser.id);this._whiteboardDrawPermission=!!(n&&n.canDraw)}this.whiteboard.handleStateSync(t)}),this.socketManager.onRaw("whiteboard-permission-changed",t=>{if(t&&t.targetUserId===this.currentUser.id&&(this._whiteboardDrawPermission=!!t.canDraw),Array.isArray(t&&t.drawPermissions)){const n=t.drawPermissions.find(s=>s.userId===this.currentUser.id);n&&(this._whiteboardDrawPermission=!!n.canDraw)}this.whiteboard.refreshPermissionUI()}),this.socketManager.emit("whiteboard-state-request",{roomId:this.currentRoom}))}}_canEditCode(){return this.myRole==="organizer"?!0:!!this._codeEditPermission}_canDrawWhiteboard(){return this.myRole==="organizer"?!0:!!this._whiteboardDrawPermission}async fetchChatHistory(e={}){if(!this.isInitialized)throw new Error("SDK not initialized");const t=new URLSearchParams;e.limit&&t.set("limit",String(e.limit)),e.before&&t.set("before",e.before),e.after&&t.set("after",e.after);const n=t.toString(),s=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/chat/messages${n?"?"+n:""}`,{headers:this.buildHeaders()});if(!s.ok)throw new Error(`chat/messages: HTTP ${s.status}`);return s.json()}async uploadChatAttachment(e){if(!this.isInitialized)throw new Error("SDK not initialized");const t=new FormData;t.append("file",e,e.name),t.append("userId",this.currentUser.id),t.append("userName",this.currentUser.name);const n=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/chat/attachments`,{method:"POST",headers:this.buildHeaders(),body:t});if(!n.ok){const s=await n.json().catch(()=>({}));throw new Error(s.error||`Upload failed: HTTP ${n.status}`)}return n.json()}async setupRecording(e){if(this.recorder){if(this.recorder.on("stateChange",t=>{this.uiManager.updateRecordingIndicator(t),this.uiManager.setPauseButtonVisible(t==="recording"||t==="paused"),this.uiManager.setPauseButtonState(t==="paused")}),this.uiManager.onControlClick("toggle-pause",()=>{this.recorder.isPaused()?this.recorder.resume():this.recorder.pause()}),this.config.recordOnlyIfHost&&await this.waitForRole()!=="organizer"){console.log("MeetSDK: not the host — skipping recording");return}this.config.recording==="auto"&&this.startRecording().catch(t=>console.error("Auto-record failed:",t)),this.config.recording==="manual"&&this.uiManager.onControlClick("toggle-record",async()=>{this.recorder.isRecording()?await this.stopRecording():await this.startRecording()})}}async startRecording(){if(!this.recorder)throw new Error("recording is disabled in SDK config");let e;if(this.config.recordingMode==="composite"&&this.compositor){if(e=this.compositor.getStream(),!e)throw new Error("composite stream not ready")}else if(e=this.peerManager.localStream,!e)throw new Error("local stream not ready");const t=this.readStoredSession();let n=null,s=0;if(t){const i=await this.probeSessionStatus(t.sessionId).catch(()=>null);i&&i.active?(n={sessionId:t.sessionId},s=(i.lastSeq||-1)+1,console.log(`MeetSDK: resuming recording session ${t.sessionId} at seq=${s}`)):this.clearStoredSession()}n||(n=await this.startRecordingSession(),this.persistStoredSession(n)),this.recordingSession=n,this.chunkQueue=[],this.chunkDrainerRunning=!1,this.recorder.start(e,{timesliceMs:15e3,startSeq:s,videoBitsPerSecond:this.config.recordingVideoBps,audioBitsPerSecond:this.config.recordingAudioBps,onChunk:(i,o)=>(this.enqueueChunk(n.sessionId,i,o),Promise.resolve())})}storedSessionKey(){return`meetSdk.session.${this.config.workspace}.${this.currentRoom}`}readStoredSession(){try{const e=window.localStorage.getItem(this.storedSessionKey());if(!e)return null;const t=JSON.parse(e);return Date.now()-(t.at||0)>24*60*60*1e3?null:t}catch{return null}}persistStoredSession(e){try{window.localStorage.setItem(this.storedSessionKey(),JSON.stringify({sessionId:e.sessionId,at:Date.now()}))}catch{}}clearStoredSession(){try{window.localStorage.removeItem(this.storedSessionKey())}catch{}}async probeSessionStatus(e){const t=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/status`,{headers:this.buildHeaders()});return t.ok?t.json():null}enqueueChunk(e,t,n){this.chunkQueue=this.chunkQueue||[],this.chunkQueue.push({sessionId:e,blob:t,seq:n}),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length),this.runChunkDrainer().catch(s=>console.warn("Chunk drainer error:",s&&s.message))}async runChunkDrainer(){if(!this.chunkDrainerRunning){this.chunkDrainerRunning=!0;try{for(;this.chunkQueue&&this.chunkQueue.length>0;){const e=this.chunkQueue[0];try{await this.uploadRecordingChunk(e.sessionId,e.blob,e.seq),this.chunkQueue.shift(),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length)}catch(t){if(/HTTP 404|HTTP 409/.test(String(t&&t.message))){console.warn(`Dropping chunk seq=${e.seq}: ${t.message}`),this.chunkQueue.shift(),this.uiManager&&this.uiManager.setQueueCount&&this.uiManager.setQueueCount(this.chunkQueue.length);continue}const n=Math.min(3e4,1e3*Math.pow(2,this._chunkFailStreak||0));this._chunkFailStreak=(this._chunkFailStreak||0)+1,console.warn(`Chunk seq=${e.seq} failed, retrying in ${n}ms`),await new Promise(s=>setTimeout(s,n))}}this._chunkFailStreak=0}finally{this.chunkDrainerRunning=!1}}}async waitForChunkQueueEmpty(){for(;this.chunkQueue&&this.chunkQueue.length>0||this.chunkDrainerRunning;)await new Promise(e=>setTimeout(e,200))}async stopRecording(){if(!this.recorder)return null;const e=await this.recorder.stop();if(!e||!this.recordingSession)return null;const t=this.recordingSession.sessionId;this.recordingSession=null,await this.waitForChunkQueueEmpty();try{return await this.finalizeRecordingSession(t,e)}catch(n){throw console.error("Recording finalize failed:",n),n}}async startRecordingSession(){const e={recordedBy:this.currentUser.id,contentType:this.recorder.mimeType||"video/webm",transcribe:this.config.transcribe,summarize:this.config.summarize},t=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/start`,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`session/start failed: HTTP ${t.status}`);return t.json()}async uploadRecordingChunk(e,t,n){const s=new FormData;s.append("chunk",t,`chunk-${n}.webm`);const i=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/chunk?seq=${n}`,{method:"POST",headers:this.buildHeaders(),body:s});if(!i.ok)throw new Error(`chunk seq=${n}: HTTP ${i.status}`)}async finalizeRecordingSession(e,t){const n=Math.max(0,Math.round((t.endedAt-t.startedAt)/1e3)),s=await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/session/${encodeURIComponent(e)}/finalize`,{method:"POST",headers:{...this.buildHeaders(),"Content-Type":"application/json"},body:JSON.stringify({durationSec:n,startedAt:t.startedAt.toISOString(),endedAt:t.endedAt.toISOString()})});if(!s.ok)throw new Error(`session/finalize failed: HTTP ${s.status}`);const i=await s.json();return this.clearStoredSession(),i}async listRecordings(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings`,{headers:this.buildHeaders()})).json()}async getRecording(e){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${encodeURIComponent(this.currentRoom)}/recordings/${encodeURIComponent(e)}`,{headers:this.buildHeaders()})).json()}setupUIControls(){let e=!0,t=!0;this.uiManager.onControlClick("toggle-video",()=>{e=this.peerManager.toggleVideo(),this.uiManager.updateButtonState("toggle-video",e?"Video On":"Video Off")}),this.uiManager.onControlClick("toggle-audio",()=>{t=this.peerManager.toggleAudio(),this.uiManager.updateButtonState("toggle-audio",t?"Mic On":"Mic Off")}),this.uiManager.onControlClick("leave-meeting",()=>{this.leave()}),this.uiManager.onControlClick("toggle-screenshare",async()=>{try{if(this.peerManager.isScreenSharing())await this.peerManager.stopScreenShare(),this.uiManager.setScreenSharingState(!1),this.socketManager.emitMediaState(this.currentRoom,this.currentUser.id,"screen",!1),this.setPresentingPeer(null);else{await this.peerManager.startScreenShare(),this.uiManager.setScreenSharingState(!0),this.socketManager.emitMediaState(this.currentRoom,this.currentUser.id,"screen",!0);const n=`${this.config.workspace}-${this.currentRoom}-${this.currentUser.id}`;this.setPresentingPeer(n)}}catch(n){console.warn("Screen share toggle failed:",n&&n.message)}}),this.uiManager.onChatSend((n,s)=>{this.socketManager.sendMessage(this.currentRoom,this.currentUser.id,this.currentUser.name,n,s)}),this.uiManager.onAttachFile(async n=>this.uploadChatAttachment(n))}buildHeaders(e={}){const t=this.config.ai||{},n={workspace:this.config.workspace,...e};return t.whisperKey&&(n["x-whisper-key"]=t.whisperKey),t.whisperUrl&&(n["x-whisper-url"]=t.whisperUrl),t.llmKey&&(n["x-llm-key"]=t.llmKey),t.llmUrl&&(n["x-llm-url"]=t.llmUrl),t.llmModel&&(n["x-llm-model"]=t.llmModel),n}setAiConfig(e={}){if(!this.config)throw new Error("SDK not initialized");this.config.ai={...this.config.ai||{},...e}}async getSummary(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/summary`,{headers:this.buildHeaders()})).json()}async generateSummary(){if(!this.isInitialized)throw new Error("SDK not initialized");return(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/summary/generate`,{method:"POST",headers:this.buildHeaders()})).json()}async transcribeAudio(e,t="audio.webm"){if(!this.isInitialized)throw new Error("SDK not initialized");const n=new FormData;return n.append("audio",e,t),(await fetch(`${this.config.apiUrl}/rooms/${this.currentRoom}/transcribe`,{method:"POST",headers:this.buildHeaders(),body:n})).json()}grantCodeEdit(e,t,n=!0){this.socketManager.emit("code-permission-change",{roomId:this.currentRoom,userId:this.currentUser.id,targetUserId:e,targetUserName:t||e,canEdit:!!n})}grantWhiteboardDraw(e,t,n=!0){this.socketManager.emit("whiteboard-permission-change",{roomId:this.currentRoom,userId:this.currentUser.id,targetUserId:e,targetUserName:t||e,canDraw:!!n})}async leave(){if(this.recorder&&this.recorder.isRecording())try{this.uiManager.setUploadingIndicator(!0),await this.stopRecording()}catch(e){console.warn("Recording upload on leave failed:",e)}finally{this.uiManager.setUploadingIndicator(!1)}if(this.socketManager.leaveRoom(),this.socketManager.disconnect(),this.peerManager.disconnect(),this.mediaManager.cleanup(),this.uiManager.destroy(),this.compositor){try{this.compositor.stop()}catch{}this.compositor=null}this.isInitialized=!1,console.log("Left meeting")}}typeof window<"u"&&(window.MeetSDK=new hn),x.default=hn,Object.defineProperties(x,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|