From b25ff453a0b7dbdb7ed0eb4c53311af50cbb8dc3 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Tue, 10 Sep 2019 14:53:26 -0700 Subject: build --- webtorrent.min.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webtorrent.min.js b/webtorrent.min.js index 3b21499..6a8d8f9 100644 --- a/webtorrent.min.js +++ b/webtorrent.min.js @@ -1 +1 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).WebTorrent=e()}}(function(){var e=function(e){var t;return function(n){return t||e(t={exports:{},parent:n},t.exports),t.exports}},t=e(function(e,t){(function(e){var r=n({}),i=t,s={moov:["mvhd","meta","traks","mvex"],trak:["tkhd","tref","trgr","edts","meta","mdia","udta"],edts:["elst"],mdia:["mdhd","hdlr","elng","minf"],minf:["vmhd","smhd","hmhd","sthd","nmhd","dinf","stbl"],dinf:["dref"],stbl:["stsd","stts","ctts","cslg","stsc","stsz","stz2","stco","co64","stss","stsh","padb","stdp","sdtp","sbgps","sgpds","subss","saizs","saios"],mvex:["mehd","trexs","leva"],moof:["mfhd","meta","trafs"],traf:["tfhd","tfdt","trun","sbgps","sgpds","subss","saizs","saios","meta"]};i.encode=function(t,n,r){return i.encodingLength(t),r=r||0,n=n||e.alloc(t.length),i._encode(t,n,r)},i._encode=function(e,t,n){var o=e.type,a=e.length;a>4294967295&&(a=1),t.writeUInt32BE(a,n),t.write(e.type,n+4,4,"ascii");var h=n+8;if(1===a&&(Er.encode(e.length,t,h),h+=8),r.fullBoxes[o]&&(t.writeUInt32BE(e.flags||0,h),t.writeUInt8(e.version||0,h),h+=4),s[o])s[o].forEach(function(n){if(5===n.length){var r=e[n]||[];n=n.substr(0,4),r.forEach(function(e){i._encode(e,t,h),h+=i.encode.bytes})}else e[n]&&(i._encode(e[n],t,h),h+=i.encode.bytes)}),e.otherBoxes&&e.otherBoxes.forEach(function(e){i._encode(e,t,h),h+=i.encode.bytes});else if(r[o]){var c=r[o].encode;c(e,t,h),h+=c.bytes}else{if(!e.buffer)throw new Error("Either `type` must be set to a known type (not'"+o+"') or `buffer` must be set");e.buffer.copy(t,h),h+=e.buffer.length}return i.encode.bytes=h-n,t},i.readHeaders=function(e,t,n){if(t=t||0,(n=n||e.length)-t<8)return 8;var i,s,o=e.readUInt32BE(t),a=e.toString("ascii",t+4,t+8),h=t+8;if(1===o){if(n-t<16)return 16;o=Er.decode(e,h),h+=8}return r.fullBoxes[a]&&(i=e.readUInt8(h),s=16777215&e.readUInt32BE(h),h+=4),{length:o,headersLen:h-t,contentLen:o-(h-t),type:a,version:i,flags:s}},i.decode=function(e,t,n){t=t||0,n=n||e.length;var r=i.readHeaders(e,t,n);if(!r||r.length>n-t)throw new Error("Data too short");return i.decodeWithoutHeaders(r,e,t+r.headersLen,t+r.length)},i.decodeWithoutHeaders=function(t,n,o,a){o=o||0,a=a||n.length;var h=t.type,c={};if(s[h]){c.otherBoxes=[];for(var u=s[h],d=o;a-d>=8;){var l=i.decode(n,d,a);if(d+=l.length,u.indexOf(l.type)>=0)c[l.type]=l;else if(u.indexOf(l.type+"s")>=0){var f=l.type+"s";(c[f]=c[f]||[]).push(l)}else c.otherBoxes.push(l)}}else r[h]?c=(0,r[h].decode)(n,o,a):c.buffer=e.from(n.slice(o,a));return c.length=t.length,c.contentLen=t.contentLen,c.type=t.type,c.version=t.version,c.flags=t.flags,c},i.encodingLength=function(e){var t=e.type,n=8;if(r.fullBoxes[t]&&(n+=4),s[t])s[t].forEach(function(t){if(5===t.length){var r=e[t]||[];t=t.substr(0,4),r.forEach(function(e){e.type=t,n+=i.encodingLength(e)})}else if(e[t]){var s=e[t];s.type=t,n+=i.encodingLength(s)}}),e.otherBoxes&&e.otherBoxes.forEach(function(e){n+=i.encodingLength(e)});else if(r[t])n+=r[t].encodingLength(e);else{if(!e.buffer)throw new Error("Either `type` must be set to a known type (not'"+t+"') or `buffer` must be set");n+=e.buffer.length}return n>4294967295&&(n+=8),e.length=n,n}}).call(this,u({}).Buffer)}),n=e(function(e,n){(function(e){var r=t({}),i=20828448e5;function s(e,t,n){for(var r=t;r=8;){var h=r.decode(e,a,i);o.children.push(h),o[h.type]=h,a+=h.length}return o},n.VisualSampleEntry.encodingLength=function(e){var t=78;return(e.children||[]).forEach(function(e){t+=r.encodingLength(e)}),t},n.avcC={},n.avcC.encode=function(t,r,i){r=r?r.slice(i):e.alloc(t.buffer.length),t.buffer.copy(r),n.avcC.encode.bytes=t.buffer.length},n.avcC.decode=function(t,n,r){return{mimeCodec:(t=t.slice(n,r)).toString("hex",1,4),buffer:e.from(t)}},n.avcC.encodingLength=function(e){return e.buffer.length},n.mp4a=n.AudioSampleEntry={},n.AudioSampleEntry.encode=function(t,i,o){s(i=i?i.slice(o):e.alloc(n.AudioSampleEntry.encodingLength(t)),0,6),i.writeUInt16BE(t.dataReferenceIndex||0,6),s(i,8,16),i.writeUInt16BE(t.channelCount||2,16),i.writeUInt16BE(t.sampleSize||16,18),s(i,20,24),i.writeUInt32BE(t.sampleRate||0,24);var a=28;(t.children||[]).forEach(function(e){r.encode(e,i,a),a+=r.encode.bytes}),n.AudioSampleEntry.encode.bytes=a},n.AudioSampleEntry.decode=function(e,t,n){for(var i=n-t,s={dataReferenceIndex:(e=e.slice(t,n)).readUInt16BE(6),channelCount:e.readUInt16BE(16),sampleSize:e.readUInt16BE(18),sampleRate:e.readUInt32BE(24),children:[]},o=28;i-o>=8;){var a=r.decode(e,o,i);s.children.push(a),s[a.type]=a,o+=a.length}return s},n.AudioSampleEntry.encodingLength=function(e){var t=28;return(e.children||[]).forEach(function(e){t+=r.encodingLength(e)}),t},n.esds={},n.esds.encode=function(t,r,i){r=r?r.slice(i):e.alloc(t.buffer.length),t.buffer.copy(r,0),n.esds.encode.bytes=t.buffer.length},n.esds.decode=function(t,n,r){t=t.slice(n,r);var i=Sr.Descriptor.decode(t,0,t.length),s=("ESDescriptor"===i.tagName?i:{}).DecoderConfigDescriptor||{},o=s.oti||0,a=s.DecoderSpecificInfo,h=a?(248&a.buffer.readUInt8(0))>>3:0,c=null;return o&&(c=o.toString(16),h&&(c+="."+h)),{mimeCodec:c,buffer:e.from(t.slice(0))}},n.esds.encodingLength=function(e){return e.buffer.length},n.stsz={},n.stsz.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.stsz.encodingLength(t))).writeUInt32BE(0,0),r.writeUInt32BE(s.length,4);for(var o=0;o=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}e.exports=function(e,t){t=t||{};var a,h,c=typeof e;if("string"===c&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return 6048e5*o;case"days":case"day":case"d":return o*s;case"hours":case"hour":case"hrs":case"hr":case"h":return o*i;case"minutes":case"minute":case"mins":case"min":case"m":return o*r;case"seconds":case"second":case"secs":case"sec":case"s":return o*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===c&&isFinite(e))return t.long?(a=e,(h=Math.abs(a))>=s?o(a,h,s,"day"):h>=i?o(a,h,i,"hour"):h>=r?o(a,h,r,"minute"):h>=n?o(a,h,n,"second"):a+" ms"):function(e){var t=Math.abs(e);return t>=s?Math.round(e/s)+"d":t>=i?Math.round(e/i)+"h":t>=r?Math.round(e/r)+"m":t>=n?Math.round(e/n)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}),i=e(function(e,t){(function(t,n){"use strict";var r;e.exports=S,S.ReadableState=k,d.EventEmitter;var i,o=function(e,t){return e.listeners(t).length},c=u({}).Buffer,l=n.Uint8Array||function(){};i=te&&te.debuglog?te.debuglog("stream"):function(){};var f,p,g=Ie.getHighWaterMark,m=ke.codes,_=m.ERR_INVALID_ARG_TYPE,y=m.ERR_STREAM_PUSH_AFTER_EOF,b=m.ERR_METHOD_NOT_IMPLEMENTED,w=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,v=Ae.emitExperimentalWarning;Re(S,ee);var E=["error","close","destroy","pause","resume"];function k(e,t,n){r=r||h({}),e=e||{},"boolean"!=typeof n&&(n=t instanceof r),this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=g(this,e,"readableHighWaterMark",n),this.buffer=new he,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==e.emitClose,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(f||(f=a({}).StringDecoder),this.decoder=new f(e.encoding),this.encoding=e.encoding)}function S(e){if(r=r||h({}),!(this instanceof S))return new S(e);var t=this instanceof r;this._readableState=new k(e,this,t),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),ee.call(this)}function C(e,t,n,r,s){i("readableAddChunk",t);var o,a=e._readableState;if(null===t)a.reading=!1,function(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?A(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,R(e)))}}(e,a);else if(s||(o=function(e,t){var n,r;return r=t,c.isBuffer(r)||r instanceof l||"string"==typeof t||void 0===t||e.objectMode||(n=new _("chunk",["string","Buffer","Uint8Array"],t)),n}(a,t)),o)e.emit("error",o);else if(a.objectMode||t&&t.length>0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r)a.endEmitted?e.emit("error",new w):x(e,a,t,!0);else if(a.ended)e.emit("error",new y);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!n?(t=a.decoder.write(t),a.objectMode||0!==t.length?x(e,a,t,!1):L(e,a)):x(e,a,t,!1)}else r||(a.reading=!1,L(e,a));return!a.ended&&(a.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=T?e=T:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function A(e){var n=e._readableState;n.needReadable=!1,n.emittedReadable||(i("emitReadable",n.flowing),n.emittedReadable=!0,t.nextTick(R,e))}function R(e){var t=e._readableState;i("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||e.emit("readable"),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,P(e)}function L(e,n){n.readingMore||(n.readingMore=!0,t.nextTick(B,e,n))}function B(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function O(e){i("readable nexttick read 0"),e.read(0)}function M(e,t){i("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),P(e),t.flowing&&!t.reading&&e.read(0)}function P(e){var t=e._readableState;for(i("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function j(e){var n=e._readableState;i("endReadable",n.endEmitted),n.endEmitted||(n.ended=!0,t.nextTick(H,n,e))}function H(e,t){i("endReadableNT",e.endEmitted,e.length),e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function D(e,t){for(var n=0,r=e.length;n=t.highWaterMark:t.length>0)||t.ended))return i("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?j(this):A(this),null;if(0===(e=I(e,t))&&t.ended)return 0===t.length&&j(this),null;var r,s=t.needReadable;return i("need readable",s),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=!0,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&j(this)),null!==r&&this.emit("data",r),r},S.prototype._read=function(e){this.emit("error",new b("_read()"))},S.prototype.pipe=function(e,n){var r=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,i("pipe count=%d opts=%j",s.pipesCount,n);var a=n&&!1===n.end||e===t.stdout||e===t.stderr?g:h;function h(){i("onend"),e.end()}s.endEmitted?t.nextTick(a):r.once("end",a),e.on("unpipe",function t(n,o){i("onunpipe"),n===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,i("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",c),e.removeListener("error",l),e.removeListener("unpipe",t),r.removeListener("end",h),r.removeListener("end",g),r.removeListener("data",d),u=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||c())});var c=function(e){return function(){var t=e._readableState;i("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,P(e))}}(r);e.on("drain",c);var u=!1;function d(t){i("ondata");var n=e.write(t);i("dest.write",n),!1===n&&((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==D(s.pipes,e))&&!u&&(i("false write response, pause",s.awaitDrain),s.awaitDrain++),r.pause())}function l(t){i("onerror",t),g(),e.removeListener("error",l),0===o(e,"error")&&e.emit("error",t)}function f(){e.removeListener("finish",p),g()}function p(){i("onfinish"),e.removeListener("close",f),g()}function g(){i("unpipe"),r.unpipe(e)}return r.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener("error",n);e._events&&e._events.error?Array.isArray(e._events.error)?e._events.error.unshift(n):e._events.error=[n,e._events.error]:e.on("error",n)}(e,0,l),e.once("close",f),e.once("finish",p),e.emit("pipe",r),s.flowing||(i("pipe resume"),r.resume()),e},S.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,i("on readable",s.length,s.reading),s.length?A(this):s.reading||t.nextTick(O,this))),r},S.prototype.addListener=S.prototype.on,S.prototype.removeListener=function(e,n){var r=ee.prototype.removeListener.call(this,e,n);return"readable"===e&&t.nextTick(U,this),r},S.prototype.removeAllListeners=function(e){var n=ee.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||t.nextTick(U,this),n},S.prototype.resume=function(){var e=this._readableState;return e.flowing||(i("resume"),e.flowing=!e.readableListening,function(e,n){n.resumeScheduled||(n.resumeScheduled=!0,t.nextTick(M,e,n))}(this,e)),e.paused=!1,this},S.prototype.pause=function(){return i("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(i("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},S.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var s in e.on("end",function(){if(i("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(s){i("wrapped data"),n.decoder&&(s=n.decoder.write(s)),n.objectMode&&null==s||(n.objectMode||s&&s.length)&&(t.push(s)||(r=!0,e.pause()))}),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var o=0;o>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function o(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"\ufffd";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"\ufffd";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"\ufffd"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function a(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function h(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function c(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function u(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function l(e){return e&&e.length?this.write(e):""}t.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0?(i>0&&(e.lastNeed=i-1),i):--r=0?(i>0&&(e.lastNeed=i-2),i):--r=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}}),h=e(function(e,t){(function(t){"use strict";var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=u;var r=i({}),s=c({});Re(u,r);for(var o=n(s.prototype),a=0;a-1))throw new w(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(k.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(k.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),k.prototype._write=function(e,t,n){n(new p("_write()"))},k.prototype._writev=null,k.prototype.end=function(e,n,r){var i=this._writableState;return"function"==typeof e?(r=e,e=null,n=null):"function"==typeof n&&(r=n,n=null),null!=e&&this.write(e,n),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,n,r){n.ending=!0,A(e,n),r&&(n.finished?t.nextTick(r):e.once("finish",r)),n.ended=!0,e.writable=!1}(this,i,r),this},Object.defineProperty(k.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(k.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),k.prototype.destroy=Ee.destroy,k.prototype._undestroy=Ee.undestroy,k.prototype._destroy=function(e,t){t(e)}}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})}),u=e(function(e,t){(function(e){"use strict";var n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=e,t.SlowBuffer=function(t){return+t!=t&&(t=0),e.alloc(+t)},t.INSPECT_MAX_BYTES=50;var r=2147483647;function i(t){if(t>r)throw new RangeError('The value "'+t+'" is invalid for option "size"');var n=new Uint8Array(t);return Object.setPrototypeOf(n,e.prototype),n}function e(e,t,n){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 s(e,t,n)}function s(t,n,r){if("string"==typeof t)return function(t,n){if("string"==typeof n&&""!==n||(n="utf8"),!e.isEncoding(n))throw new TypeError("Unknown encoding: "+n);var r=0|u(t,n),s=i(r),o=s.write(t,n);return o!==r&&(s=s.slice(0,o)),s}(t,n);if(ArrayBuffer.isView(t))return h(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(j(t,ArrayBuffer)||t&&j(t.buffer,ArrayBuffer))return function(t,n,r){if(n<0||t.byteLength=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function u(t,n){if(e.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||j(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var s=!1;;)switch(n){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return O(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return P(t).length;default:if(s)return i?-1:O(t).length;n=(""+n).toLowerCase(),s=!0}}function d(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function l(t,n,r,i,s){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=s?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(s)return-1;r=t.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof n&&(n=e.from(n,i)),e.isBuffer(n))return 0===n.length?-1:f(t,n,r,i,s);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,n,r):Uint8Array.prototype.lastIndexOf.call(t,n,r):f(t,[n],r,i,s);throw new TypeError("val must be string, number or Buffer")}function f(e,t,n,r,i){var s,o=1,a=e.length,h=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,h/=2,n/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var u=-1;for(s=n;sa&&(n=a-h),s=n;s>=0;s--){for(var d=!0,l=0;li&&(r=i):r=i;var s=t.length;r>s/2&&(r=s/2);for(var o=0;o>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function w(e,t,n){return 0===t&&n===e.length?x.fromByteArray(e):x.fromByteArray(e.slice(t,n))}function v(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+d<=n)switch(d){case 1:c<128&&(u=c);break;case 2:128==(192&(s=e[i+1]))&&(h=(31&c)<<6|63&s)>127&&(u=h);break;case 3:s=e[i+1],o=e[i+2],128==(192&s)&&128==(192&o)&&(h=(15&c)<<12|(63&s)<<6|63&o)>2047&&(h<55296||h>57343)&&(u=h);break;case 4:s=e[i+1],o=e[i+2],a=e[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(h=(15&c)<<18|(63&s)<<12|(63&o)<<6|63&a)>65535&&h<1114112&&(u=h)}null===u?(u=65533,d=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),i+=d}return function(e){var t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);for(var n="",r=0;rthis.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,n);case"utf8":case"utf-8":return v(this,t,n);case"ascii":return k(this,t,n);case"latin1":case"binary":return S(this,t,n);case"base64":return w(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}.apply(this,arguments)},e.prototype.toLocaleString=e.prototype.toString,e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===e.compare(this,t)},e.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),""},n&&(e.prototype[n]=e.prototype.inspect),e.prototype.compare=function(t,n,r,i,s){if(j(t,Uint8Array)&&(t=e.from(t,t.offset,t.byteLength)),!e.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===n&&(n=0),void 0===r&&(r=t?t.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),n<0||r>t.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&n>=r)return 0;if(i>=s)return-1;if(n>=r)return 1;if(this===t)return 0;for(var o=(s>>>=0)-(i>>>=0),a=(r>>>=0)-(n>>>=0),h=Math.min(o,a),c=this.slice(i,s),u=t.slice(n,r),d=0;d>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return p(this,e,t,n);case"utf8":case"utf-8":return g(this,e,t,n);case"ascii":return m(this,e,t,n);case"latin1":case"binary":return _(this,e,t,n);case"base64":return y(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var E=4096;function k(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;ii)&&(n=i);for(var s="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function A(t,n,r,i,s,o){if(!e.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>s||nt.length)throw new RangeError("Index out of range")}function R(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,r,i){return t=+t,n>>>=0,i||R(e,0,n,4),M.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,i){return t=+t,n>>>=0,i||R(e,0,n,8),M.write(e,t,n,r,52,8),n+8}e.prototype.slice=function(t,n){var r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(n=void 0===n?r:~~n)<0?(n+=r)<0&&(n=0):n>r&&(n=r),n>>=0,t>>>=0,n||I(e,t,this.length);for(var r=this[e],i=1,s=0;++s>>=0,t>>>=0,n||I(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},e.prototype.readUInt8=function(e,t){return e>>>=0,t||I(e,1,this.length),this[e]},e.prototype.readUInt16LE=function(e,t){return e>>>=0,t||I(e,2,this.length),this[e]|this[e+1]<<8},e.prototype.readUInt16BE=function(e,t){return e>>>=0,t||I(e,2,this.length),this[e]<<8|this[e+1]},e.prototype.readUInt32LE=function(e,t){return e>>>=0,t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},e.prototype.readUInt32BE=function(e,t){return e>>>=0,t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},e.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||I(e,t,this.length);for(var r=this[e],i=1,s=0;++s=(i*=128)&&(r-=Math.pow(2,8*t)),r},e.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||I(e,t,this.length);for(var r=t,i=1,s=this[e+--r];r>0&&(i*=256);)s+=this[e+--r]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},e.prototype.readInt8=function(e,t){return e>>>=0,t||I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},e.prototype.readInt16LE=function(e,t){e>>>=0,t||I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt16BE=function(e,t){e>>>=0,t||I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt32LE=function(e,t){return e>>>=0,t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},e.prototype.readInt32BE=function(e,t){return e>>>=0,t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},e.prototype.readFloatLE=function(e,t){return e>>>=0,t||I(e,4,this.length),M.read(this,e,!0,23,4)},e.prototype.readFloatBE=function(e,t){return e>>>=0,t||I(e,4,this.length),M.read(this,e,!1,23,4)},e.prototype.readDoubleLE=function(e,t){return e>>>=0,t||I(e,8,this.length),M.read(this,e,!0,52,8)},e.prototype.readDoubleBE=function(e,t){return e>>>=0,t||I(e,8,this.length),M.read(this,e,!1,52,8)},e.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||A(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,r||A(this,e,t,n,Math.pow(2,8*n)-1,0);var i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+n},e.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,1,255,0),this[t]=255&e,t+1},e.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},e.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},e.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},e.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},e.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);A(this,e,t,n,i-1,-i)}var s=0,o=1,a=0;for(this[t]=255&e;++s>0)-a&255;return t+n},e.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);A(this,e,t,n,i-1,-i)}var s=n-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o>>0)-a&255;return t+n},e.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},e.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},e.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},e.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},e.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},e.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},e.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},e.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},e.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},e.prototype.copy=function(t,n,r,i){if(!e.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),n>=t.length&&(n=t.length),n||(n=0),i>0&&i=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),t.length-n=0;--o)t[o+n]=this[o+r];else Uint8Array.prototype.set.call(t,this.subarray(r,i),n);return s},e.prototype.fill=function(t,n,r,i){if("string"==typeof t){if("string"==typeof n?(i=n,n=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!e.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var s=t.charCodeAt(0);("utf8"===i&&s<128||"latin1"===i)&&(t=s)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(n<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=n;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function P(e){return x.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(U,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function N(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function H(e){return e!=e}}).call(this,u({}).Buffer)}),d={},l=Object.create||function(e){var t=function(){};return t.prototype=e,new t},f=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return n},p=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function g(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=l(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}d=g,g.EventEmitter=g,g.prototype._events=void 0,g.prototype._maxListeners=void 0;var m,_=10;try{var y={};Object.defineProperty&&Object.defineProperty(y,"x",{value:0}),m=0===y.x}catch(li){m=!1}function b(e){return void 0===e._maxListeners?g.defaultMaxListeners:e._maxListeners}function w(e,t,n,r){var i,s,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]):(s=e._events=l(null),e._eventsCount=0),o){if("function"==typeof o?o=s[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),!o.warned&&(i=b(e))&&i>0&&o.length>i){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else o=s[t]=n,++e._eventsCount;return e}function v(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t1&&(t=arguments[1]),t instanceof Error)throw t;var h=new Error('Unhandled "error" event. ('+t+")");throw h.context=t,h}if(!(n=o[e]))return!1;var c="function"==typeof n;switch(r=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var r=e.length,i=C(e,r),s=0;s=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():function(e,t){for(var n=i,r=n+1,s=e.length;r=0;r--)this.removeListener(e,t[r]);return this},g.prototype.listeners=function(e){return k(this,e,!0)},g.prototype.rawListeners=function(e){return k(this,e,!1)},g.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):S.call(e,t)},g.prototype.listenerCount=S,g.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};for(var x={toByteArray:function(e){var t,n,r=U(e),i=r[0],s=r[1],o=new A(function(e,t,n){return 3*(t+n)/4-n}(0,i,s)),a=0,h=s>0?i-4:i;for(n=0;n>16&255,o[a++]=t>>8&255,o[a++]=255&t;return 2===s&&(t=I[e.charCodeAt(n)]<<2|I[e.charCodeAt(n+1)]>>4,o[a++]=255&t),1===s&&(t=I[e.charCodeAt(n)]<<10|I[e.charCodeAt(n+1)]<<4|I[e.charCodeAt(n+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t),o},fromByteArray:function(e){for(var t,n=e.length,r=n%3,i=[],s=0,o=n-r;so?o:s+16383));return 1===r?(t=e[n-1],i.push(T[t>>2]+T[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(T[t>>10]+T[t>>4&63]+T[t<<2&63]+"=")),i.join("")}},T=[],I=[],A="undefined"!=typeof Uint8Array?Uint8Array:Array,R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",L=0,B=R.length;L0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function O(e,t,n){for(var r,i,s=[],o=t;o>18&63]+T[i>>12&63]+T[i>>6&63]+T[63&i]);return s.join("")}I["-".charCodeAt(0)]=62,I["_".charCodeAt(0)]=63;var M={read:function(e,t,n,r,i){var s,o,a=8*i-r-1,h=(1<>1,u=-7,d=n?i-1:0,l=n?-1:1,f=e[t+d];for(d+=l,s=f&(1<<-u)-1,f>>=-u,u+=a;u>0;s=256*s+e[t+d],d+=l,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=r;u>0;o=256*o+e[t+d],d+=l,u-=8);if(0===s)s=1-c;else{if(s===h)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),s-=c}return(f?-1:1)*o*Math.pow(2,s-r)},write:function(e,t,n,r,i,s){var o,a,h,c=8*s-i-1,u=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(h=Math.pow(2,-o))<1&&(o--,h*=2),(t+=o+d>=1?l/h:l*Math.pow(2,1-d))*h>=2&&(o++,h/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*h-1)*Math.pow(2,i),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=255&a,f+=p,a/=256,i-=8);for(o=o<0;e[n+f]=255&o,f+=p,o/=256,c-=8);e[n+f-p]|=128*g}},P={};(function(e){P=function(t,n){var r=[];t.on("data",function(e){r.push(e)}),t.once("end",function(){n&&n(null,e.concat(r)),n=null}),t.once("error",function(e){n&&n(e),n=null})}}).call(this,u({}).Buffer);var N={},j=u({}),H=j.Buffer;function D(e,t){for(var n in e)t[n]=e[n]}function q(e,t,n){return H(e,t,n)}H.from&&H.alloc&&H.allocUnsafe&&H.allocUnsafeSlow?N=j:(D(j,N),N.Buffer=q),q.prototype=Object.create(H.prototype),D(H,q),q.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return H(e,t,n)},q.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=H(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},q.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return H(e)},q.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return j.SlowBuffer(e)};var F,W=N.Buffer;function z(e,t,n){var r=[],i=null;return z._encode(r,e),i=W.concat(r),z.bytes=i.length,W.isBuffer(t)?(i.copy(t,n),t):i}z.bytes=-1,z._floatConversionDetected=!1,z.getType=function(e){return W.isBuffer(e)?"buffer":Array.isArray(e)?"array":ArrayBuffer.isView(e)?"arraybufferview":e instanceof Number?"number":e instanceof Boolean?"boolean":e instanceof ArrayBuffer?"arraybuffer":typeof e},z._encode=function(e,t){if(null!=t)switch(z.getType(t)){case"buffer":z.buffer(e,t);break;case"object":z.dict(e,t);break;case"array":z.list(e,t);break;case"string":z.string(e,t);break;case"number":case"boolean":z.number(e,t);break;case"arraybufferview":z.buffer(e,W.from(t.buffer,t.byteOffset,t.byteLength));break;case"arraybuffer":z.buffer(e,W.from(t))}};var $=W.from("e"),V=W.from("d"),G=W.from("l");z.buffer=function(e,t){e.push(W.from(t.length+":"),t)},z.string=function(e,t){e.push(W.from(W.byteLength(t)+":"+t))},z.number=function(e,t){var n=2147483648*(t/2147483648<<0)+(t%2147483648<<0);e.push(W.from("i"+n+"e")),n===t||z._floatConversionDetected||(z._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+t+'":','Bencoding only defines support for integers, value was converted to "'+n+'"'),console.trace())},z.dict=function(e,t){e.push(V);for(var n,r=0,i=Object.keys(t).sort(),s=i.length;r=48)r=10*r+(o-48);else if(s!==t||43!==o){if(s!==t||45!==o){if(46===o)break;throw new Error("not a number: buffer["+s+"] = "+o)}i=-1}}return r*i}function X(e,t,n,r){return null==e||0===e.length?null:("number"!=typeof t&&null==r&&(r=t,t=void 0),"number"!=typeof n&&null==r&&(r=n,n=void 0),X.position=0,X.encoding=r||null,X.data=Y.isBuffer(e)?e.slice(t,n):Y.from(e),X.bytes=X.data.length,X.next())}X.bytes=0,X.position=0,X.data=null,X.encoding=null,X.next=function(){switch(X.data[X.position]){case 100:return X.dictionary();case 108:return X.list();case 105:return X.integer();default:return X.buffer()}},X.find=function(e){for(var t=X.position,n=X.data.length,r=X.data;t0?this.tail.next=t:this.head=t,this.tail=t,++this.length},t.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},t.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},t.clear=function(){this.head=this.tail=null,this.length=0},t.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},t.concat=function(e){if(0===this.length)return se.alloc(0);for(var t,n,r,i=se.allocUnsafe(e>>>0),s=this.head,o=0;s;)t=s.data,n=i,r=o,se.prototype.copy.call(t,n,r),o+=s.data.length,s=s.next;return i},t.consume=function(e,t){var n;return ei.length?i.length:e;if(s===i.length?r+=i:r+=i.slice(0,e),0==(e-=s)){s===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r},t._getBuffer=function(e){var t=se.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0==(e-=s)){s===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t},t[ae]=function(e,t){return oe(this,function(e){for(var t=1;t1)for(var n=1;n2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}Ce("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError),Ce("ERR_INVALID_ARG_TYPE",function(e,t,n){var r,i,s,o;if("string"==typeof t&&("not ","not "===t.substr(0,"not ".length))?(r="must not be",t=t.replace(/^not /,"")):r="must be",s=e,(void 0===o||o>s.length)&&(o=s.length)," argument"===s.substring(o-" argument".length,o))i="The ".concat(e," ").concat(r," ").concat(xe(t,"type"));else{var a=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+".".length>e.length)&&-1!==e.indexOf(".",n)}(e)?"property":"argument";i='The "'.concat(e,'" ').concat(a," ").concat(r," ").concat(xe(t,"type"))}return i+". Received type ".concat(typeof n)},TypeError),Ce("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Ce("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),Ce("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Ce("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),Ce("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Ce("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Ce("ERR_STREAM_WRITE_AFTER_END","write after end"),Ce("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Ce("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),Ce("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),ke.codes=Se;var Te=ke.codes.ERR_INVALID_OPT_VALUE,Ie={getHighWaterMark:function(e,t,n,r){var i=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(t,r,n);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Te(r?n:"highWaterMark",i);return Math.floor(i)}return e.objectMode?16:16384}},Ae={};(function(e){"use strict";var t=new Set;Ae.emitExperimentalWarning=e.emitWarning?function(n){if(!t.has(n)){var r=n+" is an experimental feature. This feature could change at any time";t.add(n),e.emitWarning(r,"ExperimentalWarning")}}:function(){}}).call(this,ce);var Re={};Re="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}};var Le={};(function(e){function t(t){try{if(!e.localStorage)return!1}catch(r){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}Le=function(e,n){if(t("noDeprecation"))return e;var r=!1;return function(){if(!r){if(t("throwDeprecation"))throw new Error(n);t("traceDeprecation")?console.trace(n):console.warn(n),r=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Be=De,Ue=ke.codes,Oe=Ue.ERR_METHOD_NOT_IMPLEMENTED,Me=Ue.ERR_MULTIPLE_CALLBACK,Pe=Ue.ERR_TRANSFORM_ALREADY_TRANSFORMING,Ne=Ue.ERR_TRANSFORM_WITH_LENGTH_0,je=h({});function He(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new Me);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length0,function(e){r||(r=e),e&&s.forEach(Je),a||(s.forEach(Je),i(r))})});return t.reduce(Xe)};var Qe={};(function(e){const{Transform:t}=Ze;Qe=class extends t{constructor(e,t={}){super(t),"object"==typeof e&&(e=(t=e).size),this.size=e||512;const{nopad:n,zeroPadding:r=!0}=t;this._zeroPadding=!n&&!!r,this._buffered=[],this._bufferedBytes=0}_transform(t,n,r){for(this._bufferedBytes+=t.length,this._buffered.push(t);this._bufferedBytes>=this.size;){const t=e.concat(this._buffered);this._bufferedBytes-=this.size,this.push(t.slice(0,this.size)),this._buffered=[t.slice(this.size,t.length)]}r()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const t=e.alloc(this.size-this._bufferedBytes);this._buffered.push(t),this.push(e.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(e.concat(this._buffered)),this._buffered=null);this.push(null)}}}).call(this,u({}).Buffer);var et={};(function(e){function t(e,t){for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function n(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r=1;--s)if(47===(t=e.charCodeAt(s))){if(!i){r=s;break}}else i=!1;return-1===r?n?"/":".":n&&1===r?"/":e.slice(0,r)},et.basename=function(e,t){var n=function(e){"string"!=typeof e&&(e+="");var t,n=0,r=-1,i=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!i){n=t+1;break}}else-1===r&&(i=!1,r=t+1);return-1===r?"":e.slice(n,r)}(e);return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},et.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,n=0,r=-1,i=!0,s=0,o=e.length-1;o>=0;--o){var a=e.charCodeAt(o);if(47!==a)-1===r&&(i=!1,r=o+1),46===a?-1===t?t=o:1!==s&&(s=1):-1!==t&&(s=-1);else if(!i){n=o+1;break}}return-1===t||-1===r||0===s||1===s&&t===r-1&&t===n+1?"":e.slice(t,r)};var r="b"==="ab".substr(-1)?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return t<0&&(t=e.length+t),e.substr(t,n)}}).call(this,ce);var tt;tt=it,it.strict=st,it.loose=ot;var nt=Object.prototype.toString,rt={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0};function it(e){return st(e)||ot(e)}function st(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function ot(e){return rt[nt.call(e)]}var at={};(function(e){var t=tt.strict;at=function(n){if(t(n)){var r=e.from(n.buffer);return n.byteLength!==n.buffer.byteLength&&(r=r.slice(n.byteOffset,n.byteOffset+n.byteLength)),r}return e.from(n)}}).call(this,u({}).Buffer);const{Readable:ht}=Ze;var ct=class extends ht{constructor(e,t={}){super(t),this._offset=0,this._ready=!1,this._file=e,this._size=e.size,this._chunkSize=t.chunkSize||Math.max(this._size/1e3,204800);const n=new FileReader;n.onload=(()=>{this.push(at(n.result))}),n.onerror=(()=>{this.emit("error",n.error)}),this.reader=n,this._generateHeaderBlocks(e,t,(e,t)=>{if(e)return this.emit("error",e);Array.isArray(t)&&t.forEach(e=>this.push(e)),this._ready=!0,this.emit("_ready")})}_generateHeaderBlocks(e,t,n){n(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const e=this._offset;let t=this._offset+this._chunkSize;if(t>this._size&&(t=this._size),e===this._size)return this.destroy(),void this.push(null);this.reader.readAsArrayBuffer(this._file.slice(e,t)),this._offset=t}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}},ut={},dt={};function lt(e){return ut.existsSync(e)&&ut.statSync(e).isFile()}(dt=function(e,t){if(!t)return lt(e);ut.stat(e,function(e,n){return e?t(e):t(null,n.isFile())})}).sync=lt;var ft={};ft.regex=new RegExp(["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"].join("|")),ft.is=(e=>ft.regex.test(e)),ft.not=(e=>!ft.is(e));var pt={};function gt(e){return _t(e,{objectMode:!0,highWaterMark:16})}function mt(e){return _t(e)}function _t(e,t){if(!e||"function"==typeof e||e._readableState)return e;var n=new Ze.Readable(t).wrap(e);return e.destroy&&(n.destroy=e.destroy.bind(e)),n}class yt extends Ze.Readable{constructor(e,t){super(t),this.destroyed=!1,this._drained=!1,this._forwarding=!1,this._current=null,this._toStreams2=t&&t.objectMode?gt:mt,"function"==typeof e?this._queue=e:(this._queue=e.map(this._toStreams2),this._queue.forEach(e=>{"function"!=typeof e&&this._attachErrorListener(e)})),this._next()}_read(){this._drained=!0,this._forward()}_forward(){if(!this._forwarding&&this._drained&&this._current){var e;for(this._forwarding=!0;null!==(e=this._current.read())&&this._drained;)this._drained=this.push(e);this._forwarding=!1}}destroy(e){this.destroyed||(this.destroyed=!0,this._current&&this._current.destroy&&this._current.destroy(),"function"!=typeof this._queue&&this._queue.forEach(e=>{e.destroy&&e.destroy()}),e&&this.emit("error",e),this.emit("close"))}_next(){if(this._current=null,"function"==typeof this._queue)this._queue((e,t)=>{if(e)return this.destroy(e);t=this._toStreams2(t),this._attachErrorListener(t),this._gotNextStream(t)});else{var e=this._queue.shift();"function"==typeof e&&(e=this._toStreams2(e()),this._attachErrorListener(e)),this._gotNextStream(e)}}_gotNextStream(e){if(!e)return this.push(null),void this.destroy();this._current=e,this._forward();const t=()=>{this._forward()},n=()=>{e._readableState.ended||this.destroy()},r=()=>{this._current=null,e.removeListener("readable",t),e.removeListener("end",r),e.removeListener("close",n),this._next()};e.on("readable",t),e.once("end",r),e.once("close",n)}_attachErrorListener(e){if(!e)return;const t=n=>{e.removeListener("error",t),this.destroy(n)};e.once("error",t)}}yt.obj=(e=>new yt(e,{objectMode:!0,highWaterMark:16})),pt=yt;var bt=function e(t,n){if(t&&n)return e(t)(n);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach(function(e){r[e]=t[e]}),r;function r(){for(var e=new Array(arguments.length),n=0;n0;e+=1);return e},c=function(e,t){var n=new Int32Array(e,t+320,5),r=new Int32Array(5),i=new DataView(r.buffer);return i.setInt32(0,n[0],!1),i.setInt32(4,n[1],!1),i.setInt32(8,n[2],!1),i.setInt32(12,n[3],!1),i.setInt32(16,n[4],!1),r},u=function(){function e(t){if(function(t,n){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this),(t=t||65536)%64>0)throw new Error("Chunk size must be a multiple of 128 bit");this._offset=0,this._maxChunkLen=t,this._padMaxChunkLen=h(t),this._heap=new ArrayBuffer(o(this._padMaxChunkLen+320+20)),this._h32=new Int32Array(this._heap),this._h8=new Int8Array(this._heap),this._core=new r({Int32Array:Int32Array},{},this._heap)}return e.prototype._initState=function(e,t){this._offset=0;var n=new Int32Array(e,t+320,5);n[0]=1732584193,n[1]=-271733879,n[2]=-1732584194,n[3]=271733878,n[4]=-1009589776},e.prototype._padChunk=function(e,t){var n=h(e),r=new Int32Array(this._heap,0,n>>2);return function(e,t){var n=new Uint8Array(e.buffer),r=t%4,i=t-r;switch(r){case 0:n[i+3]=0;case 1:n[i+2]=0;case 2:n[i+1]=0;case 3:n[i+0]=0}for(var s=1+(t>>2);s>2]|=128<<24-(t%4<<3),e[14+(2+(t>>2)&-16)]=n/(1<<29)|0,e[15+(2+(t>>2)&-16)]=n<<3}(r,e,t),n},e.prototype._write=function(e,t,n,r){a(e,this._h8,this._h32,t,n,r||0)},e.prototype._coreCall=function(e,t,n,r,i){var s=n;this._write(e,t,n),i&&(s=this._padChunk(n,r)),this._core.hash(s,this._padMaxChunkLen)},e.prototype.rawDigest=function(e){var t=e.byteLength||e.length||e.size||0;this._initState(this._heap,this._padMaxChunkLen);var n=0,r=this._maxChunkLen;for(n=0;t>n+r;n+=r)this._coreCall(e,n,r,t,!1);return this._coreCall(e,n,t-n,t,!0),c(this._heap,this._padMaxChunkLen)},e.prototype.digest=function(e){return s(this.rawDigest(e).buffer)},e.prototype.digestFromString=function(e){return this.digest(e)},e.prototype.digestFromBuffer=function(e){return this.digest(e)},e.prototype.digestFromArrayBuffer=function(e){return this.digest(e)},e.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},e.prototype.append=function(e){var t=0,n=e.byteLength||e.length||e.size||0,r=this._offset%this._maxChunkLen,i=void 0;for(this._offset+=n;t0},!1)}e.exports=function(e,t){t=t||{};var i={main:n.m},s=t.all?{main:Object.keys(i)}:function(e,t){for(var n={main:[t]},r={main:[]},i={main:{}};h(n);)for(var s=Object.keys(n),o=0;o>2]|0;a=r[t+324>>2]|0;c=r[t+328>>2]|0;d=r[t+332>>2]|0;f=r[t+336>>2]|0;for(n=0;(n|0)<(e|0);n=n+64|0){o=s;h=a;u=c;l=d;p=f;for(i=0;(i|0)<64;i=i+4|0){m=r[n+i>>2]|0;g=((s<<5|s>>>27)+(a&c|~a&d)|0)+((m+f|0)+1518500249|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[e+i>>2]=m}for(i=e+64|0;(i|0)<(e+80|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a&c|~a&d)|0)+((m+f|0)+1518500249|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+80|0;(i|0)<(e+160|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a^c^d)|0)+((m+f|0)+1859775393|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+160|0;(i|0)<(e+240|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a&c|a&d|c&d)|0)+((m+f|0)-1894007588|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+240|0;(i|0)<(e+320|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a^c^d)|0)+((m+f|0)-899497514|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}s=s+o|0;a=a+h|0;c=c+u|0;d=d+l|0;f=f+p|0}r[t+320>>2]=s;r[t+324>>2]=a;r[t+328>>2]=c;r[t+332>>2]=d;r[t+336>>2]=f}return{hash:i}}},function(e,t){var n=this,r=void 0;"undefined"!=typeof self&&void 0!==self.FileReaderSync&&(r=new self.FileReaderSync);var i=function(e,t,n,r,i,s){var o=void 0,a=s%4,h=(i+a)%4,c=i-h;switch(a){case 0:t[s]=e[r+3];case 1:t[s+1-(a<<1)|0]=e[r+2];case 2:t[s+2-(a<<1)|0]=e[r+1];case 3:t[s+3-(a<<1)|0]=e[r]}if(!(i>2|0]=e[r+o]<<24|e[r+o+1]<<16|e[r+o+2]<<8|e[r+o+3];switch(h){case 3:t[s+c+1|0]=e[r+c+2];case 2:t[s+c+2|0]=e[r+c+1];case 1:t[s+c+3|0]=e[r+c]}}};e.exports=function(e,t,s,o,a,h){if("string"==typeof e)return function(e,t,n,r,i,s){var o=void 0,a=s%4,h=(i+a)%4,c=i-h;switch(a){case 0:t[s]=e.charCodeAt(r+3);case 1:t[s+1-(a<<1)|0]=e.charCodeAt(r+2);case 2:t[s+2-(a<<1)|0]=e.charCodeAt(r+1);case 3:t[s+3-(a<<1)|0]=e.charCodeAt(r)}if(!(i>2]=e.charCodeAt(r+o)<<24|e.charCodeAt(r+o+1)<<16|e.charCodeAt(r+o+2)<<8|e.charCodeAt(r+o+3);switch(h){case 3:t[s+c+1|0]=e.charCodeAt(r+c+2);case 2:t[s+c+2|0]=e.charCodeAt(r+c+1);case 1:t[s+c+3|0]=e.charCodeAt(r+c)}}}(e,t,s,o,a,h);if(e instanceof Array)return i(e,t,s,o,a,h);if(n&&n.Buffer&&n.Buffer.isBuffer(e))return i(e,t,s,o,a,h);if(e instanceof ArrayBuffer)return i(new Uint8Array(e),t,s,o,a,h);if(e.buffer instanceof ArrayBuffer)return i(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),t,s,o,a,h);if(e instanceof Blob)return function(e,t,n,i,s,o){var a=void 0,h=o%4,c=(s+h)%4,u=s-c,d=new Uint8Array(r.readAsArrayBuffer(e.slice(i,i+s)));switch(h){case 0:t[o]=d[3];case 1:t[o+1-(h<<1)|0]=d[2];case 2:t[o+2-(h<<1)|0]=d[1];case 3:t[o+3-(h<<1)|0]=d[0]}if(!(s>2|0]=d[a]<<24|d[a+1]<<16|d[a+2]<<8|d[a+3];switch(c){case 3:t[o+u+1|0]=d[u+2];case 2:t[o+u+2|0]=d[u+1];case 1:t[o+u+3|0]=d[u]}}}(e,t,s,o,a,h);throw new Error("Unsupported data type.")}},function(e,t,n){var r=n(0),i=n(1).toHex,s=function(){function e(){!function(t,n){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this),this._rusha=new r,this._rusha.resetState()}return e.prototype.update=function(e){return this._rusha.append(e),this},e.prototype.digest=function(e){var t=this._rusha.rawEnd().buffer;if(!e)return t;if("hex"===e)return i(t);throw new Error("unsupported digest encoding")},e}();e.exports=function(){return new s}}])},"object"==typeof At.exports?At.exports=Ct():"object"==typeof At.exports?At.exports.Rusha=Ct():St.Rusha=Ct(),At=At.exports;var Rt={},Lt=new At,Bt="undefined"!=typeof window?window:self,Ut=Bt.crypto||Bt.msCrypto||{},Ot=Ut.subtle||Ut.webkitSubtle;function Mt(e){return Lt.digest(e)}try{Ot.digest({name:"sha-1"},new Uint8Array).catch(function(){Ot=!1})}catch(li){Ot=!1}(Rt=function(e,t){Ot?("string"==typeof e&&(e=function(e){for(var t=e.length,n=new Uint8Array(t),r=0;r>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")}(new Uint8Array(e)))},function(){t(Mt(e))})):"undefined"!=typeof window?function(e,t){xt||(xt=At.createWorker(),Tt=1,It={},xt.onmessage=function(e){var t=e.data.id,n=It[t];delete It[t],null!=e.data.error?n(new Error("Rusha worker error: "+e.data.error)):n(null,e.data.hash)}),It[Tt]=t,xt.postMessage({id:Tt,data:e}),Tt+=1}(e,function(n,r){t(n?Mt(e):r)}):queueMicrotask(()=>t(Mt(e)))}).sync=Mt;var Pt={};(function(e,t,n){function r(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(r(t)):e.concat(t),[])}function i(t,i,a){if("undefined"!=typeof FileList&&t instanceof FileList&&(t=Array.from(t)),Array.isArray(t)||(t=[t]),0===t.length)throw new Error("invalid input type");t.forEach(e=>{if(null==e)throw new Error(`invalid input type: ${e}`)}),1!==(t=t.map(e=>h(e)&&"string"==typeof e.path&&"function"==typeof ut.stat?e.path:e)).length||"string"==typeof t[0]||t[0].name||(t[0].name=i.name);let u=null;t.forEach((e,n)=>{if("string"==typeof e)return;let r=e.fullPath||e.name;r||(r=`Unknown File ${n+1}`,e.unknownName=!0),e.path=r.split("/"),e.path[0]||e.path.shift(),e.path.length<2?u=null:0===n&&t.length>1?u=e.path[0]:e.path[0]!==u&&(u=null)}),t=t.filter(e=>{if("string"==typeof e)return!0;const t=e.path[e.path.length-1];return o(t)&&ft.not(t)}),u&&t.forEach(e=>{const t=(n.isBuffer(e)||c(e))&&!e.path;"string"==typeof e||t||e.path.shift()}),!i.name&&u&&(i.name=u),i.name||t.some(e=>"string"==typeof e?(i.name=et.basename(e),!0):e.unknownName?void 0:(i.name=e.path[e.path.length-1],!0)),i.name||(i.name=`Unnamed Torrent ${Date.now()}`);const d=t.reduce((e,t)=>e+Number("string"==typeof t),0);let l=1===t.length;if(1===t.length&&"string"==typeof t[0]){if("function"!=typeof ut.stat)throw new Error("filesystem paths do not work in the browser");dt(t[0],(e,t)=>{if(e)return a(e);l=t,f()})}else e.nextTick(()=>{f()});function f(){kt(t.map(e=>t=>{const i={};if(h(e))i.getStream=function(e){return()=>new ct(e)}(e),i.length=e.size;else if(n.isBuffer(e))i.getStream=function(e){return()=>{const t=new Ze.PassThrough;return t.end(e),t}}(e),i.length=e.length;else{if(!c(e)){if("string"==typeof e){if("function"!=typeof ut.stat)throw new Error("filesystem paths do not work in the browser");return void function(e,t,n){!function e(t,n,r){ut.stat(t,(i,s)=>{if(i)return r(i);s.isDirectory()?ut.readdir(t,(i,s)=>{if(i)return r(i);kt(s.filter(o).filter(ft.not).map(r=>i=>{e(et.join(t,r),n,i)}),r)}):s.isFile()&&n(t,r)})}(e,s,(i,s)=>{if(i)return n(i);s=Array.isArray(s)?r(s):[s],e=et.normalize(e),t&&(e=e.slice(0,e.lastIndexOf(et.sep)+1)),e[e.length-1]!==et.sep&&(e+=et.sep),s.forEach(t=>{t.getStream=function(e){return()=>ut.createReadStream(e)}(t.path),t.path=t.path.replace(e,"").split(et.sep)}),n(null,s)})}(e,d>1||l,t)}throw new Error("invalid input type")}i.getStream=function(e,t){return()=>{const n=new Ze.Transform;return n._transform=function(e,n,r){t.length+=e.length,this.push(e),r()},e.pipe(n),n}}(e,i),i.length=0}i.path=e.path,t(null,i)}),(e,t)=>{if(e)return a(e);t=r(t),a(null,t,l)})}}function s(e,t){t=wt(t),ut.stat(e,(n,r)=>{if(n)return t(n);const i={length:r.size,path:e};t(null,i)})}function o(e){return"."!==e[0]}function a(e,t){return e+t.length}function h(e){return"undefined"!=typeof Blob&&e instanceof Blob}function c(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(Pt=function(e,r,s){"function"==typeof r&&([r,s]=[s,r]),i(e,r=r?Object.assign({},r):{},(e,i,o)=>{if(e)return s(e);r.singleFileTorrent=o,function(e,r,i){let s=r.announceList;s||("string"==typeof r.announce?s=[[r.announce]]:Array.isArray(r.announce)&&(s=r.announce.map(e=>[e]))),s||(s=[]),t.WEBTORRENT_ANNOUNCE&&("string"==typeof t.WEBTORRENT_ANNOUNCE?s.push([[t.WEBTORRENT_ANNOUNCE]]):Array.isArray(t.WEBTORRENT_ANNOUNCE)&&(s=s.concat(t.WEBTORRENT_ANNOUNCE.map(e=>[e])))),void 0===r.announce&&void 0===r.announceList&&(s=s.concat(Pt.announceList)),"string"==typeof r.urlList&&(r.urlList=[r.urlList]);const o={info:{name:r.name},"creation date":Math.ceil((Number(r.creationDate)||Date.now())/1e3),encoding:"UTF-8"};0!==s.length&&(o.announce=s[0][0],o["announce-list"]=s),void 0!==r.comment&&(o.comment=r.comment),void 0!==r.createdBy&&(o["created by"]=r.createdBy),void 0!==r.private&&(o.info.private=Number(r.private)),void 0!==r.info&&Object.assign(o.info,r.info),void 0!==r.sslCert&&(o.info["ssl-cert"]=r.sslCert),void 0!==r.urlList&&(o["url-list"]=r.urlList);const h=r.pieceLength||(c=e.reduce(a,0),Math.max(16384,1<e.getStream);let a=0,h=0,c=!1;const u=new pt(o),d=new Qe(t,{zeroPadding:!1});function l(e){s+=e.length;const t=h;Rt(e,e=>{i[t]=e,a-=1,m()}),a+=1,h+=1}function f(){c=!0,m()}function p(e){g(),r(e)}function g(){u.removeListener("error",p),d.removeListener("data",l),d.removeListener("end",f),d.removeListener("error",p)}function m(){c&&0===a&&(g(),r(null,n.from(i.join(""),"hex"),s))}u.on("error",p),u.pipe(d).on("data",l).on("end",f).on("error",p)}(e,h,(t,n,s)=>{if(t)return i(t);o.info.pieces=n,e.forEach(e=>{delete e.getStream}),r.singleFileTorrent?o.info.length=s:o.info.files=e,i(null,Z.encode(o))})}(i,r,s)})}).parseInput=function(e,t,n){"function"==typeof t&&([t,n]=[n,t]),i(e,t=t?Object.assign({},t):{},n)},Pt.announceList=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"],["wss://tracker.fastcast.nz"]]}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u({}).Buffer);var Nt={};(function(e){Nt.log=function(...e){return"object"==typeof console&&console.log&&console.log(...e)},Nt.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Nt.humanize(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let n=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(r=n))}),e.splice(r,0,t)},Nt.save=function(e){try{e?Nt.storage.setItem("debug",e):Nt.storage.removeItem("debug")}catch(t){}},Nt.load=function(){let t;try{t=Nt.storage.getItem("debug")}catch(n){}return!t&&void 0!==e&&"env"in e&&(t=e.env.DEBUG),t},Nt.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+)/))},Nt.storage=function(){try{return localStorage}catch(e){}}(),Nt.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"],Nt=function(e){function t(e){let t=0;for(let n=0;n{if("%%"===r)return r;a++;const s=n.formatters[i];if("function"==typeof s){const n=e[a];r=s.call(t,n),e.splice(a,1),a--}return r}),n.formatArgs.call(t,e),(t.log||n.log).apply(t,e)}return o.namespace=e,o.enabled=n.enabled(e),o.useColors=n.useColors(),o.color=t(e),o.destroy=i,o.extend=s,"function"==typeof n.init&&n.init(o),n.instances.push(o),o}function i(){const e=n.instances.indexOf(this);return-1!==e&&(n.instances.splice(e,1),!0)}function s(e,t){const r=n(this.namespace+(void 0===t?":":t)+e);return r.log=this.log,r}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return n.debug=n,n.default=n,n.coerce=function(e){return e instanceof Error?e.stack||e.message:e},n.disable=function(){const e=[...n.names.map(o),...n.skips.map(o).map(e=>"-"+e)].join(",");return n.enable(""),e},n.enable=function(e){let t;n.save(e),n.names=[],n.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(t=0;t{n[t]=e[t]}),n.instances=[],n.names=[],n.skips=[],n.formatters={},n.selectColor=t,n.enable(n.load()),n}(Nt);const{formatters:t}=Nt;t.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}).call(this,ce);var jt={};(function(e){jt=function(t,n){if("undefined"==typeof Blob||!(t instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof n)throw new Error("second argument must be a function");var r=new FileReader;r.addEventListener("loadend",function t(i){r.removeEventListener("loadend",t,!1),i.error?n(i.error):n(null,e.from(r.result))},!1),r.readAsArrayBuffer(t)}}).call(this,u({}).Buffer);var Ht={};(function(e){var t;function n(){if(void 0!==t)return t;if(e.XMLHttpRequest){t=new e.XMLHttpRequest;try{t.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(n){t=null}}else t=null;return t}function r(e){var t=n();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(r){}return!1}function i(e){return"function"==typeof e}Ht.fetch=i(e.fetch)&&i(e.ReadableStream),Ht.writableStream=i(e.WritableStream),Ht.abortController=i(e.AbortController),Ht.arraybuffer=Ht.fetch||r("arraybuffer"),Ht.msstream=!Ht.fetch&&r("ms-stream"),Ht.mozchunkedarraybuffer=!Ht.fetch&&r("moz-chunked-arraybuffer"),Ht.overrideMimeType=Ht.fetch||!!n()&&i(n().overrideMimeType),t=null}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Dt={};(function(e,t,n){var r=Dt.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},i=Dt.IncomingMessage=function(r,i,s,o){var a=this;if(Ze.Readable.call(a),a._mode=s,a.headers={},a.rawHeaders=[],a.trailers={},a.rawTrailers=[],a.on("end",function(){e.nextTick(function(){a.emit("close")})}),"fetch"===s){if(a._fetchResponse=i,a.url=i.url,a.statusCode=i.status,a.statusMessage=i.statusText,i.headers.forEach(function(e,t){a.headers[t.toLowerCase()]=e,a.rawHeaders.push(t,e)}),Ht.writableStream){var h=new WritableStream({write:function(e){return new Promise(function(t,r){a._destroyed?r():a.push(n.from(e))?t():a._resumeFetch=t})},close:function(){t.clearTimeout(o),a._destroyed||a.push(null)},abort:function(e){a._destroyed||a.emit("error",e)}});try{return void i.body.pipeTo(h).catch(function(e){t.clearTimeout(o),a._destroyed||a.emit("error",e)})}catch(l){}}var c=i.body.getReader();!function e(){c.read().then(function(r){if(!a._destroyed){if(r.done)return t.clearTimeout(o),void a.push(null);a.push(n.from(r.value)),e()}}).catch(function(e){t.clearTimeout(o),a._destroyed||a.emit("error",e)})}()}else if(a._xhr=r,a._pos=0,a.url=r.responseURL,a.statusCode=r.status,a.statusMessage=r.statusText,r.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var n=t[1].toLowerCase();"set-cookie"===n?(void 0===a.headers[n]&&(a.headers[n]=[]),a.headers[n].push(t[2])):void 0!==a.headers[n]?a.headers[n]+=", "+t[2]:a.headers[n]=t[2],a.rawHeaders.push(t[1],t[2])}}),a._charset="x-user-defined",!Ht.overrideMimeType){var u=a.rawHeaders["mime-type"];if(u){var d=u.match(/;\s*charset=([^;])(;|$)/);d&&(a._charset=d[1].toLowerCase())}a._charset||(a._charset="utf-8")}};Re(i,Ze.Readable),i.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},i.prototype._onXHRProgress=function(){var e=this,i=e._xhr,s=null;switch(e._mode){case"text":if((s=i.responseText).length>e._pos){var o=s.substr(e._pos);if("x-user-defined"===e._charset){for(var a=n.alloc(o.length),h=0;he._pos&&(e.push(n.from(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(s)}e._xhr.readyState===r.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u({}).Buffer);var qt={};(function(e,t,n){var r=Dt.IncomingMessage,i=Dt.readyStates,s=qt=function(e){var t,r=this;Ze.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+n.from(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var i=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!Ht.abortController)i=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!Ht.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return Ht.fetch&&t?"fetch":Ht.mozchunkedarraybuffer?"moz-chunked-arraybuffer":Ht.msstream?"ms-stream":Ht.arraybuffer&&e?"arraybuffer":"text"}(t,i),r._fetchTimer=null,r.on("finish",function(){r._onFinish()})};Re(s,Ze.Writable),s.prototype.setHeader=function(e,t){var n=e.toLowerCase();-1===o.indexOf(n)&&(this._headers[n]={name:e,value:t})},s.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},s.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},s.prototype._onFinish=function(){var n=this;if(!n._destroyed){var r=n._opts,s=n._headers,o=null;"GET"!==r.method&&"HEAD"!==r.method&&(o=new Blob(n._body,{type:(s["content-type"]||{}).value||""}));var a=[];if(Object.keys(s).forEach(function(e){var t=s[e].name,n=s[e].value;Array.isArray(n)?n.forEach(function(e){a.push([t,e])}):a.push([t,n])}),"fetch"===n._mode){var h=null;if(Ht.abortController){var c=new AbortController;h=c.signal,n._fetchAbortController=c,"requestTimeout"in r&&0!==r.requestTimeout&&(n._fetchTimer=t.setTimeout(function(){n.emit("requestTimeout"),n._fetchAbortController&&n._fetchAbortController.abort()},r.requestTimeout))}t.fetch(n._opts.url,{method:n._opts.method,headers:a,body:o||void 0,mode:"cors",credentials:r.withCredentials?"include":"same-origin",signal:h}).then(function(e){n._fetchResponse=e,n._connect()},function(e){t.clearTimeout(n._fetchTimer),n._destroyed||n.emit("error",e)})}else{var u=n._xhr=new t.XMLHttpRequest;try{u.open(n._opts.method,n._opts.url,!0)}catch(li){return void e.nextTick(function(){n.emit("error",li)})}"responseType"in u&&(u.responseType=n._mode),"withCredentials"in u&&(u.withCredentials=!!r.withCredentials),"text"===n._mode&&"overrideMimeType"in u&&u.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in r&&(u.timeout=r.requestTimeout,u.ontimeout=function(){n.emit("requestTimeout")}),a.forEach(function(e){u.setRequestHeader(e[0],e[1])}),n._response=null,u.onreadystatechange=function(){switch(u.readyState){case i.LOADING:case i.DONE:n._onXHRProgress()}},"moz-chunked-arraybuffer"===n._mode&&(u.onprogress=function(){n._onXHRProgress()}),u.onerror=function(){n._destroyed||n.emit("error",new Error("XHR error"))};try{u.send(o)}catch(li){return void e.nextTick(function(){n.emit("error",li)})}}}},s.prototype._onXHRProgress=function(){(function(e){try{var t=e.status;return null!==t&&0!==t}catch(n){return!1}})(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},s.prototype._connect=function(){var e=this;e._destroyed||(e._response=new r(e._xhr,e._fetchResponse,e._mode,e._fetchTimer),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},s.prototype._write=function(e,t,n){this._body.push(e),n()},s.prototype.abort=s.prototype.destroy=function(){this._destroyed=!0,t.clearTimeout(this._fetchTimer),this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},s.prototype.end=function(e,t,n){"function"==typeof e&&(n=e,e=void 0),Ze.Writable.prototype.end.call(this,e,t,n)},s.prototype.flushHeaders=function(){},s.prototype.setTimeout=function(){},s.prototype.setNoDelay=function(){},s.prototype.setSocketKeepAlive=function(){};var o=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u({}).Buffer);var Ft=Object.prototype.hasOwnProperty,Wt={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},zt={exports:{}};(function(e){!function(t){var n="object"==typeof zt.exports&&zt.exports&&!zt.exports.nodeType&&zt.exports,r=zt&&!zt.nodeType&&zt,i="object"==typeof e&&e;i.global!==i&&i.window!==i&&i.self!==i||(t=i);var s,o,a=2147483647,h=36,c=1,u=26,d=38,l=700,f=72,p=128,g="-",m=/^xn--/,_=/[^\x20-\x7E]/,y=/[\x2E\u3002\uFF0E\uFF61]/g,b={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},w=h-c,v=Math.floor,E=String.fromCharCode;function k(e){throw new RangeError(b[e])}function S(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function C(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+S((e=e.replace(y,".")).split("."),t).join(".")}function x(e){for(var t,n,r=[],i=0,s=e.length;i=55296&&t<=56319&&i65535&&(t+=E((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+E(e)}).join("")}function I(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function A(e,t,n){var r=0;for(e=n?v(e/l):e>>1,e+=v(e/t);e>w*u>>1;r+=h)e=v(e/w);return v(r+(w+1)*e/(e+d))}function R(e){var t,n,r,i,s,o,d,l,m,_,y,b=[],w=e.length,E=0,S=p,C=f;for((n=e.lastIndexOf(g))<0&&(n=0),r=0;r=128&&k("not-basic"),b.push(e.charCodeAt(r));for(i=n>0?n+1:0;i=w&&k("invalid-input"),((l=(y=e.charCodeAt(i++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:h)>=h||l>v((a-E)/o))&&k("overflow"),E+=l*o,!(l<(m=d<=C?c:d>=C+u?u:d-C));d+=h)o>v(a/(_=h-m))&&k("overflow"),o*=_;C=A(E-s,t=b.length+1,0==s),v(E/t)>a-S&&k("overflow"),S+=v(E/t),E%=t,b.splice(E++,0,S)}return T(b)}function L(e){var t,n,r,i,s,o,d,l,m,_,y,b,w,S,C,T=[];for(b=(e=x(e)).length,t=p,n=0,s=f,o=0;o=t&&yv((a-n)/(w=r+1))&&k("overflow"),n+=(d-t)*w,t=d,o=0;oa&&k("overflow"),y==t){for(l=n,m=h;!(l<(_=m<=s?c:m>=s+u?u:m-s));m+=h)C=l-_,S=h-_,T.push(E(I(_+C%S,0))),l=v(C/S);T.push(E(I(l,0))),s=A(n,w,r==i),n=0,++r}++n,++t}return T.join("")}if(s={version:"1.4.1",ucs2:{decode:x,encode:T},decode:R,encode:L,toASCII:function(e){return C(e,function(e){return _.test(e)?"xn--"+L(e):e})},toUnicode:function(e){return C(e,function(e){return m.test(e)?R(e.slice(4).toLowerCase()):e})}},n&&r)if(zt.exports==n)r.exports=s;else for(o in s)s.hasOwnProperty(o)&&(n[o]=s[o]);else t.punycode=s}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),zt=zt.exports;var $t={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}};function Vt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Gt=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},Kt=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},Yt=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function Jt(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r0&&a>o&&(a=o);for(var h=0;h=0?(c=f.substr(0,p),u=f.substr(p+1)):(c=f,u=""),d=decodeURIComponent(c),l=decodeURIComponent(u),Vt(i,d)?Gt(i[d])?i[d].push(l):i[d]=[i[d],l]:i[d]=l}return i},stringify:function(e,t,n,r){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?Jt(Xt(e),function(r){var i=encodeURIComponent(Kt(r))+n;return Yt(e[r])?Jt(e[r],function(e){return i+encodeURIComponent(Kt(e))}).join(t):i+encodeURIComponent(Kt(e[r]))}).join(t):r?encodeURIComponent(Kt(r))+n+encodeURIComponent(Kt(e)):""}},Qt={};function en(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}Qt.parse=pn;var tn=/^([a-z0-9.+-]+:)/i,nn=/:[0-9]*$/,rn=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,sn=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),on=["'"].concat(sn),an=["%","/","?",";","#"].concat(on),hn=["/","?","#"],cn=/^[+a-z0-9A-Z_-]{0,63}$/,un=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,dn={javascript:!0,"javascript:":!0},ln={javascript:!0,"javascript:":!0},fn={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function pn(e,t,n){if(e&&$t.isObject(e)&&e instanceof en)return e;var r=new en;return r.parse(e,t,n),r}en.prototype.parse=function(e,t,n){if(!$t.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var r=e.indexOf("?"),i=-1!==r&&r127?w+="x":w+=b[v];if(!w.match(cn)){var k=_.slice(0,p),S=_.slice(p+1),C=b.match(un);C&&(k.push(C[1]),S.unshift(C[2])),S.length&&(o="/"+S.join(".")+o),this.hostname=k.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),m||(this.hostname=zt.toASCII(this.hostname));var x=this.port?":"+this.port:"",T=this.hostname||"";this.host=T+x,this.href+=this.host,m&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==o[0]&&(o="/"+o))}if(!dn[c])for(p=0,y=on.length;p0)&&n.host.split("@"))&&(n.auth=C.shift(),n.host=n.hostname=C.shift())),n.search=e.search,n.query=e.query,$t.isNull(n.pathname)&&$t.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!b.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var v=b.slice(-1)[0],E=(n.host||e.host||b.length>1)&&("."===v||".."===v)||""===v,k=0,S=b.length;S>=0;S--)"."===(v=b[S])?b.splice(S,1):".."===v?(b.splice(S,1),k++):k&&(b.splice(S,1),k--);if(!_&&!y)for(;k--;k)b.unshift("..");!_||""===b[0]||b[0]&&"/"===b[0].charAt(0)||b.unshift(""),E&&"/"!==b.join("/").substr(-1)&&b.push("");var C,x=""===b[0]||b[0]&&"/"===b[0].charAt(0);return w&&(n.hostname=n.host=x?"":b.length?b.shift():"",(C=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=C.shift(),n.host=n.hostname=C.shift())),(_=_||n.host&&b.length)&&!x&&b.unshift(""),b.length?n.pathname=b.join("/"):(n.pathname=null,n.path=null),$t.isNull(n.pathname)&&$t.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},en.prototype.parseHost=function(){var e=this.host,t=nn.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var gn={};(function(e){var t=gn;t.request=function(t,n){t="string"==typeof t?Qt.parse(t):function(){for(var e={},t=0;tnull!==e&&"object"==typeof e&&"function"==typeof e.pipe;function n(r,i){if(r=Object.assign({maxRedirects:10},"string"==typeof r?{url:r}:r),i=wt(i),r.url){const{hostname:e,port:t,protocol:n,auth:i,path:s}=Qt.parse(r.url);delete r.url,e||t||n||i?Object.assign(r,{hostname:e,port:t,protocol:n,auth:i,path:s}):r.path=s}const s={"accept-encoding":"gzip, deflate"};let o;r.headers&&Object.keys(r.headers).forEach(e=>s[e.toLowerCase()]=r.headers[e]),r.headers=s,r.body?o=r.json&&!t(r.body)?JSON.stringify(r.body):r.body:r.form&&(o="string"==typeof r.form?r.form:Zt.stringify(r.form),r.headers["content-type"]="application/x-www-form-urlencoded"),o&&(r.method||(r.method="POST"),t(o)||(r.headers["content-length"]=e.byteLength(o)),r.json&&!r.form&&(r.headers["content-type"]="application/json")),delete r.body,delete r.form,r.json&&(r.headers.accept="application/json"),r.method&&(r.method=r.method.toUpperCase());const a=("https:"===r.protocol?mn:gn).request(r,e=>{if(e.statusCode>=300&&e.statusCode<400&&e.headers.location)return r.url=e.headers.location,delete r.headers.host,e.resume(),"POST"===r.method&&[301,302].includes(e.statusCode)&&(r.method="GET",delete r.headers["content-length"],delete r.headers["content-type"]),0==r.maxRedirects--?i(new Error("too many redirects")):n(r,i);const t="function"==typeof te&&"HEAD"!==r.method;i(null,t?te(e):e)});return a.on("timeout",()=>{a.abort(),i(new Error("Request timed out"))}),a.on("error",i),t(o)?o.on("error",i).pipe(a):a.end(o),a}n.concat=((e,t)=>n(e,(n,r)=>{if(n)return t(n);P(r,(n,i)=>{if(n)return t(n);if(e.json)try{i=JSON.parse(i.toString())}catch(n){return t(n,r,i)}t(null,r,i)})})),["get","post","put","patch","head","delete"].forEach(e=>{n[e]=((t,r)=>("string"==typeof t&&(t={url:t}),n(Object.assign({method:e.toUpperCase()},t),r)))})}).call(this,u({}).Buffer);var vn={};(function(e){"use strict";var t=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];vn.decode=function(n){var r,i=0,s=0,o=0;e.isBuffer(n)||(n=new e(n));for(var a=new e(Math.ceil(5*n.length/8)),h=0;h>>(i=(i+5)%8),a[o]=r,o++,r=255&s<<8-i)}return a.slice(0,o)}}).call(this,u({}).Buffer);var En={};vn.encode,En.decode=vn.decode;var kn=function(e,t,n){return 0===e.length?e:t?(n||e.sort(t),function(e,t){for(var n=1,r=e.length,i=e[0],s=e[0],o=1;o=0?r.split("&"):[]).forEach(e=>{const t=e.split("=");if(2!==t.length)return;const r=t[0];let i=t[1];if("dn"===r&&(i=decodeURIComponent(i).replace(/\+/g," ")),"tr"!==r&&"xs"!==r&&"as"!==r&&"ws"!==r||(i=decodeURIComponent(i)),"kt"===r&&(i=decodeURIComponent(i).split("+")),"ix"===r&&(i=Number(i)),n[r])if(Array.isArray(n[r]))n[r].push(i);else{const e=n[r];n[r]=[e,i]}else n[r]=i}),n.xt&&(Array.isArray(n.xt)?n.xt:[n.xt]).forEach(t=>{if(i=t.match(/^urn:btih:(.{40})/))n.infoHash=i[1].toLowerCase();else if(i=t.match(/^urn:btih:(.{32})/)){const t=En.decode(i[1]);n.infoHash=e.from(t,"binary").toString("hex")}}),n.infoHash&&(n.infoHashBuffer=e.from(n.infoHash,"hex")),n.dn&&(n.name=n.dn),n.kt&&(n.keywords=n.kt),"string"==typeof n.tr?n.announce=[n.tr]:Array.isArray(n.tr)?n.announce=n.tr:n.announce=[],n.urlList=[],("string"==typeof n.as||Array.isArray(n.as))&&(n.urlList=n.urlList.concat(n.as)),("string"==typeof n.ws||Array.isArray(n.ws))&&(n.urlList=n.urlList.concat(n.ws)),kn(n.announce),kn(n.urlList),n}(Sn=t).decode=t,Sn.encode=function(e){(e=Object.assign({},e)).infoHashBuffer&&(e.xt=`urn:btih:${e.infoHashBuffer.toString("hex")}`),e.infoHash&&(e.xt=`urn:btih:${e.infoHash}`),e.name&&(e.dn=e.name),e.keywords&&(e.kt=e.keywords),e.announce&&(e.tr=e.announce),e.urlList&&(e.ws=e.urlList,delete e.as);let t="magnet:?";return Object.keys(e).filter(e=>2===e.length).forEach((n,r)=>{(Array.isArray(e[n])?e[n]:[e[n]]).forEach((e,i)=>{!(r>0||i>0)||"kt"===n&&0!==i||(t+="&"),"dn"===n&&(e=encodeURIComponent(e).replace(/%20/g,"+")),"tr"!==n&&"xs"!==n&&"as"!==n&&"ws"!==n||(e=encodeURIComponent(e)),"kt"===n&&(e=encodeURIComponent(e)),t+="kt"===n&&i>0?`+${e}`:`${n}=${e}`})}),t}}).call(this,u({}).Buffer);var Cn={};(function(e,t){function n(e){if("string"==typeof e&&/^(stream-)?magnet:/.test(e))return Sn(e);if("string"==typeof e&&(/^[a-f0-9]{40}$/i.test(e)||/^[a-z2-7]{32}$/i.test(e)))return Sn(`magnet:?xt=urn:btih:${e}`);if(t.isBuffer(e)&&20===e.length)return Sn(`magnet:?xt=urn:btih:${e.toString("hex")}`);if(t.isBuffer(e))return function(e){t.isBuffer(e)&&(e=Z.decode(e)),i(e.info,"info"),i(e.info["name.utf-8"]||e.info.name,"info.name"),i(e.info["piece length"],"info['piece length']"),i(e.info.pieces,"info.pieces"),e.info.files?e.info.files.forEach(e=>{i("number"==typeof e.length,"info.files[0].length"),i(e["path.utf-8"]||e.path,"info.files[0].path")}):i("number"==typeof e.info.length,"info.length");const n={info:e.info,infoBuffer:Z.encode(e.info),name:(e.info["name.utf-8"]||e.info.name).toString(),announce:[]};n.infoHash=Rt.sync(n.infoBuffer),n.infoHashBuffer=t.from(n.infoHash,"hex"),void 0!==e.info.private&&(n.private=!!e.info.private),e["creation date"]&&(n.created=new Date(1e3*e["creation date"])),e["created by"]&&(n.createdBy=e["created by"].toString()),t.isBuffer(e.comment)&&(n.comment=e.comment.toString()),Array.isArray(e["announce-list"])&&e["announce-list"].length>0?e["announce-list"].forEach(e=>{e.forEach(e=>{n.announce.push(e.toString())})}):e.announce&&n.announce.push(e.announce.toString()),t.isBuffer(e["url-list"])&&(e["url-list"]=e["url-list"].length>0?[e["url-list"]]:[]),n.urlList=(e["url-list"]||[]).map(e=>e.toString()),kn(n.announce),kn(n.urlList);const s=e.info.files||[e.info];n.files=s.map((e,t)=>{const i=[].concat(n.name,e["path.utf-8"]||e.path||[]).map(e=>e.toString());return{path:et.join.apply(null,[et.sep].concat(i)).slice(1),name:i[i.length-1],length:e.length,offset:s.slice(0,t).reduce(r,0)}}),n.length=s.reduce(r,0);const o=n.files[n.files.length-1];return n.pieceLength=e.info["piece length"],n.lastPieceLength=(o.offset+o.length)%n.pieceLength||n.pieceLength,n.pieces=function(e){const t=[];for(let n=0;n{r(null,i)}):"undefined"!=typeof Blob&&t instanceof Blob?jt(t,(e,t)=>{if(e)return r(new Error(`Error converting Blob: ${e.message}`));s(t)}):"function"==typeof wn&&/^https?:/.test(t)?wn.concat({url:t,timeout:3e4,headers:{"user-agent":"WebTorrent (https://webtorrent.io)"}},(e,t,n)=>{if(e)return r(new Error(`Error downloading torrent: ${e.message}`));s(n)}):"function"==typeof ut.readFile&&"string"==typeof t?ut.readFile(t,(e,t)=>{if(e)return r(new Error("Invalid torrent identifier"));s(t)}):e.nextTick(()=>{r(new Error("Invalid torrent identifier"))})},Cn.toMagnetURI=Sn.encode,Cn.toTorrentFile=function(e){const n={info:e.info};return n["announce-list"]=(e.announce||[]).map(e=>(n.announce||(n.announce=e),[e=t.from(e,"utf8")])),n["url-list"]=e.urlList||[],void 0!==e.private&&(n.private=Number(e.private)),e.created&&(n["creation date"]=e.created.getTime()/1e3|0),e.createdBy&&(n["created by"]=e.createdBy),e.comment&&(n.comment=e.comment),Z.encode(n)},t.alloc(0)}).call(this,ce,u({}).Buffer);var xn=function(){if("undefined"==typeof window)return null;var e={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null},Tn={};(function(e,t){"use strict";var n=N.Buffer,r=t.crypto||t.msCrypto;Tn=r&&r.getRandomValues?function(t,i){if(t>4294967295)throw new RangeError("requested too many random bytes");var s=n.allocUnsafe(t);if(t>0)if(t>65536)for(var o=0;ot.destroy(li),0)}t._isReactNativeWebrtc="number"==typeof t._pc._peerConnectionId,t._pc.oniceconnectionstatechange=function(){t._onIceStateChange()},t._pc.onicegatheringstatechange=function(){t._onIceStateChange()},t._pc.onsignalingstatechange=function(){t._onSignalingStateChange()},t._pc.onicecandidate=function(e){t._onIceCandidate(e)},t.initiator?t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)}):t._pc.ondatachannel=function(e){t._setupData(e)},t.streams&&t.streams.forEach(function(e){t.addStream(e)}),t._pc.ontrack=function(e){t._onTrack(e)},t.initiator&&t._needsNegotiation(),t._onFinishBound=function(){t._onFinish()},t.once("finish",t._onFinishBound)}function i(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}function s(e,t){var n=new Error(e);return n.code=t,n}Re(r,Ze.Duplex),r.WEBRTC_SUPPORT=!!xn(),r.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478?transport=udp"}],sdpSemantics:"unified-plan"},r.channelConfig={},Object.defineProperty(r.prototype,"bufferSize",{get:function(){return this._channel&&this._channel.bufferedAmount||0}}),Object.defineProperty(r.prototype,"connected",{get:function(){return this._connected&&"open"===this._channel.readyState}}),r.prototype.address=function(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}},r.prototype.signal=function(e){var t=this;if(t.destroyed)throw s("cannot signal after peer is destroyed","ERR_SIGNALING");if("string"==typeof e)try{e=JSON.parse(e)}catch(li){e={}}t._debug("signal()"),e.renegotiate&&t.initiator&&(t._debug("got request to renegotiate"),t._needsNegotiation()),e.transceiverRequest&&t.initiator&&(t._debug("got request for transceiver"),t.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(t._pc.localDescription&&t._pc.localDescription.type&&t._pc.remoteDescription&&t._pc.remoteDescription.type?t._addIceCandidate(e.candidate):t._pendingCandidates.push(e.candidate)),e.sdp&&t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e)).then(function(){t.destroyed||(t._pendingCandidates.forEach(function(e){t._addIceCandidate(e)}),t._pendingCandidates=[],"offer"===t._pc.remoteDescription.type&&t._createAnswer())}).catch(function(e){t.destroy(s(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||t.destroy(s("signal() called with invalid signal data","ERR_SIGNALING"))},r.prototype._addIceCandidate=function(e){var t=this,n=new t._wrtc.RTCIceCandidate(e);t._pc.addIceCandidate(n).catch(function(e){!n.address||n.address.endsWith(".local")?("Ignoring unsupported ICE candidate.",console.warn("Ignoring unsupported ICE candidate.")):t.destroy(s(e,"ERR_ADD_ICE_CANDIDATE"))})},r.prototype.send=function(e){this._channel.send(e)},r.prototype.addTransceiver=function(e,t){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(li){this.destroy(li)}else this.emit("signal",{transceiverRequest:{kind:e,init:t}})},r.prototype.addStream=function(e){var t=this;t._debug("addStream()"),e.getTracks().forEach(function(n){t.addTrack(n,e)})},r.prototype.addTrack=function(e,t){this._debug("addTrack()");var n=this._senderMap.get(e)||new Map,r=n.get(t);r?r.removed?this.destroy(s("Track has been removed. You should enable/disable tracks that you want to re-add.","ERR_SENDER_REMOVED")):this.destroy(s("Track has already been added to that stream.","ERR_SENDER_ALREADY_ADDED")):(r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation())},r.prototype.replaceTrack=function(e,t,n){this._debug("replaceTrack()");var r=this._senderMap.get(e),i=r?r.get(n):null;i||this.destroy(s("Cannot replace track that was never added.","ERR_TRACK_NOT_ADDED")),t&&this._senderMap.set(t,r),null!=i.replaceTrack?i.replaceTrack(t):this.destroy(s("replaceTrack is not supported in this browser","ERR_UNSUPPORTED_REPLACETRACK"))},r.prototype.removeTrack=function(e,t){this._debug("removeSender()");var n=this._senderMap.get(e),r=n?n.get(t):null;r||this.destroy(s("Cannot remove track that was never added.","ERR_TRACK_NOT_ADDED"));try{r.removed=!0,this._pc.removeTrack(r)}catch(li){"NS_ERROR_UNEXPECTED"===li.name?this._sendersAwaitingStable.push(r):this.destroy(li)}this._needsNegotiation()},r.prototype.removeStream=function(e){var t=this;t._debug("removeSenders()"),e.getTracks().forEach(function(n){t.removeTrack(n,e)})},r.prototype._needsNegotiation=function(){var e=this;e._debug("_needsNegotiation"),e._batchedNegotiation||(e._batchedNegotiation=!0,setTimeout(function(){e._batchedNegotiation=!1,e._debug("starting batched negotiation"),e.negotiate()},0))},r.prototype.negotiate=function(){var e=this;e.initiator?e._isNegotiating?(e._queuedNegotiation=!0,e._debug("already negotiating, queueing")):(e._debug("start negotiation"),setTimeout(()=>{e._createOffer()},0)):e._isNegotiating||(e._debug("requesting negotiation from initiator"),e.emit("signal",{renegotiate:!0})),e._isNegotiating=!0},r.prototype.destroy=function(e){this._destroy(e,function(){})},r.prototype._destroy=function(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.destroyed=!0,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,e&&this.emit("error",e),this.emit("close"),t()}},r.prototype._setupData=function(e){var t=this;if(!e.channel)return t.destroy(s("Data channel event is missing `channel` property","ERR_DATA_CHANNEL"));t._channel=e.channel,t._channel.binaryType="arraybuffer","number"==typeof t._channel.bufferedAmountLowThreshold&&(t._channel.bufferedAmountLowThreshold=65536),t.channelName=t._channel.label,t._channel.onmessage=function(e){t._onChannelMessage(e)},t._channel.onbufferedamountlow=function(){t._onChannelBufferedAmountLow()},t._channel.onopen=function(){t._onChannelOpen()},t._channel.onclose=function(){t._onChannelClose()},t._channel.onerror=function(e){t.destroy(s(e,"ERR_DATA_CHANNEL"))};var n=!1;t._closingInterval=setInterval(function(){t._channel&&"closing"===t._channel.readyState?(n&&t._onChannelClose(),n=!0):n=!1},5e3)},r.prototype._read=function(){},r.prototype._write=function(e,t,n){if(this.destroyed)return n(s("cannot write after peer is destroyed","ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(li){return this.destroy(s(li,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>65536?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n},r.prototype._onFinish=function(){var e=this;function t(){setTimeout(function(){e.destroy()},1e3)}e.destroyed||(e._connected?t():e.once("connect",t))},r.prototype._startIceCompleteTimeout=function(){var e=this;e.destroyed||e._iceCompleteTimer||(e._debug("started iceComplete timeout"),e._iceCompleteTimer=setTimeout(function(){e._iceComplete||(e._iceComplete=!0,e._debug("iceComplete timeout completed"),e.emit("iceTimeout"),e.emit("_iceComplete"))},e.iceCompleteTimeout))},r.prototype._createOffer=function(){var e=this;e.destroyed||e._pc.createOffer(e.offerOptions).then(function(t){function n(){if(!e.destroyed){var n=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:n.type,sdp:n.sdp})}}e.destroyed||(e.trickle||e.allowHalfTrickle||(t.sdp=i(t.sdp)),t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(function(){e._debug("createOffer success"),e.destroyed||(e.trickle||e._iceComplete?n():e.once("_iceComplete",n))}).catch(function(t){e.destroy(s(t,"ERR_SET_LOCAL_DESCRIPTION"))}))}).catch(function(t){e.destroy(s(t,"ERR_CREATE_OFFER"))})},r.prototype._requestMissingTransceivers=function(){var e=this;e._pc.getTransceivers&&e._pc.getTransceivers().forEach(t=>{t.mid||!t.sender.track||t.requested||(t.requested=!0,e.addTransceiver(t.sender.track.kind))})},r.prototype._createAnswer=function(){var e=this;e.destroyed||e._pc.createAnswer(e.answerOptions).then(function(t){function n(){if(!e.destroyed){var n=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:n.type,sdp:n.sdp}),e.initiator||e._requestMissingTransceivers()}}e.destroyed||(e.trickle||e.allowHalfTrickle||(t.sdp=i(t.sdp)),t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(function(){e.destroyed||(e.trickle||e._iceComplete?n():e.once("_iceComplete",n))}).catch(function(t){e.destroy(s(t,"ERR_SET_LOCAL_DESCRIPTION"))}))}).catch(function(t){e.destroy(s(t,"ERR_CREATE_ANSWER"))})},r.prototype._onIceStateChange=function(){if(!this.destroyed){var 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(s("Ice connection failed.","ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(s("Ice connection closed.","ERR_ICE_CONNECTION_CLOSED"))}},r.prototype.getStats=function(e){var t=this;function n(e){return"[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(function(t){Object.assign(e,t)}),e}0===t._pc.getStats.length?t._pc.getStats().then(function(t){var r=[];t.forEach(function(e){r.push(n(e))}),e(null,r)},function(t){e(t)}):t._isReactNativeWebrtc?t._pc.getStats(null,function(t){var r=[];t.forEach(function(e){r.push(n(e))}),e(null,r)},function(t){e(t)}):t._pc.getStats.length>0?t._pc.getStats(function(r){if(!t.destroyed){var i=[];r.result().forEach(function(e){var t={};e.names().forEach(function(n){t[n]=e.stat(n)}),t.id=e.id,t.type=e.type,t.timestamp=e.timestamp,i.push(n(t))}),e(null,i)}},function(t){e(t)}):e(null,[])},r.prototype._maybeReady=function(){var e=this;e._debug("maybeReady pc %s channel %s",e._pcReady,e._channelReady),!e._connected&&!e._connecting&&e._pcReady&&e._channelReady&&(e._connecting=!0,function t(){e.destroyed||e.getStats(function(n,r){if(!e.destroyed){n&&(r=[]);var i={},o={},a={},h=!1;if(r.forEach(function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(o[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(a[e.id]=e)}),r.forEach(function(e){"transport"===e.type&&e.selectedCandidatePairId&&u(a[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&u(e)}),h||Object.keys(a).length&&!Object.keys(o).length){if(e._connecting=!1,e._connected=!0,e._chunk){try{e.send(e._chunk)}catch(n){return e.destroy(s(n,"ERR_DATA_CHANNEL"))}e._chunk=null,e._debug('sent chunk from "write before connect"');var c=e._cb;e._cb=null,c(null)}"number"!=typeof e._channel.bufferedAmountLowThreshold&&(e._interval=setInterval(function(){e._onInterval()},150),e._interval.unref&&e._interval.unref()),e._debug("connect"),e.emit("connect")}else setTimeout(t,100)}function u(t){h=!0;var n=o[t.localCandidateId];n&&(n.ip||n.address)?(e.localAddress=n.ip||n.address,e.localPort=Number(n.port)):n&&n.ipAddress?(e.localAddress=n.ipAddress,e.localPort=Number(n.portNumber)):"string"==typeof t.googLocalAddress&&(n=t.googLocalAddress.split(":"),e.localAddress=n[0],e.localPort=Number(n[1])),e.localAddress&&(e.localFamily=e.localAddress.includes(":")?"IPv6":"IPv4");var r=i[t.remoteCandidateId];r&&(r.ip||r.address)?(e.remoteAddress=r.ip||r.address,e.remotePort=Number(r.port)):r&&r.ipAddress?(e.remoteAddress=r.ipAddress,e.remotePort=Number(r.portNumber)):"string"==typeof t.googRemoteAddress&&(r=t.googRemoteAddress.split(":"),e.remoteAddress=r[0],e.remotePort=Number(r[1])),e.remoteAddress&&(e.remoteFamily=e.remoteAddress.includes(":")?"IPv6":"IPv4"),e._debug("connect local: %s:%s remote: %s:%s",e.localAddress,e.localPort,e.remoteAddress,e.remotePort)}})}())},r.prototype._onInterval=function(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()},r.prototype._onSignalingStateChange=function(){var e=this;e.destroyed||("stable"!==e._pc.signalingState||e._firstStable||(e._isNegotiating=!1,e._debug("flushing sender queue",e._sendersAwaitingStable),e._sendersAwaitingStable.forEach(function(t){e._pc.removeTrack(t),e._queuedNegotiation=!0}),e._sendersAwaitingStable=[],e._queuedNegotiation&&(e._debug("flushing negotiation queue"),e._queuedNegotiation=!1,e._needsNegotiation()),e._debug("negotiate"),e.emit("negotiate")),e._firstStable=!1,e._debug("signalingStateChange %s",e._pc.signalingState),e.emit("signalingStateChange",e._pc.signalingState))},r.prototype._onIceCandidate=function(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{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())},r.prototype._onChannelMessage=function(t){if(!this.destroyed){var n=t.data;n instanceof ArrayBuffer&&(n=e.from(n)),this.push(n)}},r.prototype._onChannelBufferedAmountLow=function(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);var e=this._cb;this._cb=null,e(null)}},r.prototype._onChannelOpen=function(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())},r.prototype._onChannelClose=function(){this.destroyed||(this._debug("on channel close"),this.destroy())},r.prototype._onTrack=function(e){var t=this;t.destroyed||e.streams.forEach(function(n){t._debug("on track"),t.emit("track",e.track,n),t._remoteTracks.push({track:e.track,stream:n}),t._remoteStreams.some(function(e){return e.id===n.id})||(t._remoteStreams.push(n),setTimeout(function(){t.emit("stream",n)},0))})},r.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],t.apply(null,e)}}).call(this,u({}).Buffer);var An,Rn=1,Ln=function(){Rn=Rn+1&65535},Bn=function(e){An||(An=setInterval(Ln,250)).unref&&An.unref();var t=4*(e||5),n=[0],r=1,i=Rn-1&65535;return function(e){var s=Rn-i&65535;for(s>t&&(s=t),i=Rn;s--;)r===t&&(r=0),n[r]=n[0===r?t-1:r-1],r++;e&&(n[r-1]+=e);var o=n[r-1],a=n.length>3;return e%8!=0&&t++,t}Nn.exports=class{constructor(e=0,t){const n=null!=t&&t.grow;this.grow=n&&isFinite(n)&&jn(n)||n||0,this.buffer="number"==typeof e?new Uint8Array(jn(e)):e}get(e){const t=e>>3;return t>e%8)}set(e,t=!0){const n=e>>3;if(t){if(this.buffer.length>e%8}else n>e%8))}},Nn=Nn.exports;var Hn=class extends Ze.Writable{constructor(e,t,n={}){if(super(n),!e||!e.put||!e.get)throw new Error("First argument must be an abstract-chunk-store compliant store");if(!(t=Number(t)))throw new Error("Second argument must be a chunk length");this._blockstream=new Qe(t,{zeroPadding:!1}),this._outstandingPuts=0;let r=0;this._blockstream.on("data",t=>{this.destroyed||(this._outstandingPuts+=1,e.put(r,t,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),r+=1)}).on("error",e=>{this.destroy(e)})}_write(e,t,n){this._blockstream.write(e,t,n)}_final(e){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?e(null):this._finalCb=e})}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e),this.emit("close"))}},Dn={};(function(e){Dn.DEFAULT_ANNOUNCE_PEERS=50,Dn.binaryToHex=function(t){return"string"!=typeof t&&(t=String(t)),e.from(t,"binary").toString("hex")},Dn.hexToBinary=function(t){return"string"!=typeof t&&(t=String(t)),e.from(t,"hex").toString("binary")},Object.assign(Dn,te)}).call(this,u({}).Buffer);var qn={};(function(e,t){const n=Nt("simple-websocket"),r="function"!=typeof te?WebSocket:te,i=65536;class s extends Ze.Duplex{constructor(t={}){if("string"==typeof t&&(t={url:t}),super(t=Object.assign({allowHalfOpen:!1},t)),null==t.url&&null==t.socket)throw new Error("Missing required `url` or `socket` option");if(null!=t.url&&null!=t.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=Tn(4).toString("hex").slice(0,7),this._debug("new websocket: %o",t),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,t.socket)this.url=t.socket.url,this._ws=t.socket,this.connected=t.socket.readyState===r.OPEN;else{this.url=t.url;try{this._ws="function"==typeof te?new r(t.url,t):new r(t.url)}catch(li){return void e.nextTick(()=>this.destroy(li))}}this._ws.binaryType="arraybuffer",this._ws.onopen=(()=>{this._onOpen()}),this._ws.onmessage=(e=>{this._onMessage(e)}),this._ws.onclose=(()=>{this._onClose()}),this._ws.onerror=(()=>{this.destroy(new Error("connection error to "+this.url))}),this._onFinishBound=(()=>{this._onFinish()}),this.once("finish",this._onFinishBound)}send(e){this._ws.send(e)}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const t=this._ws,n=()=>{t.onclose=null};if(t.readyState===r.CLOSED)n();else try{t.onclose=n,t.close()}catch(e){n()}t.onopen=null,t.onmessage=null,t.onerror=(()=>{})}if(this._ws=null,e){if("undefined"!=typeof DOMException&&e instanceof DOMException){const t=e.code;(e=new Error(e.message)).code=t}this.emit("error",e)}this.emit("close"),t()}}_read(){}_write(e,t,n){if(this.destroyed)return n(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(li){return this.destroy(li)}"function"!=typeof te&&this._ws.bufferedAmount>i?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?e():this.once("connect",e)}_onMessage(e){if(this.destroyed)return;let n=e.data;n instanceof ArrayBuffer&&(n=t.from(n)),this.push(n)}_onOpen(){if(!this.connected&&!this.destroyed){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(li){return this.destroy(li)}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"function"!=typeof te&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(!this._cb||!this._ws||this._ws.bufferedAmount>i)return;this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],n.apply(null,e)}}s.WEBSOCKET_SUPPORT=!!r,qn=s}).call(this,ce,u({}).Buffer);var Fn=class extends d{constructor(e,t){super(),this.client=e,this.announceUrl=t,this.interval=null,this.destroyed=!1}setInterval(e){null==e&&(e=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),e&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},e),this.interval.unref&&this.interval.unref())}},Wn={};const zn=Nt("bittorrent-tracker:websocket-tracker"),$n={},Vn=1e4,Gn=18e5,Kn=12e4,Yn=5e4;class Jn extends Fn{constructor(e,t,n){super(e,t),zn("new websocket tracker %s",t),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(e)});const t=Object.assign({},e,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(t.trackerid=this._trackerId),"stopped"===e.event||"completed"===e.event)this._send(t);else{const n=Math.min(e.numwant,10);this._generateOffers(n,e=>{t.numwant=n,t.offers=e,this._send(t)})}}scrape(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(e)});const t={action:"scrape",info_hash:Array.isArray(e.infoHash)&&e.infoHash.length>0?e.infoHash.map(e=>e.toString("binary")):e.infoHash&&e.infoHash.toString("binary")||this.client._infoHashBinary};this._send(t)}destroy(e=Xn){if(this.destroyed)return e(null);this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer);for(const i in this.peers){const e=this.peers[i];clearTimeout(e.trackerTimeout),e.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,$n[this.announceUrl]&&($n[this.announceUrl].consumers-=1),$n[this.announceUrl].consumers>0)return e();let t=$n[this.announceUrl];if(delete $n[this.announceUrl],t.on("error",Xn),t.once("close",e),!this.expectingResponse)return r();var n=setTimeout(r,Dn.DESTROY_TIMEOUT);function r(){n&&(clearTimeout(n),n=null),t.removeListener("data",r),t.destroy(),t=null}t.once("data",r)}_openSocket(){this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=(()=>{this._onSocketConnect()}),this._onSocketErrorBound=(e=>{this._onSocketError(e)}),this._onSocketDataBound=(e=>{this._onSocketData(e)}),this._onSocketCloseBound=(()=>{this._onSocketClose()}),this.socket=$n[this.announceUrl],this.socket?($n[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound()):(this.socket=$n[this.announceUrl]=new qn(this.announceUrl),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)),this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(e){if(!this.destroyed){this.expectingResponse=!1;try{e=JSON.parse(e)}catch(li){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===e.action?this._onAnnounceResponse(e):"scrape"===e.action?this._onScrapeResponse(e):this._onSocketError(new Error(`invalid action in WS response: ${e.action}`))}}_onAnnounceResponse(e){if(e.info_hash!==this.client._infoHashBinary)return void zn("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,Dn.binaryToHex(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;zn("received %s from %s for %s",JSON.stringify(e),this.announceUrl,this.client.infoHash);const t=e["failure reason"];if(t)return this.client.emit("warning",new Error(t));const n=e["warning message"];n&&this.client.emit("warning",new Error(n));const r=e.interval||e["min interval"];r&&this.setInterval(1e3*r);const i=e["tracker id"];if(i&&(this._trackerId=i),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:Dn.binaryToHex(e.info_hash)});this.client.emit("update",t)}let s;if(e.offer&&e.peer_id&&(zn("creating peer (from remote offer)"),(s=this._createPeer()).id=Dn.binaryToHex(e.peer_id),s.once("signal",t=>{const n={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:e.peer_id,answer:t,offer_id:e.offer_id};this._trackerId&&(n.trackerid=this._trackerId),this._send(n)}),s.signal(e.offer),this.client.emit("peer",s)),e.answer&&e.peer_id){const t=Dn.binaryToHex(e.offer_id);(s=this.peers[t])?(s.id=Dn.binaryToHex(e.peer_id),s.signal(e.answer),this.client.emit("peer",s),clearTimeout(s.trackerTimeout),s.trackerTimeout=null,delete this.peers[t]):zn(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);0!==t.length?t.forEach(t=>{const n=Object.assign(e[t],{announce:this.announceUrl,infoHash:Dn.binaryToHex(t)});this.client.emit("scrape",n)}):this.client.emit("warning",new Error("invalid scrape response"))}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(e){this.destroyed||(this.destroy(),this.client.emit("warning",e),this._startReconnectTimer())}_startReconnectTimer(){const e=Math.floor(Math.random()*Kn)+Math.min(Math.pow(2,this.retries)*Vn,Gn);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},e),this.reconnectTimer.unref&&this.reconnectTimer.unref(),zn("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);zn("send %s",t),this.socket.send(t)}_generateOffers(e,t){const n=this,r=[];zn("generating %s offers",e);for(let o=0;o{r.push({offer:t,offer_id:Dn.hexToBinary(e)}),s()}),t.trackerTimeout=setTimeout(()=>{zn("tracker timeout: destroying peer"),t.trackerTimeout=null,delete n.peers[e],t.destroy()},Yn),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function s(){r.length===e&&(zn("generated %s offers",e),t(r))}s()}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const n=new In(e);return n.once("error",r),n.once("connect",function e(){n.removeListener("error",r),n.removeListener("connect",e)}),n;function r(e){t.client.emit("warning",new Error(`Connection error: ${e.message}`)),n.destroy()}}}function Xn(){}Jn.prototype.DEFAULT_ANNOUNCE_INTERVAL=3e4,Jn._socketPool=$n,Wn=Jn;var Zn={};(function(e,t){const n=Nt("bittorrent-tracker:client");class r extends d{constructor(r={}){if(super(),!r.peerId)throw new Error("Option `peerId` is required");if(!r.infoHash)throw new Error("Option `infoHash` is required");if(!r.announce)throw new Error("Option `announce` is required");if(!e.browser&&!r.port)throw new Error("Option `port` is required");this.peerId="string"==typeof r.peerId?r.peerId:r.peerId.toString("hex"),this._peerIdBuffer=t.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof r.infoHash?r.infoHash.toLowerCase():r.infoHash.toString("hex"),this._infoHashBuffer=t.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),n("new client %s",this.infoHash),this.destroyed=!1,this._port=r.port,this._getAnnounceOpts=r.getAnnounceOpts,this._rtcConfig=r.rtcConfig,this._userAgent=r.userAgent,this._wrtc="function"==typeof r.wrtc?r.wrtc():r.wrtc;let i="string"==typeof r.announce?[r.announce]:null==r.announce?[]:r.announce;i=i.map(e=>("/"===(e=e.toString())[e.length-1]&&(e=e.substring(0,e.length-1)),e)),i=kn(i);const s=!1!==this._wrtc&&(!!this._wrtc||In.WEBRTC_SUPPORT),o=t=>{e.nextTick(()=>{this.emit("warning",t)})};this._trackers=i.map(e=>{let t;try{t=new URL(e)}catch(li){return o(new Error(`Invalid tracker URL: ${e}`)),null}const n=t.port;if(n<0||n>65535)return o(new Error(`Invalid tracker port: ${e}`)),null;const r=t.protocol;return"http:"!==r&&"https:"!==r||"function"!=typeof te?"udp:"===r&&"function"==typeof te?new te(this,e):"ws:"!==r&&"wss:"!==r||!s?(o(new Error(`Unsupported tracker protocol: ${e}`)),null):"ws:"===r&&"undefined"!=typeof window&&"https:"===window.location.protocol?(o(new Error(`Unsupported tracker protocol: ${e}`)),null):new Wn(this,e):new te(this,e)}).filter(Boolean)}start(e){(e=this._defaultAnnounceOpts(e)).event="started",n("send `start` %o",e),this._announce(e),this._trackers.forEach(e=>{e.setInterval()})}stop(e){(e=this._defaultAnnounceOpts(e)).event="stopped",n("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),(e=this._defaultAnnounceOpts(e)).event="completed",n("send `complete` %o",e),this._announce(e)}update(e){(e=this._defaultAnnounceOpts(e)).event&&delete e.event,n("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach(t=>{t.announce(e)})}scrape(e){n("send `scrape`"),e||(e={}),this._trackers.forEach(t=>{t.scrape(e)})}setInterval(e){n("setInterval %d",e),this._trackers.forEach(t=>{t.setInterval(e)})}destroy(e){if(this.destroyed)return;this.destroyed=!0,n("destroy");const t=this._trackers.map(e=>t=>{e.destroy(t)});kt(t,e),this._trackers=[],this._getAnnounceOpts=null}_defaultAnnounceOpts(e={}){return null==e.numwant&&(e.numwant=Dn.DEFAULT_ANNOUNCE_PEERS),null==e.uploaded&&(e.uploaded=0),null==e.downloaded&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}r.scrape=((e,n)=>{if(n=wt(n),!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");const i=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:t.from("01234567890123456789"),port:6881}),s=new r(i);s.once("error",n),s.once("warning",n);let o=Array.isArray(e.infoHash)?e.infoHash.length:1;const a={};return s.on("scrape",e=>{if(o-=1,a[e.infoHash]=e,0===o){s.destroy();const e=Object.keys(a);1===e.length?n(null,a[e[0]]):n(null,a)}}),e.infoHash=Array.isArray(e.infoHash)?e.infoHash.map(e=>t.from(e,"hex")):t.from(e.infoHash,"hex"),s.scrape({infoHash:e.infoHash}),s}),Zn=r}).call(this,ce,u({}).Buffer);var Qn={};(function(e){const t=Nt("torrent-discovery"),n=d.EventEmitter;Qn=class extends n{constructor(t){if(super(),!t.peerId)throw new Error("Option `peerId` is required");if(!t.infoHash)throw new Error("Option `infoHash` is required");if(!e.browser&&!t.port)throw new Error("Option `port` is required");this.peerId="string"==typeof t.peerId?t.peerId:t.peerId.toString("hex"),this.infoHash="string"==typeof t.infoHash?t.infoHash.toLowerCase():t.infoHash.toString("hex"),this._port=t.port,this._userAgent=t.userAgent,this.destroyed=!1,this._announce=t.announce||[],this._intervalMs=t.intervalMs||9e5,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=(e=>{this.emit("warning",e)}),this._onError=(e=>{this.emit("error",e)}),this._onDHTPeer=((e,t)=>{t.toString("hex")===this.infoHash&&this.emit("peer",`${e.host}:${e.port}`,"dht")}),this._onTrackerPeer=(e=>{this.emit("peer",e,"tracker")}),this._onTrackerAnnounce=(()=>{this.emit("trackerAnnounce")});const n=(e,t)=>{const n=new te(t);return n.on("warning",this._onWarning),n.on("error",this._onError),n.listen(e),this._internalDHT=!0,n};!1===t.tracker?this.tracker=null:t.tracker&&"object"==typeof t.tracker?(this._trackerOpts=Object.assign({},t.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),!1===t.dht||"function"!=typeof te?this.dht=null:t.dht&&"function"==typeof t.dht.addNode?this.dht=t.dht:t.dht&&"object"==typeof t.dht?this.dht=n(t.dhtPort,t.dht):this.dht=n(t.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce())}updatePort(e){e!==this._port&&(this._port=e,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(e){this.tracker&&this.tracker.complete(e)}destroy(e){if(this.destroyed)return;this.destroyed=!0,clearTimeout(this._dhtTimeout);const t=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),t.push(e=>{this.tracker.destroy(e)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),t.push(e=>{this.dht.destroy(e)})),kt(t,e),this.dht=null,this.tracker=null,this._announce=null}_createTracker(){const e=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),t=new Zn(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onTrackerPeer),t.on("update",this._onTrackerAnnounce),t.setInterval(this._intervalMs),t.start(),t}_dhtAnnounce(){this._dhtAnnouncing||(t("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,e=>{this._dhtAnnouncing=!1,t("dht announce complete"),e&&this.emit("warning",e),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+Math.floor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}}}).call(this,ce);var er={};(function(e){function t(e,n){if(!(this instanceof t))return new t(e,n);if(n||(n={}),this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=Number(n.length)||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1)}function n(t,n,r){e.nextTick(function(){t&&t(n,r)})}er=t,t.prototype.put=function(e,t,r){if(this.closed)return n(r,new Error("Storage is closed"));var i=e===this.lastChunkIndex;return i&&t.length!==this.lastChunkLength?n(r,new Error("Last chunk length must be "+this.lastChunkLength)):i||t.length===this.chunkLength?(this.chunks[e]=t,void n(r,null)):n(r,new Error("Chunk length must be "+this.chunkLength))},t.prototype.get=function(e,t,r){if("function"==typeof t)return this.get(e,null,t);if(this.closed)return n(r,new Error("Storage is closed"));var i=this.chunks[e];if(!i){var s=new Error("Chunk not found");return s.notFound=!0,n(r,s)}if(!t)return n(r,null,i);var o=t.offset||0,a=t.length||i.length-o;n(r,null,i.slice(o,a+o))},t.prototype.close=t.prototype.destroy=function(e){if(this.closed)return n(e,new Error("Storage is closed"));this.closed=!0,this.chunks=null,n(e,null)}}).call(this,ce);var tr={};(function(e){tr=class{constructor(e){if(this.store=e,this.chunkLength=e.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(e,t,n){this.mem[e]=t,this.store.put(e,t,t=>{this.mem[e]=null,n&&n(t)})}get(t,n,r){if("function"==typeof n)return this.get(t,null,n);const i=n&&n.offset||0,s=n&&n.length&&i+n.length,o=this.mem[t];if(o)return function(t,n,r){e.nextTick(()=>{t&&t(null,r)})}(r,0,n?o.slice(i,s):o);this.store.get(t,n,r)}close(e){this.store.close(e)}destroy(e){this.store.destroy(e)}}}).call(this,ce);var nr={};(function(e){nr=function(t,n,r){if("number"!=typeof n)throw new Error("second argument must be a Number");var i,s,o,a,h,c=!0;function u(t){function n(){r&&r(t,i),r=null}c?e.nextTick(n):n()}function d(e,n,r){if(i[e]=r,n&&(h=!0),0==--o||n)u(n);else if(!h&&l0,function(t){e||(e=t),t&&h.forEach(i),u||(h.forEach(i),a(e))})});return o.reduce(s)}}).call(this,ce);var hr={};(function(e){const{EventEmitter:t}=d,n=Nt("ut_metadata"),r=1e7,i=1e3,s=16384;hr=(o=>{class a extends t{constructor(t){super(),this._wire=t,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new Nn(0,{grow:i}),e.isBuffer(o)&&this.setMetadata(o)}onHandshake(e,t,n){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||rthis._metadataSize&&(n=this._metadataSize);const r=this.metadata.slice(t,n);this._data(e,r,this._metadataSize)}_onData(e,t,n){t.length>s||!this._fetching||(t.copy(this.metadata,e*s),this._bitfield.set(e),this._checkDone())}_onReject(e){this._remainingRejects>0&&this._fetching?(this._request(e),this._remainingRejects-=1):this.emit("warning",new Error('Peer sent "reject" too much'))}_requestPieces(){if(this._fetching){this.metadata=e.alloc(this._metadataSize);for(let e=0;e0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return a.prototype.name="ut_metadata",a})}).call(this,u({}).Buffer);var cr={parse:function(e){var t=e.split(",").map(function(e){return function(e){if(/^-?\d+$/.test(e))return parseInt(e,10);var t;if(t=e.match(/^(-?\d+)(-|\.\.\.?|\u2025|\u2026|\u22EF)(-?\d+)$/)){var n=t[1],r=t[2],i=t[3];if(n&&i){var s=[],o=(n=parseInt(n))<(i=parseInt(i))?1:-1;"-"!=r&&".."!=r&&"\u2025"!=r||(i+=o);for(var a=n;a!=i;a+=o)s.push(a);return s}}return[]}(e)});return 0===t.length?[]:1===t.length?Array.isArray(t[0])?t[0]:t:t.reduce(function(e,t){return Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]),e.concat(t)})}},ur=function(e){for(var t=0,n=e.length;t127)return!1;return!0},dr=u({}).Buffer,lr=gr,fr="undefined"!=typeof window&&window.MediaSource,pr=60;function gr(e,t){var n=this;if(!(n instanceof gr))return new gr(e,t);if(!fr)throw new Error("web browser lacks MediaSource support");t||(t={}),n._debug=t.debug,n._bufferDuration=t.bufferDuration||pr,n._elem=e,n._mediaSource=new fr,n._streams=[],n.detailedError=null,n._errorHandler=function(){n._elem.removeEventListener("error",n._errorHandler),n._streams.slice().forEach(function(e){e.destroy(n._elem.error)})},n._elem.addEventListener("error",n._errorHandler),n._elem.src=window.URL.createObjectURL(n._mediaSource)}function mr(e,t){var n=this;if(Ze.Writable.call(n),n._wrapper=e,n._elem=e._elem,n._mediaSource=e._mediaSource,n._allStreams=e._streams,n._allStreams.push(n),n._bufferDuration=e._bufferDuration,n._sourceBuffer=null,n._debugBuffers=[],n._openHandler=function(){n._onSourceOpen()},n._flowHandler=function(){n._flow()},n._errorHandler=function(e){n.destroyed||n.emit("error",e)},"string"==typeof t)n._type=t,"open"===n._mediaSource.readyState?n._createSourceBuffer():n._mediaSource.addEventListener("sourceopen",n._openHandler);else if(null===t._sourceBuffer)t.destroy(),n._type=t._type,n._mediaSource.addEventListener("sourceopen",n._openHandler);else{if(!t._sourceBuffer)throw new Error("The argument to MediaElementWrapper.createWriteStream must be a string or a previous stream returned from that function");t.destroy(),n._type=t._type,n._sourceBuffer=t._sourceBuffer,n._debugBuffers=t._debugBuffers,n._sourceBuffer.addEventListener("updateend",n._flowHandler),n._sourceBuffer.addEventListener("error",n._errorHandler)}n._elem.addEventListener("timeupdate",n._flowHandler),n.on("error",function(e){n._wrapper.error(e)}),n.on("finish",function(){if(!n.destroyed&&(n._finished=!0,n._allStreams.every(function(e){return e._finished}))){n._wrapper._dumpDebugData();try{n._mediaSource.endOfStream()}catch(li){}}})}gr.prototype.createWriteStream=function(e){return new mr(this,e)},gr.prototype.error=function(e){this.detailedError||(this.detailedError=e),this._dumpDebugData();try{this._mediaSource.endOfStream("decode")}catch(e){}try{window.URL.revokeObjectURL(this._elem.src)}catch(e){}},gr.prototype._dumpDebugData=function(){this._debug&&(this._debug=!1,this._streams.forEach(function(e,t){var n,r,i;n=e._debugBuffers,r="mediasource-stream-"+t,(i=document.createElement("a")).href=window.URL.createObjectURL(new window.Blob(n)),i.download=r,i.click()}))},Re(mr,Ze.Writable),mr.prototype._onSourceOpen=function(){this.destroyed||(this._mediaSource.removeEventListener("sourceopen",this._openHandler),this._createSourceBuffer())},mr.prototype.destroy=function(e){this.destroyed||(this.destroyed=!0,this._allStreams.splice(this._allStreams.indexOf(this),1),this._mediaSource.removeEventListener("sourceopen",this._openHandler),this._elem.removeEventListener("timeupdate",this._flowHandler),this._sourceBuffer&&(this._sourceBuffer.removeEventListener("updateend",this._flowHandler),this._sourceBuffer.removeEventListener("error",this._errorHandler),"open"===this._mediaSource.readyState&&this._sourceBuffer.abort()),e&&this.emit("error",e),this.emit("close"))},mr.prototype._createSourceBuffer=function(){if(!this.destroyed)if(fr.isTypeSupported(this._type)){if(this._sourceBuffer=this._mediaSource.addSourceBuffer(this._type),this._sourceBuffer.addEventListener("updateend",this._flowHandler),this._sourceBuffer.addEventListener("error",this._errorHandler),this._cb){var e=this._cb;this._cb=null,e()}}else this.destroy(new Error("The provided type is not supported"))},mr.prototype._write=function(e,t,n){var r=this;if(!r.destroyed)if(r._sourceBuffer){if(r._sourceBuffer.updating)return n(new Error("Cannot append buffer while source buffer updating"));var i=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(dr.isBuffer(e)){for(var t=new Uint8Array(e.length),n=e.length,r=0;rthis._bufferDuration)&&this._cb){var e=this._cb;this._cb=null,e()}},mr.prototype._getBufferDuration=function(){for(var e=this._sourceBuffer.buffered,t=this._elem.currentTime,n=-1,r=0;rt)break;(n>=0||t<=s)&&(n=s)}var o=n-t;return o<0&&(o=0),o};var _r=function(e,t){if(null!=t&&"string"!=typeof t)throw new Error("Invalid mimetype, expected string.");return new Promise((n,r)=>{const i=[];e.on("data",e=>i.push(e)).once("end",()=>{const e=null!=t?new Blob(i,{type:t}):new Blob(i);n(e)}).once("error",r)})},yr=async function(e,t){const n=await _r(e,t);return URL.createObjectURL(n)},br={};(function(e){var t=function(){try{if(!e.isEncoding("latin1"))return!1;var t=e.alloc?e.alloc(4):new e(4);return t.fill("ab","ucs2"),"61006200"===t.toString("hex")}catch(n){return!1}}();function n(e,t,n,r){if(n<0||r>e.length)throw new RangeError("Out of range index");return n>>>=0,(r=void 0===r?e.length:r>>>0)>n&&e.fill(t,n,r),e}br=function(r,i,s,o,a){if(t)return r.fill(i,s,o,a);if("number"==typeof i)return n(r,i,s,o);if("string"==typeof i){if("string"==typeof s?(a=s,s=0,o=r.length):"string"==typeof o&&(a=o,o=r.length),void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("latin1"===a&&(a="binary"),"string"==typeof a&&!e.isEncoding(a))throw new TypeError("Unknown encoding: "+a);if(""===i)return n(r,0,s,o);if(function(e){return 1===e.length&&e.charCodeAt(0)<256}(i))return n(r,i.charCodeAt(0),s,o);i=new e(i,a)}return e.isBuffer(i)?function(e,t,n,r){if(n<0||r>e.length)throw new RangeError("Out of range index");if(r<=n)return e;n>>>=0,r=void 0===r?e.length:r>>>0;for(var i=n,s=t.length;i<=r-s;)t.copy(e,i),i+=s;return i!==r&&t.copy(e,i,0,r-i),e}(r,i,s,o):n(r,0,s,o)}}).call(this,u({}).Buffer);var wr={};(function(e){wr=function(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative');return e.allocUnsafe?e.allocUnsafe(t):new e(t)}}).call(this,u({}).Buffer);var vr={};(function(e){vr=function(t,n,r){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative');if(e.alloc)return e.alloc(t,n,r);var i=wr(t);return 0===t?i:void 0===n?br(i,0):("string"!=typeof r&&(r=void 0),br(i,n,r))}}).call(this,u({}).Buffer);var Er={},kr=Math.pow(2,32);Er.encode=function(e,t,n){t||(t=vr(8)),n||(n=0);var r=Math.floor(e/kr),i=e-r*kr;return t.writeUInt32BE(r,n),t.writeUInt32BE(i,n+4),t},Er.decode=function(e,t){t||(t=0);var n=e.readUInt32BE(t),r=e.readUInt32BE(t+4);return n*kr+r},Er.encode.bytes=8,Er.decode.bytes=8;var Sr={};(function(e){var t={3:"ESDescriptor",4:"DecoderConfigDescriptor",5:"DecoderSpecificInfo",6:"SLConfigDescriptor"};Sr.Descriptor={},Sr.Descriptor.decode=function(n,r,i){var s,o,a=n.readUInt8(r),h=r+1,c=0;do{c=c<<7|127&(s=n.readUInt8(h++))}while(128&s);var u=t[a];return(o=Sr[u]?Sr[u].decode(n,h,i):{buffer:e.from(n.slice(h,h+c))}).tag=a,o.tagName=u,o.length=h-r+c,o.contentsLen=c,o},Sr.DescriptorArray={},Sr.DescriptorArray.decode=function(e,n,r){for(var i=n,s={};i+2<=r;){var o=Sr.Descriptor.decode(e,i,r);i+=o.length,s[t[o.tag]||"Descriptor"+o.tag]=o}return s},Sr.ESDescriptor={},Sr.ESDescriptor.decode=function(e,t,n){var r=e.readUInt8(t+2),i=t+3;return 128&r&&(i+=2),64&r&&(i+=e.readUInt8(i)+1),32&r&&(i+=2),Sr.DescriptorArray.decode(e,i,n)},Sr.DecoderConfigDescriptor={},Sr.DecoderConfigDescriptor.decode=function(e,t,n){var r=e.readUInt8(t),i=Sr.DescriptorArray.decode(e,t+13,n);return i.oti=r,i}}).call(this,u({}).Buffer);var Cr={};(function(e){var n=t({}),r=e.alloc(0);class i extends Ze.PassThrough{constructor(e){super(),this._parent=e,this.destroyed=!1}destroy(e){this.destroyed||(this.destroyed=!0,this._parent.destroy(e),e&&this.emit("error",e),this.emit("close"))}}Cr=class extends Ze.Writable{constructor(e){super(e),this.destroyed=!1,this._pending=0,this._missing=0,this._ignoreEmpty=!1,this._buf=null,this._str=null,this._cb=null,this._ondrain=null,this._writeBuffer=null,this._writeCb=null,this._ondrain=null,this._kick()}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e),this.emit("close"))}_write(e,t,n){if(!this.destroyed){for(var i=!this._str||!this._str._writableState.needDrain;e.length&&!this.destroyed;){if(!this._missing&&!this._ignoreEmpty)return this._writeBuffer=e,void(this._writeCb=n);var s=e.length{this._pending--,this._kick()}),this._cb=t,this._str;var n,r,s}_readBox(){const t=(r,i)=>{this._buffer(r,r=>{i=i?e.concat([i,r]):r;var s=n.readHeaders(i);"number"==typeof s?t(s-i.length,i):(this._pending++,this._headers=s,this.emit("box",s))})};t(8)}stream(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var e=this._headers;return this._headers=null,this._stream(e.contentLen,null)}decode(e){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var t=this._headers;this._headers=null,this._buffer(t.contentLen,r=>{var i=n.decodeWithoutHeaders(t,r);e(i),this._pending--,this._kick()})}ignore(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var e=this._headers;this._headers=null,this._missing=e.contentLen,0===this._missing&&(this._ignoreEmpty=!0),this._cb=(()=>{this._pending--,this._kick()})}_kick(){if(!this._pending&&(this._buf||this._str||this._readBox(),this._writeBuffer)){var e=this._writeCb,t=this._writeBuffer;this._writeBuffer=null,this._writeCb=null,this._write(t,null,e)}}}}).call(this,u({}).Buffer);var xr={};(function(e,n){var r=t({});function i(){}class s extends Ze.PassThrough{constructor(e){super(),this._parent=e,this.destroyed=!1}destroy(e){this.destroyed||(this.destroyed=!0,this._parent.destroy(e),e&&this.emit("error",e),this.emit("close"))}}xr=class extends Ze.Readable{constructor(e){super(e),this.destroyed=!1,this._finalized=!1,this._reading=!1,this._stream=null,this._drain=null,this._want=!1,this._onreadable=(()=>{this._want&&(this._want=!1,this._read())}),this._onend=(()=>{this._stream=null})}mdat(e,t){this.mediaData(e,t)}mediaData(e,t){var n=new s(this);return this.box({type:"mdat",contentLength:e,encodeBufferLen:8,stream:n},t),n}box(t,s){if(s||(s=i),this.destroyed)return s(new Error("Encoder is destroyed"));var o;if(t.encodeBufferLen&&(o=n.alloc(t.encodeBufferLen)),t.stream)t.buffer=null,o=r.encode(t,o),this.push(o),this._stream=t.stream,this._stream.on("readable",this._onreadable),this._stream.on("end",this._onend),this._stream.on("end",s),this._forward();else{if(o=r.encode(t,o),this.push(o))return e.nextTick(s);this._drain=s}}destroy(e){if(!this.destroyed){if(this.destroyed=!0,this._stream&&this._stream.destroy&&this._stream.destroy(),this._stream=null,this._drain){var t=this._drain;this._drain=null,t(e)}e&&this.emit("error",e),this.emit("close")}}finalize(){this._finalized=!0,this._stream||this._drain||this.push(null)}_forward(){if(this._stream)for(;!this.destroyed;){var e=this._stream.read();if(!e)return void(this._want=!!this._stream);if(!this.push(e))return}}_read(){if(!this._reading&&!this.destroyed){if(this._reading=!0,this._stream&&this._forward(),this._drain){var e=this._drain;this._drain=null,e()}this._reading=!1,this._finalized&&this.push(null)}}}}).call(this,ce,u({}).Buffer);var Tr={decode:e=>new Cr(e),encode:e=>new xr(e)};const{Writable:Ir,PassThrough:Ar}=Ze;var Rr=class extends Ir{constructor(e,t={}){super(t),this.destroyed=!1,this._queue=[],this._position=e||0,this._cb=null,this._buffer=null,this._out=null}_write(e,t,n){let r=!0;for(;;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=e,void(this._cb=n);this._buffer=null;var i=this._queue[0];const t=Math.max(i.start-this._position,0),s=i.end-this._position;if(t>=e.length)return this._position+=e.length,n(null);let o;if(s>e.length){this._position+=e.length,o=0===t?e:e.slice(t),r=i.stream.write(o)&&r;break}this._position+=s,o=0===t&&s===e.length?e:e.slice(t,s),r=i.stream.write(o)&&r,i.last&&i.stream.end(),e=e.slice(s),this._queue.shift()}r?n(null):i.stream.once("drain",n.bind(null,null))}slice(e){if(this.destroyed)return null;Array.isArray(e)||(e=[e]);const t=new Ar;return e.forEach((n,r)=>{this._queue.push({start:n.start,end:n.end,stream:t,last:r===e.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),t}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e))}},Lr={};(function(e){const n=t({});class r{constructor(e,t){this._entries=e,this._countName=t||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}Lr=class extends d{constructor(e){super(),this._tracks=[],this._file=e,this._decoder=null,this._findMoov(0)}_findMoov(e){this._decoder&&this._decoder.destroy();let t=0;this._decoder=Tr.decode();const n=this._file.createReadStream({start:e});n.pipe(this._decoder);const r=i=>{"moov"===i.type?(this._decoder.removeListener("box",r),this._decoder.decode(e=>{n.destroy();try{this._processMoov(e)}catch(li){li.message=`Cannot parse mp4 file: ${li.message}`,this.emit("error",li)}})):i.length<4096?(t+=i.length,this._decoder.ignore()):(this._decoder.removeListener("box",r),t+=i.length,n.destroy(),this._decoder.destroy(),this._findMoov(e+t))};this._decoder.on("box",r)}_processMoov(t){const i=t.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let e=0;e=o.stsz.entries.length)break;if(g+=e,++f>=s.samplesPerChunk){f=0,g=0,p++;const e=o.stsc.entries[m+1];e&&p+1>=e.firstChunk&&m++}_+=t,y.inc(),b&&b.inc(),r&&w++}n.mdia.mdhd.duration=0,n.tkhd.duration=0;const v=s.sampleDescriptionId,E={type:"moov",mvhd:t.mvhd,traks:[{tkhd:n.tkhd,mdia:{mdhd:n.mdia.mdhd,hdlr:n.mdia.hdlr,elng:n.mdia.elng,minf:{vmhd:n.mdia.minf.vmhd,smhd:n.mdia.minf.smhd,dinf:n.mdia.minf.dinf,stbl:{stsd:o.stsd,stts:{version:0,flags:0,entries:[]},ctts:{version:0,flags:0,entries:[]},stsc:{version:0,flags:0,entries:[]},stsz:{version:0,flags:0,entries:[]},stco:{version:0,flags:0,entries:[]},stss:{version:0,flags:0,entries:[]}}}}}],mvex:{mehd:{fragmentDuration:t.mvhd.duration},trexs:[{trackId:n.tkhd.trackId,defaultSampleDescriptionIndex:v,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:n.tkhd.trackId,timeScale:n.mdia.mdhd.timeScale,samples:d,currSample:null,currTime:null,moov:E,mime:u})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));t.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const o=n.encode(this._ftyp),a=this._tracks.map(t=>{const r=n.encode(t.moov);return{mime:t.mime,init:e.concat([o,r])}});this.emit("ready",a)}seek(e){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let t=-1;if(this._tracks.map((n,r)=>{n.outStream&&n.outStream.destroy(),n.inStream&&(n.inStream.destroy(),n.inStream=null);const i=n.outStream=Tr.encode(),s=this._generateFragment(r,e);if(!s)return i.finalize();(-1===t||s.ranges[0].start{i.destroyed||i.box(e.moof,t=>{if(t)return this.emit("error",t);i.destroyed||n.inStream.slice(e.ranges).pipe(i.mediaData(e.length,e=>{if(e)return this.emit("error",e);if(i.destroyed)return;const t=this._generateFragment(r);if(!t)return i.finalize();o(t)}))})};o(s)}),t>=0){const e=this._fileStream=this._file.createReadStream({start:t});this._tracks.forEach(n=>{n.inStream=new Rr(t,{highWaterMark:1e7}),e.pipe(n.inStream)})}return this._tracks.map(e=>e.outStream)}_findSampleBefore(e,t){const n=this._tracks[e],r=Math.floor(n.timeScale*t);let i=function(e,t,n,r,i){var s,o;if(void 0===r)r=0;else if((r|=0)<0||r>=e.length)throw new RangeError("invalid lower bound");if(void 0===i)i=e.length-1;else if((i|=0)=e.length)throw new RangeError("invalid upper bound");for(;r<=i;)if((o=+n(e[s=r+(i-r>>>1)],t,s,e))<0)r=s+1;else{if(!(o>0))return s;i=s-1}return~r}(n.samples,r,(e,t)=>e.dts+e.presentationOffset-t);for(-1===i?i=0:i<0&&(i=-i-2);!n.samples[i].sync;)i--;return i}_generateFragment(e,t){const n=this._tracks[e];let r;if((r=void 0!==t?this._findSampleBefore(e,t):n.currSample)>=n.samples.length)return null;const i=n.samples[r].dts;let s=0;const o=[];for(var a=r;a=1*n.timeScale)break;s+=e.size;const t=o.length-1;t<0||o[t].end!==e.offset?o.push({start:e.offset,end:e.offset+e.size}):o[t].end+=e.size}return n.currSample=a,{moof:this._generateMoof(e,r,a),ranges:o,length:s}}_generateMoof(e,t,r){const i=this._tracks[e],s=[];let o=0;for(let n=t;n{this.detailedError=this._elemWrapper.detailedError,this.destroy()}),this._onWaiting=(()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()}),t.autoplay&&(t.preload="auto"),t.addEventListener("waiting",this._onWaiting),t.addEventListener("error",this._onError)}Ur.prototype={_createMuxer(){this._muxer=new Lr(this._file),this._muxer.on("ready",e=>{this._tracks=e.map(e=>{const t=this._elemWrapper.createWriteStream(e.mime);t.on("error",e=>{this._elemWrapper.error(e)});const n={muxed:null,mediaSource:t,initFlushed:!1,onInitFlushed:null};return t.write(e.init,e=>{n.initFlushed=!0,n.onInitFlushed&&n.onInitFlushed(e)}),n}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",e=>{this._elemWrapper.error(e)})},_pump(){const e=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((t,n)=>{const r=()=>{t.muxed&&(t.muxed.destroy(),t.mediaSource=this._elemWrapper.createWriteStream(t.mediaSource),t.mediaSource.on("error",e=>{this._elemWrapper.error(e)})),t.muxed=e[n],ar(t.muxed,t.mediaSource)};t.initFlushed?r():t.onInitFlushed=(e=>{e?this._elemWrapper.error(e):r()})})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(e=>{e.muxed&&e.muxed.destroy()}),this._elem.src="")}},Br=Ur;var Or={render:function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n||(n={}),r||(r=function(){}),Gr(e),Kr(n),"string"==typeof t&&(t=document.querySelector(t)),$r(e,function(r){if(t.nodeName!==r.toUpperCase()){var i=et.extname(e.name).toLowerCase();throw new Error('Cannot render "'+i+'" inside a "'+t.nodeName.toLowerCase()+'" element, expected "'+r+'"')}return"video"!==r&&"audio"!==r||Yr(t,n),t},n,r)},append:function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),n||(n={}),r||(r=function(){}),Gr(e),Kr(n),"string"==typeof t&&(t=document.querySelector(t)),t&&("VIDEO"===t.nodeName||"AUDIO"===t.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");function i(e){var n=document.createElement(e);return t.appendChild(n),n}$r(e,function(e){return"video"===e||"audio"===e?function(e){var r=i(e);return Yr(r,n),t.appendChild(r),r}(e):i(e)},n,function(e,t){e&&t&&t.remove(),r(e,t)})},mime:{".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},Mr=Nt("render-media"),Pr=[".m4a",".m4b",".m4p",".m4v",".mp4"],Nr=[".m4v",".mkv",".mp4",".webm"],jr=[].concat(Nr,[".m4a",".m4b",".m4p",".mp3"]),Hr=[".mov",".ogv"],Dr=[".aac",".oga",".ogg",".wav",".flac"],qr=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],Fr=[".css",".html",".js",".md",".pdf",".txt"],Wr=2e8,zr="undefined"!=typeof window&&window.MediaSource;function $r(e,t,n,r){var i,s=et.extname(e.name).toLowerCase(),o=0;function a(){return!("number"==typeof e.length&&e.length>n.maxBlobLength&&(Mr("File length too large for Blob URL approach: %d (max: %d)",e.length,n.maxBlobLength),l(new Error("File length too large for Blob URL approach: "+e.length+" (max: "+n.maxBlobLength+")")),1))}function h(n){a()&&(i=t(n),Vr(e,function(e,t){if(e)return l(e);i.addEventListener("error",l),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),i.src=t}))}function c(){i.removeEventListener("loadstart",c),n.autoplay&&i.play()}function u(){i.removeEventListener("canplay",u),r(null,i)}function d(){Vr(e,function(e,n){if(e)return l(e);".pdf"!==s?((i=t("iframe")).sandbox="allow-forms allow-scripts",i.src=n):((i=t("object")).setAttribute("typemustmatch",!0),i.setAttribute("type","application/pdf"),i.setAttribute("data",n)),r(null,i)})}function l(t){t.message='Error rendering file "'+e.name+'": '+t.message,Mr(t.message),r(t)}jr.indexOf(s)>=0?function(){var n=Nr.indexOf(s)>=0?"video":"audio";function r(){Mr("Use MediaSource API for "+e.name),f(),i.addEventListener("error",d),i.addEventListener("loadstart",c),i.addEventListener("canplay",u);var t,n=new lr(i).createWriteStream((t=e.name,{".m4a":'audio/mp4; codecs="mp4a.40.5"',".m4b":'audio/mp4; codecs="mp4a.40.5"',".m4p":'audio/mp4; codecs="mp4a.40.5"',".m4v":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".mkv":'video/webm; codecs="avc1.640029, mp4a.40.5"',".mp3":"audio/mpeg",".mp4":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".webm":'video/webm; codecs="vorbis, vp8"'}[et.extname(t).toLowerCase()]));e.createReadStream().pipe(n),o&&(i.currentTime=o)}function h(){Mr("Use Blob URL for "+e.name),f(),i.addEventListener("error",l),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),Vr(e,function(e,t){if(e)return l(e);i.src=t,o&&(i.currentTime=o)})}function d(e){Mr("MediaSource API error: fallback to Blob URL: %o",e.message||e),a()&&(i.removeEventListener("error",d),i.removeEventListener("canplay",u),h())}function f(){i||(i=t(n)).addEventListener("progress",function(){o=i.currentTime})}zr?Pr.indexOf(s)>=0?(Mr("Use `videostream` package for "+e.name),f(),i.addEventListener("error",function e(t){Mr("videostream error: fallback to MediaSource API: %o",t.message||t),i.removeEventListener("error",e),i.removeEventListener("canplay",u),r()}),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),Br(e,i)):r():h()}():Hr.indexOf(s)>=0?h("video"):Dr.indexOf(s)>=0?h("audio"):qr.indexOf(s)>=0?(i=t("img"),Vr(e,function(t,n){if(t)return l(t);i.src=n,i.alt=e.name,r(null,i)})):Fr.indexOf(s)>=0?d():function(){Mr('Unknown file extension "%s" - will attempt to render into iframe',s);var t="";e.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",function(e){t+=e}).on("end",function(){ur(t)?(Mr('File extension "%s" appears ascii, so will render.',s),d()):(Mr('File extension "%s" appears non-ascii, will not render.',s),r(new Error('Unsupported file type "'+s+'": Cannot append to DOM')))}).on("error",r)}()}function Vr(e,t){var n=et.extname(e.name).toLowerCase();yr(e.createReadStream(),Or.mime[n]).then(e=>t(null,e),e=>t(e))}function Gr(e){if(null==e)throw new Error("file cannot be null or undefined");if("string"!=typeof e.name)throw new Error("missing or invalid file.name property");if("function"!=typeof e.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function Kr(e){null==e.autoplay&&(e.autoplay=!1),null==e.muted&&(e.muted=!1),null==e.controls&&(e.controls=!0),null==e.maxBlobLength&&(e.maxBlobLength=Wr)}function Yr(e,t){e.autoplay=!!t.autoplay,e.muted=!!t.muted,e.controls=!!t.controls}var Jr={};(function(e){Jr=function(t,n,r){r=wt(r);var i=e.alloc(n),s=0;t.on("data",function(e){e.copy(i,s),s+=e.length}).on("end",function(){r(null,i)}).on("error",r)}}).call(this,u({}).Buffer);const Xr=Nt("webtorrent:file-stream");var Zr=class extends Ze.Readable{constructor(e,t){super(t),this.destroyed=!1,this._torrent=e._torrent;const n=t&&t.start||0,r=t&&t.end&&t.end{if(this._notifying=!1,!this.destroyed){if(Xr("read %s (length %s) (err %s)",e,n.length,t&&t.message),t)return this._destroy(t);this._offset&&(n=n.slice(this._offset),this._offset=0),this._missing{t.end()}),t}const r=new Zr(this,t);return this._torrent.select(r._startPiece,r._endPiece,!0,()=>{r._notify()}),or(r,()=>{this._destroyed||this._torrent.destroyed||this._torrent.deselect(r._startPiece,r._endPiece,!0)}),r}getBuffer(e){Jr(this.createReadStream(),this.length,e)}getBlob(e){if("undefined"==typeof window)throw new Error("browser-only method");_r(this.createReadStream(),this._getMimeType()).then(t=>e(null,t),t=>e(t))}getBlobURL(e){if("undefined"==typeof window)throw new Error("browser-only method");yr(this.createReadStream(),this._getMimeType()).then(t=>e(null,t),t=>e(t))}appendTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");Or.append(this,e,t,n)}renderTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");Or.render(this,e,t,n)}_getMimeType(){return Or.mime[et.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}}).call(this,ce);var ei=function(e,t){if(!(t>=e.length||t<0)){var n=e.pop();if(t{this.keepAlive()},55e3))}setTimeout(e,t){this._debug("setTimeout ms=%d unref=%s",e,t),this._clearTimeout(),this._timeoutMs=e,this._timeoutUnref=!!t,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...e){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...e)}use(e){const t=e.prototype.name;if(!t)throw new Error('Extension class requires a "name" property on the prototype');this._debug("use extension.name=%s",t);const n=this._nextExt,r=new e(this);function i(){}"function"!=typeof r.onHandshake&&(r.onHandshake=i),"function"!=typeof r.onExtendedHandshake&&(r.onExtendedHandshake=i),"function"!=typeof r.onMessage&&(r.onMessage=i),this.extendedMapping[n]=t,this._ext[t]=r,this[t]=r,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(r)}handshake(t,r,i){let s,o;if("string"==typeof t?(t=t.toLowerCase(),s=e.from(t,"hex")):t=(s=t).toString("hex"),"string"==typeof r?o=e.from(r,"hex"):r=(o=r).toString("hex"),20!==s.length||20!==o.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",t,r,i);const a=e.from(h);a[5]|=16,i&&i.dht&&(a[7]|=1),this._push(e.concat([n,a,s,o])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const e=Object.assign({},this.extendedHandshake);e.m={};for(const t in this.extendedMapping){const n=this.extendedMapping[t];e.m[n]=Number(t)}this.extended(0,Z.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(i)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(s))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(o))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(a))}have(e){this._debug("have %d",e),this._message(4,[e],null)}bitfield(t){this._debug("bitfield"),e.isBuffer(t)||(t=t.buffer),this._message(5,[],t)}request(e,t,n,r){return r||(r=(()=>{})),this._finished?r(new Error("wire is closed")):this.peerChoking?r(new Error("peer is choking")):(this._debug("request index=%d offset=%d length=%d",e,t,n),this.requests.push(new u(e,t,n,r)),this._updateTimeout(),void this._message(6,[e,t,n],null))}piece(e,t,n){this._debug("piece index=%d offset=%d",e,t),this.uploaded+=n.length,this.uploadSpeed(n.length),this.emit("upload",n.length),this._message(7,[e,t],n)}cancel(e,t,n){this._debug("cancel index=%d offset=%d length=%d",e,t,n),this._callback(this._pull(this.requests,e,t,n),new Error("request was cancelled"),null),this._message(8,[e,t,n],null)}port(t){this._debug("port %d",t);const n=e.from(c);n.writeUInt16BE(t,5),this._push(n)}extended(t,n){if(this._debug("extended ext=%s",t),"string"==typeof t&&this.peerExtendedMapping[t]&&(t=this.peerExtendedMapping[t]),"number"!=typeof t)throw new Error(`Unrecognized extension: ${t}`);{const r=e.from([t]),i=e.isBuffer(n)?n:Z.encode(n);this._message(20,[],e.concat([r,i]))}}_read(){}_message(t,n,r){const i=r?r.length:0,s=e.allocUnsafe(5+4*n.length);s.writeUInt32BE(s.length+i-4,0),s[4]=t;for(let e=0;e{if(i===this._pull(this.peerRequests,e,t,n))return r?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,n,r.message):void this.piece(e,t,s)};var i=new u(e,t,n,r);this.peerRequests.push(i),this.emit("request",e,t,n,r)}_onPiece(e,t,n){this._debug("got piece index=%d offset=%d",e,t),this._callback(this._pull(this.requests,e,t,n.length),null,n),this.downloaded+=n.length,this.downloadSpeed(n.length),this.emit("download",n.length),this.emit("piece",e,t,n)}_onCancel(e,t,n){this._debug("got cancel index=%d offset=%d length=%d",e,t,n),this._pull(this.peerRequests,e,t,n),this.emit("cancel",e,t,n)}_onPort(e){this._debug("got port %d",e),this.emit("port",e)}_onExtended(e,t){if(0===e){let e,n;try{e=Z.decode(t)}catch(li){this._debug("ignoring invalid extended handshake: %s",li.message||li)}if(!e)return;if(this.peerExtendedHandshake=e,"object"==typeof e.m)for(n in e.m)this.peerExtendedMapping[n]=Number(e.m[n].toString());for(n in this._ext)this.peerExtendedMapping[n]&&this._ext[n].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[e]&&(e=this.extendedMapping[e],this._ext[e]&&this._ext[e].onMessage(t)),this._debug("got extended message ext=%s",e),this.emit("extended",e,t)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(t,n,r){for(this._bufferSize+=t.length,this._buffer.push(t);this._bufferSize>=this._parserSize;){const t=1===this._buffer.length?this._buffer[0]:e.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[t.slice(this._parserSize)]:[],this._parser(t.slice(0,this._parserSize))}r(null)}_callback(e,t,n){e&&(this._clearTimeout(),this.peerChoking||this._finished||this._updateTimeout(),e.callback(t,n))}_clearTimeout(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_updateTimeout(){this._timeoutMs&&this.requests.length&&!this._timeout&&(this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref())}_parse(e,t){this._parserSize=e,this._parser=t}_onMessageLength(e){const t=e.readUInt32BE(0);t>0?this._parse(t,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(e){switch(this._parse(4,this._onMessageLength),e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",e)}}_parseHandshake(){this._parse(1,e=>{const t=e.readUInt8(0);this._parse(t+48,e=>{const n=e.slice(0,t);if("BitTorrent protocol"!==n.toString())return this._debug("Error: wire not speaking BitTorrent protocol (%s)",n.toString()),void this.end();e=e.slice(t),this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(1&e[7]),extended:!!(16&e[5])}),this._parse(4,this._onMessageLength)})})}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...e){e[0]=`[${this._debugId}] ${e[0]}`,t(...e)}_pull(e,t,n,r){for(let i=0;i{if(this.destroyed)return;this.handshake(e,this.webPeerId);const n=this._torrent.pieces.length,r=new Nn(n);for(let i=0;i<=n;i++)r.set(i,!0);this.bitfield(r)}),this.once("interested",()=>{t("interested"),this.unchoke()}),this.on("uninterested",()=>{t("uninterested")}),this.on("choke",()=>{t("choke")}),this.on("unchoke",()=>{t("unchoke")}),this.on("bitfield",()=>{t("bitfield")}),this.on("request",(e,n,r,i)=>{t("request pieceIndex=%d offset=%d length=%d",e,n,r),this.httpRequest(e,n,r,i)})}httpRequest(r,i,s,o){const a=r*this._torrent.pieceLength+i,h=a+s-1,c=this._torrent.files;let u;if(c.length<=1)u=[{url:this.url,start:a,end:h}];else{const e=c.filter(e=>e.offset<=h&&e.offset+e.length>a);if(e.length<1)return o(new Error("Could not find file corresponnding to web seed range request"));u=e.map(e=>{const t=e.offset+e.length-1;return{url:this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path,fileOffsetInRange:Math.max(e.offset-a,0),start:Math.max(a-e.offset,0),end:Math.min(t,h-e.offset)}})}let d,l=0,f=!1;u.length>1&&(d=e.alloc(s)),u.forEach(e=>{const a=e.url,h=e.start,c=e.end;t("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",a,r,i,s,h,c);const p={url:a,method:"GET",headers:{"user-agent":`WebTorrent/${n} (https://webtorrent.io)`,range:`bytes=${h}-${c}`}};function g(n,r){if(n.statusCode<200||n.statusCode>=300)return f=!0,o(new Error(`Unexpected HTTP status code ${n.statusCode}`));t("Got data of length %d",r.length),1===u.length?o(null,r):(r.copy(d,e.fileOffsetInRange),++l===u.length&&o(null,d))}wn.concat(p,(e,t,n)=>{if(!f)return e?"undefined"==typeof window||a.startsWith(`${window.location.origin}/`)?(f=!0,o(e)):wn.head(a,(t,n)=>{if(!f){if(t)return f=!0,o(t);if(n.statusCode<200||n.statusCode>=300)return f=!0,o(new Error(`Unexpected HTTP status code ${n.statusCode}`));if(n.url===a)return f=!0,o(e);p.url=n.url,wn.concat(p,(e,t,n)=>{if(!f)return e?(f=!0,o(e)):void g(t,n)})}}):void g(t,n)})})}destroy(){super.destroy(),this._torrent=null}}}).call(this,u({}).Buffer);var ii={};const si=Nt("webtorrent:peer"),oi=5e3,ai=25e3,hi=25e3;ii.createWebRTCPeer=((e,t)=>{const n=new ci(e.id,"webrtc");return n.conn=e,n.swarm=t,n.conn.connected?n.onConnect():(n.conn.once("connect",()=>{n.onConnect()}),n.conn.once("error",e=>{n.destroy(e)}),n.startConnectTimeout()),n}),ii.createTCPOutgoingPeer=((e,t)=>{const n=new ci(e,"tcpOutgoing");return n.addr=e,n.swarm=t,n}),ii.createWebSeedPeer=((e,t)=>{const n=new ci(e,"webSeed");return n.swarm=t,n.conn=new ri(e,t),n.onConnect(),n});class ci{constructor(e,t){this.id=e,this.type=t,si("new %s Peer %s",t,e),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentHandshake=!1}onConnect(){if(this.destroyed)return;this.connected=!0,si("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const e=this.conn;e.once("end",()=>{this.destroy()}),e.once("close",()=>{this.destroy()}),e.once("finish",()=>{this.destroy()}),e.once("error",e=>{this.destroy(e)});const t=this.wire=new ti;t.type=this.type,t.once("end",()=>{this.destroy()}),t.once("close",()=>{this.destroy()}),t.once("finish",()=>{this.destroy()}),t.once("error",e=>{this.destroy(e)}),t.once("handshake",(e,t)=>{this.onHandshake(e,t)}),this.startHandshakeTimeout(),e.pipe(t).pipe(e),this.swarm&&!this.sentHandshake&&this.handshake()}onHandshake(e,t){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(e!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(t===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));si("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let n=this.addr;!n&&this.conn.remoteAddress&&this.conn.remotePort&&(n=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,n),this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout),this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},"webrtc"===this.type?ai:oi),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout(()=>{this.destroy(new Error("handshake timeout"))},hi),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,si("destroy %s (error: %s)",this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,n=this.conn,r=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&r&&ei(t.wires,t.wires.indexOf(r)),n&&(n.on("error",()=>{}),n.destroy()),r&&r.destroy(),t&&t.removePeer(this.id)}}var ui={};(function(e,t){const n=Nt("webtorrent:torrent"),r=d.EventEmitter,i=3*rr.BLOCK_LENGTH,s=e.browser?1/0:2,o=[1e3,5e3,15e3],a=`WebTorrent/${ni} (https://webtorrent.io)`;let h;try{h=et.join(ut.statSync("/tmp")&&"/tmp","webtorrent")}catch(li){h=et.join("function"==typeof te.tmpdir?te.tmpdir():"/","webtorrent")}function c(e,t){return 2+Math.ceil(t*e.downloadSpeed()/rr.BLOCK_LENGTH)}function u(){}ui=class extends r{constructor(e,t,n){super(),this._debugId="unknown infohash",this.client=t,this.announce=n.announce,this.urlList=n.urlList,this.path=n.path,this.skipVerify=!!n.skipVerify,this._store=n.store||er,this._getAnnounceOpts=n.getAnnounceOpts,this.strategy=n.strategy||"sequential",this.maxWebConns=n.maxWebConns||4,this._rechokeNumSlots=!1===n.uploads||0===n.uploads?0:+n.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=!1,this.done=!1,this.metadata=null,this.store=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=Bn(),this._uploadSpeed=Bn(),this._servers=[],this._xsRequests=[],this._fileModtimes=n.fileModtimes,null!==e&&this._onTorrentId(e),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:(this.length-this.downloaded)/this.downloadSpeed*1e3}get downloaded(){if(!this.bitfield)return 0;let e=0;for(let t=0,n=this.pieces.length;t{this.destroyed||this._onParsedTorrent(n)})):Cn.remote(t,(e,t)=>{if(!this.destroyed)return e?this._destroy(e):void this._onParsedTorrent(t)})}_onParsedTorrent(e){if(!this.destroyed){if(this._processParsedTorrent(e),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));this.path||(this.path=et.join(h,this.infoHash)),this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),this.destroyed||(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(e){this._debugId=e.infoHash.toString("hex").substring(0,7),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&t.WEBTORRENT_ANNOUNCE&&!this.private&&(e.announce=e.announce.concat(t.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),kn(e.announce),kn(e.urlList),Object.assign(this,e),this.magnetURI=Cn.toMagnetURI(e),this.torrentFile=Cn.toTorrentFile(e)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let e=this.client.tracker;e&&(e=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const e={uploaded:this.uploaded,downloaded:this.downloaded,left:Math.max(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(e,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(e,this._getAnnounceOpts()),e}})),this.discovery=new Qn({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:a}),this.discovery.on("error",e=>{this._destroy(e)}),this.discovery.on("peer",e=>{"string"==typeof e&&this.done||this.addPeer(e)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",e=>{this.emit("warning",e)})}_getMetadataFromServer(){const e=this,t=(Array.isArray(this.xs)?this.xs:[this.xs]).map(t=>n=>{!function(t,n){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),n(null);const r={url:t,method:"GET",headers:{"user-agent":a}};let i;try{i=wn.concat(r,function(r,i,s){if(e.destroyed)return n(null);if(e.metadata)return n(null);if(r)return e.emit("warning",new Error(`http error from xs param: ${t}`)),n(null);if(200!==i.statusCode)return e.emit("warning",new Error(`non-200 status code ${i.statusCode} from xs param: ${t}`)),n(null);let o;try{o=Cn(s)}catch(r){}return o?o.infoHash!==e.infoHash?(e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),n(null)):(e._onMetadata(o),void n(null)):(e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),n(null))})}catch(li){return e.emit("warning",new Error(`skipping invalid url xs param: ${t}`)),n(null)}e._xsRequests.push(i)}(t,n)});kt(t)}_onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequests.forEach(e=>{e.abort()}),this._xsRequests=[],e&&e.infoHash)t=e;else try{t=Cn(e)}catch(li){return this._destroy(li)}if(this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(e=>{this.addWebSeed(e)}),this._rarityMap=new class{constructor(e){this._torrent=e,this._numPieces=e.pieces.length,this._pieces=new Array(this._numPieces),this._onWire=(e=>{this.recalculate(),this._initWire(e)}),this._onWireHave=(e=>{this._pieces[e]+=1}),this._onWireBitfield=(()=>{this.recalculate()}),this._torrent.wires.forEach(e=>{this._initWire(e)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(e){let t=[],n=1/0;for(let r=0;r{this._cleanupWireEvents(e)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(e){e._onClose=(()=>{this._cleanupWireEvents(e);for(let t=0;t({path:et.join(this.path,e.path),length:e.length,offset:e.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(e=>new Qr(this,e)),this.so){const e=cr.parse(this.so);this.files.forEach((t,n)=>{e.includes(n)&&this.files[n].select(!0)})}else 0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1);if(this._hashes=this.pieces,this.pieces=this.pieces.map((e,t)=>{const n=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new rr(n)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new Nn(this.pieces.length),this.wires.forEach(e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)}),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const e=e=>{if(e)return this._destroy(e);this._debug("done verifying"),this._onStore()};this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===er?this.getFileModtimes((t,n)=>{if(t)return this._destroy(t);this.files.map((e,t)=>n[t]===this._fileModtimes[t]).every(e=>e)?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)}):this._verifyPieces(e)}}getFileModtimes(e){const t=[];nr(this.files.map((e,n)=>r=>{ut.stat(et.join(this.path,e.path),(e,i)=>{if(e&&"ENOENT"!==e.code)return r(e);t[n]=i&&i.mtime.getTime(),r(null)})}),s,n=>{this._debug("done getting file modtimes"),e(n,t)})}_verifyPieces(t){nr(this.pieces.map((t,n)=>t=>{if(this.destroyed)return t(new Error("torrent is destroyed"));this.store.get(n,(r,i)=>this.destroyed?t(new Error("torrent is destroyed")):r?e.nextTick(t,null):void Rt(i,e=>{if(this.destroyed)return t(new Error("torrent is destroyed"));if(e===this._hashes[n]){if(!this.pieces[n])return t(null);this._debug("piece verified %s",n),this._markVerified(n)}else this._debug("piece invalid %s",n);t(null)}))}),s,t)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=u),this._verifyPieces(t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)})}_markAllVerified(){for(let e=0;e{e.abort()}),this._rarityMap&&this._rarityMap.destroy();for(const r in this._peers)this.removePeer(r);this.files.forEach(e=>{e instanceof Qr&&e._destroy()});const n=this._servers.map(e=>t=>{e.destroy(t)});this.discovery&&n.push(e=>{this.discovery.destroy(e)}),this.store&&n.push(e=>{this.store.close(e)}),kt(n,t),e&&(0===this.listenerCount("error")?this.client.emit("error",e):this.emit("error",e)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}addPeer(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let t;if("string"==typeof e){let r;try{r=Un(e)}catch(n){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}t=r[0]}else"string"==typeof e.remoteAddress&&(t=e.remoteAddress);if(t&&this.client.blocked.contains(t))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const t=!!this._addPeer(e);return t?this.emit("peer",e):this.emit("invalidPeer",e),t}_addPeer(e){if(this.destroyed)return"string"!=typeof e&&e.destroy(),null;if("string"==typeof e&&!this._validAddr(e))return this._debug("ignoring peer: invalid %s",e),null;const t=e&&e.id||e;if(this._peers[t])return this._debug("ignoring peer: duplicate (%s)",t),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let n;return this._debug("add peer %s",t),n="string"==typeof e?ii.createTCPOutgoingPeer(e,this):ii.createWebRTCPeer(e,this),this._peers[n.id]=n,this._peersLength+=1,"string"==typeof e&&(this._queue.push(n),this._drain()),n}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(e))return this.emit("warning",new Error(`ignoring invalid web seed: ${e}`)),void this.emit("invalidPeer",e);if(this._peers[e])return this.emit("warning",new Error(`ignoring duplicate web seed: ${e}`)),void this.emit("invalidPeer",e);this._debug("add web seed %s",e);const t=ii.createWebSeedPeer(e,this);this._peers[t.id]=t,this._peersLength+=1,this.emit("peer",e)}_addIncomingPeer(e){return this.destroyed?e.destroy(new Error("torrent is destroyed")):this.paused?e.destroy(new Error("torrent is paused")):(this._debug("add incoming peer %s",e.id),this._peers[e.id]=e,void(this._peersLength+=1))}removePeer(e){const t=e&&e.id||e;(e=this._peers[t])&&(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,e.destroy(),this._drain())}select(e,t,n,r){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||tt.priority-e.priority),this._updateSelections()}deselect(e,t,n){if(this.destroyed)throw new Error("torrent is destroyed");n=Number(n)||0,this._debug("deselect %s-%s (priority %s)",e,t,n);for(let r=0;r{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.client.emit("download",e))}),t.on("upload",e=>{this.destroyed||(this.uploaded+=e,this._uploadSpeed(e),this.client._uploadSpeed(e),this.emit("upload",e),this.client.emit("upload",e))}),this.wires.push(t),n){const e=Un(n);t.remoteAddress=e[0],t.remotePort=e[1]}this.client.dht&&this.client.dht.listening&&t.on("port",e=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!t.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===e||e>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",e,n),this.client.dht.addNode({host:t.remoteAddress,port:e})}}),t.on("timeout",()=>{this._debug("wire timeout (%s)",n),t.destroy()}),t.setTimeout(3e4,!0),t.setKeepAlive(!0),t.use(hr(this.metadata)),t.ut_metadata.on("warning",e=>{this._debug("ut_metadata warning: %s",e.message)}),this.metadata||(t.ut_metadata.on("metadata",e=>{this._debug("got metadata via ut_metadata"),this._onMetadata(e)}),t.ut_metadata.fetch()),"function"!=typeof te||this.private||(t.use(te()),t.ut_pex.on("peer",e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,n),this.addPeer(e))}),t.ut_pex.on("dropped",e=>{const t=this._peers[e];t&&!t.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,n),this.removePeer(e))}),t.once("close",()=>{t.ut_pex.reset()})),this.emit("wire",t,n),this.metadata&&e.nextTick(()=>{this._onWireWithMetadata(t)})}_onWireWithMetadata(e){let t=null;const n=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(n,5e3)).unref&&t.unref())};let r;const i=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(r=0;r{i(),this._update()}),e.on("have",()=>{i(),this._update()}),e.once("interested",()=>{e.unchoke()}),e.once("close",()=>{clearTimeout(t)}),e.on("choke",()=>{clearTimeout(t),(t=setTimeout(n,5e3)).unref&&t.unref()}),e.on("unchoke",()=>{clearTimeout(t),this._update()}),e.on("request",(t,n,r,i)=>{if(r>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:n,length:r},i)}),e.bitfield(this.bitfield),e.uninterested(),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(n,5e3)).unref&&t.unref(),e.isSeeder=!1,i()}_updateSelections(){this.ready&&!this.destroyed&&(e.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;e{let t=!1;for(let n=0;n=r.from+r.offset;--i)if(e.peerPieces.get(i)&&t._request(e,i,!1))return}}();const n=c(e,.5);if(e.requests.length>=n)return;const r=c(e,1);function s(t,n,r,i){return s=>s>=t&&s<=n&&!(s in r)&&e.peerPieces.get(s)&&(!i||i(s))}function o(e){let n=e;for(let i=e;i=r)return!0;const a=function(){const n=e.downloadSpeed()||1;if(n>i)return()=>!0;const r=Math.max(1,e.requests.length)*rr.BLOCK_LENGTH/n;let s=10,o=0;return e=>{if(!s||t.bitfield.get(e))return!0;let a=t.pieces[e].missing;for(;o0))return s--,!1}return!0}}();for(let i=0;i0?this._rechokeOptimisticTime-=1:this._rechokeOptimisticWire=null;const e=[];this.wires.forEach(t=>{t.isSeeder||t===this._rechokeOptimisticWire||e.push({wire:t,downloadSpeed:t.downloadSpeed(),uploadSpeed:t.uploadSpeed(),salt:Math.random(),isChoked:!0})}),e.sort(function(e,t){return e.downloadSpeed!==t.downloadSpeed?t.downloadSpeed-e.downloadSpeed:e.uploadSpeed!==t.uploadSpeed?t.uploadSpeed-e.uploadSpeed:e.wire.amChoking!==t.wire.amChoking?e.wire.amChoking?1:-1:e.salt-t.salt});let t=0,n=0;for(;ne.wire.peerInterested),i=t[(r=t.length,Math.random()*r|0)];i&&(i.isChoked=!1,this._rechokeOptimisticWire=i.wire,this._rechokeOptimisticTime=2)}var r;e.forEach(e=>{e.wire.amChoking!==e.isChoked&&(e.isChoked?e.wire.choke():e.wire.unchoke())})}_hotswap(e,t){const n=e.downloadSpeed();if(n=i||2*h>n||h>a||(s=t,a=h)}if(!s)return!1;for(o=0;o=(o?Math.min(function(e,t,n){return 1+Math.ceil(1*e.downloadSpeed()/n)}(t,0,i.pieceLength),i.maxWebConns):c(t,1)))return!1;const a=i.pieces[n];let h=o?a.reserveRemaining():a.reserve();if(-1===h&&r&&i._hotswap(t,n)&&(h=o?a.reserveRemaining():a.reserve()),-1===h)return!1;let u=i._reservations[n];u||(u=i._reservations[n]=[]);let d=u.indexOf(null);-1===d&&(d=u.length),u[d]=t;const l=a.chunkOffset(h),f=o?a.chunkLengthRemaining(h):a.chunkLength(h);function p(){e.nextTick(()=>{i._update()})}return t.request(n,l,f,function e(r,s){if(i.destroyed)return;if(!i.ready)return i.once("ready",()=>{e(r,s)});if(u[d]===t&&(u[d]=null),a!==i.pieces[n])return p();if(r)return i._debug("error getting piece %s (offset: %s length: %s) from %s: %s",n,l,f,`${t.remoteAddress}:${t.remotePort}`,r.message),o?a.cancelRemaining(h):a.cancel(h),void p();if(i._debug("got piece %s (offset: %s length: %s) from %s",n,l,f,`${t.remoteAddress}:${t.remotePort}`),!a.set(h,s,t))return p();const c=a.flush();Rt(c,e=>{if(!i.destroyed){if(e===i._hashes[n]){if(!i.pieces[n])return;i._debug("piece verified %s",n),i.pieces[n]=null,i._reservations[n]=null,i.bitfield.set(n,!0),i.store.put(n,c),i.wires.forEach(e=>{e.have(n)}),i._checkDone()&&!i.destroyed&&i.discovery.complete()}else i.pieces[n]=new rr(a.length),i.emit("warning",new Error(`Piece ${n} failed verification`));p()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(e=>{if(!e.done){for(let t=e._startPiece;t<=e._endPiece;++t)if(!this.bitfield.get(t))return;e.done=!0,e.emit("done"),this._debug(`file done: ${e.name}`)}});let e=!0;for(let t=0;t{this.load(e,t)});Array.isArray(e)||(e=[e]),t||(t=u);const n=new pt(e),r=new Hn(this.store,this.pieceLength);ar(n,r,e=>{if(e)return t(e);this._markAllVerified(),this._checkDone(),t(null)})}createServer(e){if("function"!=typeof te)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const t=new te(this,e);return this._servers.push(t),t}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const e=[].slice.call(arguments);e[0]=`[${this.client._debugId}] [${this._debugId}] ${e[0]}`,n(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof te.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const e=this._queue.shift();if(!e)return;this._debug("tcp connect attempt to %s",e.addr);const t=Un(e.addr),n={host:t[0],port:t[1]},r=e.conn=te.connect(n);r.once("connect",()=>{e.onConnect()}),r.once("error",t=>{e.destroy(t)}),e.startConnectTimeout(),r.on("close",()=>{if(this.destroyed)return;if(e.retries>=o.length)return void this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,o.length);const t=o[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const n=setTimeout(()=>{const t=this._addPeer(e.addr);t&&(t.retries=e.retries+1)},t);n.unref&&n.unref()})}_validAddr(e){let t;try{t=Un(e)}catch(i){return!1}const n=t[0],r=t[1];return r>0&&r<65535&&!("127.0.0.1"===n&&r===this.client.torrentPort)}}}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var di={};return function(e,t,n){const{EventEmitter:r}=d,i=Nt("webtorrent"),s=ni,o=s.replace(/\d*./g,e=>`0${e%100}`.slice(-2)).slice(0,4),a=`-WW${o}-`;class h extends r{constructor(r={}){super(),"string"==typeof r.peerId?this.peerId=r.peerId:n.isBuffer(r.peerId)?this.peerId=r.peerId.toString("hex"):this.peerId=n.from(a+Tn(9).toString("base64")).toString("hex"),this.peerIdBuffer=n.from(this.peerId,"hex"),"string"==typeof r.nodeId?this.nodeId=r.nodeId:n.isBuffer(r.nodeId)?this.nodeId=r.nodeId.toString("hex"):this.nodeId=Tn(20).toString("hex"),this.nodeIdBuffer=n.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=r.torrentPort||0,this.dhtPort=r.dhtPort||0,this.tracker=void 0!==r.tracker?r.tracker:{},this.torrents=[],this.maxConns=Number(r.maxConns)||55,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),r.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=r.rtcConfig),r.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=r.wrtc),t.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=t.WRTC)),"function"==typeof te?this._tcpPool=new te(this):e.nextTick(()=>{this._onListening()}),this._downloadSpeed=Bn(),this._uploadSpeed=Bn(),!1!==r.dht&&"function"==typeof te?(this.dht=new te(Object.assign({},{nodeId:this.nodeId},r.dht)),this.dht.once("error",e=>{this._destroy(e)}),this.dht.once("listening",()=>{const e=this.dht.address();e&&(this.dhtPort=e.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==r.webSeeds;const i=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof te&&null!=r.blocklist?te(r.blocklist,{headers:{"user-agent":`WebTorrent/${s} (https://webtorrent.io)`}},(e,t)=>{if(e)return this.error(`Failed to load blocklist: ${e.message}`);this.blocked=t,i()}):e.nextTick(i)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const e=this.torrents.filter(e=>1!==e.progress);return e.reduce((e,t)=>e+t.downloaded,0)/(e.reduce((e,t)=>e+(t.length||0),0)||1)}get ratio(){return this.torrents.reduce((e,t)=>e+t.uploaded,0)/(this.torrents.reduce((e,t)=>e+t.received,0)||1)}get(e){if(e instanceof ui){if(this.torrents.includes(e))return e}else{let t;try{t=Cn(e)}catch(li){}if(!t)return null;if(!t.infoHash)throw new Error("Invalid torrent identifier");for(const e of this.torrents)if(e.infoHash===t.infoHash)return e}return null}download(e,t,n){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(e,t,n)}add(e,t={},n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]);const r=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===s.infoHash&&e!==s)return void s._destroy(new Error(`Cannot add duplicate torrent ${s.infoHash}`))},i=()=>{this.destroyed||("function"==typeof n&&n(s),this.emit("torrent",s))};this._debug("add"),t=t?Object.assign({},t):{};const s=new ui(e,this,t);return this.torrents.push(s),s.once("_infoHash",r),s.once("ready",i),s.once("close",function e(){s.removeListener("_infoHash",r),s.removeListener("ready",i),s.removeListener("close",e)}),s}seed(e,t,n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const r="string"==typeof e;r&&(t.path=et.dirname(e)),t.createdBy||(t.createdBy=`WebTorrent/${o}`);const i=e=>{this._debug("on seed"),"function"==typeof n&&n(e),e.emit("seed"),this.emit("seed",e)},s=this.add(null,t,e=>{const t=[t=>{if(r)return t();e.load(a,t)}];this.dht&&t.push(t=>{e.once("dhtAnnounce",t)}),kt(t,t=>{if(!this.destroyed)return t?e._destroy(t):void i(e)})});let a;return"undefined"!=typeof FileList&&e instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),kt(e.map(e=>t=>{!function(t){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}()?t(null,e):P(e,t)}),(e,n)=>{if(!this.destroyed)return e?s._destroy(e):void Pt.parseInput(n,t,(e,r)=>{if(!this.destroyed){if(e)return s._destroy(e);a=r.map(e=>e.getStream),Pt(n,t,(e,t)=>{if(this.destroyed)return;if(e)return s._destroy(e);const n=this.get(t);n?s._destroy(new Error(`Cannot add duplicate torrent ${n.infoHash}`)):s._onTorrentId(t)})}})}),s}remove(e,t){if(this._debug("remove"),!this.get(e))throw new Error(`No torrent with id ${e}`);this._remove(e,t)}_remove(e,t){const n=this.get(e);n&&(this.torrents.splice(this.torrents.indexOf(n),1),n.destroy(t))}address(){return this.listening?this._tcpPool?this._tcpPool.server.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(e){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,e)}_destroy(e,t){this._debug("client destroy"),this.destroyed=!0;const n=this.torrents.map(e=>t=>{e.destroy(t)});this._tcpPool&&n.push(e=>{this._tcpPool.destroy(e)}),this.dht&&n.push(e=>{this.dht.destroy(e)}),kt(n,t),e&&this.emit("error",e),this.torrents=[],this._tcpPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._tcpPool){const e=this._tcpPool.server.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,i(...e)}}h.WEBRTC_SUPPORT=In.WEBRTC_SUPPORT,h.VERSION=s,di=h}.call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u({}).Buffer),di}); \ No newline at end of file +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).WebTorrent=e()}}(function(){var e=function(e){var t;return function(n){return t||e(t={exports:{},parent:n},t.exports),t.exports}},t=e(function(e,t){(function(e){var r=n({}),i=t,s={moov:["mvhd","meta","traks","mvex"],trak:["tkhd","tref","trgr","edts","meta","mdia","udta"],edts:["elst"],mdia:["mdhd","hdlr","elng","minf"],minf:["vmhd","smhd","hmhd","sthd","nmhd","dinf","stbl"],dinf:["dref"],stbl:["stsd","stts","ctts","cslg","stsc","stsz","stz2","stco","co64","stss","stsh","padb","stdp","sdtp","sbgps","sgpds","subss","saizs","saios"],mvex:["mehd","trexs","leva"],moof:["mfhd","meta","trafs"],traf:["tfhd","tfdt","trun","sbgps","sgpds","subss","saizs","saios","meta"]};i.encode=function(t,n,r){return i.encodingLength(t),r=r||0,n=n||e.alloc(t.length),i._encode(t,n,r)},i._encode=function(e,t,n){var o=e.type,a=e.length;a>4294967295&&(a=1),t.writeUInt32BE(a,n),t.write(e.type,n+4,4,"ascii");var h=n+8;if(1===a&&(Er.encode(e.length,t,h),h+=8),r.fullBoxes[o]&&(t.writeUInt32BE(e.flags||0,h),t.writeUInt8(e.version||0,h),h+=4),s[o])s[o].forEach(function(n){if(5===n.length){var r=e[n]||[];n=n.substr(0,4),r.forEach(function(e){i._encode(e,t,h),h+=i.encode.bytes})}else e[n]&&(i._encode(e[n],t,h),h+=i.encode.bytes)}),e.otherBoxes&&e.otherBoxes.forEach(function(e){i._encode(e,t,h),h+=i.encode.bytes});else if(r[o]){var c=r[o].encode;c(e,t,h),h+=c.bytes}else{if(!e.buffer)throw new Error("Either `type` must be set to a known type (not'"+o+"') or `buffer` must be set");e.buffer.copy(t,h),h+=e.buffer.length}return i.encode.bytes=h-n,t},i.readHeaders=function(e,t,n){if(t=t||0,(n=n||e.length)-t<8)return 8;var i,s,o=e.readUInt32BE(t),a=e.toString("ascii",t+4,t+8),h=t+8;if(1===o){if(n-t<16)return 16;o=Er.decode(e,h),h+=8}return r.fullBoxes[a]&&(i=e.readUInt8(h),s=16777215&e.readUInt32BE(h),h+=4),{length:o,headersLen:h-t,contentLen:o-(h-t),type:a,version:i,flags:s}},i.decode=function(e,t,n){t=t||0,n=n||e.length;var r=i.readHeaders(e,t,n);if(!r||r.length>n-t)throw new Error("Data too short");return i.decodeWithoutHeaders(r,e,t+r.headersLen,t+r.length)},i.decodeWithoutHeaders=function(t,n,o,a){o=o||0,a=a||n.length;var h=t.type,c={};if(s[h]){c.otherBoxes=[];for(var u=s[h],d=o;a-d>=8;){var l=i.decode(n,d,a);if(d+=l.length,u.indexOf(l.type)>=0)c[l.type]=l;else if(u.indexOf(l.type+"s")>=0){var f=l.type+"s";(c[f]=c[f]||[]).push(l)}else c.otherBoxes.push(l)}}else r[h]?c=(0,r[h].decode)(n,o,a):c.buffer=e.from(n.slice(o,a));return c.length=t.length,c.contentLen=t.contentLen,c.type=t.type,c.version=t.version,c.flags=t.flags,c},i.encodingLength=function(e){var t=e.type,n=8;if(r.fullBoxes[t]&&(n+=4),s[t])s[t].forEach(function(t){if(5===t.length){var r=e[t]||[];t=t.substr(0,4),r.forEach(function(e){e.type=t,n+=i.encodingLength(e)})}else if(e[t]){var s=e[t];s.type=t,n+=i.encodingLength(s)}}),e.otherBoxes&&e.otherBoxes.forEach(function(e){n+=i.encodingLength(e)});else if(r[t])n+=r[t].encodingLength(e);else{if(!e.buffer)throw new Error("Either `type` must be set to a known type (not'"+t+"') or `buffer` must be set");n+=e.buffer.length}return n>4294967295&&(n+=8),e.length=n,n}}).call(this,u({}).Buffer)}),n=e(function(e,n){(function(e){var r=t({}),i=20828448e5;function s(e,t,n){for(var r=t;r=8;){var h=r.decode(e,a,i);o.children.push(h),o[h.type]=h,a+=h.length}return o},n.VisualSampleEntry.encodingLength=function(e){var t=78;return(e.children||[]).forEach(function(e){t+=r.encodingLength(e)}),t},n.avcC={},n.avcC.encode=function(t,r,i){r=r?r.slice(i):e.alloc(t.buffer.length),t.buffer.copy(r),n.avcC.encode.bytes=t.buffer.length},n.avcC.decode=function(t,n,r){return{mimeCodec:(t=t.slice(n,r)).toString("hex",1,4),buffer:e.from(t)}},n.avcC.encodingLength=function(e){return e.buffer.length},n.mp4a=n.AudioSampleEntry={},n.AudioSampleEntry.encode=function(t,i,o){s(i=i?i.slice(o):e.alloc(n.AudioSampleEntry.encodingLength(t)),0,6),i.writeUInt16BE(t.dataReferenceIndex||0,6),s(i,8,16),i.writeUInt16BE(t.channelCount||2,16),i.writeUInt16BE(t.sampleSize||16,18),s(i,20,24),i.writeUInt32BE(t.sampleRate||0,24);var a=28;(t.children||[]).forEach(function(e){r.encode(e,i,a),a+=r.encode.bytes}),n.AudioSampleEntry.encode.bytes=a},n.AudioSampleEntry.decode=function(e,t,n){for(var i=n-t,s={dataReferenceIndex:(e=e.slice(t,n)).readUInt16BE(6),channelCount:e.readUInt16BE(16),sampleSize:e.readUInt16BE(18),sampleRate:e.readUInt32BE(24),children:[]},o=28;i-o>=8;){var a=r.decode(e,o,i);s.children.push(a),s[a.type]=a,o+=a.length}return s},n.AudioSampleEntry.encodingLength=function(e){var t=28;return(e.children||[]).forEach(function(e){t+=r.encodingLength(e)}),t},n.esds={},n.esds.encode=function(t,r,i){r=r?r.slice(i):e.alloc(t.buffer.length),t.buffer.copy(r,0),n.esds.encode.bytes=t.buffer.length},n.esds.decode=function(t,n,r){t=t.slice(n,r);var i=Sr.Descriptor.decode(t,0,t.length),s=("ESDescriptor"===i.tagName?i:{}).DecoderConfigDescriptor||{},o=s.oti||0,a=s.DecoderSpecificInfo,h=a?(248&a.buffer.readUInt8(0))>>3:0,c=null;return o&&(c=o.toString(16),h&&(c+="."+h)),{mimeCodec:c,buffer:e.from(t.slice(0))}},n.esds.encodingLength=function(e){return e.buffer.length},n.stsz={},n.stsz.encode=function(t,r,i){var s=t.entries||[];(r=r?r.slice(i):e.alloc(n.stsz.encodingLength(t))).writeUInt32BE(0,0),r.writeUInt32BE(s.length,4);for(var o=0;o=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}e.exports=function(e,t){t=t||{};var a,h,c=typeof e;if("string"===c&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var o=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return 6048e5*o;case"days":case"day":case"d":return o*s;case"hours":case"hour":case"hrs":case"hr":case"h":return o*i;case"minutes":case"minute":case"mins":case"min":case"m":return o*r;case"seconds":case"second":case"secs":case"sec":case"s":return o*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===c&&isFinite(e))return t.long?(a=e,(h=Math.abs(a))>=s?o(a,h,s,"day"):h>=i?o(a,h,i,"hour"):h>=r?o(a,h,r,"minute"):h>=n?o(a,h,n,"second"):a+" ms"):function(e){var t=Math.abs(e);return t>=s?Math.round(e/s)+"d":t>=i?Math.round(e/i)+"h":t>=r?Math.round(e/r)+"m":t>=n?Math.round(e/n)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}}),i=e(function(e,t){(function(t,n){"use strict";var r;e.exports=S,S.ReadableState=k,d.EventEmitter;var i,o=function(e,t){return e.listeners(t).length},c=u({}).Buffer,l=n.Uint8Array||function(){};i=te&&te.debuglog?te.debuglog("stream"):function(){};var f,p,g=Ie.getHighWaterMark,m=ke.codes,_=m.ERR_INVALID_ARG_TYPE,y=m.ERR_STREAM_PUSH_AFTER_EOF,b=m.ERR_METHOD_NOT_IMPLEMENTED,w=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,v=Ae.emitExperimentalWarning;Re(S,ee);var E=["error","close","destroy","pause","resume"];function k(e,t,n){r=r||h({}),e=e||{},"boolean"!=typeof n&&(n=t instanceof r),this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=g(this,e,"readableHighWaterMark",n),this.buffer=new he,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==e.emitClose,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(f||(f=a({}).StringDecoder),this.decoder=new f(e.encoding),this.encoding=e.encoding)}function S(e){if(r=r||h({}),!(this instanceof S))return new S(e);var t=this instanceof r;this._readableState=new k(e,this,t),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),ee.call(this)}function C(e,t,n,r,s){i("readableAddChunk",t);var o,a=e._readableState;if(null===t)a.reading=!1,function(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?A(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,R(e)))}}(e,a);else if(s||(o=function(e,t){var n,r;return r=t,c.isBuffer(r)||r instanceof l||"string"==typeof t||void 0===t||e.objectMode||(n=new _("chunk",["string","Buffer","Uint8Array"],t)),n}(a,t)),o)e.emit("error",o);else if(a.objectMode||t&&t.length>0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),r)a.endEmitted?e.emit("error",new w):x(e,a,t,!0);else if(a.ended)e.emit("error",new y);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!n?(t=a.decoder.write(t),a.objectMode||0!==t.length?x(e,a,t,!1):L(e,a)):x(e,a,t,!1)}else r||(a.reading=!1,L(e,a));return!a.ended&&(a.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=T?e=T:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function A(e){var n=e._readableState;n.needReadable=!1,n.emittedReadable||(i("emitReadable",n.flowing),n.emittedReadable=!0,t.nextTick(R,e))}function R(e){var t=e._readableState;i("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||e.emit("readable"),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,P(e)}function L(e,n){n.readingMore||(n.readingMore=!0,t.nextTick(B,e,n))}function B(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function O(e){i("readable nexttick read 0"),e.read(0)}function M(e,t){i("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),P(e),t.flowing&&!t.reading&&e.read(0)}function P(e){var t=e._readableState;for(i("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function j(e){var n=e._readableState;i("endReadable",n.endEmitted),n.endEmitted||(n.ended=!0,t.nextTick(H,n,e))}function H(e,t){i("endReadableNT",e.endEmitted,e.length),e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function D(e,t){for(var n=0,r=e.length;n=t.highWaterMark:t.length>0)||t.ended))return i("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?j(this):A(this),null;if(0===(e=I(e,t))&&t.ended)return 0===t.length&&j(this),null;var r,s=t.needReadable;return i("need readable",s),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=!0,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&j(this)),null!==r&&this.emit("data",r),r},S.prototype._read=function(e){this.emit("error",new b("_read()"))},S.prototype.pipe=function(e,n){var r=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,i("pipe count=%d opts=%j",s.pipesCount,n);var a=n&&!1===n.end||e===t.stdout||e===t.stderr?g:h;function h(){i("onend"),e.end()}s.endEmitted?t.nextTick(a):r.once("end",a),e.on("unpipe",function t(n,o){i("onunpipe"),n===r&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,i("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",c),e.removeListener("error",l),e.removeListener("unpipe",t),r.removeListener("end",h),r.removeListener("end",g),r.removeListener("data",d),u=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||c())});var c=function(e){return function(){var t=e._readableState;i("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,P(e))}}(r);e.on("drain",c);var u=!1;function d(t){i("ondata");var n=e.write(t);i("dest.write",n),!1===n&&((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==D(s.pipes,e))&&!u&&(i("false write response, pause",s.awaitDrain),s.awaitDrain++),r.pause())}function l(t){i("onerror",t),g(),e.removeListener("error",l),0===o(e,"error")&&e.emit("error",t)}function f(){e.removeListener("finish",p),g()}function p(){i("onfinish"),e.removeListener("close",f),g()}function g(){i("unpipe"),r.unpipe(e)}return r.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener("error",n);e._events&&e._events.error?Array.isArray(e._events.error)?e._events.error.unshift(n):e._events.error=[n,e._events.error]:e.on("error",n)}(e,0,l),e.once("close",f),e.once("finish",p),e.emit("pipe",r),s.flowing||(i("pipe resume"),r.resume()),e},S.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,i("on readable",s.length,s.reading),s.length?A(this):s.reading||t.nextTick(O,this))),r},S.prototype.addListener=S.prototype.on,S.prototype.removeListener=function(e,n){var r=ee.prototype.removeListener.call(this,e,n);return"readable"===e&&t.nextTick(U,this),r},S.prototype.removeAllListeners=function(e){var n=ee.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||t.nextTick(U,this),n},S.prototype.resume=function(){var e=this._readableState;return e.flowing||(i("resume"),e.flowing=!e.readableListening,function(e,n){n.resumeScheduled||(n.resumeScheduled=!0,t.nextTick(M,e,n))}(this,e)),e.paused=!1,this},S.prototype.pause=function(){return i("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(i("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},S.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var s in e.on("end",function(){if(i("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(s){i("wrapped data"),n.decoder&&(s=n.decoder.write(s)),n.objectMode&&null==s||(n.objectMode||s&&s.length)&&(t.push(s)||(r=!0,e.pause()))}),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var o=0;o>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function o(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"\ufffd";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"\ufffd";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"\ufffd"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function a(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function h(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function c(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function u(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function l(e){return e&&e.length?this.write(e):""}t.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0?(i>0&&(e.lastNeed=i-1),i):--r=0?(i>0&&(e.lastNeed=i-2),i):--r=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}}),h=e(function(e,t){(function(t){"use strict";var n=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=u;var r=i({}),s=c({});Re(u,r);for(var o=n(s.prototype),a=0;a-1))throw new w(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(k.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(k.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),k.prototype._write=function(e,t,n){n(new p("_write()"))},k.prototype._writev=null,k.prototype.end=function(e,n,r){var i=this._writableState;return"function"==typeof e?(r=e,e=null,n=null):"function"==typeof n&&(r=n,n=null),null!=e&&this.write(e,n),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,n,r){n.ending=!0,A(e,n),r&&(n.finished?t.nextTick(r):e.once("finish",r)),n.ended=!0,e.writable=!1}(this,i,r),this},Object.defineProperty(k.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(k.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),k.prototype.destroy=Ee.destroy,k.prototype._undestroy=Ee.undestroy,k.prototype._destroy=function(e,t){t(e)}}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})}),u=e(function(e,t){(function(e){"use strict";var n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=e,t.SlowBuffer=function(t){return+t!=t&&(t=0),e.alloc(+t)},t.INSPECT_MAX_BYTES=50;var r=2147483647;function i(t){if(t>r)throw new RangeError('The value "'+t+'" is invalid for option "size"');var n=new Uint8Array(t);return Object.setPrototypeOf(n,e.prototype),n}function e(e,t,n){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 s(e,t,n)}function s(t,n,r){if("string"==typeof t)return function(t,n){if("string"==typeof n&&""!==n||(n="utf8"),!e.isEncoding(n))throw new TypeError("Unknown encoding: "+n);var r=0|u(t,n),s=i(r),o=s.write(t,n);return o!==r&&(s=s.slice(0,o)),s}(t,n);if(ArrayBuffer.isView(t))return h(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(j(t,ArrayBuffer)||t&&j(t.buffer,ArrayBuffer))return function(t,n,r){if(n<0||t.byteLength=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function u(t,n){if(e.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||j(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var s=!1;;)switch(n){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return O(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return P(t).length;default:if(s)return i?-1:O(t).length;n=(""+n).toLowerCase(),s=!0}}function d(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function l(t,n,r,i,s){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),H(r=+r)&&(r=s?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(s)return-1;r=t.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof n&&(n=e.from(n,i)),e.isBuffer(n))return 0===n.length?-1:f(t,n,r,i,s);if("number"==typeof n)return n&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,n,r):Uint8Array.prototype.lastIndexOf.call(t,n,r):f(t,[n],r,i,s);throw new TypeError("val must be string, number or Buffer")}function f(e,t,n,r,i){var s,o=1,a=e.length,h=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,h/=2,n/=2}function c(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){var u=-1;for(s=n;sa&&(n=a-h),s=n;s>=0;s--){for(var d=!0,l=0;li&&(r=i):r=i;var s=t.length;r>s/2&&(r=s/2);for(var o=0;o>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function w(e,t,n){return 0===t&&n===e.length?x.fromByteArray(e):x.fromByteArray(e.slice(t,n))}function v(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+d<=n)switch(d){case 1:c<128&&(u=c);break;case 2:128==(192&(s=e[i+1]))&&(h=(31&c)<<6|63&s)>127&&(u=h);break;case 3:s=e[i+1],o=e[i+2],128==(192&s)&&128==(192&o)&&(h=(15&c)<<12|(63&s)<<6|63&o)>2047&&(h<55296||h>57343)&&(u=h);break;case 4:s=e[i+1],o=e[i+2],a=e[i+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&(h=(15&c)<<18|(63&s)<<12|(63&o)<<6|63&a)>65535&&h<1114112&&(u=h)}null===u?(u=65533,d=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),i+=d}return function(e){var t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);for(var n="",r=0;rthis.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return C(this,t,n);case"utf8":case"utf-8":return v(this,t,n);case"ascii":return k(this,t,n);case"latin1":case"binary":return S(this,t,n);case"base64":return w(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}.apply(this,arguments)},e.prototype.toLocaleString=e.prototype.toString,e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===e.compare(this,t)},e.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),""},n&&(e.prototype[n]=e.prototype.inspect),e.prototype.compare=function(t,n,r,i,s){if(j(t,Uint8Array)&&(t=e.from(t,t.offset,t.byteLength)),!e.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===n&&(n=0),void 0===r&&(r=t?t.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),n<0||r>t.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&n>=r)return 0;if(i>=s)return-1;if(n>=r)return 1;if(this===t)return 0;for(var o=(s>>>=0)-(i>>>=0),a=(r>>>=0)-(n>>>=0),h=Math.min(o,a),c=this.slice(i,s),u=t.slice(n,r),d=0;d>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return p(this,e,t,n);case"utf8":case"utf-8":return g(this,e,t,n);case"ascii":return m(this,e,t,n);case"latin1":case"binary":return _(this,e,t,n);case"base64":return y(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var E=4096;function k(e,t,n){var r="";n=Math.min(e.length,n);for(var i=t;ii)&&(n=i);for(var s="",o=t;on)throw new RangeError("Trying to access beyond buffer length")}function A(t,n,r,i,s,o){if(!e.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(n>s||nt.length)throw new RangeError("Index out of range")}function R(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,r,i){return t=+t,n>>>=0,i||R(e,0,n,4),M.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,i){return t=+t,n>>>=0,i||R(e,0,n,8),M.write(e,t,n,r,52,8),n+8}e.prototype.slice=function(t,n){var r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(n=void 0===n?r:~~n)<0?(n+=r)<0&&(n=0):n>r&&(n=r),n>>=0,t>>>=0,n||I(e,t,this.length);for(var r=this[e],i=1,s=0;++s>>=0,t>>>=0,n||I(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},e.prototype.readUInt8=function(e,t){return e>>>=0,t||I(e,1,this.length),this[e]},e.prototype.readUInt16LE=function(e,t){return e>>>=0,t||I(e,2,this.length),this[e]|this[e+1]<<8},e.prototype.readUInt16BE=function(e,t){return e>>>=0,t||I(e,2,this.length),this[e]<<8|this[e+1]},e.prototype.readUInt32LE=function(e,t){return e>>>=0,t||I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},e.prototype.readUInt32BE=function(e,t){return e>>>=0,t||I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},e.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||I(e,t,this.length);for(var r=this[e],i=1,s=0;++s=(i*=128)&&(r-=Math.pow(2,8*t)),r},e.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||I(e,t,this.length);for(var r=t,i=1,s=this[e+--r];r>0&&(i*=256);)s+=this[e+--r]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},e.prototype.readInt8=function(e,t){return e>>>=0,t||I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},e.prototype.readInt16LE=function(e,t){e>>>=0,t||I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt16BE=function(e,t){e>>>=0,t||I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},e.prototype.readInt32LE=function(e,t){return e>>>=0,t||I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},e.prototype.readInt32BE=function(e,t){return e>>>=0,t||I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},e.prototype.readFloatLE=function(e,t){return e>>>=0,t||I(e,4,this.length),M.read(this,e,!0,23,4)},e.prototype.readFloatBE=function(e,t){return e>>>=0,t||I(e,4,this.length),M.read(this,e,!1,23,4)},e.prototype.readDoubleLE=function(e,t){return e>>>=0,t||I(e,8,this.length),M.read(this,e,!0,52,8)},e.prototype.readDoubleBE=function(e,t){return e>>>=0,t||I(e,8,this.length),M.read(this,e,!1,52,8)},e.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||A(this,e,t,n,Math.pow(2,8*n)-1,0);var i=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,r||A(this,e,t,n,Math.pow(2,8*n)-1,0);var i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+n},e.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,1,255,0),this[t]=255&e,t+1},e.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},e.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},e.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},e.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},e.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);A(this,e,t,n,i-1,-i)}var s=0,o=1,a=0;for(this[t]=255&e;++s>0)-a&255;return t+n},e.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);A(this,e,t,n,i-1,-i)}var s=n-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o>>0)-a&255;return t+n},e.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},e.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},e.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},e.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},e.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||A(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},e.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},e.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},e.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},e.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},e.prototype.copy=function(t,n,r,i){if(!e.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),n>=t.length&&(n=t.length),n||(n=0),i>0&&i=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),t.length-n=0;--o)t[o+n]=this[o+r];else Uint8Array.prototype.set.call(t,this.subarray(r,i),n);return s},e.prototype.fill=function(t,n,r,i){if("string"==typeof t){if("string"==typeof n?(i=n,n=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!e.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var s=t.charCodeAt(0);("utf8"===i&&s<128||"latin1"===i)&&(t=s)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(n<0||this.length>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=n;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function P(e){return x.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(U,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function N(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function H(e){return e!=e}}).call(this,u({}).Buffer)}),d={},l=Object.create||function(e){var t=function(){};return t.prototype=e,new t},f=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return n},p=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function g(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=l(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}d=g,g.EventEmitter=g,g.prototype._events=void 0,g.prototype._maxListeners=void 0;var m,_=10;try{var y={};Object.defineProperty&&Object.defineProperty(y,"x",{value:0}),m=0===y.x}catch(li){m=!1}function b(e){return void 0===e._maxListeners?g.defaultMaxListeners:e._maxListeners}function w(e,t,n,r){var i,s,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]):(s=e._events=l(null),e._eventsCount=0),o){if("function"==typeof o?o=s[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),!o.warned&&(i=b(e))&&i>0&&o.length>i){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",a.name,a.message)}}else o=s[t]=n,++e._eventsCount;return e}function v(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t1&&(t=arguments[1]),t instanceof Error)throw t;var h=new Error('Unhandled "error" event. ('+t+")");throw h.context=t,h}if(!(n=o[e]))return!1;var c="function"==typeof n;switch(r=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var r=e.length,i=C(e,r),s=0;s=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():function(e,t){for(var n=i,r=n+1,s=e.length;r=0;r--)this.removeListener(e,t[r]);return this},g.prototype.listeners=function(e){return k(this,e,!0)},g.prototype.rawListeners=function(e){return k(this,e,!1)},g.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):S.call(e,t)},g.prototype.listenerCount=S,g.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};for(var x={toByteArray:function(e){var t,n,r=U(e),i=r[0],s=r[1],o=new A(function(e,t,n){return 3*(t+n)/4-n}(0,i,s)),a=0,h=s>0?i-4:i;for(n=0;n>16&255,o[a++]=t>>8&255,o[a++]=255&t;return 2===s&&(t=I[e.charCodeAt(n)]<<2|I[e.charCodeAt(n+1)]>>4,o[a++]=255&t),1===s&&(t=I[e.charCodeAt(n)]<<10|I[e.charCodeAt(n+1)]<<4|I[e.charCodeAt(n+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t),o},fromByteArray:function(e){for(var t,n=e.length,r=n%3,i=[],s=0,o=n-r;so?o:s+16383));return 1===r?(t=e[n-1],i.push(T[t>>2]+T[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(T[t>>10]+T[t>>4&63]+T[t<<2&63]+"=")),i.join("")}},T=[],I=[],A="undefined"!=typeof Uint8Array?Uint8Array:Array,R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",L=0,B=R.length;L0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function O(e,t,n){for(var r,i,s=[],o=t;o>18&63]+T[i>>12&63]+T[i>>6&63]+T[63&i]);return s.join("")}I["-".charCodeAt(0)]=62,I["_".charCodeAt(0)]=63;var M={read:function(e,t,n,r,i){var s,o,a=8*i-r-1,h=(1<>1,u=-7,d=n?i-1:0,l=n?-1:1,f=e[t+d];for(d+=l,s=f&(1<<-u)-1,f>>=-u,u+=a;u>0;s=256*s+e[t+d],d+=l,u-=8);for(o=s&(1<<-u)-1,s>>=-u,u+=r;u>0;o=256*o+e[t+d],d+=l,u-=8);if(0===s)s=1-c;else{if(s===h)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),s-=c}return(f?-1:1)*o*Math.pow(2,s-r)},write:function(e,t,n,r,i,s){var o,a,h,c=8*s-i-1,u=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=u):(o=Math.floor(Math.log(t)/Math.LN2),t*(h=Math.pow(2,-o))<1&&(o--,h*=2),(t+=o+d>=1?l/h:l*Math.pow(2,1-d))*h>=2&&(o++,h/=2),o+d>=u?(a=0,o=u):o+d>=1?(a=(t*h-1)*Math.pow(2,i),o+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=255&a,f+=p,a/=256,i-=8);for(o=o<0;e[n+f]=255&o,f+=p,o/=256,c-=8);e[n+f-p]|=128*g}},P={};(function(e){P=function(t,n){var r=[];t.on("data",function(e){r.push(e)}),t.once("end",function(){n&&n(null,e.concat(r)),n=null}),t.once("error",function(e){n&&n(e),n=null})}}).call(this,u({}).Buffer);var N={},j=u({}),H=j.Buffer;function D(e,t){for(var n in e)t[n]=e[n]}function q(e,t,n){return H(e,t,n)}H.from&&H.alloc&&H.allocUnsafe&&H.allocUnsafeSlow?N=j:(D(j,N),N.Buffer=q),q.prototype=Object.create(H.prototype),D(H,q),q.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return H(e,t,n)},q.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=H(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},q.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return H(e)},q.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return j.SlowBuffer(e)};var F,W=N.Buffer;function z(e,t,n){var r=[],i=null;return z._encode(r,e),i=W.concat(r),z.bytes=i.length,W.isBuffer(t)?(i.copy(t,n),t):i}z.bytes=-1,z._floatConversionDetected=!1,z.getType=function(e){return W.isBuffer(e)?"buffer":Array.isArray(e)?"array":ArrayBuffer.isView(e)?"arraybufferview":e instanceof Number?"number":e instanceof Boolean?"boolean":e instanceof ArrayBuffer?"arraybuffer":typeof e},z._encode=function(e,t){if(null!=t)switch(z.getType(t)){case"buffer":z.buffer(e,t);break;case"object":z.dict(e,t);break;case"array":z.list(e,t);break;case"string":z.string(e,t);break;case"number":case"boolean":z.number(e,t);break;case"arraybufferview":z.buffer(e,W.from(t.buffer,t.byteOffset,t.byteLength));break;case"arraybuffer":z.buffer(e,W.from(t))}};var $=W.from("e"),V=W.from("d"),G=W.from("l");z.buffer=function(e,t){e.push(W.from(t.length+":"),t)},z.string=function(e,t){e.push(W.from(W.byteLength(t)+":"+t))},z.number=function(e,t){var n=2147483648*(t/2147483648<<0)+(t%2147483648<<0);e.push(W.from("i"+n+"e")),n===t||z._floatConversionDetected||(z._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+t+'":','Bencoding only defines support for integers, value was converted to "'+n+'"'),console.trace())},z.dict=function(e,t){e.push(V);for(var n,r=0,i=Object.keys(t).sort(),s=i.length;r=48)r=10*r+(o-48);else if(s!==t||43!==o){if(s!==t||45!==o){if(46===o)break;throw new Error("not a number: buffer["+s+"] = "+o)}i=-1}}return r*i}function X(e,t,n,r){return null==e||0===e.length?null:("number"!=typeof t&&null==r&&(r=t,t=void 0),"number"!=typeof n&&null==r&&(r=n,n=void 0),X.position=0,X.encoding=r||null,X.data=Y.isBuffer(e)?e.slice(t,n):Y.from(e),X.bytes=X.data.length,X.next())}X.bytes=0,X.position=0,X.data=null,X.encoding=null,X.next=function(){switch(X.data[X.position]){case 100:return X.dictionary();case 108:return X.list();case 105:return X.integer();default:return X.buffer()}},X.find=function(e){for(var t=X.position,n=X.data.length,r=X.data;t0?this.tail.next=t:this.head=t,this.tail=t,++this.length},t.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},t.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},t.clear=function(){this.head=this.tail=null,this.length=0},t.join=function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n},t.concat=function(e){if(0===this.length)return se.alloc(0);for(var t,n,r,i=se.allocUnsafe(e>>>0),s=this.head,o=0;s;)t=s.data,n=i,r=o,se.prototype.copy.call(t,n,r),o+=s.data.length,s=s.next;return i},t.consume=function(e,t){var n;return ei.length?i.length:e;if(s===i.length?r+=i:r+=i.slice(0,e),0==(e-=s)){s===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r},t._getBuffer=function(e){var t=se.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0==(e-=s)){s===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t},t[ae]=function(e,t){return oe(this,function(e){for(var t=1;t1)for(var n=1;n2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}Ce("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError),Ce("ERR_INVALID_ARG_TYPE",function(e,t,n){var r,i,s,o;if("string"==typeof t&&("not ","not "===t.substr(0,"not ".length))?(r="must not be",t=t.replace(/^not /,"")):r="must be",s=e,(void 0===o||o>s.length)&&(o=s.length)," argument"===s.substring(o-" argument".length,o))i="The ".concat(e," ").concat(r," ").concat(xe(t,"type"));else{var a=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+".".length>e.length)&&-1!==e.indexOf(".",n)}(e)?"property":"argument";i='The "'.concat(e,'" ').concat(a," ").concat(r," ").concat(xe(t,"type"))}return i+". Received type ".concat(typeof n)},TypeError),Ce("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Ce("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),Ce("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Ce("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),Ce("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Ce("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Ce("ERR_STREAM_WRITE_AFTER_END","write after end"),Ce("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Ce("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),Ce("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),ke.codes=Se;var Te=ke.codes.ERR_INVALID_OPT_VALUE,Ie={getHighWaterMark:function(e,t,n,r){var i=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(t,r,n);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new Te(r?n:"highWaterMark",i);return Math.floor(i)}return e.objectMode?16:16384}},Ae={};(function(e){"use strict";var t=new Set;Ae.emitExperimentalWarning=e.emitWarning?function(n){if(!t.has(n)){var r=n+" is an experimental feature. This feature could change at any time";t.add(n),e.emitWarning(r,"ExperimentalWarning")}}:function(){}}).call(this,ce);var Re={};Re="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}};var Le={};(function(e){function t(t){try{if(!e.localStorage)return!1}catch(r){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}Le=function(e,n){if(t("noDeprecation"))return e;var r=!1;return function(){if(!r){if(t("throwDeprecation"))throw new Error(n);t("traceDeprecation")?console.trace(n):console.warn(n),r=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Be=De,Ue=ke.codes,Oe=Ue.ERR_METHOD_NOT_IMPLEMENTED,Me=Ue.ERR_MULTIPLE_CALLBACK,Pe=Ue.ERR_TRANSFORM_ALREADY_TRANSFORMING,Ne=Ue.ERR_TRANSFORM_WITH_LENGTH_0,je=h({});function He(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new Me);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length0,function(e){r||(r=e),e&&s.forEach(Je),a||(s.forEach(Je),i(r))})});return t.reduce(Xe)};var Qe={};(function(e){const{Transform:t}=Ze;Qe=class extends t{constructor(e,t={}){super(t),"object"==typeof e&&(e=(t=e).size),this.size=e||512;const{nopad:n,zeroPadding:r=!0}=t;this._zeroPadding=!n&&!!r,this._buffered=[],this._bufferedBytes=0}_transform(t,n,r){for(this._bufferedBytes+=t.length,this._buffered.push(t);this._bufferedBytes>=this.size;){const t=e.concat(this._buffered);this._bufferedBytes-=this.size,this.push(t.slice(0,this.size)),this._buffered=[t.slice(this.size,t.length)]}r()}_flush(){if(this._bufferedBytes&&this._zeroPadding){const t=e.alloc(this.size-this._bufferedBytes);this._buffered.push(t),this.push(e.concat(this._buffered)),this._buffered=null}else this._bufferedBytes&&(this.push(e.concat(this._buffered)),this._buffered=null);this.push(null)}}}).call(this,u({}).Buffer);var et={};(function(e){function t(e,t){for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function n(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r=1;--s)if(47===(t=e.charCodeAt(s))){if(!i){r=s;break}}else i=!1;return-1===r?n?"/":".":n&&1===r?"/":e.slice(0,r)},et.basename=function(e,t){var n=function(e){"string"!=typeof e&&(e+="");var t,n=0,r=-1,i=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!i){n=t+1;break}}else-1===r&&(i=!1,r=t+1);return-1===r?"":e.slice(n,r)}(e);return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},et.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,n=0,r=-1,i=!0,s=0,o=e.length-1;o>=0;--o){var a=e.charCodeAt(o);if(47!==a)-1===r&&(i=!1,r=o+1),46===a?-1===t?t=o:1!==s&&(s=1):-1!==t&&(s=-1);else if(!i){n=o+1;break}}return-1===t||-1===r||0===s||1===s&&t===r-1&&t===n+1?"":e.slice(t,r)};var r="b"==="ab".substr(-1)?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return t<0&&(t=e.length+t),e.substr(t,n)}}).call(this,ce);var tt;tt=it,it.strict=st,it.loose=ot;var nt=Object.prototype.toString,rt={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0};function it(e){return st(e)||ot(e)}function st(e){return e instanceof Int8Array||e instanceof Int16Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Uint16Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array}function ot(e){return rt[nt.call(e)]}var at={};(function(e){var t=tt.strict;at=function(n){if(t(n)){var r=e.from(n.buffer);return n.byteLength!==n.buffer.byteLength&&(r=r.slice(n.byteOffset,n.byteOffset+n.byteLength)),r}return e.from(n)}}).call(this,u({}).Buffer);const{Readable:ht}=Ze;var ct=class extends ht{constructor(e,t={}){super(t),this._offset=0,this._ready=!1,this._file=e,this._size=e.size,this._chunkSize=t.chunkSize||Math.max(this._size/1e3,204800);const n=new FileReader;n.onload=(()=>{this.push(at(n.result))}),n.onerror=(()=>{this.emit("error",n.error)}),this.reader=n,this._generateHeaderBlocks(e,t,(e,t)=>{if(e)return this.emit("error",e);Array.isArray(t)&&t.forEach(e=>this.push(e)),this._ready=!0,this.emit("_ready")})}_generateHeaderBlocks(e,t,n){n(null,[])}_read(){if(!this._ready)return void this.once("_ready",this._read.bind(this));const e=this._offset;let t=this._offset+this._chunkSize;if(t>this._size&&(t=this._size),e===this._size)return this.destroy(),void this.push(null);this.reader.readAsArrayBuffer(this._file.slice(e,t)),this._offset=t}destroy(){if(this._file=null,this.reader){this.reader.onload=null,this.reader.onerror=null;try{this.reader.abort()}catch(e){}}this.reader=null}},ut={},dt={};function lt(e){return ut.existsSync(e)&&ut.statSync(e).isFile()}(dt=function(e,t){if(!t)return lt(e);ut.stat(e,function(e,n){return e?t(e):t(null,n.isFile())})}).sync=lt;var ft={};ft.regex=new RegExp(["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"].join("|")),ft.is=(e=>ft.regex.test(e)),ft.not=(e=>!ft.is(e));var pt={};function gt(e){return _t(e,{objectMode:!0,highWaterMark:16})}function mt(e){return _t(e)}function _t(e,t){if(!e||"function"==typeof e||e._readableState)return e;var n=new Ze.Readable(t).wrap(e);return e.destroy&&(n.destroy=e.destroy.bind(e)),n}class yt extends Ze.Readable{constructor(e,t){super(t),this.destroyed=!1,this._drained=!1,this._forwarding=!1,this._current=null,this._toStreams2=t&&t.objectMode?gt:mt,"function"==typeof e?this._queue=e:(this._queue=e.map(this._toStreams2),this._queue.forEach(e=>{"function"!=typeof e&&this._attachErrorListener(e)})),this._next()}_read(){this._drained=!0,this._forward()}_forward(){if(!this._forwarding&&this._drained&&this._current){var e;for(this._forwarding=!0;null!==(e=this._current.read())&&this._drained;)this._drained=this.push(e);this._forwarding=!1}}destroy(e){this.destroyed||(this.destroyed=!0,this._current&&this._current.destroy&&this._current.destroy(),"function"!=typeof this._queue&&this._queue.forEach(e=>{e.destroy&&e.destroy()}),e&&this.emit("error",e),this.emit("close"))}_next(){if(this._current=null,"function"==typeof this._queue)this._queue((e,t)=>{if(e)return this.destroy(e);t=this._toStreams2(t),this._attachErrorListener(t),this._gotNextStream(t)});else{var e=this._queue.shift();"function"==typeof e&&(e=this._toStreams2(e()),this._attachErrorListener(e)),this._gotNextStream(e)}}_gotNextStream(e){if(!e)return this.push(null),void this.destroy();this._current=e,this._forward();const t=()=>{this._forward()},n=()=>{e._readableState.ended||this.destroy()},r=()=>{this._current=null,e.removeListener("readable",t),e.removeListener("end",r),e.removeListener("close",n),this._next()};e.on("readable",t),e.once("end",r),e.once("close",n)}_attachErrorListener(e){if(!e)return;const t=n=>{e.removeListener("error",t),this.destroy(n)};e.once("error",t)}}yt.obj=(e=>new yt(e,{objectMode:!0,highWaterMark:16})),pt=yt;var bt=function e(t,n){if(t&&n)return e(t)(n);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach(function(e){r[e]=t[e]}),r;function r(){for(var e=new Array(arguments.length),n=0;n0;e+=1);return e},c=function(e,t){var n=new Int32Array(e,t+320,5),r=new Int32Array(5),i=new DataView(r.buffer);return i.setInt32(0,n[0],!1),i.setInt32(4,n[1],!1),i.setInt32(8,n[2],!1),i.setInt32(12,n[3],!1),i.setInt32(16,n[4],!1),r},u=function(){function e(t){if(function(t,n){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this),(t=t||65536)%64>0)throw new Error("Chunk size must be a multiple of 128 bit");this._offset=0,this._maxChunkLen=t,this._padMaxChunkLen=h(t),this._heap=new ArrayBuffer(o(this._padMaxChunkLen+320+20)),this._h32=new Int32Array(this._heap),this._h8=new Int8Array(this._heap),this._core=new r({Int32Array:Int32Array},{},this._heap)}return e.prototype._initState=function(e,t){this._offset=0;var n=new Int32Array(e,t+320,5);n[0]=1732584193,n[1]=-271733879,n[2]=-1732584194,n[3]=271733878,n[4]=-1009589776},e.prototype._padChunk=function(e,t){var n=h(e),r=new Int32Array(this._heap,0,n>>2);return function(e,t){var n=new Uint8Array(e.buffer),r=t%4,i=t-r;switch(r){case 0:n[i+3]=0;case 1:n[i+2]=0;case 2:n[i+1]=0;case 3:n[i+0]=0}for(var s=1+(t>>2);s>2]|=128<<24-(t%4<<3),e[14+(2+(t>>2)&-16)]=n/(1<<29)|0,e[15+(2+(t>>2)&-16)]=n<<3}(r,e,t),n},e.prototype._write=function(e,t,n,r){a(e,this._h8,this._h32,t,n,r||0)},e.prototype._coreCall=function(e,t,n,r,i){var s=n;this._write(e,t,n),i&&(s=this._padChunk(n,r)),this._core.hash(s,this._padMaxChunkLen)},e.prototype.rawDigest=function(e){var t=e.byteLength||e.length||e.size||0;this._initState(this._heap,this._padMaxChunkLen);var n=0,r=this._maxChunkLen;for(n=0;t>n+r;n+=r)this._coreCall(e,n,r,t,!1);return this._coreCall(e,n,t-n,t,!0),c(this._heap,this._padMaxChunkLen)},e.prototype.digest=function(e){return s(this.rawDigest(e).buffer)},e.prototype.digestFromString=function(e){return this.digest(e)},e.prototype.digestFromBuffer=function(e){return this.digest(e)},e.prototype.digestFromArrayBuffer=function(e){return this.digest(e)},e.prototype.resetState=function(){return this._initState(this._heap,this._padMaxChunkLen),this},e.prototype.append=function(e){var t=0,n=e.byteLength||e.length||e.size||0,r=this._offset%this._maxChunkLen,i=void 0;for(this._offset+=n;t0},!1)}e.exports=function(e,t){t=t||{};var i={main:n.m},s=t.all?{main:Object.keys(i)}:function(e,t){for(var n={main:[t]},r={main:[]},i={main:{}};h(n);)for(var s=Object.keys(n),o=0;o>2]|0;a=r[t+324>>2]|0;c=r[t+328>>2]|0;d=r[t+332>>2]|0;f=r[t+336>>2]|0;for(n=0;(n|0)<(e|0);n=n+64|0){o=s;h=a;u=c;l=d;p=f;for(i=0;(i|0)<64;i=i+4|0){m=r[n+i>>2]|0;g=((s<<5|s>>>27)+(a&c|~a&d)|0)+((m+f|0)+1518500249|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[e+i>>2]=m}for(i=e+64|0;(i|0)<(e+80|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a&c|~a&d)|0)+((m+f|0)+1518500249|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+80|0;(i|0)<(e+160|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a^c^d)|0)+((m+f|0)+1859775393|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+160|0;(i|0)<(e+240|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a&c|a&d|c&d)|0)+((m+f|0)-1894007588|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}for(i=e+240|0;(i|0)<(e+320|0);i=i+4|0){m=(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])<<1|(r[i-12>>2]^r[i-32>>2]^r[i-56>>2]^r[i-64>>2])>>>31;g=((s<<5|s>>>27)+(a^c^d)|0)+((m+f|0)-899497514|0)|0;f=d;d=c;c=a<<30|a>>>2;a=s;s=g;r[i>>2]=m}s=s+o|0;a=a+h|0;c=c+u|0;d=d+l|0;f=f+p|0}r[t+320>>2]=s;r[t+324>>2]=a;r[t+328>>2]=c;r[t+332>>2]=d;r[t+336>>2]=f}return{hash:i}}},function(e,t){var n=this,r=void 0;"undefined"!=typeof self&&void 0!==self.FileReaderSync&&(r=new self.FileReaderSync);var i=function(e,t,n,r,i,s){var o=void 0,a=s%4,h=(i+a)%4,c=i-h;switch(a){case 0:t[s]=e[r+3];case 1:t[s+1-(a<<1)|0]=e[r+2];case 2:t[s+2-(a<<1)|0]=e[r+1];case 3:t[s+3-(a<<1)|0]=e[r]}if(!(i>2|0]=e[r+o]<<24|e[r+o+1]<<16|e[r+o+2]<<8|e[r+o+3];switch(h){case 3:t[s+c+1|0]=e[r+c+2];case 2:t[s+c+2|0]=e[r+c+1];case 1:t[s+c+3|0]=e[r+c]}}};e.exports=function(e,t,s,o,a,h){if("string"==typeof e)return function(e,t,n,r,i,s){var o=void 0,a=s%4,h=(i+a)%4,c=i-h;switch(a){case 0:t[s]=e.charCodeAt(r+3);case 1:t[s+1-(a<<1)|0]=e.charCodeAt(r+2);case 2:t[s+2-(a<<1)|0]=e.charCodeAt(r+1);case 3:t[s+3-(a<<1)|0]=e.charCodeAt(r)}if(!(i>2]=e.charCodeAt(r+o)<<24|e.charCodeAt(r+o+1)<<16|e.charCodeAt(r+o+2)<<8|e.charCodeAt(r+o+3);switch(h){case 3:t[s+c+1|0]=e.charCodeAt(r+c+2);case 2:t[s+c+2|0]=e.charCodeAt(r+c+1);case 1:t[s+c+3|0]=e.charCodeAt(r+c)}}}(e,t,s,o,a,h);if(e instanceof Array)return i(e,t,s,o,a,h);if(n&&n.Buffer&&n.Buffer.isBuffer(e))return i(e,t,s,o,a,h);if(e instanceof ArrayBuffer)return i(new Uint8Array(e),t,s,o,a,h);if(e.buffer instanceof ArrayBuffer)return i(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),t,s,o,a,h);if(e instanceof Blob)return function(e,t,n,i,s,o){var a=void 0,h=o%4,c=(s+h)%4,u=s-c,d=new Uint8Array(r.readAsArrayBuffer(e.slice(i,i+s)));switch(h){case 0:t[o]=d[3];case 1:t[o+1-(h<<1)|0]=d[2];case 2:t[o+2-(h<<1)|0]=d[1];case 3:t[o+3-(h<<1)|0]=d[0]}if(!(s>2|0]=d[a]<<24|d[a+1]<<16|d[a+2]<<8|d[a+3];switch(c){case 3:t[o+u+1|0]=d[u+2];case 2:t[o+u+2|0]=d[u+1];case 1:t[o+u+3|0]=d[u]}}}(e,t,s,o,a,h);throw new Error("Unsupported data type.")}},function(e,t,n){var r=n(0),i=n(1).toHex,s=function(){function e(){!function(t,n){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this),this._rusha=new r,this._rusha.resetState()}return e.prototype.update=function(e){return this._rusha.append(e),this},e.prototype.digest=function(e){var t=this._rusha.rawEnd().buffer;if(!e)return t;if("hex"===e)return i(t);throw new Error("unsupported digest encoding")},e}();e.exports=function(){return new s}}])},"object"==typeof At.exports?At.exports=Ct():"object"==typeof At.exports?At.exports.Rusha=Ct():St.Rusha=Ct(),At=At.exports;var Rt={},Lt=new At,Bt="undefined"!=typeof window?window:self,Ut=Bt.crypto||Bt.msCrypto||{},Ot=Ut.subtle||Ut.webkitSubtle;function Mt(e){return Lt.digest(e)}try{Ot.digest({name:"sha-1"},new Uint8Array).catch(function(){Ot=!1})}catch(li){Ot=!1}(Rt=function(e,t){Ot?("string"==typeof e&&(e=function(e){for(var t=e.length,n=new Uint8Array(t),r=0;r>>4).toString(16)),n.push((15&i).toString(16))}return n.join("")}(new Uint8Array(e)))},function(){t(Mt(e))})):"undefined"!=typeof window?function(e,t){xt||(xt=At.createWorker(),Tt=1,It={},xt.onmessage=function(e){var t=e.data.id,n=It[t];delete It[t],null!=e.data.error?n(new Error("Rusha worker error: "+e.data.error)):n(null,e.data.hash)}),It[Tt]=t,xt.postMessage({id:Tt,data:e}),Tt+=1}(e,function(n,r){t(n?Mt(e):r)}):queueMicrotask(()=>t(Mt(e)))}).sync=Mt;var Pt={};(function(e,t,n){function r(e){return e.reduce((e,t)=>Array.isArray(t)?e.concat(r(t)):e.concat(t),[])}function i(t,i,a){if("undefined"!=typeof FileList&&t instanceof FileList&&(t=Array.from(t)),Array.isArray(t)||(t=[t]),0===t.length)throw new Error("invalid input type");t.forEach(e=>{if(null==e)throw new Error(`invalid input type: ${e}`)}),1!==(t=t.map(e=>h(e)&&"string"==typeof e.path&&"function"==typeof ut.stat?e.path:e)).length||"string"==typeof t[0]||t[0].name||(t[0].name=i.name);let u=null;t.forEach((e,n)=>{if("string"==typeof e)return;let r=e.fullPath||e.name;r||(r=`Unknown File ${n+1}`,e.unknownName=!0),e.path=r.split("/"),e.path[0]||e.path.shift(),e.path.length<2?u=null:0===n&&t.length>1?u=e.path[0]:e.path[0]!==u&&(u=null)}),t=t.filter(e=>{if("string"==typeof e)return!0;const t=e.path[e.path.length-1];return o(t)&&ft.not(t)}),u&&t.forEach(e=>{const t=(n.isBuffer(e)||c(e))&&!e.path;"string"==typeof e||t||e.path.shift()}),!i.name&&u&&(i.name=u),i.name||t.some(e=>"string"==typeof e?(i.name=et.basename(e),!0):e.unknownName?void 0:(i.name=e.path[e.path.length-1],!0)),i.name||(i.name=`Unnamed Torrent ${Date.now()}`);const d=t.reduce((e,t)=>e+Number("string"==typeof t),0);let l=1===t.length;if(1===t.length&&"string"==typeof t[0]){if("function"!=typeof ut.stat)throw new Error("filesystem paths do not work in the browser");dt(t[0],(e,t)=>{if(e)return a(e);l=t,f()})}else e.nextTick(()=>{f()});function f(){kt(t.map(e=>t=>{const i={};if(h(e))i.getStream=function(e){return()=>new ct(e)}(e),i.length=e.size;else if(n.isBuffer(e))i.getStream=function(e){return()=>{const t=new Ze.PassThrough;return t.end(e),t}}(e),i.length=e.length;else{if(!c(e)){if("string"==typeof e){if("function"!=typeof ut.stat)throw new Error("filesystem paths do not work in the browser");return void function(e,t,n){!function e(t,n,r){ut.stat(t,(i,s)=>{if(i)return r(i);s.isDirectory()?ut.readdir(t,(i,s)=>{if(i)return r(i);kt(s.filter(o).filter(ft.not).map(r=>i=>{e(et.join(t,r),n,i)}),r)}):s.isFile()&&n(t,r)})}(e,s,(i,s)=>{if(i)return n(i);s=Array.isArray(s)?r(s):[s],e=et.normalize(e),t&&(e=e.slice(0,e.lastIndexOf(et.sep)+1)),e[e.length-1]!==et.sep&&(e+=et.sep),s.forEach(t=>{t.getStream=function(e){return()=>ut.createReadStream(e)}(t.path),t.path=t.path.replace(e,"").split(et.sep)}),n(null,s)})}(e,d>1||l,t)}throw new Error("invalid input type")}i.getStream=function(e,t){return()=>{const n=new Ze.Transform;return n._transform=function(e,n,r){t.length+=e.length,this.push(e),r()},e.pipe(n),n}}(e,i),i.length=0}i.path=e.path,t(null,i)}),(e,t)=>{if(e)return a(e);t=r(t),a(null,t,l)})}}function s(e,t){t=wt(t),ut.stat(e,(n,r)=>{if(n)return t(n);const i={length:r.size,path:e};t(null,i)})}function o(e){return"."!==e[0]}function a(e,t){return e+t.length}function h(e){return"undefined"!=typeof Blob&&e instanceof Blob}function c(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(Pt=function(e,r,s){"function"==typeof r&&([r,s]=[s,r]),i(e,r=r?Object.assign({},r):{},(e,i,o)=>{if(e)return s(e);r.singleFileTorrent=o,function(e,r,i){let s=r.announceList;s||("string"==typeof r.announce?s=[[r.announce]]:Array.isArray(r.announce)&&(s=r.announce.map(e=>[e]))),s||(s=[]),t.WEBTORRENT_ANNOUNCE&&("string"==typeof t.WEBTORRENT_ANNOUNCE?s.push([[t.WEBTORRENT_ANNOUNCE]]):Array.isArray(t.WEBTORRENT_ANNOUNCE)&&(s=s.concat(t.WEBTORRENT_ANNOUNCE.map(e=>[e])))),void 0===r.announce&&void 0===r.announceList&&(s=s.concat(Pt.announceList)),"string"==typeof r.urlList&&(r.urlList=[r.urlList]);const o={info:{name:r.name},"creation date":Math.ceil((Number(r.creationDate)||Date.now())/1e3),encoding:"UTF-8"};0!==s.length&&(o.announce=s[0][0],o["announce-list"]=s),void 0!==r.comment&&(o.comment=r.comment),void 0!==r.createdBy&&(o["created by"]=r.createdBy),void 0!==r.private&&(o.info.private=Number(r.private)),void 0!==r.info&&Object.assign(o.info,r.info),void 0!==r.sslCert&&(o.info["ssl-cert"]=r.sslCert),void 0!==r.urlList&&(o["url-list"]=r.urlList);const h=r.pieceLength||(c=e.reduce(a,0),Math.max(16384,1<e.getStream);let a=0,h=0,c=!1;const u=new pt(o),d=new Qe(t,{zeroPadding:!1});function l(e){s+=e.length;const t=h;Rt(e,e=>{i[t]=e,a-=1,m()}),a+=1,h+=1}function f(){c=!0,m()}function p(e){g(),r(e)}function g(){u.removeListener("error",p),d.removeListener("data",l),d.removeListener("end",f),d.removeListener("error",p)}function m(){c&&0===a&&(g(),r(null,n.from(i.join(""),"hex"),s))}u.on("error",p),u.pipe(d).on("data",l).on("end",f).on("error",p)}(e,h,(t,n,s)=>{if(t)return i(t);o.info.pieces=n,e.forEach(e=>{delete e.getStream}),r.singleFileTorrent?o.info.length=s:o.info.files=e,i(null,Z.encode(o))})}(i,r,s)})}).parseInput=function(e,t,n){"function"==typeof t&&([t,n]=[n,t]),i(e,t=t?Object.assign({},t):{},n)},Pt.announceList=[["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://tracker.opentrackr.org:1337"],["udp://explodie.org:6969"],["udp://tracker.empire-js.us:1337"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"],["wss://tracker.fastcast.nz"]]}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u({}).Buffer);var Nt={};(function(e){Nt.log=function(...e){return"object"==typeof console&&console.log&&console.log(...e)},Nt.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Nt.humanize(this.diff),!this.useColors)return;const t="color: "+this.color;e.splice(1,0,t,"color: inherit");let n=0,r=0;e[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(r=n))}),e.splice(r,0,t)},Nt.save=function(e){try{e?Nt.storage.setItem("debug",e):Nt.storage.removeItem("debug")}catch(t){}},Nt.load=function(){let t;try{t=Nt.storage.getItem("debug")}catch(n){}return!t&&void 0!==e&&"env"in e&&(t=e.env.DEBUG),t},Nt.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+)/))},Nt.storage=function(){try{return localStorage}catch(e){}}(),Nt.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"],Nt=function(e){function t(e){let t=0;for(let n=0;n{if("%%"===r)return r;a++;const s=n.formatters[i];if("function"==typeof s){const n=e[a];r=s.call(t,n),e.splice(a,1),a--}return r}),n.formatArgs.call(t,e),(t.log||n.log).apply(t,e)}return o.namespace=e,o.enabled=n.enabled(e),o.useColors=n.useColors(),o.color=t(e),o.destroy=i,o.extend=s,"function"==typeof n.init&&n.init(o),n.instances.push(o),o}function i(){const e=n.instances.indexOf(this);return-1!==e&&(n.instances.splice(e,1),!0)}function s(e,t){const r=n(this.namespace+(void 0===t?":":t)+e);return r.log=this.log,r}function o(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return n.debug=n,n.default=n,n.coerce=function(e){return e instanceof Error?e.stack||e.message:e},n.disable=function(){const e=[...n.names.map(o),...n.skips.map(o).map(e=>"-"+e)].join(",");return n.enable(""),e},n.enable=function(e){let t;n.save(e),n.names=[],n.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(t=0;t{n[t]=e[t]}),n.instances=[],n.names=[],n.skips=[],n.formatters={},n.selectColor=t,n.enable(n.load()),n}(Nt);const{formatters:t}=Nt;t.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}).call(this,ce);var jt={};(function(e){jt=function(t,n){if("undefined"==typeof Blob||!(t instanceof Blob))throw new Error("first argument must be a Blob");if("function"!=typeof n)throw new Error("second argument must be a function");var r=new FileReader;r.addEventListener("loadend",function t(i){r.removeEventListener("loadend",t,!1),i.error?n(i.error):n(null,e.from(r.result))},!1),r.readAsArrayBuffer(t)}}).call(this,u({}).Buffer);var Ht={};(function(e){var t;function n(){if(void 0!==t)return t;if(e.XMLHttpRequest){t=new e.XMLHttpRequest;try{t.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(n){t=null}}else t=null;return t}function r(e){var t=n();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(r){}return!1}function i(e){return"function"==typeof e}Ht.fetch=i(e.fetch)&&i(e.ReadableStream),Ht.writableStream=i(e.WritableStream),Ht.abortController=i(e.AbortController),Ht.arraybuffer=Ht.fetch||r("arraybuffer"),Ht.msstream=!Ht.fetch&&r("ms-stream"),Ht.mozchunkedarraybuffer=!Ht.fetch&&r("moz-chunked-arraybuffer"),Ht.overrideMimeType=Ht.fetch||!!n()&&i(n().overrideMimeType),t=null}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Dt={};(function(e,t,n){var r=Dt.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},i=Dt.IncomingMessage=function(r,i,s,o){var a=this;if(Ze.Readable.call(a),a._mode=s,a.headers={},a.rawHeaders=[],a.trailers={},a.rawTrailers=[],a.on("end",function(){e.nextTick(function(){a.emit("close")})}),"fetch"===s){if(a._fetchResponse=i,a.url=i.url,a.statusCode=i.status,a.statusMessage=i.statusText,i.headers.forEach(function(e,t){a.headers[t.toLowerCase()]=e,a.rawHeaders.push(t,e)}),Ht.writableStream){var h=new WritableStream({write:function(e){return new Promise(function(t,r){a._destroyed?r():a.push(n.from(e))?t():a._resumeFetch=t})},close:function(){t.clearTimeout(o),a._destroyed||a.push(null)},abort:function(e){a._destroyed||a.emit("error",e)}});try{return void i.body.pipeTo(h).catch(function(e){t.clearTimeout(o),a._destroyed||a.emit("error",e)})}catch(l){}}var c=i.body.getReader();!function e(){c.read().then(function(r){if(!a._destroyed){if(r.done)return t.clearTimeout(o),void a.push(null);a.push(n.from(r.value)),e()}}).catch(function(e){t.clearTimeout(o),a._destroyed||a.emit("error",e)})}()}else if(a._xhr=r,a._pos=0,a.url=r.responseURL,a.statusCode=r.status,a.statusMessage=r.statusText,r.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var n=t[1].toLowerCase();"set-cookie"===n?(void 0===a.headers[n]&&(a.headers[n]=[]),a.headers[n].push(t[2])):void 0!==a.headers[n]?a.headers[n]+=", "+t[2]:a.headers[n]=t[2],a.rawHeaders.push(t[1],t[2])}}),a._charset="x-user-defined",!Ht.overrideMimeType){var u=a.rawHeaders["mime-type"];if(u){var d=u.match(/;\s*charset=([^;])(;|$)/);d&&(a._charset=d[1].toLowerCase())}a._charset||(a._charset="utf-8")}};Re(i,Ze.Readable),i.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},i.prototype._onXHRProgress=function(){var e=this,i=e._xhr,s=null;switch(e._mode){case"text":if((s=i.responseText).length>e._pos){var o=s.substr(e._pos);if("x-user-defined"===e._charset){for(var a=n.alloc(o.length),h=0;he._pos&&(e.push(n.from(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(s)}e._xhr.readyState===r.DONE&&"ms-stream"!==e._mode&&e.push(null)}}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u({}).Buffer);var qt={};(function(e,t,n){var r=Dt.IncomingMessage,i=Dt.readyStates,s=qt=function(e){var t,r=this;Ze.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+n.from(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var i=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!Ht.abortController)i=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!Ht.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return Ht.fetch&&t?"fetch":Ht.mozchunkedarraybuffer?"moz-chunked-arraybuffer":Ht.msstream?"ms-stream":Ht.arraybuffer&&e?"arraybuffer":"text"}(t,i),r._fetchTimer=null,r.on("finish",function(){r._onFinish()})};Re(s,Ze.Writable),s.prototype.setHeader=function(e,t){var n=e.toLowerCase();-1===o.indexOf(n)&&(this._headers[n]={name:e,value:t})},s.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},s.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},s.prototype._onFinish=function(){var n=this;if(!n._destroyed){var r=n._opts,s=n._headers,o=null;"GET"!==r.method&&"HEAD"!==r.method&&(o=new Blob(n._body,{type:(s["content-type"]||{}).value||""}));var a=[];if(Object.keys(s).forEach(function(e){var t=s[e].name,n=s[e].value;Array.isArray(n)?n.forEach(function(e){a.push([t,e])}):a.push([t,n])}),"fetch"===n._mode){var h=null;if(Ht.abortController){var c=new AbortController;h=c.signal,n._fetchAbortController=c,"requestTimeout"in r&&0!==r.requestTimeout&&(n._fetchTimer=t.setTimeout(function(){n.emit("requestTimeout"),n._fetchAbortController&&n._fetchAbortController.abort()},r.requestTimeout))}t.fetch(n._opts.url,{method:n._opts.method,headers:a,body:o||void 0,mode:"cors",credentials:r.withCredentials?"include":"same-origin",signal:h}).then(function(e){n._fetchResponse=e,n._connect()},function(e){t.clearTimeout(n._fetchTimer),n._destroyed||n.emit("error",e)})}else{var u=n._xhr=new t.XMLHttpRequest;try{u.open(n._opts.method,n._opts.url,!0)}catch(li){return void e.nextTick(function(){n.emit("error",li)})}"responseType"in u&&(u.responseType=n._mode),"withCredentials"in u&&(u.withCredentials=!!r.withCredentials),"text"===n._mode&&"overrideMimeType"in u&&u.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in r&&(u.timeout=r.requestTimeout,u.ontimeout=function(){n.emit("requestTimeout")}),a.forEach(function(e){u.setRequestHeader(e[0],e[1])}),n._response=null,u.onreadystatechange=function(){switch(u.readyState){case i.LOADING:case i.DONE:n._onXHRProgress()}},"moz-chunked-arraybuffer"===n._mode&&(u.onprogress=function(){n._onXHRProgress()}),u.onerror=function(){n._destroyed||n.emit("error",new Error("XHR error"))};try{u.send(o)}catch(li){return void e.nextTick(function(){n.emit("error",li)})}}}},s.prototype._onXHRProgress=function(){(function(e){try{var t=e.status;return null!==t&&0!==t}catch(n){return!1}})(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},s.prototype._connect=function(){var e=this;e._destroyed||(e._response=new r(e._xhr,e._fetchResponse,e._mode,e._fetchTimer),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},s.prototype._write=function(e,t,n){this._body.push(e),n()},s.prototype.abort=s.prototype.destroy=function(){this._destroyed=!0,t.clearTimeout(this._fetchTimer),this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},s.prototype.end=function(e,t,n){"function"==typeof e&&(n=e,e=void 0),Ze.Writable.prototype.end.call(this,e,t,n)},s.prototype.flushHeaders=function(){},s.prototype.setTimeout=function(){},s.prototype.setNoDelay=function(){},s.prototype.setSocketKeepAlive=function(){};var o=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u({}).Buffer);var Ft=Object.prototype.hasOwnProperty,Wt={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},zt={exports:{}};(function(e){!function(t){var n="object"==typeof zt.exports&&zt.exports&&!zt.exports.nodeType&&zt.exports,r=zt&&!zt.nodeType&&zt,i="object"==typeof e&&e;i.global!==i&&i.window!==i&&i.self!==i||(t=i);var s,o,a=2147483647,h=36,c=1,u=26,d=38,l=700,f=72,p=128,g="-",m=/^xn--/,_=/[^\x20-\x7E]/,y=/[\x2E\u3002\uFF0E\uFF61]/g,b={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},w=h-c,v=Math.floor,E=String.fromCharCode;function k(e){throw new RangeError(b[e])}function S(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function C(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+S((e=e.replace(y,".")).split("."),t).join(".")}function x(e){for(var t,n,r=[],i=0,s=e.length;i=55296&&t<=56319&&i65535&&(t+=E((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+E(e)}).join("")}function I(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function A(e,t,n){var r=0;for(e=n?v(e/l):e>>1,e+=v(e/t);e>w*u>>1;r+=h)e=v(e/w);return v(r+(w+1)*e/(e+d))}function R(e){var t,n,r,i,s,o,d,l,m,_,y,b=[],w=e.length,E=0,S=p,C=f;for((n=e.lastIndexOf(g))<0&&(n=0),r=0;r=128&&k("not-basic"),b.push(e.charCodeAt(r));for(i=n>0?n+1:0;i=w&&k("invalid-input"),((l=(y=e.charCodeAt(i++))-48<10?y-22:y-65<26?y-65:y-97<26?y-97:h)>=h||l>v((a-E)/o))&&k("overflow"),E+=l*o,!(l<(m=d<=C?c:d>=C+u?u:d-C));d+=h)o>v(a/(_=h-m))&&k("overflow"),o*=_;C=A(E-s,t=b.length+1,0==s),v(E/t)>a-S&&k("overflow"),S+=v(E/t),E%=t,b.splice(E++,0,S)}return T(b)}function L(e){var t,n,r,i,s,o,d,l,m,_,y,b,w,S,C,T=[];for(b=(e=x(e)).length,t=p,n=0,s=f,o=0;o=t&&yv((a-n)/(w=r+1))&&k("overflow"),n+=(d-t)*w,t=d,o=0;oa&&k("overflow"),y==t){for(l=n,m=h;!(l<(_=m<=s?c:m>=s+u?u:m-s));m+=h)C=l-_,S=h-_,T.push(E(I(_+C%S,0))),l=v(C/S);T.push(E(I(l,0))),s=A(n,w,r==i),n=0,++r}++n,++t}return T.join("")}if(s={version:"1.4.1",ucs2:{decode:x,encode:T},decode:R,encode:L,toASCII:function(e){return C(e,function(e){return _.test(e)?"xn--"+L(e):e})},toUnicode:function(e){return C(e,function(e){return m.test(e)?R(e.slice(4).toLowerCase()):e})}},n&&r)if(zt.exports==n)r.exports=s;else for(o in s)s.hasOwnProperty(o)&&(n[o]=s[o]);else t.punycode=s}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),zt=zt.exports;var $t={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}};function Vt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Gt=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},Kt=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},Yt=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function Jt(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r0&&a>o&&(a=o);for(var h=0;h=0?(c=f.substr(0,p),u=f.substr(p+1)):(c=f,u=""),d=decodeURIComponent(c),l=decodeURIComponent(u),Vt(i,d)?Gt(i[d])?i[d].push(l):i[d]=[i[d],l]:i[d]=l}return i},stringify:function(e,t,n,r){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?Jt(Xt(e),function(r){var i=encodeURIComponent(Kt(r))+n;return Yt(e[r])?Jt(e[r],function(e){return i+encodeURIComponent(Kt(e))}).join(t):i+encodeURIComponent(Kt(e[r]))}).join(t):r?encodeURIComponent(Kt(r))+n+encodeURIComponent(Kt(e)):""}},Qt={};function en(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}Qt.parse=pn;var tn=/^([a-z0-9.+-]+:)/i,nn=/:[0-9]*$/,rn=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,sn=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),on=["'"].concat(sn),an=["%","/","?",";","#"].concat(on),hn=["/","?","#"],cn=/^[+a-z0-9A-Z_-]{0,63}$/,un=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,dn={javascript:!0,"javascript:":!0},ln={javascript:!0,"javascript:":!0},fn={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function pn(e,t,n){if(e&&$t.isObject(e)&&e instanceof en)return e;var r=new en;return r.parse(e,t,n),r}en.prototype.parse=function(e,t,n){if(!$t.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var r=e.indexOf("?"),i=-1!==r&&r127?w+="x":w+=b[v];if(!w.match(cn)){var k=_.slice(0,p),S=_.slice(p+1),C=b.match(un);C&&(k.push(C[1]),S.unshift(C[2])),S.length&&(o="/"+S.join(".")+o),this.hostname=k.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),m||(this.hostname=zt.toASCII(this.hostname));var x=this.port?":"+this.port:"",T=this.hostname||"";this.host=T+x,this.href+=this.host,m&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==o[0]&&(o="/"+o))}if(!dn[c])for(p=0,y=on.length;p0)&&n.host.split("@"))&&(n.auth=C.shift(),n.host=n.hostname=C.shift())),n.search=e.search,n.query=e.query,$t.isNull(n.pathname)&&$t.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!b.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var v=b.slice(-1)[0],E=(n.host||e.host||b.length>1)&&("."===v||".."===v)||""===v,k=0,S=b.length;S>=0;S--)"."===(v=b[S])?b.splice(S,1):".."===v?(b.splice(S,1),k++):k&&(b.splice(S,1),k--);if(!_&&!y)for(;k--;k)b.unshift("..");!_||""===b[0]||b[0]&&"/"===b[0].charAt(0)||b.unshift(""),E&&"/"!==b.join("/").substr(-1)&&b.push("");var C,x=""===b[0]||b[0]&&"/"===b[0].charAt(0);return w&&(n.hostname=n.host=x?"":b.length?b.shift():"",(C=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=C.shift(),n.host=n.hostname=C.shift())),(_=_||n.host&&b.length)&&!x&&b.unshift(""),b.length?n.pathname=b.join("/"):(n.pathname=null,n.path=null),$t.isNull(n.pathname)&&$t.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},en.prototype.parseHost=function(){var e=this.host,t=nn.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var gn={};(function(e){var t=gn;t.request=function(t,n){t="string"==typeof t?Qt.parse(t):function(){for(var e={},t=0;tnull!==e&&"object"==typeof e&&"function"==typeof e.pipe;function n(r,i){if(r=Object.assign({maxRedirects:10},"string"==typeof r?{url:r}:r),i=wt(i),r.url){const{hostname:e,port:t,protocol:n,auth:i,path:s}=Qt.parse(r.url);delete r.url,e||t||n||i?Object.assign(r,{hostname:e,port:t,protocol:n,auth:i,path:s}):r.path=s}const s={"accept-encoding":"gzip, deflate"};let o;r.headers&&Object.keys(r.headers).forEach(e=>s[e.toLowerCase()]=r.headers[e]),r.headers=s,r.body?o=r.json&&!t(r.body)?JSON.stringify(r.body):r.body:r.form&&(o="string"==typeof r.form?r.form:Zt.stringify(r.form),r.headers["content-type"]="application/x-www-form-urlencoded"),o&&(r.method||(r.method="POST"),t(o)||(r.headers["content-length"]=e.byteLength(o)),r.json&&!r.form&&(r.headers["content-type"]="application/json")),delete r.body,delete r.form,r.json&&(r.headers.accept="application/json"),r.method&&(r.method=r.method.toUpperCase());const a=("https:"===r.protocol?mn:gn).request(r,e=>{if(e.statusCode>=300&&e.statusCode<400&&e.headers.location)return r.url=e.headers.location,delete r.headers.host,e.resume(),"POST"===r.method&&[301,302].includes(e.statusCode)&&(r.method="GET",delete r.headers["content-length"],delete r.headers["content-type"]),0==r.maxRedirects--?i(new Error("too many redirects")):n(r,i);const t="function"==typeof te&&"HEAD"!==r.method;i(null,t?te(e):e)});return a.on("timeout",()=>{a.abort(),i(new Error("Request timed out"))}),a.on("error",i),t(o)?o.on("error",i).pipe(a):a.end(o),a}n.concat=((e,t)=>n(e,(n,r)=>{if(n)return t(n);P(r,(n,i)=>{if(n)return t(n);if(e.json)try{i=JSON.parse(i.toString())}catch(n){return t(n,r,i)}t(null,r,i)})})),["get","post","put","patch","head","delete"].forEach(e=>{n[e]=((t,r)=>("string"==typeof t&&(t={url:t}),n(Object.assign({method:e.toUpperCase()},t),r)))})}).call(this,u({}).Buffer);var vn={};(function(e){"use strict";var t=[255,255,26,27,28,29,30,31,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255];vn.decode=function(n){var r,i=0,s=0,o=0;e.isBuffer(n)||(n=new e(n));for(var a=new e(Math.ceil(5*n.length/8)),h=0;h>>(i=(i+5)%8),a[o]=r,o++,r=255&s<<8-i)}return a.slice(0,o)}}).call(this,u({}).Buffer);var En={};vn.encode,En.decode=vn.decode;var kn=function(e,t,n){return 0===e.length?e:t?(n||e.sort(t),function(e,t){for(var n=1,r=e.length,i=e[0],s=e[0],o=1;o=0?r.split("&"):[]).forEach(e=>{const t=e.split("=");if(2!==t.length)return;const r=t[0];let i=t[1];if("dn"===r&&(i=decodeURIComponent(i).replace(/\+/g," ")),"tr"!==r&&"xs"!==r&&"as"!==r&&"ws"!==r||(i=decodeURIComponent(i)),"kt"===r&&(i=decodeURIComponent(i).split("+")),"ix"===r&&(i=Number(i)),n[r])if(Array.isArray(n[r]))n[r].push(i);else{const e=n[r];n[r]=[e,i]}else n[r]=i}),n.xt&&(Array.isArray(n.xt)?n.xt:[n.xt]).forEach(t=>{if(i=t.match(/^urn:btih:(.{40})/))n.infoHash=i[1].toLowerCase();else if(i=t.match(/^urn:btih:(.{32})/)){const t=En.decode(i[1]);n.infoHash=e.from(t,"binary").toString("hex")}}),n.infoHash&&(n.infoHashBuffer=e.from(n.infoHash,"hex")),n.dn&&(n.name=n.dn),n.kt&&(n.keywords=n.kt),"string"==typeof n.tr?n.announce=[n.tr]:Array.isArray(n.tr)?n.announce=n.tr:n.announce=[],n.urlList=[],("string"==typeof n.as||Array.isArray(n.as))&&(n.urlList=n.urlList.concat(n.as)),("string"==typeof n.ws||Array.isArray(n.ws))&&(n.urlList=n.urlList.concat(n.ws)),kn(n.announce),kn(n.urlList),n}(Sn=t).decode=t,Sn.encode=function(e){(e=Object.assign({},e)).infoHashBuffer&&(e.xt=`urn:btih:${e.infoHashBuffer.toString("hex")}`),e.infoHash&&(e.xt=`urn:btih:${e.infoHash}`),e.name&&(e.dn=e.name),e.keywords&&(e.kt=e.keywords),e.announce&&(e.tr=e.announce),e.urlList&&(e.ws=e.urlList,delete e.as);let t="magnet:?";return Object.keys(e).filter(e=>2===e.length).forEach((n,r)=>{(Array.isArray(e[n])?e[n]:[e[n]]).forEach((e,i)=>{!(r>0||i>0)||"kt"===n&&0!==i||(t+="&"),"dn"===n&&(e=encodeURIComponent(e).replace(/%20/g,"+")),"tr"!==n&&"xs"!==n&&"as"!==n&&"ws"!==n||(e=encodeURIComponent(e)),"kt"===n&&(e=encodeURIComponent(e)),t+="kt"===n&&i>0?`+${e}`:`${n}=${e}`})}),t}}).call(this,u({}).Buffer);var Cn={};(function(e,t){function n(e){if("string"==typeof e&&/^(stream-)?magnet:/.test(e))return Sn(e);if("string"==typeof e&&(/^[a-f0-9]{40}$/i.test(e)||/^[a-z2-7]{32}$/i.test(e)))return Sn(`magnet:?xt=urn:btih:${e}`);if(t.isBuffer(e)&&20===e.length)return Sn(`magnet:?xt=urn:btih:${e.toString("hex")}`);if(t.isBuffer(e))return function(e){t.isBuffer(e)&&(e=Z.decode(e)),i(e.info,"info"),i(e.info["name.utf-8"]||e.info.name,"info.name"),i(e.info["piece length"],"info['piece length']"),i(e.info.pieces,"info.pieces"),e.info.files?e.info.files.forEach(e=>{i("number"==typeof e.length,"info.files[0].length"),i(e["path.utf-8"]||e.path,"info.files[0].path")}):i("number"==typeof e.info.length,"info.length");const n={info:e.info,infoBuffer:Z.encode(e.info),name:(e.info["name.utf-8"]||e.info.name).toString(),announce:[]};n.infoHash=Rt.sync(n.infoBuffer),n.infoHashBuffer=t.from(n.infoHash,"hex"),void 0!==e.info.private&&(n.private=!!e.info.private),e["creation date"]&&(n.created=new Date(1e3*e["creation date"])),e["created by"]&&(n.createdBy=e["created by"].toString()),t.isBuffer(e.comment)&&(n.comment=e.comment.toString()),Array.isArray(e["announce-list"])&&e["announce-list"].length>0?e["announce-list"].forEach(e=>{e.forEach(e=>{n.announce.push(e.toString())})}):e.announce&&n.announce.push(e.announce.toString()),t.isBuffer(e["url-list"])&&(e["url-list"]=e["url-list"].length>0?[e["url-list"]]:[]),n.urlList=(e["url-list"]||[]).map(e=>e.toString()),kn(n.announce),kn(n.urlList);const s=e.info.files||[e.info];n.files=s.map((e,t)=>{const i=[].concat(n.name,e["path.utf-8"]||e.path||[]).map(e=>e.toString());return{path:et.join.apply(null,[et.sep].concat(i)).slice(1),name:i[i.length-1],length:e.length,offset:s.slice(0,t).reduce(r,0)}}),n.length=s.reduce(r,0);const o=n.files[n.files.length-1];return n.pieceLength=e.info["piece length"],n.lastPieceLength=(o.offset+o.length)%n.pieceLength||n.pieceLength,n.pieces=function(e){const t=[];for(let n=0;n{r(null,i)}):"undefined"!=typeof Blob&&t instanceof Blob?jt(t,(e,t)=>{if(e)return r(new Error(`Error converting Blob: ${e.message}`));s(t)}):"function"==typeof wn&&/^https?:/.test(t)?wn.concat({url:t,timeout:3e4,headers:{"user-agent":"WebTorrent (https://webtorrent.io)"}},(e,t,n)=>{if(e)return r(new Error(`Error downloading torrent: ${e.message}`));s(n)}):"function"==typeof ut.readFile&&"string"==typeof t?ut.readFile(t,(e,t)=>{if(e)return r(new Error("Invalid torrent identifier"));s(t)}):e.nextTick(()=>{r(new Error("Invalid torrent identifier"))})},Cn.toMagnetURI=Sn.encode,Cn.toTorrentFile=function(e){const n={info:e.info};return n["announce-list"]=(e.announce||[]).map(e=>(n.announce||(n.announce=e),[e=t.from(e,"utf8")])),n["url-list"]=e.urlList||[],void 0!==e.private&&(n.private=Number(e.private)),e.created&&(n["creation date"]=e.created.getTime()/1e3|0),e.createdBy&&(n["created by"]=e.createdBy),e.comment&&(n.comment=e.comment),Z.encode(n)},t.alloc(0)}).call(this,ce,u({}).Buffer);var xn=function(){if("undefined"==typeof window)return null;var e={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null},Tn={};(function(e,t){"use strict";var n=N.Buffer,r=t.crypto||t.msCrypto;Tn=r&&r.getRandomValues?function(t,i){if(t>4294967295)throw new RangeError("requested too many random bytes");var s=n.allocUnsafe(t);if(t>0)if(t>65536)for(var o=0;ot.destroy(li),0)}t._isReactNativeWebrtc="number"==typeof t._pc._peerConnectionId,t._pc.oniceconnectionstatechange=function(){t._onIceStateChange()},t._pc.onicegatheringstatechange=function(){t._onIceStateChange()},t._pc.onsignalingstatechange=function(){t._onSignalingStateChange()},t._pc.onicecandidate=function(e){t._onIceCandidate(e)},t.initiator?t._setupData({channel:t._pc.createDataChannel(t.channelName,t.channelConfig)}):t._pc.ondatachannel=function(e){t._setupData(e)},t.streams&&t.streams.forEach(function(e){t.addStream(e)}),t._pc.ontrack=function(e){t._onTrack(e)},t.initiator&&t._needsNegotiation(),t._onFinishBound=function(){t._onFinish()},t.once("finish",t._onFinishBound)}function i(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}function s(e,t){var n=new Error(e);return n.code=t,n}Re(r,Ze.Duplex),r.WEBRTC_SUPPORT=!!xn(),r.config={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478?transport=udp"}],sdpSemantics:"unified-plan"},r.channelConfig={},Object.defineProperty(r.prototype,"bufferSize",{get:function(){return this._channel&&this._channel.bufferedAmount||0}}),Object.defineProperty(r.prototype,"connected",{get:function(){return this._connected&&"open"===this._channel.readyState}}),r.prototype.address=function(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}},r.prototype.signal=function(e){var t=this;if(t.destroyed)throw s("cannot signal after peer is destroyed","ERR_SIGNALING");if("string"==typeof e)try{e=JSON.parse(e)}catch(li){e={}}t._debug("signal()"),e.renegotiate&&t.initiator&&(t._debug("got request to renegotiate"),t._needsNegotiation()),e.transceiverRequest&&t.initiator&&(t._debug("got request for transceiver"),t.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(t._pc.localDescription&&t._pc.localDescription.type&&t._pc.remoteDescription&&t._pc.remoteDescription.type?t._addIceCandidate(e.candidate):t._pendingCandidates.push(e.candidate)),e.sdp&&t._pc.setRemoteDescription(new t._wrtc.RTCSessionDescription(e)).then(function(){t.destroyed||(t._pendingCandidates.forEach(function(e){t._addIceCandidate(e)}),t._pendingCandidates=[],"offer"===t._pc.remoteDescription.type&&t._createAnswer())}).catch(function(e){t.destroy(s(e,"ERR_SET_REMOTE_DESCRIPTION"))}),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||t.destroy(s("signal() called with invalid signal data","ERR_SIGNALING"))},r.prototype._addIceCandidate=function(e){var t=this,n=new t._wrtc.RTCIceCandidate(e);t._pc.addIceCandidate(n).catch(function(e){!n.address||n.address.endsWith(".local")?("Ignoring unsupported ICE candidate.",console.warn("Ignoring unsupported ICE candidate.")):t.destroy(s(e,"ERR_ADD_ICE_CANDIDATE"))})},r.prototype.send=function(e){this._channel.send(e)},r.prototype.addTransceiver=function(e,t){if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(li){this.destroy(li)}else this.emit("signal",{transceiverRequest:{kind:e,init:t}})},r.prototype.addStream=function(e){var t=this;t._debug("addStream()"),e.getTracks().forEach(function(n){t.addTrack(n,e)})},r.prototype.addTrack=function(e,t){this._debug("addTrack()");var n=this._senderMap.get(e)||new Map,r=n.get(t);r?r.removed?this.destroy(s("Track has been removed. You should enable/disable tracks that you want to re-add.","ERR_SENDER_REMOVED")):this.destroy(s("Track has already been added to that stream.","ERR_SENDER_ALREADY_ADDED")):(r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation())},r.prototype.replaceTrack=function(e,t,n){this._debug("replaceTrack()");var r=this._senderMap.get(e),i=r?r.get(n):null;i||this.destroy(s("Cannot replace track that was never added.","ERR_TRACK_NOT_ADDED")),t&&this._senderMap.set(t,r),null!=i.replaceTrack?i.replaceTrack(t):this.destroy(s("replaceTrack is not supported in this browser","ERR_UNSUPPORTED_REPLACETRACK"))},r.prototype.removeTrack=function(e,t){this._debug("removeSender()");var n=this._senderMap.get(e),r=n?n.get(t):null;r||this.destroy(s("Cannot remove track that was never added.","ERR_TRACK_NOT_ADDED"));try{r.removed=!0,this._pc.removeTrack(r)}catch(li){"NS_ERROR_UNEXPECTED"===li.name?this._sendersAwaitingStable.push(r):this.destroy(li)}this._needsNegotiation()},r.prototype.removeStream=function(e){var t=this;t._debug("removeSenders()"),e.getTracks().forEach(function(n){t.removeTrack(n,e)})},r.prototype._needsNegotiation=function(){var e=this;e._debug("_needsNegotiation"),e._batchedNegotiation||(e._batchedNegotiation=!0,setTimeout(function(){e._batchedNegotiation=!1,e._debug("starting batched negotiation"),e.negotiate()},0))},r.prototype.negotiate=function(){var e=this;e.initiator?e._isNegotiating?(e._queuedNegotiation=!0,e._debug("already negotiating, queueing")):(e._debug("start negotiation"),setTimeout(()=>{e._createOffer()},0)):e._isNegotiating||(e._debug("requesting negotiation from initiator"),e.emit("signal",{renegotiate:!0})),e._isNegotiating=!0},r.prototype.destroy=function(e){this._destroy(e,function(){})},r.prototype._destroy=function(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.destroyed=!0,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,e&&this.emit("error",e),this.emit("close"),t()}},r.prototype._setupData=function(e){var t=this;if(!e.channel)return t.destroy(s("Data channel event is missing `channel` property","ERR_DATA_CHANNEL"));t._channel=e.channel,t._channel.binaryType="arraybuffer","number"==typeof t._channel.bufferedAmountLowThreshold&&(t._channel.bufferedAmountLowThreshold=65536),t.channelName=t._channel.label,t._channel.onmessage=function(e){t._onChannelMessage(e)},t._channel.onbufferedamountlow=function(){t._onChannelBufferedAmountLow()},t._channel.onopen=function(){t._onChannelOpen()},t._channel.onclose=function(){t._onChannelClose()},t._channel.onerror=function(e){t.destroy(s(e,"ERR_DATA_CHANNEL"))};var n=!1;t._closingInterval=setInterval(function(){t._channel&&"closing"===t._channel.readyState?(n&&t._onChannelClose(),n=!0):n=!1},5e3)},r.prototype._read=function(){},r.prototype._write=function(e,t,n){if(this.destroyed)return n(s("cannot write after peer is destroyed","ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(li){return this.destroy(s(li,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>65536?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n},r.prototype._onFinish=function(){var e=this;function t(){setTimeout(function(){e.destroy()},1e3)}e.destroyed||(e._connected?t():e.once("connect",t))},r.prototype._startIceCompleteTimeout=function(){var e=this;e.destroyed||e._iceCompleteTimer||(e._debug("started iceComplete timeout"),e._iceCompleteTimer=setTimeout(function(){e._iceComplete||(e._iceComplete=!0,e._debug("iceComplete timeout completed"),e.emit("iceTimeout"),e.emit("_iceComplete"))},e.iceCompleteTimeout))},r.prototype._createOffer=function(){var e=this;e.destroyed||e._pc.createOffer(e.offerOptions).then(function(t){function n(){if(!e.destroyed){var n=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:n.type,sdp:n.sdp})}}e.destroyed||(e.trickle||e.allowHalfTrickle||(t.sdp=i(t.sdp)),t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(function(){e._debug("createOffer success"),e.destroyed||(e.trickle||e._iceComplete?n():e.once("_iceComplete",n))}).catch(function(t){e.destroy(s(t,"ERR_SET_LOCAL_DESCRIPTION"))}))}).catch(function(t){e.destroy(s(t,"ERR_CREATE_OFFER"))})},r.prototype._requestMissingTransceivers=function(){var e=this;e._pc.getTransceivers&&e._pc.getTransceivers().forEach(t=>{t.mid||!t.sender.track||t.requested||(t.requested=!0,e.addTransceiver(t.sender.track.kind))})},r.prototype._createAnswer=function(){var e=this;e.destroyed||e._pc.createAnswer(e.answerOptions).then(function(t){function n(){if(!e.destroyed){var n=e._pc.localDescription||t;e._debug("signal"),e.emit("signal",{type:n.type,sdp:n.sdp}),e.initiator||e._requestMissingTransceivers()}}e.destroyed||(e.trickle||e.allowHalfTrickle||(t.sdp=i(t.sdp)),t.sdp=e.sdpTransform(t.sdp),e._pc.setLocalDescription(t).then(function(){e.destroyed||(e.trickle||e._iceComplete?n():e.once("_iceComplete",n))}).catch(function(t){e.destroy(s(t,"ERR_SET_LOCAL_DESCRIPTION"))}))}).catch(function(t){e.destroy(s(t,"ERR_CREATE_ANSWER"))})},r.prototype._onIceStateChange=function(){if(!this.destroyed){var 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(s("Ice connection failed.","ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(s("Ice connection closed.","ERR_ICE_CONNECTION_CLOSED"))}},r.prototype.getStats=function(e){var t=this;function n(e){return"[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach(function(t){Object.assign(e,t)}),e}0===t._pc.getStats.length?t._pc.getStats().then(function(t){var r=[];t.forEach(function(e){r.push(n(e))}),e(null,r)},function(t){e(t)}):t._isReactNativeWebrtc?t._pc.getStats(null,function(t){var r=[];t.forEach(function(e){r.push(n(e))}),e(null,r)},function(t){e(t)}):t._pc.getStats.length>0?t._pc.getStats(function(r){if(!t.destroyed){var i=[];r.result().forEach(function(e){var t={};e.names().forEach(function(n){t[n]=e.stat(n)}),t.id=e.id,t.type=e.type,t.timestamp=e.timestamp,i.push(n(t))}),e(null,i)}},function(t){e(t)}):e(null,[])},r.prototype._maybeReady=function(){var e=this;e._debug("maybeReady pc %s channel %s",e._pcReady,e._channelReady),!e._connected&&!e._connecting&&e._pcReady&&e._channelReady&&(e._connecting=!0,function t(){e.destroyed||e.getStats(function(n,r){if(!e.destroyed){n&&(r=[]);var i={},o={},a={},h=!1;if(r.forEach(function(e){"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(o[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(a[e.id]=e)}),r.forEach(function(e){"transport"===e.type&&e.selectedCandidatePairId&&u(a[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&u(e)}),h||Object.keys(a).length&&!Object.keys(o).length){if(e._connecting=!1,e._connected=!0,e._chunk){try{e.send(e._chunk)}catch(n){return e.destroy(s(n,"ERR_DATA_CHANNEL"))}e._chunk=null,e._debug('sent chunk from "write before connect"');var c=e._cb;e._cb=null,c(null)}"number"!=typeof e._channel.bufferedAmountLowThreshold&&(e._interval=setInterval(function(){e._onInterval()},150),e._interval.unref&&e._interval.unref()),e._debug("connect"),e.emit("connect")}else setTimeout(t,100)}function u(t){h=!0;var n=o[t.localCandidateId];n&&(n.ip||n.address)?(e.localAddress=n.ip||n.address,e.localPort=Number(n.port)):n&&n.ipAddress?(e.localAddress=n.ipAddress,e.localPort=Number(n.portNumber)):"string"==typeof t.googLocalAddress&&(n=t.googLocalAddress.split(":"),e.localAddress=n[0],e.localPort=Number(n[1])),e.localAddress&&(e.localFamily=e.localAddress.includes(":")?"IPv6":"IPv4");var r=i[t.remoteCandidateId];r&&(r.ip||r.address)?(e.remoteAddress=r.ip||r.address,e.remotePort=Number(r.port)):r&&r.ipAddress?(e.remoteAddress=r.ipAddress,e.remotePort=Number(r.portNumber)):"string"==typeof t.googRemoteAddress&&(r=t.googRemoteAddress.split(":"),e.remoteAddress=r[0],e.remotePort=Number(r[1])),e.remoteAddress&&(e.remoteFamily=e.remoteAddress.includes(":")?"IPv6":"IPv4"),e._debug("connect local: %s:%s remote: %s:%s",e.localAddress,e.localPort,e.remoteAddress,e.remotePort)}})}())},r.prototype._onInterval=function(){!this._cb||!this._channel||this._channel.bufferedAmount>65536||this._onChannelBufferedAmountLow()},r.prototype._onSignalingStateChange=function(){var e=this;e.destroyed||("stable"!==e._pc.signalingState||e._firstStable||(e._isNegotiating=!1,e._debug("flushing sender queue",e._sendersAwaitingStable),e._sendersAwaitingStable.forEach(function(t){e._pc.removeTrack(t),e._queuedNegotiation=!0}),e._sendersAwaitingStable=[],e._queuedNegotiation&&(e._debug("flushing negotiation queue"),e._queuedNegotiation=!1,e._needsNegotiation()),e._debug("negotiate"),e.emit("negotiate")),e._firstStable=!1,e._debug("signalingStateChange %s",e._pc.signalingState),e.emit("signalingStateChange",e._pc.signalingState))},r.prototype._onIceCandidate=function(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{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())},r.prototype._onChannelMessage=function(t){if(!this.destroyed){var n=t.data;n instanceof ArrayBuffer&&(n=e.from(n)),this.push(n)}},r.prototype._onChannelBufferedAmountLow=function(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);var e=this._cb;this._cb=null,e(null)}},r.prototype._onChannelOpen=function(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())},r.prototype._onChannelClose=function(){this.destroyed||(this._debug("on channel close"),this.destroy())},r.prototype._onTrack=function(e){var t=this;t.destroyed||e.streams.forEach(function(n){t._debug("on track"),t.emit("track",e.track,n),t._remoteTracks.push({track:e.track,stream:n}),t._remoteStreams.some(function(e){return e.id===n.id})||(t._remoteStreams.push(n),setTimeout(function(){t.emit("stream",n)},0))})},r.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],t.apply(null,e)}}).call(this,u({}).Buffer);var An,Rn=1,Ln=function(){Rn=Rn+1&65535},Bn=function(e){An||(An=setInterval(Ln,250)).unref&&An.unref();var t=4*(e||5),n=[0],r=1,i=Rn-1&65535;return function(e){var s=Rn-i&65535;for(s>t&&(s=t),i=Rn;s--;)r===t&&(r=0),n[r]=n[0===r?t-1:r-1],r++;e&&(n[r-1]+=e);var o=n[r-1],a=n.length>3;return e%8!=0&&t++,t}Nn.exports=class{constructor(e=0,t){const n=null!=t&&t.grow;this.grow=n&&isFinite(n)&&jn(n)||n||0,this.buffer="number"==typeof e?new Uint8Array(jn(e)):e}get(e){const t=e>>3;return t>e%8)}set(e,t=!0){const n=e>>3;if(t){if(this.buffer.length>e%8}else n>e%8))}},Nn=Nn.exports;var Hn=class extends Ze.Writable{constructor(e,t,n={}){if(super(n),!e||!e.put||!e.get)throw new Error("First argument must be an abstract-chunk-store compliant store");if(!(t=Number(t)))throw new Error("Second argument must be a chunk length");this._blockstream=new Qe(t,{zeroPadding:!1}),this._outstandingPuts=0;let r=0;this._blockstream.on("data",t=>{this.destroyed||(this._outstandingPuts+=1,e.put(r,t,()=>{this._outstandingPuts-=1,0===this._outstandingPuts&&"function"==typeof this._finalCb&&(this._finalCb(null),this._finalCb=null)}),r+=1)}).on("error",e=>{this.destroy(e)})}_write(e,t,n){this._blockstream.write(e,t,n)}_final(e){this._blockstream.end(),this._blockstream.once("end",()=>{0===this._outstandingPuts?e(null):this._finalCb=e})}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e),this.emit("close"))}},Dn={};(function(e){Dn.DEFAULT_ANNOUNCE_PEERS=50,Dn.binaryToHex=function(t){return"string"!=typeof t&&(t=String(t)),e.from(t,"binary").toString("hex")},Dn.hexToBinary=function(t){return"string"!=typeof t&&(t=String(t)),e.from(t,"hex").toString("binary")},Object.assign(Dn,te)}).call(this,u({}).Buffer);var qn={};(function(e,t){const n=Nt("simple-websocket"),r="function"!=typeof te?WebSocket:te,i=65536;class s extends Ze.Duplex{constructor(t={}){if("string"==typeof t&&(t={url:t}),super(t=Object.assign({allowHalfOpen:!1},t)),null==t.url&&null==t.socket)throw new Error("Missing required `url` or `socket` option");if(null!=t.url&&null!=t.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=Tn(4).toString("hex").slice(0,7),this._debug("new websocket: %o",t),this.connected=!1,this.destroyed=!1,this._chunk=null,this._cb=null,this._interval=null,t.socket)this.url=t.socket.url,this._ws=t.socket,this.connected=t.socket.readyState===r.OPEN;else{this.url=t.url;try{this._ws="function"==typeof te?new r(t.url,t):new r(t.url)}catch(li){return void e.nextTick(()=>this.destroy(li))}}this._ws.binaryType="arraybuffer",this._ws.onopen=(()=>{this._onOpen()}),this._ws.onmessage=(e=>{this._onMessage(e)}),this._ws.onclose=(()=>{this._onClose()}),this._ws.onerror=(()=>{this.destroy(new Error("connection error to "+this.url))}),this._onFinishBound=(()=>{this._onFinish()}),this.once("finish",this._onFinishBound)}send(e){this._ws.send(e)}destroy(e){this._destroy(e,()=>{})}_destroy(e,t){if(!this.destroyed){if(this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this.connected=!1,this.destroyed=!0,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._ws){const t=this._ws,n=()=>{t.onclose=null};if(t.readyState===r.CLOSED)n();else try{t.onclose=n,t.close()}catch(e){n()}t.onopen=null,t.onmessage=null,t.onerror=(()=>{})}if(this._ws=null,e){if("undefined"!=typeof DOMException&&e instanceof DOMException){const t=e.code;(e=new Error(e.message)).code=t}this.emit("error",e)}this.emit("close"),t()}}_read(){}_write(e,t,n){if(this.destroyed)return n(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(li){return this.destroy(li)}"function"!=typeof te&&this._ws.bufferedAmount>i?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout(()=>this.destroy(),1e3)};this.connected?e():this.once("connect",e)}_onMessage(e){if(this.destroyed)return;let n=e.data;n instanceof ArrayBuffer&&(n=t.from(n)),this.push(n)}_onOpen(){if(!this.connected&&!this.destroyed){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(li){return this.destroy(li)}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"function"!=typeof te&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_onInterval(){if(!this._cb||!this._ws||this._ws.bufferedAmount>i)return;this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onClose(){this.destroyed||(this._debug("on close"),this.destroy())}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],n.apply(null,e)}}s.WEBSOCKET_SUPPORT=!!r,qn=s}).call(this,ce,u({}).Buffer);var Fn=class extends d{constructor(e,t){super(),this.client=e,this.announceUrl=t,this.interval=null,this.destroyed=!1}setInterval(e){null==e&&(e=this.DEFAULT_ANNOUNCE_INTERVAL),clearInterval(this.interval),e&&(this.interval=setInterval(()=>{this.announce(this.client._defaultAnnounceOpts())},e),this.interval.unref&&this.interval.unref())}},Wn={};const zn=Nt("bittorrent-tracker:websocket-tracker"),$n={},Vn=1e4,Gn=18e5,Kn=12e4,Yn=5e4;class Jn extends Fn{constructor(e,t,n){super(e,t),zn("new websocket tracker %s",t),this.peers={},this.socket=null,this.reconnecting=!1,this.retries=0,this.reconnectTimer=null,this.expectingResponse=!1,this._openSocket()}announce(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.announce(e)});const t=Object.assign({},e,{action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary});if(this._trackerId&&(t.trackerid=this._trackerId),"stopped"===e.event||"completed"===e.event)this._send(t);else{const n=Math.min(e.numwant,10);this._generateOffers(n,e=>{t.numwant=n,t.offers=e,this._send(t)})}}scrape(e){if(this.destroyed||this.reconnecting)return;if(!this.socket.connected)return void this.socket.once("connect",()=>{this.scrape(e)});const t={action:"scrape",info_hash:Array.isArray(e.infoHash)&&e.infoHash.length>0?e.infoHash.map(e=>e.toString("binary")):e.infoHash&&e.infoHash.toString("binary")||this.client._infoHashBinary};this._send(t)}destroy(e=Xn){if(this.destroyed)return e(null);this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer);for(const i in this.peers){const e=this.peers[i];clearTimeout(e.trackerTimeout),e.destroy()}if(this.peers=null,this.socket&&(this.socket.removeListener("connect",this._onSocketConnectBound),this.socket.removeListener("data",this._onSocketDataBound),this.socket.removeListener("close",this._onSocketCloseBound),this.socket.removeListener("error",this._onSocketErrorBound),this.socket=null),this._onSocketConnectBound=null,this._onSocketErrorBound=null,this._onSocketDataBound=null,this._onSocketCloseBound=null,$n[this.announceUrl]&&($n[this.announceUrl].consumers-=1),$n[this.announceUrl].consumers>0)return e();let t=$n[this.announceUrl];if(delete $n[this.announceUrl],t.on("error",Xn),t.once("close",e),!this.expectingResponse)return r();var n=setTimeout(r,Dn.DESTROY_TIMEOUT);function r(){n&&(clearTimeout(n),n=null),t.removeListener("data",r),t.destroy(),t=null}t.once("data",r)}_openSocket(){this.destroyed=!1,this.peers||(this.peers={}),this._onSocketConnectBound=(()=>{this._onSocketConnect()}),this._onSocketErrorBound=(e=>{this._onSocketError(e)}),this._onSocketDataBound=(e=>{this._onSocketData(e)}),this._onSocketCloseBound=(()=>{this._onSocketClose()}),this.socket=$n[this.announceUrl],this.socket?($n[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound()):(this.socket=$n[this.announceUrl]=new qn(this.announceUrl),this.socket.consumers=1,this.socket.once("connect",this._onSocketConnectBound)),this.socket.on("data",this._onSocketDataBound),this.socket.once("close",this._onSocketCloseBound),this.socket.once("error",this._onSocketErrorBound)}_onSocketConnect(){this.destroyed||this.reconnecting&&(this.reconnecting=!1,this.retries=0,this.announce(this.client._defaultAnnounceOpts()))}_onSocketData(e){if(!this.destroyed){this.expectingResponse=!1;try{e=JSON.parse(e)}catch(li){return void this.client.emit("warning",new Error("Invalid tracker response"))}"announce"===e.action?this._onAnnounceResponse(e):"scrape"===e.action?this._onScrapeResponse(e):this._onSocketError(new Error(`invalid action in WS response: ${e.action}`))}}_onAnnounceResponse(e){if(e.info_hash!==this.client._infoHashBinary)return void zn("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,Dn.binaryToHex(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;zn("received %s from %s for %s",JSON.stringify(e),this.announceUrl,this.client.infoHash);const t=e["failure reason"];if(t)return this.client.emit("warning",new Error(t));const n=e["warning message"];n&&this.client.emit("warning",new Error(n));const r=e.interval||e["min interval"];r&&this.setInterval(1e3*r);const i=e["tracker id"];if(i&&(this._trackerId=i),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:Dn.binaryToHex(e.info_hash)});this.client.emit("update",t)}let s;if(e.offer&&e.peer_id&&(zn("creating peer (from remote offer)"),(s=this._createPeer()).id=Dn.binaryToHex(e.peer_id),s.once("signal",t=>{const n={action:"announce",info_hash:this.client._infoHashBinary,peer_id:this.client._peerIdBinary,to_peer_id:e.peer_id,answer:t,offer_id:e.offer_id};this._trackerId&&(n.trackerid=this._trackerId),this._send(n)}),s.signal(e.offer),this.client.emit("peer",s)),e.answer&&e.peer_id){const t=Dn.binaryToHex(e.offer_id);(s=this.peers[t])?(s.id=Dn.binaryToHex(e.peer_id),s.signal(e.answer),this.client.emit("peer",s),clearTimeout(s.trackerTimeout),s.trackerTimeout=null,delete this.peers[t]):zn(`got unexpected answer: ${JSON.stringify(e.answer)}`)}}_onScrapeResponse(e){e=e.files||{};const t=Object.keys(e);0!==t.length?t.forEach(t=>{const n=Object.assign(e[t],{announce:this.announceUrl,infoHash:Dn.binaryToHex(t)});this.client.emit("scrape",n)}):this.client.emit("warning",new Error("invalid scrape response"))}_onSocketClose(){this.destroyed||(this.destroy(),this._startReconnectTimer())}_onSocketError(e){this.destroyed||(this.destroy(),this.client.emit("warning",e),this._startReconnectTimer())}_startReconnectTimer(){const e=Math.floor(Math.random()*Kn)+Math.min(Math.pow(2,this.retries)*Vn,Gn);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.retries++,this._openSocket()},e),this.reconnectTimer.unref&&this.reconnectTimer.unref(),zn("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);zn("send %s",t),this.socket.send(t)}_generateOffers(e,t){const n=this,r=[];zn("generating %s offers",e);for(let o=0;o{r.push({offer:t,offer_id:Dn.hexToBinary(e)}),s()}),t.trackerTimeout=setTimeout(()=>{zn("tracker timeout: destroying peer"),t.trackerTimeout=null,delete n.peers[e],t.destroy()},Yn),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function s(){r.length===e&&(zn("generated %s offers",e),t(r))}s()}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const n=new In(e);return n.once("error",r),n.once("connect",function e(){n.removeListener("error",r),n.removeListener("connect",e)}),n;function r(e){t.client.emit("warning",new Error(`Connection error: ${e.message}`)),n.destroy()}}}function Xn(){}Jn.prototype.DEFAULT_ANNOUNCE_INTERVAL=3e4,Jn._socketPool=$n,Wn=Jn;var Zn={};(function(e,t){const n=Nt("bittorrent-tracker:client");class r extends d{constructor(r={}){if(super(),!r.peerId)throw new Error("Option `peerId` is required");if(!r.infoHash)throw new Error("Option `infoHash` is required");if(!r.announce)throw new Error("Option `announce` is required");if(!e.browser&&!r.port)throw new Error("Option `port` is required");this.peerId="string"==typeof r.peerId?r.peerId:r.peerId.toString("hex"),this._peerIdBuffer=t.from(this.peerId,"hex"),this._peerIdBinary=this._peerIdBuffer.toString("binary"),this.infoHash="string"==typeof r.infoHash?r.infoHash.toLowerCase():r.infoHash.toString("hex"),this._infoHashBuffer=t.from(this.infoHash,"hex"),this._infoHashBinary=this._infoHashBuffer.toString("binary"),n("new client %s",this.infoHash),this.destroyed=!1,this._port=r.port,this._getAnnounceOpts=r.getAnnounceOpts,this._rtcConfig=r.rtcConfig,this._userAgent=r.userAgent,this._wrtc="function"==typeof r.wrtc?r.wrtc():r.wrtc;let i="string"==typeof r.announce?[r.announce]:null==r.announce?[]:r.announce;i=i.map(e=>("/"===(e=e.toString())[e.length-1]&&(e=e.substring(0,e.length-1)),e)),i=kn(i);const s=!1!==this._wrtc&&(!!this._wrtc||In.WEBRTC_SUPPORT),o=t=>{e.nextTick(()=>{this.emit("warning",t)})};this._trackers=i.map(e=>{let t;try{t=new URL(e)}catch(li){return o(new Error(`Invalid tracker URL: ${e}`)),null}const n=t.port;if(n<0||n>65535)return o(new Error(`Invalid tracker port: ${e}`)),null;const r=t.protocol;return"http:"!==r&&"https:"!==r||"function"!=typeof te?"udp:"===r&&"function"==typeof te?new te(this,e):"ws:"!==r&&"wss:"!==r||!s?(o(new Error(`Unsupported tracker protocol: ${e}`)),null):"ws:"===r&&"undefined"!=typeof window&&"https:"===window.location.protocol?(o(new Error(`Unsupported tracker protocol: ${e}`)),null):new Wn(this,e):new te(this,e)}).filter(Boolean)}start(e){(e=this._defaultAnnounceOpts(e)).event="started",n("send `start` %o",e),this._announce(e),this._trackers.forEach(e=>{e.setInterval()})}stop(e){(e=this._defaultAnnounceOpts(e)).event="stopped",n("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),(e=this._defaultAnnounceOpts(e)).event="completed",n("send `complete` %o",e),this._announce(e)}update(e){(e=this._defaultAnnounceOpts(e)).event&&delete e.event,n("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach(t=>{t.announce(e)})}scrape(e){n("send `scrape`"),e||(e={}),this._trackers.forEach(t=>{t.scrape(e)})}setInterval(e){n("setInterval %d",e),this._trackers.forEach(t=>{t.setInterval(e)})}destroy(e){if(this.destroyed)return;this.destroyed=!0,n("destroy");const t=this._trackers.map(e=>t=>{e.destroy(t)});kt(t,e),this._trackers=[],this._getAnnounceOpts=null}_defaultAnnounceOpts(e={}){return null==e.numwant&&(e.numwant=Dn.DEFAULT_ANNOUNCE_PEERS),null==e.uploaded&&(e.uploaded=0),null==e.downloaded&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}r.scrape=((e,n)=>{if(n=wt(n),!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");const i=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:t.from("01234567890123456789"),port:6881}),s=new r(i);s.once("error",n),s.once("warning",n);let o=Array.isArray(e.infoHash)?e.infoHash.length:1;const a={};return s.on("scrape",e=>{if(o-=1,a[e.infoHash]=e,0===o){s.destroy();const e=Object.keys(a);1===e.length?n(null,a[e[0]]):n(null,a)}}),e.infoHash=Array.isArray(e.infoHash)?e.infoHash.map(e=>t.from(e,"hex")):t.from(e.infoHash,"hex"),s.scrape({infoHash:e.infoHash}),s}),Zn=r}).call(this,ce,u({}).Buffer);var Qn={};(function(e){const t=Nt("torrent-discovery"),n=d.EventEmitter;Qn=class extends n{constructor(t){if(super(),!t.peerId)throw new Error("Option `peerId` is required");if(!t.infoHash)throw new Error("Option `infoHash` is required");if(!e.browser&&!t.port)throw new Error("Option `port` is required");this.peerId="string"==typeof t.peerId?t.peerId:t.peerId.toString("hex"),this.infoHash="string"==typeof t.infoHash?t.infoHash.toLowerCase():t.infoHash.toString("hex"),this._port=t.port,this._userAgent=t.userAgent,this.destroyed=!1,this._announce=t.announce||[],this._intervalMs=t.intervalMs||9e5,this._trackerOpts=null,this._dhtAnnouncing=!1,this._dhtTimeout=!1,this._internalDHT=!1,this._onWarning=(e=>{this.emit("warning",e)}),this._onError=(e=>{this.emit("error",e)}),this._onDHTPeer=((e,t)=>{t.toString("hex")===this.infoHash&&this.emit("peer",`${e.host}:${e.port}`,"dht")}),this._onTrackerPeer=(e=>{this.emit("peer",e,"tracker")}),this._onTrackerAnnounce=(()=>{this.emit("trackerAnnounce")});const n=(e,t)=>{const n=new te(t);return n.on("warning",this._onWarning),n.on("error",this._onError),n.listen(e),this._internalDHT=!0,n};!1===t.tracker?this.tracker=null:t.tracker&&"object"==typeof t.tracker?(this._trackerOpts=Object.assign({},t.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),!1===t.dht||"function"!=typeof te?this.dht=null:t.dht&&"function"==typeof t.dht.addNode?this.dht=t.dht:t.dht&&"object"==typeof t.dht?this.dht=n(t.dhtPort,t.dht):this.dht=n(t.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce())}updatePort(e){e!==this._port&&(this._port=e,this.dht&&this._dhtAnnounce(),this.tracker&&(this.tracker.stop(),this.tracker.destroy(()=>{this.tracker=this._createTracker()})))}complete(e){this.tracker&&this.tracker.complete(e)}destroy(e){if(this.destroyed)return;this.destroyed=!0,clearTimeout(this._dhtTimeout);const t=[];this.tracker&&(this.tracker.stop(),this.tracker.removeListener("warning",this._onWarning),this.tracker.removeListener("error",this._onError),this.tracker.removeListener("peer",this._onTrackerPeer),this.tracker.removeListener("update",this._onTrackerAnnounce),t.push(e=>{this.tracker.destroy(e)})),this.dht&&this.dht.removeListener("peer",this._onDHTPeer),this._internalDHT&&(this.dht.removeListener("warning",this._onWarning),this.dht.removeListener("error",this._onError),t.push(e=>{this.dht.destroy(e)})),kt(t,e),this.dht=null,this.tracker=null,this._announce=null}_createTracker(){const e=Object.assign({},this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port,userAgent:this._userAgent}),t=new Zn(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onTrackerPeer),t.on("update",this._onTrackerAnnounce),t.setInterval(this._intervalMs),t.start(),t}_dhtAnnounce(){this._dhtAnnouncing||(t("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,e=>{this._dhtAnnouncing=!1,t("dht announce complete"),e&&this.emit("warning",e),this.emit("dhtAnnounce"),this.destroyed||(this._dhtTimeout=setTimeout(()=>{this._dhtAnnounce()},this._intervalMs+Math.floor(Math.random()*this._intervalMs/5)),this._dhtTimeout.unref&&this._dhtTimeout.unref())}))}}}).call(this,ce);var er={};(function(e){function t(e,n){if(!(this instanceof t))return new t(e,n);if(n||(n={}),this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=Number(n.length)||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1)}function n(t,n,r){e.nextTick(function(){t&&t(n,r)})}er=t,t.prototype.put=function(e,t,r){if(this.closed)return n(r,new Error("Storage is closed"));var i=e===this.lastChunkIndex;return i&&t.length!==this.lastChunkLength?n(r,new Error("Last chunk length must be "+this.lastChunkLength)):i||t.length===this.chunkLength?(this.chunks[e]=t,void n(r,null)):n(r,new Error("Chunk length must be "+this.chunkLength))},t.prototype.get=function(e,t,r){if("function"==typeof t)return this.get(e,null,t);if(this.closed)return n(r,new Error("Storage is closed"));var i=this.chunks[e];if(!i){var s=new Error("Chunk not found");return s.notFound=!0,n(r,s)}if(!t)return n(r,null,i);var o=t.offset||0,a=t.length||i.length-o;n(r,null,i.slice(o,a+o))},t.prototype.close=t.prototype.destroy=function(e){if(this.closed)return n(e,new Error("Storage is closed"));this.closed=!0,this.chunks=null,n(e,null)}}).call(this,ce);var tr={};(function(e){tr=class{constructor(e){if(this.store=e,this.chunkLength=e.chunkLength,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.mem=[]}put(e,t,n){this.mem[e]=t,this.store.put(e,t,t=>{this.mem[e]=null,n&&n(t)})}get(t,n,r){if("function"==typeof n)return this.get(t,null,n);const i=n&&n.offset||0,s=n&&n.length&&i+n.length,o=this.mem[t];if(o)return function(t,n,r){e.nextTick(()=>{t&&t(null,r)})}(r,0,n?o.slice(i,s):o);this.store.get(t,n,r)}close(e){this.store.close(e)}destroy(e){this.store.destroy(e)}}}).call(this,ce);var nr={};(function(e){nr=function(t,n,r){if("number"!=typeof n)throw new Error("second argument must be a Number");var i,s,o,a,h,c=!0;function u(t){function n(){r&&r(t,i),r=null}c?e.nextTick(n):n()}function d(e,n,r){if(i[e]=r,n&&(h=!0),0==--o||n)u(n);else if(!h&&l0,function(t){e||(e=t),t&&h.forEach(i),u||(h.forEach(i),a(e))})});return o.reduce(s)}}).call(this,ce);var hr={};(function(e){const{EventEmitter:t}=d,n=Nt("ut_metadata"),r=1e7,i=1e3,s=16384;hr=(o=>{class a extends t{constructor(t){super(),this._wire=t,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new Nn(0,{grow:i}),e.isBuffer(o)&&this.setMetadata(o)}onHandshake(e,t,n){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||rthis._metadataSize&&(n=this._metadataSize);const r=this.metadata.slice(t,n);this._data(e,r,this._metadataSize)}_onData(e,t,n){t.length>s||!this._fetching||(t.copy(this.metadata,e*s),this._bitfield.set(e),this._checkDone())}_onReject(e){this._remainingRejects>0&&this._fetching?(this._request(e),this._remainingRejects-=1):this.emit("warning",new Error('Peer sent "reject" too much'))}_requestPieces(){if(this._fetching){this.metadata=e.alloc(this._metadataSize);for(let e=0;e0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return a.prototype.name="ut_metadata",a})}).call(this,u({}).Buffer);var cr={parse:function(e){var t=e.split(",").map(function(e){return function(e){if(/^-?\d+$/.test(e))return parseInt(e,10);var t;if(t=e.match(/^(-?\d+)(-|\.\.\.?|\u2025|\u2026|\u22EF)(-?\d+)$/)){var n=t[1],r=t[2],i=t[3];if(n&&i){var s=[],o=(n=parseInt(n))<(i=parseInt(i))?1:-1;"-"!=r&&".."!=r&&"\u2025"!=r||(i+=o);for(var a=n;a!=i;a+=o)s.push(a);return s}}return[]}(e)});return 0===t.length?[]:1===t.length?Array.isArray(t[0])?t[0]:t:t.reduce(function(e,t){return Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]),e.concat(t)})}},ur=function(e){for(var t=0,n=e.length;t127)return!1;return!0},dr=u({}).Buffer,lr=gr,fr="undefined"!=typeof window&&window.MediaSource,pr=60;function gr(e,t){var n=this;if(!(n instanceof gr))return new gr(e,t);if(!fr)throw new Error("web browser lacks MediaSource support");t||(t={}),n._debug=t.debug,n._bufferDuration=t.bufferDuration||pr,n._elem=e,n._mediaSource=new fr,n._streams=[],n.detailedError=null,n._errorHandler=function(){n._elem.removeEventListener("error",n._errorHandler),n._streams.slice().forEach(function(e){e.destroy(n._elem.error)})},n._elem.addEventListener("error",n._errorHandler),n._elem.src=window.URL.createObjectURL(n._mediaSource)}function mr(e,t){var n=this;if(Ze.Writable.call(n),n._wrapper=e,n._elem=e._elem,n._mediaSource=e._mediaSource,n._allStreams=e._streams,n._allStreams.push(n),n._bufferDuration=e._bufferDuration,n._sourceBuffer=null,n._debugBuffers=[],n._openHandler=function(){n._onSourceOpen()},n._flowHandler=function(){n._flow()},n._errorHandler=function(e){n.destroyed||n.emit("error",e)},"string"==typeof t)n._type=t,"open"===n._mediaSource.readyState?n._createSourceBuffer():n._mediaSource.addEventListener("sourceopen",n._openHandler);else if(null===t._sourceBuffer)t.destroy(),n._type=t._type,n._mediaSource.addEventListener("sourceopen",n._openHandler);else{if(!t._sourceBuffer)throw new Error("The argument to MediaElementWrapper.createWriteStream must be a string or a previous stream returned from that function");t.destroy(),n._type=t._type,n._sourceBuffer=t._sourceBuffer,n._debugBuffers=t._debugBuffers,n._sourceBuffer.addEventListener("updateend",n._flowHandler),n._sourceBuffer.addEventListener("error",n._errorHandler)}n._elem.addEventListener("timeupdate",n._flowHandler),n.on("error",function(e){n._wrapper.error(e)}),n.on("finish",function(){if(!n.destroyed&&(n._finished=!0,n._allStreams.every(function(e){return e._finished}))){n._wrapper._dumpDebugData();try{n._mediaSource.endOfStream()}catch(li){}}})}gr.prototype.createWriteStream=function(e){return new mr(this,e)},gr.prototype.error=function(e){this.detailedError||(this.detailedError=e),this._dumpDebugData();try{this._mediaSource.endOfStream("decode")}catch(e){}try{window.URL.revokeObjectURL(this._elem.src)}catch(e){}},gr.prototype._dumpDebugData=function(){this._debug&&(this._debug=!1,this._streams.forEach(function(e,t){var n,r,i;n=e._debugBuffers,r="mediasource-stream-"+t,(i=document.createElement("a")).href=window.URL.createObjectURL(new window.Blob(n)),i.download=r,i.click()}))},Re(mr,Ze.Writable),mr.prototype._onSourceOpen=function(){this.destroyed||(this._mediaSource.removeEventListener("sourceopen",this._openHandler),this._createSourceBuffer())},mr.prototype.destroy=function(e){this.destroyed||(this.destroyed=!0,this._allStreams.splice(this._allStreams.indexOf(this),1),this._mediaSource.removeEventListener("sourceopen",this._openHandler),this._elem.removeEventListener("timeupdate",this._flowHandler),this._sourceBuffer&&(this._sourceBuffer.removeEventListener("updateend",this._flowHandler),this._sourceBuffer.removeEventListener("error",this._errorHandler),"open"===this._mediaSource.readyState&&this._sourceBuffer.abort()),e&&this.emit("error",e),this.emit("close"))},mr.prototype._createSourceBuffer=function(){if(!this.destroyed)if(fr.isTypeSupported(this._type)){if(this._sourceBuffer=this._mediaSource.addSourceBuffer(this._type),this._sourceBuffer.addEventListener("updateend",this._flowHandler),this._sourceBuffer.addEventListener("error",this._errorHandler),this._cb){var e=this._cb;this._cb=null,e()}}else this.destroy(new Error("The provided type is not supported"))},mr.prototype._write=function(e,t,n){var r=this;if(!r.destroyed)if(r._sourceBuffer){if(r._sourceBuffer.updating)return n(new Error("Cannot append buffer while source buffer updating"));var i=function(e){if(e instanceof Uint8Array){if(0===e.byteOffset&&e.byteLength===e.buffer.byteLength)return e.buffer;if("function"==typeof e.buffer.slice)return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}if(dr.isBuffer(e)){for(var t=new Uint8Array(e.length),n=e.length,r=0;rthis._bufferDuration)&&this._cb){var e=this._cb;this._cb=null,e()}},mr.prototype._getBufferDuration=function(){for(var e=this._sourceBuffer.buffered,t=this._elem.currentTime,n=-1,r=0;rt)break;(n>=0||t<=s)&&(n=s)}var o=n-t;return o<0&&(o=0),o};var _r=function(e,t){if(null!=t&&"string"!=typeof t)throw new Error("Invalid mimetype, expected string.");return new Promise((n,r)=>{const i=[];e.on("data",e=>i.push(e)).once("end",()=>{const e=null!=t?new Blob(i,{type:t}):new Blob(i);n(e)}).once("error",r)})},yr=async function(e,t){const n=await _r(e,t);return URL.createObjectURL(n)},br={};(function(e){var t=function(){try{if(!e.isEncoding("latin1"))return!1;var t=e.alloc?e.alloc(4):new e(4);return t.fill("ab","ucs2"),"61006200"===t.toString("hex")}catch(n){return!1}}();function n(e,t,n,r){if(n<0||r>e.length)throw new RangeError("Out of range index");return n>>>=0,(r=void 0===r?e.length:r>>>0)>n&&e.fill(t,n,r),e}br=function(r,i,s,o,a){if(t)return r.fill(i,s,o,a);if("number"==typeof i)return n(r,i,s,o);if("string"==typeof i){if("string"==typeof s?(a=s,s=0,o=r.length):"string"==typeof o&&(a=o,o=r.length),void 0!==a&&"string"!=typeof a)throw new TypeError("encoding must be a string");if("latin1"===a&&(a="binary"),"string"==typeof a&&!e.isEncoding(a))throw new TypeError("Unknown encoding: "+a);if(""===i)return n(r,0,s,o);if(function(e){return 1===e.length&&e.charCodeAt(0)<256}(i))return n(r,i.charCodeAt(0),s,o);i=new e(i,a)}return e.isBuffer(i)?function(e,t,n,r){if(n<0||r>e.length)throw new RangeError("Out of range index");if(r<=n)return e;n>>>=0,r=void 0===r?e.length:r>>>0;for(var i=n,s=t.length;i<=r-s;)t.copy(e,i),i+=s;return i!==r&&t.copy(e,i,0,r-i),e}(r,i,s,o):n(r,0,s,o)}}).call(this,u({}).Buffer);var wr={};(function(e){wr=function(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative');return e.allocUnsafe?e.allocUnsafe(t):new e(t)}}).call(this,u({}).Buffer);var vr={};(function(e){vr=function(t,n,r){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative');if(e.alloc)return e.alloc(t,n,r);var i=wr(t);return 0===t?i:void 0===n?br(i,0):("string"!=typeof r&&(r=void 0),br(i,n,r))}}).call(this,u({}).Buffer);var Er={},kr=Math.pow(2,32);Er.encode=function(e,t,n){t||(t=vr(8)),n||(n=0);var r=Math.floor(e/kr),i=e-r*kr;return t.writeUInt32BE(r,n),t.writeUInt32BE(i,n+4),t},Er.decode=function(e,t){t||(t=0);var n=e.readUInt32BE(t),r=e.readUInt32BE(t+4);return n*kr+r},Er.encode.bytes=8,Er.decode.bytes=8;var Sr={};(function(e){var t={3:"ESDescriptor",4:"DecoderConfigDescriptor",5:"DecoderSpecificInfo",6:"SLConfigDescriptor"};Sr.Descriptor={},Sr.Descriptor.decode=function(n,r,i){var s,o,a=n.readUInt8(r),h=r+1,c=0;do{c=c<<7|127&(s=n.readUInt8(h++))}while(128&s);var u=t[a];return(o=Sr[u]?Sr[u].decode(n,h,i):{buffer:e.from(n.slice(h,h+c))}).tag=a,o.tagName=u,o.length=h-r+c,o.contentsLen=c,o},Sr.DescriptorArray={},Sr.DescriptorArray.decode=function(e,n,r){for(var i=n,s={};i+2<=r;){var o=Sr.Descriptor.decode(e,i,r);i+=o.length,s[t[o.tag]||"Descriptor"+o.tag]=o}return s},Sr.ESDescriptor={},Sr.ESDescriptor.decode=function(e,t,n){var r=e.readUInt8(t+2),i=t+3;return 128&r&&(i+=2),64&r&&(i+=e.readUInt8(i)+1),32&r&&(i+=2),Sr.DescriptorArray.decode(e,i,n)},Sr.DecoderConfigDescriptor={},Sr.DecoderConfigDescriptor.decode=function(e,t,n){var r=e.readUInt8(t),i=Sr.DescriptorArray.decode(e,t+13,n);return i.oti=r,i}}).call(this,u({}).Buffer);var Cr={};(function(e){var n=t({}),r=e.alloc(0);class i extends Ze.PassThrough{constructor(e){super(),this._parent=e,this.destroyed=!1}destroy(e){this.destroyed||(this.destroyed=!0,this._parent.destroy(e),e&&this.emit("error",e),this.emit("close"))}}Cr=class extends Ze.Writable{constructor(e){super(e),this.destroyed=!1,this._pending=0,this._missing=0,this._ignoreEmpty=!1,this._buf=null,this._str=null,this._cb=null,this._ondrain=null,this._writeBuffer=null,this._writeCb=null,this._ondrain=null,this._kick()}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e),this.emit("close"))}_write(e,t,n){if(!this.destroyed){for(var i=!this._str||!this._str._writableState.needDrain;e.length&&!this.destroyed;){if(!this._missing&&!this._ignoreEmpty)return this._writeBuffer=e,void(this._writeCb=n);var s=e.length{this._pending--,this._kick()}),this._cb=t,this._str;var n,r,s}_readBox(){const t=(r,i)=>{this._buffer(r,r=>{i=i?e.concat([i,r]):r;var s=n.readHeaders(i);"number"==typeof s?t(s-i.length,i):(this._pending++,this._headers=s,this.emit("box",s))})};t(8)}stream(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var e=this._headers;return this._headers=null,this._stream(e.contentLen,null)}decode(e){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var t=this._headers;this._headers=null,this._buffer(t.contentLen,r=>{var i=n.decodeWithoutHeaders(t,r);e(i),this._pending--,this._kick()})}ignore(){if(!this._headers)throw new Error("this function can only be called once after 'box' is emitted");var e=this._headers;this._headers=null,this._missing=e.contentLen,0===this._missing&&(this._ignoreEmpty=!0),this._cb=(()=>{this._pending--,this._kick()})}_kick(){if(!this._pending&&(this._buf||this._str||this._readBox(),this._writeBuffer)){var e=this._writeCb,t=this._writeBuffer;this._writeBuffer=null,this._writeCb=null,this._write(t,null,e)}}}}).call(this,u({}).Buffer);var xr={};(function(e,n){var r=t({});function i(){}class s extends Ze.PassThrough{constructor(e){super(),this._parent=e,this.destroyed=!1}destroy(e){this.destroyed||(this.destroyed=!0,this._parent.destroy(e),e&&this.emit("error",e),this.emit("close"))}}xr=class extends Ze.Readable{constructor(e){super(e),this.destroyed=!1,this._finalized=!1,this._reading=!1,this._stream=null,this._drain=null,this._want=!1,this._onreadable=(()=>{this._want&&(this._want=!1,this._read())}),this._onend=(()=>{this._stream=null})}mdat(e,t){this.mediaData(e,t)}mediaData(e,t){var n=new s(this);return this.box({type:"mdat",contentLength:e,encodeBufferLen:8,stream:n},t),n}box(t,s){if(s||(s=i),this.destroyed)return s(new Error("Encoder is destroyed"));var o;if(t.encodeBufferLen&&(o=n.alloc(t.encodeBufferLen)),t.stream)t.buffer=null,o=r.encode(t,o),this.push(o),this._stream=t.stream,this._stream.on("readable",this._onreadable),this._stream.on("end",this._onend),this._stream.on("end",s),this._forward();else{if(o=r.encode(t,o),this.push(o))return e.nextTick(s);this._drain=s}}destroy(e){if(!this.destroyed){if(this.destroyed=!0,this._stream&&this._stream.destroy&&this._stream.destroy(),this._stream=null,this._drain){var t=this._drain;this._drain=null,t(e)}e&&this.emit("error",e),this.emit("close")}}finalize(){this._finalized=!0,this._stream||this._drain||this.push(null)}_forward(){if(this._stream)for(;!this.destroyed;){var e=this._stream.read();if(!e)return void(this._want=!!this._stream);if(!this.push(e))return}}_read(){if(!this._reading&&!this.destroyed){if(this._reading=!0,this._stream&&this._forward(),this._drain){var e=this._drain;this._drain=null,e()}this._reading=!1,this._finalized&&this.push(null)}}}}).call(this,ce,u({}).Buffer);var Tr={decode:e=>new Cr(e),encode:e=>new xr(e)};const{Writable:Ir,PassThrough:Ar}=Ze;var Rr=class extends Ir{constructor(e,t={}){super(t),this.destroyed=!1,this._queue=[],this._position=e||0,this._cb=null,this._buffer=null,this._out=null}_write(e,t,n){let r=!0;for(;;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=e,void(this._cb=n);this._buffer=null;var i=this._queue[0];const t=Math.max(i.start-this._position,0),s=i.end-this._position;if(t>=e.length)return this._position+=e.length,n(null);let o;if(s>e.length){this._position+=e.length,o=0===t?e:e.slice(t),r=i.stream.write(o)&&r;break}this._position+=s,o=0===t&&s===e.length?e:e.slice(t,s),r=i.stream.write(o)&&r,i.last&&i.stream.end(),e=e.slice(s),this._queue.shift()}r?n(null):i.stream.once("drain",n.bind(null,null))}slice(e){if(this.destroyed)return null;Array.isArray(e)||(e=[e]);const t=new Ar;return e.forEach((n,r)=>{this._queue.push({start:n.start,end:n.end,stream:t,last:r===e.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),t}destroy(e){this.destroyed||(this.destroyed=!0,e&&this.emit("error",e))}},Lr={};(function(e){const n=t({});class r{constructor(e,t){this._entries=e,this._countName=t||"count",this._index=0,this._offset=0,this.value=this._entries[0]}inc(){this._offset++,this._offset>=this._entries[this._index][this._countName]&&(this._index++,this._offset=0),this.value=this._entries[this._index]}}Lr=class extends d{constructor(e){super(),this._tracks=[],this._file=e,this._decoder=null,this._findMoov(0)}_findMoov(e){this._decoder&&this._decoder.destroy();let t=0;this._decoder=Tr.decode();const n=this._file.createReadStream({start:e});n.pipe(this._decoder);const r=i=>{"moov"===i.type?(this._decoder.removeListener("box",r),this._decoder.decode(e=>{n.destroy();try{this._processMoov(e)}catch(li){li.message=`Cannot parse mp4 file: ${li.message}`,this.emit("error",li)}})):i.length<4096?(t+=i.length,this._decoder.ignore()):(this._decoder.removeListener("box",r),t+=i.length,n.destroy(),this._decoder.destroy(),this._findMoov(e+t))};this._decoder.on("box",r)}_processMoov(t){const i=t.traks;this._tracks=[],this._hasVideo=!1,this._hasAudio=!1;for(let e=0;e=o.stsz.entries.length)break;if(g+=e,++f>=s.samplesPerChunk){f=0,g=0,p++;const e=o.stsc.entries[m+1];e&&p+1>=e.firstChunk&&m++}_+=t,y.inc(),b&&b.inc(),r&&w++}n.mdia.mdhd.duration=0,n.tkhd.duration=0;const v=s.sampleDescriptionId,E={type:"moov",mvhd:t.mvhd,traks:[{tkhd:n.tkhd,mdia:{mdhd:n.mdia.mdhd,hdlr:n.mdia.hdlr,elng:n.mdia.elng,minf:{vmhd:n.mdia.minf.vmhd,smhd:n.mdia.minf.smhd,dinf:n.mdia.minf.dinf,stbl:{stsd:o.stsd,stts:{version:0,flags:0,entries:[]},ctts:{version:0,flags:0,entries:[]},stsc:{version:0,flags:0,entries:[]},stsz:{version:0,flags:0,entries:[]},stco:{version:0,flags:0,entries:[]},stss:{version:0,flags:0,entries:[]}}}}}],mvex:{mehd:{fragmentDuration:t.mvhd.duration},trexs:[{trackId:n.tkhd.trackId,defaultSampleDescriptionIndex:v,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};this._tracks.push({fragmentSequence:1,trackId:n.tkhd.trackId,timeScale:n.mdia.mdhd.timeScale,samples:d,currSample:null,currTime:null,moov:E,mime:u})}if(0===this._tracks.length)return void this.emit("error",new Error("no playable tracks"));t.mvhd.duration=0,this._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};const o=n.encode(this._ftyp),a=this._tracks.map(t=>{const r=n.encode(t.moov);return{mime:t.mime,init:e.concat([o,r])}});this.emit("ready",a)}seek(e){if(!this._tracks)throw new Error("Not ready yet; wait for 'ready' event");this._fileStream&&(this._fileStream.destroy(),this._fileStream=null);let t=-1;if(this._tracks.map((n,r)=>{n.outStream&&n.outStream.destroy(),n.inStream&&(n.inStream.destroy(),n.inStream=null);const i=n.outStream=Tr.encode(),s=this._generateFragment(r,e);if(!s)return i.finalize();(-1===t||s.ranges[0].start{i.destroyed||i.box(e.moof,t=>{if(t)return this.emit("error",t);i.destroyed||n.inStream.slice(e.ranges).pipe(i.mediaData(e.length,e=>{if(e)return this.emit("error",e);if(i.destroyed)return;const t=this._generateFragment(r);if(!t)return i.finalize();o(t)}))})};o(s)}),t>=0){const e=this._fileStream=this._file.createReadStream({start:t});this._tracks.forEach(n=>{n.inStream=new Rr(t,{highWaterMark:1e7}),e.pipe(n.inStream)})}return this._tracks.map(e=>e.outStream)}_findSampleBefore(e,t){const n=this._tracks[e],r=Math.floor(n.timeScale*t);let i=function(e,t,n,r,i){var s,o;if(void 0===r)r=0;else if((r|=0)<0||r>=e.length)throw new RangeError("invalid lower bound");if(void 0===i)i=e.length-1;else if((i|=0)=e.length)throw new RangeError("invalid upper bound");for(;r<=i;)if((o=+n(e[s=r+(i-r>>>1)],t,s,e))<0)r=s+1;else{if(!(o>0))return s;i=s-1}return~r}(n.samples,r,(e,t)=>e.dts+e.presentationOffset-t);for(-1===i?i=0:i<0&&(i=-i-2);!n.samples[i].sync;)i--;return i}_generateFragment(e,t){const n=this._tracks[e];let r;if((r=void 0!==t?this._findSampleBefore(e,t):n.currSample)>=n.samples.length)return null;const i=n.samples[r].dts;let s=0;const o=[];for(var a=r;a=1*n.timeScale)break;s+=e.size;const t=o.length-1;t<0||o[t].end!==e.offset?o.push({start:e.offset,end:e.offset+e.size}):o[t].end+=e.size}return n.currSample=a,{moof:this._generateMoof(e,r,a),ranges:o,length:s}}_generateMoof(e,t,r){const i=this._tracks[e],s=[];let o=0;for(let n=t;n{this.detailedError=this._elemWrapper.detailedError,this.destroy()}),this._onWaiting=(()=>{this._waitingFired=!0,this._muxer?this._tracks&&this._pump():this._createMuxer()}),t.autoplay&&(t.preload="auto"),t.addEventListener("waiting",this._onWaiting),t.addEventListener("error",this._onError)}Ur.prototype={_createMuxer(){this._muxer=new Lr(this._file),this._muxer.on("ready",e=>{this._tracks=e.map(e=>{const t=this._elemWrapper.createWriteStream(e.mime);t.on("error",e=>{this._elemWrapper.error(e)});const n={muxed:null,mediaSource:t,initFlushed:!1,onInitFlushed:null};return t.write(e.init,e=>{n.initFlushed=!0,n.onInitFlushed&&n.onInitFlushed(e)}),n}),(this._waitingFired||"auto"===this._elem.preload)&&this._pump()}),this._muxer.on("error",e=>{this._elemWrapper.error(e)})},_pump(){const e=this._muxer.seek(this._elem.currentTime,!this._tracks);this._tracks.forEach((t,n)=>{const r=()=>{t.muxed&&(t.muxed.destroy(),t.mediaSource=this._elemWrapper.createWriteStream(t.mediaSource),t.mediaSource.on("error",e=>{this._elemWrapper.error(e)})),t.muxed=e[n],ar(t.muxed,t.mediaSource)};t.initFlushed?r():t.onInitFlushed=(e=>{e?this._elemWrapper.error(e):r()})})},destroy(){this.destroyed||(this.destroyed=!0,this._elem.removeEventListener("waiting",this._onWaiting),this._elem.removeEventListener("error",this._onError),this._tracks&&this._tracks.forEach(e=>{e.muxed&&e.muxed.destroy()}),this._elem.src="")}},Br=Ur;var Or={render:function(e,t,n,r){"function"==typeof n&&(r=n,n={}),n||(n={}),r||(r=function(){}),Gr(e),Kr(n),"string"==typeof t&&(t=document.querySelector(t)),$r(e,function(r){if(t.nodeName!==r.toUpperCase()){var i=et.extname(e.name).toLowerCase();throw new Error('Cannot render "'+i+'" inside a "'+t.nodeName.toLowerCase()+'" element, expected "'+r+'"')}return"video"!==r&&"audio"!==r||Yr(t,n),t},n,r)},append:function(e,t,n,r){if("function"==typeof n&&(r=n,n={}),n||(n={}),r||(r=function(){}),Gr(e),Kr(n),"string"==typeof t&&(t=document.querySelector(t)),t&&("VIDEO"===t.nodeName||"AUDIO"===t.nodeName))throw new Error("Invalid video/audio node argument. Argument must be root element that video/audio tag will be appended to.");function i(e){var n=document.createElement(e);return t.appendChild(n),n}$r(e,function(e){return"video"===e||"audio"===e?function(e){var r=i(e);return Yr(r,n),t.appendChild(r),r}(e):i(e)},n,function(e,t){e&&t&&t.remove(),r(e,t)})},mime:{".3gp":"video/3gpp",".aac":"audio/aac",".aif":"audio/x-aiff",".aiff":"audio/x-aiff",".atom":"application/atom+xml",".avi":"video/x-msvideo",".bmp":"image/bmp",".bz2":"application/x-bzip2",".conf":"text/plain",".css":"text/css",".csv":"text/plain",".diff":"text/x-diff",".doc":"application/msword",".flv":"video/x-flv",".gif":"image/gif",".gz":"application/x-gzip",".htm":"text/html",".html":"text/html",".ico":"image/vnd.microsoft.icon",".ics":"text/calendar",".iso":"application/octet-stream",".jar":"application/java-archive",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"application/javascript",".json":"application/json",".less":"text/css",".log":"text/plain",".m3u":"audio/x-mpegurl",".m4a":"audio/x-m4a",".m4b":"audio/mp4",".m4p":"audio/mp4",".m4v":"video/x-m4v",".manifest":"text/cache-manifest",".markdown":"text/x-markdown",".mathml":"application/mathml+xml",".md":"text/x-markdown",".mid":"audio/midi",".midi":"audio/midi",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4v":"video/mp4",".mpeg":"video/mpeg",".mpg":"video/mpeg",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"application/ogg",".pdf":"application/pdf",".png":"image/png",".pps":"application/vnd.ms-powerpoint",".ppt":"application/vnd.ms-powerpoint",".ps":"application/postscript",".psd":"image/vnd.adobe.photoshop",".qt":"video/quicktime",".rar":"application/x-rar-compressed",".rdf":"application/rdf+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swf":"application/x-shockwave-flash",".tar":"application/x-tar",".tbz":"application/x-bzip-compressed-tar",".text":"text/plain",".tif":"image/tiff",".tiff":"image/tiff",".torrent":"application/x-bittorrent",".ttf":"application/x-font-ttf",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".wma":"audio/x-ms-wma",".wmv":"video/x-ms-wmv",".xls":"application/vnd.ms-excel",".xml":"application/xml",".yaml":"text/yaml",".yml":"text/yaml",".zip":"application/zip"}},Mr=Nt("render-media"),Pr=[".m4a",".m4b",".m4p",".m4v",".mp4"],Nr=[".m4v",".mkv",".mp4",".webm"],jr=[].concat(Nr,[".m4a",".m4b",".m4p",".mp3"]),Hr=[".mov",".ogv"],Dr=[".aac",".oga",".ogg",".wav",".flac"],qr=[".bmp",".gif",".jpeg",".jpg",".png",".svg"],Fr=[".css",".html",".js",".md",".pdf",".txt"],Wr=2e8,zr="undefined"!=typeof window&&window.MediaSource;function $r(e,t,n,r){var i,s=et.extname(e.name).toLowerCase(),o=0;function a(){return!("number"==typeof e.length&&e.length>n.maxBlobLength&&(Mr("File length too large for Blob URL approach: %d (max: %d)",e.length,n.maxBlobLength),l(new Error("File length too large for Blob URL approach: "+e.length+" (max: "+n.maxBlobLength+")")),1))}function h(n){a()&&(i=t(n),Vr(e,function(e,t){if(e)return l(e);i.addEventListener("error",l),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),i.src=t}))}function c(){i.removeEventListener("loadstart",c),n.autoplay&&i.play()}function u(){i.removeEventListener("canplay",u),r(null,i)}function d(){Vr(e,function(e,n){if(e)return l(e);".pdf"!==s?((i=t("iframe")).sandbox="allow-forms allow-scripts",i.src=n):((i=t("object")).setAttribute("typemustmatch",!0),i.setAttribute("type","application/pdf"),i.setAttribute("data",n)),r(null,i)})}function l(t){t.message='Error rendering file "'+e.name+'": '+t.message,Mr(t.message),r(t)}jr.indexOf(s)>=0?function(){var n=Nr.indexOf(s)>=0?"video":"audio";function r(){Mr("Use MediaSource API for "+e.name),f(),i.addEventListener("error",d),i.addEventListener("loadstart",c),i.addEventListener("canplay",u);var t,n=new lr(i).createWriteStream((t=e.name,{".m4a":'audio/mp4; codecs="mp4a.40.5"',".m4b":'audio/mp4; codecs="mp4a.40.5"',".m4p":'audio/mp4; codecs="mp4a.40.5"',".m4v":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".mkv":'video/webm; codecs="avc1.640029, mp4a.40.5"',".mp3":"audio/mpeg",".mp4":'video/mp4; codecs="avc1.640029, mp4a.40.5"',".webm":'video/webm; codecs="vorbis, vp8"'}[et.extname(t).toLowerCase()]));e.createReadStream().pipe(n),o&&(i.currentTime=o)}function h(){Mr("Use Blob URL for "+e.name),f(),i.addEventListener("error",l),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),Vr(e,function(e,t){if(e)return l(e);i.src=t,o&&(i.currentTime=o)})}function d(e){Mr("MediaSource API error: fallback to Blob URL: %o",e.message||e),a()&&(i.removeEventListener("error",d),i.removeEventListener("canplay",u),h())}function f(){i||(i=t(n)).addEventListener("progress",function(){o=i.currentTime})}zr?Pr.indexOf(s)>=0?(Mr("Use `videostream` package for "+e.name),f(),i.addEventListener("error",function e(t){Mr("videostream error: fallback to MediaSource API: %o",t.message||t),i.removeEventListener("error",e),i.removeEventListener("canplay",u),r()}),i.addEventListener("loadstart",c),i.addEventListener("canplay",u),Br(e,i)):r():h()}():Hr.indexOf(s)>=0?h("video"):Dr.indexOf(s)>=0?h("audio"):qr.indexOf(s)>=0?(i=t("img"),Vr(e,function(t,n){if(t)return l(t);i.src=n,i.alt=e.name,r(null,i)})):Fr.indexOf(s)>=0?d():function(){Mr('Unknown file extension "%s" - will attempt to render into iframe',s);var t="";e.createReadStream({start:0,end:1e3}).setEncoding("utf8").on("data",function(e){t+=e}).on("end",function(){ur(t)?(Mr('File extension "%s" appears ascii, so will render.',s),d()):(Mr('File extension "%s" appears non-ascii, will not render.',s),r(new Error('Unsupported file type "'+s+'": Cannot append to DOM')))}).on("error",r)}()}function Vr(e,t){var n=et.extname(e.name).toLowerCase();yr(e.createReadStream(),Or.mime[n]).then(e=>t(null,e),e=>t(e))}function Gr(e){if(null==e)throw new Error("file cannot be null or undefined");if("string"!=typeof e.name)throw new Error("missing or invalid file.name property");if("function"!=typeof e.createReadStream)throw new Error("missing or invalid file.createReadStream property")}function Kr(e){null==e.autoplay&&(e.autoplay=!1),null==e.muted&&(e.muted=!1),null==e.controls&&(e.controls=!0),null==e.maxBlobLength&&(e.maxBlobLength=Wr)}function Yr(e,t){e.autoplay=!!t.autoplay,e.muted=!!t.muted,e.controls=!!t.controls}var Jr={};(function(e){Jr=function(t,n,r){r=wt(r);var i=e.alloc(n),s=0;t.on("data",function(e){e.copy(i,s),s+=e.length}).on("end",function(){r(null,i)}).on("error",r)}}).call(this,u({}).Buffer);const Xr=Nt("webtorrent:file-stream");var Zr=class extends Ze.Readable{constructor(e,t){super(t),this.destroyed=!1,this._torrent=e._torrent;const n=t&&t.start||0,r=t&&t.end&&t.end{if(this._notifying=!1,!this.destroyed){if(Xr("read %s (length %s) (err %s)",e,n.length,t&&t.message),t)return this._destroy(t);this._offset&&(n=n.slice(this._offset),this._offset=0),this._missing{t.end()}),t}const r=new Zr(this,t);return this._torrent.select(r._startPiece,r._endPiece,!0,()=>{r._notify()}),or(r,()=>{this._destroyed||this._torrent.destroyed||this._torrent.deselect(r._startPiece,r._endPiece,!0)}),r}getBuffer(e){Jr(this.createReadStream(),this.length,e)}getBlob(e){if("undefined"==typeof window)throw new Error("browser-only method");_r(this.createReadStream(),this._getMimeType()).then(t=>e(null,t),t=>e(t))}getBlobURL(e){if("undefined"==typeof window)throw new Error("browser-only method");yr(this.createReadStream(),this._getMimeType()).then(t=>e(null,t),t=>e(t))}appendTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");Or.append(this,e,t,n)}renderTo(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");Or.render(this,e,t,n)}_getMimeType(){return Or.mime[et.extname(this.name).toLowerCase()]}_destroy(){this._destroyed=!0,this._torrent=null}}}).call(this,ce);var ei=function(e,t){if(!(t>=e.length||t<0)){var n=e.pop();if(t{this.keepAlive()},55e3))}setTimeout(e,t){this._debug("setTimeout ms=%d unref=%s",e,t),this._clearTimeout(),this._timeoutMs=e,this._timeoutUnref=!!t,this._updateTimeout()}destroy(){this.destroyed||(this.destroyed=!0,this._debug("destroy"),this.emit("close"),this.end())}end(...e){this._debug("end"),this._onUninterested(),this._onChoke(),super.end(...e)}use(e){const t=e.prototype.name;if(!t)throw new Error('Extension class requires a "name" property on the prototype');this._debug("use extension.name=%s",t);const n=this._nextExt,r=new e(this);function i(){}"function"!=typeof r.onHandshake&&(r.onHandshake=i),"function"!=typeof r.onExtendedHandshake&&(r.onExtendedHandshake=i),"function"!=typeof r.onMessage&&(r.onMessage=i),this.extendedMapping[n]=t,this._ext[t]=r,this[t]=r,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(r)}handshake(t,r,i){let s,o;if("string"==typeof t?(t=t.toLowerCase(),s=e.from(t,"hex")):t=(s=t).toString("hex"),"string"==typeof r?o=e.from(r,"hex"):r=(o=r).toString("hex"),20!==s.length||20!==o.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",t,r,i);const a=e.from(h);a[5]|=16,i&&i.dht&&(a[7]|=1),this._push(e.concat([n,a,s,o])),this._handshakeSent=!0,this.peerExtensions.extended&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_sendExtendedHandshake(){const e=Object.assign({},this.extendedHandshake);e.m={};for(const t in this.extendedMapping){const n=this.extendedMapping[t];e.m[n]=Number(t)}this.extended(0,Z.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking){for(this.amChoking=!0,this._debug("choke");this.peerRequests.length;)this.peerRequests.pop();this._push(i)}}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(s))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(o))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(a))}have(e){this._debug("have %d",e),this._message(4,[e],null)}bitfield(t){this._debug("bitfield"),e.isBuffer(t)||(t=t.buffer),this._message(5,[],t)}request(e,t,n,r){return r||(r=(()=>{})),this._finished?r(new Error("wire is closed")):this.peerChoking?r(new Error("peer is choking")):(this._debug("request index=%d offset=%d length=%d",e,t,n),this.requests.push(new u(e,t,n,r)),this._updateTimeout(),void this._message(6,[e,t,n],null))}piece(e,t,n){this._debug("piece index=%d offset=%d",e,t),this.uploaded+=n.length,this.uploadSpeed(n.length),this.emit("upload",n.length),this._message(7,[e,t],n)}cancel(e,t,n){this._debug("cancel index=%d offset=%d length=%d",e,t,n),this._callback(this._pull(this.requests,e,t,n),new Error("request was cancelled"),null),this._message(8,[e,t,n],null)}port(t){this._debug("port %d",t);const n=e.from(c);n.writeUInt16BE(t,5),this._push(n)}extended(t,n){if(this._debug("extended ext=%s",t),"string"==typeof t&&this.peerExtendedMapping[t]&&(t=this.peerExtendedMapping[t]),"number"!=typeof t)throw new Error(`Unrecognized extension: ${t}`);{const r=e.from([t]),i=e.isBuffer(n)?n:Z.encode(n);this._message(20,[],e.concat([r,i]))}}_read(){}_message(t,n,r){const i=r?r.length:0,s=e.allocUnsafe(5+4*n.length);s.writeUInt32BE(s.length+i-4,0),s[4]=t;for(let e=0;e{if(i===this._pull(this.peerRequests,e,t,n))return r?this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,n,r.message):void this.piece(e,t,s)};var i=new u(e,t,n,r);this.peerRequests.push(i),this.emit("request",e,t,n,r)}_onPiece(e,t,n){this._debug("got piece index=%d offset=%d",e,t),this._callback(this._pull(this.requests,e,t,n.length),null,n),this.downloaded+=n.length,this.downloadSpeed(n.length),this.emit("download",n.length),this.emit("piece",e,t,n)}_onCancel(e,t,n){this._debug("got cancel index=%d offset=%d length=%d",e,t,n),this._pull(this.peerRequests,e,t,n),this.emit("cancel",e,t,n)}_onPort(e){this._debug("got port %d",e),this.emit("port",e)}_onExtended(e,t){if(0===e){let e,n;try{e=Z.decode(t)}catch(li){this._debug("ignoring invalid extended handshake: %s",li.message||li)}if(!e)return;if(this.peerExtendedHandshake=e,"object"==typeof e.m)for(n in e.m)this.peerExtendedMapping[n]=Number(e.m[n].toString());for(n in this._ext)this.peerExtendedMapping[n]&&this._ext[n].onExtendedHandshake(this.peerExtendedHandshake);this._debug("got extended handshake"),this.emit("extended","handshake",this.peerExtendedHandshake)}else this.extendedMapping[e]&&(e=this.extendedMapping[e],this._ext[e]&&this._ext[e].onMessage(t)),this._debug("got extended message ext=%s",e),this.emit("extended",e,t)}_onTimeout(){this._debug("request timed out"),this._callback(this.requests.shift(),new Error("request has timed out"),null),this.emit("timeout")}_write(t,n,r){for(this._bufferSize+=t.length,this._buffer.push(t);this._bufferSize>=this._parserSize;){const t=1===this._buffer.length?this._buffer[0]:e.concat(this._buffer);this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[t.slice(this._parserSize)]:[],this._parser(t.slice(0,this._parserSize))}r(null)}_callback(e,t,n){e&&(this._clearTimeout(),this.peerChoking||this._finished||this._updateTimeout(),e.callback(t,n))}_clearTimeout(){this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_updateTimeout(){this._timeoutMs&&this.requests.length&&!this._timeout&&(this._timeout=setTimeout(()=>this._onTimeout(),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref())}_parse(e,t){this._parserSize=e,this._parser=t}_onMessageLength(e){const t=e.readUInt32BE(0);t>0?this._parse(t,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(e){switch(this._parse(4,this._onMessageLength),e[0]){case 0:return this._onChoke();case 1:return this._onUnchoke();case 2:return this._onInterested();case 3:return this._onUninterested();case 4:return this._onHave(e.readUInt32BE(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 7:return this._onPiece(e.readUInt32BE(1),e.readUInt32BE(5),e.slice(9));case 8:return this._onCancel(e.readUInt32BE(1),e.readUInt32BE(5),e.readUInt32BE(9));case 9:return this._onPort(e.readUInt16BE(1));case 20:return this._onExtended(e.readUInt8(1),e.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",e)}}_parseHandshake(){this._parse(1,e=>{const t=e.readUInt8(0);this._parse(t+48,e=>{const n=e.slice(0,t);if("BitTorrent protocol"!==n.toString())return this._debug("Error: wire not speaking BitTorrent protocol (%s)",n.toString()),void this.end();e=e.slice(t),this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(1&e[7]),extended:!!(16&e[5])}),this._parse(4,this._onMessageLength)})})}_onFinish(){for(this._finished=!0,this.push(null);this.read(););for(clearInterval(this._keepAliveInterval),this._parse(Number.MAX_VALUE,()=>{});this.peerRequests.length;)this.peerRequests.pop();for(;this.requests.length;)this._callback(this.requests.pop(),new Error("wire was closed"),null)}_debug(...e){e[0]=`[${this._debugId}] ${e[0]}`,t(...e)}_pull(e,t,n,r){for(let i=0;i{if(this.destroyed)return;this.handshake(e,this.webPeerId);const n=this._torrent.pieces.length,r=new Nn(n);for(let i=0;i<=n;i++)r.set(i,!0);this.bitfield(r)}),this.once("interested",()=>{t("interested"),this.unchoke()}),this.on("uninterested",()=>{t("uninterested")}),this.on("choke",()=>{t("choke")}),this.on("unchoke",()=>{t("unchoke")}),this.on("bitfield",()=>{t("bitfield")}),this.on("request",(e,n,r,i)=>{t("request pieceIndex=%d offset=%d length=%d",e,n,r),this.httpRequest(e,n,r,i)})}httpRequest(r,i,s,o){const a=r*this._torrent.pieceLength+i,h=a+s-1,c=this._torrent.files;let u;if(c.length<=1)u=[{url:this.url,start:a,end:h}];else{const e=c.filter(e=>e.offset<=h&&e.offset+e.length>a);if(e.length<1)return o(new Error("Could not find file corresponnding to web seed range request"));u=e.map(e=>{const t=e.offset+e.length-1;return{url:this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path,fileOffsetInRange:Math.max(e.offset-a,0),start:Math.max(a-e.offset,0),end:Math.min(t,h-e.offset)}})}let d,l=0,f=!1;u.length>1&&(d=e.alloc(s)),u.forEach(e=>{const a=e.url,h=e.start,c=e.end;t("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",a,r,i,s,h,c);const p={url:a,method:"GET",headers:{"user-agent":`WebTorrent/${n} (https://webtorrent.io)`,range:`bytes=${h}-${c}`}};function g(n,r){if(n.statusCode<200||n.statusCode>=300)return f=!0,o(new Error(`Unexpected HTTP status code ${n.statusCode}`));t("Got data of length %d",r.length),1===u.length?o(null,r):(r.copy(d,e.fileOffsetInRange),++l===u.length&&o(null,d))}wn.concat(p,(e,t,n)=>{if(!f)return e?"undefined"==typeof window||a.startsWith(`${window.location.origin}/`)?(f=!0,o(e)):wn.head(a,(t,n)=>{if(!f){if(t)return f=!0,o(t);if(n.statusCode<200||n.statusCode>=300)return f=!0,o(new Error(`Unexpected HTTP status code ${n.statusCode}`));if(n.url===a)return f=!0,o(e);p.url=n.url,wn.concat(p,(e,t,n)=>{if(!f)return e?(f=!0,o(e)):void g(t,n)})}}):void g(t,n)})})}destroy(){super.destroy(),this._torrent=null}}}).call(this,u({}).Buffer);var ii={};const si=Nt("webtorrent:peer"),oi=5e3,ai=25e3,hi=25e3;ii.createWebRTCPeer=((e,t)=>{const n=new ci(e.id,"webrtc");return n.conn=e,n.swarm=t,n.conn.connected?n.onConnect():(n.conn.once("connect",()=>{n.onConnect()}),n.conn.once("error",e=>{n.destroy(e)}),n.startConnectTimeout()),n}),ii.createTCPOutgoingPeer=((e,t)=>{const n=new ci(e,"tcpOutgoing");return n.addr=e,n.swarm=t,n}),ii.createWebSeedPeer=((e,t)=>{const n=new ci(e,"webSeed");return n.swarm=t,n.conn=new ri(e,t),n.onConnect(),n});class ci{constructor(e,t){this.id=e,this.type=t,si("new %s Peer %s",t,e),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentHandshake=!1}onConnect(){if(this.destroyed)return;this.connected=!0,si("Peer %s connected",this.id),clearTimeout(this.connectTimeout);const e=this.conn;e.once("end",()=>{this.destroy()}),e.once("close",()=>{this.destroy()}),e.once("finish",()=>{this.destroy()}),e.once("error",e=>{this.destroy(e)});const t=this.wire=new ti;t.type=this.type,t.once("end",()=>{this.destroy()}),t.once("close",()=>{this.destroy()}),t.once("finish",()=>{this.destroy()}),t.once("error",e=>{this.destroy(e)}),t.once("handshake",(e,t)=>{this.onHandshake(e,t)}),this.startHandshakeTimeout(),e.pipe(t).pipe(e),this.swarm&&!this.sentHandshake&&this.handshake()}onHandshake(e,t){if(!this.swarm)return;if(this.destroyed)return;if(this.swarm.destroyed)return this.destroy(new Error("swarm already destroyed"));if(e!==this.swarm.infoHash)return this.destroy(new Error("unexpected handshake info hash for this swarm"));if(t===this.swarm.peerId)return this.destroy(new Error("refusing to connect to ourselves"));si("Peer %s got handshake %s",this.id,e),clearTimeout(this.handshakeTimeout),this.retries=0;let n=this.addr;!n&&this.conn.remoteAddress&&this.conn.remotePort&&(n=`${this.conn.remoteAddress}:${this.conn.remotePort}`),this.swarm._onWire(this.wire,n),this.swarm&&!this.swarm.destroyed&&(this.sentHandshake||this.handshake())}handshake(){const e={dht:!this.swarm.private&&!!this.swarm.client.dht};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout),this.connectTimeout=setTimeout(()=>{this.destroy(new Error("connect timeout"))},"webrtc"===this.type?ai:oi),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout(()=>{this.destroy(new Error("handshake timeout"))},hi),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,si("destroy %s (error: %s)",this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,n=this.conn,r=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&r&&ei(t.wires,t.wires.indexOf(r)),n&&(n.on("error",()=>{}),n.destroy()),r&&r.destroy(),t&&t.removePeer(this.id)}}var ui={};(function(e,t){const n=Nt("webtorrent:torrent"),r=d.EventEmitter,i=3*rr.BLOCK_LENGTH,s=e.browser?1/0:2,o=[1e3,5e3,15e3],a=`WebTorrent/${ni} (https://webtorrent.io)`;let h;try{h=et.join(ut.statSync("/tmp")&&"/tmp","webtorrent")}catch(li){h=et.join("function"==typeof te.tmpdir?te.tmpdir():"/","webtorrent")}function c(e,t){return 2+Math.ceil(t*e.downloadSpeed()/rr.BLOCK_LENGTH)}function u(){}ui=class extends r{constructor(e,t,n){super(),this._debugId="unknown infohash",this.client=t,this.announce=n.announce,this.urlList=n.urlList,this.path=n.path,this.skipVerify=!!n.skipVerify,this._store=n.store||er,this._getAnnounceOpts=n.getAnnounceOpts,this.strategy=n.strategy||"sequential",this.maxWebConns=n.maxWebConns||4,this._rechokeNumSlots=!1===n.uploads||0===n.uploads?0:+n.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=!1,this.done=!1,this.metadata=null,this.store=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=Bn(),this._uploadSpeed=Bn(),this._servers=[],this._xsRequests=[],this._fileModtimes=n.fileModtimes,null!==e&&this._onTorrentId(e),this._debug("new torrent")}get timeRemaining(){return this.done?0:0===this.downloadSpeed?1/0:(this.length-this.downloaded)/this.downloadSpeed*1e3}get downloaded(){if(!this.bitfield)return 0;let e=0;for(let t=0,n=this.pieces.length;t{this.destroyed||this._onParsedTorrent(n)})):Cn.remote(t,(e,t)=>{if(!this.destroyed)return e?this._destroy(e):void this._onParsedTorrent(t)})}_onParsedTorrent(e){if(!this.destroyed){if(this._processParsedTorrent(e),!this.infoHash)return this._destroy(new Error("Malformed torrent data: No info hash"));this.path||(this.path=et.join(h,this.infoHash)),this._rechokeIntervalId=setInterval(()=>{this._rechoke()},1e4),this._rechokeIntervalId.unref&&this._rechokeIntervalId.unref(),this.emit("_infoHash",this.infoHash),this.destroyed||(this.emit("infoHash",this.infoHash),this.destroyed||(this.client.listening?this._onListening():this.client.once("listening",()=>{this._onListening()})))}}_processParsedTorrent(e){this._debugId=e.infoHash.toString("hex").substring(0,7),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&t.WEBTORRENT_ANNOUNCE&&!this.private&&(e.announce=e.announce.concat(t.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),kn(e.announce),kn(e.urlList),Object.assign(this,e),this.magnetURI=Cn.toMagnetURI(e),this.torrentFile=Cn.toTorrentFile(e)}_onListening(){this.destroyed||(this.info?this._onMetadata(this):(this.xs&&this._getMetadataFromServer(),this._startDiscovery()))}_startDiscovery(){if(this.discovery||this.destroyed)return;let e=this.client.tracker;e&&(e=Object.assign({},this.client.tracker,{getAnnounceOpts:()=>{const e={uploaded:this.uploaded,downloaded:this.downloaded,left:Math.max(this.length-this.downloaded,0)};return this.client.tracker.getAnnounceOpts&&Object.assign(e,this.client.tracker.getAnnounceOpts()),this._getAnnounceOpts&&Object.assign(e,this._getAnnounceOpts()),e}})),this.discovery=new Qn({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:a}),this.discovery.on("error",e=>{this._destroy(e)}),this.discovery.on("peer",e=>{"string"==typeof e&&this.done||this.addPeer(e)}),this.discovery.on("trackerAnnounce",()=>{this.emit("trackerAnnounce"),0===this.numPeers&&this.emit("noPeers","tracker")}),this.discovery.on("dhtAnnounce",()=>{this.emit("dhtAnnounce"),0===this.numPeers&&this.emit("noPeers","dht")}),this.discovery.on("warning",e=>{this.emit("warning",e)})}_getMetadataFromServer(){const e=this,t=(Array.isArray(this.xs)?this.xs:[this.xs]).map(t=>n=>{!function(t,n){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),n(null);const r={url:t,method:"GET",headers:{"user-agent":a}};let i;try{i=wn.concat(r,function(r,i,s){if(e.destroyed)return n(null);if(e.metadata)return n(null);if(r)return e.emit("warning",new Error(`http error from xs param: ${t}`)),n(null);if(200!==i.statusCode)return e.emit("warning",new Error(`non-200 status code ${i.statusCode} from xs param: ${t}`)),n(null);let o;try{o=Cn(s)}catch(r){}return o?o.infoHash!==e.infoHash?(e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),n(null)):(e._onMetadata(o),void n(null)):(e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),n(null))})}catch(li){return e.emit("warning",new Error(`skipping invalid url xs param: ${t}`)),n(null)}e._xsRequests.push(i)}(t,n)});kt(t)}_onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequests.forEach(e=>{e.abort()}),this._xsRequests=[],e&&e.infoHash)t=e;else try{t=Cn(e)}catch(li){return this._destroy(li)}if(this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach(e=>{this.addWebSeed(e)}),this._rarityMap=new class{constructor(e){this._torrent=e,this._numPieces=e.pieces.length,this._pieces=new Array(this._numPieces),this._onWire=(e=>{this.recalculate(),this._initWire(e)}),this._onWireHave=(e=>{this._pieces[e]+=1}),this._onWireBitfield=(()=>{this.recalculate()}),this._torrent.wires.forEach(e=>{this._initWire(e)}),this._torrent.on("wire",this._onWire),this.recalculate()}getRarestPiece(e){let t=[],n=1/0;for(let r=0;r{this._cleanupWireEvents(e)}),this._torrent=null,this._pieces=null,this._onWire=null,this._onWireHave=null,this._onWireBitfield=null}_initWire(e){e._onClose=(()=>{this._cleanupWireEvents(e);for(let t=0;t({path:et.join(this.path,e.path),length:e.length,offset:e.offset})),length:this.length,name:this.infoHash})),this.files=this.files.map(e=>new Qr(this,e)),this.so){const e=cr.parse(this.so);this.files.forEach((t,n)=>{e.includes(n)&&this.files[n].select(!0)})}else 0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1);if(this._hashes=this.pieces,this.pieces=this.pieces.map((e,t)=>{const n=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new rr(n)}),this._reservations=this.pieces.map(()=>[]),this.bitfield=new Nn(this.pieces.length),this.wires.forEach(e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)}),this.emit("metadata"),!this.destroyed)if(this.skipVerify)this._markAllVerified(),this._onStore();else{const e=e=>{if(e)return this._destroy(e);this._debug("done verifying"),this._onStore()};this._debug("verifying existing torrent data"),this._fileModtimes&&this._store===er?this.getFileModtimes((t,n)=>{if(t)return this._destroy(t);this.files.map((e,t)=>n[t]===this._fileModtimes[t]).every(e=>e)?(this._markAllVerified(),this._onStore()):this._verifyPieces(e)}):this._verifyPieces(e)}}getFileModtimes(e){const t=[];nr(this.files.map((e,n)=>r=>{ut.stat(et.join(this.path,e.path),(e,i)=>{if(e&&"ENOENT"!==e.code)return r(e);t[n]=i&&i.mtime.getTime(),r(null)})}),s,n=>{this._debug("done getting file modtimes"),e(n,t)})}_verifyPieces(t){nr(this.pieces.map((t,n)=>t=>{if(this.destroyed)return t(new Error("torrent is destroyed"));this.store.get(n,(r,i)=>this.destroyed?t(new Error("torrent is destroyed")):r?e.nextTick(t,null):void Rt(i,e=>{if(this.destroyed)return t(new Error("torrent is destroyed"));if(e===this._hashes[n]){if(!this.pieces[n])return t(null);this._debug("piece verified %s",n),this._markVerified(n)}else this._debug("piece invalid %s",n);t(null)}))}),s,t)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=u),this._verifyPieces(t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)})}_markAllVerified(){for(let e=0;e{e.abort()}),this._rarityMap&&this._rarityMap.destroy();for(const r in this._peers)this.removePeer(r);this.files.forEach(e=>{e instanceof Qr&&e._destroy()});const n=this._servers.map(e=>t=>{e.destroy(t)});this.discovery&&n.push(e=>{this.discovery.destroy(e)}),this.store&&n.push(e=>{this.store.close(e)}),kt(n,t),e&&(0===this.listenerCount("error")?this.client.emit("error",e):this.emit("error",e)),this.emit("close"),this.client=null,this.files=[],this.discovery=null,this.store=null,this._rarityMap=null,this._peers=null,this._servers=null,this._xsRequests=null}addPeer(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(this.client.blocked){let t;if("string"==typeof e){let r;try{r=Un(e)}catch(n){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}t=r[0]}else"string"==typeof e.remoteAddress&&(t=e.remoteAddress);if(t&&this.client.blocked.contains(t))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const t=!!this._addPeer(e);return t?this.emit("peer",e):this.emit("invalidPeer",e),t}_addPeer(e){if(this.destroyed)return"string"!=typeof e&&e.destroy(),null;if("string"==typeof e&&!this._validAddr(e))return this._debug("ignoring peer: invalid %s",e),null;const t=e&&e.id||e;if(this._peers[t])return this._debug("ignoring peer: duplicate (%s)",t),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let n;return this._debug("add peer %s",t),n="string"==typeof e?ii.createTCPOutgoingPeer(e,this):ii.createWebRTCPeer(e,this),this._peers[n.id]=n,this._peersLength+=1,"string"==typeof e&&(this._queue.push(n),this._drain()),n}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(e))return this.emit("warning",new Error(`ignoring invalid web seed: ${e}`)),void this.emit("invalidPeer",e);if(this._peers[e])return this.emit("warning",new Error(`ignoring duplicate web seed: ${e}`)),void this.emit("invalidPeer",e);this._debug("add web seed %s",e);const t=ii.createWebSeedPeer(e,this);this._peers[t.id]=t,this._peersLength+=1,this.emit("peer",e)}_addIncomingPeer(e){return this.destroyed?e.destroy(new Error("torrent is destroyed")):this.paused?e.destroy(new Error("torrent is paused")):(this._debug("add incoming peer %s",e.id),this._peers[e.id]=e,void(this._peersLength+=1))}removePeer(e){const t=e&&e.id||e;(e=this._peers[t])&&(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,e.destroy(),this._drain())}select(e,t,n,r){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||tt.priority-e.priority),this._updateSelections()}deselect(e,t,n){if(this.destroyed)throw new Error("torrent is destroyed");n=Number(n)||0,this._debug("deselect %s-%s (priority %s)",e,t,n);for(let r=0;r{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.client.emit("download",e))}),t.on("upload",e=>{this.destroyed||(this.uploaded+=e,this._uploadSpeed(e),this.client._uploadSpeed(e),this.emit("upload",e),this.client.emit("upload",e))}),this.wires.push(t),n){const e=Un(n);t.remoteAddress=e[0],t.remotePort=e[1]}this.client.dht&&this.client.dht.listening&&t.on("port",e=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!t.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===e||e>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",e,n),this.client.dht.addNode({host:t.remoteAddress,port:e})}}),t.on("timeout",()=>{this._debug("wire timeout (%s)",n),t.destroy()}),t.setTimeout(3e4,!0),t.setKeepAlive(!0),t.use(hr(this.metadata)),t.ut_metadata.on("warning",e=>{this._debug("ut_metadata warning: %s",e.message)}),this.metadata||(t.ut_metadata.on("metadata",e=>{this._debug("got metadata via ut_metadata"),this._onMetadata(e)}),t.ut_metadata.fetch()),"function"!=typeof te||this.private||(t.use(te()),t.ut_pex.on("peer",e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,n),this.addPeer(e))}),t.ut_pex.on("dropped",e=>{const t=this._peers[e];t&&!t.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,n),this.removePeer(e))}),t.once("close",()=>{t.ut_pex.reset()})),this.emit("wire",t,n),this.metadata&&e.nextTick(()=>{this._onWireWithMetadata(t)})}_onWireWithMetadata(e){let t=null;const n=()=>{this.destroyed||e.destroyed||(this._numQueued>2*(this._numConns-this.numPeers)&&e.amInterested?e.destroy():(t=setTimeout(n,5e3)).unref&&t.unref())};let r;const i=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(r=0;r{i(),this._update()}),e.on("have",()=>{i(),this._update()}),e.once("interested",()=>{e.unchoke()}),e.once("close",()=>{clearTimeout(t)}),e.on("choke",()=>{clearTimeout(t),(t=setTimeout(n,5e3)).unref&&t.unref()}),e.on("unchoke",()=>{clearTimeout(t),this._update()}),e.on("request",(t,n,r,i)=>{if(r>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:n,length:r},i)}),e.bitfield(this.bitfield),e.uninterested(),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(n,5e3)).unref&&t.unref(),e.isSeeder=!1,i()}_updateSelections(){this.ready&&!this.destroyed&&(e.nextTick(()=>{this._gcSelections()}),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;e{let t=!1;for(let n=0;n=r.from+r.offset;--i)if(e.peerPieces.get(i)&&t._request(e,i,!1))return}}();const n=c(e,.5);if(e.requests.length>=n)return;const r=c(e,1);function s(t,n,r,i){return s=>s>=t&&s<=n&&!(s in r)&&e.peerPieces.get(s)&&(!i||i(s))}function o(e){let n=e;for(let i=e;i=r)return!0;const a=function(){const n=e.downloadSpeed()||1;if(n>i)return()=>!0;const r=Math.max(1,e.requests.length)*rr.BLOCK_LENGTH/n;let s=10,o=0;return e=>{if(!s||t.bitfield.get(e))return!0;let a=t.pieces[e].missing;for(;o0))return s--,!1}return!0}}();for(let i=0;i0?this._rechokeOptimisticTime-=1:this._rechokeOptimisticWire=null;const e=[];this.wires.forEach(t=>{t.isSeeder||t===this._rechokeOptimisticWire||e.push({wire:t,downloadSpeed:t.downloadSpeed(),uploadSpeed:t.uploadSpeed(),salt:Math.random(),isChoked:!0})}),e.sort(function(e,t){return e.downloadSpeed!==t.downloadSpeed?t.downloadSpeed-e.downloadSpeed:e.uploadSpeed!==t.uploadSpeed?t.uploadSpeed-e.uploadSpeed:e.wire.amChoking!==t.wire.amChoking?e.wire.amChoking?1:-1:e.salt-t.salt});let t=0,n=0;for(;ne.wire.peerInterested),i=t[(r=t.length,Math.random()*r|0)];i&&(i.isChoked=!1,this._rechokeOptimisticWire=i.wire,this._rechokeOptimisticTime=2)}var r;e.forEach(e=>{e.wire.amChoking!==e.isChoked&&(e.isChoked?e.wire.choke():e.wire.unchoke())})}_hotswap(e,t){const n=e.downloadSpeed();if(n=i||2*h>n||h>a||(s=t,a=h)}if(!s)return!1;for(o=0;o=(o?Math.min(function(e,t,n){return 1+Math.ceil(1*e.downloadSpeed()/n)}(t,0,i.pieceLength),i.maxWebConns):c(t,1)))return!1;const a=i.pieces[n];let h=o?a.reserveRemaining():a.reserve();if(-1===h&&r&&i._hotswap(t,n)&&(h=o?a.reserveRemaining():a.reserve()),-1===h)return!1;let u=i._reservations[n];u||(u=i._reservations[n]=[]);let d=u.indexOf(null);-1===d&&(d=u.length),u[d]=t;const l=a.chunkOffset(h),f=o?a.chunkLengthRemaining(h):a.chunkLength(h);function p(){e.nextTick(()=>{i._update()})}return t.request(n,l,f,function e(r,s){if(i.destroyed)return;if(!i.ready)return i.once("ready",()=>{e(r,s)});if(u[d]===t&&(u[d]=null),a!==i.pieces[n])return p();if(r)return i._debug("error getting piece %s (offset: %s length: %s) from %s: %s",n,l,f,`${t.remoteAddress}:${t.remotePort}`,r.message),o?a.cancelRemaining(h):a.cancel(h),void p();if(i._debug("got piece %s (offset: %s length: %s) from %s",n,l,f,`${t.remoteAddress}:${t.remotePort}`),!a.set(h,s,t))return p();const c=a.flush();Rt(c,e=>{if(!i.destroyed){if(e===i._hashes[n]){if(!i.pieces[n])return;i._debug("piece verified %s",n),i.pieces[n]=null,i._reservations[n]=null,i.bitfield.set(n,!0),i.store.put(n,c),i.wires.forEach(e=>{e.have(n)}),i._checkDone()&&!i.destroyed&&i.discovery.complete()}else i.pieces[n]=new rr(a.length),i.emit("warning",new Error(`Piece ${n} failed verification`));p()}})}),!0}_checkDone(){if(this.destroyed)return;this.files.forEach(e=>{if(!e.done){for(let t=e._startPiece;t<=e._endPiece;++t)if(!this.bitfield.get(t))return;e.done=!0,e.emit("done"),this._debug(`file done: ${e.name}`)}});let e=!0;for(let t=0;t{this.load(e,t)});Array.isArray(e)||(e=[e]),t||(t=u);const n=new pt(e),r=new Hn(this.store,this.pieceLength);ar(n,r,e=>{if(e)return t(e);this._markAllVerified(),this._checkDone(),t(null)})}createServer(e){if("function"!=typeof te)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");const t=new te(this,e);return this._servers.push(t),t}pause(){this.destroyed||(this._debug("pause"),this.paused=!0)}resume(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())}_debug(){const e=[].slice.call(arguments);e[0]=`[${this.client._debugId}] [${this._debugId}] ${e[0]}`,n(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof te.connect||this.destroyed||this.paused||this._numConns>=this.client.maxConns)return;this._debug("drain (%s queued, %s/%s peers)",this._numQueued,this.numPeers,this.client.maxConns);const e=this._queue.shift();if(!e)return;this._debug("tcp connect attempt to %s",e.addr);const t=Un(e.addr),n={host:t[0],port:t[1]},r=e.conn=te.connect(n);r.once("connect",()=>{e.onConnect()}),r.once("error",t=>{e.destroy(t)}),e.startConnectTimeout(),r.on("close",()=>{if(this.destroyed)return;if(e.retries>=o.length)return void this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,o.length);const t=o[e.retries];this._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",e.addr,t,e.retries+1);const n=setTimeout(()=>{const t=this._addPeer(e.addr);t&&(t.retries=e.retries+1)},t);n.unref&&n.unref()})}_validAddr(e){let t;try{t=Un(e)}catch(i){return!1}const n=t[0],r=t[1];return r>0&&r<65535&&!("127.0.0.1"===n&&r===this.client.torrentPort)}}}).call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var di={};return function(e,t,n){const{EventEmitter:r}=d,i=Nt("webtorrent"),s=ni,o=s.replace(/\d*./g,e=>`0${e%100}`.slice(-2)).slice(0,4),a=`-WW${o}-`;class h extends r{constructor(r={}){super(),"string"==typeof r.peerId?this.peerId=r.peerId:n.isBuffer(r.peerId)?this.peerId=r.peerId.toString("hex"):this.peerId=n.from(a+Tn(9).toString("base64")).toString("hex"),this.peerIdBuffer=n.from(this.peerId,"hex"),"string"==typeof r.nodeId?this.nodeId=r.nodeId:n.isBuffer(r.nodeId)?this.nodeId=r.nodeId.toString("hex"):this.nodeId=Tn(20).toString("hex"),this.nodeIdBuffer=n.from(this.nodeId,"hex"),this._debugId=this.peerId.toString("hex").substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=r.torrentPort||0,this.dhtPort=r.dhtPort||0,this.tracker=void 0!==r.tracker?r.tracker:{},this.torrents=[],this.maxConns=Number(r.maxConns)||55,this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),r.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),this.tracker.rtcConfig=r.rtcConfig),r.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),this.tracker.wrtc=r.wrtc),t.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=t.WRTC)),"function"==typeof te?this._tcpPool=new te(this):e.nextTick(()=>{this._onListening()}),this._downloadSpeed=Bn(),this._uploadSpeed=Bn(),!1!==r.dht&&"function"==typeof te?(this.dht=new te(Object.assign({},{nodeId:this.nodeId},r.dht)),this.dht.once("error",e=>{this._destroy(e)}),this.dht.once("listening",()=>{const e=this.dht.address();e&&(this.dhtPort=e.port)}),this.dht.setMaxListeners(0),this.dht.listen(this.dhtPort)):this.dht=!1,this.enableWebSeeds=!1!==r.webSeeds;const i=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof te&&null!=r.blocklist?te(r.blocklist,{headers:{"user-agent":`WebTorrent/${s} (https://webtorrent.io)`}},(e,t)=>{if(e)return this.error(`Failed to load blocklist: ${e.message}`);this.blocked=t,i()}):e.nextTick(i)}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){const e=this.torrents.filter(e=>1!==e.progress);return e.reduce((e,t)=>e+t.downloaded,0)/(e.reduce((e,t)=>e+(t.length||0),0)||1)}get ratio(){return this.torrents.reduce((e,t)=>e+t.uploaded,0)/(this.torrents.reduce((e,t)=>e+t.received,0)||1)}get(e){if(e instanceof ui){if(this.torrents.includes(e))return e}else{let t;try{t=Cn(e)}catch(li){}if(!t)return null;if(!t.infoHash)throw new Error("Invalid torrent identifier");for(const e of this.torrents)if(e.infoHash===t.infoHash)return e}return null}download(e,t,n){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(e,t,n)}add(e,t={},n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]);const r=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===s.infoHash&&e!==s)return void s._destroy(new Error(`Cannot add duplicate torrent ${s.infoHash}`))},i=()=>{this.destroyed||("function"==typeof n&&n(s),this.emit("torrent",s))};this._debug("add"),t=t?Object.assign({},t):{};const s=new ui(e,this,t);return this.torrents.push(s),s.once("_infoHash",r),s.once("ready",i),s.once("close",function e(){s.removeListener("_infoHash",r),s.removeListener("ready",i),s.removeListener("close",e)}),s}seed(e,t,n){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]),this._debug("seed"),(t=t?Object.assign({},t):{}).skipVerify=!0;const r="string"==typeof e;r&&(t.path=et.dirname(e)),t.createdBy||(t.createdBy=`WebTorrent/${o}`);const i=e=>{this._debug("on seed"),"function"==typeof n&&n(e),e.emit("seed"),this.emit("seed",e)},s=this.add(null,t,e=>{const t=[t=>{if(r)return t();e.load(a,t)}];this.dht&&t.push(t=>{e.once("dhtAnnounce",t)}),kt(t,t=>{if(!this.destroyed)return t?e._destroy(t):void i(e)})});let a;return"undefined"!=typeof FileList&&e instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),kt(e.map(e=>t=>{!function(t){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}()?t(null,e):P(e,t)}),(e,n)=>{if(!this.destroyed)return e?s._destroy(e):void Pt.parseInput(n,t,(e,r)=>{if(!this.destroyed){if(e)return s._destroy(e);a=r.map(e=>e.getStream),Pt(n,t,(e,t)=>{if(this.destroyed)return;if(e)return s._destroy(e);const n=this.get(t);n?s._destroy(new Error(`Cannot add duplicate torrent ${n.infoHash}`)):s._onTorrentId(t)})}})}),s}remove(e,t){if(this._debug("remove"),!this.get(e))throw new Error(`No torrent with id ${e}`);this._remove(e,t)}_remove(e,t){const n=this.get(e);n&&(this.torrents.splice(this.torrents.indexOf(n),1),n.destroy(t))}address(){return this.listening?this._tcpPool?this._tcpPool.server.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}destroy(e){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,e)}_destroy(e,t){this._debug("client destroy"),this.destroyed=!0;const n=this.torrents.map(e=>t=>{e.destroy(t)});this._tcpPool&&n.push(e=>{this._tcpPool.destroy(e)}),this.dht&&n.push(e=>{this.dht.destroy(e)}),kt(n,t),e&&this.emit("error",e),this.torrents=[],this._tcpPool=null,this.dht=null}_onListening(){if(this._debug("listening"),this.listening=!0,this._tcpPool){const e=this._tcpPool.server.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,i(...e)}}h.WEBRTC_SUPPORT=In.WEBRTC_SUPPORT,h.VERSION=s,di=h}.call(this,ce,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u({}).Buffer),di}); \ No newline at end of file -- cgit v1.2.3