@swarmcloud/hls
Version:
Let your viewers become your unlimitedly scalable CDN.
1 lines • 208 kB
JavaScript
var e={415:e=>{var t,s="object"==typeof Reflect?Reflect:null,i=s&&"function"==typeof s.apply?s.apply:function(e,t,s){return Function.prototype.apply.call(e,t,s)};t=s&&"function"==typeof s.ownKeys?s.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function n(){n.init.call(this)}e.exports=n,e.exports.once=function(e,t){return new Promise((function(s,i){function r(s){e.removeListener(t,n),i(s)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",r),s([].slice.call(arguments))}p(e,t,n,{once:!0}),"error"!==t&&function(e,t,s){"function"==typeof e.on&&p(e,"error",t,s)}(e,r,{once:!0})}))},n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?n.defaultMaxListeners:e._maxListeners}function l(e,t,s,i){var r,n,o,l;if(a(s),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,s.listener?s.listener:s),n=e._events),o=n[t]),void 0===o)o=n[t]=s,++e._eventsCount;else if("function"==typeof o?o=n[t]=i?[s,o]:[o,s]:i?o.unshift(s):o.push(s),(r=h(e))>0&&o.length>r&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,l=c,console&&console.warn&&console.warn(l)}return e}function c(){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 d(e,t,s){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:s},r=c.bind(i);return r.listener=s,i.wrapFn=r,r}function u(e,t,s){var i=e._events;if(void 0===i)return[];var r=i[t];return void 0===r?[]:"function"==typeof r?s?[r.listener||r]:[r]:s?function(e){for(var t=new Array(e.length),s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(r):f(r,r.length)}function g(e){var t=this._events;if(void 0!==t){var s=t[e];if("function"==typeof s)return 1;if(void 0!==s)return s.length}return 0}function f(e,t){for(var s=new Array(t),i=0;i<t;++i)s[i]=e[i];return s}function p(e,t,s,i){if("function"==typeof e.on)i.once?e.once(t,s):e.on(t,s);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 r(n){i.once&&e.removeEventListener(t,r),s(n)}))}}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),n.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},n.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(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},n.prototype.getMaxListeners=function(){return h(this)},n.prototype.emit=function(e){for(var t=[],s=1;s<arguments.length;s++)t.push(arguments[s]);var r="error"===e,n=this._events;if(void 0!==n)r=r&&void 0===n.error;else if(!r)return!1;if(r){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var h=n[e];if(void 0===h)return!1;if("function"==typeof h)i(h,this,t);else{var l=h.length,c=f(h,l);for(s=0;s<l;++s)i(c[s],this,t)}return!0},n.prototype.addListener=function(e,t){return l(this,e,t,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(e,t){return l(this,e,t,!0)},n.prototype.once=function(e,t){return a(t),this.on(e,d(this,e,t)),this},n.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,d(this,e,t)),this},n.prototype.removeListener=function(e,t){var s,i,r,n,o;if(a(t),void 0===(i=this._events))return this;if(void 0===(s=i[e]))return this;if(s===t||s.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,s.listener||t));else if("function"!=typeof s){for(r=-1,n=s.length-1;n>=0;n--)if(s[n]===t||s[n].listener===t){o=s[n].listener,r=n;break}if(r<0)return this;0===r?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,r),1===s.length&&(i[e]=s[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(e){var t,s,i;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var r,n=Object.keys(s);for(i=0;i<n.length;++i)"removeListener"!==(r=n[i])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},n.prototype.listeners=function(e){return u(this,e,!0)},n.prototype.rawListeners=function(e){return u(this,e,!1)},n.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},n.prototype.listenerCount=g,n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var r=o.parseURL(e);if(!r)throw new Error("Error trying to parse base URL.");return r.path=o.normalizePath(r.path),o.buildURLFromParts(r)}var n=o.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=o.normalizePath(n.path),o.buildURLFromParts(n)):t;var a=o.parseURL(e);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var h=i.exec(a.path);a.netLoc=h[1],a.path=h[2]}a.netLoc&&!a.path&&(a.path="/");var l={scheme:a.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(l.netLoc=a.netLoc,"/"!==n.path[0]))if(n.path){var c=a.path,d=c.substring(0,c.lastIndexOf("/")+1)+n.path;l.path=o.normalizePath(d)}else l.path=a.path,n.params||(l.params=a.params,n.query||(l.query=a.query));return null===l.path&&(l.path=s.alwaysNormalize?o.normalizePath(n.path):n.path),o.buildURLFromParts(l)},parseURL:function(e){var t=s.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=o}()},424:(e,t)=>{t.h=r;var s=2147483647;function i(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=r.prototype,t}function r(e,t,s){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return a(e)}return n(e,t,s)}function n(e,t,s){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!r.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var s=0|c(e,t),n=i(s),o=n.write(e,t);o!==s&&(n=n.slice(0,o));return n}(e,t);if(ArrayBuffer.isView(e))return h(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(_(e,ArrayBuffer)||e&&_(e.buffer,ArrayBuffer))return function(e,t,s){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(s||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===t&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,t):new Uint8Array(e,t,s);return i.__proto__=r.prototype,i}(e,t,s);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return r.from(n,t,s);var o=function(e){if(r.isBuffer(e)){var t=0|l(e.length),s=i(t);return 0===s.length||e.copy(s,0,0,t),s}if(void 0!==e.length)return"number"!=typeof e.length||S(e.length)?i(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return r.from(e[Symbol.toPrimitive]("string"),t,s);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function o(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function a(e){return o(e),i(e<0?0:0|l(e))}function h(e){for(var t=e.length<0?0:0|l(e.length),s=i(t),r=0;r<t;r+=1)s[r]=255&e[r];return s}function l(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function c(e,t){if(r.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||_(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var s=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===s)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":return m(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;default:if(n)return i?-1:m(e).length;t=(""+t).toLowerCase(),n=!0}}function d(e,t,s,i){s=Number(s)||0;const r=e.length-s;i?(i=Number(i))>r&&(i=r):i=r;const n=t.length;let o;for(i>n/2&&(i=n/2),o=0;o<i;++o){const i=parseInt(t.substr(2*o,2),16);if(S(i))return o;e[s+o]=i}return o}function u(e,t,s,i){return p(m(t,e.length-s),e,s,i)}function g(e,t,s,i){return p(function(e){const t=[];for(let s=0;s<e.length;++s)t.push(255&e.charCodeAt(s));return t}(t),e,s,i)}function f(e,t,s,i){return p(function(e,t){let s,i,r;const n=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)s=e.charCodeAt(o),i=s>>8,r=s%256,n.push(r),n.push(i);return n}(t,e.length-s),e,s,i)}function p(e,t,s,i){let r;for(r=0;r<i&&!(r+s>=t.length||r>=e.length);++r)t[r+s]=e[r];return r}function m(e,t){var s;t=t||1/0;for(var i=e.length,r=null,n=[],o=0;o<i;++o){if((s=e.charCodeAt(o))>55295&&s<57344){if(!r){if(s>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&n.push(239,191,189);continue}r=s;continue}if(s<56320){(t-=3)>-1&&n.push(239,191,189),r=s;continue}s=65536+(r-55296<<10|s-56320)}else r&&(t-=3)>-1&&n.push(239,191,189);if(r=null,s<128){if((t-=1)<0)break;n.push(s)}else if(s<2048){if((t-=2)<0)break;n.push(s>>6|192,63&s|128)}else if(s<65536){if((t-=3)<0)break;n.push(s>>12|224,s>>6&63|128,63&s|128)}else{if(!(s<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(s>>18|240,s>>12&63|128,s>>6&63|128,63&s|128)}}return n}function _(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function S(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),r.from=function(e,t,s){return n(e,t,s)},r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,r.alloc=function(e,t,s){return function(e,t,s){return o(e),e<=0?i(e):void 0!==t?"string"==typeof s?i(e).fill(t,s):i(e).fill(t):i(e)}(e,t,s)},r.allocUnsafe=function(e){return a(e)},r.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==r.prototype},r.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return r.alloc(0);var s;if(void 0===t)for(t=0,s=0;s<e.length;++s)t+=e[s].length;var i=r.allocUnsafe(t),n=0;for(s=0;s<e.length;++s){var o=e[s];if(_(o,Uint8Array)&&(o=r.from(o)),!r.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(i,n),n+=o.length}return i},r.byteLength=c,r.prototype._isBuffer=!0,r.prototype.copy=function(e,t,s,i){if(!r.isBuffer(e))throw new TypeError("argument should be a Buffer");if(s||(s=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<s&&(i=s),i===s)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(s<0||s>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-s&&(i=e.length-t+s);var n=i-s;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,s,i);else if(this===e&&s<t&&t<i)for(var o=n-1;o>=0;--o)e[o+t]=this[o+s];else Uint8Array.prototype.set.call(e,this.subarray(s,i),t);return n},r.prototype.write=function(e,t,s,i){if(void 0===t)i="utf8",s=this.length,t=0;else if(void 0===s&&"string"==typeof t)i=t,s=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(s)?(s>>>=0,void 0===i&&(i="utf8")):(i=s,s=void 0)}const r=this.length-t;if((void 0===s||s>r)&&(s=r),e.length>0&&(s<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!1;for(;;)switch(i){case"hex":return d(this,e,t,s);case"utf8":case"utf-8":return u(this,e,t,s);case"ascii":case"latin1":case"binary":return g(this,e,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return f(this,e,t,s);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}}},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var s={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return s.isAndroid()||s.isAndroidWebView()?t.ANDROID_WEB:s.isIOS()||s.isIpad()||s.isIOSWebView()?t.IOS_WEB:s.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!n(r("os "))&&!n(r("android[/ ]"))},isIOS:function(){return n(r("os "))},isIpad:function(){return i().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return n(r("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return s.isAndroid()||s.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=i();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=i();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return s.isAndroidWebView()||s.isIOSWebView()},device:t,getBrowser:function(){return s.isX5()?"X5":s.isAndroidWebView()?"Android-WebView":s.isIOSWebView()?"iOS-WebView":s.isChrome()?"Chrome":s.isFirefox()?"Firefox":s.isIpadSafari()?"iPad-Safari":s.isIOSSafari()?"iPhone-Safari":s.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function r(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function n(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=s}},t={};function s(i){var r=t[i];if(void 0!==r)return r.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,s),n.exports}s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},s.d=(e,t)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};(()=>{s.d(i,{A:()=>ks});const e={DC_SIGNAL:"SIGNAL",DC_SIGNAL_BATCH:"SIGNAL_BATCH",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_PIECE_CANCEL:"PIECE_CANCEL",DC_CLOSE:"CLOSE",DC_DISCONNECT:"DISCONNECT",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",BM_FATAL_ERROR:"BM_FATAL_ERROR",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PROGRESS:"SYN_PROGRESS",MEDIA_REBUFFER:"MEDIA_REBUFFER"},t={...e,SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_GET_MEDIA:"SW_GET_MEDIA",SW_DEBUG:"SW_DEBUG",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED"};var r=s(415),n=s.n(r),o=s(424),a=s(558),h=s.n(a);const l="__PROXY_IDENTIFIER__";const c={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},d=64e3;function u(){return!0}function g(e){return new URL(location.href).searchParams.get(e)}function f(e,t,s){const i=new URL(e);return i.searchParams.append(t,s),i.href}function p(){return Math.floor(Date.now()/1e3)}function m(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function _(e){return new Promise((t=>setTimeout(t,e)))}function S(e,t){return new Promise(((s,i)=>setTimeout((()=>{i(t)}),e)))}function y(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function v(e){const t=o.h.from(e),s=new o.h(e.byteLength);return t.copy(s),s}function P(){return location.protocol.startsWith("https")}function b(e,t,s){if(e.size<=t)return;const i=[...e.keys()];do{const t=i.shift();s&&s(e.get(t)),e.delete(t)}while(e.size>t)}function w(e,t){if(e.size<=t)return;const s=[...e.values()];do{e.delete(s.shift())}while(e.size>t)}function E(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function C(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const s=Number(t[0]),i=t[1]?Number(t[1]):-1;return{rangeStart:s,rangeEnd:i>=0?i+1:void 0}}function T(e){return e.split("?")[0]}function I(){let e=new Date,t=e.getHours(),s=e.getMinutes(),i=e.getSeconds(),r=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${r}`}function L(e){return e&&"function"==typeof e}function R(e,t,s,i,r,n){const{sn:o,seg_id:a,size:h,level:l}=s;e.sendPartialBuffer(s,i,{from:r,incompletes:n})&&(e.bitset.add(o,l,a,c.COMPLETE,h),i.length<s.attachments?function(e,t,s){e.addStreamListener(s,t.remotePeerId,((e,s,i,r,n)=>{i?t.sendMsgPieceAbort(r,s,!0):t.uploading&&t.send(r),n&&(t.uploading=!1)}))}(t,e,!!s.reverse):e.uploading=!1)}const A=e=>0===m(0,1)?[null,e]:[e,null];function D(e,t,s){return 1===e.length?t.length>=1&&s.length>=1?t[0].weight>s[0].weight?[t[0],e[0]]:[e[0],s[0]]:t.length>=1?[t[0],e[0]]:s.length>=1?[e[0],s[0]]:A(e[0]):[t.length>=1?t[0]:null,s.length>=1?s[0]:null]}function M(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}async function k(e){if(crypto.subtle)try{const t=await crypto.subtle.digest("SHA-256",e),s=String.fromCharCode.apply(null,new Uint8Array(t));return btoa(s)}catch(e){}}function N(e,t,s){if(!t)return{message:e,stack:"",filename:s};let i="";if("string"==typeof t)i=t;else if(t.message)i=t.message;else if(t.error&&t.error.message)i=t.error.message;else if(t.reason&&t.reason.message)i=t.reason.message;else try{i=String(t)}catch(e){}let r="";return r=t.stack?t.stack:t.error&&t.error.stack?t.error.stack:t.reason&&t.reason.stack?t.reason.stack:"",{message:i.trim()||e,stack:r.trim()||JSON.stringify(t),filename:s}}function O(e){const t=[...e];for(let e=t.length-1;e>0;e--){const s=Math.floor(Math.random()*(e+1));[t[e],t[s]]=[t[s],t[e]]}return t}class ${constructor(e,t){this.target=t,this.type=e}}class B extends ${constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class x extends ${constructor(e=1e3,t="",s){super("close",s),this.code=e,this.reason=t,this.wasClean=!0}}const F=()=>{if("undefined"!=typeof WebSocket)return WebSocket},q={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1};class W{constructor(e,t,s={}){this._listeners={error:[],message:[],open:[],close:[]},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._messageQueue=[],this._closeCalled=!1,this._connectLock=!1,this._shouldReconnect=!0,this._retryCount=-1,this._binaryType="blob",this._url=e,this._protocols=t,this._options=s,this._options.startClosed&&(this._shouldReconnect=!1),this._connect(),this._handleOpen=this._handleOpen.bind(this),this._handleClose=this._handleClose.bind(this),this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this)}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return W.CONNECTING}get OPEN(){return W.OPEN}get CLOSING(){return W.CLOSING}get CLOSED(){return W.CLOSED}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?W.CLOSED:W.CONNECTING}get url(){return this._ws?this._ws.url:""}close(e=1e3,t){this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws&&this._ws.readyState!==this.CLOSED&&this._ws.close(e,t)}reconnect(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._ws.send(e);else{const{maxEnqueuedMessages:t=q.maxEnqueuedMessages}=this._options;this._messageQueue.length<t&&this._messageQueue.push(e)}}addEventListener(e,t){this._listeners[e]&&this._listeners[e].push(t)}dispatchEvent(e){const t=this._listeners[e.type];if(t)for(const s of t)this._callEventListener(e,s);return!0}removeEventListener(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((e=>e!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=q.reconnectionDelayGrowFactor,minReconnectionDelay:t=q.minReconnectionDelay,maxReconnectionDelay:s=q.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=t*Math.pow(e,this._retryCount-1),i>s&&(i=s)),i}_wait(){return new Promise((e=>{setTimeout(e,this._getNextDelay())}))}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:e=q.maxRetries,connectionTimeout:t=q.connectionTimeout,WebSocket:s=F()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(i=s)||!i||2!==i.CLOSING)throw Error("No valid WebSocket class provided");var i;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new s(e,this._protocols):new s(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout((()=>this._handleTimeout()),t))})).catch((e=>{this._connectLock=!1,this._handleError(new B(Error(e.message),this))}))}}_handleTimeout(){this._handleError(new B(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new x(e,t,this))}catch(e){}}}_acceptOpen(){this._retryCount=0}_callEventListener(e,t){"handleEvent"in t?t.handleEvent(e):t(e)}_handleOpen(e){const{minUptime:t=q.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout((()=>this._acceptOpen()),t),this._ws.binaryType=this._binaryType,this._messageQueue.forEach((e=>this._ws.send(e))),this._messageQueue=[],this.onopen&&this.onopen(e),this._listeners.open.forEach((t=>this._callEventListener(e,t)))}_handleMessage(e){this.onmessage&&this.onmessage(e),this._listeners.message.forEach((t=>this._callEventListener(e,t)))}_handleError(e){this._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),this.onerror&&this.onerror(e),this._listeners.error.forEach((t=>this._callEventListener(e,t))),this._connect()}_handleClose(e){this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this._listeners.close.forEach((t=>this._callEventListener(e,t)))}_removeListeners(){this._ws&&(this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const z={debug:3,info:4,warn:5,error:6};class U{constructor(e,t,s,i){this.wsAddr=`${e}?app=${t}&id=${s}&v=${i}`,this.destroyed=!1;try{this._ws=this._init()}catch(e){console.error(e)}}_init(){const e={maxRetries:3,minReconnectionDelay:m(5e3,15e3),maxReconnectionDelay:6e5,maxEnqueuedMessages:200};return new W(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const s=z[e];this._ws.send(JSON.stringify({records:[{level:s,text:`${I()}: ${t}`}]}))}sendBatch(e){const t=[];for(let s of e)t.push({level:z[s.levelKey],text:s.message});this._ws.send(JSON.stringify({records:t}))}destroy(){this._ws&&(this._ws.close(1e3),this._ws=null,this.destroyed=!0)}}const H={debug:0,info:1,warn:2,error:3,none:4};const j=class{constructor(e,t){this.logLevel=e,this.onlineDebug=!1,this.logCache=[],this.app=t;try{console.debug=console.log}catch(e){console.debug=console.info}"debug"!==e&&"info"!==e||(this.logLevel="error"),(e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}})("SW_DEBUG")&&(this.logLevel="debug"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in H||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in H)this[e]=console[e];this._hookLogFunc(((e,t)=>{this.logUploader&&this.logUploader.send(e,t)}))}enableReport(e){this.reportUrl=e,this._hookLogFunc(((e,t)=>{this.reportUrl?(this.logCache.push({levelKey:e,message:`${I()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,s,i,r=5e3){this.reportUrl&&!this.reporter&&e&&(this.reporter=new U(this.reportUrl,`${t}(${this.app})`,s,i),this.reporter._ws.addEventListener("open",(()=>{this.reportUrl=void 0,this.logCache.unshift({levelKey:"info",message:e}),this.reporter.sendBatch(this.logCache),setTimeout((()=>{this.reporter.destroy(),this.reporter=null}),r)}),{once:!0}))}_hookLogFunc(e){for(let t in H){const s=this[t];this[t]=i=>{e(t,i),s(i)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in H)H[e]<H[this.logLevel]?this[e]=u:this[e]=console[e]}get isDebugLevel(){return H[this.logLevel]<=2||this.onlineDebug}};let G;const V="function"==typeof queueMicrotask?queueMicrotask.bind(globalThis):e=>(G||(G=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),X=65536;function Y(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class J extends(n()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||J.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},J.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,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,this._wrtc=y(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void V((()=>this.destroy(e)))}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)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{e.debug=!0,this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var s;!t.address||t.address.endsWith(".local")?(s="Ignoring unsupported ICE candidate.",console.warn(s)):(e.debug=!0,this.destroy(e))}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,V((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,V((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=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.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=X),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=>{e.debug=!0,this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}get isBufferedAmountHigh(){return this._channel.bufferedAmount>X}write(e,t){if(this.destroyed)return t(new Error("cannot write after peer is destroyed"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(e)}this.isBufferedAmountHigh?this._cb=t:t(null)}else this._chunk=e,this._cb=t}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,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=Y(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=Y(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((s=>{const i=[];s.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((s=>{if(this.destroyed)return;const i=[];s.result().forEach((e=>{const s={};e.names().forEach((t=>{s[t]=e.stat(t)})),s.id=e.id,s.type=e.type,s.timestamp=e.timestamp,i.push(t(s))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,s)=>{if(this.destroyed)return;t&&(s=[]);const i={},r={},n={};let o=!1;s.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(r[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(n[e.id]=e)}));const a=e=>{o=!0;let t=r[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 s=i[e.remoteCandidateId];s&&(s.ip||s.address)?(this.remoteAddress=s.ip||s.address,this.remotePort=Number(s.port)):s&&s.ipAddress?(this.remoteAddress=s.ipAddress,this.remotePort=Number(s.portNumber)):"string"==typeof e.googRemoteAddress&&(s=e.googRemoteAddress.split(":"),this.remoteAddress=s[0],this.remotePort=Number(s[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(s.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(n[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),o||Object.keys(n).length&&!Object.keys(r).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;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.emit("connect");for(let e of this._pendingData)this.emit("data",e);this._pendingData=[]}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>X||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),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;t instanceof ArrayBuffer&&(t=o.h.from(t)),this._connected?this.emit("data",t):this._pendingData.length<10&&this._pendingData.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}J.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},J.channelConfig={};const Q=J;class K{constructor(e,t,s,i,r=0,n={}){this.sn=e,this.segId=t,this.data=s,this.fromPeerId=i,this.level=r,this.ext=n}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var Z=s(365),ee=s.n(Z);class te extends(n()){static get defaultPacketSize(){return d}static get VERSION(){return"8"}constructor(e,t,s,i,r,n={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=r,this.isInitiator=i,this.options=n,this.intermediator=n.intermediator||null,this.signalMsgs=[],this.signalRejectCache="",this.assignPeerId(t,s),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=d,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceiveData=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.currentLost=0,this._currentSharedPeers=[],this.notFoundPeers=new Set,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.incomingSignal=[],this.signalName="",this.webRTCConfig={};const{stuns:o}=this.options;if(o&&o.length>0){const e=[];o.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,s){this.remotePeerId=s,this.channelId=this.isInitiator?`${t}-${s}`:`${s}-${t}`,s&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(e.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=p(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:t,sentSignal:s,signalName:i}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${s} signalName ${i}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:s,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,s,i){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${i} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceiveData=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:s,seg_id:i}))))}_initPeerChannel(){const t=new Q({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let s=!0;(this.connected||this.notFatalClosed)&&(s=!1);let i=t.message;t.debug&&(i=`${i} raw: ${JSON.stringify(this.incomingSignal)}`),this.emit(e.DC_ERROR,s,i)})),t.on("signal",(t=>{t.candidate&&!t.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(t),this.sentSignal=!0,this.emit(e.DC_SIGNAL,t))}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.byPeerSignal?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,this.incomingSignal=[],clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:s}=this;if("string"==typeof t){let i;try{i=JSON.parse(t)}catch(e){return void s.error(e)}if(!i)return void s.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(i);let r,n=i.event;switch(r=n!==e.DC_PLAYLIST&&n!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${n}`,s.debug(`datachannel receive ${r} from ${this.remotePeerId}`),n){case e.DC_HAVE:if(this.emit(i.event,i),!i.sn)return;this.config.live||(i.sn<this.startSN&&(this.startSN=i.sn),i.sn>this.endSN&&(this.endSN=i.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=p(),this.pieceMsg=i,this._prepareForBinary(i.attachments,i.seg_id,i.sn,i.size),this.emit(i.event,i);break;case e.DC_PIECE_CANCEL:s.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(i.event,i),this.sendMsgPieceAbort("transfer canceled",i.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(i.event,i);break;case e.DC_REQUEST:this._handleRequestMsg(i);break;case e.DC_PIECE_ACK:this._handlePieceAck(i.seg_id,i.size,i.miss);break;case e.DC_STATS:this._handleStats(i);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(i);break;case e.DC_METADATA:this._handleMetadata(i);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,i)),this.downloading=!1,this.segId=void 0;break;case e.DC_CHOKE:s.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:s.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(i.event,i.fatal||!1);break;default:this.emit(i.event,i)}}else{if(!t)return void s.error("datachannel on data is undefined!");if(!this.downloading){const i=`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`;return s.warn(i),void this.emit(e.DC_ERROR,!1,i)}this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,s)=>{this.connected&&"disconnected"===t&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(e.DC_DISCONNECT))}))}sendJson(t){if(!this.remotePeerId)return!1;t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const s=JSON.stringify(t);return s.length>d?(this.logger.error("string to send is too large"),!1):this.send(s,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();t?("string"!=typeof t&&(this.bytesUploaded+=t.byteLength),this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,void this.emit(e.DC_ERROR,!1,t.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){const s=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,s)}return!1}sendMsgHave(t,s,i={}){const r=i.reverse||void 0;delete i.reverse,this.sendJson({event:r?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:s,...i})}sendPieceNotFound(t,s,i={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:s||void 0,sn:t,...i})}sendMsgStats(t,s,i={}){const r={event:e.DC_STATS,total_conns:t,shared_peers:s,...i};this.sendJson(r)}sendMsgPlaylist(t,s,i){const r=this.playlistMap.get(t);if(r&&r.seq>=i)return;const n={event:e.DC_PLAYLIST,url:t,data:s,seq:i};this.playlistMap.set(t,{data:s,seq:i}),this.sendJson(n)}sendMsgSignal(t,s,i){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:s,data:i})}sendMsgSignalReject(t,s,i,r=!1){const n=`${t}-${s}`;return this.signalRejectCache===n||(this.signalRejectCache=n,this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:s,reason:i,fatal:r}))}sendMetaData(t,s,i,r,n=!1,o=[]){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!ee().isMobile(),mobile_net:n,channel:this.channel,version:"2.18.0",sequential:s,peers:i,region:r,shared_peers:o})}sendPartialBuffer(e,t,s={}){if(!this.sendMsgPiece(e,s))return!1;for(let e=0;e<t.length;e++)this.send(t[e]);return!0}sendMsgPiece(e,t={}){if(!this.uploading)return this.logger.info("not uploading, cancel send buffer"),!1;this.datasToSend=[],this.bytesUploaded=0,e.ext||(e.ext={}),e.ext.from&&t.from&&t.from.length<2500&&(t.from=`${e.ext.from}-${t.from}`),t.incompletes&&e.ext.incompletes&&(t.incompletes+=e.ext.incompletes),t=Object.assign({},e.ext,t);const s={...e,ext:t};return this.sendJson(s)}sendBuffer(t,s,i,r={}){const n=r.reverse||void 0;if(delete r.reverse,!i)return void this.logger.error("sendBuffer payload is undefined!");let o=i.byteLength,a=0,h=0;o%this.packetSize==0?h=o/this.packetSize:(h=Math.floor(o/this.packetSize)+1,a=o%this.packetSize);let l={event:e.DC_PIECE,attachments:h,seg_id:s,sn:t,level:r.level,size:o,reverse:n};if(delete r.level,!this.sendMsgPiece(l,r))return;const c=function(e,t,s,i){let r=[];if(i){let n;for(let i=0;i<s-1;i++)n=e.slice(i*t,(i+1)*t),r.push(n);n=e.slice(e.byteLength-i,e.byteLength),r.push(n)}else{let i;for(let n=0;n<s;n++)i=e.slice(n*t,(n+1)*t),r.push(i)}return r}(i,this.packetSize,h,a);this._sendBufferArray(c,n),this.uploading=!1,this.timeSendPiece=performance.now()}get downloadNum(){return this.downloading?this.sendReqQueue.length+1:0}get byPeerSignal(){return!!this.intermediator&&!this.signalName}get useBackupSignal(){ret