my eye

webtorrent.min.js

var e,t,n={9742:(e,t)=>{t.byteLength=function(e){var t=a(e),n=t[0],i=t[1];return 3*(n+i)/4-i},t.toByteArray=function(e){var t,n,s=a(e),o=s[0],h=s[1],c=new r(function(e,t,n){return 3*(t+n)/4-n}(0,o,h)),l=0,u=h>0?o-4:o;for(n=0;n<u;n+=4)t=i[e.charCodeAt(n)]<<18|i[e.charCodeAt(n+1)]<<12|i[e.charCodeAt(n+2)]<<6|i[e.charCodeAt(n+3)],c[l++]=t>>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===h&&(t=i[e.charCodeAt(n)]<<2|i[e.charCodeAt(n+1)]>>4,c[l++]=255&t);1===h&&(t=i[e.charCodeAt(n)]<<10|i[e.charCodeAt(n+1)]<<4|i[e.charCodeAt(n+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},t.fromByteArray=function(e){for(var t,i=e.length,r=i%3,s=[],o=16383,a=0,c=i-r;a<c;a+=o)s.push(h(e,a,a+o>c?c:a+o));1===r?(t=e[i-1],s.push(n[t>>2]+n[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],s.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return s.join("")};for(var n=[],i=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)n[o]=s[o],i[s.charCodeAt(o)]=o;function a(e){var t=e.length;if(t%4>0)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 h(e,t,i){for(var r,s,o=[],a=t;a<i;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),o.push(n[(s=r)>>18&63]+n[s>>12&63]+n[s>>6&63]+n[63&s]);return o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},2090:e=>{function t(e,t){if("string"==typeof e[0])return e.join("");if("number"==typeof e[0])return new Uint8Array(e);const n=new Uint8Array(t);let i=0;for(let t=0,r=e.length;t<r;t++){const r=e[t];n.set(r,i),i+=r.byteLength||r.length}return n}e.exports=async function*(e,n=512,i={}){"object"==typeof n&&(n=(i=n).size);let{nopad:r,zeroPadding:s=!0}=i;r&&(s=!1);let o=[],a=0;for await(const i of e)if(a+=i.byteLength||i.length||1,o.push(i),a>=n){const e=t(o,a);let i=0;for(;a>=n;)yield e.slice(i,i+n),a-=n,i+=n;o=[e.slice(i,e.length)]}a&&(yield t(o,s?n:a))}},8764:(e,t,n)=>{const i=n(9742),r=n(645),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.lW=h,t.h2=50;const o=2147483647;function a(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,h.prototype),t}function h(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 u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!h.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|g(e,t);let i=a(n);const r=i.write(e,t);r!==n&&(i=i.slice(0,r));return i}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Z(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Z(e,ArrayBuffer)||e&&Z(e.buffer,ArrayBuffer))return f(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(Z(e,SharedArrayBuffer)||e&&Z(e.buffer,SharedArrayBuffer)))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return h.from(i,t,n);const r=function(e){if(h.isBuffer(e)){const t=0|p(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||Y(e.length)?a(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(e.data)}(e);if(r)return r;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return h.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return l(e),a(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),n=a(t);for(let i=0;i<t;i+=1)n[i]=255&e[i];return n}function f(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(i,h.prototype),i}function p(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function g(e,t){if(h.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Z(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;let r=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return V(e).length;default:if(r)return i?-1:G(e).length;t=(""+t).toLowerCase(),r=!0}}function m(e,t,n){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.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 I(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return T(this,t,n);case"latin1":case"binary":return P(this,t,n);case"base64":return S(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function _(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}function y(e,t,n,i,r){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=h.from(t,i)),h.isBuffer(t))return 0===t.length?-1:w(e,t,n,i,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):w(e,[t],n,i,r);throw new TypeError("val must be string, number or Buffer")}function w(e,t,n,i,r){let s,o=1,a=e.length,h=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){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(r){let i=-1;for(s=n;s<a;s++)if(c(e,s)===c(t,-1===i?0:s-i)){if(-1===i&&(i=s),s-i+1===h)return i*o}else-1!==i&&(s-=s-i),i=-1}else for(n+h>a&&(n=a-h),s=n;s>=0;s--){let n=!0;for(let i=0;i<h;i++)if(c(e,s+i)!==c(t,i)){n=!1;break}if(n)return s}return-1}function b(e,t,n,i){n=Number(n)||0;const r=e.length-n;i?(i=Number(i))>r&&(i=r):i=r;const s=t.length;let o;for(i>s/2&&(i=s/2),o=0;o<i;++o){const i=parseInt(t.substr(2*o,2),16);if(Y(i))return o;e[n+o]=i}return o}function v(e,t,n,i){return K(G(t,e.length-n),e,n,i)}function k(e,t,n,i){return K(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,i)}function x(e,t,n,i){return K(V(t),e,n,i)}function E(e,t,n,i){return K(function(e,t){let n,i,r;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),i=n>>8,r=n%256,s.push(r),s.push(i);return s}(t,e.length-n),e,n,i)}function S(e,t,n){return 0===t&&n===e.length?i.fromByteArray(e):i.fromByteArray(e.slice(t,n))}function C(e,t,n){n=Math.min(e.length,n);const i=[];let r=t;for(;r<n;){const t=e[r];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(r+o<=n){let n,i,a,h;switch(o){case 1:t<128&&(s=t);break;case 2:n=e[r+1],128==(192&n)&&(h=(31&t)<<6|63&n,h>127&&(s=h));break;case 3:n=e[r+1],i=e[r+2],128==(192&n)&&128==(192&i)&&(h=(15&t)<<12|(63&n)<<6|63&i,h>2047&&(h<55296||h>57343)&&(s=h));break;case 4:n=e[r+1],i=e[r+2],a=e[r+3],128==(192&n)&&128==(192&i)&&128==(192&a)&&(h=(15&t)<<18|(63&n)<<12|(63&i)<<6|63&a,h>65535&&h<1114112&&(s=h))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,i.push(s>>>10&1023|55296),s=56320|1023&s),i.push(s),r+=o}return function(e){const t=e.length;if(t<=A)return String.fromCharCode.apply(String,e);let n="",i=0;for(;i<t;)n+=String.fromCharCode.apply(String,e.slice(i,i+=A));return n}(i)}h.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),h.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(h.prototype,"parent",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.buffer}}),Object.defineProperty(h.prototype,"offset",{enumerable:!0,get:function(){if(h.isBuffer(this))return this.byteOffset}}),h.poolSize=8192,h.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(h.prototype,Uint8Array.prototype),Object.setPrototypeOf(h,Uint8Array),h.alloc=function(e,t,n){return function(e,t,n){return l(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}(e,t,n)},h.allocUnsafe=function(e){return u(e)},h.allocUnsafeSlow=function(e){return u(e)},h.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==h.prototype},h.compare=function(e,t){if(Z(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),Z(t,Uint8Array)&&(t=h.from(t,t.offset,t.byteLength)),!h.isBuffer(e)||!h.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,i=t.length;for(let r=0,s=Math.min(n,i);r<s;++r)if(e[r]!==t[r]){n=e[r],i=t[r];break}return n<i?-1:i<n?1:0},h.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},h.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return h.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const i=h.allocUnsafe(t);let r=0;for(n=0;n<e.length;++n){let t=e[n];if(Z(t,Uint8Array))r+t.length>i.length?(h.isBuffer(t)||(t=h.from(t)),t.copy(i,r)):Uint8Array.prototype.set.call(i,t,r);else{if(!h.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,r)}r+=t.length}return i},h.byteLength=g,h.prototype._isBuffer=!0,h.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)_(this,t,t+1);return this},h.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)_(this,t,t+3),_(this,t+1,t+2);return this},h.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)_(this,t,t+7),_(this,t+1,t+6),_(this,t+2,t+5),_(this,t+3,t+4);return this},h.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):m.apply(this,arguments)},h.prototype.toLocaleString=h.prototype.toString,h.prototype.equals=function(e){if(!h.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===h.compare(this,e)},h.prototype.inspect=function(){let e="";const n=t.h2;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},s&&(h.prototype[s]=h.prototype.inspect),h.prototype.compare=function(e,t,n,i,r){if(Z(e,Uint8Array)&&(e=h.from(e,e.offset,e.byteLength)),!h.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===r&&(r=this.length),t<0||n>e.length||i<0||r>this.length)throw new RangeError("out of range index");if(i>=r&&t>=n)return 0;if(i>=r)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(r>>>=0)-(i>>>=0),o=(n>>>=0)-(t>>>=0);const a=Math.min(s,o),c=this.slice(i,r),l=e.slice(t,n);for(let e=0;e<a;++e)if(c[e]!==l[e]){s=c[e],o=l[e];break}return s<o?-1:o<s?1:0},h.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},h.prototype.indexOf=function(e,t,n){return y(this,e,t,n,!0)},h.prototype.lastIndexOf=function(e,t,n){return y(this,e,t,n,!1)},h.prototype.write=function(e,t,n,i){if(void 0===t)i="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)i=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===i&&(i="utf8")):(i=n,n=void 0)}const r=this.length-t;if((void 0===n||n>r)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let s=!1;for(;;)switch(i){case"hex":return b(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return x(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}},h.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const A=4096;function T(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;r<n;++r)i+=String.fromCharCode(127&e[r]);return i}function P(e,t,n){let i="";n=Math.min(e.length,n);for(let r=t;r<n;++r)i+=String.fromCharCode(e[r]);return i}function I(e,t,n){const i=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>i)&&(n=i);let r="";for(let i=t;i<n;++i)r+=J[e[i]];return r}function R(e,t,n){const i=e.slice(t,n);let r="";for(let e=0;e<i.length-1;e+=2)r+=String.fromCharCode(i[e]+256*i[e+1]);return r}function L(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,i,r,s){if(!h.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<s)throw new RangeError('"value" argument is out of bounds');if(n+i>e.length)throw new RangeError("Index out of range")}function B(e,t,n,i,r){q(t,i,r,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function U(e,t,n,i,r){q(t,i,r,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function N(e,t,n,i,r,s){if(n+i>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function M(e,t,n,i,s){return t=+t,n>>>=0,s||N(e,0,n,4),r.write(e,t,n,i,23,4),n+4}function j(e,t,n,i,s){return t=+t,n>>>=0,s||N(e,0,n,8),r.write(e,t,n,i,52,8),n+8}h.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,h.prototype),i},h.prototype.readUintLE=h.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||L(e,t,this.length);let i=this[e],r=1,s=0;for(;++s<t&&(r*=256);)i+=this[e+s]*r;return i},h.prototype.readUintBE=h.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||L(e,t,this.length);let i=this[e+--t],r=1;for(;t>0&&(r*=256);)i+=this[e+--t]*r;return i},h.prototype.readUint8=h.prototype.readUInt8=function(e,t){return e>>>=0,t||L(e,1,this.length),this[e]},h.prototype.readUint16LE=h.prototype.readUInt16LE=function(e,t){return e>>>=0,t||L(e,2,this.length),this[e]|this[e+1]<<8},h.prototype.readUint16BE=h.prototype.readUInt16BE=function(e,t){return e>>>=0,t||L(e,2,this.length),this[e]<<8|this[e+1]},h.prototype.readUint32LE=h.prototype.readUInt32LE=function(e,t){return e>>>=0,t||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},h.prototype.readUint32BE=h.prototype.readUInt32BE=function(e,t){return e>>>=0,t||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},h.prototype.readBigUInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||W(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,r=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(i)+(BigInt(r)<<BigInt(32))})),h.prototype.readBigUInt64BE=X((function(e){$(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||W(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],r=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(i)<<BigInt(32))+BigInt(r)})),h.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||L(e,t,this.length);let i=this[e],r=1,s=0;for(;++s<t&&(r*=256);)i+=this[e+s]*r;return r*=128,i>=r&&(i-=Math.pow(2,8*t)),i},h.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||L(e,t,this.length);let i=t,r=1,s=this[e+--i];for(;i>0&&(r*=256);)s+=this[e+--i]*r;return r*=128,s>=r&&(s-=Math.pow(2,8*t)),s},h.prototype.readInt8=function(e,t){return e>>>=0,t||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},h.prototype.readInt16LE=function(e,t){e>>>=0,t||L(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},h.prototype.readInt16BE=function(e,t){e>>>=0,t||L(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},h.prototype.readInt32LE=function(e,t){return e>>>=0,t||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},h.prototype.readInt32BE=function(e,t){return e>>>=0,t||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},h.prototype.readBigInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||W(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),h.prototype.readBigInt64BE=X((function(e){$(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||W(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)})),h.prototype.readFloatLE=function(e,t){return e>>>=0,t||L(e,4,this.length),r.read(this,e,!0,23,4)},h.prototype.readFloatBE=function(e,t){return e>>>=0,t||L(e,4,this.length),r.read(this,e,!1,23,4)},h.prototype.readDoubleLE=function(e,t){return e>>>=0,t||L(e,8,this.length),r.read(this,e,!0,52,8)},h.prototype.readDoubleBE=function(e,t){return e>>>=0,t||L(e,8,this.length),r.read(this,e,!1,52,8)},h.prototype.writeUintLE=h.prototype.writeUIntLE=function(e,t,n,i){if(e=+e,t>>>=0,n>>>=0,!i){O(this,e,t,n,Math.pow(2,8*n)-1,0)}let r=1,s=0;for(this[t]=255&e;++s<n&&(r*=256);)this[t+s]=e/r&255;return t+n},h.prototype.writeUintBE=h.prototype.writeUIntBE=function(e,t,n,i){if(e=+e,t>>>=0,n>>>=0,!i){O(this,e,t,n,Math.pow(2,8*n)-1,0)}let r=n-1,s=1;for(this[t+r]=255&e;--r>=0&&(s*=256);)this[t+r]=e/s&255;return t+n},h.prototype.writeUint8=h.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},h.prototype.writeUint16LE=h.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},h.prototype.writeUint16BE=h.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},h.prototype.writeUint32LE=h.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(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},h.prototype.writeUint32BE=h.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(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},h.prototype.writeBigUInt64LE=X((function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),h.prototype.writeBigUInt64BE=X((function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),h.prototype.writeIntLE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}let r=0,s=1,o=0;for(this[t]=255&e;++r<n&&(s*=256);)e<0&&0===o&&0!==this[t+r-1]&&(o=1),this[t+r]=(e/s>>0)-o&255;return t+n},h.prototype.writeIntBE=function(e,t,n,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}let r=n-1,s=1,o=0;for(this[t+r]=255&e;--r>=0&&(s*=256);)e<0&&0===o&&0!==this[t+r+1]&&(o=1),this[t+r]=(e/s>>0)-o&255;return t+n},h.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},h.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},h.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},h.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(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},h.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(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},h.prototype.writeBigInt64LE=X((function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),h.prototype.writeBigInt64BE=X((function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),h.prototype.writeFloatLE=function(e,t,n){return M(this,e,t,!0,n)},h.prototype.writeFloatBE=function(e,t,n){return M(this,e,t,!1,n)},h.prototype.writeDoubleLE=function(e,t,n){return j(this,e,t,!0,n)},h.prototype.writeDoubleBE=function(e,t,n){return j(this,e,t,!1,n)},h.prototype.copy=function(e,t,n,i){if(!h.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<n&&(i=n),i===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-n&&(i=e.length-t+n);const r=i-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),t),r},h.prototype.fill=function(e,t,n,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!h.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let r;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(r=t;r<n;++r)this[r]=e;else{const s=h.isBuffer(e)?e:h.from(e,i),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(r=0;r<n-t;++r)this[r+t]=s[r%o]}return this};const H={};function D(e,t,n){H[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function F(e){let t="",n=e.length;const i="-"===e[0]?1:0;for(;n>=i+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function q(e,t,n,i,r,s){if(e>n||e<t){const i="bigint"==typeof t?"n":"";let r;throw r=s>3?0===t||t===BigInt(0)?`>= 0${i} and < 2${i} ** ${8*(s+1)}${i}`:`>= -(2${i} ** ${8*(s+1)-1}${i}) and < 2 ** ${8*(s+1)-1}${i}`:`>= ${t}${i} and <= ${n}${i}`,new H.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){$(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||W(t,e.length-(n+1))}(i,r,s)}function $(e,t){if("number"!=typeof e)throw new H.ERR_INVALID_ARG_TYPE(t,"number",e)}function W(e,t,n){if(Math.floor(e)!==e)throw $(e,n),new H.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new H.ERR_BUFFER_OUT_OF_BOUNDS;throw new H.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}D("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),D("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),D("ERR_OUT_OF_RANGE",(function(e,t,n){let i=`The value of "${e}" is out of range.`,r=n;return Number.isInteger(n)&&Math.abs(n)>2**32?r=F(String(n)):"bigint"==typeof n&&(r=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(r=F(r)),r+="n"),i+=` It must be ${t}. Received ${r}`,i}),RangeError);const z=/[^+/0-9A-Za-z-_]/g;function G(e,t){let n;t=t||1/0;const i=e.length;let r=null;const s=[];for(let o=0;o<i;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&s.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&s.push(239,191,189);if(r=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 V(e){return i.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,n,i){let r;for(r=0;r<i&&!(r+n>=t.length||r>=e.length);++r)t[r+n]=e[r];return r}function Z(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const J=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const i=16*n;for(let r=0;r<16;++r)t[i+r]=e[n]+e[r]}return t}();function X(e){return"undefined"==typeof BigInt?Q:e}function Q(){throw new Error("BigInt not supported")}},9421:(e,t,n)=>{const i=n(7117),r=n(4375);e.exports=class{constructor(e,t){if(this.store=e,this.chunkLength=e.chunkLength,this.inProgressGets=new Map,!this.store||!this.store.get||!this.store.put)throw new Error("First argument must be abstract-chunk-store compliant");this.cache=new i(t)}put(e,t,n=(()=>{})){if(!this.cache)return r((()=>n(new Error("CacheStore closed"))));this.cache.remove(e),this.store.put(e,t,n)}get(e,t,n=(()=>{})){if("function"==typeof t)return this.get(e,null,t);if(!this.cache)return r((()=>n(new Error("CacheStore closed"))));t||(t={});let i=this.cache.get(e);if(i){const e=t.offset||0,s=t.length||i.length-e;return 0===e&&s===i.length||(i=i.slice(e,s+e)),r((()=>n(null,i)))}let s=this.inProgressGets.get(e);const o=!!s;s||(s=[],this.inProgressGets.set(e,s)),s.push({opts:t,cb:n}),o||this.store.get(e,((t,n)=>{t||null==this.cache||this.cache.set(e,n);const i=this.inProgressGets.get(e);this.inProgressGets.delete(e);for(const{opts:e,cb:r}of i)if(t)r(t);else{const t=e.offset||0,i=e.length||n.length-t;let s=n;0===t&&i===n.length||(s=n.slice(t,i+t)),r(null,s)}}))}close(e=(()=>{})){if(!this.cache)return r((()=>e(new Error("CacheStore closed"))));this.cache=null,this.store.close(e)}destroy(e=(()=>{})){if(!this.cache)return r((()=>e(new Error("CacheStore closed"))));this.cache=null,this.store.destroy(e)}}},6313:(e,t,n)=>{var i=n(8764).lW,r=function(){function e(e,t){return null!=t&&e instanceof t}var t,n,r;try{t=Map}catch(e){t=function(){}}try{n=Set}catch(e){n=function(){}}try{r=Promise}catch(e){r=function(){}}function s(o,h,c,l,u){"object"==typeof h&&(c=h.depth,l=h.prototype,u=h.includeNonEnumerable,h=h.circular);var d=[],f=[],p=void 0!==i;return void 0===h&&(h=!0),void 0===c&&(c=1/0),function o(c,g){if(null===c)return null;if(0===g)return c;var m,_;if("object"!=typeof c)return c;if(e(c,t))m=new t;else if(e(c,n))m=new n;else if(e(c,r))m=new r((function(e,t){c.then((function(t){e(o(t,g-1))}),(function(e){t(o(e,g-1))}))}));else if(s.__isArray(c))m=[];else if(s.__isRegExp(c))m=new RegExp(c.source,a(c)),c.lastIndex&&(m.lastIndex=c.lastIndex);else if(s.__isDate(c))m=new Date(c.getTime());else{if(p&&i.isBuffer(c))return m=i.allocUnsafe?i.allocUnsafe(c.length):new i(c.length),c.copy(m),m;e(c,Error)?m=Object.create(c):void 0===l?(_=Object.getPrototypeOf(c),m=Object.create(_)):(m=Object.create(l),_=l)}if(h){var y=d.indexOf(c);if(-1!=y)return f[y];d.push(c),f.push(m)}for(var w in e(c,t)&&c.forEach((function(e,t){var n=o(t,g-1),i=o(e,g-1);m.set(n,i)})),e(c,n)&&c.forEach((function(e){var t=o(e,g-1);m.add(t)})),c){var b;_&&(b=Object.getOwnPropertyDescriptor(_,w)),b&&null==b.set||(m[w]=o(c[w],g-1))}if(Object.getOwnPropertySymbols){var v=Object.getOwnPropertySymbols(c);for(w=0;w<v.length;w++){var k=v[w];(!(E=Object.getOwnPropertyDescriptor(c,k))||E.enumerable||u)&&(m[k]=o(c[k],g-1),E.enumerable||Object.defineProperty(m,k,{enumerable:!1}))}}if(u){var x=Object.getOwnPropertyNames(c);for(w=0;w<x.length;w++){var E,S=x[w];(E=Object.getOwnPropertyDescriptor(c,S))&&E.enumerable||(m[S]=o(c[S],g-1),Object.defineProperty(m,S,{enumerable:!1}))}}return m}(o,c)}function o(e){return Object.prototype.toString.call(e)}function a(e){var t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),t}return s.clonePrototype=function(e){if(null===e)return null;var t=function(){};return t.prototype=e,new t},s.__objToStr=o,s.__isDate=function(e){return"object"==typeof e&&"[object Date]"===o(e)},s.__isArray=function(e){return"object"==typeof e&&"[object Array]"===o(e)},s.__isRegExp=function(e){return"object"==typeof e&&"[object RegExp]"===o(e)},s.__getRegExpFlags=a,s}();e.exports&&(e.exports=r)},9648:e=>{e.exports=function(){for(var e=navigator.hardwareConcurrency||1,t=[],n=0;n<e;n++)t.push({model:"",speed:0,times:{user:0,nice:0,sys:0,idle:0,irq:0}});return t}},1227:(e,t,n)=>{var i=n(8768);t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let i=0,r=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(i++,"%c"===e&&(r=i))})),t.splice(r,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&void 0!==i&&"env"in i&&(e=i.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(2447)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},2447:(e,t,n)=>{e.exports=function(e){function t(e){let n,r,s,o=null;function a(...e){if(!a.enabled)return;const i=a,r=Number(new Date),s=r-(n||r);i.diff=s,i.prev=n,i.curr=r,n=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,r)=>{if("%%"===n)return"%";o++;const s=t.formatters[r];if("function"==typeof s){const t=e[o];n=s.call(i,t),e.splice(o,1),o--}return n})),t.formatArgs.call(i,e);(i.log||t.log).apply(i,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=i,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(r!==t.namespaces&&(r=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function i(e,n){const i=t(this.namespace+(void 0===n?":":n)+e);return i.log=this.log,i}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const i=("string"==typeof e?e:"").split(/[\s,]+/),r=i.length;for(n=0;n<r;n++)i[n]&&("-"===(e=i[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,i;for(n=0,i=t.skips.length;n<i;n++)if(t.skips[n].test(e))return!1;for(n=0,i=t.names.length;n<i;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=n(7824),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}},2840:(e,t,n)=>{var i=n(8768),r=n(778),s=function(){},o=function(e,t,n){if("function"==typeof t)return o(e,null,t);t||(t={}),n=r(n||s);var a=e._writableState,h=e._readableState,c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,u=!1,d=function(){e.writable||f()},f=function(){l=!1,c||n.call(e)},p=function(){c=!1,l||n.call(e)},g=function(t){n.call(e,t?new Error("exited with error code: "+t):null)},m=function(t){n.call(e,t)},_=function(){i.nextTick(y)},y=function(){if(!u)return(!c||h&&h.ended&&!h.destroyed)&&(!l||a&&a.ended&&!a.destroyed)?void 0:n.call(e,new Error("premature close"))},w=function(){e.req.on("finish",f)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?l&&!a&&(e.on("end",d),e.on("close",d)):(e.on("complete",f),e.on("abort",_),e.req?w():e.on("request",w)),function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length}(e)&&e.on("exit",g),e.on("end",p),e.on("finish",f),!1!==t.error&&e.on("error",m),e.on("close",_),function(){u=!0,e.removeListener("complete",f),e.removeListener("abort",_),e.removeListener("request",w),e.req&&e.req.removeListener("finish",f),e.removeListener("end",d),e.removeListener("close",d),e.removeListener("finish",f),e.removeListener("exit",g),e.removeListener("end",p),e.removeListener("error",m),e.removeListener("close",_)}};e.exports=o},2114:e=>{function t(e,t){for(const n in t)Object.defineProperty(e,n,{value:t[n],enumerable:!0,configurable:!0});return e}e.exports=function(e,n,i){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");i||(i={}),"object"==typeof n&&(i=n,n=""),n&&(i.code=n);try{return t(e,i)}catch(n){i.message=e.message,i.stack=e.stack;const r=function(){};r.prototype=Object.create(Object.getPrototypeOf(e));return t(new r,i)}}},5573:e=>{var t=/["'&<>]/;e.exports=function(e){var n,i=""+e,r=t.exec(i);if(!r)return i;var s="",o=0,a=0;for(o=r.index;o<i.length;o++){switch(i.charCodeAt(o)){case 34:n="&quot;";break;case 38:n="&amp;";break;case 39:n="&#39;";break;case 60:n="&lt;";break;case 62:n="&gt;";break;default:continue}a!==o&&(s+=i.substring(a,o)),a=o+1,s+=n}return a!==o?s+i.substring(a,o):s}},7187:e=>{var t=Object.create||function(e){var t=function(){};return t.prototype=e,new t},n=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return n},i=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function r(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=t(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0;var s,o=10;try{var a={};Object.defineProperty&&Object.defineProperty(a,"x",{value:0}),s=0===a.x}catch(e){s=!1}function h(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function c(e,n,i,r){var s,o,a;if("function"!=typeof i)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",n,i.listener?i.listener:i),o=e._events),a=o[n]):(o=e._events=t(null),e._eventsCount=0),a){if("function"==typeof a?a=o[n]=r?[i,a]:[a,i]:r?a.unshift(i):a.push(i),!a.warned&&(s=h(e))&&s>0&&a.length>s){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+' "'+String(n)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=n,c.count=a.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else a=o[n]=i,++e._eventsCount;return e}function l(){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;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},s=i.call(l,r);return s.listener=n,r.wrapFn=s,s}function d(e,t,n){var i=e._events;if(!i)return[];var r=i[t];return r?"function"==typeof r?n?[r.listener||r]:[r]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(r):p(r,r.length):[]}function f(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function p(e,t){for(var n=new Array(t),i=0;i<t;++i)n[i]=e[i];return n}s?Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');o=e}}):r.defaultMaxListeners=o,r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return h(this)},r.prototype.emit=function(e){var t,n,i,r,s,o,a="error"===e;if(o=this._events)a=a&&null==o.error;else if(!a)return!1;if(a){if(arguments.length>1&&(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(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,r=p(e,i),s=0;s<i;++s)r[s].call(n)}(n,c,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var r=e.length,s=p(e,r),o=0;o<r;++o)s[o].call(n,i)}(n,c,this,arguments[1]);break;case 3:!function(e,t,n,i,r){if(t)e.call(n,i,r);else for(var s=e.length,o=p(e,s),a=0;a<s;++a)o[a].call(n,i,r)}(n,c,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,r,s){if(t)e.call(n,i,r,s);else for(var o=e.length,a=p(e,o),h=0;h<o;++h)a[h].call(n,i,r,s)}(n,c,this,arguments[1],arguments[2],arguments[3]);break;default:for(r=new Array(i-1),s=1;s<i;s++)r[s-1]=arguments[s];!function(e,t,n,i){if(t)e.apply(n,i);else for(var r=e.length,s=p(e,r),o=0;o<r;++o)s[o].apply(n,i)}(n,c,this,r)}return!0},r.prototype.addListener=function(e,t){return c(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return c(this,e,t,!0)},r.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,u(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,u(this,e,t)),this},r.prototype.removeListener=function(e,n){var i,r,s,o,a;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(i=r[e]))return this;if(i===n||i.listener===n)0==--this._eventsCount?this._events=t(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,i.listener||n));else if("function"!=typeof i){for(s=-1,o=i.length-1;o>=0;o--)if(i[o]===n||i[o].listener===n){a=i[o].listener,s=o;break}if(s<0)return this;0===s?i.shift():function(e,t){for(var n=t,i=n+1,r=e.length;i<r;n+=1,i+=1)e[n]=e[i];e.pop()}(i,s),1===i.length&&(r[e]=i[0]),r.removeListener&&this.emit("removeListener",e,a||n)}return this},r.prototype.removeAllListeners=function(e){var i,r,s;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=t(null),this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=t(null):delete r[e]),this;if(0===arguments.length){var o,a=n(r);for(s=0;s<a.length;++s)"removeListener"!==(o=a[s])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=t(null),this._eventsCount=0,this}if("function"==typeof(i=r[e]))this.removeListener(e,i);else if(i)for(s=i.length-1;s>=0;s--)this.removeListener(e,i[s]);return this},r.prototype.listeners=function(e){return d(this,e,!0)},r.prototype.rawListeners=function(e){return d(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},r.prototype.listenerCount=f,r.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},3975:e=>{e.exports=class{constructor(e){if(!(e>0)||0!=(e-1&e))throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return void 0===this.buffer[this.btm]}}},1607:(e,t,n)=>{const i=n(3975);e.exports=class{constructor(e){this.hwm=e||16,this.head=new i(this.hwm),this.tail=this.head,this.length=0}push(e){if(this.length++,!this.head.push(e)){const t=this.head;this.head=t.next=new i(2*this.head.buffer.length),this.head.push(e)}}shift(){0!==this.length&&this.length--;const e=this.tail.shift();if(void 0===e&&this.tail.next){const e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){return this.tail.peek()}isEmpty(){return this.head.isEmpty()}}},3811:()=>{"undefined"==typeof ReadableStream||ReadableStream.prototype[Symbol.asyncIterator]||(ReadableStream.prototype[Symbol.asyncIterator]=function(){const e=this.getReader();let t=e.read();return{next(){const n=t;return t=e.read(),n},return(){t.then((()=>e.releaseLock()))},throw(e){throw this.return(),e},[Symbol.asyncIterator](){return this}}})},5177:e=>{e.exports=function(){if("undefined"==typeof globalThis)return null;var e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}},4137:(e,t,n)=>{var i=n(8764).lW;const r=n(3029),s=n(7187).EventEmitter,o=n(4375);e.exports=class extends s{constructor(e,t){if(t||(t={}),super(),this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.closed=!1,this.destroyed=!1,this.length=Number(t.length)||1/0,this.name=t.name||"idb-chunk-store",this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1),this.dbPromise=r.openDB(this.name,void 0,{upgrade:e=>{e.createObjectStore("chunks")},blocking:()=>{this.close()},terminated:()=>{this.closed=!0,this.emit("error",new Error("Database unexpectedly closed"))}})}put(e,t,n=(()=>{})){if(this.closed)return o((()=>n(new Error("Storage is closed"))));const i=e===this.lastChunkIndex;return i&&t.length!==this.lastChunkLength?o((()=>n(new Error("Last chunk length must be "+this.lastChunkLength)))):i||t.length===this.chunkLength?(0===(t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).byteOffset&&t.byteLength===t.buffer.byteLength||(t=t.slice()),void(async()=>{try{const n=await this.dbPromise;await n.put("chunks",t,e)}catch(e){return void n(e)}n(null)})()):o((()=>n(new Error("Chunk length must be "+this.chunkLength))))}get(e,t,n=(()=>{})){return"function"==typeof t?this.get(e,{},t):(t||(t={}),this.closed?o((()=>n(new Error("Storage is closed")))):void(async()=>{let r;try{const t=await this.dbPromise;r=await t.get("chunks",e)}catch(e){return void n(e)}if(null==r){const e=new Error("Chunk not found");return e.notFound=!0,void n(e)}let s=i.from(r.buffer,r.byteOffset,r.byteLength);const o=t.offset||0,a=t.length||s.length-o;0===o&&a===s.length||(s=s.slice(o,a+o)),n(null,s)})())}close(e=(()=>{})){if(this.closed)return o((()=>e(new Error("Storage is closed"))));this.closed=!0,(async()=>{try{(await this.dbPromise).close()}catch(t){return void e(t)}e(null)})()}destroy(e=(()=>{})){return this.closed?o((()=>e(new Error("Storage is closed")))):this.destroyed?o((()=>e(new Error("Storage is destroyed")))):(this.destroyed=!0,void this.close((async t=>{if(t)e(t);else{try{await r.deleteDB(this.name)}catch(t){return void e(t)}e(null)}})))}}},3029:(e,t,n)=>{n.r(t),n.d(t,{deleteDB:()=>_,openDB:()=>m,unwrap:()=>g,wrap:()=>p});const i=(e,t)=>t.some((t=>e instanceof t));let r,s;const o=new WeakMap,a=new WeakMap,h=new WeakMap,c=new WeakMap,l=new WeakMap;let u={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return a.get(e);if("objectStoreNames"===t)return e.objectStoreNames||h.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return p(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function d(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(s||(s=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(g(this),t),p(o.get(this))}:function(...t){return p(e.apply(g(this),t))}:function(t,...n){const i=e.call(g(this),t,...n);return h.set(i,t.sort?t.sort():[t]),p(i)}}function f(e){return"function"==typeof e?d(e):(e instanceof IDBTransaction&&function(e){if(a.has(e))return;const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",s),e.removeEventListener("abort",s)},r=()=>{t(),i()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",r),e.addEventListener("error",s),e.addEventListener("abort",s)}));a.set(e,t)}(e),i(e,r||(r=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,u):e)}function p(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("success",r),e.removeEventListener("error",s)},r=()=>{t(p(e.result)),i()},s=()=>{n(e.error),i()};e.addEventListener("success",r),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&o.set(t,e)})).catch((()=>{})),l.set(t,e),t}(e);if(c.has(e))return c.get(e);const t=f(e);return t!==e&&(c.set(e,t),l.set(t,e)),t}const g=e=>l.get(e);function m(e,t,{blocked:n,upgrade:i,blocking:r,terminated:s}={}){const o=indexedDB.open(e,t),a=p(o);return i&&o.addEventListener("upgradeneeded",(e=>{i(p(o.result),e.oldVersion,e.newVersion,p(o.transaction))})),n&&o.addEventListener("blocked",(()=>n())),a.then((e=>{s&&e.addEventListener("close",(()=>s())),r&&e.addEventListener("versionchange",(()=>r()))})).catch((()=>{})),a}function _(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(()=>t())),p(n).then((()=>{}))}const y=["get","getKey","getAll","getAllKeys","count"],w=["put","add","delete","clear"],b=new Map;function v(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(b.get(t))return b.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,r=w.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!r&&!y.includes(n))return;const s=async function(e,...t){const s=this.transaction(e,r?"readwrite":"readonly");let o=s.store;return i&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),r&&s.done]))[0]};return b.set(t,s),s}u=(e=>({...e,get:(t,n,i)=>v(t,n)||e.get(t,n,i),has:(t,n)=>!!v(t,n)||e.has(t,n)}))(u)},645:(e,t)=>{t.read=function(e,t,n,i,r){var s,o,a=8*r-i-1,h=(1<<a)-1,c=h>>1,l=-7,u=n?r-1:0,d=n?-1:1,f=e[t+u];for(u+=d,s=f&(1<<-l)-1,f>>=-l,l+=a;l>0;s=256*s+e[t+u],u+=d,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=i;l>0;o=256*o+e[t+u],u+=d,l-=8);if(0===s)s=1-c;else{if(s===h)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,i),s-=c}return(f?-1:1)*o*Math.pow(2,s-i)},t.write=function(e,t,n,i,r,s){var o,a,h,c=8*s-r-1,l=(1<<c)-1,u=l>>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=i?0:s-1,p=i?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=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(h=Math.pow(2,-o))<1&&(o--,h*=2),(t+=o+u>=1?d/h:d*Math.pow(2,1-u))*h>=2&&(o++,h/=2),o+u>=l?(a=0,o=l):o+u>=1?(a=(t*h-1)*Math.pow(2,r),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;e[n+f]=255&a,f+=p,a/=256,r-=8);for(o=o<<r|a,c+=r;c>0;e[n+f]=255&o,f+=p,o/=256,c-=8);e[n+f-p]|=128*g}},3700:(e,t,n)=>{const i=n(4375);e.exports=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(t)}))}get(e,t,n=(()=>{})){if("function"==typeof t)return this.get(e,null,t);let r=this.mem[e];if(!r)return this.store.get(e,t,n);t||(t={});const s=t.offset||0,o=t.length||r.length-s;0===s&&o===r.length||(r=r.slice(s,o+s)),i((()=>n(null,r)))}close(e=(()=>{})){this.store.close(e)}destroy(e=(()=>{})){this.store.destroy(e)}}},5717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},8225:e=>{e.exports=async function*(e){for(let t of e)"function"==typeof t&&(t=t()),yield*t}},1351:(e,t)=>{t.re=()=>{throw new Error("`junk.re` was renamed to `junk.regex`")},t.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("|")),t.is=e=>t.regex.test(e),t.not=e=>!t.is(e),t.default=e.exports},5516:(e,t,n)=>{t.RateLimiter=n(1114),t.TokenBucket=n(4976)},6188:(e,t,n)=>{var i=n(8768);e.exports=function(){if(void 0!==i&&i.hrtime){var e=i.hrtime(),t=e[0],n=e[1];return 1e3*t+Math.floor(n/1e6)}return(new Date).getTime()}},1114:(e,t,n)=>{var i=n(8768),r=n(4976),s=n(6188),o=function(e,t,n){this.tokenBucket=new r(e,e,t,null),this.tokenBucket.content=e,this.curIntervalStart=s(),this.tokensThisInterval=0,this.fireImmediately=n};o.prototype={tokenBucket:null,curIntervalStart:0,tokensThisInterval:0,fireImmediately:!1,removeTokens:function(e,t){if(e>this.tokenBucket.bucketSize)return i.nextTick(t.bind(null,"Requested tokens "+e+" exceeds maximum tokens per interval "+this.tokenBucket.bucketSize,null)),!1;var n=this,r=s();if((r<this.curIntervalStart||r-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=r,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval){if(this.fireImmediately)i.nextTick(t.bind(null,null,-1));else{var o=Math.ceil(this.curIntervalStart+this.tokenBucket.interval-r);setTimeout((function(){n.tokenBucket.removeTokens(e,a)}),o)}return!1}return this.tokenBucket.removeTokens(e,a);function a(i,r){if(i)return t(i,null);n.tokensThisInterval+=e,t(null,r)}},tryRemoveTokens:function(e){if(e>this.tokenBucket.bucketSize)return!1;var t=s();if((t<this.curIntervalStart||t-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=t,this.tokensThisInterval=0),e>this.tokenBucket.tokensPerInterval-this.tokensThisInterval)return!1;var n=this.tokenBucket.tryRemoveTokens(e);return n&&(this.tokensThisInterval+=e),n},getTokensRemaining:function(){return this.tokenBucket.drip(),this.tokenBucket.content}},e.exports=o},4976:(e,t,n)=>{var i=n(8768),r=function(e,t,n,i){if(this.bucketSize=e,this.tokensPerInterval=t,"string"==typeof n)switch(n){case"sec":case"second":this.interval=1e3;break;case"min":case"minute":this.interval=6e4;break;case"hr":case"hour":this.interval=36e5;break;case"day":this.interval=864e5;break;default:throw new Error("Invaid interval "+n)}else this.interval=n;this.parentBucket=i,this.content=0,this.lastDrip=+new Date};r.prototype={bucketSize:1,tokensPerInterval:1,interval:1e3,parentBucket:null,content:0,lastDrip:0,removeTokens:function(e,t){var n=this;return this.bucketSize?e>this.bucketSize?(i.nextTick(t.bind(null,"Requested tokens "+e+" exceeds bucket size "+this.bucketSize,null)),!1):(this.drip(),e>this.content?r():this.parentBucket?this.parentBucket.removeTokens(e,(function(i,s){return i?t(i,null):e>n.content?r():(n.content-=e,void t(null,Math.min(s,n.content)))})):(this.content-=e,i.nextTick(t.bind(null,null,this.content)),!0)):(i.nextTick(t.bind(null,null,e,Number.POSITIVE_INFINITY)),!0);function r(){var i=Math.ceil((e-n.content)*(n.interval/n.tokensPerInterval));return setTimeout((function(){n.removeTokens(e,t)}),i),!1}},tryRemoveTokens:function(e){return!this.bucketSize||!(e>this.bucketSize)&&(this.drip(),!(e>this.content)&&(!(this.parentBucket&&!this.parentBucket.tryRemoveTokens(e))&&(this.content-=e,!0)))},drip:function(){if(this.tokensPerInterval){var e=+new Date,t=Math.max(e-this.lastDrip,0);this.lastDrip=e;var n=t*(this.tokensPerInterval/this.interval);this.content=Math.min(this.content+n,this.bucketSize)}else this.content=this.bucketSize}},e.exports=r},7117:(e,t,n)=>{var i=n(7187),r=n(5717);function s(e){if(!(this instanceof s))return new s(e);"number"==typeof e&&(e={max:e}),e||(e={}),i.EventEmitter.call(this),this.cache={},this.head=this.tail=null,this.length=0,this.max=e.max||1e3,this.maxAge=e.maxAge||0}e.exports=s,r(s,i.EventEmitter),Object.defineProperty(s.prototype,"keys",{get:function(){return Object.keys(this.cache)}}),s.prototype.clear=function(){this.cache={},this.head=this.tail=null,this.length=0},s.prototype.remove=function(e){if("string"!=typeof e&&(e=""+e),this.cache.hasOwnProperty(e)){var t=this.cache[e];return delete this.cache[e],this._unlink(e,t.prev,t.next),t.value}},s.prototype._unlink=function(e,t,n){this.length--,0===this.length?this.head=this.tail=null:this.head===e?(this.head=t,this.cache[this.head].next=null):this.tail===e?(this.tail=n,this.cache[this.tail].prev=null):(this.cache[t].next=n,this.cache[n].prev=t)},s.prototype.peek=function(e){if(this.cache.hasOwnProperty(e)){var t=this.cache[e];if(this._checkAge(e,t))return t.value}},s.prototype.set=function(e,t){var n;if("string"!=typeof e&&(e=""+e),this.cache.hasOwnProperty(e)){if((n=this.cache[e]).value=t,this.maxAge&&(n.modified=Date.now()),e===this.head)return t;this._unlink(e,n.prev,n.next)}else n={value:t,modified:0,next:null,prev:null},this.maxAge&&(n.modified=Date.now()),this.cache[e]=n,this.length===this.max&&this.evict();return this.length++,n.next=null,n.prev=this.head,this.head&&(this.cache[this.head].next=e),this.head=e,this.tail||(this.tail=e),t},s.prototype._checkAge=function(e,t){return!(this.maxAge&&Date.now()-t.modified>this.maxAge)||(this.remove(e),this.emit("evict",{key:e,value:t.value}),!1)},s.prototype.get=function(e){if("string"!=typeof e&&(e=""+e),this.cache.hasOwnProperty(e)){var t=this.cache[e];if(this._checkAge(e,t))return this.head!==e&&(e===this.tail?(this.tail=t.next,this.cache[this.tail].prev=null):this.cache[t.prev].next=t.next,this.cache[t.next].prev=t.prev,this.cache[this.head].next=e,t.prev=this.head,t.next=null,this.head=e),t.value}},s.prototype.evict=function(){if(this.tail){var e=this.tail,t=this.remove(this.tail);this.emit("evict",{key:e,value:t})}}},9417:(e,t,n)=>{var i=n(8764).lW;const r=n(6581),{EventEmitter:s}=n(7187),o=n(1227)("lt_donthave");e.exports=()=>{class e extends s{constructor(e){super(),this._peerSupports=!1,this._wire=e}onExtendedHandshake(){this._peerSupports=!0}onMessage(e){let t;try{t=e.readUInt32BE()}catch(e){return}this._wire.peerPieces.get(t)&&(o("got donthave %d",t),this._wire.peerPieces.set(t,!1),this.emit("donthave",t),this._failRequests(t))}donthave(e){if(!this._peerSupports)return;o("donthave %d",e);const t=i.alloc(4);t.writeUInt32BE(e),this._wire.extended("lt_donthave",t)}_failRequests(e){const t=this._wire.requests;for(let n=0;n<t.length;n++){const i=t[n];i.piece===e&&(r(t,n),n-=1,this._wire._callback(i,new Error("peer sent donthave"),null))}}}return e.prototype.name="lt_donthave",e}},1191:(e,t,n)=>{e.exports=r;const i=n(4375);function r(e,t){if(!(this instanceof r))return new r(e,t);if(t||(t={}),this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.chunks=[],this.closed=!1,this.length=Number(t.length)||1/0,this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1)}r.prototype.put=function(e,t,n=(()=>{})){if(this.closed)return i((()=>n(new Error("Storage is closed"))));const r=e===this.lastChunkIndex;return r&&t.length!==this.lastChunkLength?i((()=>n(new Error("Last chunk length must be "+this.lastChunkLength)))):r||t.length===this.chunkLength?(this.chunks[e]=t,void i((()=>n(null)))):i((()=>n(new Error("Chunk length must be "+this.chunkLength))))},r.prototype.get=function(e,t,n=(()=>{})){if("function"==typeof t)return this.get(e,null,t);if(this.closed)return i((()=>n(new Error("Storage is closed"))));let r=this.chunks[e];if(!r){const e=new Error("Chunk not found");return e.notFound=!0,i((()=>n(e)))}t||(t={});const s=t.offset||0,o=t.length||r.length-s;0===s&&o===r.length||(r=r.slice(s,o+s)),i((()=>n(null,r)))},r.prototype.close=r.prototype.destroy=function(e=(()=>{})){if(this.closed)return i((()=>e(new Error("Storage is closed"))));this.closed=!0,this.chunks=null,i((()=>e(null)))}},9146:e=>{function t(){this._types=Object.create(null),this._extensions=Object.create(null);for(let e=0;e<arguments.length;e++)this.define(arguments[e]);this.define=this.define.bind(this),this.getType=this.getType.bind(this),this.getExtension=this.getExtension.bind(this)}t.prototype.define=function(e,t){for(let n in e){let i=e[n].map((function(e){return e.toLowerCase()}));n=n.toLowerCase();for(let e=0;e<i.length;e++){const r=i[e];if("*"!==r[0]){if(!t&&r in this._types)throw new Error('Attempt to change mapping for "'+r+'" extension from "'+this._types[r]+'" to "'+n+'". Pass `force=true` to allow this, otherwise remove "'+r+'" from the list of extensions for "'+n+'".');this._types[r]=n}}if(t||!this._extensions[n]){const e=i[0];this._extensions[n]="*"!==e[0]?e:e.substr(1)}}},t.prototype.getType=function(e){let t=(e=String(e)).replace(/^.*[/\\]/,"").toLowerCase(),n=t.replace(/^.*\./,"").toLowerCase(),i=t.length<e.length;return(n.length<t.length-1||!i)&&this._types[n]||null},t.prototype.getExtension=function(e){return(e=/^\s*([^;\s]*)/.test(e)&&RegExp.$1)&&this._extensions[e.toLowerCase()]||null},e.exports=t},2109:(e,t,n)=>{let i=n(9146);e.exports=new i(n(4415))},4415:e=>{e.exports={"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}},7824:e=>{var t=1e3,n=60*t,i=60*n,r=24*i,s=7*r,o=365.25*r;function a(e,t,n,i){var r=t>=1.5*n;return Math.round(e/n)+" "+i+(r?"s":"")}e.exports=function(e,h){h=h||{};var c=typeof e;if("string"===c&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\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(!a)return;var h=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return h*o;case"weeks":case"week":case"w":return h*s;case"days":case"day":case"d":return h*r;case"hours":case"hour":case"hrs":case"hr":case"h":return h*i;case"minutes":case"minute":case"mins":case"min":case"m":return h*n;case"seconds":case"second":case"secs":case"sec":case"s":return h*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return h;default:return}}(e);if("number"===c&&isFinite(e))return h.long?function(e){var s=Math.abs(e);if(s>=r)return a(e,s,r,"day");if(s>=i)return a(e,s,i,"hour");if(s>=n)return a(e,s,n,"minute");if(s>=t)return a(e,s,t,"second");return e+" ms"}(e):function(e){var s=Math.abs(e);if(s>=r)return Math.round(e/r)+"d";if(s>=i)return Math.round(e/i)+"h";if(s>=n)return Math.round(e/n)+"m";if(s>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},778:(e,t,n)=>{var i=n(2479);function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function s(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}e.exports=i(r),e.exports.strict=i(s),r.proto=r((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s(this)},configurable:!0})}))},6470:(e,t,n)=>{var i=n(8768);function r(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function s(e,t){for(var n,i="",r=0,s=-1,o=0,a=0;a<=e.length;++a){if(a<e.length)n=e.charCodeAt(a);else{if(47===n)break;n=47}if(47===n){if(s===a-1||1===o);else if(s!==a-1&&2===o){if(i.length<2||2!==r||46!==i.charCodeAt(i.length-1)||46!==i.charCodeAt(i.length-2))if(i.length>2){var h=i.lastIndexOf("/");if(h!==i.length-1){-1===h?(i="",r=0):r=(i=i.slice(0,h)).length-1-i.lastIndexOf("/"),s=a,o=0;continue}}else if(2===i.length||1===i.length){i="",r=0,s=a,o=0;continue}t&&(i.length>0?i+="/..":i="..",r=2)}else i.length>0?i+="/"+e.slice(s+1,a):i=e.slice(s+1,a),r=a-s-1;s=a,o=0}else 46===n&&-1!==o?++o:o=-1}return i}var o={resolve:function(){for(var e,t="",n=!1,o=arguments.length-1;o>=-1&&!n;o--){var a;o>=0?a=arguments[o]:(void 0===e&&(e=i.cwd()),a=e),r(a),0!==a.length&&(t=a+"/"+t,n=47===a.charCodeAt(0))}return t=s(t,!n),n?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(e){if(r(e),0===e.length)return".";var t=47===e.charCodeAt(0),n=47===e.charCodeAt(e.length-1);return 0!==(e=s(e,!t)).length||t||(e="."),e.length>0&&n&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return r(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,t=0;t<arguments.length;++t){var n=arguments[t];r(n),n.length>0&&(void 0===e?e=n:e+="/"+n)}return void 0===e?".":o.normalize(e)},relative:function(e,t){if(r(e),r(t),e===t)return"";if((e=o.resolve(e))===(t=o.resolve(t)))return"";for(var n=1;n<e.length&&47===e.charCodeAt(n);++n);for(var i=e.length,s=i-n,a=1;a<t.length&&47===t.charCodeAt(a);++a);for(var h=t.length-a,c=s<h?s:h,l=-1,u=0;u<=c;++u){if(u===c){if(h>c){if(47===t.charCodeAt(a+u))return t.slice(a+u+1);if(0===u)return t.slice(a+u)}else s>c&&(47===e.charCodeAt(n+u)?l=u:0===u&&(l=0));break}var d=e.charCodeAt(n+u);if(d!==t.charCodeAt(a+u))break;47===d&&(l=u)}var f="";for(u=n+l+1;u<=i;++u)u!==i&&47!==e.charCodeAt(u)||(0===f.length?f+="..":f+="/..");return f.length>0?f+t.slice(a+l):(a+=l,47===t.charCodeAt(a)&&++a,t.slice(a))},_makeLong:function(e){return e},dirname:function(e){if(r(e),0===e.length)return".";for(var t=e.charCodeAt(0),n=47===t,i=-1,s=!0,o=e.length-1;o>=1;--o)if(47===(t=e.charCodeAt(o))){if(!s){i=o;break}}else s=!1;return-1===i?n?"/":".":n&&1===i?"//":e.slice(0,i)},basename:function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');r(e);var n,i=0,s=-1,o=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var a=t.length-1,h=-1;for(n=e.length-1;n>=0;--n){var c=e.charCodeAt(n);if(47===c){if(!o){i=n+1;break}}else-1===h&&(o=!1,h=n+1),a>=0&&(c===t.charCodeAt(a)?-1==--a&&(s=n):(a=-1,s=h))}return i===s?s=h:-1===s&&(s=e.length),e.slice(i,s)}for(n=e.length-1;n>=0;--n)if(47===e.charCodeAt(n)){if(!o){i=n+1;break}}else-1===s&&(o=!1,s=n+1);return-1===s?"":e.slice(i,s)},extname:function(e){r(e);for(var t=-1,n=0,i=-1,s=!0,o=0,a=e.length-1;a>=0;--a){var h=e.charCodeAt(a);if(47!==h)-1===i&&(s=!1,i=a+1),46===h?-1===t?t=a:1!==o&&(o=1):-1!==t&&(o=-1);else if(!s){n=a+1;break}}return-1===t||-1===i||0===o||1===o&&t===i-1&&t===n+1?"":e.slice(t,i)},format:function(e){if(null===e||"object"!=typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var n=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+i:n+e+i:i}("/",e)},parse:function(e){r(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var n,i=e.charCodeAt(0),s=47===i;s?(t.root="/",n=1):n=0;for(var o=-1,a=0,h=-1,c=!0,l=e.length-1,u=0;l>=n;--l)if(47!==(i=e.charCodeAt(l)))-1===h&&(c=!1,h=l+1),46===i?-1===o?o=l:1!==u&&(u=1):-1!==o&&(u=-1);else if(!c){a=l+1;break}return-1===o||-1===h||0===u||1===u&&o===h-1&&o===a+1?-1!==h&&(t.base=t.name=0===a&&s?e.slice(1,h):e.slice(a,h)):(0===a&&s?(t.name=e.slice(1,o),t.base=e.slice(1,h)):(t.name=e.slice(a,o),t.base=e.slice(a,h)),t.ext=e.slice(o,h)),a>0?t.dir=e.slice(0,a-1):s&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};o.posix=o,e.exports=o},3786:e=>{e.exports=function(e){return Math.max(16384,1<<Math.log2(e<1024?1:e/1024)+.5|0)}},4286:(e,t,n)=>{var i=n(8768),r=n(778),s=n(2840),o=n(1156),a=function(){},h=/^v?\.0/.test(i.version),c=function(e){return"function"==typeof e},l=function(e,t,n,i){i=r(i);var l=!1;e.on("close",(function(){l=!0})),s(e,{readable:t,writable:n},(function(e){if(e)return i(e);l=!0,i()}));var u=!1;return function(t){if(!l&&!u)return u=!0,function(e){return!!h&&!!o&&(e instanceof(o.ReadStream||a)||e instanceof(o.WriteStream||a))&&c(e.close)}(e)?e.close(a):function(e){return e.setHeader&&c(e.abort)}(e)?e.abort():c(e.destroy)?e.destroy():void i(t||new Error("stream was destroyed"))}},u=function(e){e()},d=function(e,t){return e.pipe(t)};e.exports=function(){var e,t=Array.prototype.slice.call(arguments),n=c(t[t.length-1]||a)&&t.pop()||a;if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new Error("pump requires two streams per minimum");var i=t.map((function(r,s){var o=s<t.length-1;return l(r,o,s>0,(function(t){e||(e=t),t&&i.forEach(u),o||(i.forEach(u),n(e))}))}));return t.reduce(d)}},4375:e=>{let t;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:globalThis):e=>(t||(t=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))},3527:e=>{e.exports="function"==typeof queueMicrotask?queueMicrotask:e=>Promise.resolve().then(e)},5960:e=>{e.exports=function(e){var t=0;return function(){if(t===e.length)return null;var n=e.length-t,i=Math.random()*n|0,r=e[t+i],s=e[t];return e[t]=r,e[t+i]=s,t++,r}}},4622:e=>{function t(e,t){return{start:e.start,end:e.end,index:t}}function n(e){return{start:e.start,end:e.end}}function i(e,t){return e.index-t.index}function r(e,t){return e.start-t.start}e.exports=function(e,s,o){if("string"!=typeof s)throw new TypeError("argument str must be a string");var a=s.indexOf("=");if(-1===a)return-2;var h=s.slice(a+1).split(","),c=[];c.type=s.slice(0,a);for(var l=0;l<h.length;l++){var u=h[l].split("-"),d=parseInt(u[0],10),f=parseInt(u[1],10);isNaN(d)?(d=e-f,f=e-1):isNaN(f)&&(f=e-1),f>e-1&&(f=e-1),isNaN(d)||isNaN(f)||d>f||d<0||c.push({start:d,end:f})}if(c.length<1)return-1;return o&&o.combine?function(e){for(var s=e.map(t).sort(r),o=0,a=1;a<s.length;a++){var h=s[a],c=s[o];h.start>c.end+1?s[++o]=h:h.end>c.end&&(c.end=h.end,c.index=Math.min(c.index,h.index))}s.length=o+1;var l=s.sort(i).map(n);return l.type=e.type,l}(c):c}},7830:e=>{function t(e){return parseInt(e,10)===e}function n(e){function n(t){if(void 0===t){t=new Array(e);for(var n=0;n<e;n++)t[n]=Math.floor(Math.random()*e)}else if("string"==typeof t)t=(t=""+t).split("").map((function(t){return t.charCodeAt(0)%e}));else{if(!Array.isArray(t))throw new TypeError("invalid seed key specified");if(!t.every((function(e){return"number"==typeof e&&e===(0|e)})))throw new TypeError("invalid seed key specified: not array of integers")}for(var i=t.length,r=function(){for(var t=new Array(e),n=0;n<e;n++)t[n]=n;return t}(),s=0,o=0;o<e;o++){s=(s+r[o]+t[o%i])%e;var a=r[o];r[o]=r[s],r[s]=a}return r}function i(e){this.s=n(e),this.i=0,this.j=0}return i.prototype.randomNative=function(){this.i=(this.i+1)%e,this.j=(this.j+this.s[this.i])%e;var t=this.s[this.i];return this.s[this.i]=this.s[this.j],this.s[this.j]=t,this.s[(this.s[this.i]+this.s[this.j])%e]},i.prototype.randomUInt32=function(){return 256*(256*(256*this.randomByte()+this.randomByte())+this.randomByte())+this.randomByte()},i.prototype.randomFloat=function(){return this.randomUInt32()/4294967296},i.prototype.random=function(){var e,n;if(1===arguments.length)e=0,n=arguments[0];else{if(2!==arguments.length)throw new TypeError("random takes one or two integer arguments");e=arguments[0],n=arguments[1]}if(!t(e)||!t(n))throw new TypeError("random takes one or two integer arguments");return e+this.randomUInt32()%(n-e+1)},i.prototype.currentState=function(){return{i:this.i,j:this.j,s:this.s.slice()}},i.prototype.setState=function(t){var n=t.s,i=t.i,r=t.j;if(!(i===(0|i)&&0<=i&&i<e))throw new Error("state.i should be integer [0, "+(e-1)+"]");if(!(r===(0|r)&&0<=r&&r<e))throw new Error("state.j should be integer [0, "+(e-1)+"]");if(!Array.isArray(n)||n.length!==e)throw new Error("state should be array of length "+e);for(var s=0;s<e;s++)if(-1===n.indexOf(s))throw new Error("state should be permutation of 0.."+(e-1)+": "+s+" is missing");this.i=i,this.j=r,this.s=n.slice()},i}var i=n(256);i.prototype.randomByte=i.prototype.randomNative;var r=n(16);r.prototype.randomByte=function(){return 16*this.randomNative()+this.randomNative()};var s="a".charCodeAt(0),o="0".charCodeAt(0);function a(e){return e<10?String.fromCharCode(o+e):String.fromCharCode(s+e-10)}function h(e){return parseInt(e,16)}r.prototype.currentStateString=function(){var e=this.currentState();return a(e.i)+a(e.j)+e.s.map(a).join("")},r.prototype.setStateString=function(e){if(!e.match(/^[0-9a-f]{18}$/))throw new TypeError("RC4small stateString should be 18 hex character string");var t=h(e[0]),n=h(e[1]),i=e.split("").slice(2).map(h);this.setState({i:t,j:n,s:i})},i.RC4small=r,e.exports=i},9967:(e,t,n)=>{e.exports=function(e,t,n){if("number"!=typeof t)throw new Error("second argument must be a Number");let r,s,o,a,h,c,l=!0;Array.isArray(e)?(r=[],o=s=e.length):(a=Object.keys(e),r={},o=s=a.length);function u(e){function t(){n&&n(e,r),n=null}l?i(t):t()}function d(t,n,i){if(r[t]=i,n&&(h=!0),0==--o||n)u(n);else if(!h&&c<s){let t;a?(t=a[c],c+=1,e[t]((function(e,n){d(t,e,n)}))):(t=c,c+=1,e[t]((function(e,n){d(t,e,n)})))}}c=t,o?a?a.some((function(n,i){return e[n]((function(e,t){d(n,e,t)})),i===t-1})):e.some((function(e,n){return e((function(e,t){d(n,e,t)})),n===t-1})):u(null);l=!1};const i=n(4375)},4595:(e,t,n)=>{e.exports=function(e,t){let n,r,s,o=!0;Array.isArray(e)?(n=[],r=e.length):(s=Object.keys(e),n={},r=s.length);function a(e){function r(){t&&t(e,n),t=null}o?i(r):r()}function h(e,t,i){n[e]=i,(0==--r||t)&&a(t)}r?s?s.forEach((function(t){e[t]((function(e,n){h(t,e,n)}))})):e.forEach((function(e,t){e((function(e,n){h(t,e,n)}))})):a(null);o=!1};const i=n(4375)},558:(e,t,n)=>{const i=n(7768),r=n(9929);e.exports={Throttle:i,ThrottleGroup:r}},9929:(e,t,n)=>{const{TokenBucket:i}=n(5516),r=n(7768);e.exports=class{constructor(e={}){if("object"!=typeof e)throw new Error("Options must be an object");this.throttles=[],this.setEnabled(e.enabled),this.setRate(e.rate,e.chunksize)}getEnabled(){return this._enabled}getRate(){return this.bucket.tokensPerInterval}getChunksize(){return this.chunksize}setEnabled(e=!0){if("boolean"!=typeof e)throw new Error("Enabled must be a boolean");this._enabled=e;for(const t of this.throttles)t.setEnabled(e)}setRate(e,t=null){if(!Number.isInteger(e)||e<0)throw new Error("Rate must be an integer bigger than zero");if(e=parseInt(e),t&&("number"!=typeof t||t<=0))throw new Error("Chunksize must be bigger than zero");if(t=t||Math.max(parseInt(e/10),1),t=parseInt(t),e>0&&t>e)throw new Error("Chunk size must be smaller than rate");this.bucket||(this.bucket=new i(e,e,"second",null)),this.bucket.bucketSize=e,this.bucket.tokensPerInterval=e,this.chunksize=t}setChunksize(e){if(!Number.isInteger(e)||e<=0)throw new Error("Chunk size must be an integer bigger than zero");const t=this.getRate();if(e=parseInt(e),t>0&&e>t)throw new Error("Chunk size must be smaller than rate");this.chunksize=e}throttle(e={}){if("object"!=typeof e)throw new Error("Options must be an object");return new r({...e,group:this})}destroy(){for(const e of this.throttles)e.destroy();this.throttles=[]}_addThrottle(e){if(!(e instanceof r))throw new Error("Throttle must be an instance of Throttle");this.throttles.push(e)}_removeThrottle(e){const t=this.throttles.indexOf(e);t>-1&&this.throttles.splice(t,1)}}},7768:(e,t,n)=>{const{EventEmitter:i}=n(7187),{Transform:r}=n(1237),{wait:s}=n(5324);e.exports=class extends r{constructor(e={}){if(super(),"object"!=typeof e)throw new Error("Options must be an object");const t=Object.assign({},e);if(t.group&&!(t.group instanceof o))throw new Error("Group must be an instanece of ThrottleGroup");t.group||(t.group=new o(t)),this._setEnabled(t.enabled||t.group.enabled),this._group=t.group,this._emitter=new i,this._destroyed=!1,this._group._addThrottle(this)}getEnabled(){return this._enabled}getGroup(){return this._group}_setEnabled(e=!0){if("boolean"!=typeof e)throw new Error("Enabled must be a boolean");this._enabled=e}setEnabled(e){this._setEnabled(e),this._enabled?this._emitter.emit("enabled"):this._emitter.emit("disabled")}_transform(e,t){this._processChunk(e,t)}async _waitForTokens(e){return new Promise(((t,n)=>{let i=!1;const r=this;function s(e){if(r._emitter.removeListener("disabled",s),r._emitter.removeListener("destroyed",s),!i){if(i=!0,e)return n(e);t()}}this._emitter.once("disabled",s),this._emitter.once("destroyed",s),this._group.bucket.removeTokens(e,s)}))}_areBothEnabled(){return this._enabled&&this._group.getEnabled()}async _processChunk(e,t){if(!this._areBothEnabled())return t(null,e);let n=0,i=this._group.getChunksize(),r=e.slice(n,n+i);for(;r.length>0;){if(this._areBothEnabled())try{for(;0===this._group.getRate()&&!this._destroyed&&this._areBothEnabled();)if(await s(1e3),this._destroyed)return;if(this._areBothEnabled()&&!this._group.bucket.tryRemoveTokens(r.length)&&(await this._waitForTokens(r.length),this._destroyed))return}catch(e){return t(e)}this.push(r),n+=i,i=this._areBothEnabled()?this._group.getChunksize():e.length-n,r=e.slice(n,n+i)}return t()}destroy(...e){this._group._removeThrottle(this),this._destroyed=!0,this._emitter.emit("destroyed"),super.destroy(...e)}};const o=n(9929)},5324:e=>{e.exports={wait:function(e){return new Promise((t=>setTimeout(t,e)))}}},1237:(e,t,n)=>{const{EventEmitter:i}=n(7187),r=new Error("Stream was destroyed"),s=new Error("Premature close"),o=n(3527),a=n(1607),h=67108863,c=1^h,l=16,u=128,d=256,f=1024,p=2048,g=4096,m=8192,_=16384,y=32784,w=768^h,b=1<<17,v=2<<17,k=4<<17,x=8<<17,E=16<<17,S=32<<17,C=64<<17,A=129<<17,T=256<<17,P=66977791,I=66846719,R=131088,L=66977775,O=4210688,B=14,U=15,N=4210702,M=16941072,j=16809999,H=1179648,D=1179663,F=Symbol.asyncIterator||Symbol("asyncIterator");class q{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:i,byteLength:r,byteLengthWritable:s}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=s||r||ce,this.map=i||n,this.afterWrite=Z.bind(this),this.afterUpdateNextTick=X.bind(this)}get ended(){return 0!=(this.stream._duplexState&S)}push(e){return null!==this.map&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=x,!0):(this.stream._duplexState|=3145728,!1)}shift(){const e=this.queue.shift(),t=this.stream;return this.buffered-=this.byteLength(e),0===this.buffered&&(t._duplexState&=66060287),e}end(e){"function"==typeof e?this.stream.once("finish",e):null!=e&&this.push(e),this.stream._duplexState=(this.stream._duplexState|T)&I}autoBatch(e,t){const n=[],i=this.stream;for(n.push(e);(i._duplexState&D)===H;)n.push(i._writableState.shift());if(0!=(i._duplexState&U))return t(null);i._writev(n,t)}update(){const e=this.stream;for(;(e._duplexState&D)===x;){const t=this.shift();e._duplexState|=655360,e._write(t,this.afterWrite),e._duplexState&=66584575}0==(393216&e._duplexState)&&this.updateNonPrimary()}updateNonPrimary(){const e=this.stream;if((38928399&e._duplexState)===T)return e._duplexState=33554431&(e._duplexState|b),void e._final(V.bind(this));4!=(e._duplexState&B)?1==(e._duplexState&j)&&(e._duplexState=(e._duplexState|R)&c,e._open(Q.bind(this))):0==(e._duplexState&M)&&(e._duplexState|=R,e._destroy(K.bind(this)))}updateNextTick(){0==(this.stream._duplexState&A)&&(this.stream._duplexState|=A,o(this.afterUpdateNextTick))}}class ${constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:i,byteLength:r,byteLengthReadable:s}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.byteLength=s||r||ce,this.map=i||n,this.pipeTo=null,this.afterRead=Y.bind(this),this.afterUpdateNextTick=J.bind(this)}get ended(){return 0!=(this.stream._duplexState&_)}pipe(e,t){if(null!==this.pipeTo)throw new Error("Can only pipe to one destination");if("function"!=typeof t&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new z(this.stream,e,t),t&&this.stream.on("error",le),he(e))e._writableState.pipeline=this.pipeline,t&&e.on("error",le),e.on("finish",this.pipeline.finished.bind(this.pipeline));else{const t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on("error",t),e.on("close",n),e.on("finish",this.pipeline.finished.bind(this.pipeline))}e.on("drain",G.bind(this)),this.stream.emit("piping",e),e.emit("pipe",this.stream)}push(e){const t=this.stream;return null===e?(this.highWaterMark=0,t._duplexState=67043295&(t._duplexState|f),!1):(null!==this.map&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=67043327&(t._duplexState|u),this.buffered<this.highWaterMark)}shift(){const e=this.queue.shift();return this.buffered-=this.byteLength(e),0===this.buffered&&(this.stream._duplexState&=67100543),e}unshift(e){let t;const n=[];for(;void 0!==(t=this.queue.shift());)n.push(t);this.push(e);for(let e=0;e<n.length;e++)this.queue.push(n[e])}read(){const e=this.stream;if((16527&e._duplexState)===u){const t=this.shift();return null!==this.pipeTo&&!1===this.pipeTo.write(t)&&(e._duplexState&=w),0!=(e._duplexState&p)&&e.emit("data",t),t}return null}drain(){const e=this.stream;for(;(16527&e._duplexState)===u&&0!=(768&e._duplexState);){const t=this.shift();null!==this.pipeTo&&!1===this.pipeTo.write(t)&&(e._duplexState&=w),0!=(e._duplexState&p)&&e.emit("data",t)}}update(){const e=this.stream;for(this.drain();this.buffered<this.highWaterMark&&0==(82975&e._duplexState);)e._duplexState|=65616,e._read(this.afterRead),e._duplexState&=67108799,0==(e._duplexState&l)&&this.drain();4224==(12431&e._duplexState)&&(e._duplexState|=m,e.emit("readable")),0==(48&e._duplexState)&&this.updateNonPrimary()}updateNonPrimary(){const e=this.stream;(1167&e._duplexState)===f&&(e._duplexState=67107839&(e._duplexState|_),e.emit("end"),(e._duplexState&N)===O&&(e._duplexState|=4),null!==this.pipeTo&&this.pipeTo.end()),4!=(e._duplexState&B)?1==(e._duplexState&j)&&(e._duplexState=(e._duplexState|R)&c,e._open(Q.bind(this))):0==(e._duplexState&M)&&(e._duplexState|=R,e._destroy(K.bind(this)))}updateNextTick(){0==(this.stream._duplexState&y)&&(this.stream._duplexState|=y,o(this.afterUpdateNextTick))}}class W{constructor(e){this.data=null,this.afterTransform=ee.bind(e),this.afterFinal=null}}class z{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){t&&(this.error=t),e!==this.to||(this.to=null,null===this.from)?e!==this.from||(this.from=null,null===this.to)?(null!==this.afterPipe&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null):0==(e._duplexState&_)&&this.to.destroy(this.error||new Error("Readable stream closed before ending")):0!=(this.from._duplexState&_)&&this.pipeToFinished||this.from.destroy(this.error||new Error("Writable stream closed prematurely"))}}function G(){this.stream._duplexState|=512,0==(80&this.stream._duplexState)?this.updateNextTick():this.drain()}function V(e){const t=this.stream;e&&t.destroy(e),0==(t._duplexState&B)&&(t._duplexState|=S,t.emit("finish")),(t._duplexState&N)===O&&(t._duplexState|=4),t._duplexState&=P,this.update()}function K(e){const t=this.stream;e||this.error===r||(e=this.error),e&&t.emit("error",e),t._duplexState|=8,t.emit("close");const n=t._readableState,i=t._writableState;null!==n&&null!==n.pipeline&&n.pipeline.done(t,e),null!==i&&null!==i.pipeline&&i.pipeline.done(t,e)}function Z(e){const t=this.stream;e&&t.destroy(e),t._duplexState&=P,(3276815&t._duplexState)===E&&(t._duplexState&=65011711,(t._duplexState&C)===C&&t.emit("drain")),0==(t._duplexState&k)&&this.update()}function Y(e){e&&this.stream.destroy(e),this.stream._duplexState&=67108847,0==(64&this.stream._duplexState)&&this.update()}function J(){this.stream._duplexState&=67076079,this.update()}function X(){this.stream._duplexState&=50200575,this.update()}function Q(e){const t=this.stream;e&&t.destroy(e),0==(4&t._duplexState)&&(0==(17423&t._duplexState)&&(t._duplexState|=32),0==(37748751&t._duplexState)&&(t._duplexState|=v),t.emit("open")),t._duplexState&=L,null!==t._writableState&&t._writableState.update(),null!==t._readableState&&t._readableState.update()}function ee(e,t){null!=t&&this.push(t),this._writableState.afterWrite(e)}class te extends i{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener("abort",ue.bind(this)))}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return null!==this._readableState||void 0}get writable(){return null!==this._writableState||void 0}get destroyed(){return 0!=(8&this._duplexState)}get destroying(){return 0!=(this._duplexState&B)}destroy(e){0==(this._duplexState&B)&&(e||(e=r),this._duplexState=66846687&(4|this._duplexState),null!==this._readableState&&(this._readableState.error=e),null!==this._writableState&&(this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=67108861,null!==this._readableState&&this._readableState.updateNextTick(),null!==this._writableState&&this._writableState.updateNextTick())}on(e,t){return null!==this._readableState&&("data"===e&&(this._duplexState|=2304,this._readableState.updateNextTick()),"readable"===e&&(this._duplexState|=g,this._readableState.updateNextTick())),null!==this._writableState&&"drain"===e&&(this._duplexState|=C,this._writableState.updateNextTick()),super.on(e,t)}}class ne extends te{constructor(e){super(e),this._duplexState|=4194305,this._readableState=new $(this,e),e&&(e.read&&(this._read=e.read),e.eagerOpen&&this.resume().pause())}_read(e){e(null)}pipe(e,t){return this._readableState.pipe(e,t),this._readableState.updateNextTick(),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTick(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTick(),this._readableState.unshift(e)}resume(){return this._duplexState|=d,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=67108607,this}static _fromAsyncIterator(e,t){let n;const i=new ne({...t,read(t){e.next().then(r).then(t.bind(null,null)).catch(t)},predestroy(){n=e.return()},destroy(e){if(!n)return e(null);n.then(e.bind(null,null)).catch(e)}});return i;function r(e){e.done?i.push(null):i.push(e.value)}}static from(e,t){if(he(n=e)&&n.readable)return e;var n;if(e[F])return this._fromAsyncIterator(e[F](),t);Array.isArray(e)||(e=void 0===e?[]:[e]);let i=0;return new ne({...t,read(t){this.push(i===e.length?null:e[i++]),t(null)}})}static isBackpressured(e){return 0!=(17422&e._duplexState)||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return 0==(e._duplexState&d)}[F](){const e=this;let t=null,n=null,i=null;return this.on("error",(e=>{t=e})),this.on("readable",(function(){null!==n&&s(e.read())})),this.on("close",(function(){null!==n&&s(null)})),{[F](){return this},next:()=>new Promise((function(t,r){n=t,i=r;const o=e.read();null!==o?s(o):0!=(8&e._duplexState)&&s(null)})),return:()=>o(null),throw:e=>o(e)};function s(s){null!==i&&(t?i(t):null===s&&0==(e._duplexState&_)?i(r):n({value:s,done:null===s}),i=n=null)}function o(t){return e.destroy(t),new Promise(((n,i)=>{if(8&e._duplexState)return n({value:void 0,done:!0});e.once("close",(function(){t?i(t):n({value:void 0,done:!0})}))}))}}}class ie extends ne{constructor(e){super(e),this._duplexState=1,this._writableState=new q(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}}class re extends ie{constructor(e){super(e),this._transformState=new W(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(null!==this._transformState.data){const t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(se.bind(this))}}function se(e,t){const n=this._transformState.afterFinal;if(e)return n(e);null!=t&&this.push(t),this.push(null),n(null)}function oe(e,...t){const n=Array.isArray(e)?[...e,...t]:[e,...t],i=n.length&&"function"==typeof n[n.length-1]?n.pop():null;if(n.length<2)throw new Error("Pipeline requires at least 2 streams");let r=n[0],o=null,a=null;for(let e=1;e<n.length;e++)o=n[e],he(r)?r.pipe(o,c):(h(r,!0,e>1,c),r.pipe(o)),r=o;if(i){let e=!1;o.on("finish",(()=>{e=!0})),o.on("error",(e=>{a=a||e})),o.on("close",(()=>i(a||(e?null:s))))}return o;function h(e,t,n,i){e.on("error",i),e.on("close",(function(){if(t&&e._readableState&&!e._readableState.ended)return i(s);if(n&&e._writableState&&!e._writableState.ended)return i(s)}))}function c(e){if(e&&!a){a=e;for(const t of n)t.destroy(e)}}}function ae(e){return!!e._readableState||!!e._writableState}function he(e){return"number"==typeof e._duplexState&&ae(e)}function ce(e){return function(e){return"object"==typeof e&&null!==e&&"number"==typeof e.byteLength}(e)?e.byteLength:1024}function le(){}function ue(){this.destroy(new Error("Stream aborted."))}e.exports={pipeline:oe,pipelinePromise:function(...e){return new Promise(((t,n)=>oe(...e,(e=>{if(e)return n(e);t()}))))},isStream:ae,isStreamx:he,getStreamError:function(e){return e._readableState&&e._readableState.error||e._writableState&&e._writableState.error},Stream:te,Writable:class extends te{constructor(e){super(e),this._duplexState|=16385,this._writableState=new q(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return 0!=(39845902&e._duplexState)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Readable:ne,Duplex:ie,Transform:re,PassThrough:class extends re{}}},5017:(e,t,n)=>{var i=n(883);t.encode=i.encode,t.decode=i.decode},883:(e,t,n)=>{var i=n(8764).lW,r=[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];t.encode=function(e){i.isBuffer(e)||(e=new i(e));for(var t,n,r=0,s=0,o=0,a=0,h=new i(8*(t=e,n=Math.floor(t.length/5),t.length%5==0?n:n+1));r<e.length;){var c=e[r];o>3?(a=(a=c&255>>o)<<(o=(o+5)%8)|(r+1<e.length?e[r+1]:0)>>8-o,r++):(a=c>>8-(o+5)&31,0===(o=(o+5)%8)&&r++),h[s]="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".charCodeAt(a),s++}for(r=s;r<h.length;r++)h[r]=61;return h},t.decode=function(e){var t,n=0,s=0,o=0;i.isBuffer(e)||(e=new i(e));for(var a=new i(Math.ceil(5*e.length/8)),h=0;h<e.length&&61!==e[h];h++){var c=e[h]-48;if(!(c<r.length))throw new Error("Invalid input - it is not base32 encoded string");s=r[c],n<=3?0===(n=(n+5)%8)?(t|=s,a[o]=t,o++,t=0):t|=255&s<<8-n:(t|=255&s>>>(n=(n+5)%8),a[o]=t,o++,t=255&s<<8-n)}return a.slice(0,o)}},1463:e=>{function t(e){return(+Date.now()-e)/100&65535}e.exports=function(e){const n=+Date.now(),i=10*(e||5),r=[0];let s=1,o=t(n)-1&65535;return function(e){const a=t(n);let h=a-o&65535;for(h>i&&(h=i),o=a;h--;)s===i&&(s=0),r[s]=r[0===s?i-1:s-1],s++;e&&(r[s-1]+=e);const c=r[s-1],l=r.length<i?0:r[s===i?0:s];return r.length<10?c:10*(c-l)/r.length}}},8687:(e,t,n)=>{var i=n(8764).lW;const r=16384;class s{constructor(e){this.length=e,this.missing=e,this.sources=null,this._chunks=Math.ceil(e/r),this._remainder=e%r||r,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,this._flushed=!1}chunkLength(e){return e===this._chunks-1?this._remainder:r}chunkLengthRemaining(e){return this.length-e*r}chunkOffset(e){return e*r}reserve(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservations<this._chunks?this._reservations++:-1:-1}reserveRemaining(){if(!this.init())return-1;if(this._cancellations.length||this._reservations<this._chunks){let e=this._reservations;for(;this._cancellations.length;)e=Math.min(e,this._cancellations.pop());return this._reservations=this._chunks,e}return-1}cancel(e){this.init()&&this._cancellations.push(e)}cancelRemaining(e){this.init()&&(this._reservations=e)}get(e){return this.init()?this._buffer[e]:null}set(e,t,n){if(!this.init())return!1;const i=t.length,s=Math.ceil(i/r);for(let i=0;i<s;i++)if(!this._buffer[e+i]){const s=i*r,o=t.slice(s,s+r);this._buffered++,this._buffer[e+i]=o,this.missing-=o.length,this.sources.includes(n)||this.sources.push(n)}return this._buffered===this._chunks}flush(){if(!this._buffer||this._chunks!==this._buffered)return null;const e=i.concat(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,e}init(){return!this._flushed&&(this._buffer||(this._buffer=new Array(this._chunks),this._cancellations=[],this.sources=[]),!0)}}Object.defineProperty(s,"BLOCK_LENGTH",{value:r}),e.exports=s},6581:e=>{e.exports=function(e,t){if(t>=e.length||t<0)return;var n=e.pop();if(t<e.length){var i=e[t];return e[t]=n,i}return n}},2479:e=>{e.exports=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){i[e]=t[e]})),i;function i(){for(var e=new Array(arguments.length),n=0;n<e.length;n++)e[n]=arguments[n];var i=t.apply(this,e),r=e[e.length-1];return"function"==typeof i&&i!==r&&Object.keys(r).forEach((function(e){i[e]=r[e]})),i}}},6475:()=>{},2203:()=>{},3423:()=>{},1494:()=>{},5381:()=>{},8838:()=>{},9356:()=>{},5517:()=>{},9354:()=>{},8411:()=>{},1857:()=>{},159:()=>{},859:()=>{},2911:()=>{},970:()=>{},1982:()=>{},1156:()=>{},1018:()=>{},2067:()=>{},8302:()=>{},3552:()=>{},5843:()=>{},3287:(e,t,n)=>{n.r(t),n.d(t,{default:()=>m,enableSecure:()=>g});var i=n(7187),r=n(1237),s=n(6581),o=n(1227),a=n(814);const h="tcpIncoming",c="tcpOutgoing",l="utpIncoming",u="utpOutgoing",d="webSeed",f=o("webtorrent:peer");let p=!1;const g=()=>{p=!0};class m extends i{constructor(e,t){super(),this.id=e,this.type=t,f("new %s Peer %s",t,e),this.addr=null,this.conn=null,this.swarm=null,this.wire=null,this.source=null,this.connected=!1,this.destroyed=!1,this.timeout=null,this.retries=0,this.sentPe1=!1,this.sentPe2=!1,this.sentPe3=!1,this.sentPe4=!1,this.sentHandshake=!1}onConnect(){if(this.destroyed)return;this.connected=!0,f("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 a.Z(this.type,this.retries,p);t.once("end",(()=>{this.destroy()})),t.once("close",(()=>{this.destroy()})),t.once("finish",(()=>{this.destroy()})),t.once("error",(e=>{this.destroy(e)})),t.once("pe1",(()=>{this.onPe1()})),t.once("pe2",(()=>{this.onPe2()})),t.once("pe3",(()=>{this.onPe3()})),t.once("pe4",(()=>{this.onPe4()})),t.once("handshake",((e,t)=>{this.onHandshake(e,t)})),this.startHandshakeTimeout(),this.setThrottlePipes(),this.swarm&&("tcpOutgoing"===this.type?p&&0===this.retries&&!this.sentPe1?this.sendPe1():this.sentHandshake||this.handshake():"tcpIncoming"===this.type||this.sentHandshake||this.handshake())}sendPe1(){this.wire.sendPe1(),this.sentPe1=!0}onPe1(){this.sendPe2()}sendPe2(){this.wire.sendPe2(),this.sentPe2=!0}onPe2(){this.sendPe3()}sendPe3(){this.wire.sendPe3(this.swarm.infoHash),this.sentPe3=!0}onPe3(e){this.swarm&&(this.swarm.infoHashHash!==e&&this.destroy(new Error("unexpected crypto handshake info hash for this swarm")),this.sendPe4())}sendPe4(){this.wire.sendPe4(this.swarm.infoHash),this.sentPe4=!0}onPe4(){this.sentHandshake||this.handshake()}clearPipes(){this.conn.unpipe(),this.wire.unpipe()}setThrottlePipes(){const e=this;(0,r.pipeline)(this.conn,this.throttleGroups.down.throttle(),new r.Transform({transform(t,n){e.emit("download",t.length),e.destroyed||n(null,t)}}),this.wire,this.throttleGroups.up.throttle(),new r.Transform({transform(t,n){e.emit("upload",t.length),e.destroyed||n(null,t)}}),this.conn)}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"));f("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,fast:!0};this.wire.handshake(this.swarm.infoHash,this.swarm.client.peerId,e),this.sentHandshake=!0}startConnectTimeout(){clearTimeout(this.connectTimeout);const e={webrtc:25e3,tcpOutgoing:5e3,utpOutgoing:5e3};this.connectTimeout=setTimeout((()=>{this.destroy(new Error("connect timeout"))}),e[this.type]),this.connectTimeout.unref&&this.connectTimeout.unref()}startHandshakeTimeout(){clearTimeout(this.handshakeTimeout),this.handshakeTimeout=setTimeout((()=>{this.destroy(new Error("handshake timeout"))}),25e3),this.handshakeTimeout.unref&&this.handshakeTimeout.unref()}destroy(e){if(this.destroyed)return;this.destroyed=!0,this.connected=!1,f("destroy %s %s (error: %s)",this.type,this.id,e&&(e.message||e)),clearTimeout(this.connectTimeout),clearTimeout(this.handshakeTimeout);const t=this.swarm,n=this.conn,i=this.wire;this.swarm=null,this.conn=null,this.wire=null,t&&i&&s(t.wires,t.wires.indexOf(i)),n&&(n.on("error",(()=>{})),n.destroy()),i&&i.destroy(),t&&t.removePeer(this.id)}}m.TYPE_TCP_INCOMING=h,m.TYPE_TCP_OUTGOING=c,m.TYPE_UTP_INCOMING=l,m.TYPE_UTP_OUTGOING=u,m.TYPE_WEBRTC="webrtc",m.TYPE_WEBSEED=d,m.SOURCE_MANUAL="manual",m.SOURCE_TRACKER="tracker",m.SOURCE_DHT="dht",m.SOURCE_LSD="lsd",m.SOURCE_UT_PEX="ut_pex",m.createWebRTCPeer=(e,t,n)=>{const i=new m(e.id,"webrtc");if(i.conn=e,i.swarm=t,i.throttleGroups=n,i.conn.connected)i.onConnect();else{const e=()=>{i.conn.removeListener("connect",t),i.conn.removeListener("error",n)},t=()=>{e(),i.onConnect()},n=t=>{e(),i.destroy(t)};i.conn.once("connect",t),i.conn.once("error",n),i.startConnectTimeout()}return i},m.createTCPIncomingPeer=(e,t)=>m._createIncomingPeer(e,h,t),m.createUTPIncomingPeer=(e,t)=>m._createIncomingPeer(e,l,t),m.createTCPOutgoingPeer=(e,t,n)=>m._createOutgoingPeer(e,t,c,n),m.createUTPOutgoingPeer=(e,t,n)=>m._createOutgoingPeer(e,t,u,n),m._createIncomingPeer=(e,t,n)=>{const i=`${e.remoteAddress}:${e.remotePort}`,r=new m(i,t);return r.conn=e,r.addr=i,r.throttleGroups=n,r.onConnect(),r},m._createOutgoingPeer=(e,t,n,i)=>{const r=new m(e,n);return r.addr=e,r.swarm=t,r.throttleGroups=i,r},m.createWebSeedPeer=(e,t,n,i)=>{const r=new m(t,d);return r.swarm=n,r.conn=e,r.throttleGroups=i,r.onConnect(),r}},502:(e,t,n)=>{n.d(t,{Z:()=>p});var i=n(5194);function r(e){const t=e<0?1:0;return e=Math.abs(Number(e||1)),Math.floor(Math.log10(e))+1+t}function s(e){return ArrayBuffer.isView(e)?"arraybufferview":Array.isArray(e)?"array":e instanceof Number?"number":e instanceof Boolean?"boolean":e instanceof Set?"set":e instanceof Map?"map":e instanceof String?"string":e instanceof ArrayBuffer?"arraybuffer":typeof e}function o(e,t,n){const r=[];let s=null;return o._encode(r,e),s=(0,i.zo)(r),o.bytes=s.length,ArrayBuffer.isView(t)?(t.set(s,n),t):s}o.bytes=-1,o._floatConversionDetected=!1,o._encode=function(e,t){if(null!=t)switch(s(t)){case"object":o.dict(e,t);break;case"map":o.dictMap(e,t);break;case"array":o.list(e,t);break;case"set":o.listSet(e,t);break;case"string":o.string(e,t);break;case"number":case"boolean":o.number(e,t);break;case"arraybufferview":o.buffer(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));break;case"arraybuffer":o.buffer(e,new Uint8Array(t))}};const a=new Uint8Array([101]),h=new Uint8Array([100]),c=new Uint8Array([108]);o.buffer=function(e,t){e.push((0,i.gR)(t.length+":"),t)},o.string=function(e,t){e.push((0,i.gR)((0,i.gR)(t).byteLength+":"+t))},o.number=function(e,t){const n=2147483648,r=(t/n<<0)*n+(t%n<<0);e.push((0,i.gR)("i"+r+"e")),r===t||o._floatConversionDetected||(o._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+t+'":','Bencoding only defines support for integers, value was converted to "'+r+'"'),console.trace())},o.dict=function(e,t){e.push(h);let n,i=0;const r=Object.keys(t).sort(),s=r.length;for(;i<s;i++)n=r[i],null!=t[n]&&(o.string(e,n),o._encode(e,t[n]));e.push(a)},o.dictMap=function(e,t){e.push(h);const n=Array.from(t.keys()).sort();for(const i of n)null!=t.get(i)&&(ArrayBuffer.isView(i)?o._encode(e,i):o.string(e,String(i)),o._encode(e,t.get(i)));e.push(a)},o.list=function(e,t){let n=0;const i=t.length;for(e.push(c);n<i;n++)null!=t[n]&&o._encode(e,t[n]);e.push(a)},o.listSet=function(e,t){e.push(c);for(const n of t)null!=n&&o._encode(e,n);e.push(a)};const l=o;function u(e,t,n){let i=0,r=1;for(let s=t;s<n;s++){const n=e[s];if(n<58&&n>=48)i=10*i+(n-48);else if(s!==t||43!==n){if(s!==t||45!==n){if(46===n)break;throw new Error("not a number: buffer["+s+"] = "+n)}r=-1}}return i*r}function d(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),d.position=0,d.encoding=r||null,d.data=ArrayBuffer.isView(e)?new Uint8Array(e.slice(t,n)):(0,i.gR)(e),d.bytes=d.data.length,d.next())}d.bytes=0,d.position=0,d.data=null,d.encoding=null,d.next=function(){switch(d.data[d.position]){case 100:return d.dictionary();case 108:return d.list();case 105:return d.integer();default:return d.buffer()}},d.find=function(e){let t=d.position;const n=d.data.length,i=d.data;for(;t<n;){if(i[t]===e)return t;t++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(e)+'" [0x'+e.toString(16)+"]")},d.dictionary=function(){d.position++;const e={};for(;101!==d.data[d.position];)e[(0,i.vV)(d.buffer())]=d.next();return d.position++,e},d.list=function(){d.position++;const e=[];for(;101!==d.data[d.position];)e.push(d.next());return d.position++,e},d.integer=function(){const e=d.find(101),t=u(d.data,d.position+1,e);return d.position+=e+1-d.position,t},d.buffer=function(){let e=d.find(58);const t=u(d.data,d.position,e),n=++e+t;return d.position=n,d.encoding?(0,i.vV)(d.data.slice(e,n)):d.data.slice(e,n)};function f(e){if(null==e)return 0;const t=s(e);switch(t){case"arraybufferview":return function(e){const t=e.byteLength-e.byteOffset;return r(t)+1+t}(e);case"string":return function(e){const t=(0,i.gR)(e).byteLength;return r(t)+1+t}(e);case"array":case"set":return function(e){let t=2;for(const n of e)t+=f(n);return t}(e);case"number":return 1+r(Math.floor(e))+1;case"bigint":return 1+e.toString().length+1;case"object":return function(e){let t=2;const n=Object.keys(e);for(let s=0;s<n.length;s++){const o=(0,i.gR)(n[s]).byteLength;t+=r(o)+1+o,t+=f(e[n[s]])}return t}(e);case"map":return function(e){let t=2;for(const[n,s]of e){const e=(0,i.gR)(n).byteLength;t+=r(e)+1+e,t+=f(s)}return t}(e);default:throw new TypeError(`Unsupported value of type "${t}"`)}}const p={encode:l,decode:d,byteLength:f,encodingLength:f}},8205:(e,t,n)=>{function i(e){let t=e>>3;return e%8!=0&&t++,t}n.d(t,{Z:()=>r});class r{constructor(e=0,t){const n=null==t?void 0:t.grow;this.grow=n&&isFinite(n)&&i(n)||n||0,this.buffer="number"==typeof e?new Uint8Array(i(e)):e}get(e){const t=e>>3;return t<this.buffer.length&&!!(this.buffer[t]&128>>e%8)}set(e,t=!0){const n=e>>3;if(t){if(this.buffer.length<n+1){const e=Math.max(n+1,Math.min(2*this.buffer.length,this.grow));if(e<=this.grow){const t=new Uint8Array(e);t.set(this.buffer),this.buffer=t}}this.buffer[n]|=128>>e%8}else n<this.buffer.length&&(this.buffer[n]&=~(128>>e%8))}forEach(e,t=0,n=8*this.buffer.length){for(let i=t,r=i>>3,s=128>>i%8,o=this.buffer[r];i<n;i++)e(!!(o&s),i),s=1===s?(o=this.buffer[++r],128):s>>1}}},814:(e,t,n)=>{n.d(t,{Z:()=>I});var i=n(502),r=n(8205),s=n(5517),o=n(1227),a=n(7830),h=n(1237),c=n(5194),l=n(1463),u=n(6581);const d=o("bittorrent-protocol"),f=(0,c.gR)("BitTorrent protocol"),p=new Uint8Array([0,0,0,0]),g=new Uint8Array([0,0,0,1,0]),m=new Uint8Array([0,0,0,1,1]),_=new Uint8Array([0,0,0,1,2]),y=new Uint8Array([0,0,0,1,3]),w=[0,0,0,0,0,0,0,0],b=[0,0,0,3,9,0,0],v=new Uint8Array([0,0,0,1,14]),k=new Uint8Array([0,0,0,1,15]),x=new Uint8Array([0,0,0,0,0,0,0,0]),E=new Uint8Array([0,0,1,2]),S=new Uint8Array([0,0,0,2]);function C(e,t){for(let n=e.length;n--;)e[n]^=t[n];return e}class A{constructor(e,t,n,i){this.piece=e,this.offset=t,this.length=n,this.callback=i}}class T{constructor(){this.buffer=new Uint8Array}get(e){return!0}set(e){}}class P extends h.Duplex{constructor(e=null,t=0,n=!1){super(),this._debugId=(0,c.oc)((0,c.O6)(4)),this._debug("new wire"),this.peerId=null,this.peerIdBuffer=null,this.type=e,this.amChoking=!0,this.amInterested=!1,this.peerChoking=!0,this.peerInterested=!1,this.peerPieces=new r.Z(0,{grow:4e5}),this.extensions={},this.peerExtensions={},this.requests=[],this.peerRequests=[],this.extendedMapping={},this.peerExtendedMapping={},this.extendedHandshake={},this.peerExtendedHandshake={},this.hasFast=!1,this.allowedFastSet=[],this.peerAllowedFastSet=[],this._ext={},this._nextExt=1,this.uploaded=0,this.downloaded=0,this.uploadSpeed=l(),this.downloadSpeed=l(),this._keepAliveInterval=null,this._timeout=null,this._timeoutMs=0,this._timeoutExpiresAt=null,this._finished=!1,this._parserSize=0,this._parser=null,this._buffer=[],this._bufferSize=0,this._peEnabled=n,n?(this._dh=s.createDiffieHellman("ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a36210000000000090563","hex",2),this._myPubKey=this._dh.generateKeys("hex")):this._myPubKey=null,this._peerPubKey=null,this._sharedSecret=null,this._peerCryptoProvide=[],this._cryptoHandshakeDone=!1,this._cryptoSyncPattern=null,this._waitMaxBytes=null,this._encryptionMethod=null,this._encryptGenerator=null,this._decryptGenerator=null,this._setGenerators=!1,this.once("finish",(()=>this._onFinish())),this.on("finish",this._onFinish),this._debug("type:",this.type),"tcpIncoming"===this.type&&this._peEnabled?this._determineHandshakeType():"tcpOutgoing"===this.type&&this._peEnabled&&0===t?this._parsePe2():this._parseHandshake(null)}setKeepAlive(e){this._debug("setKeepAlive %s",e),clearInterval(this._keepAliveInterval),!1!==e&&(this._keepAliveInterval=setInterval((()=>{this.keepAlive()}),55e3))}setTimeout(e,t){this._debug("setTimeout ms=%d unref=%s",e,t),this._timeoutMs=e,this._timeoutUnref=!!t,this._resetTimeout(!0)}destroy(){if(!this.destroyed)return this._debug("destroy"),this.end(),this}end(e){if(!this.destroyed&&!this.destroying)return 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,i=new e(this);function r(){}"function"!=typeof i.onHandshake&&(i.onHandshake=r),"function"!=typeof i.onExtendedHandshake&&(i.onExtendedHandshake=r),"function"!=typeof i.onMessage&&(i.onMessage=r),this.extendedMapping[n]=t,this._ext[t]=i,this[t]=i,this._nextExt+=1}keepAlive(){this._debug("keep-alive"),this._push(p)}sendPe1(){if(this._peEnabled){const e=Math.floor(513*Math.random()),t=(0,c.O6)(e);this._push((0,c.zo)([(0,c._0)(this._myPubKey),t]))}}sendPe2(){const e=Math.floor(513*Math.random()),t=(0,c.O6)(e);this._push((0,c.zo)([(0,c._0)(this._myPubKey),t]))}async sendPe3(e){await this.setEncrypt(this._sharedSecret,e);const t=await(0,c.vp)((0,c._0)(this._utfToHex("req1")+this._sharedSecret)),n=C(await(0,c.vp)((0,c._0)(this._utfToHex("req2")+e)),await(0,c.vp)((0,c._0)(this._utfToHex("req3")+this._sharedSecret))),i=new DataView((0,c.O6)(2).buffer).getUint16(0)%512,r=(0,c.O6)(i);let s=new Uint8Array(14+i+2);s.set(x),s.set(E,8);const o=new DataView(s.buffer);o.setInt16(12,i),r.copy(s,14),o.setInt16(14+i,0),s=this._encryptHandshake(s),this._push((0,c.zo)([t,n,s]))}async sendPe4(e){await this.setEncrypt(this._sharedSecret,e);const t=new DataView((0,c.O6)(2).buffer).getUint16(0)%512,n=(0,c.O6)(t);let i=new Uint8Array(14+t);const r=new DataView(i.buffer);i.set(x),i.set(S,8),r.setInt16(12,t),i.set(n,14),i=this._encryptHandshake(i),this._push(i),this._cryptoHandshakeDone=!0,this._debug("completed crypto handshake")}handshake(e,t,n){let i,r;if("string"==typeof e?(e=e.toLowerCase(),i=(0,c._0)(e)):(i=e,e=(0,c.oc)(i)),"string"==typeof t?r=(0,c._0)(t):(r=t,t=(0,c.oc)(r)),this._infoHash=i,20!==i.length||20!==r.length)throw new Error("infoHash and peerId MUST have length 20");this._debug("handshake i=%s p=%s exts=%o",e,t,n);const s=new Uint8Array(w);this.extensions={extended:!0,dht:!(!n||!n.dht),fast:!(!n||!n.fast)},s[5]|=16,this.extensions.dht&&(s[7]|=1),this.extensions.fast&&(s[7]|=4),this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this._push((0,c.zo)([f,s,i,r])),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,i.Z.encode(e)),this._extendedHandshakeSent=!0}choke(){if(!this.amChoking)if(this.amChoking=!0,this._debug("choke"),this._push(g),this.hasFast){let e=0;for(;this.peerRequests.length>e;){const t=this.peerRequests[e];this.allowedFastSet.includes(t.piece)?++e:this.reject(t.piece,t.offset,t.length)}}else for(;this.peerRequests.length;)this.peerRequests.pop()}unchoke(){this.amChoking&&(this.amChoking=!1,this._debug("unchoke"),this._push(m))}interested(){this.amInterested||(this.amInterested=!0,this._debug("interested"),this._push(_))}uninterested(){this.amInterested&&(this.amInterested=!1,this._debug("uninterested"),this._push(y))}have(e){this._debug("have %d",e),this._message(4,[e],null)}bitfield(e){this._debug("bitfield"),ArrayBuffer.isView(e)||(e=e.buffer),this._message(5,[],e)}request(e,t,n,i){return i||(i=()=>{}),this._finished?i(new Error("wire is closed")):!this.peerChoking||this.hasFast&&this.peerAllowedFastSet.includes(e)?(this._debug("request index=%d offset=%d length=%d",e,t,n),this.requests.push(new A(e,t,n,i)),this._timeout||this._resetTimeout(!0),void this._message(6,[e,t,n],null)):i(new Error("peer is choking"))}piece(e,t,n){this._debug("piece index=%d offset=%d",e,t),this._message(7,[e,t],n),this.uploaded+=n.length,this.uploadSpeed(n.length),this.emit("upload",n.length)}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(e){this._debug("port %d",e);const t=new Uint8Array(b);new DataView(t.buffer).setUint16(5,e),this._push(t)}suggest(e){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("suggest %d",e),this._message(13,[e],null)}haveAll(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-all"),this._push(v)}haveNone(){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("have-none"),this._push(k)}reject(e,t,n){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("reject index=%d offset=%d length=%d",e,t,n),this._pull(this.peerRequests,e,t,n),this._message(16,[e,t,n],null)}allowedFast(e){if(!this.hasFast)throw Error("fast extension is disabled");this._debug("allowed-fast %d",e),this.allowedFastSet.includes(e)||this.allowedFastSet.push(e),this._message(17,[e],null)}extended(e,t){if(this._debug("extended ext=%s",e),"string"==typeof e&&this.peerExtendedMapping[e]&&(e=this.peerExtendedMapping[e]),"number"!=typeof e)throw new Error(`Unrecognized extension: ${e}`);{const n=new Uint8Array([e]),r=ArrayBuffer.isView(t)?t:i.Z.encode(t);this._message(20,[],(0,c.zo)([n,r]))}}async setEncrypt(e,t){let n,i,r,s;switch(this.type){case"tcpIncoming":n=await(0,c.vp)((0,c._0)(this._utfToHex("keyB")+e+t)),r=await(0,c.vp)((0,c._0)(this._utfToHex("keyA")+e+t)),i=[];for(const e of n.values())i.push(e);s=[];for(const e of r.values())s.push(e);this._encryptGenerator=new a(i),this._decryptGenerator=new a(s);break;case"tcpOutgoing":n=await(0,c.vp)((0,c._0)(this._utfToHex("keyA")+e+t)),r=await(0,c.vp)((0,c._0)(this._utfToHex("keyB")+e+t)),i=[];for(const e of n.values())i.push(e);s=[];for(const e of r.values())s.push(e);this._encryptGenerator=new a(i),this._decryptGenerator=new a(s);break;default:return!1}for(let e=0;e<1024;e++)this._encryptGenerator.randomByte(),this._decryptGenerator.randomByte();return this._setGenerators=!0,!0}_message(e,t,n){const i=n?n.length:0,r=new Uint8Array(5+4*t.length),s=new DataView(r.buffer);s.setUint32(0,r.length+i-4),r[4]=e;for(let e=0;e<t.length;e++)s.setUint32(5+4*e,t[e]);this._push(r),n&&this._push(n)}_push(e){if(!this._finished)return 2===this._encryptionMethod&&this._cryptoHandshakeDone&&(e=this._encrypt(e)),this.push(e)}_onKeepAlive(){this._debug("got keep-alive"),this.emit("keep-alive")}_onPe1(e){this._peerPubKey=(0,c.oc)(e),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe1")}_onPe2(e){this._peerPubKey=(0,c.oc)(e),this._sharedSecret=this._dh.computeSecret(this._peerPubKey,"hex","hex"),this.emit("pe2")}async _onPe3(e){const t=await(0,c.oc)(this._utfToHex("req3")+this._sharedSecret),n=(0,c.oc)(C(t,e));this.emit("pe3",n)}_onPe3Encrypted(e,t){if(!(0,c.Dg)(e,x))return this._debug("Error: verification constant did not match"),void this.destroy();for(const e of t.values())0!==e&&this._peerCryptoProvide.push(e);this._peerCryptoProvide.includes(2)?this._encryptionMethod=2:(this._debug("Error: RC4 encryption method not provided by peer"),this.destroy())}_onPe4(e){this._encryptionMethod=e[3],E.includes(this._encryptionMethod)||(this._debug("Error: peer selected invalid crypto method"),this.destroy()),this._cryptoHandshakeDone=!0,this._debug("crypto handshake done"),this.emit("pe4")}_onHandshake(e,t,n){const i=(0,c.oc)(e),r=(0,c.oc)(t);this._debug("got handshake i=%s p=%s exts=%o",i,r,n),this.peerId=r,this.peerIdBuffer=t,this.peerExtensions=n,this.extensions.fast&&this.peerExtensions.fast&&(this._debug("fast extension is enabled"),this.hasFast=!0),this.emit("handshake",i,r,n);for(const e in this._ext)this._ext[e].onHandshake(i,r,n);n.extended&&this._handshakeSent&&!this._extendedHandshakeSent&&this._sendExtendedHandshake()}_onChoke(){if(this.peerChoking=!0,this._debug("got choke"),this.emit("choke"),!this.hasFast)for(;this.requests.length;)this._callback(this.requests.pop(),new Error("peer is choking"),null)}_onUnchoke(){this.peerChoking=!1,this._debug("got unchoke"),this.emit("unchoke")}_onInterested(){this.peerInterested=!0,this._debug("got interested"),this.emit("interested")}_onUninterested(){this.peerInterested=!1,this._debug("got uninterested"),this.emit("uninterested")}_onHave(e){this.peerPieces.get(e)||(this._debug("got have %d",e),this.peerPieces.set(e,!0),this.emit("have",e))}_onBitField(e){this.peerPieces=new r.Z(e),this._debug("got bitfield"),this.emit("bitfield",this.peerPieces)}_onRequest(e,t,n){if(this.amChoking&&(!this.hasFast||!this.allowedFastSet.includes(e)))return void(this.hasFast&&this.reject(e,t,n));this._debug("got request index=%d offset=%d length=%d",e,t,n);const i=(i,s)=>{if(r===this._pull(this.peerRequests,e,t,n))return i?(this._debug("error satisfying request index=%d offset=%d length=%d (%s)",e,t,n,i.message),void(this.hasFast&&this.reject(e,t,n))):void this.piece(e,t,s)},r=new A(e,t,n,i);this.peerRequests.push(r),this.emit("request",e,t,n,i)}_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)}_onSuggest(e){if(!this.hasFast)return this._debug("Error: got suggest whereas fast extension is disabled"),void this.destroy();this._debug("got suggest %d",e),this.emit("suggest",e)}_onHaveAll(){if(!this.hasFast)return this._debug("Error: got have-all whereas fast extension is disabled"),void this.destroy();this._debug("got have-all"),this.peerPieces=new T,this.emit("have-all")}_onHaveNone(){if(!this.hasFast)return this._debug("Error: got have-none whereas fast extension is disabled"),void this.destroy();this._debug("got have-none"),this.emit("have-none")}_onReject(e,t,n){if(!this.hasFast)return this._debug("Error: got reject whereas fast extension is disabled"),void this.destroy();this._debug("got reject index=%d offset=%d length=%d",e,t,n),this._callback(this._pull(this.requests,e,t,n),new Error("request was rejected"),null),this.emit("reject",e,t,n)}_onAllowedFast(e){if(!this.hasFast)return this._debug("Error: got allowed-fast whereas fast extension is disabled"),void this.destroy();this._debug("got allowed-fast %d",e),this.peerAllowedFastSet.includes(e)||this.peerAllowedFastSet.push(e),this.peerAllowedFastSet.length>100&&this.peerAllowedFastSet.shift(),this.emit("allowed-fast",e)}_onExtended(e,t){if(0===e){let e;try{e=i.Z.decode(t)}catch(e){this._debug("ignoring invalid extended handshake: %s",e.message||e)}if(!e)return;if(this.peerExtendedHandshake=e,"object"==typeof e.m)for(const t in e.m)this.peerExtendedMapping[t]=Number(e.m[t].toString());for(const e in this._ext)this.peerExtendedMapping[e]&&this._ext[e].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(e,t){if(2===this._encryptionMethod&&this._cryptoHandshakeDone&&(e=this._decrypt(e)),this._bufferSize+=e.length,this._buffer.push(e),this._buffer.length>1&&(this._buffer=[(0,c.zo)(this._buffer,this._bufferSize)]),this._cryptoSyncPattern){const t=this._buffer[0].indexOf(this._cryptoSyncPattern);if(-1!==t)this._buffer[0]=this._buffer[0].slice(t+this._cryptoSyncPattern.length),this._bufferSize-=t+this._cryptoSyncPattern.length,this._cryptoSyncPattern=null;else if(this._bufferSize+e.length>this._waitMaxBytes+this._cryptoSyncPattern.length)return this._debug("Error: could not resynchronize"),void this.destroy()}for(;this._bufferSize>=this._parserSize&&!this._cryptoSyncPattern;)if(0===this._parserSize)this._parser(new Uint8Array);else{const e=this._buffer[0];this._bufferSize-=this._parserSize,this._buffer=this._bufferSize?[e.slice(this._parserSize)]:[],this._parser(e.slice(0,this._parserSize))}t(null)}_callback(e,t,n){e&&(this._resetTimeout(!this.peerChoking&&!this._finished),e.callback(t,n))}_resetTimeout(e){if(!e||!this._timeoutMs||!this.requests.length)return clearTimeout(this._timeout),this._timeout=null,void(this._timeoutExpiresAt=null);const t=Date.now()+this._timeoutMs;if(this._timeout){if(t-this._timeoutExpiresAt<.05*this._timeoutMs)return;clearTimeout(this._timeout)}this._timeoutExpiresAt=t,this._timeout=setTimeout((()=>this._onTimeout()),this._timeoutMs),this._timeoutUnref&&this._timeout.unref&&this._timeout.unref()}_parse(e,t){this._parserSize=e,this._parser=t}_parseUntil(e,t){this._cryptoSyncPattern=e,this._waitMaxBytes=t}_onMessageLength(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0);t>0?this._parse(t,this._onMessage):(this._onKeepAlive(),this._parse(4,this._onMessageLength))}_onMessage(e){this._parse(4,this._onMessageLength);const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(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(t.getUint32(1));case 5:return this._onBitField(e.slice(1));case 6:return this._onRequest(t.getUint32(1),t.getUint32(5),t.getUint32(9));case 7:return this._onPiece(t.getUint32(1),t.getUint32(5),e.slice(9));case 8:return this._onCancel(t.getUint32(1),t.getUint32(5),t.getUint32(9));case 9:return this._onPort(t.getUint16(1));case 13:return this._onSuggest(t.getUint32(1));case 14:return this._onHaveAll();case 15:return this._onHaveNone();case 16:return this._onReject(t.getUint32(1),t.getUint32(5),t.getUint32(9));case 17:return this._onAllowedFast(t.getUint32(1));case 20:return this._onExtended(e[1],e.slice(2));default:return this._debug("got unknown message"),this.emit("unknownmessage",e)}}_determineHandshakeType(){this._parse(1,(e=>{const t=e[0];19===t?this._parse(t+48,this._onHandshakeBuffer):this._parsePe1(e)}))}_parsePe1(e){this._parse(95,(t=>{this._onPe1((0,c.zo)([e,t])),this._parsePe3()}))}_parsePe2(){this._parse(96,(e=>{for(this._onPe2(e);!this._setGenerators;);this._parsePe4()}))}async _parsePe3(){const e=await(0,c.vp)((0,c._0)(this._utfToHex("req1")+this._sharedSecret));this._parseUntil(e,512),this._parse(20,(e=>{for(this._onPe3(e);!this._setGenerators;);this._parsePe3Encrypted()}))}_parsePe3Encrypted(){this._parse(14,(e=>{const t=this._decryptHandshake(e.slice(0,8)),n=this._decryptHandshake(e.slice(8,12)),i=new DataView(this._decryptHandshake(e.slice(12,14)).buffer).getUint16(0);this._parse(i,(e=>{e=this._decryptHandshake(e),this._parse(2,(i=>{const r=new DataView(this._decryptHandshake(i).buffer).getUint16(0);this._parse(r,(i=>{i=this._decryptHandshake(i),this._onPe3Encrypted(t,n,e,i);const s=r?i[0]:null,o=r?i.slice(1,20):null;19===s&&"BitTorrent protocol"===(0,c.vV)(o)?this._onHandshakeBuffer(i.slice(1)):this._parseHandshake()}))}))}))}))}_parsePe4(){const e=this._decryptHandshake(x);this._parseUntil(e,512),this._parse(6,(e=>{const t=this._decryptHandshake(e.slice(0,4)),n=new DataView(this._decryptHandshake(e.slice(4,6)).buffer).getUint16(0);this._parse(n,(e=>{this._decryptHandshake(e),this._onPe4(t),this._parseHandshake(null)}))}))}_parseHandshake(){this._parse(1,(e=>{const t=e[0];if(19!==t)return this._debug("Error: wire not speaking BitTorrent protocol (%s)",t.toString()),void this.end();this._parse(t+48,this._onHandshakeBuffer)}))}_onHandshakeBuffer(e){const t=e.slice(0,19);if("BitTorrent protocol"!==(0,c.vV)(t))return this._debug("Error: wire not speaking BitTorrent protocol (%s)",(0,c.vV)(t)),void this.end();e=e.slice(19),this._onHandshake(e.slice(8,28),e.slice(28,48),{dht:!!(1&e[7]),fast:!!(4&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]}`,d(...e)}_pull(e,t,n,i){for(let r=0;r<e.length;r++){const s=e[r];if(s.piece===t&&s.offset===n&&s.length===i)return u(e,r),s}return null}_encryptHandshake(e){const t=new Uint8Array(e);if(!this._encryptGenerator)return this._debug("Warning: Encrypting without any generator"),t;for(let n=0;n<e.length;n++){const e=this._encryptGenerator.randomByte();t[n]=t[n]^e}return t}_encrypt(e){const t=new Uint8Array(e);if(!this._encryptGenerator||2!==this._encryptionMethod)return t;for(let n=0;n<e.length;n++){const e=this._encryptGenerator.randomByte();t[n]=t[n]^e}return t}_decryptHandshake(e){const t=new Uint8Array(e);if(!this._decryptGenerator)return this._debug("Warning: Decrypting without any generator"),t;for(let n=0;n<e.length;n++){const e=this._decryptGenerator.randomByte();t[n]=t[n]^e}return t}_decrypt(e){const t=new Uint8Array(e);if(!this._decryptGenerator||2!==this._encryptionMethod)return t;for(let n=0;n<e.length;n++){const e=this._decryptGenerator.randomByte();t[n]=t[n]^e}return t}_utfToHex(e){return(0,c.oc)((0,c.gR)(e))}}const I=P},5194:(e,t,n)=>{n.d(t,{te:()=>_,oc:()=>o,vV:()=>p,Ff:()=>y,zo:()=>h,Dg:()=>c,vp:()=>E,_0:()=>a,E:()=>w,O6:()=>S,gR:()=>m});const i="0123456789abcdef",r=[],s=[];for(let e=0;e<256;e++)r[e]=i[e>>4&15]+i[15&e],e<16&&(e<10?s[48+e]=e:s[87+e]=e);const o=e=>{const t=e.length;let n="",i=0;for(;i<t;)n+=r[e[i++]];return n},a=e=>{const t=e.length>>1,n=t<<1,i=new Uint8Array(t);let r=0,o=0;for(;o<n;)i[r++]=s[e.charCodeAt(o++)]<<4|s[e.charCodeAt(o++)];return i},h=(e,t)=>{if(!t){t=0;let n=e.length||e.byteLength||0;for(;n--;)t+=e[n].length}const n=new Uint8Array(t);let i=0;for(const t of e)n.set(t,i),i+=t.byteLength||t.length;return n},c=(e,t)=>{if(e.byteLength!==t.byteLength)return!1;for(let n=e.length;n>-1;n-=1)if(e[n]!==t[n])return!1;return!0};for(var l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u="undefined"==typeof Uint8Array?[]:new Uint8Array(256),d=0;d<64;d++)u[l.charCodeAt(d)]=d;const f=new TextDecoder,p=(e,t)=>{if(!t)return f.decode(e);return new TextDecoder(t).decode(e)},g=new TextEncoder,m=e=>g.encode(e),_=e=>function(e){var t,n=new Uint8Array(e),i=n.length,r="";for(t=0;t<i;t+=3)r+=l[n[t]>>2],r+=l[(3&n[t])<<4|n[t+1]>>4],r+=l[(15&n[t+1])<<2|n[t+2]>>6],r+=l[63&n[t+2]];return i%3==2?r=r.substring(0,r.length-1)+"=":i%3==1&&(r=r.substring(0,r.length-2)+"=="),r}(e),y=e=>{let t,n="",r=0;const s=e.length;for(;r<s;)t=e.charCodeAt(r++),n+=i[t>>4],n+=i[15&t];return n},w=e=>{const t=new Array(e.length/2);for(let n=0,i=e.length/2;n<i;++n)t[n]=parseInt(e.substr(2*n,2),16);if(t.length<=65536)return String.fromCharCode(...t);let n="",i=0;for(;i<t.length;)n+=String.fromCharCode(...t.slice(i,i+=65536));return n},b="undefined"!=typeof window?window:self,v=b.crypto||b.msCrypto||{},k=v.subtle||v.webkitSubtle,x={hex:o,base64:_},E=async(e,t,n="sha-1")=>{if(!k)throw new Error("no web crypto support");"string"==typeof e&&(e=m(e));const i=new Uint8Array(await k.digest(n,e));return t?x[t](i):i},S=e=>{const t=new Uint8Array(e);return v.getRandomValues(t)}},8768:(e,t,n)=>{n.r(t),n.d(t,{addListener:()=>d,argv:()=>a,binding:()=>E,browser:()=>s,chdir:()=>S,cwd:()=>k,emit:()=>_,env:()=>o,listeners:()=>v,nextTick:()=>b,off:()=>p,on:()=>u,once:()=>f,prependListener:()=>y,prependOnceListener:()=>w,removeAllListeners:()=>m,removeListener:()=>g,title:()=>r,umask:()=>x,version:()=>h,versions:()=>c});var i=n(4375);const r="browser",s=!0,o={},a=[],h="",c={};function l(){}const u=l,d=l,f=l,p=l,g=l,m=l,_=l,y=l,w=l,b=(e,...t)=>i((()=>e(...t))),v=e=>[],k=()=>"/",x=()=>0,E=e=>{throw new Error("process.binding is not supported")},S=e=>{throw new Error("process.chdir is not supported")}}},i={};function r(e){var t=i[e];if(void 0!==t)return t.exports;var s=i[e]={exports:{}};return n[e](s,s.exports,r),s.exports}t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(n,i){if(1&i&&(n=this(n)),8&i)return n;if("object"==typeof n&&n){if(4&i&&n.__esModule)return n;if(16&i&&"function"==typeof n.then)return n}var s=Object.create(null);r.r(s);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&i&&n;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>o[e]=()=>n[e]));return o.default=()=>n,r.d(s,o),s},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};(()=>{r.d(s,{Z:()=>Rt});var e=r(7187),t=r(6470),n=r(502),i=r(2090),o=r(3786),a=r(970),h=r(1351),c=r(8225),l=r(4595),u=r(4375),d=r(5194),f=(r(3811),r(2911));const p=[["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"]];const g=Symbol("itemPath");function m(e,n,i){var r;if(r=e,"undefined"!=typeof FileList&&r instanceof FileList&&(e=Array.from(e)),Array.isArray(e)||(e=[e]),0===e.length)throw new Error("invalid input type");e.forEach((e=>{if(null==e)throw new Error(`invalid input type: ${e}`)})),1!==(e=e.map((e=>w(e)&&"string"==typeof e.path&&"function"==typeof f?e.path:e))).length||"string"==typeof e[0]||e[0].name||(e[0].name=n.name);let s=null;e.forEach(((t,n)=>{if("string"==typeof t)return;let i=t.fullPath||t.name;i||(i=`Unknown File ${n+1}`,t.unknownName=!0),t[g]=i.split("/"),t[g][0]||t[g].shift(),t[g].length<2?s=null:0===n&&e.length>1?s=t[g][0]:t[g][0]!==s&&(s=null)}));(void 0===n.filterJunkFiles||n.filterJunkFiles)&&(e=e.filter((e=>"string"==typeof e||!function(e){const t=e[e.length-1];return"."===t[0]&&h.is(t)}(e[g])))),s&&e.forEach((e=>{const t=(ArrayBuffer.isView(e)||b(e))&&!e[g];"string"==typeof e||t||e[g].shift()})),!n.name&&s&&(n.name=s),n.name||e.some((e=>"string"==typeof e?(n.name=t.basename(e),!0):!e.unknownName&&(n.name=e[g][e[g].length-1],!0))),n.name||(n.name=`Unnamed Torrent ${Date.now()}`);const o=e.reduce(((e,t)=>e+Number("string"==typeof t)),0);let c=1===e.length;if(1===e.length&&"string"==typeof e[0]){if("function"!=typeof f)throw new Error("filesystem paths do not work in the browser");a(e[0],((e,t)=>{if(e)return i(e);c=t,d()}))}else u(d);function d(){l(e.map((e=>t=>{const n={};if(w(e))n.getStream=e.stream(),n.length=e.size;else if(ArrayBuffer.isView(e))n.getStream=[e],n.length=e.length;else{if(!b(e)){if("string"==typeof e){if("function"!=typeof f)throw new Error("filesystem paths do not work in the browser");return void f(e,o>1||c,t)}throw new Error("invalid input type")}n.getStream=async function*(e,t){for await(const n of e)t.length+=n.length,yield n}(e,n),n.length=0}n.path=e[g],t(null,n)})),((e,t)=>{if(e)return i(e);t=t.flat(),i(null,t,c)}))}}const _=5;function y(e,t){return e+t.length}function w(e){return"undefined"!=typeof Blob&&e instanceof Blob}function b(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}const v=function(e,t,r){"function"==typeof t&&([t,r]=[r,t]),m(e,t=t?Object.assign({},t):{},((e,s,a)=>{if(e)return r(e);t.singleFileTorrent=a,function(e,t,r){let s=t.announceList;s||("string"==typeof t.announce?s=[[t.announce]]:Array.isArray(t.announce)&&(s=t.announce.map((e=>[e]))));s||(s=[]);globalThis.WEBTORRENT_ANNOUNCE&&("string"==typeof globalThis.WEBTORRENT_ANNOUNCE?s.push([[globalThis.WEBTORRENT_ANNOUNCE]]):Array.isArray(globalThis.WEBTORRENT_ANNOUNCE)&&(s=s.concat(globalThis.WEBTORRENT_ANNOUNCE.map((e=>[e])))));void 0===t.announce&&void 0===t.announceList&&(s=s.concat(p));"string"==typeof t.urlList&&(t.urlList=[t.urlList]);const a={info:{name:t.name},"creation date":Math.ceil((Number(t.creationDate)||Date.now())/1e3),encoding:"UTF-8"};0!==s.length&&(a.announce=s[0][0],a["announce-list"]=s);void 0!==t.comment&&(a.comment=t.comment);void 0!==t.createdBy&&(a["created by"]=t.createdBy);void 0!==t.private&&(a.info.private=Number(t.private));void 0!==t.info&&Object.assign(a.info,t.info);void 0!==t.sslCert&&(a.info["ssl-cert"]=t.sslCert);void 0!==t.urlList&&(a["url-list"]=t.urlList);const h=e.reduce(y,0),l=t.pieceLength||o(h);a.info["piece length"]=l,async function(e,t,n,r,s){const o=[];let a=0,h=0;const l=e.map((e=>e.getStream)),u=r.onProgress;let f=0,p=0,g=!1;const m=i(c(l),t,{zeroPadding:!1});try{for await(const e of m)await new Promise((t=>{a+=e.length;const i=p;++p,++f<_&&t(),(0,d.vp)(e,"hex").then((r=>{o[i]=r,--f,h+=e.length,u&&u(h,n),t(),g&&0===f&&s(null,(0,d._0)(o.join("")),a)}))}));if(0===f)return s(null,(0,d._0)(o.join("")),a);g=!0}catch(e){s(e)}}(e,l,h,t,((i,s,o)=>{if(i)return r(i);a.info.pieces=s,e.forEach((e=>{delete e.getStream})),t.singleFileTorrent?a.info.length=o:a.info.files=e,r(null,n.Z.encode(a))}))}(s,t,r)}))};var k=r(1227),x=r(3552),E=r(5843),S=r(1982);self.Blob,self.File,self.FormData,self.Headers,self.Request,self.Response,self.AbortController,self.AbortSignal;const C=self.fetch||(()=>{throw new Error("global fetch is not available!")});var A=r(5017);function T(e){return e.reduce(((e,t,n,i)=>{const r=t.split("-").map((e=>parseInt(e)));return e.concat(((e,t=e)=>Array.from({length:t-e+1},((t,n)=>n+e)))(...r))}),[])}const P=function(e){const t={},n=e.split("magnet:?")[1];let i;if((n&&n.length>=0?n.split("&"):[]).forEach((e=>{const n=e.split("=");if(2!==n.length)return;const i=n[0];let r=n[1];"dn"===i&&(r=decodeURIComponent(r).replace(/\+/g," ")),"tr"!==i&&"xs"!==i&&"as"!==i&&"ws"!==i||(r=decodeURIComponent(r)),"kt"===i&&(r=decodeURIComponent(r).split("+")),"ix"===i&&(r=Number(r)),"so"===i&&(r=T(decodeURIComponent(r).split(","))),t[i]?(Array.isArray(t[i])||(t[i]=[t[i]]),t[i].push(r)):t[i]=r})),t.xt){(Array.isArray(t.xt)?t.xt:[t.xt]).forEach((e=>{if(i=e.match(/^urn:btih:(.{40})/))t.infoHash=i[1].toLowerCase();else if(i=e.match(/^urn:btih:(.{32})/)){const e=A.decode(i[1]);t.infoHash=(0,d.Ff)(e.toString("binary"))}else(i=e.match(/^urn:btmh:1220(.{64})/))&&(t.infoHashV2=i[1].toLowerCase())}))}if(t.xs){(Array.isArray(t.xs)?t.xs:[t.xs]).forEach((e=>{(i=e.match(/^urn:btpk:(.{64})/))&&(t.publicKey=i[1].toLowerCase())}))}return t.infoHash&&(t.infoHashBuffer=(0,d._0)(t.infoHash)),t.infoHashV2&&(t.infoHashV2Buffer=(0,d._0)(t.infoHashV2)),t.publicKey&&(t.publicKeyBuffer=(0,d._0)(t.publicKey)),t.dn&&(t.name=t.dn),t.kt&&(t.keywords=t.kt),t.announce=[],("string"==typeof t.tr||Array.isArray(t.tr))&&(t.announce=t.announce.concat(t.tr)),t.urlList=[],("string"==typeof t.as||Array.isArray(t.as))&&(t.urlList=t.urlList.concat(t.as)),("string"==typeof t.ws||Array.isArray(t.ws))&&(t.urlList=t.urlList.concat(t.ws)),t.peerAddresses=[],("string"==typeof t["x.pe"]||Array.isArray(t["x.pe"]))&&(t.peerAddresses=t.peerAddresses.concat(t["x.pe"])),t.announce=Array.from(new Set(t.announce)),t.urlList=Array.from(new Set(t.urlList)),t.peerAddresses=Array.from(new Set(t.peerAddresses)),t};async function I(e){if("string"==typeof e&&/^(stream-)?magnet:/.test(e)){const t=P(e);if(!t.infoHash)throw new Error("Invalid torrent identifier");return t}if("string"==typeof e&&(/^[a-f0-9]{40}$/i.test(e)||/^[a-z2-7]{32}$/i.test(e)))return P(`magnet:?xt=urn:btih:${e}`);if(ArrayBuffer.isView(e)&&20===e.length)return P(`magnet:?xt=urn:btih:${(0,d.oc)(e)}`);if(ArrayBuffer.isView(e))return await async function(e){ArrayBuffer.isView(e)&&(e=n.Z.decode(e));O(e.info,"info"),O(e.info["name.utf-8"]||e.info.name,"info.name"),O(e.info["piece length"],"info['piece length']"),O(e.info.pieces,"info.pieces"),e.info.files?e.info.files.forEach((e=>{O("number"==typeof e.length,"info.files[0].length"),O(e["path.utf-8"]||e.path,"info.files[0].path")})):O("number"==typeof e.info.length,"info.length");const i={info:e.info,infoBuffer:n.Z.encode(e.info),name:(0,d.vV)(e.info["name.utf-8"]||e.info.name),announce:[]};i.infoHashBuffer=await(0,d.vp)(i.infoBuffer),i.infoHash=(0,d.oc)(i.infoHashBuffer),void 0!==e.info.private&&(i.private=!!e.info.private);e["creation date"]&&(i.created=new Date(1e3*e["creation date"]));e["created by"]&&(i.createdBy=(0,d.vV)(e["created by"]));ArrayBuffer.isView(e.comment)&&(i.comment=(0,d.vV)(e.comment));Array.isArray(e["announce-list"])&&e["announce-list"].length>0?e["announce-list"].forEach((e=>{e.forEach((e=>{i.announce.push((0,d.vV)(e))}))})):e.announce&&i.announce.push((0,d.vV)(e.announce));ArrayBuffer.isView(e["url-list"])&&(e["url-list"]=e["url-list"].length>0?[e["url-list"]]:[]);i.urlList=(e["url-list"]||[]).map((e=>(0,d.vV)(e))),i.announce=Array.from(new Set(i.announce)),i.urlList=Array.from(new Set(i.urlList));const r=e.info.files||[e.info];i.files=r.map(((e,n)=>{const s=[].concat(i.name,e["path.utf-8"]||e.path||[]).map((e=>ArrayBuffer.isView(e)?(0,d.vV)(e):e));return{path:t.join.apply(null,[t.sep].concat(s)).slice(1),name:s[s.length-1],length:e.length,offset:r.slice(0,n).reduce(L,0)}})),i.length=r.reduce(L,0);const s=i.files[i.files.length-1];return i.pieceLength=e.info["piece length"],i.lastPieceLength=(s.offset+s.length)%i.pieceLength||i.pieceLength,i.pieces=function(e){const t=[];for(let n=0;n<e.length;n+=20)t.push((0,d.oc)(e.slice(n,n+20)));return t}(e.info.pieces),i}(e);if(e&&e.infoHash)return e.infoHash=e.infoHash.toLowerCase(),e.announce||(e.announce=[]),"string"==typeof e.announce&&(e.announce=[e.announce]),e.urlList||(e.urlList=[]),e;throw new Error("Invalid torrent identifier")}async function R(e,t,n){if("function"==typeof t)return R(e,{},t);if("function"!=typeof n)throw new Error("second argument must be a Function");let i;try{i=await I(e)}catch(e){}if(i&&i.infoHash)u((()=>{n(null,i)}));else if(r=e,"undefined"!=typeof Blob&&r instanceof Blob)try{s(new Uint8Array(await e.arrayBuffer()))}catch(e){return n(new Error(`Error converting Blob: ${e.message}`))}else if(/^https?:/.test(e))try{const n=await C(e,{headers:{"user-agent":"WebTorrent (https://webtorrent.io)"},signal:AbortSignal.timeout(3e4),...t});s(new Uint8Array(await n.arrayBuffer()))}catch(e){return n(new Error(`Error downloading torrent: ${e.message}`))}else"function"==typeof S.readFile&&"string"==typeof e?S.readFile(e,((e,t)=>{if(e)return n(new Error("Invalid torrent identifier"));s(t)})):u((()=>{n(new Error("Invalid torrent identifier"))}));var r;async function s(e){try{i=await I(e)}catch(e){return n(e)}i&&i.infoHash?n(null,i):n(new Error("Invalid torrent identifier"))}}function L(e,t){return e+t.length}function O(e,t){if(!e)throw new Error(`Torrent is missing required field: ${t}`)}r(8764).lW.alloc(0);const B=I,U=function(e){e=Object.assign({},e);let t=new Set;e.xt&&"string"==typeof e.xt&&t.add(e.xt),e.xt&&Array.isArray(e.xt)&&(t=new Set(e.xt)),e.infoHashBuffer&&t.add(`urn:btih:${(0,d.oc)(e.infoHashBuffer)}`),e.infoHash&&t.add(`urn:btih:${e.infoHash}`),e.infoHashV2Buffer&&t.add(e.xt=`urn:btmh:1220${(0,d.oc)(e.infoHashV2Buffer)}`),e.infoHashV2&&t.add(`urn:btmh:1220${e.infoHashV2}`);const n=Array.from(t);1===n.length&&(e.xt=n[0]),n.length>1&&(e.xt=n),e.publicKeyBuffer&&(e.xs=`urn:btpk:${(0,d.oc)(e.publicKeyBuffer)}`),e.publicKey&&(e.xs=`urn:btpk:${e.publicKey}`),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),e.peerAddresses&&(e["x.pe"]=e.peerAddresses);let i="magnet:?";return Object.keys(e).filter((e=>2===e.length||"x.pe"===e)).forEach(((t,n)=>{const r=Array.isArray(e[t])?e[t]:[e[t]];var s;r.forEach(((e,r)=>{(n>0||r>0)&&("kt"!==t&&"so"!==t||0===r)&&(i+="&"),"dn"===t&&(e=encodeURIComponent(e).replace(/%20/g,"+")),"tr"!==t&&"as"!==t&&"ws"!==t||(e=encodeURIComponent(e)),"xs"!==t||e.startsWith("urn:btpk:")||(e=encodeURIComponent(e)),"kt"===t&&(e=encodeURIComponent(e)),"so"!==t&&(i+="kt"===t&&r>0?`+${e}`:`${t}=${e}`)})),"so"===t&&(i+=`${t}=${s=r,s.reduce(((e,t,n,i)=>(0!==n&&t===i[n-1]+1||e.push([]),e[e.length-1].push(t),e)),[]).map((e=>e.length>1?`${e[0]}-${e[e.length-1]}`:`${e[0]}`))}`)})),i};var N=r(5177),M=r(1237),j=r(2114);const H=k("simple-peer"),D=65536;function F(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class q extends M.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this.__objectMode=!!e.objectMode,this._id=(0,d.oc)((0,d.O6)(4)).slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||(0,d.oc)((0,d.O6)(20)):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||q.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},q.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this._destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:N(),!this._wrtc)throw"undefined"==typeof window?j(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):j(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.__destroy(j(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch((e=>{this.__destroy(j(e,"ERR_PC_PEER_IDENTITY"))})),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach((e=>{this.addStream(e)})),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this._destroying){if(this.destroyed)throw j(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.__destroy(j(e,"ERR_SET_REMOTE_DESCRIPTION"))})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.__destroy(j(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var n;!t.address||t.address.endsWith(".local")?(n="Ignoring unsupported ICE candidate.",console.warn(n)):this.__destroy(j(e,"ERR_ADD_ICE_CANDIDATE"))}))}send(e){if(!this._destroying){if(this.destroyed)throw j(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,t){if(!this._destroying){if(this.destroyed)throw j(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.__destroy(j(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this._destroying){if(this.destroyed)throw j(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach((t=>{this.addTrack(t,e)}))}}addTrack(e,t){if(this._destroying)return;if(this.destroyed)throw j(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(e)||new Map;let i=n.get(t);if(i)throw i.removed?j(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):j(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");i=this._pc.addTrack(e,t),n.set(t,i),this._senderMap.set(e,n),this._needsNegotiation()}replaceTrack(e,t,n){if(this._destroying)return;if(this.destroyed)throw j(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const i=this._senderMap.get(e),r=i?i.get(n):null;if(!r)throw j(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,i),null!=r.replaceTrack?r.replaceTrack(t):this.__destroy(j(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(e,t){if(this._destroying)return;if(this.destroyed)throw j(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(e),i=n?n.get(t):null;if(!i)throw j(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{i.removed=!0,this._pc.removeTrack(i)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(i):this.__destroy(j(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this._destroying){if(this.destroyed)throw j(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach((t=>{this.removeTrack(t,e)}))}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,u((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){if(!this._destroying){if(this.destroyed)throw j(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}_final(e){this._readableState.ended||this.push(null),e(null)}__destroy(e){this.end(),this._destroy((()=>{}),e)}_destroy(e,t){this.destroyed||this._destroying||(this._destroying=!0,this._debug("destroying (error: %s)",t&&(t.message||t)),setTimeout((()=>{if(this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,t&&this.emit("error",t),e()}),0))}_setupData(e){if(!e.channel)return this.__destroy(j(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=D),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.__destroy(j(t,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_write(e,t){if(this.destroyed)return t(j(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.__destroy(j(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>D?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=t):t(null)}else this._debug("write before connect"),this._chunk=e,this._cb=t}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.__destroy()),1e3)};this._connected?e():this.once("connect",e)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=F(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.__destroy(j(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.__destroy(j(e,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=F(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.__destroy(j(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.__destroy(j(e,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||this._destroying||"failed"===this._pc.connectionState&&this.__destroy(j(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.__destroy(j(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.__destroy(j(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{const i=[];n.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(this.destroyed)return;const i=[];n.result().forEach((e=>{const n={};e.names().forEach((t=>{n[t]=e.stat(t)})),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,i.push(t(n))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this._destroying||this.getStats(((t,n)=>{if(this.destroyed||this._destroying)return;t&&(n=[]);const i={},r={},s={};let o=!1;n.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(r[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}));const a=e=>{o=!0;let t=r[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=i[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),o||Object.keys(s).length&&!Object.keys(r).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.__destroy(j(t,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>D||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer?t=new Uint8Array(t):!1===this.__objectMode&&(t=(0,d.gR)(t)),this.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.__destroy())}_onTrack(e){this.destroyed||e.streams.forEach((t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some((e=>e.id===t.id))||(this._remoteStreams.push(t),u((()=>{this._debug("on stream"),this.emit("stream",t)})))}))}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],H.apply(null,e)}}q.WEBRTC_SUPPORT=!!N(),q.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},q.channelConfig={};const $=q;var W=r(1463),z=r(558),G=r(8302),V=r(2203),K=r(1494),Z=r(5381);const Y=/^\[?([^\]]+)]?:(\d+)$/;let J=new Map;function X(e){if(1e5===J.size&&J.clear(),!J.has(e)){const t=Y.exec(e);if(!t)throw new Error(`invalid addr: ${e}`);J.set(e,[t[1],Number(t[2])])}return J.get(e)}var Q=r(8205),ee=r(9421);async function*te(e,t={}){if(e?.[Symbol.asyncIterator])return void(yield*e[Symbol.asyncIterator](t.offset));if(!e?.get)throw new Error("First argument must be an abstract-chunk-store compliant store");const n=t.chunkLength||e.chunkLength;if(!n)throw new Error("missing required `chunkLength` property");let i=t.length||e.length;if(!Number.isFinite(i))throw new Error("missing required `length` property");const r=t.offset||0,s=(t,n,i)=>new Promise(((r,s)=>{e.get(t,{offset:i,length:n},((e,t)=>{e&&s(e),r(t)}))}));let o=Math.floor(r/n);const a=r%n;if(r){const e=Math.min(i,n-a);i-=e,yield s(o++,e,a)}for(let e=i;e>0;++o,e-=n)yield s(o,Math.min(e,n))}async function ne(e,t,n={}){if(!e?.put)throw new Error("First argument must be an abstract-chunk-store compliant store");const r=n.chunkLength||e.chunkLength;if(!r)throw new Error("missing required `chunkLength` property");const s=n.storeMaxOutstandingPuts||16;let o=0,a=0,h=()=>{},c=!1;for await(const l of i(t,r,{zeroPadding:n.zeroPadding||!1}))await new Promise((t=>{o++<=s&&t(),e.put(a++,l,(e=>{if(e)throw e;--o,t(),c&&0===o&&h()}))}));0!==o&&(c=new Promise((e=>{h=e})),await c)}var ie=r(9648),re=r(1018),se=r(778),oe=r(8411);const ae={DEFAULT_ANNOUNCE_PEERS:50,MAX_ANNOUNCE_PEERS:82,parseUrl:e=>{const t=new URL(e.replace(/^udp:/,"http:"));return e.match(/^udp:/)&&Object.defineProperties(t,{href:{value:t.href.replace(/^http/,"udp")},protocol:{value:t.protocol.replace(/^http/,"udp")},origin:{value:t.origin.replace(/^http/,"udp")}}),t},...r.t(oe,2)};var he=r(1857),ce=r(159),le=r(6313),ue=r(9356);const de=k("simple-websocket"),fe="function"!=typeof ue?WebSocket:ue;class pe extends M.Duplex{constructor(e={}){if("string"==typeof e&&(e={url:e}),super(e=Object.assign({allowHalfOpen:!1},e)),this.__objectMode=!!e.objectMode,null!=e.objectMode&&delete e.objectMode,null==e.url&&null==e.socket)throw new Error("Missing required `url` or `socket` option");if(null!=e.url&&null!=e.socket)throw new Error("Must specify either `url` or `socket` option, not both");if(this._id=(0,d.oc)((0,d.O6)(4)).slice(0,7),this._debug("new websocket: %o",e),this.connected=!1,this._chunk=null,this._cb=null,this._interval=null,e.socket)this.url=e.socket.url,this._ws=e.socket,this.connected=e.socket.readyState===fe.OPEN;else{this.url=e.url;try{this._ws="function"==typeof ue?new fe(e.url,{...e,encoding:void 0}):new fe(e.url)}catch(e){return void u((()=>this.destroy(e)))}}this._ws.binaryType="arraybuffer",e.socket&&this.connected?u((()=>this._handleOpen())):this._ws.onopen=()=>this._handleOpen(),this._ws.onmessage=e=>this._handleMessage(e),this._ws.onclose=()=>this._handleClose(),this._ws.onerror=e=>this._handleError(e),this._handleFinishBound=()=>this._handleFinish(),this.once("finish",this._handleFinishBound)}send(e){this._ws.send(e)}_final(e){this._readableState.ended||this.push(null),e(null)}_destroy(e){if(!this.destroyed){if(this._writableState.ended||this.end(),this.connected=!1,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._handleFinishBound&&this.removeListener("finish",this._handleFinishBound),this._handleFinishBound=null,this._ws){const e=this._ws,t=()=>{e.onclose=null};if(e.readyState===fe.CLOSED)t();else try{e.onclose=t,e.close()}catch(e){t()}e.onopen=null,e.onmessage=null,e.onerror=()=>{}}this._ws=null,e()}}_write(e,t){if(this.destroyed)return t(new Error("cannot write after socket is destroyed"));if(this.connected){try{this.send(e)}catch(e){return this.destroy(e)}"function"!=typeof ue&&this._ws.bufferedAmount>65536?(this._debug("start backpressure: bufferedAmount %d",this._ws.bufferedAmount),this._cb=t):t(null)}else this._debug("write before connect"),this._chunk=e,this._cb=t}_handleOpen(){if(!this.connected&&!this.destroyed){if(this.connected=!0,this._chunk){try{this.send(this._chunk)}catch(e){return this.destroy(e)}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"function"!=typeof ue&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}}_handleMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=new Uint8Array(t)),!1===this.__objectMode&&(t=(0,d.gR)(t)),this.push(t)}_handleClose(){this.destroyed||(this._debug("on close"),this.destroy())}_handleError(e){this.destroy(new Error(`Error connecting to ${this.url}`))}_handleFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.destroy()),1e3)};this.connected?e():this.once("connect",e)}_onInterval(){if(!this._cb||!this._ws||this._ws.bufferedAmount>65536)return;this._debug("ending backpressure: bufferedAmount %d",this._ws.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],de.apply(null,e)}}pe.WEBSOCKET_SUPPORT=!!fe;var ge=r(9354);const me=class extends e{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())}},_e=k("bittorrent-tracker:websocket-tracker"),ye={};class we extends me{constructor(e,t){super(e,t),_e("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,5);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=>(0,d.E)(e))):e.infoHash&&(0,d.E)(e.infoHash)||this.client._infoHashBinary};this._send(t)}destroy(e=be){if(this.destroyed)return e(null);this.destroyed=!0,clearInterval(this.interval),clearTimeout(this.reconnectTimer);for(const e in this.peers){const t=this.peers[e];clearTimeout(t.trackerTimeout),t.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,ye[this.announceUrl]&&(ye[this.announceUrl].consumers-=1),ye[this.announceUrl].consumers>0)return e();let t,n=ye[this.announceUrl];if(delete ye[this.announceUrl],n.on("error",be),n.once("close",e),!this.expectingResponse)return i();function i(){t&&(clearTimeout(t),t=null),n.removeListener("data",i),n.destroy(),n=null}t=setTimeout(i,oe.DESTROY_TIMEOUT),n.once("data",i)}_openSocket(){if(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=ye[this.announceUrl],this.socket)ye[this.announceUrl].consumers+=1,this.socket.connected&&this._onSocketConnectBound();else{const e=new URL(this.announceUrl);let t;this.client._proxyOpts&&(t="wss:"===e.protocol?this.client._proxyOpts.httpsAgent:this.client._proxyOpts.httpAgent,!t&&this.client._proxyOpts.socksProxy&&(t=new ge.Agent(le(this.client._proxyOpts.socksProxy),"wss:"===e.protocol))),this.socket=ye[this.announceUrl]=new pe({url:this.announceUrl,agent:t}),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((0,d.vV)(e))}catch(e){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 _e("ignoring websocket data from %s for %s (looking for %s: reused socket)",this.announceUrl,(0,d.Ff)(e.info_hash),this.client.infoHash);if(e.peer_id&&e.peer_id===this.client._peerIdBinary)return;_e("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 i=e.interval||e["min interval"];i&&this.setInterval(1e3*i);const r=e["tracker id"];if(r&&(this._trackerId=r),null!=e.complete){const t=Object.assign({},e,{announce:this.announceUrl,infoHash:(0,d.Ff)(e.info_hash)});this.client.emit("update",t)}let s;if(e.offer&&e.peer_id&&(_e("creating peer (from remote offer)"),s=this._createPeer(),s.id=(0,d.Ff)(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)})),this.client.emit("peer",s),s.signal(e.offer)),e.answer&&e.peer_id){const t=(0,d.Ff)(e.offer_id);s=this.peers[t],s?(s.id=(0,d.Ff)(e.peer_id),this.client.emit("peer",s),s.signal(e.answer),clearTimeout(s.trackerTimeout),s.trackerTimeout=null,delete this.peers[t]):_e(`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:(0,d.Ff)(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(3e5*Math.random())+Math.min(1e4*Math.pow(2,this.retries),36e5);this.reconnecting=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout((()=>{this.retries++,this._openSocket()}),e),this.reconnectTimer.unref&&this.reconnectTimer.unref(),_e("reconnecting socket in %s ms",e)}_send(e){if(this.destroyed)return;this.expectingResponse=!0;const t=JSON.stringify(e);_e("send %s",t),this.socket.send(t)}_generateOffers(e,t){const n=this,i=[];_e("generating %s offers",e);for(let t=0;t<e;++t)r();function r(){const e=(0,d.oc)((0,d.O6)(20));_e("creating peer (from _generateOffers)");const t=n.peers[e]=n._createPeer({initiator:!0});t.once("signal",(t=>{i.push({offer:t,offer_id:(0,d.E)(e)}),s()})),t.trackerTimeout=setTimeout((()=>{_e("tracker timeout: destroying peer"),t.trackerTimeout=null,delete n.peers[e],t.destroy()}),5e4),t.trackerTimeout.unref&&t.trackerTimeout.unref()}function s(){i.length===e&&(_e("generated %s offers",e),t(i))}s()}_createPeer(e){const t=this;e=Object.assign({trickle:!1,config:t.client._rtcConfig,wrtc:t.client._wrtc},e);const n=new $(e);return n.once("error",i),n.once("connect",(function e(){n.removeListener("error",i),n.removeListener("connect",e)})),n;function i(e){t.client.emit("warning",new Error(`Connection error: ${e.message}`)),n.destroy()}}}function be(){}we.prototype.DEFAULT_ANNOUNCE_INTERVAL=3e4,we._socketPool=ye;const ve=we;var ke=r(8768);const xe=k("bittorrent-tracker:client");class Ee extends e{constructor(e={}){if(super(),!e.peerId)throw new Error("Option `peerId` is required");if(!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");if(!ke.browser&&!e.port)throw new Error("Option `port` is required");this.peerId="string"==typeof e.peerId?e.peerId:(0,d.oc)(e.peerId),this._peerIdBuffer=(0,d._0)(this.peerId),this._peerIdBinary=(0,d.E)(this.peerId),this.infoHash="string"==typeof e.infoHash?e.infoHash.toLowerCase():(0,d.oc)(e.infoHash),this._infoHashBuffer=(0,d._0)(this.infoHash),this._infoHashBinary=(0,d.E)(this.infoHash),xe("new client %s",this.infoHash),this.destroyed=!1,this._port=e.port,this._getAnnounceOpts=e.getAnnounceOpts,this._rtcConfig=e.rtcConfig,this._userAgent=e.userAgent,this._proxyOpts=e.proxyOpts,this._wrtc="function"==typeof e.wrtc?e.wrtc():e.wrtc;let t="string"==typeof e.announce?[e.announce]:null==e.announce?[]:e.announce;t=t.map((e=>(ArrayBuffer.isView(e)&&(e=(0,d.vV)(e)),"/"===e[e.length-1]&&(e=e.substring(0,e.length-1)),e))),t=Array.from(new Set(t));const n=!1!==this._wrtc&&(!!this._wrtc||$.WEBRTC_SUPPORT),i=e=>{u((()=>{this.emit("warning",e)}))};this._trackers=t.map((e=>{let t;try{t=ae.parseUrl(e)}catch(t){return i(new Error(`Invalid tracker URL: ${e}`)),null}const r=t.port;if(r<0||r>65535)return i(new Error(`Invalid tracker port: ${e}`)),null;const s=t.protocol;return"http:"!==s&&"https:"!==s||"function"!=typeof he?"udp:"===s&&"function"==typeof ce?new ce(this,e):"ws:"!==s&&"wss:"!==s||!n||"ws:"===s&&"undefined"!=typeof window&&"https:"===window.location.protocol?(i(new Error(`Unsupported tracker protocol: ${e}`)),null):new ve(this,e):new he(this,e)})).filter(Boolean)}start(e){(e=this._defaultAnnounceOpts(e)).event="started",xe("send `start` %o",e),this._announce(e),this._trackers.forEach((e=>{e.setInterval()}))}stop(e){(e=this._defaultAnnounceOpts(e)).event="stopped",xe("send `stop` %o",e),this._announce(e)}complete(e){e||(e={}),(e=this._defaultAnnounceOpts(e)).event="completed",xe("send `complete` %o",e),this._announce(e)}update(e){(e=this._defaultAnnounceOpts(e)).event&&delete e.event,xe("send `update` %o",e),this._announce(e)}_announce(e){this._trackers.forEach((t=>{t.announce(e)}))}scrape(e){xe("send `scrape`"),e||(e={}),this._trackers.forEach((t=>{t.scrape(e)}))}setInterval(e){xe("setInterval %d",e),this._trackers.forEach((t=>{t.setInterval(e)}))}destroy(e){if(this.destroyed)return;this.destroyed=!0,xe("destroy");const t=this._trackers.map((e=>t=>{e.destroy(t)}));l(t,e),this._trackers=[],this._getAnnounceOpts=null}_defaultAnnounceOpts(e={}){return null==e.numwant&&(e.numwant=ae.DEFAULT_ANNOUNCE_PEERS),null==e.uploaded&&(e.uploaded=0),null==e.downloaded&&(e.downloaded=0),this._getAnnounceOpts&&(e=Object.assign({},e,this._getAnnounceOpts())),e}}Ee.scrape=(e,t)=>{if(t=se(t),!e.infoHash)throw new Error("Option `infoHash` is required");if(!e.announce)throw new Error("Option `announce` is required");const n=Object.assign({},e,{infoHash:Array.isArray(e.infoHash)?e.infoHash[0]:e.infoHash,peerId:(0,d.gR)("01234567890123456789"),port:6881}),i=new Ee(n);i.once("error",t),i.once("warning",t);let r=Array.isArray(e.infoHash)?e.infoHash.length:1;const s={};return i.on("scrape",(e=>{if(r-=1,s[e.infoHash]=e,0===r){i.destroy();const e=Object.keys(s);1===e.length?t(null,s[e[0]]):t(null,s)}})),i.scrape({infoHash:e.infoHash}),i};const Se=Ee;r(859);var Ce=r(2067),Ae=r(8768);const Te=k("torrent-discovery");class Pe extends e.EventEmitter{constructor(e){if(super(),!e.peerId)throw new Error("Option `peerId` is required");if(!e.infoHash)throw new Error("Option `infoHash` is required");if(!Ae.browser&&!e.port)throw new Error("Option `port` is required");this.peerId="string"==typeof e.peerId?e.peerId:e.peerId.toString("hex"),this.infoHash="string"==typeof e.infoHash?e.infoHash.toLowerCase():e.infoHash.toString("hex"),this._port=e.port,this._userAgent=e.userAgent,this.destroyed=!1,this._announce=e.announce||[],this._intervalMs=e.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")},this._onLSDPeer=(e,t)=>{this.emit("peer",e,"lsd")};const t=(e,t)=>{const n=new re.Client(t);return n.on("warning",this._onWarning),n.on("error",this._onError),n.listen(e),this._internalDHT=!0,n};!1===e.tracker?this.tracker=null:e.tracker&&"object"==typeof e.tracker?(this._trackerOpts=Object.assign({},e.tracker),this.tracker=this._createTracker()):this.tracker=this._createTracker(),!1===e.dht||"function"!=typeof re.Client?this.dht=null:e.dht&&"function"==typeof e.dht.addNode?this.dht=e.dht:e.dht&&"object"==typeof e.dht?this.dht=t(e.dhtPort,e.dht):this.dht=t(e.dhtPort),this.dht&&(this.dht.on("peer",this._onDHTPeer),this._dhtAnnounce()),!1===e.lsd||"function"!=typeof Ce?this.lsd=null:this.lsd=this._createLSD()}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)}))),this.lsd&&(this.lsd.removeListener("warning",this._onWarning),this.lsd.removeListener("error",this._onError),this.lsd.removeListener("peer",this._onLSDPeer),t.push((e=>{this.lsd.destroy(e)}))),l(t,e),this.dht=null,this.tracker=null,this.lsd=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 Se(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||(Te("dht announce"),this._dhtAnnouncing=!0,clearTimeout(this._dhtTimeout),this.dht.announce(this.infoHash,this._port,(e=>{this._dhtAnnouncing=!1,Te("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())})))}_createLSD(){const e=Object.assign({},{infoHash:this.infoHash,peerId:this.peerId,port:this._port}),t=new Ce(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onLSDPeer),t.start(),t}}const Ie=Pe;"undefined"!=typeof navigator&&navigator.storage?.getDirectory&&navigator.storage.getDirectory().then((e=>{e.removeEntry("chunks",{recursive:!0})}));const Re=()=>{};class Le{constructor(e,t={}){if(this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");if("undefined"==typeof navigator||!navigator.storage?.getDirectory)throw new Error("FSA API is not supported");if(this.closed=!1,this.name=t.name||crypto.randomUUID(),this.chunks=[],this.rootDirPromise=t.rootDir||navigator.storage.getDirectory(),this.storageDirPromise=(async()=>(await this.rootDirPromise).getDirectoryHandle(this.name,{create:!0}))(),this.chunksDirPromise=this.storageDirPromise,t.files&&t.rootDir){if(this.chunkMap=[],this.directoryMap={},this.chunksDirPromise=this._getChunksDirHandle(),this.files=t.files.map(((e,t,n)=>{if(null==e.path)throw new Error("File is missing `path` property");if(null==e.length)throw new Error("File is missing `length` property");if(null==e.offset)if(0===t)e.offset=0;else{const i=n[t-1];e.offset=i.offset+i.length}null==e.handle&&(e.handle=this._createFileHandle({path:e.path})),e.blob=this._createBlobReference(e.handle);const i=e.offset,r=e.offset+e.length,s=Math.floor(i/this.chunkLength),o=Math.floor((r-1)/this.chunkLength);for(let t=s;t<=o;++t){const n=t*this.chunkLength,s=i<n?0:i-n,o=r>n+this.chunkLength?this.chunkLength:r-n,a=i>n?0:n-i;this.chunkMap[t]||(this.chunkMap[t]=[]),this.chunkMap[t].push({from:s,to:o,offset:a,file:e})}return e})),window.addEventListener("pagehide",(()=>this.cleanup())),this.length=this.files.reduce(((e,t)=>e+t.length),0),null!=t.length&&t.length!==this.length)throw new Error("total `files` length is not equal to explicit `length` option")}else this.length=Number(t.length)||1/0;this.length!==1/0&&(this.lastChunkLength=this.length%this.chunkLength||this.chunkLength,this.lastChunkIndex=Math.ceil(this.length/this.chunkLength)-1)}async _getChunkHandle(e){let t=this.chunks[e];if(!t){const n=await this.chunksDirPromise;this.chunks[e]=t=await n.getFileHandle(e,{create:!0})}return t}async _createFileHandle(e){const t=e.path.slice(e.path.lastIndexOf("/")+1);return(await this._getDirectoryHandle(e)).getFileHandle(t,{create:!0})}async _createBlobReference(e){return(await e).getFile()}async _getDirectoryHandle(e){const t=e.path.lastIndexOf("/");if(-1===t||0===t)return this.storageDirPromise;const n=e.path=e.path.slice(0,t);return this.directoryMap[n]||(this.directoryMap[n]=(async()=>(await this._getDirectoryHandle(e)).getDirectoryHandle(n.slice(n.lastIndexOf("/")+1),{create:!0}))()),this.directoryMap[n]}async _getChunksDirHandle(){const e=await navigator.storage.getDirectory();return(await e.getDirectoryHandle("chunks",{create:!0})).getDirectoryHandle(this.name,{create:!0})}async put(e,t,n=Re){try{return await this._put(e,t),n(null),null}catch(e){return queueMicrotask((()=>n(e))),e}}async _put(e,t){if(this.closed)throw new Error("Storage is closed");const n=e===this.lastChunkIndex;if(n&&t.length!==this.lastChunkLength)throw new Error(`Last chunk length must be ${this.lastChunkLength}`);if(!n&&t.length!==this.chunkLength)throw new Error(`Chunk length must be ${this.chunkLength}`);const i=(async()=>{const n=await this._getChunkHandle(e),i=await n.createWritable({keepExistingData:!1});await i.write(t),await i.close()})();if(!this.files)return i;const r=this.chunkMap[e];if(!r)throw new Error("No files matching the request range");const s=r.map((async({file:e,offset:n,from:i,to:r})=>{e.stream||(e.stream=await(await e.handle).createWritable({keepExistingData:!0})),await e.stream.write({type:"write",position:n,data:t.slice(i,r)})}));s.push(i),await Promise.all(s)}async get(e,t,n=Re){null==t&&(t={});try{const i=await this._get(e,t);return n(null,i),i}catch(e){return n(e),e}}async _get(e,t){if("function"==typeof t)return this.get(e,void 0,t);if(this.closed)throw new Error("Storage is closed");const n=e===this.lastChunkIndex?this.lastChunkLength:this.chunkLength,i=t.offset||0,r=t.length?i+t.length:n,s=t.length||n-i;if(i<0||i<0||r>n)throw new Error("Invalid offset and/or length");if(i===r)return new Uint8Array(0);if(!this.files||this.chunks[e]){const t=await this._getChunkHandle(e);let r=await t.getFile();0===i&&s===n||(r=r.slice(i,s+i));const o=await r.arrayBuffer();if(0===o.byteLength)throw new Error(`Index ${e} does not exist`);return new Uint8Array(o)}let o=this.chunkMap[e];if(!o)throw new Error("No files matching the request range");if(t&&(o=o.filter((({from:e,to:t})=>t>i&&e<r)),0===o.length))throw new Error("No files matching the request range");const a=o.map((async({from:e,to:n,offset:s,file:o})=>{t&&(n>r&&(n=r),e<i&&(s+=i-e,e=i));return(await o.blob).slice(s,s+n-e)})),h=await Promise.all(a),c=1===h.length?await h[0].arrayBuffer():await new Blob(h).arrayBuffer();if(0===c.byteLength)throw new Error(`Index ${e} does not exist`);return new Uint8Array(c)}async close(e=Re){if(this.closed)return((e=Re,t)=>queueMicrotask((()=>e(new Error(t)))))(e,"Storage is closed");this.closed=!0,this.chunkMap=null,this.directoryMap=null,this.files&&await this.cleanup(),queueMicrotask((()=>e(null)))}async cleanup(){const e=[];for(const t of this.files)t.stream&&(e.push(t.stream.close()),t.stream=null);const t=(async()=>{const e=await this.chunksDirPromise;this.chunks=[];for await(const t of e.keys())await e.removeEntry(t,{recursive:!0});this.chunksDirPromise=await this._getChunksDirHandle()})();await Promise.all(e);for(const e of this.files)e.blob=this._createBlobReference(e.handle);await t}async destroy(e=Re){this.close((async t=>{if(t)e(t);else{try{const e=await this.rootDirPromise;await e.removeEntry(this.name,{recursive:!0})}catch(t){return void e(t)}e(null)}}))}}var Oe=r(4137),Be=r(1191);const Ue=!!("undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||"undefined"!=typeof window&&window||"undefined"!=typeof globalThis&&globalThis).chrome?1/0:2130706432,Ne="undefined"!=typeof navigator&&navigator.storage?.getDirectory&&FileSystemFileHandle?.prototype?.createWritable,Me=()=>{};class je{constructor(e,t={}){if(this.chunkLength=Number(e),!this.chunkLength)throw new Error("First argument must be a chunk length");this.length=Number(t.length)||1/0,this.limit=t.limit||Ue,this.fallbackStore=null,this.dataStore=null,this.chunkCount=0,this.stores=[],this._init(t),this.dataStore&&(t.max>0&&(this.dataStore=new ee(this.dataStore,{max:t.max})),this.stores.push(this.dataStore)),this.stores.push(this.fallbackStore)}_init(e){if(e.onlyMem||this.limit<this.chunkLength)return void(this.fallbackStore=new Be(this.chunkLength,e));const t=Ne?Le:Oe;if(this.limit>=this.length)return void(this.fallbackStore=new t(this.chunkLength,e));this.chunkCount=Math.floor(Math.min(this.length,this.limit)/this.chunkLength);const n=this.chunkCount*this.chunkLength,i=this.length-n;this.dataStore=new t(this.chunkLength,{...e,length:n}),this.fallbackStore=new Be(this.chunkLength,{...e,length:i})}get(e,t,n){e>=this.chunkCount?this.fallbackStore.get(e-this.chunkCount,t,n):this.dataStore.get(e,t,n)}put(e,t,n){e>=this.chunkCount?this.fallbackStore.put(e-this.chunkCount,t,n):this.dataStore.put(e,t,n)}close(e=Me){Promise.all(this.stores.map((e=>new Promise((t=>e.close(t)))))).then((t=>{const n=t.find((e=>e));e(n)}))}destroy(e=Me){Promise.all(this.stores.map((e=>new Promise((t=>e.destroy(t)))))).then((t=>{const n=t.find((e=>e));e(n)}))}}var He=r(3700),De=r(9417),Fe=r(9967),qe=r(8687),$e=r(5960);const We=k("ut_metadata"),ze=16384,Ge=t=>{class i extends e.EventEmitter{constructor(e){super(),this._wire=e,this._fetching=!1,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._bitfield=new Q.Z(0,{grow:1e3}),ArrayBuffer.isView(t)&&this.setMetadata(t)}onHandshake(e,t,n){this._infoHash=e}onExtendedHandshake(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||1e7<e.metadata_size||e.metadata_size<=0?this.emit("warning",new Error("Peer gave invalid metadata size")):(this._metadataSize=e.metadata_size,this._numPieces=Math.ceil(this._metadataSize/ze),this._remainingRejects=2*this._numPieces,void this._requestPieces()):this.emit("warning",new Error("Peer does not have metadata")):this.emit("warning",new Error("Peer does not support ut_metadata"))}onMessage(e){let t,i;try{const r=(0,d.vV)(e),s=r.indexOf("ee")+2;t=n.Z.decode(r.substring(0,s)),i=e.slice(s)}catch(e){return}switch(t.msg_type){case 0:this._onRequest(t.piece);break;case 1:this._onData(t.piece,i,t.total_size);break;case 2:this._onReject(t.piece)}}fetch(){this._metadataComplete||(this._fetching=!0,this._metadataSize&&this._requestPieces())}cancel(){this._fetching=!1}async setMetadata(e){if(this._metadataComplete)return!0;We("set metadata");try{const t=n.Z.decode(e).info;t&&(e=n.Z.encode(t))}catch(e){}return(!this._infoHash||this._infoHash===await(0,d.vp)(e,"hex"))&&(this.cancel(),this.metadata=e,this._metadataComplete=!0,this._metadataSize=this.metadata.length,this._wire.extendedHandshake.metadata_size=this._metadataSize,this.emit("metadata",n.Z.encode({info:n.Z.decode(this.metadata)})),!0)}_send(e,t){let i=n.Z.encode(e);ArrayBuffer.isView(t)&&(i=(0,d.zo)([i,t])),this._wire.extended("ut_metadata",i)}_request(e){this._send({msg_type:0,piece:e})}_data(e,t,n){const i={msg_type:1,piece:e};"number"==typeof n&&(i.total_size=n),this._send(i,t)}_reject(e){this._send({msg_type:2,piece:e})}_onRequest(e){if(!this._metadataComplete)return void this._reject(e);const t=e*ze;let n=t+ze;n>this._metadataSize&&(n=this._metadataSize);const i=this.metadata.slice(t,n);this._data(e,i,this._metadataSize)}_onData(e,t,n){t.length>ze||!this._fetching||(this.metadata.set(t,e*ze),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=new Uint8Array(this._metadataSize);for(let e=0;e<this._numPieces;e++)this._request(e)}}async _checkDone(){let e=!0;for(let t=0;t<this._numPieces;t++)if(!this._bitfield.get(t)){e=!1;break}if(!e)return;await this.setMetadata(this.metadata)||this._failedMetadata()}_failedMetadata(){this._bitfield=new Q.Z(0,{grow:1e3}),this._remainingRejects-=this._numPieces,this._remainingRejects>0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))}}return i.prototype.name="ut_metadata",i};var Ve=r(8838),Ke=r(2109);const Ze=k("webtorrent:file-iterator");class Ye extends e{constructor(e,{start:t,end:n}){super(),this._torrent=e._torrent,this._pieceLength=e._torrent.pieceLength,this._startPiece=(t+e.offset)/this._pieceLength|0,this._endPiece=(n+e.offset)/this._pieceLength|0,this._piece=this._startPiece,this._offset=t+e.offset-this._startPiece*this._pieceLength,this._missing=n-t+1,this._criticalLength=Math.min(1048576/this._pieceLength|0,2),this._torrent.select(this._startPiece,this._endPiece,!0,(()=>{this.emit("_notify")})),this.destroyed=!1}[Symbol.asyncIterator](){return this}next(){return new Promise(((e,t)=>{if(0===this._missing||this.destroyed)return e({done:!0}),this.destroy();const n=(i,r)=>{if(!this._torrent.bitfield.get(i)){this._torrent.critical(i,i+this._criticalLength);const e=()=>{this._torrent.bitfield.get(i)&&(this.removeListener("_notify",e),n(i,r))};return this.on("_notify",e)}if(this._torrent.destroyed)return t(new Error("Torrent removed"));this._torrent.store.get(i,r,((n,r)=>this.destroyed?e({done:!0}):(Ze("read %s and yielding (length %s) (err %s)",i,r?.length,n?.message),n?t(n):void e({value:r,done:!1}))))},i=Math.min(this._missing,this._pieceLength-this._offset);n(this._piece++,{length:i,offset:this._offset}),this._missing-=i,this._offset=0}))}async return(){this.destroy();const{value:e}=await this.next();return{done:!0,value:e}}async throw(e){throw e}destroy(e=(()=>{}),t){this.destroyed||(this.destroyed=!0,this._torrent.destroyed||this._torrent.deselect(this._startPiece,this._endPiece,!0),this.emit("return"),e(t))}}class Je extends e{constructor(e,t){super(),this._torrent=e,this._destroyed=!1,this._fileStreams=new Set,this._iterators=new Set,this.name=t.name,this.path=t.path,this.length=t.length,this.size=t.length,this.type=Ke.getType(this.name)||"application/octet-stream",this.offset=t.offset,this.done=!1;const n=t.offset,i=n+t.length-1;this._startPiece=n/this._torrent.pieceLength|0,this._endPiece=i/this._torrent.pieceLength|0,0===this.length&&(this.done=!0,this.emit("done")),this._client=e.client}get downloaded(){if(this._destroyed||!this._torrent.bitfield)return 0;const{pieces:e,bitfield:t,pieceLength:n,lastPieceLength:i}=this._torrent,{_startPiece:r,_endPiece:s}=this,o=r=>{const s=r===e.length-1?i:n;return t.get(r)?s:s-e[r].missing};let a=0;for(let t=r;t<=s;t+=1){const h=o(t);if(a+=h,t===r){const e=this.offset%n;a-=Math.min(e,h)}if(t===s){const t=(s===e.length-1?i:n)-(this.offset+this.length)%n;a-=Math.min(t,h)}}return a}get progress(){return this.length?this.downloaded/this.length:0}select(e){0!==this.length&&this._torrent.select(this._startPiece,this._endPiece,e)}deselect(){0!==this.length&&this._torrent.deselect(this._startPiece,this._endPiece,!1)}[Symbol.asyncIterator](e={}){if(0===this.length)return async function*(){}();const{start:t=0}=e??{},n=e?.end&&e.end<this.length?e.end:this.length-1;if(this.done)return te(this._torrent.store,{offset:t+this.offset,length:n-t+1});const i=new Ye(this,{start:t,end:n});return this._iterators.add(i),i.once("return",(()=>{this._iterators.delete(i)})),i}createReadStream(e){const t=this[Symbol.asyncIterator](e),n=M.Readable.from(t);return this._fileStreams.add(n),n.once("close",(()=>{this._fileStreams.delete(n)})),n}async arrayBuffer(e){const t=new Uint8Array(this.length);let n=0;for await(const i of this[Symbol.asyncIterator](e))t.set(i,n),n+=i.length;return t.buffer}async blob(e){return new Blob([await this.arrayBuffer(e)],{type:this.type})}stream(e){let t;return new ReadableStream({start(){t=this[Symbol.asyncIterator](e)},async pull({close:e,enqueue:n}){const{value:i,done:r}=await t.next();r?e():n(i)},cancel(){t.return()}})}get streamURL(){if(!this._client._server)throw new Error("No server created");return`${this._client._server.pathname}/${this._torrent.infoHash}/${encodeURI(this.path)}`}streamTo(e){return e.src=this.streamURL,e}includes(e){return this._startPiece<=e&&this._endPiece>=e}_destroy(){this._destroyed=!0,this._torrent=null;for(const e of this._fileStreams)e.destroy();this._fileStreams.clear();for(const e of this._iterators)e.destroy();this._iterators.clear()}}var Xe=r(3287);class Qe{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 i=0;i<this._numPieces;++i){if(e&&!e(i))continue;const r=this._pieces[i];r===n?t.push(i):r<n&&(t=[i],n=r)}return t.length?t[Math.random()*t.length|0]:-1}destroy(){this._torrent.removeListener("wire",this._onWire),this._torrent.wires.forEach((e=>{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<this._numPieces;++t)this._pieces[t]-=e.peerPieces.get(t)},e.on("have",this._onWireHave),e.on("bitfield",this._onWireBitfield),e.once("close",e._onClose)}recalculate(){this._pieces.fill(0);for(const e of this._torrent.wires)for(let t=0;t<this._numPieces;++t)this._pieces[t]+=e.peerPieces.get(t)}_cleanupWireEvents(e){e.removeListener("have",this._onWireHave),e.removeListener("bitfield",this._onWireBitfield),e._onClose&&e.removeListener("close",e._onClose),e._onClose=null}}var et=r(6475),tt=r(814);const nt="2.0.24",it=k("webtorrent:webconn"),rt=nt;class st extends tt.Z{constructor(e,t){super(),this.url=e,this.connId=e,this._torrent=t,this._init(e)}_init(e){this.setKeepAlive(!0),this.use(De()),this.once("handshake",(async(t,n)=>{const i=await(0,d.vp)(e,"hex");if(this.destroyed)return;this.handshake(t,i);const r=this._torrent.pieces.length,s=new Q.Z(r);for(let e=0;e<=r;e++)s.set(e,!0);this.bitfield(s)})),this.once("interested",(()=>{it("interested"),this.unchoke()})),this.on("uninterested",(()=>{it("uninterested")})),this.on("choke",(()=>{it("choke")})),this.on("unchoke",(()=>{it("unchoke")})),this.on("bitfield",(()=>{it("bitfield")})),this.lt_donthave.on("donthave",(()=>{it("donthave")})),this.on("request",((e,t,n,i)=>{it("request pieceIndex=%d offset=%d length=%d",e,t,n),this.httpRequest(e,t,n,((t,n)=>{if(t){this.lt_donthave.donthave(e);const t=setTimeout((()=>{this.destroyed||this.have(e)}),1e4);t.unref&&t.unref()}i(t,n)}))}))}async httpRequest(e,t,n,i){i=se(i);const r=e*this._torrent.pieceLength+t,s=r+n-1,o=this._torrent.files;let a,h;if(o.length<=1)a=[{url:this.url,start:r,end:s}];else{const e=o.filter((e=>e.offset<=s&&e.offset+e.length>r));if(e.length<1)return i(new Error("Could not find file corresponding to web seed range request"));a=e.map((e=>{const t=e.offset+e.length-1;return{url:this.url+("/"===this.url[this.url.length-1]?"":"/")+e.path.replace(this._torrent.path,""),fileOffsetInRange:Math.max(e.offset-r,0),start:Math.max(r-e.offset,0),end:Math.min(t,s-e.offset)}}))}try{h=await Promise.all(a.map((async({start:i,end:r,url:s})=>{it("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",s,e,t,n,i,r);const o=await C(s,{cache:"no-store",method:"GET",headers:{"Cache-Control":"no-store","user-agent":`WebTorrent/${rt} (https://webtorrent.io)`,range:`bytes=${i}-${r}`},signal:AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`Unexpected HTTP status code ${o.status}`);const a=new Uint8Array(await o.arrayBuffer());return it("Got data of length %d",a.length),a})))}catch(e){return i(e)}i(null,(0,d.zo)(h))}destroy(){super.destroy(),this._torrent=null}}var ot=r(8768);const at=k("webtorrent:torrent"),ht=5e3,ct=3*qe.BLOCK_LENGTH,lt=ot.browser?ie().length:2,ut=[1e3,5e3,15e3],dt=`WebTorrent/${nt} (https://webtorrent.io)`;let ft;try{ft=t.join(V.statSync("/tmp")&&"/tmp","webtorrent")}catch(e){ft=t.join("function"==typeof Z.tmpdir?Z.tmpdir():"/","webtorrent")}const pt="undefined"!=typeof window&&"function"==typeof window.requestIdleCallback&&window.requestIdleCallback;class gt extends e{constructor(e,t,n){super(),this._debugId="unknown infohash",this.client=t,this.announce=n.announce,this.urlList=n.urlList,this.path=n.path||ft,this.addUID=n.addUID||!1,this.rootDir=n.rootDir||null,this.skipVerify=!!n.skipVerify,this._store=n.store||je,this._preloadedStore=n.preloadedStore||null,this._storeCacheSlots=void 0!==n.storeCacheSlots?n.storeCacheSlots:20,this._destroyStoreOnDestroy=n.destroyStoreOnDestroy||!1,this.store=null,this.storeOpts=n.storeOpts,this._getAnnounceOpts=n.getAnnounceOpts,"boolean"==typeof n.private&&(this.private=n.private),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._noPeersIntervalId=null,this._noPeersIntervalTime=n.noPeersIntervalTime?1e3*n.noPeersIntervalTime:3e4,this.ready=!1,this.destroyed=!1,this.paused=n.paused||!1,this.done=!1,this.metadata=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=W(),this._uploadSpeed=W(),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<n;++t)if(this.bitfield.get(t))e+=t===n-1?this.lastPieceLength:this.pieceLength;else{const n=this.pieces[t];e+=n.length-n.missing}return e}get downloadSpeed(){return this._downloadSpeed()}get uploadSpeed(){return this._uploadSpeed()}get progress(){return this.length?this.downloaded/this.length:0}get ratio(){return this.uploaded/(this.received||this.length)}get numPeers(){return this.wires.length}get torrentFileBlob(){return this.torrentFile?new Blob([this.torrentFile],{type:"application/x-bittorrent"}):null}get _numQueued(){return this._queue.length+(this._peersLength-this._numConns)}get _numConns(){let e=0;for(const t in this._peers)this._peers[t].connected&&(e+=1);return e}async _onTorrentId(e){if(this.destroyed)return;let t;try{t=await B(e)}catch(e){}t?(this.infoHash=t.infoHash,this._debugId=(0,d.oc)(t.infoHash).substring(0,7),u((()=>{this.destroyed||this._onParsedTorrent(t)}))):R(e,((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._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=(0,d.oc)(e.infoHash).substring(0,7),void 0!==this.private&&(e.private=this.private),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&globalThis.WEBTORRENT_ANNOUNCE&&!e.private&&(e.announce=e.announce.concat(globalThis.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),e.announce=Array.from(new Set(e.announce)),e.urlList=Array.from(new Set(e.urlList)),Object.assign(this,e),this.magnetURI=U(e),this.torrentFile=function(e){const t={info:e.info};return t["announce-list"]=(e.announce||[]).map((e=>(t.announce||(t.announce=e),[e=(0,d.gR)(e)]))),t["url-list"]=e.urlList||[],void 0!==e.private&&(t.private=Number(e.private)),e.created&&(t["creation date"]=e.created.getTime()/1e3|0),e.createdBy&&(t["created by"]=e.createdBy),e.comment&&(t.comment=e.comment),n.Z.encode(t)}(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:()=>{if(this.destroyed)return;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.peerAddresses&&this.peerAddresses.forEach((e=>this.addPeer(e,Xe.default.SOURCE_MANUAL))),this.discovery=new Ie({infoHash:this.infoHash,announce:this.announce,peerId:this.client.peerId,dht:!this.private&&this.client.dht,tracker:e,port:this.client.torrentPort,userAgent:dt,lsd:this.client.lsd}),this.discovery.on("error",(e=>{this._destroy(e)})),this.discovery.on("peer",((e,t)=>{this._debug("peer %s discovered via %s",e,t),"string"==typeof e&&this.done||this.addPeer(e,t)})),this.discovery.on("trackerAnnounce",(()=>{this.emit("trackerAnnounce")})),this.discovery.on("dhtAnnounce",(()=>{this.emit("dhtAnnounce")})),this.discovery.on("warning",(e=>{this.emit("warning",e)})),this._noPeersIntervalId=setInterval((()=>{if(this.destroyed)return;const e={[Xe.default.SOURCE_TRACKER]:{enabled:!!this.client.tracker,numPeers:0},[Xe.default.SOURCE_DHT]:{enabled:!!this.client.dht,numPeers:0},[Xe.default.SOURCE_LSD]:{enabled:!!this.client.lsd,numPeers:0},[Xe.default.SOURCE_UT_PEX]:{enabled:this.client.utPex&&"function"==typeof Ve,numPeers:0}};for(const t of Object.values(this._peers)){const n=e[t.source];void 0!==n&&n.numPeers++}for(const t of Object.keys(e)){const n=e[t];n.enabled&&0===n.numPeers&&this.emit("noPeers",t)}}),this._noPeersIntervalTime),this._noPeersIntervalId.unref&&this._noPeersIntervalId.unref()}_getMetadataFromServer(){const e=this,t=Array.isArray(this.xs)?this.xs:[this.xs];e._xsRequestsController=new AbortController;const n=e._xsRequestsController.signal,i=t.map((t=>i=>{!async function(t,i){if(0!==t.indexOf("http://")&&0!==t.indexOf("https://"))return e.emit("warning",new Error(`skipping non-http xs param: ${t}`)),i(null);const r={method:"GET",headers:{"user-agent":dt},signal:n};let s,o,a;try{s=await C(t,r)}catch(n){return e.emit("warning",new Error(`http error from xs param: ${t}`)),i(null)}if(e.destroyed)return i(null);if(e.metadata)return i(null);if(200!==s.status)return e.emit("warning",new Error(`non-200 status code ${s.status} from xs param: ${t}`)),i(null);try{o=new Uint8Array(await s.arrayBuffer())}catch(t){return e.emit("warning",t),i(null)}try{a=await B(o)}catch(e){}if(!a)return e.emit("warning",new Error(`got invalid torrent file from xs param: ${t}`)),i(null);if(a.infoHash!==e.infoHash)return e.emit("warning",new Error(`got torrent file with incorrect info hash from xs param: ${t}`)),i(null);e._onMetadata(a),i(null)}(t,i)}));l(i)}async _onMetadata(e){if(this.metadata||this.destroyed)return;let t;if(this._debug("got metadata"),this._xsRequestsController?.abort(),this._xsRequestsController=null,e&&e.infoHash)t=e;else try{t=await B(e)}catch(e){return this._destroy(e)}this._processParsedTorrent(t),this.metadata=this.torrentFile,this.client.enableWebSeeds&&this.urlList.forEach((e=>{this.addWebSeed(e)})),this._rarityMap=new Qe(this),this.files=this.files.map((e=>new Je(this,e)));let n=this._preloadedStore;if(n||(n=new this._store(this.pieceLength,{...this.storeOpts,torrent:this,path:this.path,files:this.files,length:this.length,name:this.name+" - "+this.infoHash.slice(0,8),addUID:this.addUID,rootDir:this.rootDir,max:this._storeCacheSlots})),this._storeCacheSlots>0&&!(n instanceof Be||n instanceof je)&&(n=new ee(n,{max:this._storeCacheSlots})),this.store=new He(n),this.so?this.files.forEach(((e,t)=>{this.so.includes(t)?this.files[t].select():this.files[t].deselect()})):0!==this.pieces.length&&this.select(0,this.pieces.length-1,!1),this._hashes=this.pieces,this.pieces=this.pieces.map(((e,t)=>{const n=t===this.pieces.length-1?this.lastPieceLength:this.pieceLength;return new qe(n)})),this._reservations=this.pieces.map((()=>[])),this.bitfield=new Q.Z(this.pieces.length),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===je?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 n=[];Fe(this.files.map(((e,i)=>r=>{const s=this.addUID?t.join(this.name+" - "+this.infoHash.slice(0,8)):t.join(this.path,e.path);V.stat(s,((e,t)=>{if(e&&"ENOENT"!==e.code)return r(e);n[i]=t&&t.mtime.getTime(),r(null)}))})),lt,(t=>{this._debug("done getting file modtimes"),e(t,n)}))}_verifyPieces(e){Fe(this.pieces.map(((e,t)=>e=>{if(this.destroyed)return e(new Error("torrent is destroyed"));const n={};t===this.pieces.length-1&&(n.length=this.lastPieceLength),this.store.get(t,n,(async(n,i)=>{if(this.destroyed)return e(new Error("torrent is destroyed"));if(n)return u((()=>e(null)));const r=await(0,d.vp)(i,"hex");if(this.destroyed)return e(new Error("torrent is destroyed"));r===this._hashes[t]?(this._debug("piece verified %s",t),this._markVerified(t)):(this._markUnverified(t),this._debug("piece invalid %s",t)),e(null)}))})),lt,e)}rescanFiles(e){if(this.destroyed)throw new Error("torrent is destroyed");e||(e=_t),this._verifyPieces((t=>{if(t)return this._destroy(t),e(t);this._checkDone(),e(null)}))}_markAllVerified(){for(let e=0;e<this.pieces.length;e++)this._markVerified(e)}_markVerified(e){this.pieces[e]=null,this._reservations[e]=null,this.bitfield.set(e,!0)}_markUnverified(e){const t=e===this.pieces.length-1?this.lastPieceLength:this.pieceLength;this.pieces[e]=new qe(t),this.bitfield.set(e,!1),this.select(e,e,1),this.files.forEach((t=>{t.done&&t.includes(e)&&(t.done=!1)}))}_hasAllPieces(){for(let e=0;e<this.pieces.length;e++)if(!this.bitfield.get(e))return!1;return!0}_hasNoPieces(){return!this._hasMorePieces(0)}_hasMorePieces(e){let t=0;for(let n=0;n<this.pieces.length;n++)if(this.bitfield.get(n)&&(t+=1,t>e))return!0;return!1}_onStore(){this.destroyed||(this._debug("on store"),this._startDiscovery(),this.ready=!0,this.emit("ready"),this._checkDone(),this._updateSelections(),this.wires.forEach((e=>{e.ut_metadata&&e.ut_metadata.setMetadata(this.metadata),this._onWireWithMetadata(e)})))}destroy(e,t){if("function"==typeof e)return this.destroy(null,e);this._destroy(null,e,t)}_destroy(e,t,n){if("function"==typeof t)return this._destroy(e,null,t);if(this.destroyed)return;this.destroyed=!0,this._debug("destroy"),this.client._remove(this),clearInterval(this._rechokeIntervalId),clearInterval(this._noPeersIntervalId),this._xsRequestsController?.abort(),this._rarityMap&&this._rarityMap.destroy();for(const e in this._peers)this.removePeer(e);this.files.forEach((e=>{e instanceof Je&&e._destroy()}));const i=this._servers.map((e=>t=>{e.destroy(t)}));if(this.discovery&&i.push((e=>{this.discovery.destroy(e)})),this.store){let e=this._destroyStoreOnDestroy;t&&void 0!==t.destroyStore&&(e=t.destroyStore),i.push((t=>{e?this.store.destroy(t):this.store.close(t)}))}l(i,n),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,t){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");let n;if(this.client.blocked){if("string"==typeof e){let t;try{t=X(e)}catch(t){return this._debug("ignoring peer: invalid %s",e),this.emit("invalidPeer",e),!1}n=t[0]}else"string"==typeof e.remoteAddress&&(n=e.remoteAddress);if(n&&this.client.blocked.contains(n))return this._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),this.emit("blockedPeer",e),!1}const i=this.client.utp&&this._isIPv4(n)?"utp":"tcp",r=!!this._addPeer(e,i,t);return r?this.emit("peer",e):this.emit("invalidPeer",e),r}_addPeer(e,t,n){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 i=e&&e.id||e;if(this._peers[i])return this._debug("ignoring peer: duplicate (%s)",i),"string"!=typeof e&&e.destroy(),null;if(this.paused)return this._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;let r;return this._debug("add peer %s",i),r="string"==typeof e?"utp"===t?Xe.default.createUTPOutgoingPeer(e,this,this.client.throttleGroups):Xe.default.createTCPOutgoingPeer(e,this,this.client.throttleGroups):Xe.default.createWebRTCPeer(e,this,this.client.throttleGroups),this._registerPeer(r),"string"==typeof e&&(this._queue.push(r),this._drain()),r}addWebSeed(e){if(this.destroyed)throw new Error("torrent is destroyed");let t,n;if("string"==typeof e){if(t=e,!/^https?:\/\/.+/.test(t))return this.emit("warning",new Error(`ignoring invalid web seed: ${t}`)),void this.emit("invalidPeer",t);if(this._peers[t])return this.emit("warning",new Error(`ignoring duplicate web seed: ${t}`)),void this.emit("invalidPeer",t);n=new st(t,this)}else{if(!e||"string"!=typeof e.connId)return void this.emit("warning",new Error("addWebSeed must be passed a string or connection object with id property"));if(n=e,t=n.connId,this._peers[t])return this.emit("warning",new Error(`ignoring duplicate web seed: ${t}`)),void this.emit("invalidPeer",t)}this._debug("add web seed %s",t);const i=Xe.default.createWebSeedPeer(n,t,this,this.client.throttleGroups);this._registerPeer(i),this.emit("peer",t)}_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),void this._registerPeer(e))}_registerPeer(e){e.on("download",(e=>{this.destroyed||(this.received+=e,this._downloadSpeed(e),this.client._downloadSpeed(e),this.emit("download",e),this.destroyed||this.client.emit("download",e))})),e.on("upload",(e=>{this.destroyed||(this.uploaded+=e,this._uploadSpeed(e),this.client._uploadSpeed(e),this.emit("upload",e),this.destroyed||this.client.emit("upload",e))})),this._peers[e.id]=e,this._peersLength+=1}removePeer(e){const t=e?.id||e;e&&!e.id&&(e=this._peers?.[t]),e&&(e.destroy(),this.destroyed||(this._debug("removePeer %s",t),delete this._peers[t],this._peersLength-=1,this._drain()))}select(e,t,n,i){if(this.destroyed)throw new Error("torrent is destroyed");if(e<0||t<e||this.pieces.length<=t)throw new Error(`invalid selection ${e} : ${t}`);n=Number(n)||0,this._debug("select %s-%s (priority %s)",e,t,n),this._selections.push({from:e,to:t,offset:0,priority:n,notify:i||_t}),this._selections.sort(((e,t)=>t.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 i=0;i<this._selections.length;++i){const r=this._selections[i];if(r.from===e&&r.to===t&&r.priority===n){this._selections.splice(i,1);break}}this._updateSelections()}critical(e,t){if(this.destroyed)throw new Error("torrent is destroyed");this._debug("critical %s-%s",e,t);for(let n=e;n<=t;++n)this._critical[n]=!0;this._updateSelections()}_onWire(e,t){if(this._debug("got wire %s (%s)",e._debugId,t||"Unknown"),this.wires.push(e),t){const n=X(t);e.remoteAddress=n[0],e.remotePort=n[1]}this.client.dht&&this.client.dht.listening&&e.on("port",(n=>{if(!this.destroyed&&!this.client.dht.destroyed){if(!e.remoteAddress)return this._debug("ignoring PORT from peer with no address");if(0===n||n>65536)return this._debug("ignoring invalid PORT from peer");this._debug("port: %s (from %s)",n,t),this.client.dht.addNode({host:e.remoteAddress,port:n})}})),e.on("timeout",(()=>{this._debug("wire timeout (%s)",t),e.destroy()})),"webSeed"!==e.type&&e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(Ge(this.metadata)),e.ut_metadata.on("warning",(e=>{this._debug("ut_metadata warning: %s",e.message)})),this.metadata||(e.ut_metadata.on("metadata",(e=>{this._debug("got metadata via ut_metadata"),this._onMetadata(e)})),e.ut_metadata.fetch()),this.client.utPex&&"function"==typeof Ve&&!this.private&&(e.use(Ve()),e.ut_pex.on("peer",(e=>{this.done||(this._debug("ut_pex: got peer: %s (from %s)",e,t),this.addPeer(e,Xe.default.SOURCE_UT_PEX))})),e.ut_pex.on("dropped",(e=>{const n=this._peers[e];n&&!n.connected&&(this._debug("ut_pex: dropped peer: %s (from %s)",e,t),this.removePeer(e))})),e.once("close",(()=>{e.ut_pex.reset()}))),e.use(De()),this.emit("wire",e,t),this.ready&&u((()=>{this._onWireWithMetadata(e)}))}_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,ht),t.unref&&t.unref()))};let i;const r=()=>{if(e.peerPieces.buffer.length===this.bitfield.buffer.length){for(i=0;i<this.pieces.length;++i)if(!e.peerPieces.get(i))return;e.isSeeder=!0,e.choke()}};e.on("bitfield",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.on("have",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.lt_donthave.on("donthave",(()=>{r(),this._update(),this._updateWireInterest(e)})),e.on("have-all",(()=>{e.isSeeder=!0,e.choke(),this._update(),this._updateWireInterest(e)})),e.on("have-none",(()=>{e.isSeeder=!1,this._update(),this._updateWireInterest(e)})),e.on("allowed-fast",(e=>{this._update()})),e.once("interested",(()=>{e.unchoke()})),e.once("close",(()=>{clearTimeout(t)})),e.on("choke",(()=>{clearTimeout(t),t=setTimeout(n,ht),t.unref&&t.unref()})),e.on("unchoke",(()=>{clearTimeout(t),this._update()})),e.on("request",((t,n,i,r)=>{if(i>131072)return e.destroy();this.pieces[t]||this.store.get(t,{offset:n,length:i},r)})),e.hasFast&&this._hasAllPieces()?e.haveAll():e.hasFast&&this._hasNoPieces()?e.haveNone():e.bitfield(this.bitfield),this._updateWireInterest(e),e.peerExtensions.dht&&this.client.dht&&this.client.dht.listening&&e.port(this.client.dht.address().port),"webSeed"!==e.type&&(t=setTimeout(n,ht),t.unref&&t.unref()),e.isSeeder=!1,r()}_updateSelections(){this.ready&&!this.destroyed&&(u((()=>{this._gcSelections()})),this._updateInterest(),this._update())}_gcSelections(){for(let e=0;e<this._selections.length;++e){const t=this._selections[e],n=t.offset;for(;this.bitfield.get(t.from+t.offset)&&t.from+t.offset<t.to;)t.offset+=1;n!==t.offset&&t.notify(),t.to===t.from+t.offset&&(this.bitfield.get(t.from+t.offset)&&(this._selections.splice(e,1),e-=1,t.notify(),this._updateInterest()))}this._selections.length||this.emit("idle")}_updateInterest(){const e=this._amInterested;this._amInterested=!!this._selections.length,this.wires.forEach((e=>this._updateWireInterest(e))),e!==this._amInterested&&(this._amInterested?this.emit("interested"):this.emit("uninterested"))}_updateWireInterest(e){let t=!1;for(let n=0;n<this.pieces.length;++n)if(this.pieces[n]&&e.peerPieces.get(n)){t=!0;break}t?e.interested():e.uninterested()}_update(){pt?pt((()=>this._updateWireWrapper()),{timeout:250}):this._updateWireWrapper()}_updateWireWrapper(){if(this.destroyed)return;const e=$e(this.wires);let t;for(;t=e();)this._updateWire(t)}_updateWire(e){if(e.destroyed)return!1;const t=this,n=mt(e,.5);if(e.requests.length>=n)return;const i=mt(e,1);if(e.peerChoking)e.hasFast&&e.peerAllowedFastSet.length>0&&!this._hasMorePieces(e.peerAllowedFastSet.length-1)&&function(){if(e.requests.length>=i)return!1;for(const n of e.peerAllowedFastSet){if(e.peerPieces.get(n)&&!t.bitfield.get(n))for(;t._request(e,n,!1)&&e.requests.length<i;);if(!(e.requests.length<i))return!0}}();else{if(!e.downloaded)return function(){if(e.requests.length)return;let n=t._selections.length;for(;n--;){const i=t._selections[n];let s;if("rarest"===t.strategy){const n=i.from+i.offset,o=i.to,a=o-n+1,h={};let c=0;const l=r(n,o,h);for(;c<a&&(s=t._rarityMap.getRarestPiece(l),!(s<0));){if(t._request(e,s,!1))return;h[s]=!0,c+=1}}else for(s=i.to;s>=i.from+i.offset;--s)if(e.peerPieces.get(s)&&t._request(e,s,!1))return}}();o(!1)||o(!0)}function r(t,n,i,r){return s=>s>=t&&s<=n&&!(s in i)&&e.peerPieces.get(s)&&(!r||r(s))}function s(e){let n=e;for(let i=e;i<t._selections.length&&t._selections[i].priority;i++)n=i;const i=t._selections[e];t._selections[e]=t._selections[n],t._selections[n]=i}function o(n){if(e.requests.length>=i)return!0;const o=function(){const n=e.downloadSpeed()||1;if(n>ct)return()=>!0;const i=Math.max(1,e.requests.length)*qe.BLOCK_LENGTH/n;let r=10,s=0;return e=>{if(!r||t.bitfield.get(e))return!0;let o=t.pieces[e].missing;for(;s<t.wires.length;s++){const a=t.wires[s],h=a.downloadSpeed();if(!(h<ct)&&!(h<=n)&&a.peerPieces.get(e)&&!((o-=h*i)>0))return r--,!1}return!0}}();for(let a=0;a<t._selections.length;a++){const h=t._selections[a];let c;if("rarest"===t.strategy){const l=h.from+h.offset,u=h.to,d=u-l+1,f={};let p=0;const g=r(l,u,f,o);for(;p<d&&(c=t._rarityMap.getRarestPiece(g),!(c<0));){for(;t._request(e,c,t._critical[c]||n)&&e.requests.length<i;);if(!(e.requests.length<i))return h.priority&&s(a),!0;f[c]=!0,p++}}else for(c=h.from+h.offset;c<=h.to;c++)if(e.peerPieces.get(c)&&o(c)){for(;t._request(e,c,t._critical[c]||n)&&e.requests.length<i;);if(!(e.requests.length<i))return h.priority&&s(a),!0}}return!1}}_rechoke(){if(!this.ready)return;const e=this.wires.map((e=>({wire:e,random:Math.random()}))).sort(((e,t)=>{const n=e.wire,i=t.wire;return n.downloadSpeed()!==i.downloadSpeed()?n.downloadSpeed()-i.downloadSpeed():n.uploadSpeed()!==i.uploadSpeed()?n.uploadSpeed()-i.uploadSpeed():n.amChoking!==i.amChoking?n.amChoking?-1:1:e.random-t.random})).map((e=>e.wire));this._rechokeOptimisticTime<=0?this._rechokeOptimisticWire=null:this._rechokeOptimisticTime-=1;let t=0;for(;e.length>0&&t<this._rechokeNumSlots-1;){const n=e.pop();n.isSeeder||n===this._rechokeOptimisticWire||(n.unchoke(),n.peerInterested&&t++)}if(null===this._rechokeOptimisticWire&&this._rechokeNumSlots>0){const t=e.filter((e=>e.peerInterested));if(t.length>0){const e=t[(n=t.length,Math.random()*n|0)];e.unchoke(),this._rechokeOptimisticWire=e,this._rechokeOptimisticTime=2}}var n;e.filter((e=>e!==this._rechokeOptimisticWire)).forEach((e=>e.choke()))}_hotswap(e,t){const n=e.downloadSpeed();if(n<qe.BLOCK_LENGTH)return!1;if(!this._reservations[t])return!1;const i=this._reservations[t];if(!i)return!1;let r,s,o=1/0;for(s=0;s<i.length;s++){const t=i[s];if(!t||t===e)continue;const a=t.downloadSpeed();a>=ct||(2*a>n||a>o||(r=t,o=a))}if(!r)return!1;for(s=0;s<i.length;s++)i[s]===r&&(i[s]=null);for(s=0;s<r.requests.length;s++){const e=r.requests[s];e.piece===t&&this.pieces[t].cancel(e.offset/qe.BLOCK_LENGTH|0)}return this.emit("hotswap",r,e,t),!0}_request(e,t,n){const i=this,r=e.requests.length,s="webSeed"===e.type;if(i.bitfield.get(t))return!1;const o=s?Math.min(function(e,t,n){return 1+Math.ceil(t*e.downloadSpeed()/n)}(e,1,i.pieceLength),i.maxWebConns):mt(e,1);if(r>=o)return!1;const a=i.pieces[t];let h=s?a.reserveRemaining():a.reserve();if(-1===h&&n&&i._hotswap(e,t)&&(h=s?a.reserveRemaining():a.reserve()),-1===h)return!1;let c=i._reservations[t];c||(c=i._reservations[t]=[]);let l=c.indexOf(null);-1===l&&(l=c.length),c[l]=e;const f=a.chunkOffset(h),p=s?a.chunkLengthRemaining(h):a.chunkLength(h);function g(){u((()=>{i._update()}))}return e.request(t,f,p,(async function n(r,o){if(i.destroyed)return;if(!i.ready)return i.once("ready",(()=>{n(r,o)}));if(c[l]===e&&(c[l]=null),a!==i.pieces[t])return g();if(r)return i._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,f,p,`${e.remoteAddress}:${e.remotePort}`,r.message),s?a.cancelRemaining(h):a.cancel(h),void g();if(i._debug("got piece %s (offset: %s length: %s) from %s",t,f,p,`${e.remoteAddress}:${e.remotePort}`),!a.set(h,o,e))return g();const u=a.flush(),m=await(0,d.vp)(u,"hex");i.destroyed||(m===i._hashes[t]?(i._debug("piece verified %s",t),i.store.put(t,u,(e=>{e?i._destroy(e):(i.pieces[t]=null,i._markVerified(t),i.wires.forEach((e=>{e.have(t)})),i._checkDone()&&!i.destroyed&&i.discovery.complete(),g())}))):(i.pieces[t]=new qe(a.length),i.emit("warning",new Error(`Piece ${t} failed verification`)),g()))})),!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(const t of this._selections){for(let n=t.from;n<=t.to;n++)if(!this.bitfield.get(n)){e=!1;break}if(!e)break}return!this.done&&e?(this.done=!0,this._debug(`torrent done: ${this.infoHash}`),this.emit("done")):this.done=!1,this._gcSelections(),e}async load(e,t){if(this.destroyed)throw new Error("torrent is destroyed");if(!this.ready)return this.once("ready",(()=>{this.load(e,t)}));Array.isArray(e)||(e=[e]),t||(t=_t);try{await ne(this.store,c(e),{chunkLength:this.pieceLength}),this._markAllVerified(),this._checkDone(),t(null)}catch(e){return t(e),e}}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?this.client._debugId:"No Client"}] [${this._debugId}] ${e[0]}`,at(...e)}_drain(){if(this._debug("_drain numConns %s maxConns %s",this._numConns,this.client.maxConns),"function"!=typeof K.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("%s connect attempt to %s",e.type,e.addr);const t=X(e.addr),n={host:t[0],port:t[1]};this.client.utp&&e.type===Xe.default.TYPE_UTP_OUTGOING?e.conn=et.connect(n.port,n.host):e.conn=K.connect(n);const i=e.conn;i.once("connect",(()=>{this.destroyed||e.onConnect()})),i.once("error",(t=>{e.destroy(t)})),e.startConnectTimeout(),i.on("close",(()=>{if(this.destroyed)return;if(e.retries>=ut.length){if(this.client.utp){const t=this._addPeer(e.addr,"tcp",e.source);t&&(t.retries=0)}else this._debug("conn %s closed: will not re-add (max %s attempts)",e.addr,ut.length);return}const t=ut[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((()=>{if(this.destroyed)return;const t=X(e.addr)[0],n=this.client.utp&&this._isIPv4(t)?"utp":"tcp",i=this._addPeer(e.addr,n,e.source);i&&(i.retries=e.retries+1)}),t);n.unref&&n.unref()}))}_validAddr(e){let t;try{t=X(e)}catch(e){return!1}const n=t[0],i=t[1];return i>0&&i<65535&&!("127.0.0.1"===n&&i===this.client.torrentPort)}_isIPv4(e){return/^((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/.test(e)}}function mt(e,t){let n=2+Math.ceil(t*e.downloadSpeed()/qe.BLOCK_LENGTH);if(e.peerExtendedHandshake){const t=e.peerExtendedHandshake.reqq;"number"==typeof t&&t>0&&(n=Math.min(n,t))}return n}function _t(){}var yt=r(3423),wt=r(5573),bt=r(4286),vt=r(4622);class kt{constructor(e,t={}){this.client=e,t.origin||(t.origin="*"),this.opts=t,this.pendingReady=new Set}static serveIndexPage(e,t,n){const i=t.map((e=>`<li>\n        <a href="${wt(n)}/${e.infoHash}">\n          ${wt(e.name)}\n        </a>\n        (${wt(e.length)} bytes)\n      </li>`)).join("<br>");return e.status=200,e.headers["Content-Type"]="text/html",e.body=St("WebTorrent",`<h1>WebTorrent</h1>\n         <ol>${i}</ol>`),e}isOriginAllowed(e){return!1!==this.opts.origin&&("*"===this.opts.origin||e.headers.origin===this.opts.origin)}static serveMethodNotAllowed(e){return e.status=405,e.headers["Content-Type"]="text/html",e.body=St("405 - Method Not Allowed","<h1>405 - Method Not Allowed</h1>"),e}static serve404Page(e){return e.status=404,e.headers["Content-Type"]="text/html",e.body=St("404 - Not Found","<h1>404 - Not Found</h1>"),e}static serveTorrentPage(e,t,n){const i=e.files.map((t=>`<li>\n      <a href="${wt(n)}/${e.infoHash}/${wt(t.path)}">\n        ${wt(t.path)}\n      </a>\n      (${wt(t.length)} bytes)\n    </li>`)).join("<br>");return t.status=200,t.headers["Content-Type"]="text/html",t.body=St(`${wt(e.name)} - WebTorrent`,`<h1>${wt(e.name)}</h1>\n        <ol>${i}</ol>`),t}static serveOptionsRequest(e,t){return t.status=204,t.headers["Access-Control-Max-Age"]="600",t.headers["Access-Control-Allow-Methods"]="GET,HEAD",e.headers["access-control-request-headers"]&&(t.headers["Access-Control-Allow-Headers"]=e.headers["access-control-request-headers"]),t}static serveFile(e,t,n){n.status=200,n.headers.Expires="0",n.headers["Cache-Control"]="no-cache, no-store, must-revalidate, max-age=0",n.headers["Accept-Ranges"]="bytes",n.headers["Content-Type"]=e.type,n.headers["transferMode.dlna.org"]="Streaming",n.headers["contentFeatures.dlna.org"]="DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000","document"===t.destination?(n.headers["Content-Type"]="application/octet-stream",n.headers["Content-Disposition"]=`attachment; filename*=UTF-8''${Ct(e.name)}`,n.body="DOWNLOAD"):n.headers["Content-Disposition"]=`inline; filename*=UTF-8''${Ct(e.name)}`;let i=vt(e.length,t.headers.range||"");if(Array.isArray(i)?(n.status=206,i=i[0],n.headers["Content-Range"]=`bytes ${i.start}-${i.end}/${e.length}`,n.headers["Content-Length"]=i.end-i.start+1):(n.statusCode=200,i=null,n.headers["Content-Length"]=e.length),"GET"===t.method){const r=e[Symbol.asyncIterator](i);let s=null;e.emit("iterator",{iterator:r,req:t,file:e},(e=>{s=e}));const o=M.Readable.from(s||r);let a=null;e.emit("stream",{stream:o,req:t,file:e},(e=>{a=bt(o,e)})),n.body=a||o}else n.body=!1;return n}async onRequest(e,t){let n=new URL(e.url,"http://example.com").pathname;n=n.slice(n.indexOf(this.pathname)+this.pathname.length+1);const i={headers:{"X-Content-Type-Options":"nosniff","Content-Security-Policy":"base-uri 'none'; frame-ancestors 'none'; form-action 'none';"}};if(this.isOriginAllowed(e)&&(i.headers["Access-Control-Allow-Origin"]="*"===this.opts.origin?"*":e.headers.origin),"favicon.ico"===n)return t(kt.serve404Page(i));if("OPTIONS"===e.method)return this.isOriginAllowed(e)?t(kt.serveOptionsRequest(e,i)):t(kt.serveMethodNotAllowed(i));const r=async()=>{this.pendingReady.delete(r);const e=await s();t(e)},s=async()=>{if(""===n)return kt.serveIndexPage(i,this.client.torrents,this.pathname);let[t,...r]=n.split("/");r=decodeURI(r.join("/"));const s=await this.client.get(t);if(!t||!s)return kt.serve404Page(i);if(!r)return kt.serveTorrentPage(s,i,this.pathname);const o=s.files.find((e=>e.path.replace(/\\/g,"/")===r));return o?kt.serveFile(o,e,i):kt.serve404Page(i)};if("GET"===e.method||"HEAD"===e.method){if(this.client.ready){const e=await s();return t(e)}return this.pendingReady.add(r),void this.client.once("ready",r)}return kt.serveMethodNotAllowed(i)}close(e=(()=>{})){this.closed=!0,this.pendingReady.forEach((e=>{this.client.removeListener("ready",e)})),this.pendingReady.clear(),u(e)}destroy(e=(()=>{})){this.closed?u(e):this.close(e),this.client=null}}class xt extends kt{constructor(e,t){super(e,t),this.server=yt.createServer(),this._listen=this.server.listen,this.server.listen=this.listen.bind(this),this._close=this.server.close,this.server.close=this.close.bind(this),this.sockets=new Set,this.closed=!1,this.pathname=t?.pathname||"/webtorrent"}wrapRequest(e,t){return this.opts.hostname&&e.headers.host!==`${this.opts.hostname}:${this.server.address().port}`?e.destroy():new URL(e.url,"http://example.com").pathname.startsWith(this.pathname)?void this.onRequest(e,(({status:e,headers:n,body:i})=>{t.writeHead(e,n),i instanceof M.Readable?bt(i,t):t.end(i)})):e.destroy()}onConnection(e){e.setTimeout(36e6),this.sockets.add(e),e.once("close",(()=>{this.sockets.delete(e)}))}address(){return this.server.address()}listen(...e){return this.closed=!1,this.server.on("connection",this.onConnection.bind(this)),this.server.on("request",this.wrapRequest.bind(this)),this._listen.apply(this.server,e)}close(e=(()=>{})){this.server.removeAllListeners("connection"),this.server.removeAllListeners("request"),super.close(),this._close.call(this.server,e)}destroy(e){this.sockets.forEach((e=>{e.destroy()})),super.destroy(e)}}class Et extends kt{constructor(e,t){super(e,t),this.registration=t.controller,this.workerKeepAliveInterval=null,this.workerPortCount=0;const n=new URL(t.controller.scope);this.pathname=n.pathname+"webtorrent",this._address={port:n.port,family:"IPv4",address:n.hostname},this.boundHandler=this.wrapRequest.bind(this),navigator.serviceWorker.addEventListener("message",this.boundHandler),fetch(`${this.pathname}/cancel/`).then((e=>{e.body.cancel()}))}wrapRequest(e){const t=e.data;if("webtorrent"===!t?.type||!t.url)return null;const[n]=e.ports;this.onRequest(t,(({status:e,headers:t,body:i})=>{const r=i instanceof M.Readable&&i[Symbol.asyncIterator](),s=()=>{n.onmessage=null,i?.destroy&&i.destroy(),this.workerPortCount--,this.workerPortCount||(clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null)};n.onmessage=async e=>{if(e.data){let e;try{e=(await r.next()).value}catch(e){}n.postMessage(e),e||s(),this.workerKeepAliveInterval||(this.workerKeepAliveInterval=setInterval((()=>fetch(`${this.pathname}/keepalive/`)),2e4))}else s()},this.workerPortCount++,n.postMessage({status:e,headers:t,body:r?"STREAM":i})}))}listen(e,t){t()}address(){return this._address}close(e){navigator.serviceWorker.removeEventListener("message",this.boundHandler),super.close(e)}destroy(e){super.destroy(e)}}function St(e,t){return`\n    <!DOCTYPE html>\n    <html lang="en">\n      <head>\n        <meta charset="utf-8">\n        <title>${e}</title>\n      </head>\n      <body>\n        ${t}\n      </body>\n    </html>\n  `}function Ct(e){return encodeURIComponent(e).replace(/['()]/g,escape).replace(/\*/g,"%2A").replace(/%(?:7C|60|5E)/g,unescape)}const At=nt,Tt=k("webtorrent"),Pt=At.replace(/\d*./g,(e=>("0"+e%100).slice(-2))).slice(0,4),It=`-WW${Pt}-`;class Rt extends e{constructor(e={}){super(),"string"==typeof e.peerId?this.peerId=e.peerId:ArrayBuffer.isView(e.peerId)?this.peerId=(0,d.oc)(e.peerId):this.peerId=(0,d.oc)((0,d.gR)(It+(0,d.te)((0,d.O6)(9)))),this.peerIdBuffer=(0,d._0)(this.peerId),"string"==typeof e.nodeId?this.nodeId=e.nodeId:ArrayBuffer.isView(e.nodeId)?this.nodeId=(0,d.oc)(e.nodeId):this.nodeId=(0,d.oc)((0,d.O6)(20)),this.nodeIdBuffer=(0,d._0)(this.nodeId),this._debugId=(0,d.oc)(this.peerId).substring(0,7),this.destroyed=!1,this.listening=!1,this.torrentPort=e.torrentPort||0,this.dhtPort=e.dhtPort||0,this.tracker=void 0!==e.tracker?e.tracker:{},this.lsd=!1!==e.lsd,this.utPex=!1!==e.utPex,this.torrents=[],this.maxConns=Number(e.maxConns)||55,this.utp=Rt.UTP_SUPPORT&&!1!==e.utp,this._downloadLimit=Math.max("number"==typeof e.downloadLimit?e.downloadLimit:-1,-1),this._uploadLimit=Math.max("number"==typeof e.uploadLimit?e.uploadLimit:-1,-1),!0===e.secure&&Promise.resolve().then(r.bind(r,3287)).then((({enableSecure:e})=>e())),this._debug("new webtorrent (peerId %s, nodeId %s, port %s)",this.peerId,this.nodeId,this.torrentPort),this.throttleGroups={down:new z.ThrottleGroup({rate:Math.max(this._downloadLimit,0),enabled:this._downloadLimit>=0}),up:new z.ThrottleGroup({rate:Math.max(this._uploadLimit,0),enabled:this._uploadLimit>=0})},this.tracker&&("object"!=typeof this.tracker&&(this.tracker={}),globalThis.WRTC&&!this.tracker.wrtc&&(this.tracker.wrtc=globalThis.WRTC)),"function"==typeof G?this._connPool=new G(this):u((()=>{this._onListening()})),this._downloadSpeed=W(),this._uploadSpeed=W(),!1!==e.dht&&"function"==typeof x.Client?(this.dht=new x.Client(Object.assign({},{nodeId:this.nodeId},e.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!==e.webSeeds;const t=()=>{this.destroyed||(this.ready=!0,this.emit("ready"))};"function"==typeof E&&null!=e.blocklist?E(e.blocklist,{headers:{"user-agent":`WebTorrent/${At} (https://webtorrent.io)`}},((e,n)=>{if(e)return console.error(`Failed to load blocklist: ${e.message}`);this.blocked=n,t()})):u(t)}createServer(e,t){if(this.destroyed)throw new Error("torrent is destroyed");if(this._server)throw new Error("server already created");if("undefined"!=typeof window&&"node"!==t||"browser"===t){if(!(e?.controller instanceof ServiceWorkerRegistration))throw new Error("Invalid worker registration");if("activated"!==e.controller.active.state)throw new Error("Worker isn't activated");return this._server=new Et(this,e),this._server}return this._server=new xt(this,e),this._server}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)}async get(e){if(e instanceof gt){if(this.torrents.includes(e))return e}else{const t=this.torrents;let n;try{n=await B(e)}catch(e){}if(!n)return null;if(!n.infoHash)throw new Error("Invalid torrent identifier");for(const e of t)if(e.infoHash===n.infoHash)return e}return null}add(e,t={},n=(()=>{})){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof t&&([t,n]=[{},t]);const i=()=>{if(!this.destroyed)for(const e of this.torrents)if(e.infoHash===s.infoHash&&e!==s)return s._destroy(new Error(`Cannot add duplicate torrent ${s.infoHash}`)),void n(e)},r=()=>{this.destroyed||(n(s),this.emit("torrent",s))};this._debug("add"),t=t?Object.assign({},t):{};const s=new gt(e,this,t);return this.torrents.push(s),s.once("_infoHash",i),s.once("ready",r),s.once("close",(function e(){s.removeListener("_infoHash",i),s.removeListener("ready",r),s.removeListener("close",e)})),s}seed(e,n,i){if(this.destroyed)throw new Error("client is destroyed");"function"==typeof n&&([n,i]=[{},n]),this._debug("seed"),(n=n?Object.assign({},n):{}).skipVerify=!0;const r="string"==typeof e;r&&(n.path=t.dirname(e)),n.createdBy||(n.createdBy=`WebTorrent/${Pt}`);const s=e=>{this._debug("on seed"),"function"==typeof i&&i(e),e.emit("seed"),this.emit("seed",e)},o=this.add(null,n,(e=>{const t=[t=>{if(r||n.preloadedStore)return t();e.load(a,t)}];this.dht&&t.push((t=>{e.once("dhtAnnounce",t)})),l(t,(t=>{if(!this.destroyed)return t?e._destroy(t):void s(e)}))}));let a;var h;return h=e,"undefined"!=typeof FileList&&h instanceof FileList?e=Array.from(e):Array.isArray(e)||(e=[e]),l(e.map((e=>async t=>{if(!n.preloadedStore&&function(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}(e)){const n=[];try{for await(const t of e)n.push(t)}catch(e){return t(e)}const i=(0,d.zo)(n);i.name=e.name,t(null,i)}else t(null,e)})),((e,t)=>{if(!this.destroyed)return e?o._destroy(e):void function(e,t,n){"function"==typeof t&&([t,n]=[n,t]),m(e,t=t?Object.assign({},t):{},n)}(t,n,((e,r)=>{if(!this.destroyed){if(e)return o._destroy(e);a=r.map((e=>e.getStream)),v(t,n,(async(e,t)=>{if(this.destroyed)return;if(e)return o._destroy(e);const n=await this.get(t);n?(console.warn("A torrent with the same id is already being seeded"),o._destroy(),"function"==typeof i&&i(n)):o._onTorrentId(t)}))}}))})),o}async remove(e,t,n){if("function"==typeof t)return this.remove(e,null,t);this._debug("remove");const i=await this.get(e);if(!i)throw new Error(`No torrent with id ${e}`);this._remove(i,t,n)}_remove(e,t,n){if(e){if("function"==typeof t)return this._remove(e,null,t);this.torrents.splice(this.torrents.indexOf(e),1),e.destroy(t,n),this.dht&&this.dht._tables.remove(e.infoHash)}}address(){return this.listening?this._connPool?this._connPool.tcpServer.address():{address:"0.0.0.0",family:"IPv4",port:0}:null}throttleDownload(e){return e=Number(e),!(isNaN(e)||!isFinite(e)||e<-1)&&(this._downloadLimit=e,this._downloadLimit<0?this.throttleGroups.down.setEnabled(!1):(this.throttleGroups.down.setEnabled(!0),void this.throttleGroups.down.setRate(this._downloadLimit)))}throttleUpload(e){return e=Number(e),!(isNaN(e)||!isFinite(e)||e<-1)&&(this._uploadLimit=e,this._uploadLimit<0?this.throttleGroups.up.setEnabled(!1):(this.throttleGroups.up.setEnabled(!0),void this.throttleGroups.up.setRate(this._uploadLimit)))}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._connPool&&n.push((e=>{this._connPool.destroy(e)})),this.dht&&n.push((e=>{this.dht.destroy(e)})),this._server&&n.push((e=>{this._server.destroy(e)})),l(n,t),e&&this.emit("error",e),this.torrents=[],this._connPool=null,this.dht=null,this.throttleGroups.down.destroy(),this.throttleGroups.up.destroy()}_onListening(){if(this._debug("listening"),this.listening=!0,this._connPool){const e=this._connPool.tcpServer.address();e&&(this.torrentPort=e.port)}this.emit("listening")}_debug(){const e=[].slice.call(arguments);e[0]=`[${this._debugId}] ${e[0]}`,Tt(...e)}async _getByHash(e){for(const t of this.torrents)if(t.infoHashHash||(t.infoHashHash=await(0,d.vp)((0,d._0)("72657132"+t.infoHash),"hex")),e===t.infoHashHash)return t;return null}}Rt.WEBRTC_SUPPORT=$.WEBRTC_SUPPORT,Rt.UTP_SUPPORT=G.UTP_SUPPORT,Rt.VERSION=At})();var o=s.Z;export{o as default};
//# sourceMappingURL=webtorrent.min.js.map