@afterrealism/dendri-client 2.4.0 → 2.5.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/README.md +8 -17
- package/dist/{chunk-MBMSG4EC.js → chunk-3CE674DE.js} +72 -15
- package/dist/chunk-3CE674DE.js.map +1 -0
- package/dist/dendri.browser.global.js +70 -13
- package/dist/dendri.browser.global.js.map +1 -1
- package/dist/dendri.cjs +70 -13
- package/dist/dendri.cjs.map +1 -1
- package/dist/dendri.d.cts +13 -4
- package/dist/dendri.d.ts +13 -4
- package/dist/dendri.js +2 -2
- package/dist/dendri.min.global.js +7 -7
- package/dist/dendri.min.global.js.map +1 -1
- package/dist/serializer.msgpack.d.cts +14 -0
- package/dist/serializer.msgpack.d.ts +14 -0
- package/dist/{store-DVE0ih44.d.cts → store-C3Nwl62R.d.cts} +14 -0
- package/dist/{store-DVE0ih44.d.ts → store-C3Nwl62R.d.ts} +14 -0
- package/dist/store.cjs +70 -13
- package/dist/store.cjs.map +1 -1
- package/dist/store.d.cts +1 -1
- package/dist/store.d.ts +1 -1
- package/dist/store.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-MBMSG4EC.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var dendri=(()=>{var kt=Object.create;var ge=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var Et=Object.getPrototypeOf,Pt=Object.prototype.hasOwnProperty;var rt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),
|
|
1
|
+
"use strict";var dendri=(()=>{var kt=Object.create;var ge=Object.defineProperty;var Rt=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var Et=Object.getPrototypeOf,Pt=Object.prototype.hasOwnProperty;var rt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),W=(r,e)=>{for(var t in e)ge(r,t,{get:e[t],enumerable:!0})},Dt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xt(e))!Pt.call(r,i)&&i!==t&&ge(r,i,{get:()=>e[i],enumerable:!(n=Rt(e,i))||n.enumerable});return r};var L=(r,e,t)=>(t=r!=null?kt(Et(r)):{},Dt(e||!r||!r.__esModule?ge(t,"default",{value:r,enumerable:!0}):t,r));var Qe=rt((Vt,Je)=>{"use strict";var f={};f.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};f.localCName=f.generateIdentifier();f.splitLines=function(r){return r.trim().split(`
|
|
2
2
|
`).map(e=>e.trim())};f.splitSections=function(r){return r.split(`
|
|
3
3
|
m=`).map((t,n)=>(n>0?"m="+t:t).trim()+`\r
|
|
4
4
|
`)};f.getDescription=function(r){let e=f.splitSections(r);return e&&e[0]};f.getMediaSections=function(r){let e=f.splitSections(r);return e.shift(),e};f.matchPrefix=function(r,e){return f.splitLines(r).filter(t=>t.indexOf(e)===0)};f.parseCandidate=function(r){let e;r.indexOf("a=candidate:")===0?e=r.substring(12).split(" "):e=r.substring(10).split(" ");let t={foundation:e[0],component:{1:"rtp",2:"rtcp"}[e[1]]||e[1],protocol:e[2].toLowerCase(),priority:parseInt(e[3],10),ip:e[4],address:e[4],port:parseInt(e[5],10),type:e[7]};for(let n=8;n<e.length;n+=2)switch(e[n]){case"raddr":t.relatedAddress=e[n+1];break;case"rport":t.relatedPort=parseInt(e[n+1],10);break;case"tcptype":t.tcpType=e[n+1];break;case"ufrag":t.ufrag=e[n+1],t.usernameFragment=e[n+1];break;default:t[e[n]]===void 0&&(t[e[n]]=e[n+1]);break}return t};f.writeCandidate=function(r){let e=[];e.push(r.foundation);let t=r.component;t==="rtp"?e.push(1):t==="rtcp"?e.push(2):e.push(t),e.push(r.protocol.toUpperCase()),e.push(r.priority),e.push(r.address||r.ip),e.push(r.port);let n=r.type;return e.push("typ"),e.push(n),n!=="host"&&r.relatedAddress&&r.relatedPort!==void 0&&(e.push("raddr"),e.push(r.relatedAddress),e.push("rport"),e.push(r.relatedPort)),r.tcpType&&r.protocol.toLowerCase()==="tcp"&&(e.push("tcptype"),e.push(r.tcpType)),(r.usernameFragment||r.ufrag)&&(e.push("ufrag"),e.push(r.usernameFragment||r.ufrag)),"candidate:"+e.join(" ")};f.parseIceOptions=function(r){return r.substring(14).split(" ")};f.parseRtpMap=function(r){let e=r.substring(9).split(" "),t={payloadType:parseInt(e.shift(),10)};return e=e[0].split("/"),t.name=e[0],t.clockRate=parseInt(e[1],10),t.channels=e.length===3?parseInt(e[2],10):1,t.numChannels=t.channels,t};f.writeRtpMap=function(r){let e=r.payloadType;r.preferredPayloadType!==void 0&&(e=r.preferredPayloadType);let t=r.channels||r.numChannels||1;return"a=rtpmap:"+e+" "+r.name+"/"+r.clockRate+(t!==1?"/"+t:"")+`\r
|
|
@@ -29,18 +29,18 @@ a=ice-pwd:`+r.password+`\r
|
|
|
29
29
|
o=`+(t||"thisisadapterortc")+" "+n+" "+i+` IN IP4 127.0.0.1\r
|
|
30
30
|
s=-\r
|
|
31
31
|
t=0 0\r
|
|
32
|
-
`};f.getDirection=function(r,e){let t=f.splitLines(r);for(let n=0;n<t.length;n++)switch(t[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return t[n].substring(2);default:}return e?f.getDirection(e):"sendrecv"};f.getKind=function(r){return f.splitLines(r)[0].split(" ")[0].substring(2)};f.isRejected=function(r){return r.split(" ",2)[1]==="0"};f.parseMLine=function(r){let t=f.splitLines(r)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}};f.parseOLine=function(r){let t=f.matchPrefix(r,"o=")[0].substring(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}};f.isValidSDP=function(r){if(typeof r!="string"||r.length===0)return!1;let e=f.splitLines(r);for(let t=0;t<e.length;t++)if(e[t].length<2||e[t].charAt(1)!=="=")return!1;return!0};typeof Je=="object"&&(Je.exports=f)});var ae=rt((ln,tt)=>{"use strict";var Ut=Object.prototype.hasOwnProperty,C="~";function H(){}Object.create&&(H.prototype=Object.create(null),new H().__proto__||(C=!1));function Ft(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function yt(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Ft(t,n||r,i),s=C?C+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function se(r,e){--r._eventsCount===0?r._events=new H:delete r._events[e]}function y(){this._events=new H,this._eventsCount=0}y.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ut.call(t,n)&&e.push(C?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};y.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 i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};y.prototype.listenerCount=function(e){var t=C?C+e:e,n=this._events[t];return n?n.fn?1:n.length:0};y.prototype.emit=function(e,t,n,i,o,s){var a=C?C+e:e;if(!this._events[a])return!1;var c=this._events[a],p=arguments.length,d,h;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),p){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,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(h=1,d=new Array(p-1);h<p;h++)d[h-1]=arguments[h];c.fn.apply(c.context,d)}else{var u=c.length,m;for(h=0;h<u;h++)switch(c[h].once&&this.removeListener(e,c[h].fn,void 0,!0),p){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,n);break;case 4:c[h].fn.call(c[h].context,t,n,i);break;default:if(!d)for(m=1,d=new Array(p-1);m<p;m++)d[m-1]=arguments[m];c[h].fn.apply(c[h].context,d)}}return!0};y.prototype.on=function(e,t,n){return yt(this,e,t,n,!1)};y.prototype.once=function(e,t,n){return yt(this,e,t,n,!0)};y.prototype.removeListener=function(e,t,n,i){var o=C?C+e:e;if(!this._events[o])return this;if(!t)return se(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&se(this,o);else{for(var a=0,c=[],p=s.length;a<p;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:se(this,o)}return this};y.prototype.removeAllListeners=function(e){var t;return e?(t=C?C+e:e,this._events[t]&&se(this,t)):(this._events=new H,this._eventsCount=0),this};y.prototype.off=y.prototype.removeListener;y.prototype.addListener=y.prototype.on;y.prefixed=C;y.EventEmitter=y;typeof tt<"u"&&(tt.exports=y)});var Mt="Dendri: ";var ye=class{_logLevel=0;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){let n=[Mt,...t];for(let i in n)n[i]instanceof Error&&(n[i]=`(${n[i].name}) ${n[i].message}`);e>=3?console.log(...n):e>=2?console.warn("WARNING",...n):e>=1&&console.error("ERROR",...n)}},l=new ye;var ve=class{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){let e=new Uint8Array(this._pieces);this._parts.push(e),this._pieces=[]}}toArrayBuffer(){let e=[];for(let t of this._parts)e.push(t);return It(e).buffer}};function It(r){let e=0;for(let i of r)e+=i.byteLength;let t=new Uint8Array(e),n=0;for(let i of r){let o=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);t.set(o,n),n+=i.byteLength}return t}function w(r){return new Ce(r).unpack()}function q(r){let e=new be,t=e.pack(r);return t instanceof Promise?t.then(()=>e.getBuffer()):e.getBuffer()}var Ce=class{constructor(e){this.index=0,this.dataBuffer=e,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}unpack(){let 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(){let e=this.dataView[this.index]&255;return this.index++,e}unpack_uint16(){let e=this.read(2),t=(e[0]&255)*256+(e[1]&255);return this.index+=2,t}unpack_uint32(){let e=this.read(4),t=((e[0]*256+e[1])*256+e[2])*256+e[3];return this.index+=4,t}unpack_uint64(){let 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(){let e=this.unpack_uint8();return e<128?e:e-256}unpack_int16(){let e=this.unpack_uint16();return e<32768?e:e-65536}unpack_int32(){let e=this.unpack_uint32();return e<2**31?e:e-2**32}unpack_int64(){let 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}`);let t=this.dataBuffer.slice(this.index,this.index+e);return this.index+=e,t}unpack_string(e){let t=this.read(e),n=0,i="",o,s;for(;n<e;)o=t[n],o<160?(s=o,n++):(o^192)<32?(s=(o&31)<<6|t[n+1]&63,n+=2):(o^224)<16?(s=(o&15)<<12|(t[n+1]&63)<<6|t[n+2]&63,n+=3):(s=(o&7)<<18|(t[n+1]&63)<<12|(t[n+2]&63)<<6|t[n+3]&63,n+=4),i+=String.fromCodePoint(s);return this.index+=e,i}unpack_array(e){let t=new Array(e);for(let n=0;n<e;n++)t[n]=this.unpack();return t}unpack_map(e){let t={};for(let n=0;n<e;n++){let i=this.unpack();t[i]=this.unpack()}return t}unpack_float(){let e=this.unpack_uint32(),t=e>>31,n=(e>>23&255)-127,i=e&8388607|8388608;return(t===0?1:-1)*i*2**(n-23)}unpack_double(){let e=this.unpack_uint32(),t=this.unpack_uint32(),n=e>>31,i=(e>>20&2047)-1023,s=(e&1048575|1048576)*2**(i-20)+t*2**(i-52);return(n===0?1:-1)*s}read(e){let t=this.index;if(t+e<=this.length)return this.dataView.subarray(t,t+e);throw new Error("BinaryPackFailure: read index out of range")}},be=class{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{let t=e.constructor;if(e instanceof Array){let 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){let 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")){let 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){let 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){let 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){let 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");let n=i=>{if(i<t){let o=this.pack(e[i]);return o instanceof Promise?o.then(()=>n(i+1)):n(i+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);let n=Math.floor(Math.log(e)/Math.LN2),i=e/2**n-1,o=Math.floor(i*2**52),s=2**32,a=t<<31|n+1023<<20|o/s&1048575,c=o%s;this._bufferBuilder.append(203),this.pack_int32(a),this.pack_int32(c)}pack_object(e){let 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");let i=o=>{if(o<t.length){let s=t[o];if(e.hasOwnProperty(s)){this.pack(s);let a=this.pack(e[s]);if(a instanceof Promise)return a.then(()=>i(o+1))}return i(o+1)}};return i(0)}pack_uint8(e){this._bufferBuilder.append(e)}pack_uint16(e){this._bufferBuilder.append(e>>8),this._bufferBuilder.append(e&255)}pack_uint32(e){let 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){let 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){let 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 ve,this._textEncoder=new TextEncoder}};var R=class{chunkedMTU=16300;_dataCount=1;chunk=e=>{let t=[],n=e.byteLength,i=Math.ceil(n/this.chunkedMTU),o=0,s=0;for(;s<n;){let a=Math.min(n,s+this.chunkedMTU),c=e.slice(s,a),p={__peerData:this._dataCount,n:o,data:c,total:i};t.push(p),s=a,o++}return this._dataCount++,t}};function it(r){let e=0;for(let i of r)e+=i.byteLength;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.byteLength;return t}var st=!0,at=!0;function x(r,e,t){let n=r.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function b(r,e,t){if(!r.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){B("Unable to polyfill events");return}let i=r.RTCPeerConnection.prototype,o=i.addEventListener;i.addEventListener=function(a,c){if(a!==e)return o.apply(this,arguments);let p=d=>{let h=t(d);h&&(c.handleEvent?c.handleEvent(h):c(h))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(c,p),o.apply(this,[a,p])};let s=i.removeEventListener;i.removeEventListener=function(a,c){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(c))return s.apply(this,arguments);let p=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,s.apply(this,[a,p])},Object.defineProperty(i,"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 ct(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(st=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function pt(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(at=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function B(){if(typeof window=="object"){if(st)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function E(r,e){at&&console.warn(r+" is deprecated, please use "+e+" instead.")}function dt(r){let e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;let{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){let n=t.userAgentData.brands.find(i=>i.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(x(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(x(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(x(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype,e._safariVersion=x(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function ot(r){return Object.prototype.toString.call(r)==="[object Object]"}function Te(r){return ot(r)?Object.keys(r).reduce(function(e,t){let n=ot(r[t]),i=n?Te(r[t]):r[t],o=n&&!Object.keys(i).length;return i===void 0||o?e:Object.assign(e,{[t]:i})},{}):r}function Se(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Se(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(i=>{Se(r,r.get(i),t)})}))}function ke(r,e,t){let n=t?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;let o=[];return r.forEach(s=>{s.type==="track"&&s.trackIdentifier===e.id&&o.push(s)}),o.forEach(s=>{r.forEach(a=>{a.type===n&&a.trackId===s.id&&Se(r,a,i)})}),i}var Q={};G(Q,{fixNegotiationNeeded:()=>Me,shimAddTrackRemoveTrack:()=>De,shimAddTrackRemoveTrackWithNative:()=>ht,shimGetSendersWithDtmf:()=>Ee,shimGetUserMedia:()=>V,shimMediaStream:()=>Re,shimOnTrack:()=>xe,shimPeerConnection:()=>J,shimSenderReceiverGetStats:()=>Pe});var lt=B;function V(r,e){let t=r&&r.navigator;if(!t.mediaDevices)return;let n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;let c={};return Object.keys(a).forEach(p=>{if(p==="require"||p==="advanced"||p==="mediaSource")return;let d=typeof a[p]=="object"?a[p]:{ideal:a[p]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);let h=function(u,m){return u?u+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};if(d.ideal!==void 0){c.optional=c.optional||[];let u={};typeof d.ideal=="number"?(u[h("min",p)]=d.ideal,c.optional.push(u),u={},u[h("max",p)]=d.ideal,c.optional.push(u)):(u[h("",p)]=d.ideal,c.optional.push(u))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",p)]=d.exact):["min","max"].forEach(u=>{d[u]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(u,p)]=d[u])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},i=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){let p=function(d,h,u){h in d&&!(u in d)&&(d[u]=d[h],delete d[h])};a=JSON.parse(JSON.stringify(a)),p(a.audio,"autoGainControl","googAutoGainControl"),p(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let p=a.video.facingMode;p=p&&(typeof p=="object"?p:{ideal:p});let d=e.version<66;if(p&&(p.exact==="user"||p.exact==="environment"||p.ideal==="user"||p.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete a.video.facingMode;let h;if(p.exact==="environment"||p.ideal==="environment"?h=["back","rear"]:(p.exact==="user"||p.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(u=>{u=u.filter(g=>g.kind==="videoinput");let m=u.find(g=>h.some(v=>g.label.toLowerCase().includes(v)));return!m&&u.length&&h.includes("back")&&(m=u[u.length-1]),m&&(a.video.deviceId=p.exact?{exact:m.deviceId}:{ideal:m.deviceId}),a.video=n(a.video),lt("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return lt("chrome: "+JSON.stringify(a)),c(a)},o=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}}},s=function(a,c,p){i(a,d=>{t.webkitGetUserMedia(d,c,h=>{p&&p(o(h))})})};if(t.getUserMedia=s.bind(t),t.mediaDevices.getUserMedia){let a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return i(c,p=>a(p).then(d=>{if(p.audio&&!d.getAudioTracks().length||p.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(o(d))))}}}function Re(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function xe(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});let t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",o=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(c=>c.track&&c.track.id===o.track.id):s={track:o.track};let a=new Event("track");a.track=o.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(o=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(c=>c.track&&c.track.id===o.id):s={track:o};let a=new Event("track");a.track=o,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else b(r,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function Ee(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){let e=function(i,o){return{track:o,get dtmf(){return this._dtmf===void 0&&(o.kind==="audio"?this._dtmf=i.createDTMFSender(o):this._dtmf=null),this._dtmf},_pc:i}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,c){let p=i.apply(this,arguments);return p||(p=e(this,a),this._senders.push(p)),p};let o=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){o.apply(this,arguments);let c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}let t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(o){this._senders=this._senders||[],t.apply(this,[o]),o.getTracks().forEach(s=>{this._senders.push(e(this,s))})};let n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(o){this._senders=this._senders||[],n.apply(this,[o]),o.getTracks().forEach(s=>{let a=this._senders.find(c=>c.track===s);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)){let e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){let n=e.apply(this,[]);return n.forEach(i=>i._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 Pe(r,e){if(e.version>=67||!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){let n=r.RTCPeerConnection.prototype.getSenders;n&&(r.RTCPeerConnection.prototype.getSenders=function(){let s=n.apply(this,[]);return s.forEach(a=>a._pc=this),s});let i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){let s=i.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){let s=this;return this._pc.getStats().then(a=>ke(a,s.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){let n=r.RTCPeerConnection.prototype.getReceivers;n&&(r.RTCPeerConnection.prototype.getReceivers=function(){let o=n.apply(this,[]);return o.forEach(s=>s._pc=this),o}),b(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){let o=this;return this._pc.getStats().then(s=>ke(s,o.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;let t=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){let i=arguments[0],o,s,a;return this.getSenders().forEach(c=>{c.track===i&&(o?a=!0:o=c)}),this.getReceivers().forEach(c=>(c.track===i&&(s?a=!0:s=c),c.track===i)),a||o&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):o?o.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ht(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(s=>this._shimmedLocalStreams[s][0])};let e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(s,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let 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};let t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(p=>{if(this.getSenders().find(h=>h.track===p))throw new DOMException("Track already exists.","InvalidAccessError")});let a=this.getSenders();t.apply(this,arguments);let c=this.getSenders().filter(p=>a.indexOf(p)===-1);this._shimmedLocalStreams[s.id]=[s].concat(c)};let n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[s.id],n.apply(this,arguments)};let i=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},s&&Object.keys(this._shimmedLocalStreams).forEach(a=>{let c=this._shimmedLocalStreams[a].indexOf(s);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),i.apply(this,arguments)}}function De(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ht(r);let t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){let d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(h=>this._reverseStreams[h.id])};let n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(h=>{if(this.getSenders().find(m=>m.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){let h=new r.MediaStream(d.getTracks());this._streams[d.id]=h,this._reverseStreams[h.id]=d,d=h}n.apply(this,[d])};let i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},r.RTCPeerConnection.prototype.addTrack=function(d,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let u=[].slice.call(arguments,1);if(u.length!==1||!u[0].getTracks().find(v=>v===d))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(v=>v.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let g=this._streams[h.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let v=new r.MediaStream([d]);this._streams[h.id]=v,this._reverseStreams[v.id]=h,this.addStream(v)}return this.getSenders().find(v=>v.track===d)};function o(p,d){let h=d.sdp;return Object.keys(p._reverseStreams||[]).forEach(u=>{let m=p._reverseStreams[u],g=p._streams[m.id];h=h.replace(new RegExp(g.id,"g"),m.id)}),new RTCSessionDescription({type:d.type,sdp:h})}function s(p,d){let h=d.sdp;return Object.keys(p._reverseStreams||[]).forEach(u=>{let m=p._reverseStreams[u],g=p._streams[m.id];h=h.replace(new RegExp(m.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:h})}["createOffer","createAnswer"].forEach(function(p){let d=r.RTCPeerConnection.prototype[p],h={[p](){let u=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{let v=o(this,g);u[0].apply(null,[v])},g=>{u[1]&&u[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>o(this,g))}};r.RTCPeerConnection.prototype[p]=h[p]});let a=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=s(this,arguments[0]),a.apply(this,arguments))};let c=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){let p=c.get.apply(this);return p.type===""?p:o(this,p)}}),r.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let u;Object.keys(this._streams).forEach(m=>{this._streams[m].getTracks().find(v=>d.track===v)&&(u=this._streams[m])}),u&&(u.getTracks().length===1?this.removeStream(this._reverseStreams[u.id]):u.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function J(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let n=r.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=i[t]})}function Me(r,e){e.version>102||b(r,"negotiationneeded",t=>{let n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Z={};G(Z,{shimAddTransceiver:()=>Fe,shimCreateAnswer:()=>ze,shimCreateOffer:()=>je,shimGetDisplayMedia:()=>ft,shimGetParameters:()=>$e,shimGetStats:()=>Ae,shimGetUserMedia:()=>Y,shimOnTrack:()=>Ie,shimPeerConnection:()=>X,shimRTCDataChannel:()=>Ue,shimReceiverGetStats:()=>Le,shimRemoveStream:()=>Be,shimSenderGetStats:()=>Oe});function Y(r,e){let t=r&&r.navigator,n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(i,o,s){E("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(i).then(o,s)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){let i=function(s,a,c){a in s&&!(c in s)&&(s[c]=s[a],delete s[a])},o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(s){return typeof s=="object"&&typeof s.audio=="object"&&(s=JSON.parse(JSON.stringify(s)),i(s.audio,"autoGainControl","mozAutoGainControl"),i(s.audio,"noiseSuppression","mozNoiseSuppression")),o(s)},n&&n.prototype.getSettings){let s=n.prototype.getSettings;n.prototype.getSettings=function(){let a=s.apply(this,arguments);return i(a,"mozAutoGainControl","autoGainControl"),i(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){let s=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),i(a,"autoGainControl","mozAutoGainControl"),i(a,"noiseSuppression","mozNoiseSuppression")),s.apply(this,[a])}}}}function ft(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)})}function Ie(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 X(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){let n=r.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=i[t]}))}function Ae(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection)||e.version>=151)return;let 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(){let[o,s,a]=arguments;return this.signalingState==="closed"?Promise.resolve(new Map):n.apply(this,[o||null]).then(c=>{if(e.version<53&&!s)try{c.forEach(p=>{p.type=t[p.type]||p.type})}catch(p){if(p.name!=="TypeError")throw p;c.forEach((d,h)=>{c.set(h,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(s,a)}}function Oe(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;let e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){let i=e.apply(this,[]);return i.forEach(o=>o._pc=this),i});let t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){let i=t.apply(this,arguments);return i._pc=this,i}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Le(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;let e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){let n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n}),b(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Be(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){E("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Ue(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function Fe(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;let e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];let i=n.length>0;i&&n.forEach(s=>{if("rid"in s&&!/^[a-z0-9]{0,16}$/i.test(s.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in s&&!(parseFloat(s.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in s&&!(parseFloat(s.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let o=e.apply(this,arguments);if(i){let{sender:s}=o,a=s.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,s.sendEncodings=n,this.setParametersPromises.push(s.setParameters(a).then(()=>{delete s.sendEncodings}).catch(()=>{delete s.sendEncodings})))}return o})}function $e(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;let e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){let n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function je(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;let e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function ze(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;let e=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var ee={};G(ee,{shimAudioContext:()=>Ve,shimCallbacksAPI:()=>Ke,shimConstraints:()=>ut,shimCreateOfferLegacy:()=>qe,shimGetUserMedia:()=>We,shimLocalStreamsAPI:()=>He,shimRTCIceServerUrls:()=>Ge,shimRemoteStreamsAPI:()=>Ne,shimTrackEventTransceiver:()=>we});function He(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)){let 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(i=>e.call(this,i,n)),n.getVideoTracks().forEach(i=>e.call(this,i,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...i){return i&&i.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);let i=t.getTracks();this.getSenders().forEach(o=>{i.includes(o.track)&&this.removeTrack(o)})})}}function Ne(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(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);let o=new Event("addstream");o.stream=i,this.dispatchEvent(o)})})}});let e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){let n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(o=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(o)>=0)return;n._remoteStreams.push(o);let s=new Event("addstream");s.stream=o,n.dispatchEvent(s)})}),e.apply(n,arguments)}}}function Ke(r){if(typeof r!="object"||!r.RTCPeerConnection)return;let e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,i=e.setLocalDescription,o=e.setRemoteDescription,s=e.addIceCandidate;e.createOffer=function(p,d){let h=arguments.length>=2?arguments[2]:arguments[0],u=t.apply(this,[h]);return d?(u.then(p,d),Promise.resolve()):u},e.createAnswer=function(p,d){let h=arguments.length>=2?arguments[2]:arguments[0],u=n.apply(this,[h]);return d?(u.then(p,d),Promise.resolve()):u};let a=function(c,p,d){let h=i.apply(this,[c]);return d?(h.then(p,d),Promise.resolve()):h};e.setLocalDescription=a,a=function(c,p,d){let h=o.apply(this,[c]);return d?(h.then(p,d),Promise.resolve()):h},e.setRemoteDescription=a,a=function(c,p,d){let h=s.apply(this,[c]);return d?(h.then(p,d),Promise.resolve()):h},e.addIceCandidate=a}function We(r){let e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){let t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=i=>n(ut(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(n,i,o){e.mediaDevices.getUserMedia(n).then(i,o)}.bind(e))}function ut(r){return r&&r.video!==void 0?Object.assign({},r,{video:Te(r.video)}):r}function Ge(r){if(!r.RTCPeerConnection)return;let e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,i){if(n&&n.iceServers){let o=[];for(let s=0;s<n.iceServers.length;s++){let a=n.iceServers[s];a.urls===void 0&&a.url?(E("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,o.push(a)):o.push(n.iceServers[s])}n.iceServers=o}return new e(n,i)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function we(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 qe(r){let e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);let i=this.getTransceivers().find(s=>s.receiver.track.kind==="audio");n.offerToReceiveAudio===!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.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);let o=this.getTransceivers().find(s=>s.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&o?o.direction==="sendrecv"?o.setDirection?o.setDirection("sendonly"):o.direction="sendonly":o.direction==="recvonly"&&(o.setDirection?o.setDirection("inactive"):o.direction="inactive"):n.offerToReceiveVideo===!0&&!o&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ve(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}var Ye={};G(Ye,{removeExtmapAllowMixed:()=>re,shimAddIceCandidateNullOrEmpty:()=>j,shimConnectionState:()=>ne,shimMaxMessageSize:()=>F,shimParameterlessSetLocalDescription:()=>z,shimRTCIceCandidate:()=>U,shimRTCIceCandidateRelayProtocol:()=>te,shimSendThrowTypeError:()=>$});var P=L(Qe());function U(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;let 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){let i=new e(n),o=P.default.parseCandidate(n.candidate);for(let s in o)s in i||Object.defineProperty(i,s,{value:o[s]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(n)},r.RTCIceCandidate.prototype=e.prototype,b(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function te(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||b(r,"icecandidate",e=>{if(e.candidate){let t=P.default.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function F(r,e){if(!r.RTCPeerConnection)return;"sctp"in r.RTCPeerConnection.prototype||Object.defineProperty(r.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});let t=function(a){if(!a||!a.sdp)return!1;let c=P.default.splitSections(a.sdp);return c.shift(),c.some(p=>{let d=P.default.parseMLine(p);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},n=function(a){let c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;let p=parseInt(c[1],10);return p!==p?-1:p},i=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},o=function(a,c){let p=65536;e.browser==="firefox"&&e.version===57&&(p=65535);let d=P.default.matchPrefix(a.sdp,"a=max-message-size:");return d.length>0?p=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(p=2147483637),p},s=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){let{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])){let c=n(arguments[0]),p=i(c),d=o(arguments[0],c),h;p===0&&d===0?h=Number.POSITIVE_INFINITY:p===0||d===0?h=Math.max(p,d):h=Math.min(p,d);let u={};Object.defineProperty(u,"maxMessageSize",{get(){return h}}),this._sctp=u}return s.apply(this,arguments)}}function $(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(i,o){let s=i.send;i.send=function(){let c=arguments[0],p=c.length||c.size||c.byteLength;if(i.readyState==="open"&&o.sctp&&p>o.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+o.sctp.maxMessageSize+" bytes)");return s.apply(i,arguments)}}let n=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){let o=n.apply(this,arguments);return t(o,this),o},b(r,"datachannel",i=>(t(i.channel,i.target),i))}function ne(r){if(!r.RTCPeerConnection||"connectionState"in r.RTCPeerConnection.prototype)return;let 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=>{let n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{let o=i.target;if(o._lastConnectionState!==o.connectionState){o._lastConnectionState=o.connectionState;let s=new Event("connectionstatechange",i);o.dispatchEvent(s)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function re(r,e){if(!r.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;let t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(`
|
|
32
|
+
`};f.getDirection=function(r,e){let t=f.splitLines(r);for(let n=0;n<t.length;n++)switch(t[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return t[n].substring(2);default:}return e?f.getDirection(e):"sendrecv"};f.getKind=function(r){return f.splitLines(r)[0].split(" ")[0].substring(2)};f.isRejected=function(r){return r.split(" ",2)[1]==="0"};f.parseMLine=function(r){let t=f.splitLines(r)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}};f.parseOLine=function(r){let t=f.matchPrefix(r,"o=")[0].substring(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}};f.isValidSDP=function(r){if(typeof r!="string"||r.length===0)return!1;let e=f.splitLines(r);for(let t=0;t<e.length;t++)if(e[t].length<2||e[t].charAt(1)!=="=")return!1;return!0};typeof Je=="object"&&(Je.exports=f)});var ae=rt((hn,tt)=>{"use strict";var Ut=Object.prototype.hasOwnProperty,C="~";function H(){}Object.create&&(H.prototype=Object.create(null),new H().__proto__||(C=!1));function jt(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function yt(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new jt(t,n||r,i),s=C?C+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function se(r,e){--r._eventsCount===0?r._events=new H:delete r._events[e]}function y(){this._events=new H,this._eventsCount=0}y.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Ut.call(t,n)&&e.push(C?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};y.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 i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};y.prototype.listenerCount=function(e){var t=C?C+e:e,n=this._events[t];return n?n.fn?1:n.length:0};y.prototype.emit=function(e,t,n,i,o,s){var a=C?C+e:e;if(!this._events[a])return!1;var c=this._events[a],p=arguments.length,d,h;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),p){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,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(h=1,d=new Array(p-1);h<p;h++)d[h-1]=arguments[h];c.fn.apply(c.context,d)}else{var u=c.length,m;for(h=0;h<u;h++)switch(c[h].once&&this.removeListener(e,c[h].fn,void 0,!0),p){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,n);break;case 4:c[h].fn.call(c[h].context,t,n,i);break;default:if(!d)for(m=1,d=new Array(p-1);m<p;m++)d[m-1]=arguments[m];c[h].fn.apply(c[h].context,d)}}return!0};y.prototype.on=function(e,t,n){return yt(this,e,t,n,!1)};y.prototype.once=function(e,t,n){return yt(this,e,t,n,!0)};y.prototype.removeListener=function(e,t,n,i){var o=C?C+e:e;if(!this._events[o])return this;if(!t)return se(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&se(this,o);else{for(var a=0,c=[],p=s.length;a<p;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:se(this,o)}return this};y.prototype.removeAllListeners=function(e){var t;return e?(t=C?C+e:e,this._events[t]&&se(this,t)):(this._events=new H,this._eventsCount=0),this};y.prototype.off=y.prototype.removeListener;y.prototype.addListener=y.prototype.on;y.prefixed=C;y.EventEmitter=y;typeof tt<"u"&&(tt.exports=y)});var Mt="Dendri: ";var ye=class{_logLevel=0;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){let n=[Mt,...t];for(let i in n)n[i]instanceof Error&&(n[i]=`(${n[i].name}) ${n[i].message}`);e>=3?console.log(...n):e>=2?console.warn("WARNING",...n):e>=1&&console.error("ERROR",...n)}},l=new ye;var ve=class{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){let e=new Uint8Array(this._pieces);this._parts.push(e),this._pieces=[]}}toArrayBuffer(){let e=[];for(let t of this._parts)e.push(t);return It(e).buffer}};function It(r){let e=0;for(let i of r)e+=i.byteLength;let t=new Uint8Array(e),n=0;for(let i of r){let o=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);t.set(o,n),n+=i.byteLength}return t}function G(r){return new Ce(r).unpack()}function q(r){let e=new be,t=e.pack(r);return t instanceof Promise?t.then(()=>e.getBuffer()):e.getBuffer()}var Ce=class{constructor(e){this.index=0,this.dataBuffer=e,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}unpack(){let 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(){let e=this.dataView[this.index]&255;return this.index++,e}unpack_uint16(){let e=this.read(2),t=(e[0]&255)*256+(e[1]&255);return this.index+=2,t}unpack_uint32(){let e=this.read(4),t=((e[0]*256+e[1])*256+e[2])*256+e[3];return this.index+=4,t}unpack_uint64(){let 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(){let e=this.unpack_uint8();return e<128?e:e-256}unpack_int16(){let e=this.unpack_uint16();return e<32768?e:e-65536}unpack_int32(){let e=this.unpack_uint32();return e<2**31?e:e-2**32}unpack_int64(){let 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}`);let t=this.dataBuffer.slice(this.index,this.index+e);return this.index+=e,t}unpack_string(e){let t=this.read(e),n=0,i="",o,s;for(;n<e;)o=t[n],o<160?(s=o,n++):(o^192)<32?(s=(o&31)<<6|t[n+1]&63,n+=2):(o^224)<16?(s=(o&15)<<12|(t[n+1]&63)<<6|t[n+2]&63,n+=3):(s=(o&7)<<18|(t[n+1]&63)<<12|(t[n+2]&63)<<6|t[n+3]&63,n+=4),i+=String.fromCodePoint(s);return this.index+=e,i}unpack_array(e){let t=new Array(e);for(let n=0;n<e;n++)t[n]=this.unpack();return t}unpack_map(e){let t={};for(let n=0;n<e;n++){let i=this.unpack();t[i]=this.unpack()}return t}unpack_float(){let e=this.unpack_uint32(),t=e>>31,n=(e>>23&255)-127,i=e&8388607|8388608;return(t===0?1:-1)*i*2**(n-23)}unpack_double(){let e=this.unpack_uint32(),t=this.unpack_uint32(),n=e>>31,i=(e>>20&2047)-1023,s=(e&1048575|1048576)*2**(i-20)+t*2**(i-52);return(n===0?1:-1)*s}read(e){let t=this.index;if(t+e<=this.length)return this.dataView.subarray(t,t+e);throw new Error("BinaryPackFailure: read index out of range")}},be=class{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{let t=e.constructor;if(e instanceof Array){let 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){let 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")){let 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){let 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){let 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){let 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");let n=i=>{if(i<t){let o=this.pack(e[i]);return o instanceof Promise?o.then(()=>n(i+1)):n(i+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);let n=Math.floor(Math.log(e)/Math.LN2),i=e/2**n-1,o=Math.floor(i*2**52),s=2**32,a=t<<31|n+1023<<20|o/s&1048575,c=o%s;this._bufferBuilder.append(203),this.pack_int32(a),this.pack_int32(c)}pack_object(e){let 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");let i=o=>{if(o<t.length){let s=t[o];if(e.hasOwnProperty(s)){this.pack(s);let a=this.pack(e[s]);if(a instanceof Promise)return a.then(()=>i(o+1))}return i(o+1)}};return i(0)}pack_uint8(e){this._bufferBuilder.append(e)}pack_uint16(e){this._bufferBuilder.append(e>>8),this._bufferBuilder.append(e&255)}pack_uint32(e){let 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){let 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){let 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 ve,this._textEncoder=new TextEncoder}};var R=class{chunkedMTU=16300;_dataCount=1;chunk=e=>{let t=[],n=e.byteLength,i=Math.ceil(n/this.chunkedMTU),o=0,s=0;for(;s<n;){let a=Math.min(n,s+this.chunkedMTU),c=e.slice(s,a),p={__peerData:this._dataCount,n:o,data:c,total:i};t.push(p),s=a,o++}return this._dataCount++,t}};function it(r){let e=0;for(let i of r)e+=i.byteLength;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.byteLength;return t}var st=!0,at=!0;function x(r,e,t){let n=r.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function b(r,e,t){if(!r.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){B("Unable to polyfill events");return}let i=r.RTCPeerConnection.prototype,o=i.addEventListener;i.addEventListener=function(a,c){if(a!==e)return o.apply(this,arguments);let p=d=>{let h=t(d);h&&(c.handleEvent?c.handleEvent(h):c(h))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(c,p),o.apply(this,[a,p])};let s=i.removeEventListener;i.removeEventListener=function(a,c){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(c))return s.apply(this,arguments);let p=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,s.apply(this,[a,p])},Object.defineProperty(i,"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 ct(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(st=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function pt(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(at=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function B(){if(typeof window=="object"){if(st)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function E(r,e){at&&console.warn(r+" is deprecated, please use "+e+" instead.")}function dt(r){let e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;let{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){let n=t.userAgentData.brands.find(i=>i.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(x(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(x(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(x(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype,e._safariVersion=x(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function ot(r){return Object.prototype.toString.call(r)==="[object Object]"}function Te(r){return ot(r)?Object.keys(r).reduce(function(e,t){let n=ot(r[t]),i=n?Te(r[t]):r[t],o=n&&!Object.keys(i).length;return i===void 0||o?e:Object.assign(e,{[t]:i})},{}):r}function Se(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Se(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(i=>{Se(r,r.get(i),t)})}))}function ke(r,e,t){let n=t?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;let o=[];return r.forEach(s=>{s.type==="track"&&s.trackIdentifier===e.id&&o.push(s)}),o.forEach(s=>{r.forEach(a=>{a.type===n&&a.trackId===s.id&&Se(r,a,i)})}),i}var Q={};W(Q,{fixNegotiationNeeded:()=>Me,shimAddTrackRemoveTrack:()=>De,shimAddTrackRemoveTrackWithNative:()=>ht,shimGetSendersWithDtmf:()=>Ee,shimGetUserMedia:()=>V,shimMediaStream:()=>Re,shimOnTrack:()=>xe,shimPeerConnection:()=>J,shimSenderReceiverGetStats:()=>Pe});var lt=B;function V(r,e){let t=r&&r.navigator;if(!t.mediaDevices)return;let n=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;let c={};return Object.keys(a).forEach(p=>{if(p==="require"||p==="advanced"||p==="mediaSource")return;let d=typeof a[p]=="object"?a[p]:{ideal:a[p]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);let h=function(u,m){return u?u+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};if(d.ideal!==void 0){c.optional=c.optional||[];let u={};typeof d.ideal=="number"?(u[h("min",p)]=d.ideal,c.optional.push(u),u={},u[h("max",p)]=d.ideal,c.optional.push(u)):(u[h("",p)]=d.ideal,c.optional.push(u))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[h("",p)]=d.exact):["min","max"].forEach(u=>{d[u]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[h(u,p)]=d[u])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},i=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){let p=function(d,h,u){h in d&&!(u in d)&&(d[u]=d[h],delete d[h])};a=JSON.parse(JSON.stringify(a)),p(a.audio,"autoGainControl","googAutoGainControl"),p(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=n(a.audio)}if(a&&typeof a.video=="object"){let p=a.video.facingMode;p=p&&(typeof p=="object"?p:{ideal:p});let d=e.version<66;if(p&&(p.exact==="user"||p.exact==="environment"||p.ideal==="user"||p.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete a.video.facingMode;let h;if(p.exact==="environment"||p.ideal==="environment"?h=["back","rear"]:(p.exact==="user"||p.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(u=>{u=u.filter(g=>g.kind==="videoinput");let m=u.find(g=>h.some(v=>g.label.toLowerCase().includes(v)));return!m&&u.length&&h.includes("back")&&(m=u[u.length-1]),m&&(a.video.deviceId=p.exact?{exact:m.deviceId}:{ideal:m.deviceId}),a.video=n(a.video),lt("chrome: "+JSON.stringify(a)),c(a)})}a.video=n(a.video)}return lt("chrome: "+JSON.stringify(a)),c(a)},o=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}}},s=function(a,c,p){i(a,d=>{t.webkitGetUserMedia(d,c,h=>{p&&p(o(h))})})};if(t.getUserMedia=s.bind(t),t.mediaDevices.getUserMedia){let a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return i(c,p=>a(p).then(d=>{if(p.audio&&!d.getAudioTracks().length||p.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(o(d))))}}}function Re(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function xe(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});let t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",o=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(c=>c.track&&c.track.id===o.track.id):s={track:o.track};let a=new Event("track");a.track=o.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(o=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(c=>c.track&&c.track.id===o.id):s={track:o};let a=new Event("track");a.track=o,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else b(r,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function Ee(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){let e=function(i,o){return{track:o,get dtmf(){return this._dtmf===void 0&&(o.kind==="audio"?this._dtmf=i.createDTMFSender(o):this._dtmf=null),this._dtmf},_pc:i}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,c){let p=i.apply(this,arguments);return p||(p=e(this,a),this._senders.push(p)),p};let o=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){o.apply(this,arguments);let c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}let t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(o){this._senders=this._senders||[],t.apply(this,[o]),o.getTracks().forEach(s=>{this._senders.push(e(this,s))})};let n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(o){this._senders=this._senders||[],n.apply(this,[o]),o.getTracks().forEach(s=>{let a=this._senders.find(c=>c.track===s);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)){let e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){let n=e.apply(this,[]);return n.forEach(i=>i._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 Pe(r,e){if(e.version>=67||!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){let n=r.RTCPeerConnection.prototype.getSenders;n&&(r.RTCPeerConnection.prototype.getSenders=function(){let s=n.apply(this,[]);return s.forEach(a=>a._pc=this),s});let i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){let s=i.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){let s=this;return this._pc.getStats().then(a=>ke(a,s.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){let n=r.RTCPeerConnection.prototype.getReceivers;n&&(r.RTCPeerConnection.prototype.getReceivers=function(){let o=n.apply(this,[]);return o.forEach(s=>s._pc=this),o}),b(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){let o=this;return this._pc.getStats().then(s=>ke(s,o.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;let t=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){let i=arguments[0],o,s,a;return this.getSenders().forEach(c=>{c.track===i&&(o?a=!0:o=c)}),this.getReceivers().forEach(c=>(c.track===i&&(s?a=!0:s=c),c.track===i)),a||o&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):o?o.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ht(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(s=>this._shimmedLocalStreams[s][0])};let e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(s,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let 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};let t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(p=>{if(this.getSenders().find(h=>h.track===p))throw new DOMException("Track already exists.","InvalidAccessError")});let a=this.getSenders();t.apply(this,arguments);let c=this.getSenders().filter(p=>a.indexOf(p)===-1);this._shimmedLocalStreams[s.id]=[s].concat(c)};let n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[s.id],n.apply(this,arguments)};let i=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},s&&Object.keys(this._shimmedLocalStreams).forEach(a=>{let c=this._shimmedLocalStreams[a].indexOf(s);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),i.apply(this,arguments)}}function De(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ht(r);let t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){let d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(h=>this._reverseStreams[h.id])};let n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(h=>{if(this.getSenders().find(m=>m.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){let h=new r.MediaStream(d.getTracks());this._streams[d.id]=h,this._reverseStreams[h.id]=d,d=h}n.apply(this,[d])};let i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},r.RTCPeerConnection.prototype.addTrack=function(d,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let u=[].slice.call(arguments,1);if(u.length!==1||!u[0].getTracks().find(v=>v===d))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(v=>v.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let g=this._streams[h.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let v=new r.MediaStream([d]);this._streams[h.id]=v,this._reverseStreams[v.id]=h,this.addStream(v)}return this.getSenders().find(v=>v.track===d)};function o(p,d){let h=d.sdp;return Object.keys(p._reverseStreams||[]).forEach(u=>{let m=p._reverseStreams[u],g=p._streams[m.id];h=h.replace(new RegExp(g.id,"g"),m.id)}),new RTCSessionDescription({type:d.type,sdp:h})}function s(p,d){let h=d.sdp;return Object.keys(p._reverseStreams||[]).forEach(u=>{let m=p._reverseStreams[u],g=p._streams[m.id];h=h.replace(new RegExp(m.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:h})}["createOffer","createAnswer"].forEach(function(p){let d=r.RTCPeerConnection.prototype[p],h={[p](){let u=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{let v=o(this,g);u[0].apply(null,[v])},g=>{u[1]&&u[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>o(this,g))}};r.RTCPeerConnection.prototype[p]=h[p]});let a=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=s(this,arguments[0]),a.apply(this,arguments))};let c=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){let p=c.get.apply(this);return p.type===""?p:o(this,p)}}),r.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let u;Object.keys(this._streams).forEach(m=>{this._streams[m].getTracks().find(v=>d.track===v)&&(u=this._streams[m])}),u&&(u.getTracks().length===1?this.removeStream(this._reverseStreams[u.id]):u.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function J(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let n=r.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=i[t]})}function Me(r,e){e.version>102||b(r,"negotiationneeded",t=>{let n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Z={};W(Z,{shimAddTransceiver:()=>je,shimCreateAnswer:()=>ze,shimCreateOffer:()=>Fe,shimGetDisplayMedia:()=>ft,shimGetParameters:()=>$e,shimGetStats:()=>Ae,shimGetUserMedia:()=>Y,shimOnTrack:()=>Ie,shimPeerConnection:()=>X,shimRTCDataChannel:()=>Ue,shimReceiverGetStats:()=>Le,shimRemoveStream:()=>Be,shimSenderGetStats:()=>Oe});function Y(r,e){let t=r&&r.navigator,n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(i,o,s){E("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(i).then(o,s)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){let i=function(s,a,c){a in s&&!(c in s)&&(s[c]=s[a],delete s[a])},o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(s){return typeof s=="object"&&typeof s.audio=="object"&&(s=JSON.parse(JSON.stringify(s)),i(s.audio,"autoGainControl","mozAutoGainControl"),i(s.audio,"noiseSuppression","mozNoiseSuppression")),o(s)},n&&n.prototype.getSettings){let s=n.prototype.getSettings;n.prototype.getSettings=function(){let a=s.apply(this,arguments);return i(a,"mozAutoGainControl","autoGainControl"),i(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){let s=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),i(a,"autoGainControl","mozAutoGainControl"),i(a,"noiseSuppression","mozNoiseSuppression")),s.apply(this,[a])}}}}function ft(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)})}function Ie(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 X(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){let n=r.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=i[t]}))}function Ae(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection)||e.version>=151)return;let 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(){let[o,s,a]=arguments;return this.signalingState==="closed"?Promise.resolve(new Map):n.apply(this,[o||null]).then(c=>{if(e.version<53&&!s)try{c.forEach(p=>{p.type=t[p.type]||p.type})}catch(p){if(p.name!=="TypeError")throw p;c.forEach((d,h)=>{c.set(h,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(s,a)}}function Oe(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;let e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){let i=e.apply(this,[]);return i.forEach(o=>o._pc=this),i});let t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){let i=t.apply(this,arguments);return i._pc=this,i}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Le(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;let e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){let n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n}),b(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Be(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){E("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Ue(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function je(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;let e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];let i=n.length>0;i&&n.forEach(s=>{if("rid"in s&&!/^[a-z0-9]{0,16}$/i.test(s.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in s&&!(parseFloat(s.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in s&&!(parseFloat(s.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let o=e.apply(this,arguments);if(i){let{sender:s}=o,a=s.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=n,s.sendEncodings=n,this.setParametersPromises.push(s.setParameters(a).then(()=>{delete s.sendEncodings}).catch(()=>{delete s.sendEncodings})))}return o})}function $e(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;let e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){let n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Fe(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;let e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function ze(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;let e=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var ee={};W(ee,{shimAudioContext:()=>Ve,shimCallbacksAPI:()=>Ke,shimConstraints:()=>ut,shimCreateOfferLegacy:()=>qe,shimGetUserMedia:()=>we,shimLocalStreamsAPI:()=>He,shimRTCIceServerUrls:()=>We,shimRemoteStreamsAPI:()=>Ne,shimTrackEventTransceiver:()=>Ge});function He(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)){let 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(i=>e.call(this,i,n)),n.getVideoTracks().forEach(i=>e.call(this,i,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...i){return i&&i.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);let i=t.getTracks();this.getSenders().forEach(o=>{i.includes(o.track)&&this.removeTrack(o)})})}}function Ne(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(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);let o=new Event("addstream");o.stream=i,this.dispatchEvent(o)})})}});let e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){let n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(o=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(o)>=0)return;n._remoteStreams.push(o);let s=new Event("addstream");s.stream=o,n.dispatchEvent(s)})}),e.apply(n,arguments)}}}function Ke(r){if(typeof r!="object"||!r.RTCPeerConnection)return;let e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,i=e.setLocalDescription,o=e.setRemoteDescription,s=e.addIceCandidate;e.createOffer=function(p,d){let h=arguments.length>=2?arguments[2]:arguments[0],u=t.apply(this,[h]);return d?(u.then(p,d),Promise.resolve()):u},e.createAnswer=function(p,d){let h=arguments.length>=2?arguments[2]:arguments[0],u=n.apply(this,[h]);return d?(u.then(p,d),Promise.resolve()):u};let a=function(c,p,d){let h=i.apply(this,[c]);return d?(h.then(p,d),Promise.resolve()):h};e.setLocalDescription=a,a=function(c,p,d){let h=o.apply(this,[c]);return d?(h.then(p,d),Promise.resolve()):h},e.setRemoteDescription=a,a=function(c,p,d){let h=s.apply(this,[c]);return d?(h.then(p,d),Promise.resolve()):h},e.addIceCandidate=a}function we(r){let e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){let t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=i=>n(ut(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(n,i,o){e.mediaDevices.getUserMedia(n).then(i,o)}.bind(e))}function ut(r){return r&&r.video!==void 0?Object.assign({},r,{video:Te(r.video)}):r}function We(r){if(!r.RTCPeerConnection)return;let e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,i){if(n&&n.iceServers){let o=[];for(let s=0;s<n.iceServers.length;s++){let a=n.iceServers[s];a.urls===void 0&&a.url?(E("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,o.push(a)):o.push(n.iceServers[s])}n.iceServers=o}return new e(n,i)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Ge(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 qe(r){let e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);let i=this.getTransceivers().find(s=>s.receiver.track.kind==="audio");n.offerToReceiveAudio===!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.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);let o=this.getTransceivers().find(s=>s.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&o?o.direction==="sendrecv"?o.setDirection?o.setDirection("sendonly"):o.direction="sendonly":o.direction==="recvonly"&&(o.setDirection?o.setDirection("inactive"):o.direction="inactive"):n.offerToReceiveVideo===!0&&!o&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ve(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}var Ye={};W(Ye,{removeExtmapAllowMixed:()=>re,shimAddIceCandidateNullOrEmpty:()=>F,shimConnectionState:()=>ne,shimMaxMessageSize:()=>j,shimParameterlessSetLocalDescription:()=>z,shimRTCIceCandidate:()=>U,shimRTCIceCandidateRelayProtocol:()=>te,shimSendThrowTypeError:()=>$});var P=L(Qe());function U(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;let 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){let i=new e(n),o=P.default.parseCandidate(n.candidate);for(let s in o)s in i||Object.defineProperty(i,s,{value:o[s]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(n)},r.RTCIceCandidate.prototype=e.prototype,b(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function te(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||b(r,"icecandidate",e=>{if(e.candidate){let t=P.default.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function j(r,e){if(!r.RTCPeerConnection)return;"sctp"in r.RTCPeerConnection.prototype||Object.defineProperty(r.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});let t=function(a){if(!a||!a.sdp)return!1;let c=P.default.splitSections(a.sdp);return c.shift(),c.some(p=>{let d=P.default.parseMLine(p);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},n=function(a){let c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;let p=parseInt(c[1],10);return p!==p?-1:p},i=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},o=function(a,c){let p=65536;e.browser==="firefox"&&e.version===57&&(p=65535);let d=P.default.matchPrefix(a.sdp,"a=max-message-size:");return d.length>0?p=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(p=2147483637),p},s=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){let{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])){let c=n(arguments[0]),p=i(c),d=o(arguments[0],c),h;p===0&&d===0?h=Number.POSITIVE_INFINITY:p===0||d===0?h=Math.max(p,d):h=Math.min(p,d);let u={};Object.defineProperty(u,"maxMessageSize",{get(){return h}}),this._sctp=u}return s.apply(this,arguments)}}function $(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(i,o){let s=i.send;i.send=function(){let c=arguments[0],p=c.length||c.size||c.byteLength;if(i.readyState==="open"&&o.sctp&&p>o.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+o.sctp.maxMessageSize+" bytes)");return s.apply(i,arguments)}}let n=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){let o=n.apply(this,arguments);return t(o,this),o},b(r,"datachannel",i=>(t(i.channel,i.target),i))}function ne(r){if(!r.RTCPeerConnection||"connectionState"in r.RTCPeerConnection.prototype)return;let 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=>{let n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{let o=i.target;if(o._lastConnectionState!==o.connectionState){o._lastConnectionState=o.connectionState;let s=new Event("connectionstatechange",i);o.dispatchEvent(s)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function re(r,e){if(!r.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;let t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(`
|
|
33
33
|
a=extmap-allow-mixed`)!==-1){let o=i.sdp.split(`
|
|
34
34
|
`).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
|
|
35
|
-
`);r.RTCSessionDescription&&i instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:i.type,sdp:o}):i.sdp=o}return t.apply(this,arguments)}}function
|
|
35
|
+
`);r.RTCSessionDescription&&i instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:i.type,sdp:o}):i.sdp=o}return t.apply(this,arguments)}}function F(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;let 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 z(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;let t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>t.apply(this,[s]))})}var Ot=L(Qe());function mt({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){let t=B,n=dt(r),i={browserDetails:n,commonShim:Ye,extractVersion:x,disableLog:ct,disableWarnings:pt,sdp:Ot};switch(n.browser){case"chrome":if(!Q||!J||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=Q,F(r,n),z(r,n),V(r,n),Re(r,n),J(r,n),xe(r,n),De(r,n),Ee(r,n),Pe(r,n),Me(r,n),U(r,n),te(r,n),ne(r,n),j(r,n),$(r,n),re(r,n);break;case"firefox":if(!Z||!X||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=Z,F(r,n),z(r,n),Y(r,n),X(r,n),Ae(r,n),Ie(r,n),Be(r,n),Oe(r,n),Le(r,n),Ue(r,n),je(r,n),$e(r,n),Fe(r,n),ze(r,n),U(r,n),ne(r,n),j(r,n),$(r,n);break;case"safari":if(!ee||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=ee,F(r,n),z(r,n),We(r,n),qe(r,n),Ke(r,n),He(r,n),Ne(r,n),Ge(r,n),we(r,n),Ve(r,n),U(r,n),te(r,n),j(r,n),$(r,n),re(r,n);break;default:t("Unsupported browser!");break}return i}var Lt=mt({window:typeof window>"u"?void 0:window}),Xe=Lt;var Ze=Xe.default||Xe,D=new class{isIOS=typeof navigator<"u"?/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1:!1;supportedBrowsers=["firefox","chrome","safari"];minFirefoxVersion=59;minChromeVersion=72;minSafariVersion=605;isWebRTCSupported(){return typeof RTCPeerConnection<"u"}isBrowserSupported(){let 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 Ze.browserDetails.browser}getVersion(){return Ze.browserDetails.version||0}isUnifiedPlanSupported(){let r=this.getBrowser(),e=Ze.browserDetails.version||0;if(r==="chrome"&&e<this.minChromeVersion)return!1;if(r==="firefox"&&e>=this.minFirefoxVersion)return!0;if(typeof RTCRtpTransceiver>"u"||!("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()}`}};var ie=()=>Math.random().toString(36).slice(2);var _t=r=>!r||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(r);var gt={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}]},et=class extends R{noop(){}CLOUD_HOST="signal.dendri.dev";CLOUD_PORT=443;chunkedBrowsers={Chrome:1,chrome:1};defaultConfig=gt;browser=D.getBrowser();browserVersion=D.getVersion();get isSafari(){return typeof navigator>"u"?!1:/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}get isIOS(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}pack=q;unpack=w;supports=(()=>{let e={browser:D.isBrowserSupported(),webRTC:D.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;let t;try{t=new RTCPeerConnection(gt),e.audioVideo=!0;let n;try{n=t.createDataChannel("_DENDRITEST",{ordered:!0}),e.data=!0,e.reliable=!!n.ordered;try{n.binaryType="blob",e.binaryBlob=!D.isIOS}catch{}}catch{}finally{n&&n.close()}}catch{}finally{t&&t.close()}return e})();validateId=_t;randomToken=ie;blobToArrayBuffer(e,t){let n=new FileReader;return n.onload=i=>{i.target&&t(i.target.result)},n.readAsArrayBuffer(e),n}binaryStringToArrayBuffer(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t.buffer}isSecure(){return typeof location<"u"&&location.protocol==="https:"}},_=new et;var Bt="2.4.0",oe=class r{constructor(e){this._options=e}_options;static FETCH_TIMEOUT=1e4;_buildRequest(e){let t=this._options.secure?"https":"http",{host:n,port:i,path:o,key:s}=this._options,a=new URL(`${t}://${n}:${i}${o}${s}/${e}`);a.searchParams.set("ts",`${Date.now()}${Math.random()}`),a.searchParams.set("version",Bt);let c=new AbortController,p=setTimeout(()=>c.abort(),r.FETCH_TIMEOUT);return fetch(a.href,{referrerPolicy:this._options.referrerPolicy,signal:c.signal}).finally(()=>clearTimeout(p))}async retrieveId(){try{let e=await this._buildRequest("id");if(e.status!==200)throw new Error(`Error. Status:${e.status}`);return e.text()}catch(e){l.error("Error retrieving ID",e);let t="";throw this._options.path==="/"&&this._options.host!==_.CLOUD_HOST&&(t=" If you passed in a `path` to your self-hosted Dendri server, you'll also need to pass in that same path when creating a new Dendri instance."),new Error(`Could not get an ID from the server.${t}`)}}async getTurnCredentials(){let e=this._options.secure?"https":"http",{host:t,port:n,path:i,key:o}=this._options,s=`${e}://${t}:${n}${i}${o}/turn-credentials`;try{let a=new AbortController,c=setTimeout(()=>a.abort(),r.FETCH_TIMEOUT),p=await fetch(s,{referrerPolicy:this._options.referrerPolicy,signal:a.signal}).finally(()=>clearTimeout(c));if(!p.ok)return[];let h=(await p.json()).iceServers;return h?Array.isArray(h)?h:[h]:[]}catch(a){return l.error("Error fetching TURN credentials",a),[]}}async listAllPeers(){try{let e=await this._buildRequest("peers");if(e.status!==200)throw e.status===401?new Error("It doesn't look like you have permission to list peers IDs. Check your server configuration and ensure allow_discovery is enabled."):new Error(`Error. Status:${e.status}`);return e.json()}catch(e){throw l.error("Error retrieving list peers",e),new Error("Could not get list peers from the server. "+(e instanceof Error?e.message:e))}}};var vt=L(ae(),1);var M=class extends vt.EventEmitter{emitError(e,t,n=!1){l.error("Error:",t);let i=new nt(`${e}`,t);i.retryable=n,this.emit("error",i)}},nt=class extends Error{type;retryable;details;constructor(e,t){typeof t=="string"?super(t):(super(t.message),this.stack=t.stack),this.type=e,this.retryable=!1}setRetryable(e){return this.retryable=e,this}setDetails(e){return this.details=e,this}};var I=class extends M{constructor(t,n,i){super();this.peer=t;this.provider=n;this.options=i;this.metadata=i.metadata}peer;provider;options;_open=!1;metadata;connectionId;peerConnection;dataChannel=null;label;get open(){return this._open}};var A=class{constructor(e){this.connection=e}connection;_pendingCandidates=[];_iceCandidateFilter=null;startConnection(e){let t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type==="media"&&e._stream&&(this._addTracksToConnection(e._stream,t),this._setCodecPreferences(t)),e.originator){let n=this.connection,i={ordered:!!e.reliable},o=t.createDataChannel(n.label,i);n._initializeDataChannel(o),this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){l.log("Creating RTCPeerConnection.");let e=new RTCPeerConnection(this.connection.provider?.options.config);if(this.connection.provider?.options.ipPolicy==="public"){let t=n=>!(n.candidate??"").includes("typ host");this._iceCandidateFilter=t}return this._setupListeners(e),e}_setupListeners(e){let t=this.connection.peer,n=this.connection.connectionId,i=this.connection.type,o=this.connection.provider;l.log("Listening for ICE candidates."),e.onicecandidate=s=>{s.candidate?.candidate&&(this._iceCandidateFilter&&!this._iceCandidateFilter(s.candidate)||(l.log(`Received ICE candidates for ${t}:`,s.candidate),o.socket.send({type:"CANDIDATE",payload:{candidate:s.candidate,type:i,connectionId:n},dst:t})))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":l.log(`iceConnectionState is failed, closing connections to ${t}`),this.connection.emitError("negotiation-failed",`Negotiation of connection to ${t} failed.`),this.connection.close();break;case"closed":l.log(`iceConnectionState is closed, closing connections to ${t}`),this.connection.emitError("connection-closed",`Connection to ${t} closed.`),this.connection.close();break;case"disconnected":l.log(`iceConnectionState changed to disconnected on the connection with ${t}`);break;case"completed":e.onicecandidate=()=>{};break}this.connection.emit("iceStateChanged",e.iceConnectionState)},l.log("Listening for data channel"),e.ondatachannel=s=>{l.log("Received data channel");let a=s.channel,c=o.getConnection(t,n);if(!c){l.warn(`Received data channel for non-existent connection ${n}`);return}c._initializeDataChannel(a)},l.log("Listening for remote stream"),e.ontrack=s=>{l.log("Received remote stream");let a=s.streams[0],c=o.getConnection(t,n);if(!c){l.warn(`Received remote stream for non-existent connection ${n}`);return}if(c.type==="media"){let p=c;this._addStreamToMediaConnection(a,p)}}}cleanup(){l.log(`Cleaning up PeerConnection to ${this.connection.peer}`);let e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,this._pendingCandidates=[],e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=()=>{};let t=e.signalingState!=="closed",n=!1,i=this.connection.dataChannel;i&&(n=!!i.readyState&&i.readyState!=="closed",n&&i.close()),(t||n)&&e.close()}async _makeOffer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createOffer(this.connection.options.constraints);if(!this.connection.peerConnection){l.log("PeerConnection closed during createOffer");return}l.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),this.connection.type==="media"&&n.sdp&&(n.sdp=this._applyH264SdpFallback(n.sdp,e));try{if(await e.setLocalDescription(n),!this.connection.peerConnection){l.log("PeerConnection closed during setLocalDescription");return}l.log("Set localDescription:",n,`for:${this.connection.peer}`);let i={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type==="data"){let o=this.connection;i={...i,label:o.label,reliable:o.reliable,serialization:o.serialization}}t.socket.send({type:"OFFER",payload:i,dst:this.connection.peer})}catch(i){i!=="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError("webrtc",i instanceof Error?i:String(i)),l.log("Failed to setLocalDescription, ",i))}}catch(n){t.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to createOffer, ",n)}}async _makeAnswer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createAnswer();if(!this.connection.peerConnection){l.log("PeerConnection closed during createAnswer");return}l.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),this.connection.type==="media"&&n.sdp&&(n.sdp=this._applyH264SdpFallback(n.sdp,e));try{if(await e.setLocalDescription(n),!this.connection.peerConnection){l.log("PeerConnection closed during setLocalDescription");return}l.log("Set localDescription:",n,`for:${this.connection.peer}`),t.socket.send({type:"ANSWER",payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(i){t.emitError("webrtc",i instanceof Error?i:String(i)),l.log("Failed to setLocalDescription, ",i)}}catch(n){t.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to create answer, ",n)}}async handleSDP(e,t){let n=this.connection.peerConnection,i=this.connection.provider;l.log("Setting remote description",t);try{if(await n.setRemoteDescription(t),!this.connection.peerConnection){l.log("PeerConnection closed during setRemoteDescription");return}if(l.log(`Set remoteDescription:${e} for:${this.connection.peer}`),this._pendingCandidates.length>0){l.log(`Flushing ${this._pendingCandidates.length} pending ICE candidates`);let o=this._pendingCandidates;this._pendingCandidates=[];for(let s of o)await this.handleCandidate(s)}e==="OFFER"&&await this._makeAnswer()}catch(o){i.emitError("webrtc",o instanceof Error?o:String(o)),l.log("Failed to setRemoteDescription, ",o)}}async handleCandidate(e){l.log("handleCandidate:",e);let t=this.connection.peerConnection;if(!t){l.warn(`PeerConnection not set for ${this.connection.peer}, cannot add ICE candidate`);return}if(!t.remoteDescription){l.log("Queueing ICE candidate (no remote description yet)"),this._pendingCandidates.push(e);return}try{await t.addIceCandidate(e),l.log(`Added ICE candidate for:${this.connection.peer}`)}catch(n){this.connection.provider?.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to handleCandidate, ",n)}}_setCodecPreferences(e){if(e.getTransceivers){for(let t of e.getTransceivers())if(t.sender?.track?.kind==="video"){let n=typeof RTCRtpReceiver<"u"?RTCRtpReceiver.getCapabilities?.("video")?.codecs:void 0;if(!n)continue;let i=n.filter(s=>s.mimeType==="video/H264"),o=n.filter(s=>s.mimeType!=="video/H264");if(i.length>0&&typeof t.setCodecPreferences=="function")try{t.setCodecPreferences([...i,...o])}catch{}}}}_preferH264InSdp(e){let t=e.split(`\r
|
|
41
|
+
isUnifiedPlanSupported:${this.isUnifiedPlanSupported()}`}};var ie=()=>Math.random().toString(36).slice(2);var _t=r=>!r||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(r);var gt={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}]},et=class extends R{noop(){}CLOUD_HOST="signal.dendri.dev";CLOUD_PORT=443;chunkedBrowsers={Chrome:1,chrome:1};defaultConfig=gt;browser=D.getBrowser();browserVersion=D.getVersion();get isSafari(){return typeof navigator>"u"?!1:/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}get isIOS(){return typeof navigator>"u"?!1:/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1}pack=q;unpack=G;supports=(()=>{let e={browser:D.isBrowserSupported(),webRTC:D.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!e.webRTC)return e;let t;try{t=new RTCPeerConnection(gt),e.audioVideo=!0;let n;try{n=t.createDataChannel("_DENDRITEST",{ordered:!0}),e.data=!0,e.reliable=!!n.ordered;try{n.binaryType="blob",e.binaryBlob=!D.isIOS}catch{}}catch{}finally{n&&n.close()}}catch{}finally{t&&t.close()}return e})();validateId=_t;randomToken=ie;blobToArrayBuffer(e,t){let n=new FileReader;return n.onload=i=>{i.target&&t(i.target.result)},n.readAsArrayBuffer(e),n}binaryStringToArrayBuffer(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t.buffer}isSecure(){return typeof location<"u"&&location.protocol==="https:"}},_=new et;var Bt="2.5.0",oe=class r{constructor(e){this._options=e}_options;static FETCH_TIMEOUT=1e4;_buildRequest(e){let t=this._options.secure?"https":"http",{host:n,port:i,path:o,key:s}=this._options,a=new URL(`${t}://${n}:${i}${o}${s}/${e}`);a.searchParams.set("ts",`${Date.now()}${Math.random()}`),a.searchParams.set("version",Bt),this._options.apiKey&&a.searchParams.set("api_key",this._options.apiKey);let c=new AbortController,p=setTimeout(()=>c.abort(),r.FETCH_TIMEOUT);return fetch(a.href,{referrerPolicy:this._options.referrerPolicy,signal:c.signal}).finally(()=>clearTimeout(p))}async retrieveId(){try{let e=await this._buildRequest("id");if(e.status!==200)throw new Error(`Error. Status:${e.status}`);return e.text()}catch(e){l.error("Error retrieving ID",e);let t="";throw this._options.path==="/"&&this._options.host!==_.CLOUD_HOST&&(t=" If you passed in a `path` to your self-hosted Dendri server, you'll also need to pass in that same path when creating a new Dendri instance."),new Error(`Could not get an ID from the server.${t}`)}}async getTurnCredentials(){let e=this._options.secure?"https":"http",{host:t,port:n,path:i,key:o}=this._options,s=new URL(`${e}://${t}:${n}${i}${o}/turn-credentials`);this._options.apiKey&&s.searchParams.set("api_key",this._options.apiKey);try{let a=new AbortController,c=setTimeout(()=>a.abort(),r.FETCH_TIMEOUT),p=await fetch(s.href,{referrerPolicy:this._options.referrerPolicy,signal:a.signal}).finally(()=>clearTimeout(c));if(!p.ok)return[];let h=(await p.json()).iceServers;return h?Array.isArray(h)?h:[h]:[]}catch(a){return l.error("Error fetching TURN credentials",a),[]}}async listAllPeers(){try{let e=await this._buildRequest("peers");if(e.status!==200)throw e.status===401?new Error("It doesn't look like you have permission to list peers IDs. Check your server configuration and ensure allow_discovery is enabled."):new Error(`Error. Status:${e.status}`);return e.json()}catch(e){throw l.error("Error retrieving list peers",e),new Error("Could not get list peers from the server. "+(e instanceof Error?e.message:e))}}};var vt=L(ae(),1);var M=class extends vt.EventEmitter{emitError(e,t,n=!1){l.error("Error:",t);let i=new nt(`${e}`,t);i.retryable=n,this.emit("error",i)}},nt=class extends Error{type;retryable;details;constructor(e,t){typeof t=="string"?super(t):(super(t.message),this.stack=t.stack),this.type=e,this.retryable=!1}setRetryable(e){return this.retryable=e,this}setDetails(e){return this.details=e,this}};var I=class extends M{constructor(t,n,i){super();this.peer=t;this.provider=n;this.options=i;this.metadata=i.metadata}peer;provider;options;_open=!1;metadata;connectionId;peerConnection;dataChannel=null;label;get open(){return this._open}};var A=class{constructor(e){this.connection=e}connection;_pendingCandidates=[];_iceCandidateFilter=null;startConnection(e){let t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type==="media"&&e._stream&&(this._addTracksToConnection(e._stream,t),this._setCodecPreferences(t)),e.originator){let n=this.connection,i={ordered:!!e.reliable},o=t.createDataChannel(n.label,i);n._initializeDataChannel(o),this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){l.log("Creating RTCPeerConnection.");let e=new RTCPeerConnection(this.connection.provider?.options.config);if(this.connection.provider?.options.ipPolicy==="public"){let t=n=>!(n.candidate??"").includes("typ host");this._iceCandidateFilter=t}return this._setupListeners(e),e}_setupListeners(e){let t=this.connection.peer,n=this.connection.connectionId,i=this.connection.type,o=this.connection.provider;l.log("Listening for ICE candidates."),e.onicecandidate=s=>{s.candidate?.candidate&&(this._iceCandidateFilter&&!this._iceCandidateFilter(s.candidate)||(l.log(`Received ICE candidates for ${t}:`,s.candidate),o.socket.send({type:"CANDIDATE",payload:{candidate:s.candidate,type:i,connectionId:n},dst:t})))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":l.log(`iceConnectionState is failed, closing connections to ${t}`),this.connection.emitError("negotiation-failed",`Negotiation of connection to ${t} failed.`),this.connection.close();break;case"closed":l.log(`iceConnectionState is closed, closing connections to ${t}`),this.connection.emitError("connection-closed",`Connection to ${t} closed.`),this.connection.close();break;case"disconnected":l.log(`iceConnectionState changed to disconnected on the connection with ${t}`);break;case"completed":e.onicecandidate=()=>{};break}this.connection.emit("iceStateChanged",e.iceConnectionState)},l.log("Listening for data channel"),e.ondatachannel=s=>{l.log("Received data channel");let a=s.channel,c=o.getConnection(t,n);if(!c){l.warn(`Received data channel for non-existent connection ${n}`);return}c._initializeDataChannel(a)},l.log("Listening for remote stream"),e.ontrack=s=>{l.log("Received remote stream");let a=s.streams[0],c=o.getConnection(t,n);if(!c){l.warn(`Received remote stream for non-existent connection ${n}`);return}if(c.type==="media"){let p=c;this._addStreamToMediaConnection(a,p)}}}cleanup(){l.log(`Cleaning up PeerConnection to ${this.connection.peer}`);let e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,this._pendingCandidates=[],e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=()=>{};let t=e.signalingState!=="closed",n=!1,i=this.connection.dataChannel;i&&(n=!!i.readyState&&i.readyState!=="closed",n&&i.close()),(t||n)&&e.close()}async _makeOffer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createOffer(this.connection.options.constraints);if(!this.connection.peerConnection){l.log("PeerConnection closed during createOffer");return}l.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),this.connection.type==="media"&&n.sdp&&(n.sdp=this._applyH264SdpFallback(n.sdp,e));try{if(await e.setLocalDescription(n),!this.connection.peerConnection){l.log("PeerConnection closed during setLocalDescription");return}l.log("Set localDescription:",n,`for:${this.connection.peer}`);let i={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type==="data"){let o=this.connection;i={...i,label:o.label,reliable:o.reliable,serialization:o.serialization}}t.socket.send({type:"OFFER",payload:i,dst:this.connection.peer})}catch(i){i!=="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(t.emitError("webrtc",i instanceof Error?i:String(i)),l.log("Failed to setLocalDescription, ",i))}}catch(n){t.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to createOffer, ",n)}}async _makeAnswer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createAnswer();if(!this.connection.peerConnection){l.log("PeerConnection closed during createAnswer");return}l.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp),this.connection.type==="media"&&n.sdp&&(n.sdp=this._applyH264SdpFallback(n.sdp,e));try{if(await e.setLocalDescription(n),!this.connection.peerConnection){l.log("PeerConnection closed during setLocalDescription");return}l.log("Set localDescription:",n,`for:${this.connection.peer}`),t.socket.send({type:"ANSWER",payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(i){t.emitError("webrtc",i instanceof Error?i:String(i)),l.log("Failed to setLocalDescription, ",i)}}catch(n){t.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to create answer, ",n)}}async handleSDP(e,t){let n=this.connection.peerConnection,i=this.connection.provider;l.log("Setting remote description",t);try{if(await n.setRemoteDescription(t),!this.connection.peerConnection){l.log("PeerConnection closed during setRemoteDescription");return}if(l.log(`Set remoteDescription:${e} for:${this.connection.peer}`),this._pendingCandidates.length>0){l.log(`Flushing ${this._pendingCandidates.length} pending ICE candidates`);let o=this._pendingCandidates;this._pendingCandidates=[];for(let s of o)await this.handleCandidate(s)}e==="OFFER"&&await this._makeAnswer()}catch(o){i.emitError("webrtc",o instanceof Error?o:String(o)),l.log("Failed to setRemoteDescription, ",o)}}async handleCandidate(e){l.log("handleCandidate:",e);let t=this.connection.peerConnection;if(!t){l.warn(`PeerConnection not set for ${this.connection.peer}, cannot add ICE candidate`);return}if(!t.remoteDescription){l.log("Queueing ICE candidate (no remote description yet)"),this._pendingCandidates.push(e);return}try{await t.addIceCandidate(e),l.log(`Added ICE candidate for:${this.connection.peer}`)}catch(n){this.connection.provider?.emitError("webrtc",n instanceof Error?n:String(n)),l.log("Failed to handleCandidate, ",n)}}_setCodecPreferences(e){if(e.getTransceivers){for(let t of e.getTransceivers())if(t.sender?.track?.kind==="video"){let n=typeof RTCRtpReceiver<"u"?RTCRtpReceiver.getCapabilities?.("video")?.codecs:void 0;if(!n)continue;let i=n.filter(s=>s.mimeType==="video/H264"),o=n.filter(s=>s.mimeType!=="video/H264");if(i.length>0&&typeof t.setCodecPreferences=="function")try{t.setCodecPreferences([...i,...o])}catch{}}}}_preferH264InSdp(e){let t=e.split(`\r
|
|
42
42
|
`),n=[],i=[];for(let o of t)if(o.includes("a=rtpmap:")&&o.toLowerCase().includes("h264")){let s=o.match(/a=rtpmap:(\d+)/);s&&i.push(s[1])}for(let o of t){if(o.startsWith("m=video")&&i.length>0){let s=o.split(" "),a=s.slice(0,3).join(" "),c=s.slice(3),p=[...i,...c.filter(d=>!i.includes(d))];n.push(`${a} ${p.join(" ")}`);continue}n.push(o)}return n.join(`\r
|
|
43
|
-
`)}_applyH264SdpFallback(e,t){return t.getTransceivers&&t.getTransceivers().some(i=>typeof i.setCodecPreferences=="function")?e:this._preferH264InSdp(e)}_addTracksToConnection(e,t){if(l.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack){l.error("Your browser doesn't support RTCPeerConnection#addTrack. Ignored.");return}e.getTracks().forEach(n=>{t.addTrack(n,e)})}_addStreamToMediaConnection(e,t){l.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}};var N=class r extends I{static ID_PREFIX="dc_";static MAX_BUFFERED_AMOUNT=8*1024*1024;_negotiator;reliable;get type(){return"data"}constructor(e,t,n){super(e,t,n),this.connectionId=this.options.connectionId||r.ID_PREFIX+ie(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new A(this),this._negotiator.startConnection(this.options._payload||{originator:!0,reliable:this.reliable})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{l.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this._applyAdaptiveBuffer(e),this.emit("open")},this.dataChannel.onclose=()=>{l.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}_applyAdaptiveBuffer(e){let t=this.peerConnection;!t||typeof t.getStats!="function"||t.getStats().then(n=>{let i=null;if(n.forEach(o=>{o.type==="candidate-pair"&&o.state==="succeeded"&&o.currentRoundTripTime&&(i=o.currentRoundTripTime*1e3)}),i!==null){let o=13107200*(i/1e3),s=Math.max(1*1024*1024,Math.min(32*1024*1024,Math.ceil(o)));e.bufferedAmountLowThreshold=s}}).catch(()=>{})}_flushCloseTimeout=null;close(e){if(e?.flush){this.send({__peerData:{type:"close"}}),this._flushCloseTimeout=setTimeout(()=>{this._flushCloseTimeout=null,this.close()},5e3);return}this._flushCloseTimeout&&(clearTimeout(this._flushCloseTimeout),this._flushCloseTimeout=null),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"),this.removeAllListeners())}send(e,t=!1){if(!this.open){this.emitError("not-open-yet","Connection is not open. You should listen for the `open` event before sending messages.");return}return this._send(e,t)}async handleMessage(e){let t=e.payload;switch(e.type){case"ANSWER":this._negotiator&&await this._negotiator.handleSDP(e.type,t.sdp);break;case"CANDIDATE":this._negotiator&&await this._negotiator.handleCandidate(t.candidate);break;default:l.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}};var S=class extends N{_buffer=[];_bufferSize=0;_buffering=!1;_bufferTimer=null;_messageHandler=null;get bufferSize(){return this._bufferSize}_initializeDataChannel(e){super._initializeDataChannel(e),this.dataChannel.binaryType="arraybuffer",this._messageHandler=t=>this._handleDataMessage(t),this.dataChannel?.addEventListener("message",this._messageHandler)}_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??0)>N.MAX_BUFFERED_AMOUNT)return this._buffering=!0,this._bufferTimer=setTimeout(()=>{this._bufferTimer=null,this._buffering=!1,this._tryBuffer()},50),!1;try{this.dataChannel?.send(e)}catch(t){return l.error(`DC#:${this.connectionId} Error when sending:`,t),this._buffering=!0,this.close(),!1}return!0}_tryBuffer(){for(;this.open&&this._buffer.length>0;){let e=this._buffer[0];if(!this._trySend(e))break;this._buffer.shift(),this._bufferSize=this._buffer.length}}close(e){if(e?.flush){this.send({__peerData:{type:"close"}});return}this._bufferTimer&&(clearTimeout(this._bufferTimer),this._bufferTimer=null),this.dataChannel&&this._messageHandler&&(this.dataChannel.removeEventListener("message",this._messageHandler),this._messageHandler=null),this._buffer=[],this._bufferSize=0,super.close()}};var O=class r extends S{chunker=new R;serialization="binary";static MAX_CHUNKED_SETS=256;_chunkedData={};close(e){this._chunkedData={},super.close(e)}_handleDataMessage({data:e}){let t;try{t=w(e)}catch(i){l.error(`DC#${this.connectionId} Failed to unpack data:`,i),this.emitError("not-open-yet","Failed to deserialize received data");return}let n=t.__peerData;if(n){if(n.type==="close"){this.close();return}this._handleChunk(t);return}this.emit("data",t)}_handleChunk(e){let t=e.__peerData;if(e.n<0||e.n>=e.total){l.warn(`DC#${this.connectionId} Invalid chunk index ${e.n} of ${e.total}, dropping`);return}let 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];let i=it(n.data);this._handleDataMessage({data:i})}else{let i=Object.keys(this._chunkedData);if(i.length>r.MAX_CHUNKED_SETS){let o=i[0];l.warn(`DC#${this.connectionId} Too many pending chunk sets (${i.length}), dropping oldest`),delete this._chunkedData[Number(o)]}}}_send(e,t){let n=q(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){let t=await e;if(!this.open){l.warn(`DC#${this.connectionId} Connection closed during async send, dropping message`);return}if(t.byteLength>this.chunker.chunkedMTU){this._sendChunks(t);return}this._bufferedSend(t)}_sendChunks(e){let t=this.chunker.chunk(e);l.log(`DC#${this.connectionId} Try to send ${t.length} chunks...`);for(let n of t)this.send(n,!0)}};var ce=class extends S{serialization="json";encoder=new TextEncoder;decoder=new TextDecoder;stringify=JSON.stringify;parse=JSON.parse;_handleDataMessage({data:e}){let t;try{t=this.parse(this.decoder.decode(e))}catch(i){l.error(`DC#${this.connectionId} Failed to parse JSON data:`,i),this.emitError("not-open-yet","Failed to parse received JSON data");return}let n=t.__peerData;if(n&&n.type==="close"){this.close();return}this.emit("data",t)}_send(e,t){let n=this.encoder.encode(this.stringify(e));if(n.byteLength>=_.chunkedMTU){this.emitError("message-too-big","Message too big for JSON channel");return}this._bufferedSend(n.buffer)}};var pe=class extends S{serialization="raw";_handleDataMessage({data:e}){super.emit("data",e)}_send(e,t){this._bufferedSend(e)}};var bt=L(ae(),1);var de=class{_pending=new Map;_counter=0;nextId(){return`ack_${++this._counter}_${Date.now()}`}waitForAck(e,t=5e3,n){return new Promise((i,o)=>{let s=setTimeout(()=>{this._pending.delete(e),o(new Error(`ACK timeout for ${e}`))},t);this._pending.set(e,{resolve:i,reject:o,timer:s,peerId:n})})}handleAck(e){let t=this._pending.get(e);return t?(clearTimeout(t.timer),t.resolve(),this._pending.delete(e),!0):!1}rejectAllForPeer(e){let t=0;for(let[n,i]of this._pending)i.peerId===e&&(clearTimeout(i.timer),i.reject(new Error(`Peer ${e} disconnected`)),this._pending.delete(n),t++);return t}clear(){for(let[,e]of this._pending)clearTimeout(e.timer),e.reject(new Error("Connection closed"));this._pending.clear()}get pendingCount(){return this._pending.size}};var le=class{_keyPair=null;_sharedKey=null;_ready=!1;get ready(){return this._ready}async generateKeyPair(){return this._keyPair=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]),crypto.subtle.exportKey("jwk",this._keyPair.publicKey)}async deriveSharedKey(e){if(!this._keyPair)throw new Error("Key pair not generated");let t=await crypto.subtle.importKey("jwk",e,{name:"ECDH",namedCurve:"P-256"},!1,[]);this._sharedKey=await crypto.subtle.deriveKey({name:"ECDH",public:t},this._keyPair.privateKey,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),this._ready=!0}async encrypt(e){if(!this._sharedKey)throw new Error("Shared key not derived");let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(e),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},this._sharedKey,n);return{iv:btoa(String.fromCharCode(...t)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(i)))}}async decrypt(e){if(!this._sharedKey)throw new Error("Shared key not derived");let t=Uint8Array.from(atob(e.iv),o=>o.charCodeAt(0)),n=Uint8Array.from(atob(e.ciphertext),o=>o.charCodeAt(0)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},this._sharedKey,n);return new TextDecoder().decode(i)}clear(){this._keyPair=null,this._sharedKey=null,this._ready=!1}};function Ct(r){return typeof r=="object"&&r!==null&&"__topic"in r&&typeof r.__topic=="string"&&"__data"in r}var he=class{_handlers=new Map;_globalHandlers=new Set;subscribe(e,t){return this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t),()=>{this._handlers.get(e)?.delete(t)}}subscribeAll(e){return this._globalHandlers.add(e),()=>{this._globalHandlers.delete(e)}}dispatch(e,t,n){let i=!1;if(e!==void 0&&this._handlers.has(e))for(let o of this._handlers.get(e))o(t,n),i=!0;for(let o of this._globalHandlers)o(t,n),i=!0;return i}clear(){this._handlers.clear(),this._globalHandlers.clear()}};var fe=class extends bt.EventEmitter{peer;_provider;_options;_dataConnection=null;_mode="reconnecting";_iceTimer=null;_upgradeTimer=null;_upgradeAttempts=0;_open=!1;_closed=!1;_ackManager=new de;_topics=new he;_encryption=new le;_encryptRelay;_keyExchangeSent=!1;_pendingRelayQueue=[];_expectedSeq=null;_reorderBuffer=new Map;_reorderTimeout=500;_reorderTimers=new Set;constructor(e,t,n={}){super(),this.peer=e,this._provider=t,this._options=Object.freeze({...n}),this._encryptRelay=n.encryptRelay??!0}get mode(){return this._mode}get open(){return this._open}start(){if(!this._closed){if(l.log(`HybridConnection: start peer=${this.peer} iceTimeout=${this._options.iceTimeout??1e4}ms encryptRelay=${this._encryptRelay}`),typeof this._provider?.on!="function"){this._attemptWebRTC();return}this._tryConnectionReversal().then(e=>{e||this._attemptWebRTC()})}}send(e,t){if(this._closed){this.emit("error",new Error("Connection is closed."));return}if(!this._open){this.emit("error",new Error("Connection is not open. Listen for the `open` event before sending."));return}let n=t?.topic,i=n?{__topic:n,__data:e}:e;this._mode==="webrtc"&&this._dataConnection?.open?this._dataConnection.send(i):this._mode==="ws-relay"?this._sendRelay(i):this.emit("error",new Error(`No transport available (current mode: ${this._mode}).`))}async sendWithAck(e,t){if(this._closed)throw new Error("Connection is closed.");if(!this._open)throw new Error("Connection is not open. Listen for the `open` event before sending.");let n=this._ackManager.nextId();if(this._mode==="webrtc"&&this._dataConnection?.open)this._dataConnection.send({__ackId:n,data:e});else if(this._mode==="ws-relay")this._sendRelay({__ackId:n,data:e});else throw new Error(`No transport available (current mode: ${this._mode}).`);return this._ackManager.waitForAck(n,t)}get ackManager(){return this._ackManager}subscribe(e,t){return this._topics.subscribe(e,t)}onData(e){return this._topics.subscribeAll(e)}handleRelayData(e,t){if(this._encryptRelay&&this._encryption.ready&&e!==null&&typeof e=="object"&&"__encrypted"in e){let n=e;this._encryption.decrypt(n.__encrypted).then(i=>{this._deliverInOrder(t,JSON.parse(i))}).catch(i=>{this.emit("error",new Error(`Relay decryption failed: ${String(i)}`))});return}this._deliverInOrder(t,e)}close(){if(!this._closed){this._closed=!0,this._clearIceTimer(),this._clearUpgradeTimer(),this._ackManager.clear(),this._topics.clear(),this._encryption.clear(),this._pendingRelayQueue=[],this._keyExchangeSent=!1,this._reorderBuffer.clear(),this._expectedSeq=null;for(let e of this._reorderTimers)clearTimeout(e);this._reorderTimers.clear(),this._dataConnection&&(this._dataConnection.close(),this._dataConnection=null),this._open&&(this._open=!1,this.emit("close")),this.removeAllListeners()}}initiateKeyExchange(){!this._encryptRelay||this._keyExchangeSent||(this._keyExchangeSent=!0,this._encryption.generateKeyPair().then(e=>{this._provider.socket.send({type:"KEY-EXCHANGE",dst:this.peer,payload:{publicKey:e}})}).catch(e=>{this._keyExchangeSent=!1,this.emit("error",new Error(`Key exchange initiation failed: ${String(e)}`))}))}handleKeyExchange(e){if(!this._encryptRelay)return;let t=n=>{this._encryption.deriveSharedKey(n).then(()=>{l.log(`HybridConnection: E2E encryption established with ${this.peer}`),this._flushPendingRelayQueue()}).catch(i=>{this.emit("error",new Error(`Key derivation failed: ${String(i)}`))})};this._keyExchangeSent?t(e.publicKey):(this._keyExchangeSent=!0,this._encryption.generateKeyPair().then(n=>{this._provider.socket.send({type:"KEY-EXCHANGE",dst:this.peer,payload:{publicKey:n}}),t(e.publicKey)}).catch(n=>{this._keyExchangeSent=!1,this.emit("error",new Error(`Key exchange response failed: ${String(n)}`))}))}_sendRelay(e){if(!this._encryptRelay){this._provider.socket.send({type:"DATA",dst:this.peer,payload:e});return}if(!this._encryption.ready){this._pendingRelayQueue.push(e);return}let t=JSON.stringify(e);this._encryption.encrypt(t).then(n=>{this._provider.socket.send({type:"DATA",dst:this.peer,payload:{__encrypted:n}})}).catch(n=>{this.emit("error",new Error(`Relay encryption failed: ${String(n)}`))})}_flushPendingRelayQueue(){let e=[...this._pendingRelayQueue];this._pendingRelayQueue=[];for(let t of e)this._sendRelay(t)}_deliverInOrder(e,t){if(e===void 0||!this._encryptRelay){this._dispatchIncoming(t);return}if(this._expectedSeq===null){this._dispatchIncoming(t),this._expectedSeq=e+1;return}if(e===this._expectedSeq)this._dispatchIncoming(t),this._expectedSeq=e+1,this._flushReorderBuffer();else if(e>this._expectedSeq){this._reorderBuffer.set(e,t);let n=setTimeout(()=>{this._reorderTimers.delete(n),!this._closed&&this._reorderBuffer.has(e)&&this._forceFlushReorderBuffer()},this._reorderTimeout);this._reorderTimers.add(n)}}_flushReorderBuffer(){if(this._expectedSeq!==null)for(;this._reorderBuffer.has(this._expectedSeq);)this._dispatchIncoming(this._reorderBuffer.get(this._expectedSeq)),this._reorderBuffer.delete(this._expectedSeq),this._expectedSeq++}_forceFlushReorderBuffer(){if(this._reorderBuffer.size===0)return;let e=Number.MAX_SAFE_INTEGER;for(let t of this._reorderBuffer.keys())t<e&&(e=t);this._expectedSeq=e,this._flushReorderBuffer()}_dispatchIncoming(e){Ct(e)?(this._topics.dispatch(e.__topic,e.__data,this.peer),this.emit("data",e.__data)):(this._topics.dispatch(void 0,e,this.peer),this.emit("data",e))}_attemptWebRTC(){if(this._closed)return;let e=this._options.iceTimeout??1e4,t=this._provider.connect(this.peer,{reliable:!0});if(!t){this._fallbackToRelay();return}this._dataConnection=t,this._iceTimer=setTimeout(()=>{this._mode!=="webrtc"&&(l.warn(`HybridConnection: ICE timeout after ${e}ms for ${this.peer}, falling back to relay`),this._fallbackToRelay())},e),this._dataConnection.on("open",()=>{l.log(`HybridConnection: WebRTC opened to ${this.peer} (attempt ${this._upgradeAttempts+1})`),this._clearIceTimer(),this._clearUpgradeTimer(),this._upgradeAttempts=0,this._setMode("webrtc"),this._open||(this._open=!0,this.emit("open"))}),this._dataConnection.on("data",n=>{this._dispatchIncoming(n)}),this._dataConnection.on("close",()=>{this._open&&!this._closed&&(l.log(`HybridConnection: WebRTC to ${this.peer} closed, falling back to relay`),this._dataConnection=null,this._fallbackToRelay())}),this._dataConnection.on("error",n=>{this.emit("error",n instanceof Error?n:new Error(String(n)))})}_fallbackToRelay(){this._closed||(this._clearIceTimer(),this._setMode("ws-relay"),this._open||(this._open=!0,this.emit("open")),this.initiateKeyExchange(),this._scheduleUpgrade())}_setMode(e){this._mode!==e&&(l.log(`HybridConnection: transport ${this._mode} -> ${e} for ${this.peer}`),this._mode=e,this.emit("transportChanged",e))}_clearIceTimer(){this._iceTimer!==null&&(clearTimeout(this._iceTimer),this._iceTimer=null)}_clearUpgradeTimer(){this._upgradeTimer!==null&&(clearInterval(this._upgradeTimer),this._upgradeTimer=null)}_scheduleUpgrade(){if(!(this._options.autoUpgrade??!0))return;this._clearUpgradeTimer();let e=this._options.upgradeInterval??6e4,t=this._options.maxUpgradeAttempts??5;this._upgradeTimer=setInterval(()=>{if(this._closed){this._clearUpgradeTimer();return}if(this._upgradeAttempts>=t){this._clearUpgradeTimer();return}this._upgradeAttempts++,this._attemptWebRTC()},e)}async _tryConnectionReversal(){if(typeof this._provider?.on!="function")return!1;try{if(!(await new Promise((o,s)=>{let a=setTimeout(()=>s(new Error("timeout")),3e3),c=p=>{clearTimeout(a),this._provider.off("CONNECT-REQUEST",c),o(p)};this._provider.on("CONNECT-REQUEST",c),this._provider.socket.send({type:"CONNECT-REQUEST",payload:{peer:this.peer}})}))?.address)return!1;let n=new RTCPeerConnection(this._provider.options.config),i=n.createDataChannel("probe",{id:0});return await new Promise((o,s)=>{let a=setTimeout(()=>{n.close(),s(new Error("direct-dial-timeout"))},2500);i.onopen=()=>{clearTimeout(a),o()},i.onerror=()=>{clearTimeout(a),n.close(),s(new Error("dc-error"))}}),this._dataConnection=void 0,this._setMode("webrtc"),n.close(),!0}catch{return!1}}async _gatherSrflxCandidates(){let e=new RTCPeerConnection({iceServers:this._provider.options.config?.iceServers});e.createDataChannel("probe");let t=await e.createOffer();await e.setLocalDescription(t);let n=[];return await new Promise(i=>{let o=setTimeout(i,2e3);e.onicecandidate=s=>{if(!s.candidate){clearTimeout(o),i();return}s.candidate.candidate.includes("typ host")||n.push(s.candidate.candidate)}}),e.close(),n}async _dcutrHolePunch(){try{let e=await this._gatherSrflxCandidates(),t=performance.now(),n=await new Promise((o,s)=>{let a=setTimeout(()=>s(new Error("dcutr-timeout")),8e3),c=p=>{clearTimeout(a),this._provider.off("DCUTR-CONNECT",c),o(p?.addresses??[])};this._provider.on("DCUTR-CONNECT",c),this._provider.socket.send({type:"DCUTR-CONNECT",payload:{addresses:e}})}),i=performance.now()-t;this._provider.socket.send({type:"DCUTR-SYNC",payload:{}}),await new Promise(o=>setTimeout(o,i/2));for(let o=0;o<Math.min(n.length,4);o++)try{let s=new RTCPeerConnection(this._provider.options.config);return await new Promise((a,c)=>{let p=setTimeout(()=>{s.close(),c(new Error("dc-dial-timeout"))},5e3),d=s.createDataChannel("dcutr");d.onopen=()=>{clearTimeout(p),a()}}),this._dataConnection=void 0,this._setMode("webrtc"),s.close(),!0}catch{}return!1}catch{return!1}}};var K=class r extends I{static ID_PREFIX="mc_";_negotiator;_localStream;_remoteStream=null;get type(){return"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||r.ID_PREFIX+_.randomToken(),this._negotiator=new A(this),this._localStream&&this._negotiator.startConnection({_stream:this._localStream,originator:!0})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{l.log(`DC#${this.connectionId} dc connection success`),this.emit("willCloseOnRemote")},this.dataChannel.onclose=()=>{l.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}addStream(e){l.log("Receiving stream",e),this._remoteStream=e,super.emit("stream",e)}handleMessage(e){let t=e.type,n=e.payload;switch(e.type){case"ANSWER":this._negotiator&&this._negotiator.handleSDP(t,n.sdp).then(()=>{this._open=!0});break;case"CANDIDATE":this._negotiator&&this._negotiator.handleCandidate(n.candidate);break;default:l.warn(`Unrecognized message type:${t} from peer:${this.peer}`);break}}answer(e,t={}){if(this._localStream){l.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}if(!this._negotiator||!this.provider){l.warn("Cannot answer a connection that has already been closed.");return}this._localStream=e??null,t?.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection({...this.options._payload,_stream:e});let n=this.provider._getMessages(this.connectionId);for(let i of n)this.handleMessage(i);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?._stream&&(this.options._stream=null),this.open&&(this._open=!1,super.emit("close"),this.removeAllListeners())}};var St=L(ae(),1),T=class extends St.EventEmitter{};var ue=class r extends T{_connected=!1;_disconnected=!0;_id;_token;_messagesQueue=[];_polling=!1;_autoReconnect=!0;_reconnectAttempt=0;_reconnectTimer;_heartbeatTimer;_lastSeq=0;_baseUrl;_pingInterval;_abortController;static BACKOFF_SCHEDULE=[0,1e3,2e3,4e3,8e3,16e3,3e4];static BACKOFF_JITTER=500;constructor(e,t,n,i,o,s=5e3,a){super();let c=e?"https://":"http://";this._baseUrl=`${c+t}:${n}${i}`,this._pingInterval=s}get reconnectAttempt(){return this._reconnectAttempt}start(e,t){this._id=e,this._token=t,this._disconnected=!1,this._connected=!0,this._reconnectAttempt=0,this._startPolling().catch(n=>{l.error("Polling start failed:",n),!this._disconnected&&this._autoReconnect&&this._scheduleReconnect()}),this._startHeartbeat(),this._sendQueuedMessages()}async _startPolling(){if(!(this._polling||this._disconnected)){for(this._polling=!0;this._polling&&!this._disconnected;)try{this._abortController=new AbortController;let e=new URLSearchParams({id:this._id,token:this._token});this._lastSeq>0&&e.set("last_seq",String(this._lastSeq));let t=await fetch(`${this._baseUrl}http/poll?${e}`,{signal:this._abortController.signal});if(!t.ok)throw new Error(`Poll failed: ${t.status}`);let n=await t.json();for(let i of n)typeof i.seq=="number"&&(this._lastSeq=i.seq),this.emit("message",i)}catch(e){if(e?.name==="AbortError")break;l.error("Poll error:",e),await new Promise(t=>setTimeout(t,1e3))}this._polling=!1,!this._disconnected&&this._autoReconnect&&this._scheduleReconnect()}}send(e){if(!this._disconnected){if(!this._id||!this._connected){this._messagesQueue.push(e);return}if(!e.type){this.emit("error","Invalid message");return}this._postMessage(e)}}async _postMessage(e){let t=new URLSearchParams({id:this._id,token:this._token});try{await fetch(`${this._baseUrl}http/send?${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{this._messagesQueue.push(e)}}close(){this._autoReconnect=!1,this._cleanup(),this._disconnected=!0}_getReconnectDelay(){let e=r.BACKOFF_SCHEDULE,t=Math.min(this._reconnectAttempt,e.length-1),n=e[t],i=Math.random()*r.BACKOFF_JITTER*2-r.BACKOFF_JITTER;return Math.max(0,n+i)}_scheduleReconnect(){this._reconnectAttempt++,this.emit("reconnect-attempt",this._reconnectAttempt);let e=this._getReconnectDelay();this._reconnectTimer=setTimeout(()=>{this._startPolling().catch(t=>{l.error("Polling reconnect failed:",t),!this._disconnected&&this._autoReconnect&&this._scheduleReconnect()})},Math.max(0,e))}_startHeartbeat(){this._heartbeatTimer=setInterval(()=>{this._connected&&this._postMessage({type:"HEARTBEAT"})},this._pingInterval)}_sendQueuedMessages(){let e=[...this._messagesQueue];this._messagesQueue=[];for(let t of e)this.send(t)}_cleanup(){this._polling=!1,this._abortController?.abort(),this._abortController=void 0,clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0,clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0,this._connected=!1}};var Tt="2.4.0",me=class r extends T{constructor(t,n,i,o,s,a=5e3,c){super();this.pingInterval=a;let p=t?"wss://":"ws://";this._baseUrl=`${p+n}:${i}${o}dendri?key=${s}`,this._jwt=c}pingInterval;_disconnected=!0;_id;_messagesQueue=[];_socket;_wsPingTimer;_heartbeatWorker=null;_heartbeatWorkerUrl=void 0;_visibilityHandler;_baseUrl;_autoReconnect=!0;_lastSeq=0;_reconnectAttempt=0;_reconnectTimer;_token;_jwt;static BACKOFF_SCHEDULE=[0,1e3,2e3,4e3,8e3,16e3,3e4];static BACKOFF_JITTER=500;start(t,n){this._id=t,this._token=n;let i=`${this._baseUrl}&id=${t}&token=${n}`;this._jwt&&(i+=`&jwt=${encodeURIComponent(this._jwt)}`),!(this._socket||!this._disconnected)&&(this._socket=new WebSocket(`${i}&version=${Tt}`),this._disconnected=!1,this._socket.onmessage=o=>{let s;try{s=JSON.parse(o.data),l.log("Server message received:",s)}catch{l.log("Invalid server message",o.data);return}s!==null&&typeof s=="object"&&"seq"in s&&typeof s.seq=="number"&&(this._lastSeq=s.seq),this.emit("message",s)},this._socket.onclose=o=>{this._disconnected||(l.log("Socket closed.",o),this._cleanup(),this._disconnected=!0,this._autoReconnect&&this._id&&this._token?this._scheduleReconnect():this.emit("disconnected"))},this._socket.onerror=o=>{l.error("Socket error:",o)},this._socket.onopen=()=>{if(this._disconnected)return;let o=this._reconnectAttempt>0;this._reconnectAttempt=0,this._sendQueuedMessages(),l.log("Socket open"),this._createHeartbeatWorker(),this._startWorkerHeartbeat(),o&&this.emit("reconnected")},typeof document<"u"&&(this._visibilityHandler=()=>{document.visibilityState==="hidden"?clearTimeout(this._wsPingTimer):this._wsOpen()?this._sendHeartbeat():this._autoReconnect&&!this._disconnected&&this._scheduleReconnect()},document.addEventListener("visibilitychange",this._visibilityHandler)))}_getReconnectDelay(){let t=r.BACKOFF_SCHEDULE,n=Math.min(this._reconnectAttempt,t.length-1),i=t[n],o=Math.random()*r.BACKOFF_JITTER*2-r.BACKOFF_JITTER;return Math.max(0,i+o)}get reconnectAttempt(){return this._reconnectAttempt}_scheduleReconnect(){let t=this._getReconnectDelay();this._reconnectAttempt++,this.emit("reconnect-attempt",this._reconnectAttempt),l.log(`Scheduling reconnect attempt ${this._reconnectAttempt} in ${Math.round(t)}ms`),this._reconnectTimer=setTimeout(()=>{if(this._reconnectTimer=void 0,!this._autoReconnect||!this._id||!this._token)return;let n=`${this._baseUrl}&id=${this._id}&token=${this._token}&version=${Tt}&last_seq=${this._lastSeq}`;this._jwt&&(n+=`&jwt=${encodeURIComponent(this._jwt)}`),this._disconnected=!1,this._socket=new WebSocket(n),this._socket.onmessage=i=>{let o;try{o=JSON.parse(i.data),l.log("Server message received:",o)}catch{l.log("Invalid server message",i.data);return}o!==null&&typeof o=="object"&&"seq"in o&&typeof o.seq=="number"&&(this._lastSeq=o.seq),this.emit("message",o)},this._socket.onclose=i=>{this._disconnected||(l.log("Socket closed during reconnect.",i),this._cleanup(),this._disconnected=!0,this._autoReconnect&&this._id&&this._token?this._scheduleReconnect():this.emit("disconnected"))},this._socket.onerror=i=>{l.error("Socket error during reconnect:",i)},this._socket.onopen=()=>{this._disconnected||(this._reconnectAttempt=0,this._sendQueuedMessages(),l.log("Socket reconnected"),this._createHeartbeatWorker(),this._startWorkerHeartbeat(),this.emit("reconnected"))}},t)}_createHeartbeatWorker(){if(!(typeof Worker>"u"||typeof Blob>"u"))try{let t=`
|
|
43
|
+
`)}_applyH264SdpFallback(e,t){return t.getTransceivers&&t.getTransceivers().some(i=>typeof i.setCodecPreferences=="function")?e:this._preferH264InSdp(e)}_addTracksToConnection(e,t){if(l.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack){l.error("Your browser doesn't support RTCPeerConnection#addTrack. Ignored.");return}e.getTracks().forEach(n=>{t.addTrack(n,e)})}_addStreamToMediaConnection(e,t){l.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}};var N=class r extends I{static ID_PREFIX="dc_";static MAX_BUFFERED_AMOUNT=8*1024*1024;_negotiator;reliable;get type(){return"data"}constructor(e,t,n){super(e,t,n),this.connectionId=this.options.connectionId||r.ID_PREFIX+ie(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new A(this),this._negotiator.startConnection(this.options._payload||{originator:!0,reliable:this.reliable})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{l.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this._applyAdaptiveBuffer(e),this.emit("open")},this.dataChannel.onclose=()=>{l.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}_applyAdaptiveBuffer(e){let t=this.peerConnection;!t||typeof t.getStats!="function"||t.getStats().then(n=>{let i=null;if(n.forEach(o=>{o.type==="candidate-pair"&&o.state==="succeeded"&&o.currentRoundTripTime&&(i=o.currentRoundTripTime*1e3)}),i!==null){let o=13107200*(i/1e3),s=Math.max(1*1024*1024,Math.min(32*1024*1024,Math.ceil(o)));e.bufferedAmountLowThreshold=s}}).catch(()=>{})}_flushCloseTimeout=null;close(e){if(e?.flush){this.send({__peerData:{type:"close"}}),this._flushCloseTimeout=setTimeout(()=>{this._flushCloseTimeout=null,this.close()},5e3);return}this._flushCloseTimeout&&(clearTimeout(this._flushCloseTimeout),this._flushCloseTimeout=null),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"),this.removeAllListeners())}send(e,t=!1){if(!this.open){this.emitError("not-open-yet","Connection is not open. You should listen for the `open` event before sending messages.");return}return this._send(e,t)}async handleMessage(e){let t=e.payload;switch(e.type){case"ANSWER":this._negotiator&&await this._negotiator.handleSDP(e.type,t.sdp);break;case"CANDIDATE":this._negotiator&&await this._negotiator.handleCandidate(t.candidate);break;default:l.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}}};var S=class extends N{_buffer=[];_bufferSize=0;_buffering=!1;_bufferTimer=null;_messageHandler=null;get bufferSize(){return this._bufferSize}_initializeDataChannel(e){super._initializeDataChannel(e),this.dataChannel.binaryType="arraybuffer",this._messageHandler=t=>this._handleDataMessage(t),this.dataChannel?.addEventListener("message",this._messageHandler)}_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??0)>N.MAX_BUFFERED_AMOUNT)return this._buffering=!0,this._bufferTimer=setTimeout(()=>{this._bufferTimer=null,this._buffering=!1,this._tryBuffer()},50),!1;try{this.dataChannel?.send(e)}catch(t){return l.error(`DC#:${this.connectionId} Error when sending:`,t),this._buffering=!0,this.close(),!1}return!0}_tryBuffer(){for(;this.open&&this._buffer.length>0;){let e=this._buffer[0];if(!this._trySend(e))break;this._buffer.shift(),this._bufferSize=this._buffer.length}}close(e){if(e?.flush){this.send({__peerData:{type:"close"}});return}this._bufferTimer&&(clearTimeout(this._bufferTimer),this._bufferTimer=null),this.dataChannel&&this._messageHandler&&(this.dataChannel.removeEventListener("message",this._messageHandler),this._messageHandler=null),this._buffer=[],this._bufferSize=0,super.close()}};var O=class r extends S{chunker=new R;serialization="binary";static MAX_CHUNKED_SETS=256;_chunkedData={};close(e){this._chunkedData={},super.close(e)}_handleDataMessage({data:e}){let t;try{t=G(e)}catch(i){l.error(`DC#${this.connectionId} Failed to unpack data:`,i),this.emitError("not-open-yet","Failed to deserialize received data");return}let n=t.__peerData;if(n){if(n.type==="close"){this.close();return}this._handleChunk(t);return}this.emit("data",t)}_handleChunk(e){let t=e.__peerData;if(e.n<0||e.n>=e.total){l.warn(`DC#${this.connectionId} Invalid chunk index ${e.n} of ${e.total}, dropping`);return}let 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];let i=it(n.data);this._handleDataMessage({data:i})}else{let i=Object.keys(this._chunkedData);if(i.length>r.MAX_CHUNKED_SETS){let o=i[0];l.warn(`DC#${this.connectionId} Too many pending chunk sets (${i.length}), dropping oldest`),delete this._chunkedData[Number(o)]}}}_send(e,t){let n=q(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){let t=await e;if(!this.open){l.warn(`DC#${this.connectionId} Connection closed during async send, dropping message`);return}if(t.byteLength>this.chunker.chunkedMTU){this._sendChunks(t);return}this._bufferedSend(t)}_sendChunks(e){let t=this.chunker.chunk(e);l.log(`DC#${this.connectionId} Try to send ${t.length} chunks...`);for(let n of t)this.send(n,!0)}};var ce=class extends S{serialization="json";encoder=new TextEncoder;decoder=new TextDecoder;stringify=JSON.stringify;parse=JSON.parse;_handleDataMessage({data:e}){let t;try{t=this.parse(this.decoder.decode(e))}catch(i){l.error(`DC#${this.connectionId} Failed to parse JSON data:`,i),this.emitError("not-open-yet","Failed to parse received JSON data");return}let n=t.__peerData;if(n&&n.type==="close"){this.close();return}this.emit("data",t)}_send(e,t){let n=this.encoder.encode(this.stringify(e));if(n.byteLength>=_.chunkedMTU){this.emitError("message-too-big","Message too big for JSON channel");return}this._bufferedSend(n.buffer)}};var pe=class extends S{serialization="raw";_handleDataMessage({data:e}){super.emit("data",e)}_send(e,t){this._bufferedSend(e)}};var bt=L(ae(),1);var de=class{_pending=new Map;_counter=0;nextId(){return`ack_${++this._counter}_${Date.now()}`}waitForAck(e,t=5e3,n){return new Promise((i,o)=>{let s=setTimeout(()=>{this._pending.delete(e),o(new Error(`ACK timeout for ${e}`))},t);this._pending.set(e,{resolve:i,reject:o,timer:s,peerId:n})})}handleAck(e){let t=this._pending.get(e);return t?(clearTimeout(t.timer),t.resolve(),this._pending.delete(e),!0):!1}rejectAllForPeer(e){let t=0;for(let[n,i]of this._pending)i.peerId===e&&(clearTimeout(i.timer),i.reject(new Error(`Peer ${e} disconnected`)),this._pending.delete(n),t++);return t}clear(){for(let[,e]of this._pending)clearTimeout(e.timer),e.reject(new Error("Connection closed"));this._pending.clear()}get pendingCount(){return this._pending.size}};var le=class{_keyPair=null;_sharedKey=null;_ready=!1;get ready(){return this._ready}async generateKeyPair(){return this._keyPair=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"]),crypto.subtle.exportKey("jwk",this._keyPair.publicKey)}async deriveSharedKey(e){if(!this._keyPair)throw new Error("Key pair not generated");let t=await crypto.subtle.importKey("jwk",e,{name:"ECDH",namedCurve:"P-256"},!1,[]);this._sharedKey=await crypto.subtle.deriveKey({name:"ECDH",public:t},this._keyPair.privateKey,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),this._ready=!0}async encrypt(e){if(!this._sharedKey)throw new Error("Shared key not derived");let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(e),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},this._sharedKey,n);return{iv:btoa(String.fromCharCode(...t)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(i)))}}async decrypt(e){if(!this._sharedKey)throw new Error("Shared key not derived");let t=Uint8Array.from(atob(e.iv),o=>o.charCodeAt(0)),n=Uint8Array.from(atob(e.ciphertext),o=>o.charCodeAt(0)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},this._sharedKey,n);return new TextDecoder().decode(i)}clear(){this._keyPair=null,this._sharedKey=null,this._ready=!1}};function Ct(r){return typeof r=="object"&&r!==null&&"__topic"in r&&typeof r.__topic=="string"&&"__data"in r}var he=class{_handlers=new Map;_globalHandlers=new Set;subscribe(e,t){return this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t),()=>{this._handlers.get(e)?.delete(t)}}subscribeAll(e){return this._globalHandlers.add(e),()=>{this._globalHandlers.delete(e)}}dispatch(e,t,n){let i=!1;if(e!==void 0&&this._handlers.has(e))for(let o of this._handlers.get(e))o(t,n),i=!0;for(let o of this._globalHandlers)o(t,n),i=!0;return i}clear(){this._handlers.clear(),this._globalHandlers.clear()}};var fe=class extends bt.EventEmitter{peer;_provider;_options;_dataConnection=null;_mode="reconnecting";_iceTimer=null;_upgradeTimer=null;_upgradeAttempts=0;_open=!1;_closed=!1;_ackManager=new de;_topics=new he;_encryption=new le;_encryptRelay;_keyExchangeSent=!1;_pendingRelayQueue=[];_expectedSeq=null;_reorderBuffer=new Map;_reorderTimeout=500;_reorderTimers=new Set;constructor(e,t,n={}){super(),this.peer=e,this._provider=t,this._options=Object.freeze({...n}),this._encryptRelay=n.encryptRelay??!0}get mode(){return this._mode}get open(){return this._open}start(){if(!this._closed){if(l.log(`HybridConnection: start peer=${this.peer} iceTimeout=${this._options.iceTimeout??1e4}ms encryptRelay=${this._encryptRelay}`),typeof this._provider?.on!="function"){this._attemptWebRTC();return}this._tryConnectionReversal().then(e=>{e||this._attemptWebRTC()})}}send(e,t){if(this._closed){this.emit("error",new Error("Connection is closed."));return}if(!this._open){this.emit("error",new Error("Connection is not open. Listen for the `open` event before sending."));return}let n=t?.topic,i=n?{__topic:n,__data:e}:e;this._mode==="webrtc"&&this._dataConnection?.open?this._dataConnection.send(i):this._mode==="ws-relay"?this._sendRelay(i):this.emit("error",new Error(`No transport available (current mode: ${this._mode}).`))}async sendWithAck(e,t){if(this._closed)throw new Error("Connection is closed.");if(!this._open)throw new Error("Connection is not open. Listen for the `open` event before sending.");let n=this._ackManager.nextId();if(this._mode==="webrtc"&&this._dataConnection?.open)this._dataConnection.send({__ackId:n,data:e});else if(this._mode==="ws-relay")this._sendRelay({__ackId:n,data:e});else throw new Error(`No transport available (current mode: ${this._mode}).`);return this._ackManager.waitForAck(n,t)}get ackManager(){return this._ackManager}subscribe(e,t){return this._topics.subscribe(e,t)}onData(e){return this._topics.subscribeAll(e)}handleRelayData(e,t){if(this._encryptRelay&&this._encryption.ready&&e!==null&&typeof e=="object"&&"__encrypted"in e){let n=e;this._encryption.decrypt(n.__encrypted).then(i=>{this._deliverInOrder(t,JSON.parse(i))}).catch(i=>{this.emit("error",new Error(`Relay decryption failed: ${String(i)}`))});return}this._deliverInOrder(t,e)}close(){if(!this._closed){this._closed=!0,this._clearIceTimer(),this._clearUpgradeTimer(),this._ackManager.clear(),this._topics.clear(),this._encryption.clear(),this._pendingRelayQueue=[],this._keyExchangeSent=!1,this._reorderBuffer.clear(),this._expectedSeq=null;for(let e of this._reorderTimers)clearTimeout(e);this._reorderTimers.clear(),this._dataConnection&&(this._dataConnection.close(),this._dataConnection=null),this._open&&(this._open=!1,this.emit("close")),this.removeAllListeners()}}initiateKeyExchange(){!this._encryptRelay||this._keyExchangeSent||(this._keyExchangeSent=!0,this._encryption.generateKeyPair().then(e=>{this._provider.socket.send({type:"KEY-EXCHANGE",dst:this.peer,payload:{publicKey:e}})}).catch(e=>{this._keyExchangeSent=!1,this.emit("error",new Error(`Key exchange initiation failed: ${String(e)}`))}))}handleKeyExchange(e){if(!this._encryptRelay)return;let t=n=>{this._encryption.deriveSharedKey(n).then(()=>{l.log(`HybridConnection: E2E encryption established with ${this.peer}`),this._flushPendingRelayQueue()}).catch(i=>{this.emit("error",new Error(`Key derivation failed: ${String(i)}`))})};this._keyExchangeSent?t(e.publicKey):(this._keyExchangeSent=!0,this._encryption.generateKeyPair().then(n=>{this._provider.socket.send({type:"KEY-EXCHANGE",dst:this.peer,payload:{publicKey:n}}),t(e.publicKey)}).catch(n=>{this._keyExchangeSent=!1,this.emit("error",new Error(`Key exchange response failed: ${String(n)}`))}))}_sendRelay(e){if(!this._encryptRelay){this._provider.socket.send({type:"DATA",dst:this.peer,payload:e});return}if(!this._encryption.ready){this._pendingRelayQueue.push(e);return}let t=JSON.stringify(e);this._encryption.encrypt(t).then(n=>{this._provider.socket.send({type:"DATA",dst:this.peer,payload:{__encrypted:n}})}).catch(n=>{this.emit("error",new Error(`Relay encryption failed: ${String(n)}`))})}_flushPendingRelayQueue(){let e=[...this._pendingRelayQueue];this._pendingRelayQueue=[];for(let t of e)this._sendRelay(t)}_deliverInOrder(e,t){if(e===void 0||!this._encryptRelay){this._dispatchIncoming(t);return}if(this._expectedSeq===null){this._dispatchIncoming(t),this._expectedSeq=e+1;return}if(e===this._expectedSeq)this._dispatchIncoming(t),this._expectedSeq=e+1,this._flushReorderBuffer();else if(e>this._expectedSeq){this._reorderBuffer.set(e,t);let n=setTimeout(()=>{this._reorderTimers.delete(n),!this._closed&&this._reorderBuffer.has(e)&&this._forceFlushReorderBuffer()},this._reorderTimeout);this._reorderTimers.add(n)}}_flushReorderBuffer(){if(this._expectedSeq!==null)for(;this._reorderBuffer.has(this._expectedSeq);)this._dispatchIncoming(this._reorderBuffer.get(this._expectedSeq)),this._reorderBuffer.delete(this._expectedSeq),this._expectedSeq++}_forceFlushReorderBuffer(){if(this._reorderBuffer.size===0)return;let e=Number.MAX_SAFE_INTEGER;for(let t of this._reorderBuffer.keys())t<e&&(e=t);this._expectedSeq=e,this._flushReorderBuffer()}_dispatchIncoming(e){Ct(e)?(this._topics.dispatch(e.__topic,e.__data,this.peer),this.emit("data",e.__data)):(this._topics.dispatch(void 0,e,this.peer),this.emit("data",e))}_attemptWebRTC(){if(this._closed)return;let e=this._options.iceTimeout??1e4,t=this._provider.connect(this.peer,{reliable:!0});if(!t){this._fallbackToRelay();return}this._dataConnection=t,this._iceTimer=setTimeout(()=>{this._mode!=="webrtc"&&(l.warn(`HybridConnection: ICE timeout after ${e}ms for ${this.peer}, falling back to relay`),this._fallbackToRelay())},e),this._dataConnection.on("open",()=>{l.log(`HybridConnection: WebRTC opened to ${this.peer} (attempt ${this._upgradeAttempts+1})`),this._clearIceTimer(),this._clearUpgradeTimer(),this._upgradeAttempts=0,this._setMode("webrtc"),this._open||(this._open=!0,this.emit("open"))}),this._dataConnection.on("data",n=>{this._dispatchIncoming(n)}),this._dataConnection.on("close",()=>{this._open&&!this._closed&&(l.log(`HybridConnection: WebRTC to ${this.peer} closed, falling back to relay`),this._dataConnection=null,this._fallbackToRelay())}),this._dataConnection.on("error",n=>{this.emit("error",n instanceof Error?n:new Error(String(n)))})}_fallbackToRelay(){this._closed||(this._clearIceTimer(),this._setMode("ws-relay"),this._open||(this._open=!0,this.emit("open")),this.initiateKeyExchange(),this._scheduleUpgrade())}_setMode(e){this._mode!==e&&(l.log(`HybridConnection: transport ${this._mode} -> ${e} for ${this.peer}`),this._mode=e,this.emit("transportChanged",e))}_clearIceTimer(){this._iceTimer!==null&&(clearTimeout(this._iceTimer),this._iceTimer=null)}_clearUpgradeTimer(){this._upgradeTimer!==null&&(clearInterval(this._upgradeTimer),this._upgradeTimer=null)}_scheduleUpgrade(){if(!(this._options.autoUpgrade??!0))return;this._clearUpgradeTimer();let e=this._options.upgradeInterval??6e4,t=this._options.maxUpgradeAttempts??5;this._upgradeTimer=setInterval(()=>{if(this._closed){this._clearUpgradeTimer();return}if(this._upgradeAttempts>=t){this._clearUpgradeTimer();return}this._upgradeAttempts++,this._attemptWebRTC()},e)}async _tryConnectionReversal(){if(typeof this._provider?.on!="function")return!1;try{if(!(await new Promise((o,s)=>{let a=setTimeout(()=>s(new Error("timeout")),3e3),c=p=>{clearTimeout(a),this._provider.off("CONNECT-REQUEST",c),o(p)};this._provider.on("CONNECT-REQUEST",c),this._provider.socket.send({type:"CONNECT-REQUEST",payload:{peer:this.peer}})}))?.address)return!1;let n=new RTCPeerConnection(this._provider.options.config),i=n.createDataChannel("probe",{id:0});return await new Promise((o,s)=>{let a=setTimeout(()=>{n.close(),s(new Error("direct-dial-timeout"))},2500);i.onopen=()=>{clearTimeout(a),o()},i.onerror=()=>{clearTimeout(a),n.close(),s(new Error("dc-error"))}}),this._dataConnection=void 0,this._setMode("webrtc"),n.close(),!0}catch{return!1}}async _gatherSrflxCandidates(){let e=new RTCPeerConnection({iceServers:this._provider.options.config?.iceServers});e.createDataChannel("probe");let t=await e.createOffer();await e.setLocalDescription(t);let n=[];return await new Promise(i=>{let o=setTimeout(i,2e3);e.onicecandidate=s=>{if(!s.candidate){clearTimeout(o),i();return}s.candidate.candidate.includes("typ host")||n.push(s.candidate.candidate)}}),e.close(),n}async _dcutrHolePunch(){try{let e=await this._gatherSrflxCandidates(),t=performance.now(),n=await new Promise((o,s)=>{let a=setTimeout(()=>s(new Error("dcutr-timeout")),8e3),c=p=>{clearTimeout(a),this._provider.off("DCUTR-CONNECT",c),o(p?.addresses??[])};this._provider.on("DCUTR-CONNECT",c),this._provider.socket.send({type:"DCUTR-CONNECT",payload:{addresses:e}})}),i=performance.now()-t;this._provider.socket.send({type:"DCUTR-SYNC",payload:{}}),await new Promise(o=>setTimeout(o,i/2));for(let o=0;o<Math.min(n.length,4);o++)try{let s=new RTCPeerConnection(this._provider.options.config);return await new Promise((a,c)=>{let p=setTimeout(()=>{s.close(),c(new Error("dc-dial-timeout"))},5e3),d=s.createDataChannel("dcutr");d.onopen=()=>{clearTimeout(p),a()}}),this._dataConnection=void 0,this._setMode("webrtc"),s.close(),!0}catch{}return!1}catch{return!1}}};var K=class r extends I{static ID_PREFIX="mc_";_negotiator;_localStream;_remoteStream=null;get type(){return"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||r.ID_PREFIX+_.randomToken(),this._negotiator=new A(this),this._localStream&&this._negotiator.startConnection({_stream:this._localStream,originator:!0})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{l.log(`DC#${this.connectionId} dc connection success`),this.emit("willCloseOnRemote")},this.dataChannel.onclose=()=>{l.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}addStream(e){l.log("Receiving stream",e),this._remoteStream=e,super.emit("stream",e)}handleMessage(e){let t=e.type,n=e.payload;switch(e.type){case"ANSWER":this._negotiator&&this._negotiator.handleSDP(t,n.sdp).then(()=>{this._open=!0});break;case"CANDIDATE":this._negotiator&&this._negotiator.handleCandidate(n.candidate);break;default:l.warn(`Unrecognized message type:${t} from peer:${this.peer}`);break}}answer(e,t={}){if(this._localStream){l.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}if(!this._negotiator||!this.provider){l.warn("Cannot answer a connection that has already been closed.");return}this._localStream=e??null,t?.sdpTransform&&(this.options.sdpTransform=t.sdpTransform),this._negotiator.startConnection({...this.options._payload,_stream:e});let n=this.provider._getMessages(this.connectionId);for(let i of n)this.handleMessage(i);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?._stream&&(this.options._stream=null),this.open&&(this._open=!1,super.emit("close"),this.removeAllListeners())}};var St=L(ae(),1),T=class extends St.EventEmitter{};var ue=class r extends T{_connected=!1;_disconnected=!0;_id;_token;_messagesQueue=[];_polling=!1;_autoReconnect=!0;_reconnectAttempt=0;_reconnectTimer;_heartbeatTimer;_lastSeq=0;_baseUrl;_key;_jwt;_apiKey;_pingInterval;_abortController;static BACKOFF_SCHEDULE=[0,1e3,2e3,4e3,8e3,16e3,3e4];static BACKOFF_JITTER=500;constructor(e,t,n,i,o,s=5e3,a,c){super();let p=e?"https://":"http://";this._baseUrl=`${p+t}:${n}${i}`,this._pingInterval=s,this._key=o,this._jwt=a,this._apiKey=c}_applyAuthParams(e){e.set("key",this._key),this._jwt&&e.set("jwt",this._jwt),this._apiKey&&e.set("api_key",this._apiKey)}get reconnectAttempt(){return this._reconnectAttempt}start(e,t){this._id=e,this._token=t,this._disconnected=!1,this._connected=!0,this._reconnectAttempt=0,this._startPolling().catch(n=>{l.error("Polling start failed:",n),!this._disconnected&&this._autoReconnect&&this._scheduleReconnect()}),this._startHeartbeat(),this._sendQueuedMessages()}async _startPolling(){if(!(this._polling||this._disconnected)){for(this._polling=!0;this._polling&&!this._disconnected;)try{this._abortController=new AbortController;let e=new URLSearchParams({id:this._id,token:this._token});this._applyAuthParams(e),this._lastSeq>0&&e.set("last_seq",String(this._lastSeq));let t=await fetch(`${this._baseUrl}http/poll?${e}`,{signal:this._abortController.signal});if(!t.ok)throw new Error(`Poll failed: ${t.status}`);let n=await t.json();for(let i of n)typeof i.seq=="number"&&(this._lastSeq=i.seq),this.emit("message",i)}catch(e){if(e?.name==="AbortError")break;l.error("Poll error:",e),await new Promise(t=>setTimeout(t,1e3))}this._polling=!1,!this._disconnected&&this._autoReconnect&&this._scheduleReconnect()}}send(e){if(!this._disconnected){if(!this._id||!this._connected){this._messagesQueue.push(e);return}if(!e.type){this.emit("error","Invalid message");return}this._postMessage(e)}}async _postMessage(e){let t=new URLSearchParams({id:this._id,token:this._token});this._applyAuthParams(t);try{await fetch(`${this._baseUrl}http/send?${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{this._messagesQueue.push(e)}}close(){this._autoReconnect=!1,this._cleanup(),this._disconnected=!0}_getReconnectDelay(){let e=r.BACKOFF_SCHEDULE,t=Math.min(this._reconnectAttempt,e.length-1),n=e[t],i=Math.random()*r.BACKOFF_JITTER*2-r.BACKOFF_JITTER;return Math.max(0,n+i)}_scheduleReconnect(){this._reconnectAttempt++,this.emit("reconnect-attempt",this._reconnectAttempt);let e=this._getReconnectDelay();this._reconnectTimer=setTimeout(()=>{this._startPolling().catch(t=>{l.error("Polling reconnect failed:",t),!this._disconnected&&this._autoReconnect&&this._scheduleReconnect()})},Math.max(0,e))}_startHeartbeat(){this._heartbeatTimer=setInterval(()=>{this._connected&&this._postMessage({type:"HEARTBEAT"})},this._pingInterval)}_sendQueuedMessages(){let e=[...this._messagesQueue];this._messagesQueue=[];for(let t of e)this.send(t)}_cleanup(){this._polling=!1,this._abortController?.abort(),this._abortController=void 0,clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0,clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0,this._connected=!1}};var Tt="2.5.0",me=class r extends T{constructor(t,n,i,o,s,a=5e3,c,p){super();this.pingInterval=a;let d=t?"wss://":"ws://";this._baseUrl=`${d+n}:${i}${o}dendri?key=${s}`,p&&(this._baseUrl+=`&api_key=${encodeURIComponent(p)}`),this._jwt=c}pingInterval;_disconnected=!0;_id;_messagesQueue=[];_socket;_wsPingTimer;_heartbeatWorker=null;_heartbeatWorkerUrl=void 0;_visibilityHandler;_baseUrl;_autoReconnect=!0;_lastSeq=0;_reconnectAttempt=0;_reconnectTimer;_token;_jwt;static BACKOFF_SCHEDULE=[0,1e3,2e3,4e3,8e3,16e3,3e4];static BACKOFF_JITTER=500;start(t,n){this._id=t,this._token=n;let i=`${this._baseUrl}&id=${t}&token=${n}`;this._jwt&&(i+=`&jwt=${encodeURIComponent(this._jwt)}`),!(this._socket||!this._disconnected)&&(this._socket=new WebSocket(`${i}&version=${Tt}`),this._disconnected=!1,this._socket.onmessage=o=>{let s;try{s=JSON.parse(o.data),l.log("Server message received:",s)}catch{l.log("Invalid server message",o.data);return}s!==null&&typeof s=="object"&&"seq"in s&&typeof s.seq=="number"&&(this._lastSeq=s.seq),this.emit("message",s)},this._socket.onclose=o=>{this._disconnected||(l.log("Socket closed.",o),this._cleanup(),this._disconnected=!0,this._autoReconnect&&this._id&&this._token?this._scheduleReconnect():this.emit("disconnected"))},this._socket.onerror=o=>{l.error("Socket error:",o)},this._socket.onopen=()=>{if(this._disconnected)return;let o=this._reconnectAttempt>0;this._reconnectAttempt=0,this._sendQueuedMessages(),l.log("Socket open"),this._createHeartbeatWorker(),this._startWorkerHeartbeat(),o&&this.emit("reconnected")},typeof document<"u"&&(this._visibilityHandler=()=>{document.visibilityState==="hidden"?clearTimeout(this._wsPingTimer):this._wsOpen()?this._sendHeartbeat():this._autoReconnect&&!this._disconnected&&this._scheduleReconnect()},document.addEventListener("visibilitychange",this._visibilityHandler)))}_getReconnectDelay(){let t=r.BACKOFF_SCHEDULE,n=Math.min(this._reconnectAttempt,t.length-1),i=t[n],o=Math.random()*r.BACKOFF_JITTER*2-r.BACKOFF_JITTER;return Math.max(0,i+o)}get reconnectAttempt(){return this._reconnectAttempt}_scheduleReconnect(){let t=this._getReconnectDelay();this._reconnectAttempt++,this.emit("reconnect-attempt",this._reconnectAttempt),l.log(`Scheduling reconnect attempt ${this._reconnectAttempt} in ${Math.round(t)}ms`),this._reconnectTimer=setTimeout(()=>{if(this._reconnectTimer=void 0,!this._autoReconnect||!this._id||!this._token)return;let n=`${this._baseUrl}&id=${this._id}&token=${this._token}&version=${Tt}&last_seq=${this._lastSeq}`;this._jwt&&(n+=`&jwt=${encodeURIComponent(this._jwt)}`),this._disconnected=!1,this._socket=new WebSocket(n),this._socket.onmessage=i=>{let o;try{o=JSON.parse(i.data),l.log("Server message received:",o)}catch{l.log("Invalid server message",i.data);return}o!==null&&typeof o=="object"&&"seq"in o&&typeof o.seq=="number"&&(this._lastSeq=o.seq),this.emit("message",o)},this._socket.onclose=i=>{this._disconnected||(l.log("Socket closed during reconnect.",i),this._cleanup(),this._disconnected=!0,this._autoReconnect&&this._id&&this._token?this._scheduleReconnect():this.emit("disconnected"))},this._socket.onerror=i=>{l.error("Socket error during reconnect:",i)},this._socket.onopen=()=>{this._disconnected||(this._reconnectAttempt=0,this._sendQueuedMessages(),l.log("Socket reconnected"),this._createHeartbeatWorker(),this._startWorkerHeartbeat(),this.emit("reconnected"))}},t)}_createHeartbeatWorker(){if(!(typeof Worker>"u"||typeof Blob>"u"))try{let t=`
|
|
44
44
|
let interval = null;
|
|
45
45
|
self.onmessage = function(e) {
|
|
46
46
|
if (e.data.type === 'start') {
|
|
@@ -51,6 +51,6 @@ a=extmap-allow-mixed`)!==-1){let o=i.sdp.split(`
|
|
|
51
51
|
interval = null;
|
|
52
52
|
}
|
|
53
53
|
};
|
|
54
|
-
`,n=new Blob([t],{type:"application/javascript"}),i=URL.createObjectURL(n);this._heartbeatWorker=new Worker(i),this._heartbeatWorkerUrl=i,this._heartbeatWorker.onmessage=()=>{this._sendHeartbeat()}}catch{}}_startWorkerHeartbeat(){this._heartbeatWorker?this._heartbeatWorker.postMessage({type:"start",interval:this.pingInterval}):this._scheduleHeartbeat()}_stopWorkerHeartbeat(){this._heartbeatWorker&&this._heartbeatWorker.postMessage({type:"stop"})}_scheduleHeartbeat(){this._wsPingTimer=setTimeout(()=>{this._sendHeartbeat()},this.pingInterval)}_sendHeartbeat(){if(!this._wsOpen()){l.log("Cannot send heartbeat, because socket closed");return}let t=JSON.stringify({type:"HEARTBEAT"});this._socket?.send(t),this._heartbeatWorker||this._scheduleHeartbeat()}_wsOpen(){return!!this._socket&&this._socket.readyState===1}_sendQueuedMessages(){let t=[...this._messagesQueue];this._messagesQueue=[];for(let n of t)this.send(n)}send(t){if(this._disconnected)return;if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit("error","Invalid message");return}if(!this._wsOpen()){this._messagesQueue.push(t);return}let n=JSON.stringify(t);this._socket?.send(n)}close(){this._disconnected||(this._autoReconnect=!1,this._cleanup(),this._disconnected=!0)}_cleanup(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=this._socket.onerror=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer),this._stopWorkerHeartbeat(),this._heartbeatWorker&&(this._heartbeatWorker.terminate(),this._heartbeatWorker=null),this._heartbeatWorkerUrl&&(URL.revokeObjectURL(this._heartbeatWorkerUrl),this._heartbeatWorkerUrl=void 0),this._visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._visibilityHandler),this._visibilityHandler=void 0),this._reconnectTimer!==void 0&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0)}};var _e=class r extends T{_connected=!1;_disconnected=!0;_id;_token;_messagesQueue=[];_abortController;_autoReconnect=!0;_reconnectAttempt=0;_reconnectTimer;_heartbeatTimer;_lastSeq=0;_baseUrl;_jwt;_pingInterval;static BACKOFF_SCHEDULE=[0,1e3,2e3,4e3,8e3,16e3,3e4];static BACKOFF_JITTER=500;constructor(e,t,n,i,o,s=5e3,a){super();let
|
|
55
|
-
`);a=d.pop()||"";for(let h of d)if(h.startsWith("data: ")){let u=h.slice(6);try{let m=JSON.parse(u);typeof m.seq=="number"&&(this._lastSeq=m.seq),l.log("SSE message received:",m),this.emit("message",m)}catch{l.log("Invalid SSE message",u)}}}this._handleDisconnect()}catch(n){if(n?.name==="AbortError")return;l.error("SSE error:",n),this._handleDisconnect()}}send(e){if(!this._disconnected){if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit("error","Invalid message");return}if(!this._connected){this._messagesQueue.push(e);return}this._postMessage(e)}}async _postMessage(e){let t=new URLSearchParams({id:this._id,token:this._token});try{await fetch(`${this._baseUrl}http/send?${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){l.error("POST send failed:",n),this._messagesQueue.push(e)}}close(){this._disconnected||(this._autoReconnect=!1,this._cleanup(),this._disconnected=!0)}_handleDisconnect(){this._connected=!1,this._autoReconnect&&!this._disconnected?this._scheduleReconnect():(this._cleanup(),this._disconnected=!0,this.emit("disconnected"))}_getReconnectDelay(){let e=r.BACKOFF_SCHEDULE,t=Math.min(this._reconnectAttempt,e.length-1),n=e[t],i=Math.random()*r.BACKOFF_JITTER*2-r.BACKOFF_JITTER;return Math.max(0,n+i)}_scheduleReconnect(){this._reconnectAttempt++,this.emit("reconnect-attempt",this._reconnectAttempt);let e=this._getReconnectDelay();this._reconnectTimer=setTimeout(()=>{this._connectSSE().catch(t=>{l.error("SSE reconnect failed:",t),this._handleDisconnect()})},e)}_startHeartbeat(){this._heartbeatTimer=setInterval(()=>{this._connected&&this._postMessage({type:"HEARTBEAT"})},this._pingInterval)}_sendQueuedMessages(){let e=[...this._messagesQueue];this._messagesQueue=[];for(let t of e)this.send(t)}_cleanup(){this._abortController?.abort(),this._abortController=void 0,clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0,clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0,this._connected=!1}};var W=class r extends M{static DEFAULT_KEY="dendri";_serializers={raw:pe,json:ce,binary:O,"binary-utf8":O,default:O};_options;_api;_socket;_id=null;_lastServerId=null;_connectionState="initialized";static SUSPEND_THRESHOLD=5;_connections=new Map;_lostMessages=new Map;_lostMessageGeneration=new Map;_hybridConnections=new Map;get id(){return this._id}get options(){return this._options}get connectionState(){return this._connectionState}get open(){return this._connectionState==="connected"}get socket(){return this._socket}get connections(){let e=Object.create(null);for(let[t,n]of this._connections)e[t]=[...n];return e}get destroyed(){return this._connectionState==="closed"||this._connectionState==="failed"}get disconnected(){let e=this._connectionState;return e==="disconnected"||e==="suspended"||e==="closed"||e==="failed"}constructor(e,t){super();let n,i=t;e&&typeof e=="object"&&e.constructor===Object?i=e:e&&(n=e.toString());let o={debug:0,port:_.CLOUD_PORT,path:"/",key:r.DEFAULT_KEY,token:_.randomToken(),config:_.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin",serializers:{},...i};if(this._options=o,typeof this._options.host!="string"||this._options.host.trim()==="")throw new Error('Dendri requires a signaling server host. Pass your self-hosted server domain, for example { host: "signal.example.com", secure: true }.');if(this._options.host=this._options.host.trim(),this._serializers={...this._serializers,...this.options.serializers},this._options.host==="/"&&(this._options.host=typeof window<"u"?window.location.hostname:"localhost"),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!==_.CLOUD_HOST?this._options.secure=_.isSecure():this._options.host===_.CLOUD_HOST&&(this._options.secure=!0),this._options.logFunction&&l.setLogFunction(this._options.logFunction),l.logLevel=this._options.debug||0,this._api=new oe(this._options),this._socket=this._createServerConnection(),!_.supports.audioVideo&&!_.supports.data)if(this._options.enableRelay)l.warn("WebRTC not supported \u2014 operating in relay-only mode");else{this._delayedAbort("browser-incompatible","The current browser does not support WebRTC");return}if(n&&!_.validateId(n)){this._delayedAbort("invalid-id",`ID "${n}" is invalid`);return}n?this._initialize(n):this._api.retrieveId().then(s=>this._initialize(s)).catch(s=>this._abort("server-error",s,!0))}_setState(e){let t=this._connectionState;if(t!==e){if(!r._isValidTransition(t,e)){l.warn(`Invalid state transition: ${t} \u2192 ${e}`);return}this._connectionState=e,this.emit("connectionStateChanged",e,t)}}static _isValidTransition(e,t){return{initialized:["connecting","disconnected","closed","failed"],connecting:["connected","disconnected","failed","closed"],connected:["disconnected","closed"],disconnected:["connecting","suspended","closed","failed"],suspended:["connecting","closed","failed"],closed:[],failed:["closed"]}[e]?.includes(t)??!1}_createServerConnection(){let e=this._options.signalingTransport||"websocket",t=e==="sse"?new _e(this._options.secure??!1,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval,this._options.jwt):e==="polling"?new ue(this._options.secure??!1,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval,this._options.jwt):new me(this._options.secure??!1,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval,this._options.jwt);return t.on("message",n=>{this._handleMessage(n)}),t.on("error",n=>{this._abort("socket-error",n,!0)}),t.on("disconnected",()=>{this.disconnected||(this.emitError("network","Lost connection to server.",!0),this.disconnect())}),t.on("reconnect-attempt",n=>{n>=r.SUSPEND_THRESHOLD&&this._connectionState==="disconnected"&&this._setState("suspended")}),t.on("reconnected",()=>{this.emit("reconnected")}),t}_initialize(e){this._id=e,this._setState("connecting"),this.socket.start(e,this._options.token),(_.isSafari||_.isIOS)&&l.log("Safari/iOS detected \u2014 H.264 codec preference will be applied for video calls")}_handleMessage(e){let t=e.type,n=e.payload,i=e.src;switch(t){case"OPEN":this._lastServerId=this.id,this._setState("connected"),this._fetchTurnIfEnabled().then(()=>{this.emit("open",this.id)});break;case"ERROR":this._abort("server-error",n.msg,!0);break;case"ID-TAKEN":this._abort("unavailable-id",`ID "${this.id}" is taken`);break;case"INVALID-KEY":this._abort("invalid-key",`API KEY "${this._options.key}" is invalid`);break;case"LEAVE":l.log(`Received leave message from ${i}`),this._cleanupPeer(i),this._connections.delete(i);break;case"EXPIRE":this.emitError("peer-unavailable",`Could not connect to peer ${i}`,!0);break;case"OFFER":{let o=n.connectionId,s=this.getConnection(i,o);if(s&&(s.close(),l.warn(`Offer received for existing Connection ID:${o}`)),this._options.validateMetadata&&!this._options.validateMetadata(n.metadata)){l.warn(`Rejected connection from ${i} - metadata validation failed`);return}if(n.type==="media"){let c=new K(i,this,{connectionId:o,_payload:n,metadata:n.metadata});s=c,this._addConnection(i,s),this.emit("call",c)}else if(n.type==="data"){let c=this._serializers[n.serialization];if(!c){l.warn(`Received offer with unknown serialization type: ${n.serialization}`);return}let p=new c(i,this,{connectionId:o,_payload:n,metadata:n.metadata,label:n.label,serialization:n.serialization,reliable:n.reliable});s=p,this._addConnection(i,s),this.emit("connection",p)}else{l.warn(`Received malformed connection type:${n.type}`);return}let a=this._getMessages(o);for(let c of a)s.handleMessage(c);break}case"KEY-EXCHANGE":{let o=this._hybridConnections.get(i);o?o.handleKeyExchange(n):l.warn(`Received KEY-EXCHANGE from ${i} but no HybridConnection exists`);break}case"DATA":{let o=this._hybridConnections.get(i);if(o){let s=e.seq;n!==null&&typeof n=="object"&&"__ackId"in n&&typeof n.__ackId=="string"?(this._socket.send({type:"ACK",dst:i,payload:{ackId:n.__ackId}}),o.handleRelayData(n.data,s)):o.handleRelayData(n,s)}else this.emit("relayData",i,n,e.room);break}case"ACK":{if(n?.ackId){let o=this._hybridConnections.get(i);o&&o.ackManager.handleAck(n.ackId)}break}case"ROOM-PEERS":{let o=e.room??"",s=Array.isArray(n)?n:[];this.emit("roomPeers",o,s);break}case"PRESENCE-UPDATE":{this.emit("presenceUpdate",e.src,e.room??"",n);break}case"HEARTBEAT":break;default:{if(!n){l.warn(`You received a malformed message from ${i} of type ${t}`);return}let o=n.connectionId,s=this.getConnection(i,o);s?.peerConnection?s.handleMessage(e):o?this._storeMessage(o,e):l.warn("You received an unrecognized message:",e);break}}}static MAX_LOST_MESSAGES=1e3;static LOST_MESSAGE_TTL=300*1e3;_storeMessage(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e)?.push(t);let n=0;for(let o of this._lostMessages.values())n+=o.length;if(n>r.MAX_LOST_MESSAGES){let o=this._lostMessages.keys().next().value;o!==void 0&&(this._lostMessages.delete(o),this._lostMessageGeneration.delete(o))}let i=(this._lostMessageGeneration.get(e)??0)+1;this._lostMessageGeneration.set(e,i),setTimeout(()=>{this._lostMessageGeneration.get(e)===i&&(this._lostMessages.delete(e),this._lostMessageGeneration.delete(e))},r.LOST_MESSAGE_TTL)}_getMessages(e){let t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),this._lostMessageGeneration.delete(e),t):[]}connect(e,t={}){if(!e||typeof e!="string"){this.emitError("invalid-id","A non-empty peer ID is required to connect.");return}if(t={serialization:"default",...t},this.disconnected){l.warn("You cannot connect to a new Dendri instance because you called .disconnect() on this Dendri instance and ended your connection with the server. You can create a new Dendri instance to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError("disconnected","Cannot connect to new Dendri instance after disconnecting from server.");return}let n=this._serializers[t.serialization];if(!n){this.emitError("invalid-id",`Unknown serialization type: ${t.serialization}`);return}let i=new n(e,this,t);return this._addConnection(e,i),i}call(e,t,n={}){if(!e||typeof e!="string"){this.emitError("invalid-id","A non-empty peer ID is required to call.");return}if(this.disconnected){l.warn("You cannot connect to a new Dendri instance because you called .disconnect() on this Dendri instance and ended your connection with the server. You can create a new Dendri instance to reconnect."),this.emitError("disconnected","Cannot connect to new Dendri instance after disconnecting from server.");return}if(!t){l.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}let i=new K(e,this,{...n,_stream:t});return this._addConnection(e,i),i}connectHybrid(e,t){if(!e||typeof e!="string"){this.emitError("invalid-id","A non-empty peer ID is required to connect.");return}if(this.disconnected){l.warn("You cannot connect to a new Dendri instance because you called .disconnect() on this Dendri instance and ended your connection with the server. You can create a new Dendri instance to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError("disconnected","Cannot connect to new Dendri instance after disconnecting from server.");return}let n=new fe(e,this,t);return this._hybridConnections.set(e,n),n.on("close",()=>{this._hybridConnections.delete(e)}),n.start(),n}joinRoom(e){this.socket.send({type:"ROOM-JOIN",room:e})}leaveRoom(e){this.socket.send({type:"ROOM-LEAVE",room:e})}async _fetchTurnIfEnabled(){if(this._options.fetchTurnCredentials)try{let e=await this._api.getTurnCredentials();if(e.length>0){let t=this._options.config?.iceServers??[];this._options.config={...this._options.config,iceServers:[...t,...e]}}}catch(e){l.error("Failed to fetch TURN credentials",e)}}_addConnection(e,t){l.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){let t=this._connections.get(e.peer);if(t){let n=t.indexOf(e);n!==-1&&t.splice(n,1),t.length===0&&this._connections.delete(e.peer)}this._lostMessages.delete(e.connectionId),this._lostMessageGeneration.delete(e.connectionId)}getConnection(e,t){let n=this._connections.get(e);if(!n)return null;for(let i of n)if(i.connectionId===t)return i;return null}static FATAL_ERROR_TYPES=new Set(["browser-incompatible","invalid-id","invalid-key"]);_delayedAbort(e,t,n=!1){setTimeout(()=>{this._abort(e,t,n)},0)}_abort(e,t,n=!1){if(l.error("Aborting!"),this._lastServerId)this.emitError(e,t,n),this.disconnect();else{let o=r.FATAL_ERROR_TYPES.has(e)?"failed":"closed";this.disconnect(),this._cleanup(),this._setState(o),this.emitError(e,t,n),this.emit("close")}}destroy(){this._destroyWithState("closed")}_destroyWithState(e){this.destroyed||(l.log(`Destroy peer with ID:${this.id}`),this.disconnect(),this._cleanup(),this._setState(e),this.emit("close"))}_cleanup(){let e=[...this._connections.keys()];for(let t of e)this._cleanupPeer(t);this._connections.clear();for(let t of this._hybridConnections.values())t.close();this._hybridConnections.clear(),this.socket.removeAllListeners()}_cleanupPeer(e){let t=this._connections.get(e);if(!t)return;let n=[...t];for(let i of n)i.close()}disconnect(){let e=this._connectionState;if(e==="disconnected"||e==="suspended"||e==="closed"||e==="failed")return;let t=this.id;l.log(`Disconnect peer with ID:${t}`),this._setState("disconnected"),this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}reconnect(){if(this.disconnected&&!this.destroyed)l.log(`Attempting reconnection to server with ID ${this._lastServerId}`),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)l.error("In a hurry? We're still trying to make the initial connection!");else throw new Error(`Dendri ${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.emitError("server-error",t,!0))}diagnostics(){let e=[];for(let[n,i]of this._connections)for(let o of i)e.push({peerId:n,type:o.type,open:o.open});let t=[];for(let[n,i]of this._hybridConnections)t.push({peerId:n,mode:i.mode,open:i.open});return{peerId:this.id??null,connectionState:this.connectionState,serverConnected:!this.disconnected,connections:e,hybridConnections:t,socket:{connected:!!this.socket?._socket,autoReconnect:this.socket?._autoReconnect??!1,reconnectAttempt:this.socket?._reconnectAttempt??0,lastSeq:this.socket?._lastSeq??0},pendingMessages:this._lostMessages.size}}};window.dendri={Dendri:W,util:_};window.Dendri=W;})();
|
|
54
|
+
`,n=new Blob([t],{type:"application/javascript"}),i=URL.createObjectURL(n);this._heartbeatWorker=new Worker(i),this._heartbeatWorkerUrl=i,this._heartbeatWorker.onmessage=()=>{this._sendHeartbeat()}}catch{}}_startWorkerHeartbeat(){this._heartbeatWorker?this._heartbeatWorker.postMessage({type:"start",interval:this.pingInterval}):this._scheduleHeartbeat()}_stopWorkerHeartbeat(){this._heartbeatWorker&&this._heartbeatWorker.postMessage({type:"stop"})}_scheduleHeartbeat(){this._wsPingTimer=setTimeout(()=>{this._sendHeartbeat()},this.pingInterval)}_sendHeartbeat(){if(!this._wsOpen()){l.log("Cannot send heartbeat, because socket closed");return}let t=JSON.stringify({type:"HEARTBEAT"});this._socket?.send(t),this._heartbeatWorker||this._scheduleHeartbeat()}_wsOpen(){return!!this._socket&&this._socket.readyState===1}_sendQueuedMessages(){let t=[...this._messagesQueue];this._messagesQueue=[];for(let n of t)this.send(n)}send(t){if(this._disconnected)return;if(!this._id){this._messagesQueue.push(t);return}if(!t.type){this.emit("error","Invalid message");return}if(!this._wsOpen()){this._messagesQueue.push(t);return}let n=JSON.stringify(t);this._socket?.send(n)}close(){this._disconnected||(this._autoReconnect=!1,this._cleanup(),this._disconnected=!0)}_cleanup(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=this._socket.onerror=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer),this._stopWorkerHeartbeat(),this._heartbeatWorker&&(this._heartbeatWorker.terminate(),this._heartbeatWorker=null),this._heartbeatWorkerUrl&&(URL.revokeObjectURL(this._heartbeatWorkerUrl),this._heartbeatWorkerUrl=void 0),this._visibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._visibilityHandler),this._visibilityHandler=void 0),this._reconnectTimer!==void 0&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0)}};var _e=class r extends T{_connected=!1;_disconnected=!0;_id;_token;_messagesQueue=[];_abortController;_autoReconnect=!0;_reconnectAttempt=0;_reconnectTimer;_heartbeatTimer;_lastSeq=0;_baseUrl;_key;_jwt;_apiKey;_pingInterval;static BACKOFF_SCHEDULE=[0,1e3,2e3,4e3,8e3,16e3,3e4];static BACKOFF_JITTER=500;constructor(e,t,n,i,o,s=5e3,a,c){super();let p=e?"https://":"http://";this._baseUrl=`${p+t}:${n}${i}`,this._pingInterval=s,this._key=o,this._jwt=a,this._apiKey=c}_applyAuthParams(e){e.set("key",this._key),this._jwt&&e.set("jwt",this._jwt),this._apiKey&&e.set("api_key",this._apiKey)}get reconnectAttempt(){return this._reconnectAttempt}start(e,t){this._id=e,this._token=t,this._disconnected=!1,this._connectSSE().catch(n=>{l.error("SSE start failed:",n),this._handleDisconnect()})}async _connectSSE(){if(this._disconnected)return;let e=new URLSearchParams({id:this._id,token:this._token});this._applyAuthParams(e),this._lastSeq>0&&e.set("last_seq",String(this._lastSeq));let t=`${this._baseUrl}http/sse?${e}`;try{this._abortController=new AbortController;let n=await fetch(t,{headers:{Accept:"text/event-stream","Cache-Control":"no-cache"},signal:this._abortController.signal});if(!n.ok||!n.body)throw new Error(`SSE connection failed: ${n.status}`);let i=this._reconnectAttempt>0;this._connected=!0,this._reconnectAttempt=0,i&&this.emit("reconnected"),this._startHeartbeat(),this._sendQueuedMessages();let o=n.body.getReader(),s=new TextDecoder,a="";for(;;){let{done:c,value:p}=await o.read();if(c)break;a+=s.decode(p,{stream:!0});let d=a.split(`
|
|
55
|
+
`);a=d.pop()||"";for(let h of d)if(h.startsWith("data: ")){let u=h.slice(6);try{let m=JSON.parse(u);typeof m.seq=="number"&&(this._lastSeq=m.seq),l.log("SSE message received:",m),this.emit("message",m)}catch{l.log("Invalid SSE message",u)}}}this._handleDisconnect()}catch(n){if(n?.name==="AbortError")return;l.error("SSE error:",n),this._handleDisconnect()}}send(e){if(!this._disconnected){if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit("error","Invalid message");return}if(!this._connected){this._messagesQueue.push(e);return}this._postMessage(e)}}async _postMessage(e){let t=new URLSearchParams({id:this._id,token:this._token});this._applyAuthParams(t);try{await fetch(`${this._baseUrl}http/send?${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){l.error("POST send failed:",n),this._messagesQueue.push(e)}}close(){this._disconnected||(this._autoReconnect=!1,this._cleanup(),this._disconnected=!0)}_handleDisconnect(){this._connected=!1,this._autoReconnect&&!this._disconnected?this._scheduleReconnect():(this._cleanup(),this._disconnected=!0,this.emit("disconnected"))}_getReconnectDelay(){let e=r.BACKOFF_SCHEDULE,t=Math.min(this._reconnectAttempt,e.length-1),n=e[t],i=Math.random()*r.BACKOFF_JITTER*2-r.BACKOFF_JITTER;return Math.max(0,n+i)}_scheduleReconnect(){this._reconnectAttempt++,this.emit("reconnect-attempt",this._reconnectAttempt);let e=this._getReconnectDelay();this._reconnectTimer=setTimeout(()=>{this._connectSSE().catch(t=>{l.error("SSE reconnect failed:",t),this._handleDisconnect()})},e)}_startHeartbeat(){this._heartbeatTimer=setInterval(()=>{this._connected&&this._postMessage({type:"HEARTBEAT"})},this._pingInterval)}_sendQueuedMessages(){let e=[...this._messagesQueue];this._messagesQueue=[];for(let t of e)this.send(t)}_cleanup(){this._abortController?.abort(),this._abortController=void 0,clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0,clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0,this._connected=!1}};function $t(r){let e;try{e=new URL(r)}catch{throw new Error(`Invalid Dendri "url" option: "${r}". Expected a full URL like "wss://signal.example.com".`)}let t=e.protocol==="wss:"||e.protocol==="https:";if(!t&&e.protocol!=="ws:"&&e.protocol!=="http:")throw new Error(`Invalid Dendri "url" protocol: "${e.protocol}". Use wss://, ws://, https://, or http://.`);return{host:e.hostname,port:e.port?Number(e.port):t?443:80,secure:t,path:e.pathname||"/"}}var w=class r extends M{static DEFAULT_KEY="dendri";_serializers={raw:pe,json:ce,binary:O,"binary-utf8":O,default:O};_options;_api;_socket;_id=null;_lastServerId=null;_connectionState="initialized";static SUSPEND_THRESHOLD=5;_connections=new Map;_lostMessages=new Map;_lostMessageGeneration=new Map;_hybridConnections=new Map;get id(){return this._id}get options(){return this._options}get connectionState(){return this._connectionState}get open(){return this._connectionState==="connected"}get socket(){return this._socket}get connections(){let e=Object.create(null);for(let[t,n]of this._connections)e[t]=[...n];return e}get destroyed(){return this._connectionState==="closed"||this._connectionState==="failed"}get disconnected(){let e=this._connectionState;return e==="disconnected"||e==="suspended"||e==="closed"||e==="failed"}constructor(e,t){super();let n,i=t;e&&typeof e=="object"&&e.constructor===Object?i=e:e&&(n=e.toString()),i?.url&&(i={...$t(i.url),...i});let o={debug:0,port:_.CLOUD_PORT,path:"/",key:r.DEFAULT_KEY,token:_.randomToken(),config:_.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin",serializers:{},...i};if(this._options=o,typeof this._options.host!="string"||this._options.host.trim()==="")throw new Error('Dendri requires a signaling server host. Pass your self-hosted server domain, for example { host: "signal.example.com", secure: true }.');if(this._options.host=this._options.host.trim(),this._serializers={...this._serializers,...this.options.serializers},this._options.host==="/"&&(this._options.host=typeof window<"u"?window.location.hostname:"localhost"),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!==_.CLOUD_HOST?this._options.secure=_.isSecure():this._options.host===_.CLOUD_HOST&&(this._options.secure=!0),this._options.logFunction&&l.setLogFunction(this._options.logFunction),l.logLevel=this._options.debug||0,this._api=new oe(this._options),this._socket=this._createServerConnection(),!_.supports.audioVideo&&!_.supports.data)if(this._options.enableRelay)l.warn("WebRTC not supported \u2014 operating in relay-only mode");else{this._delayedAbort("browser-incompatible","The current browser does not support WebRTC");return}if(n&&!_.validateId(n)){this._delayedAbort("invalid-id",`ID "${n}" is invalid`);return}n?this._initialize(n):this._api.retrieveId().then(s=>this._initialize(s)).catch(s=>this._abort("server-error",s,!0))}_setState(e){let t=this._connectionState;if(t!==e){if(!r._isValidTransition(t,e)){l.warn(`Invalid state transition: ${t} \u2192 ${e}`);return}this._connectionState=e,this.emit("connectionStateChanged",e,t)}}static _isValidTransition(e,t){return{initialized:["connecting","disconnected","closed","failed"],connecting:["connected","disconnected","failed","closed"],connected:["disconnected","closed"],disconnected:["connecting","suspended","closed","failed"],suspended:["connecting","closed","failed"],closed:[],failed:["closed"]}[e]?.includes(t)??!1}_createServerConnection(){let e=this._options.signalingTransport||"websocket",t=e==="sse"?new _e(this._options.secure??!1,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval,this._options.jwt,this._options.apiKey):e==="polling"?new ue(this._options.secure??!1,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval,this._options.jwt,this._options.apiKey):new me(this._options.secure??!1,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval,this._options.jwt,this._options.apiKey);return t.on("message",n=>{this._handleMessage(n)}),t.on("error",n=>{this._abort("socket-error",n,!0)}),t.on("disconnected",()=>{this.disconnected||(this.emitError("network","Lost connection to server.",!0),this.disconnect())}),t.on("reconnect-attempt",n=>{n>=r.SUSPEND_THRESHOLD&&this._connectionState==="disconnected"&&this._setState("suspended")}),t.on("reconnected",()=>{this.emit("reconnected")}),t}_initialize(e){this._id=e,this._setState("connecting"),this.socket.start(e,this._options.token),(_.isSafari||_.isIOS)&&l.log("Safari/iOS detected \u2014 H.264 codec preference will be applied for video calls")}_handleMessage(e){let t=e.type,n=e.payload,i=e.src;switch(t){case"OPEN":this._lastServerId=this.id,this._setState("connected"),this._fetchTurnIfEnabled().then(()=>{this.emit("open",this.id)});break;case"ERROR":this._abort("server-error",n.msg,!0);break;case"ID-TAKEN":this._abort("unavailable-id",`ID "${this.id}" is taken`);break;case"INVALID-KEY":this._abort("invalid-key",`API KEY "${this._options.key}" is invalid`);break;case"LEAVE":l.log(`Received leave message from ${i}`),this._cleanupPeer(i),this._connections.delete(i);break;case"EXPIRE":this.emitError("peer-unavailable",`Could not connect to peer ${i}`,!0);break;case"OFFER":{let o=n.connectionId,s=this.getConnection(i,o);if(s&&(s.close(),l.warn(`Offer received for existing Connection ID:${o}`)),this._options.validateMetadata&&!this._options.validateMetadata(n.metadata)){l.warn(`Rejected connection from ${i} - metadata validation failed`);return}if(n.type==="media"){let c=new K(i,this,{connectionId:o,_payload:n,metadata:n.metadata});s=c,this._addConnection(i,s),this.emit("call",c)}else if(n.type==="data"){let c=this._serializers[n.serialization];if(!c){l.warn(`Received offer with unknown serialization type: ${n.serialization}`);return}let p=new c(i,this,{connectionId:o,_payload:n,metadata:n.metadata,label:n.label,serialization:n.serialization,reliable:n.reliable});s=p,this._addConnection(i,s),this.emit("connection",p)}else{l.warn(`Received malformed connection type:${n.type}`);return}let a=this._getMessages(o);for(let c of a)s.handleMessage(c);break}case"KEY-EXCHANGE":{let o=this._hybridConnections.get(i);o?o.handleKeyExchange(n):l.warn(`Received KEY-EXCHANGE from ${i} but no HybridConnection exists`);break}case"DATA":{let o=this._hybridConnections.get(i);if(o){let s=e.seq;n!==null&&typeof n=="object"&&"__ackId"in n&&typeof n.__ackId=="string"?(this._socket.send({type:"ACK",dst:i,payload:{ackId:n.__ackId}}),o.handleRelayData(n.data,s)):o.handleRelayData(n,s)}else this.emit("relayData",i,n,e.room);break}case"ACK":{if(n?.ackId){let o=this._hybridConnections.get(i);o&&o.ackManager.handleAck(n.ackId)}break}case"ROOM-PEERS":{let o=e.room??"",s=Array.isArray(n)?n:[];this.emit("roomPeers",o,s);break}case"PRESENCE-UPDATE":{this.emit("presenceUpdate",e.src,e.room??"",n);break}case"HEARTBEAT":break;default:{if(!n){l.warn(`You received a malformed message from ${i} of type ${t}`);return}let o=n.connectionId,s=this.getConnection(i,o);s?.peerConnection?s.handleMessage(e):o?this._storeMessage(o,e):l.warn("You received an unrecognized message:",e);break}}}static MAX_LOST_MESSAGES=1e3;static LOST_MESSAGE_TTL=300*1e3;_storeMessage(e,t){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e)?.push(t);let n=0;for(let o of this._lostMessages.values())n+=o.length;if(n>r.MAX_LOST_MESSAGES){let o=this._lostMessages.keys().next().value;o!==void 0&&(this._lostMessages.delete(o),this._lostMessageGeneration.delete(o))}let i=(this._lostMessageGeneration.get(e)??0)+1;this._lostMessageGeneration.set(e,i),setTimeout(()=>{this._lostMessageGeneration.get(e)===i&&(this._lostMessages.delete(e),this._lostMessageGeneration.delete(e))},r.LOST_MESSAGE_TTL)}_getMessages(e){let t=this._lostMessages.get(e);return t?(this._lostMessages.delete(e),this._lostMessageGeneration.delete(e),t):[]}connect(e,t={}){if(!e||typeof e!="string"){this.emitError("invalid-id","A non-empty peer ID is required to connect.");return}if(t={serialization:"default",...t},this.disconnected){l.warn("You cannot connect to a new Dendri instance because you called .disconnect() on this Dendri instance and ended your connection with the server. You can create a new Dendri instance to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError("disconnected","Cannot connect to new Dendri instance after disconnecting from server.");return}let n=this._serializers[t.serialization];if(!n){this.emitError("invalid-id",`Unknown serialization type: ${t.serialization}`);return}let i=new n(e,this,t);return this._addConnection(e,i),i}call(e,t,n={}){if(!e||typeof e!="string"){this.emitError("invalid-id","A non-empty peer ID is required to call.");return}if(this.disconnected){l.warn("You cannot connect to a new Dendri instance because you called .disconnect() on this Dendri instance and ended your connection with the server. You can create a new Dendri instance to reconnect."),this.emitError("disconnected","Cannot connect to new Dendri instance after disconnecting from server.");return}if(!t){l.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}let i=new K(e,this,{...n,_stream:t});return this._addConnection(e,i),i}connectHybrid(e,t){if(!e||typeof e!="string"){this.emitError("invalid-id","A non-empty peer ID is required to connect.");return}if(this.disconnected){l.warn("You cannot connect to a new Dendri instance because you called .disconnect() on this Dendri instance and ended your connection with the server. You can create a new Dendri instance to reconnect, or call reconnect on this peer if you believe its ID to still be available."),this.emitError("disconnected","Cannot connect to new Dendri instance after disconnecting from server.");return}let n=new fe(e,this,t);return this._hybridConnections.set(e,n),n.on("close",()=>{this._hybridConnections.delete(e)}),n.start(),n}joinRoom(e){this.socket.send({type:"ROOM-JOIN",room:e})}leaveRoom(e){this.socket.send({type:"ROOM-LEAVE",room:e})}async _fetchTurnIfEnabled(){if(this._options.fetchTurnCredentials)try{let e=await this._api.getTurnCredentials();if(e.length>0){let t=this._options.config?.iceServers??[];this._options.config={...this._options.config,iceServers:[...t,...e]}}}catch(e){l.error("Failed to fetch TURN credentials",e)}}_addConnection(e,t){l.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){let t=this._connections.get(e.peer);if(t){let n=t.indexOf(e);n!==-1&&t.splice(n,1),t.length===0&&this._connections.delete(e.peer)}this._lostMessages.delete(e.connectionId),this._lostMessageGeneration.delete(e.connectionId)}getConnection(e,t){let n=this._connections.get(e);if(!n)return null;for(let i of n)if(i.connectionId===t)return i;return null}static FATAL_ERROR_TYPES=new Set(["browser-incompatible","invalid-id","invalid-key"]);_delayedAbort(e,t,n=!1){setTimeout(()=>{this._abort(e,t,n)},0)}_abort(e,t,n=!1){if(l.error("Aborting!"),this._lastServerId)this.emitError(e,t,n),this.disconnect();else{let o=r.FATAL_ERROR_TYPES.has(e)?"failed":"closed";this.disconnect(),this._cleanup(),this._setState(o),this.emitError(e,t,n),this.emit("close")}}destroy(){this._destroyWithState("closed")}_destroyWithState(e){this.destroyed||(l.log(`Destroy peer with ID:${this.id}`),this.disconnect(),this._cleanup(),this._setState(e),this.emit("close"))}_cleanup(){let e=[...this._connections.keys()];for(let t of e)this._cleanupPeer(t);this._connections.clear();for(let t of this._hybridConnections.values())t.close();this._hybridConnections.clear(),this.socket.removeAllListeners()}_cleanupPeer(e){let t=this._connections.get(e);if(!t)return;let n=[...t];for(let i of n)i.close()}disconnect(){let e=this._connectionState;if(e==="disconnected"||e==="suspended"||e==="closed"||e==="failed")return;let t=this.id;l.log(`Disconnect peer with ID:${t}`),this._setState("disconnected"),this.socket.close(),this._lastServerId=t,this._id=null,this.emit("disconnected",t)}reconnect(){if(this.disconnected&&!this.destroyed)l.log(`Attempting reconnection to server with ID ${this._lastServerId}`),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)l.error("In a hurry? We're still trying to make the initial connection!");else throw new Error(`Dendri ${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.emitError("server-error",t,!0))}diagnostics(){let e=[];for(let[n,i]of this._connections)for(let o of i)e.push({peerId:n,type:o.type,open:o.open});let t=[];for(let[n,i]of this._hybridConnections)t.push({peerId:n,mode:i.mode,open:i.open});return{peerId:this.id??null,connectionState:this.connectionState,serverConnected:!this.disconnected,connections:e,hybridConnections:t,socket:{connected:!!this.socket?._socket,autoReconnect:this.socket?._autoReconnect??!1,reconnectAttempt:this.socket?._reconnectAttempt??0,lastSeq:this.socket?._lastSeq??0},pendingMessages:this._lostMessages.size}}};window.dendri={Dendri:w,util:_};window.Dendri=w;})();
|
|
56
56
|
//# sourceMappingURL=dendri.min.global.js.map
|