UNPKG

@liascript/exporter

Version:
1 lines 56.5 kB
var e=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}).parcelRequire55a5;e.register("hsMrW",(function(t,i){var n,s;n=t.exports,s=function(){return Qt},Object.defineProperty(n,"joinRoom",{get:s,set:undefined,enumerable:!0,configurable:!0});var r,a,o,d,h,l,c,u,p,f,_,m,g,y,b,v,w=e("2Xs1f"),C=e("dM3DM"),S=e("aQXMn"),E=e("jhEmn");const x="Trystero",T=(e,t)=>Array(e).fill().map(t),k=e=>T(e,(()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[Math.floor(62*Math.random())])).join(""),R=k(20),A=Promise.all.bind(Promise),{entries:N,fromEntries:L,keys:F}=Object,P=()=>{},O=e=>Error(`${x}: ${e}`),I=new TextEncoder,D=new TextDecoder,M=e=>I.encode(e),j=e=>D.decode(e),U=(...e)=>e.join("@"),q=JSON.stringify,W=JSON.parse,$={},H="AES-GCM",B={},Y=async e=>{if(B[e])return B[e];const t=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-1",M(e)))).map((e=>e.toString(36))).join("");return B[e]=t,t},z=async(e,t)=>{const i=crypto.getRandomValues(new Uint8Array(16));var n;return i.join(",")+"$"+(n=await crypto.subtle.encrypt({name:H,iv:i},await e,M(t)),btoa(String.fromCharCode.apply(null,new Uint8Array(n))))},J=async(e,t)=>{const[i,n]=t.split("$");return j(await crypto.subtle.decrypt({name:H,iv:new Uint8Array(i.split(","))},await e,(e=>{const t=atob(e);return new Uint8Array(t.length).map(((e,i)=>t.charCodeAt(i))).buffer})(n)))};function K(e){return e&&e.__esModule&&{}.hasOwnProperty.call(e,"default")?e.default:e}var V,G,X={exports:{}};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const i="color: "+this.color;t.splice(1,0,i,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,i)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&void 0!==E&&"env"in E&&(e=void 0),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=function(e){function t(e){let n,s,r,a=null;function o(...e){if(!o.enabled)return;const i=o,s=Number(new Date),r=s-(n||s);i.diff=r,i.prev=n,i.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";a++;const r=t.formatters[s];if("function"==typeof r){const t=e[a];n=r.call(i,t),e.splice(a,1),a--}return n})),t.formatArgs.call(i,e),(i.log||t.log).apply(i,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=i,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(s!==t.namespaces&&(s=t.namespaces,r=t.enabled(e)),r),set(e){a=e}}),"function"==typeof t.init&&t.init(o),o}function i(e,i){const n=t(this.namespace+(void 0===i?":":i)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let i;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(i=0;i<s;i++)n[i]&&("-"===(e=n[i].replace(/\*/g,".*?"))[0]?t.skips.push(RegExp("^"+e.slice(1)+"$")):t.names.push(RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let i,n;for(i=0,n=t.skips.length;i<n;i++)if(t.skips[i].test(e))return!1;for(i=0,n=t.names.length;i<n;i++)if(t.names[i].test(e))return!0;return!1},t.humanize=function(){if(G)return V;G=1;var e=1e3,t=60*e,i=60*t,n=24*i;function s(e,t,i,n){var s=t>=1.5*i;return Math.round(e/i)+" "+n+(s?"s":"")}return V=(r,a)=>{a=a||{};var o=typeof r;if("string"===o&&r.length>0)return function(s){if(!((s+="").length>100)){var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(r){var a=parseFloat(r[1]);switch((r[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return 6048e5*a;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*i;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(r);if("number"===o&&isFinite(r))return a.long?function(r){var a=Math.abs(r);return a>=n?s(r,a,n,"day"):a>=i?s(r,a,i,"hour"):a>=t?s(r,a,t,"minute"):a>=e?s(r,a,e,"second"):r+" ms"}(r):function(s){var r=Math.abs(s);return r>=n?Math.round(s/n)+"d":r>=i?Math.round(s/i)+"h":r>=t?Math.round(s/t)+"m":r>=e?Math.round(s/e)+"s":s+"ms"}(r);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))}}(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((i=>{t[i]=e[i]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let i=0;for(let t=0;t<e.length;t++)i=(i<<5)-i+e.charCodeAt(t),i|=0;return t.colors[Math.abs(i)%t.colors.length]},t.enable(t.load()),t}(t);const{formatters:i}=e.exports;i.j=e=>{try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(X,X.exports);var Z=K(X.exports);const Q="undefined"!=typeof window?window:self,ee=Q.RTCPeerConnection||Q.mozRTCPeerConnection||Q.webkitRTCPeerConnection,te=Q.RTCSessionDescription||Q.mozRTCSessionDescription||Q.webkitRTCSessionDescription,ie=Q.RTCIceCandidate||Q.mozRTCIceCandidate||Q.webkitRTCIceCandidate;var ne,se={exports:{}},re="object"==typeof Reflect?Reflect:null,ae=re&&"function"==typeof re.apply?re.apply:function(e,t,i){return function(){}.apply.call(e,t,i)};ne=re&&"function"==typeof re.ownKeys?re.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var oe=Number.isNaN||function(e){return e!=e};function de(){de.init.call(this)}se.exports=de,se.exports.once=function(e,t){return new Promise(((i,n)=>{function s(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}ye(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&ye(e,"error",t,{once:!0})}(e,s)}))},de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var he=10;function le(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function ce(e){return void 0===e._maxListeners?de.defaultMaxListeners:e._maxListeners}function ue(e,t,i,n){var s,r,a,o;if(le(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),a=r[t]),void 0===a)a=r[t]=i,++e._eventsCount;else if("function"==typeof a?a=r[t]=n?[i,a]:[a,i]:n?a.unshift(i):a.push(i),(s=ce(e))>0&&a.length>s&&!a.warned){a.warned=!0;var d=Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=a.length,o=d,console&&console.warn&&console.warn(o)}return e}function pe(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function fe(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},s=pe.bind(n);return s.listener=i,n.wrapFn=s,s}function _e(e,t,i){var n=e._events;if(void 0===n)return[];var s=n[t];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(s):ge(s,s.length)}function me(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function ge(e,t){for(var i=Array(t),n=0;n<t;++n)i[n]=e[n];return i}function ye(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function s(r){n.once&&e.removeEventListener(t,s),i(r)}))}}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:()=>he,set(e){if("number"!=typeof e||e<0||oe(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");he=e}}),de.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},de.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||oe(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},de.prototype.getMaxListeners=function(){return ce(this)},de.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,s=this._events;if(void 0!==s)n=n&&void 0===s.error;else if(!n)return!1;if(n){var r;if(t.length>0&&(r=t[0]),r instanceof Error)throw r;var a=Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var o=s[e];if(void 0===o)return!1;if("function"==typeof o)ae(o,this,t);else{var d=o.length,h=ge(o,d);for(i=0;i<d;++i)ae(h[i],this,t)}return!0},de.prototype.addListener=function(e,t){return ue(this,e,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(e,t){return ue(this,e,t,!0)},de.prototype.once=function(e,t){return le(t),this.on(e,fe(this,e,t)),this},de.prototype.prependOnceListener=function(e,t){return le(t),this.prependListener(e,fe(this,e,t)),this},de.prototype.removeListener=function(e,t){var i,n,s,r,a;if(le(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(s=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){a=i[r].listener,s=r;break}if(s<0)return this;0===s?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,s),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},de.prototype.off=de.prototype.removeListener,de.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var s,r=Object.keys(i);for(n=0;n<r.length;++n)"removeListener"!==(s=r[n])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},de.prototype.listeners=function(e){return _e(this,e,!0)},de.prototype.rawListeners=function(e){return _e(this,e,!1)},de.listenerCount=(e,t)=>"function"==typeof e.listenerCount?e.listenerCount(t):me.call(e,t),de.prototype.listenerCount=me,de.prototype.eventNames=function(){return this._eventsCount>0?ne(this._events):[]};var be=se.exports,ve="function"==typeof queueMicrotask?queueMicrotask:e=>Promise.resolve().then(e);const we=class{clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}constructor(e){if(!(e>0)||e-1&e)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}};var Ce=class{decode(e){return this.decoder.decode(e,{stream:!0})}flush(){return this.decoder.decode(new Uint8Array(0))}constructor(e){this.decoder=new TextDecoder("utf16le"===e?"utf16-le":e)}};const Se=Ce,Ee=Ce,{EventEmitter:xe}=be,Te=Error("Stream was destroyed"),ke=ve,Re=class{clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){const t=this.head;this.head=t.next=new we(2*this.head.buffer.length),this.head.push(e)}}shift(){0!==this.length&&this.length--;const e=this.tail.shift();if(void 0===e&&this.tail.next){const e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){const e=this.tail.peek();return void 0===e&&this.tail.next?this.tail.next.peek():e}isEmpty(){return 0===this.length}constructor(e){this.hwm=e||16,this.head=new we(this.hwm),this.tail=this.head,this.length=0}},Ae=536870910,Ne=16384,Le=32768,Fe=131072,Pe=536870143,Oe=536838143,Ie=536739839,De=524288,Me=1048576,je=2097152,Ue=8388608,qe=16777216,We=33554432,$e=469499903,He=503316479,Be=262160,Ye=8404992,ze=8405006,Je=33587200,Ke=33587215,Ve=270794767,Ge=Symbol.asyncIterator||Symbol();class Xe{get ended(){return!!(this.stream._duplexState&Ue)}push(e){return null!==this.map&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=je,!0):(this.stream._duplexState|=6291456,!1)}shift(){const e=this.queue.shift();return this.buffered-=this.byteLength(e),0===this.buffered&&(this.stream._duplexState&=534773759),e}end(e){"function"==typeof e?this.stream.once("finish",e):null!=e&&this.push(e),this.stream._duplexState=535822335&this.stream._duplexState|134217728}autoBatch(e,t){const i=[],n=this.stream;for(i.push(e);2359296==(n._duplexState&Ve);)i.push(n._writableState.shift());if(15&n._duplexState)return t(null);n._writev(i,t)}update(){const e=this.stream;e._duplexState|=De;do{for(;(e._duplexState&Ve)===je;){const t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}1310720&e._duplexState||this.updateNonPrimary()}while(!0===this.continueUpdate());e._duplexState&=536346623}updateNonPrimary(){const e=this.stream;if(134217728==(144965647&e._duplexState))return e._duplexState=402653183&e._duplexState|262144,void e._final(tt.bind(this));4!=(14&e._duplexState)?1==(e._duplexState&Ke)&&(e._duplexState=(e._duplexState|Be)&Ae,e._open(ot.bind(this))):e._duplexState&Je||(e._duplexState|=Be,e._destroy(it.bind(this)))}continueUpdate(){return!!(this.stream._duplexState&We)&&(this.stream._duplexState&=He,!0)}updateCallback(){(35127311&this.stream._duplexState)===Me?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&We||(this.stream._duplexState|=We,this.stream._duplexState&De||ke(this.afterUpdateNextTick))}constructor(e,{highWaterMark:t=16384,map:i=null,mapWritable:n,byteLength:s,byteLengthWritable:r}={}){this.stream=e,this.queue=new Re,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=r||s||pt,this.map=n||i,this.afterWrite=nt.bind(this),this.afterUpdateNextTick=at.bind(this)}}class Ze{get ended(){return!!(this.stream._duplexState&Ne)}pipe(e,t){if(null!==this.pipeTo)throw Error("Can only pipe to one destination");if("function"!=typeof t&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new Qe(this.stream,e,t),t&&this.stream.on("error",ft),ut(e))e._writableState.pipeline=this.pipeline,t&&e.on("error",ft),e.on("finish",this.pipeline.finished.bind(this.pipeline));else{const t=this.pipeline.done.bind(this.pipeline,e),i=this.pipeline.done.bind(this.pipeline,e,null);e.on("error",t),e.on("close",i),e.on("finish",this.pipeline.finished.bind(this.pipeline))}e.on("drain",et.bind(this)),this.stream.emit("piping",e),e.emit("pipe",this.stream)}push(e){const t=this.stream;return null===e?(this.highWaterMark=0,t._duplexState=536805311&t._duplexState|1024,!1):(null!==this.map&&null===(e=this.map(e))||(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=536805375&t._duplexState|128),this.buffered<this.highWaterMark)}shift(){const e=this.queue.shift();return this.buffered-=this.byteLength(e),0===this.buffered&&(this.stream._duplexState&=536862591),e}unshift(e){const t=[null!==this.map?this.map(e):e];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){const i=t[e];this.buffered+=this.byteLength(i),this.queue.push(i)}this.push(t[t.length-1])}read(){const e=this.stream;if(128==(16527&e._duplexState)){const t=this.shift();return null!==this.pipeTo&&!1===this.pipeTo.write(t)&&(e._duplexState&=Pe),2048&e._duplexState&&e.emit("data",t),t}return!1===this.readAhead&&(e._duplexState|=Fe,this.updateNextTick()),null}drain(){const e=this.stream;for(;128==(16527&e._duplexState)&&768&e._duplexState;){const t=this.shift();null!==this.pipeTo&&!1===this.pipeTo.write(t)&&(e._duplexState&=Pe),2048&e._duplexState&&e.emit("data",t)}}update(){const e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(214047&e._duplexState)===Fe;)e._duplexState|=65552,e._read(this.afterRead),this.drain();4224==(12431&e._duplexState)&&(e._duplexState|=8192,e.emit("readable")),80&e._duplexState||this.updateNonPrimary()}while(!0===this.continueUpdate());e._duplexState&=536870879}updateNonPrimary(){const e=this.stream;1024==(1167&e._duplexState)&&(e._duplexState=536869887&e._duplexState|16384,e.emit("end"),(e._duplexState&ze)===Ye&&(e._duplexState|=4),null!==this.pipeTo&&this.pipeTo.end()),4!=(14&e._duplexState)?1==(e._duplexState&Ke)&&(e._duplexState=(e._duplexState|Be)&Ae,e._open(ot.bind(this))):e._duplexState&Je||(e._duplexState|=Be,e._destroy(it.bind(this)))}continueUpdate(){return!!(this.stream._duplexState&Le)&&(this.stream._duplexState&=Oe,!0)}updateCallback(){64==(32879&this.stream._duplexState)?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&Le||(this.stream._duplexState|=Le,32&this.stream._duplexState||ke(this.afterUpdateNextTick))}constructor(e,{highWaterMark:t=16384,map:i=null,mapReadable:n,byteLength:s,byteLengthReadable:r}={}){this.stream=e,this.queue=new Re,this.highWaterMark=0===t?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=r||s||pt,this.map=n||i,this.pipeTo=null,this.afterRead=st.bind(this),this.afterUpdateNextTick=rt.bind(this)}}class Qe{finished(){this.pipeToFinished=!0}done(e,t){t&&(this.error=t),e!==this.to||(this.to=null,null===this.from)?e!==this.from||(this.from=null,null===this.to)?(null!==this.afterPipe&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null):e._duplexState&Ne||this.to.destroy(this.error||Error("Readable stream closed before ending")):this.from._duplexState&Ne&&this.pipeToFinished||this.from.destroy(this.error||Error("Writable stream closed prematurely"))}constructor(e,t,i){this.from=e,this.to=t,this.afterPipe=i,this.error=null,this.pipeToFinished=!1}}function et(){this.stream._duplexState|=512,this.updateCallback()}function tt(e){const t=this.stream;e&&t.destroy(e),14&t._duplexState||(t._duplexState|=Ue,t.emit("finish")),(t._duplexState&ze)===Ye&&(t._duplexState|=4),t._duplexState&=$e,t._duplexState&De?this.updateNextTick():this.update()}function it(e){const t=this.stream;e||this.error===Te||(e=this.error),e&&t.emit("error",e),t._duplexState|=8,t.emit("close");const i=t._readableState,n=t._writableState;if(null!==i&&null!==i.pipeline&&i.pipeline.done(t,e),null!==n){for(;null!==n.drains&&n.drains.length>0;)n.drains.shift().resolve(!1);null!==n.pipeline&&n.pipeline.done(t,e)}}function nt(e){const t=this.stream;e&&t.destroy(e),t._duplexState&=$e,null!==this.drains&&function(e){for(let t=0;t<e.length;t++)0==--e[t].writes&&(e.shift().resolve(!0),t--)}(this.drains),4194304==(6553615&t._duplexState)&&(t._duplexState&=532676607,(t._duplexState&qe)===qe&&t.emit("drain")),this.updateCallback()}function st(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,!1!==this.readAhead||256&this.stream._duplexState||(this.stream._duplexState&=Ie),this.updateCallback()}function rt(){32&this.stream._duplexState||(this.stream._duplexState&=Oe,this.update())}function at(){this.stream._duplexState&De||(this.stream._duplexState&=He,this.update())}function ot(e){const t=this.stream;e&&t.destroy(e),4&t._duplexState||(17423&t._duplexState||(t._duplexState|=64),142606351&t._duplexState||(t._duplexState|=Me),t.emit("open")),t._duplexState&=536608751,null!==t._writableState&&t._writableState.updateCallback(),null!==t._readableState&&t._readableState.updateCallback()}function dt(e){null!==this._readableState&&("data"===e&&(this._duplexState|=133376,this._readableState.updateNextTick()),"readable"===e&&(this._duplexState|=4096,this._readableState.updateNextTick())),null!==this._writableState&&"drain"===e&&(this._duplexState|=qe,this._writableState.updateNextTick())}class ht extends xe{_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return null!==this._readableState||void 0}get writable(){return null!==this._writableState||void 0}get destroyed(){return!!(8&this._duplexState)}get destroying(){return!!(14&this._duplexState)}destroy(e){14&this._duplexState||(e||(e=Te),this._duplexState=535822271&this._duplexState|4,null!==this._readableState&&(this._readableState.highWaterMark=0,this._readableState.error=e),null!==this._writableState&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,null!==this._readableState&&this._readableState.updateNextTick(),null!==this._writableState&&this._writableState.updateNextTick())}constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener("abort",_t.bind(this))),this.on("newListener",dt)}}class lt extends ht{setEncoding(e){const t=new class{push(e){return"string"==typeof e?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t="";return e&&(t=this.push(e)),t+=this.decoder.flush(),t}constructor(e="utf8"){switch(this.encoding=function(e){switch(e=e.toLowerCase()){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:throw Error("Unknown encoding: "+e)}}(e),this.encoding){case"utf8":this.decoder=new Ee;break;case"utf16le":case"base64":throw Error("Unsupported encoding: "+this.encoding);default:this.decoder=new Se(this.encoding)}}}(e),i=this._readableState.map||ct;return this._readableState.map=function(e){const n=t.push(e);return""===n?null:i(n)},this}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTick(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTick(),this._readableState.unshift(e)}resume(){return this._duplexState|=131328,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=!1===this._readableState.readAhead?536739583:536870655,this}static _fromAsyncIterator(e,t){let i;const n=new lt((0,S.default)((0,C.default)({},t),{read(t){e.next().then(s).then(t.bind(null,null)).catch(t)},predestroy(){i=e.return()},destroy(e){if(!i)return e(null);i.then(e.bind(null,null)).catch(e)}}));return n;function s(e){e.done?n.push(null):n.push(e.value)}}static from(e,t){if(ut(i=e)&&i.readable)return e;var i;if(e[Ge])return this._fromAsyncIterator(e[Ge](),t);Array.isArray(e)||(e=void 0===e?[]:[e]);let n=0;return new lt((0,S.default)((0,C.default)({},t),{read(t){this.push(n===e.length?null:e[n++]),t(null)}}))}static isBackpressured(e){return!!(17422&e._duplexState)||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return!(256&e._duplexState)}[Ge](){const e=this;let t=null,i=null,n=null;return this.on("error",(e=>{t=e})),this.on("readable",(function(){null!==i&&s(e.read())})),this.on("close",(function(){null!==i&&s(null)})),{[Ge](){return this},next:()=>new Promise(((t,r)=>{i=t,n=r;const a=e.read();null!==a?s(a):8&e._duplexState&&s(null)})),return:()=>r(null),throw:e=>r(e)};function s(s){null!==n&&(t?n(t):null!==s||e._duplexState&Ne?i({value:s,done:null===s}):n(Te),n=i=null)}function r(t){return e.destroy(t),new Promise(((i,n)=>{if(8&e._duplexState)return i({value:void 0,done:!0});e.once("close",(()=>{t?n(t):i({value:void 0,done:!0})}))}))}}constructor(e){super(e),this._duplexState|=8519681,this._readableState=new Ze(this,e),e&&(!1===this._readableState.readAhead&&(this._duplexState&=Ie),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}}function ct(e){return e}function ut(e){return"number"==typeof e._duplexState&&function(e){return!!e._readableState||!!e._writableState}(e)}function pt(e){return function(e){return"object"==typeof e&&null!==e&&"number"==typeof e.byteLength}(e)?e.byteLength:1024}function ft(){}function _t(){this.destroy(Error("Stream aborted."))}var mt=class extends lt{cork(){this._duplexState|=268435456}uncork(){this._duplexState&=268435455,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}constructor(e){super(e),this._duplexState=1|this._duplexState&Fe,this._writableState=new Xe(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}};function gt(e,t){for(const i in t)Object.defineProperty(e,i,{value:t[i],enumerable:!0,configurable:!0});return e}var yt=K((function(e,t,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof t&&(i=t,t=""),t&&(i.code=t);try{return gt(e,i)}catch(t){i.message=e.message,i.stack=e.stack;const n=()=>{};return n.prototype=Object.create(Object.getPrototypeOf(e)),gt(new n,i)}}));const bt="0123456789abcdef",vt=[];for(let e=0;e<256;e++)vt[e]=bt[e>>4&15]+bt[15&e];const wt=e=>{const t=e.length;let i="",n=0;for(;n<t;)i+=vt[e[n++]];return i};for(var Ct="undefined"==typeof Uint8Array?[]:new Uint8Array(256),St=0;St<64;St++)Ct["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(St)]=St;new TextDecoder;const Et=new TextEncoder,xt="undefined"!=typeof window?window:self,Tt=xt.crypto||xt.msCrypto||{};Tt.subtle||Tt.webkitSubtle;const kt=e=>{const t=new Uint8Array(e);return Tt.getRandomValues(t)},Rt=Z("simple-peer"),At=65536;function Nt(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}let Lt=class e extends mt{get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this._destroying){if(this.destroyed)throw yt(Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new te(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.__destroy(yt(e,"ERR_SET_REMOTE_DESCRIPTION"))})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.__destroy(yt(Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new ie(e);this._pc.addIceCandidate(t).catch((e=>{!t.address||t.address.endsWith(".local")?console.warn("Ignoring unsupported ICE candidate."):this.__destroy(yt(e,"ERR_ADD_ICE_CANDIDATE"))}))}send(e){if(!this._destroying){if(this.destroyed)throw yt(Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,queueMicrotask((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){if(!this._destroying){if(this.destroyed)throw yt(Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}_final(e){this._readableState.ended||this.push(null),e(null)}__destroy(e){this.end(),this._destroy((()=>{}),e)}_destroy(e,t){this.destroyed||this._destroying||(this._destroying=!0,this._debug("destroying (error: %s)",t&&(t.message||t)),setTimeout((()=>{if(this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,t&&this.emit("error",t),e()}),0))}_setupData(e){if(!e.channel)return this.__destroy(yt(Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=At),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.__destroy(yt(t,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_write(e,t){if(this.destroyed)return t(yt(Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.__destroy(yt(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>At?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=t):t(null)}else this._debug("write before connect"),this._chunk=e,this._cb=t}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.__destroy()),1e3)};this._connected?e():this.once("connect",e)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=Nt(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.__destroy(yt(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.__destroy(yt(e,"ERR_CREATE_OFFER"))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=Nt(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{var t;if(this.destroyed)return;const i=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:i.type,sdp:i.sdp}),this.initiator||null===(t=this._requestMissingTransceivers)||void 0===t||t.call(this)};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.__destroy(yt(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.__destroy(yt(e,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||this._destroying||"failed"===this._pc.connectionState&&this.__destroy(yt(Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.__destroy(yt(Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.__destroy(yt(Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"==={}.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((i=>{const n=[];i.forEach((e=>{n.push(t(e))})),e(null,n)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((i=>{if(this.destroyed)return;const n=[];i.result().forEach((e=>{const i={};e.names().forEach((t=>{i[t]=e.stat(t)})),i.id=e.id,i.type=e.type,i.timestamp=e.timestamp,n.push(t(i))})),e(null,n)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this._destroying||this.getStats(((t,i)=>{if(this.destroyed||this._destroying)return;t&&(i=[]);const n={},s={},r={};let a=!1;i.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(n[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(s[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(r[e.id]=e)}));const o=e=>{a=!0;let t=s[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let i=n[e.remoteCandidateId];i&&(i.ip||i.address)?(this.remoteAddress=i.ip||i.address,this.remotePort=Number(i.port)):i&&i.ipAddress?(this.remoteAddress=i.ipAddress,this.remotePort=Number(i.portNumber)):"string"==typeof e.googRemoteAddress&&(i=e.googRemoteAddress.split(":"),this.remoteAddress=i[0],this.remotePort=Number(i[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(i.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(r[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(r).length&&!Object.keys(s).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.__destroy(yt(t,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>At||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;var i;t instanceof ArrayBuffer?t=new Uint8Array(t):!1===this.__objectMode&&(i=t,t=Et.encode(i)),this.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.__destroy())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],Rt.apply(null,e)}constructor(t){if(super(t=Object.assign({allowHalfOpen:!1},t)),(0,w.default)(this,"_pc",void 0),this.__objectMode=!!t.objectMode,this._id=wt(kt(4)).slice(0,7),this._debug("new peer %o",t),this.channelName=t.initiator?t.channelName||wt(kt(20)):null,this.initiator=t.initiator||!1,this.channelConfig=t.channelConfig||e.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},e.config,t.config),this.offerOptions=t.offerOptions||{},this.answerOptions=t.answerOptions||{},this.sdpTransform=t.sdpTransform||(e=>e),this.trickle=void 0===t.trickle||t.trickle,this.allowHalfTrickle=void 0!==t.allowHalfTrickle&&t.allowHalfTrickle,this.iceCompleteTimeout=t.iceCompleteTimeout||5e3,this._destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,!ee)throw"undefined"==typeof window?yt(Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):yt(Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new ee(this.config)}catch(e){return void this.__destroy(yt(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch((e=>{this.__destroy(yt(e,"ERR_PC_PEER_IDENTITY"))})),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}};Lt.WEBRTC_SUPPORT=!!ee,Lt.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Lt.channelConfig={};class Ft extends Lt{addTransceiver(e,t){if(!this._destroying){if(this.destroyed)throw yt(Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.__destroy(yt(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this._destroying){if(this.destroyed)throw yt(Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach((t=>{this.addTrack(t,e)}))}}addTrack(e,t){if(this._destroying)return;if(this.destroyed)throw yt(Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const i=this._senderMap.get(e)||new Map;let n=i.get(t);if(n)throw n.removed?yt(Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):yt(Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");n=this._pc.addTrack(e,t),i.set(t,n),this._senderMap.set(e,i),this._needsNegotiation()}replaceTrack(e,t,i){if(this._destroying)return;if(this.destroyed)throw yt(Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const n=this._senderMap.get(e),s=n?n.get(i):null;if(!s)throw yt(Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,n),null!=s.replaceTrack?s.replaceTrack(t):this.__destroy(yt(Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(e,t){if(this._destroying)return;if(this.destroyed)throw yt(Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const i=this._senderMap.get(e),n=i?i.get(t):null;if(!n)throw yt(Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{n.removed=!0,this._pc.removeTrack(n)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(n):this.__destroy(yt(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this._destroying){if(this.destroyed)throw yt(Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach((t=>{this.removeTrack(t,e)}))}}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_onTrack(e){this.destroyed||e.streams.forEach((t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some((e=>e.id===t.id))||(this._remoteStreams.push(t),queueMicrotask((()=>{this._debug("on stream"),this.emit("stream",t)})))}))}constructor(e={}){super(e),this._pc&&(this.streams=e.streams||(e.stream?[e.stream]:[]),this._senderMap=new Map,this.streams&&this.streams.forEach((e=>{this.addStream(e)})),this._pc.ontrack=e=>{this._onTrack(e)})}}const Pt="data",Ot="signal";var It=(e,t)=>{const i=new Ft((0,S.default)((0,C.default)({iceServers:[{urls:Dt}]},t),{initiator:e,trickle:!1})),n=e=>s.push(e);let s=[];return i.on(Pt,n),{id:i._id,created:Date.now(),connection:i._pc,get channel(){return i._channel},get isDead(){return i.destroyed},signal:t=>new Promise((n=>{e||i.on(Ot,n),i.signal(t)})),sendData:e=>i.send(e),destroy:()=>i.destroy(),setHandlers:e=>Object.entries(e).forEach((([e,t])=>i.on(e,t))),offerPromise:e?new Promise((e=>i.on(Ot,e))):Promise.resolve(),addStream:e=>i.addStream(e),removeStream:e=>i.removeStream(e),addTrack:(e,t)=>i.addTrack(e,t),removeTrack:(e,t)=>i.removeTrack(e,t),replaceTrack:(e,t,n)=>i.replaceTrack(e,t,n),drainEarlyData(e){i.off(Pt,n),s.forEach(e),s=null}}};const Dt=[...T(5,((e,t)=>`stun:stun${t||""}.l.google.com:19302`)),"stun:global.stun.twilio.com:3478"],Mt=Object.getPrototypeOf(Uint8Array),jt=16369,Ut=255,qt="bufferedamountlow",Wt=e=>"@_"+e,$t={},Ht={},Bt={},Yt={},zt={},Jt={},Kt={},Vt={},Gt=async e=>{if(Ht[e])return Ht[e];const t=(await Y(e)).slice(0,20);return Ht[e]=t,Bt[t]=e,t},Xt=async(e,t,i)=>e.send(q((0,C.default)({action:"announce",info_hash:await Gt(t),peer_id:R},i))),Zt=(e,t,i)=>console.warn(`${x}: torrent tracker ${i?"failure":"warning"} from ${e} - ${t}`),Qt=(({init:e,subscribe:t,announce:i})=>{const n={};let s,_,m,g=!1;return(y,b,v)=>{var w;const{appId:E}=y;if(null===(w=n[E])||void 0===w?void 0:w[b])return n[E][b];const k={},I={},D=U(x,E,b),$=Y(D),B=Y(U(D,R)),K=y.password&&(async(e,t,i)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},M(`${e}:${t}:${i}`)),{name:H},!1,["encrypt","decrypt"]))(y.password,E,b),V=e=>async t=>K?{type:t.type,sdp:await e(K,t.sdp)}:t,G=V(J),X=V(z),Z=()=>It(!0,y.rtcConfig),Q=(e,t,i)=>{var n;I[t]?I[t]!==e&&e.destroy():(I[t]=e,ae(e,t),null===(n=k[t])||void 0===n||n.forEach(((e,t)=>{t!==i&&e.destroy()})),delete k[t])},ee=(e,t)=>{I[t]===e&&delete I[t]},te=e=>(_.push(...T(e,Z)),A(_.splice(0,e).map((e=>e.offerPromise.then(X).then((t=>({peer:e,offer:t}))))))),ie=(e,t)=>null==v?void 0:v({error:`incorrect password (${y.password}) when decrypting ${t}`,appId:E,peerId:e,roomId:b});if(!y)throw O("requires a config map as the first argument");if(!E&&!y.firebaseApp)throw O("config map is missing appId field");if(!b)throw O("roomId argument required");if(!g){const t=e(y);_=T(20,Z),s=Array.isArray(t)?t:[t],g=!0,m=setInterval((()=>_=_.filter((e=>{const t=Date.now()-e.created<57333;return t||e.destroy(),t}))),59052.99)}const ne=s.map((()=>5333)),se=[],re=s.map((async(e,i)=>t(await e,await $,await B,(e=>async(t,i,n)=>{const[s,o]=await A([$,B]);if(t!==s&&t!==o)return;const{peerId:d,offer:h,answer:l,peer:c}="string"==typeof i?W(i):i;if(d!==R&&!I[d])if(!d||h||l){if(h){var u;if((null===(u=k[d])||void 0===u?void 0:u[e])&&R>d)return;const t=It(!1,y.rtcConfig);let i;t.setHandlers({connect:()=>Q(t,d,e),close:()=>ee(t,d)});try{i=await G(h)}catch(e){return void ie(d,"offer")}if(t.isDead)return;const[s,r]=await A([Y(U(D,d)),t.signal(i)]);n(s,q({peerId:R,answer:await X(r)}))}else if(l){let t;try{t=await G(l)}catch(e){return void ie(d,"answer")}if(c)c.setHandlers({connect:()=>Q(c,d,e),close:()=>ee(c,d)}),c.si